merge: 同步 main 同名角色绑定修复
This commit is contained in:
@@ -438,9 +438,13 @@
|
||||
"revision": "20261121_0109",
|
||||
"sha256": "0aa85febbc0f2c99f5768bba2364f8797a748c4de740780e33a2017311f591b0"
|
||||
},
|
||||
"20261121_0110_account_platform_foundation.py": {
|
||||
"20261121_0110_douyu_role_api_logs.py": {
|
||||
"revision": "20261121_0110",
|
||||
"sha256": "94c0158a061a7670d1c15cfd57172d98eddd271a4d82be0cb7d0ea65013f8712"
|
||||
"sha256": "4f445f867e3fc41c7713f9296fe7be700823e936ed838039347e5b26abcd48a7"
|
||||
},
|
||||
"20261121_0111_account_platform_foundation.py": {
|
||||
"revision": "20261121_0111",
|
||||
"sha256": "0cf919b766769c84d357271acbf32bd968b2b6756b04cc059b26fd9fb5d41c10"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""add durable douyu role API response logs
|
||||
|
||||
Role binding has multiple aliases and state flags. Persist key raw responses so
|
||||
production failures can be replayed without guessing from the final task result.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261121_0110"
|
||||
down_revision: str | None = "20261121_0109"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"douyu_role_api_logs",
|
||||
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||
sa.Column("account_id", sa.Integer(), nullable=False),
|
||||
sa.Column("task_id", sa.Integer(), nullable=True),
|
||||
sa.Column(
|
||||
"scope",
|
||||
sa.String(length=16),
|
||||
nullable=False,
|
||||
server_default="elite",
|
||||
),
|
||||
sa.Column(
|
||||
"stage",
|
||||
sa.String(length=48),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
sa.Column(
|
||||
"source",
|
||||
sa.String(length=64),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
sa.Column(
|
||||
"act_alias",
|
||||
sa.String(length=64),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
sa.Column(
|
||||
"api_version",
|
||||
sa.String(length=16),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
sa.Column(
|
||||
"role_name",
|
||||
sa.String(length=128),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
sa.Column(
|
||||
"area_name",
|
||||
sa.String(length=128),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
sa.Column(
|
||||
"plat_name",
|
||||
sa.String(length=128),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
sa.Column(
|
||||
"is_bound_act",
|
||||
sa.Boolean(),
|
||||
nullable=False,
|
||||
server_default="0",
|
||||
),
|
||||
sa.Column(
|
||||
"is_bound_role",
|
||||
sa.Boolean(),
|
||||
nullable=False,
|
||||
server_default="0",
|
||||
),
|
||||
sa.Column(
|
||||
"need_bind_act",
|
||||
sa.Boolean(),
|
||||
nullable=False,
|
||||
server_default="0",
|
||||
),
|
||||
sa.Column(
|
||||
"need_bind_role",
|
||||
sa.Boolean(),
|
||||
nullable=False,
|
||||
server_default="0",
|
||||
),
|
||||
sa.Column("change_role_wait_time", sa.BigInteger(), nullable=True),
|
||||
sa.Column("can_change_time", sa.BigInteger(), nullable=True),
|
||||
sa.Column("request_json", sa.JSON(), nullable=True),
|
||||
sa.Column("response_json", sa.JSON(), nullable=True),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(),
|
||||
nullable=False,
|
||||
server_default=sa.text("CURRENT_TIMESTAMP"),
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["account_id"],
|
||||
["accounts.id"],
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["task_id"],
|
||||
["douyu_tasks.id"],
|
||||
ondelete="SET NULL",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_douyu_role_api_logs_account_created",
|
||||
"douyu_role_api_logs",
|
||||
["account_id", "created_at", "id"],
|
||||
unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
"ix_douyu_role_api_logs_task_created",
|
||||
"douyu_role_api_logs",
|
||||
["task_id", "created_at", "id"],
|
||||
unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
"ix_douyu_role_api_logs_alias_created",
|
||||
"douyu_role_api_logs",
|
||||
["act_alias", "created_at", "id"],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("douyu_role_api_logs")
|
||||
+2
-2
@@ -5,8 +5,8 @@ from __future__ import annotations
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261121_0110"
|
||||
down_revision: str | None = "20261121_0109"
|
||||
revision: str = "20261121_0111"
|
||||
down_revision: str | None = "20261121_0110"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
@@ -602,6 +602,94 @@ class DouyuConfig(Base):
|
||||
)
|
||||
|
||||
|
||||
class DouyuRoleApiLog(Base):
|
||||
"""斗鱼角色接口原始响应与归一状态,仅追加。
|
||||
|
||||
角色绑定/换绑涉及多个 alias(当前活动、cjm/legacy、确认接口),只看最终
|
||||
``douyu_tasks.result`` 无法还原每一步接口到底返回了什么。这里保存关键节点
|
||||
的原始响应,并用角色字段做快速检索;轮询阶段只在状态变化时写入,避免相同
|
||||
响应每 5 秒重复落库。
|
||||
"""
|
||||
|
||||
__tablename__ = "douyu_role_api_logs"
|
||||
|
||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
|
||||
account_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("accounts.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
)
|
||||
task_id: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("douyu_tasks.id", ondelete="SET NULL"),
|
||||
nullable=True,
|
||||
)
|
||||
scope: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default="elite", server_default="elite"
|
||||
)
|
||||
stage: Mapped[str] = mapped_column(
|
||||
String(48), nullable=False, default="", server_default=""
|
||||
)
|
||||
source: Mapped[str] = mapped_column(
|
||||
String(64), nullable=False, default="", server_default=""
|
||||
)
|
||||
act_alias: Mapped[str] = mapped_column(
|
||||
String(64), nullable=False, default="", server_default=""
|
||||
)
|
||||
api_version: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default="", server_default=""
|
||||
)
|
||||
role_name: Mapped[str] = mapped_column(
|
||||
String(128), nullable=False, default="", server_default=""
|
||||
)
|
||||
area_name: Mapped[str] = mapped_column(
|
||||
String(128), nullable=False, default="", server_default=""
|
||||
)
|
||||
plat_name: Mapped[str] = mapped_column(
|
||||
String(128), nullable=False, default="", server_default=""
|
||||
)
|
||||
is_bound_act: Mapped[bool] = mapped_column(
|
||||
Boolean, nullable=False, default=False, server_default="0"
|
||||
)
|
||||
is_bound_role: Mapped[bool] = mapped_column(
|
||||
Boolean, nullable=False, default=False, server_default="0"
|
||||
)
|
||||
need_bind_act: Mapped[bool] = mapped_column(
|
||||
Boolean, nullable=False, default=False, server_default="0"
|
||||
)
|
||||
need_bind_role: Mapped[bool] = mapped_column(
|
||||
Boolean, nullable=False, default=False, server_default="0"
|
||||
)
|
||||
change_role_wait_time: Mapped[int | None] = mapped_column(
|
||||
BigInteger, nullable=True
|
||||
)
|
||||
can_change_time: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
|
||||
request_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
response_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
UTCDateTime, default=_utcnow, nullable=False
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"ix_douyu_role_api_logs_account_created",
|
||||
"account_id",
|
||||
"created_at",
|
||||
"id",
|
||||
),
|
||||
Index(
|
||||
"ix_douyu_role_api_logs_task_created",
|
||||
"task_id",
|
||||
"created_at",
|
||||
"id",
|
||||
),
|
||||
Index(
|
||||
"ix_douyu_role_api_logs_alias_created",
|
||||
"act_alias",
|
||||
"created_at",
|
||||
"id",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class DouyuGoodsSnapshot(Base):
|
||||
"""斗鱼兑换商品快照"""
|
||||
|
||||
|
||||
@@ -295,10 +295,9 @@ def binding_pending_decision(
|
||||
) -> dict[str, Any]:
|
||||
"""解释一个绑定候选是否可进入确认阶段。
|
||||
|
||||
角色名不是唯一事实:用户可能换绑到同名角色。判断还要对比扫码前后的
|
||||
活动绑定状态,尤其是活动 alias 从 ``bindAct=1`` 转为
|
||||
``bindAct=0 + needBindAct=1`` 的待确认转换。活动 alias 上已经存在的
|
||||
同名 pending 也不是“旧角色残留”,它仍然可以调用确认接口。
|
||||
角色名不是唯一事实,也不能要求每次都必须换新角色。用户重新绑定同名角色
|
||||
时,判断还要对比扫码前后的活动绑定状态。活动 alias 只要仍要求
|
||||
``needBindAct=1``,即使当前 ``bindAct=1``,同名角色也可以进入确认流程。
|
||||
"""
|
||||
result: dict[str, Any] = {
|
||||
"alias": str((info or {}).get("act_alias") or ""),
|
||||
@@ -354,10 +353,10 @@ def binding_pending_decision(
|
||||
if role_name.casefold() != baseline.casefold():
|
||||
result.update({"confirmable": True, "reason": "role_changed"})
|
||||
return result
|
||||
if snapshot["is_bound_act"]:
|
||||
result["reason"] = "already_bound"
|
||||
return result
|
||||
if not isinstance(baseline_info, dict):
|
||||
if snapshot["is_bound_act"]:
|
||||
result["reason"] = "already_bound"
|
||||
return result
|
||||
result["reason"] = "same_role_without_baseline_info"
|
||||
return result
|
||||
|
||||
@@ -387,6 +386,9 @@ def binding_pending_decision(
|
||||
}
|
||||
)
|
||||
return result
|
||||
if snapshot["is_bound_act"]:
|
||||
result["reason"] = "already_bound"
|
||||
return result
|
||||
result["reason"] = "same_role_stale"
|
||||
return result
|
||||
|
||||
|
||||
@@ -64,6 +64,7 @@ from .douyu_elite_status import (
|
||||
normalize_elite_expire_time,
|
||||
)
|
||||
from .douyu_goods_service import serialize_goods
|
||||
from .douyu_role_audit import record_role_api_candidates
|
||||
|
||||
SESSION_VALID = "valid"
|
||||
SESSION_INVALID = "invalid"
|
||||
@@ -297,23 +298,34 @@ def resolve_elite_role(
|
||||
)
|
||||
pending_info = None
|
||||
pending_decision: dict[str, Any] | None = None
|
||||
for alias in ordered_aliases:
|
||||
for info in candidates_info:
|
||||
if str(info.get("act_alias") or "") != alias:
|
||||
continue
|
||||
decision = binding_pending_decision(
|
||||
info,
|
||||
baseline_role_name=str((bound_info or {}).get("role_name") or ""),
|
||||
baseline_is_bound_act=is_bound_act(bound_info),
|
||||
baseline_info=bound_info,
|
||||
actionable_aliases=action_aliases,
|
||||
)
|
||||
if decision["confirmable"]:
|
||||
pending_info = info
|
||||
pending_decision = decision
|
||||
break
|
||||
if pending_info is not None:
|
||||
break
|
||||
baseline_role = str((bound_info or {}).get("role_name") or "").strip()
|
||||
|
||||
def find_pending(*, changed_role_only: bool) -> tuple[dict | None, dict | None]:
|
||||
for alias in ordered_aliases:
|
||||
for info in candidates_info:
|
||||
if str(info.get("act_alias") or "") != alias:
|
||||
continue
|
||||
role_name = str(info.get("role_name") or "").strip()
|
||||
if (
|
||||
changed_role_only
|
||||
and baseline_role
|
||||
and role_name.casefold() == baseline_role.casefold()
|
||||
):
|
||||
continue
|
||||
decision = binding_pending_decision(
|
||||
info,
|
||||
baseline_role_name=baseline_role,
|
||||
baseline_is_bound_act=is_bound_act(bound_info),
|
||||
baseline_info=bound_info,
|
||||
actionable_aliases=action_aliases,
|
||||
)
|
||||
if decision["confirmable"]:
|
||||
return info, decision
|
||||
return None, None
|
||||
|
||||
pending_info, pending_decision = find_pending(changed_role_only=True)
|
||||
if pending_info is None:
|
||||
pending_info, pending_decision = find_pending(changed_role_only=False)
|
||||
if bound_info is not None:
|
||||
return _role_result(
|
||||
status=ROLE_BOUND,
|
||||
@@ -1030,6 +1042,13 @@ def persist_probe_result(
|
||||
pass
|
||||
|
||||
roles = probe.get("roles") or {}
|
||||
probe_id = str(probe.get("probe_id") or "")
|
||||
task_id: int | None = None
|
||||
if probe_id.startswith("task:"):
|
||||
try:
|
||||
task_id = int(probe_id.removeprefix("task:"))
|
||||
except ValueError:
|
||||
task_id = None
|
||||
for scope in (SCOPE_ELITE, SCOPE_ESPORTS, SCOPE_PEACE):
|
||||
role = roles.get(scope)
|
||||
if isinstance(role, dict):
|
||||
@@ -1043,6 +1062,23 @@ def persist_probe_result(
|
||||
observed_at=now,
|
||||
raw_payload=role,
|
||||
)
|
||||
raw_candidates = [
|
||||
item
|
||||
for item in (role.get("bind_infos") or [])
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
bind_info = role.get("bind_info")
|
||||
if not raw_candidates and isinstance(bind_info, dict):
|
||||
raw_candidates = [bind_info]
|
||||
record_role_api_candidates(
|
||||
db,
|
||||
account_id=account.id,
|
||||
task_id=task_id,
|
||||
candidates=raw_candidates,
|
||||
scope=scope,
|
||||
stage=f"probe.{scope}",
|
||||
source=source,
|
||||
)
|
||||
|
||||
gold = probe.get("gold") or {}
|
||||
if gold.get("status") == CAPABILITY_OK and _to_int(gold.get("balance")) is not None:
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Persist key Douyu role API responses for production diagnosis."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping, Sequence
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import DouyuRoleApiLog
|
||||
from .account_binding import binding_snapshot
|
||||
|
||||
_SENSITIVE_KEY_MARKERS = (
|
||||
"cookie",
|
||||
"authorization",
|
||||
"csrf",
|
||||
"acf_ccn",
|
||||
"token",
|
||||
"password",
|
||||
)
|
||||
|
||||
|
||||
def _redact(value: Any, *, depth: int = 0) -> Any:
|
||||
if depth > 12:
|
||||
return "<max-depth>"
|
||||
if isinstance(value, Mapping):
|
||||
cleaned: dict[str, Any] = {}
|
||||
for raw_key, raw_value in value.items():
|
||||
key = str(raw_key)
|
||||
if any(marker in key.casefold() for marker in _SENSITIVE_KEY_MARKERS):
|
||||
cleaned[key] = "<redacted>"
|
||||
else:
|
||||
cleaned[key] = _redact(raw_value, depth=depth + 1)
|
||||
return cleaned
|
||||
if isinstance(value, (list, tuple, set)):
|
||||
return [_redact(item, depth=depth + 1) for item in value]
|
||||
if isinstance(value, datetime):
|
||||
moment = value if value.tzinfo else value.replace(tzinfo=UTC)
|
||||
return moment.isoformat()
|
||||
if value is None or isinstance(value, (str, int, float, bool)):
|
||||
return value
|
||||
return str(value)
|
||||
|
||||
|
||||
def record_role_api_candidates(
|
||||
db: Session,
|
||||
*,
|
||||
account_id: int | None,
|
||||
candidates: Sequence[Mapping[str, Any]],
|
||||
scope: str,
|
||||
stage: str,
|
||||
source: str,
|
||||
task_id: int | None = None,
|
||||
) -> int:
|
||||
"""Append successful role query responses; callers decide when they matter."""
|
||||
if account_id is None:
|
||||
return 0
|
||||
rows: list[DouyuRoleApiLog] = []
|
||||
for candidate in candidates:
|
||||
info = dict(candidate)
|
||||
snapshot = binding_snapshot(info)
|
||||
act_alias = str(info.get("act_alias") or "")
|
||||
rows.append(
|
||||
DouyuRoleApiLog(
|
||||
account_id=int(account_id),
|
||||
task_id=int(task_id) if task_id is not None else None,
|
||||
scope=str(scope or "elite")[:16],
|
||||
stage=str(stage or "")[:48],
|
||||
source=str(source or "")[:64],
|
||||
act_alias=act_alias[:64],
|
||||
api_version=str(info.get("api_version") or "")[:16],
|
||||
role_name=str(snapshot["role_name"] or "")[:128],
|
||||
area_name=str(snapshot["area_name"] or "")[:128],
|
||||
plat_name=str(snapshot["plat_name"] or "")[:128],
|
||||
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"]),
|
||||
change_role_wait_time=_to_int(snapshot["change_role_wait_time"]),
|
||||
can_change_time=_to_int(snapshot["can_change_time"]),
|
||||
request_json=_redact(
|
||||
{
|
||||
"scope": scope,
|
||||
"stage": stage,
|
||||
"act_alias": act_alias,
|
||||
"api_version": info.get("api_version"),
|
||||
}
|
||||
),
|
||||
response_json=_redact(info.get("raw") or info),
|
||||
)
|
||||
)
|
||||
if not rows:
|
||||
return 0
|
||||
db.add_all(rows)
|
||||
return len(rows)
|
||||
|
||||
|
||||
def record_role_api_response(
|
||||
db: Session,
|
||||
*,
|
||||
account_id: int | None,
|
||||
response: Mapping[str, Any] | None,
|
||||
scope: str,
|
||||
stage: str,
|
||||
source: str,
|
||||
act_alias: str = "",
|
||||
task_id: int | None = None,
|
||||
) -> int:
|
||||
"""Append a write/confirm response that has no normalized role candidate."""
|
||||
if account_id is None:
|
||||
return 0
|
||||
db.add(
|
||||
DouyuRoleApiLog(
|
||||
account_id=int(account_id),
|
||||
task_id=int(task_id) if task_id is not None else None,
|
||||
scope=str(scope or "elite")[:16],
|
||||
stage=str(stage or "")[:48],
|
||||
source=str(source or "")[:64],
|
||||
act_alias=str(act_alias or "")[:64],
|
||||
request_json=_redact({"scope": scope, "act_alias": act_alias}),
|
||||
response_json=_redact(dict(response or {})),
|
||||
)
|
||||
)
|
||||
return 1
|
||||
|
||||
|
||||
def _to_int(value: Any) -> int | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
return int(float(value))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
__all__ = [
|
||||
"record_role_api_candidates",
|
||||
"record_role_api_response",
|
||||
]
|
||||
@@ -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)
|
||||
|
||||
@@ -497,7 +637,22 @@ class BindMixin:
|
||||
“是否 pending”只调用 ``_is_pending_role``;二维码轮询、查询角色和换绑
|
||||
时间查询都从这里选候选,避免各自用角色名或 bindRole 再写一套判断。
|
||||
"""
|
||||
for info in self._ordered_bind_candidates(candidates, prefer_aliases):
|
||||
ordered = self._ordered_bind_candidates(candidates, prefer_aliases)
|
||||
baseline = baseline_role_name.strip().casefold()
|
||||
if baseline:
|
||||
for info in ordered:
|
||||
role_name = str(info.get("role_name") or "").strip()
|
||||
if not role_name or role_name.casefold() == baseline:
|
||||
continue
|
||||
if self._is_pending_role(
|
||||
info,
|
||||
baseline_role_name=baseline_role_name,
|
||||
baseline_is_bound_act=baseline_is_bound_act,
|
||||
baseline_info=baseline_info,
|
||||
actionable_aliases=actionable_aliases,
|
||||
):
|
||||
return info
|
||||
for info in ordered:
|
||||
if self._is_pending_role(
|
||||
info,
|
||||
baseline_role_name=baseline_role_name,
|
||||
@@ -732,7 +887,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 +908,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 +937,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 +1060,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 +1068,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 +1137,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 +1178,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 +1221,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 +1374,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 +1460,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 +1616,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 +1658,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:
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from loguru import logger
|
||||
from sqlalchemy import and_, func, or_, select
|
||||
@@ -56,6 +56,8 @@ SUPPORTED_DOUYU_TASK_TYPES = {
|
||||
"exchange_xpd_goods": "兑换小店商品",
|
||||
}
|
||||
|
||||
BINDING_POLL_CLEANUP_GRACE_SECONDS = 120
|
||||
|
||||
DOUYU_HANDBOOK_SCOPES = {"elite", "esports", "peace"}
|
||||
DOUYU_HANDBOOK_TASK_TYPES = {
|
||||
"elite": {
|
||||
@@ -476,7 +478,8 @@ def cleanup_orphan_douyu_tasks(
|
||||
DouyuTask.queue_lane == "binding_poll",
|
||||
DouyuTask.next_run_at.isnot(None),
|
||||
DouyuTask.run_deadline_at.isnot(None),
|
||||
DouyuTask.run_deadline_at > now,
|
||||
DouyuTask.run_deadline_at
|
||||
> now - timedelta(seconds=BINDING_POLL_CLEANUP_GRACE_SECONDS),
|
||||
)
|
||||
durable_payment = and_(
|
||||
DouyuTask.task_type.in_(
|
||||
|
||||
@@ -88,7 +88,9 @@ ACTIVE_STATUSES = {
|
||||
"manual_required",
|
||||
}
|
||||
|
||||
BINDING_QR_TTL_SECONDS = int(os.getenv("PLATFORM_BINDING_QR_TTL_SECONDS", "600"))
|
||||
BINDING_QR_TTL_SECONDS = int(
|
||||
os.getenv("PLATFORM_BINDING_QR_TTL_SECONDS", "1260")
|
||||
)
|
||||
AUTO_SYNC_INTERVAL_SECONDS = 900.0
|
||||
DEFAULT_LIVE_CANDIDATE_LIMIT = 20
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ class LaneConfig:
|
||||
_DEFAULT_WORKERS: dict[TaskLane, int] = {
|
||||
TaskLane.INTERACTIVE_BINDING: 3,
|
||||
TaskLane.BATCH_COORDINATOR: 2,
|
||||
TaskLane.BINDING_POLL: 2,
|
||||
TaskLane.BINDING_POLL: 6,
|
||||
TaskLane.LOGIN: 4,
|
||||
TaskLane.ACCOUNT_CHECK: 4,
|
||||
TaskLane.ACCOUNT_SYNC: 3,
|
||||
|
||||
@@ -1519,7 +1519,12 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
: (latestQueryGameTaskByAccount.get(qrTask.account_id) || null))
|
||||
: null;
|
||||
const qrQueryResult = qrTask && qrQueryTask && qrQueryTask.id > qrTask.id ? qrQueryTask.result : null;
|
||||
const qrQueryRunning = Boolean(qrQueryTask && qrTask && qrQueryTask.id > qrTask.id && qrQueryTask.status === 'running');
|
||||
const qrQueryRunning = Boolean(
|
||||
qrQueryTask
|
||||
&& qrTask
|
||||
&& qrQueryTask.id > qrTask.id
|
||||
&& ['planned', 'pending', 'running'].includes(qrQueryTask.status),
|
||||
);
|
||||
const qrXpdConfirmTask = isXpdBindTask && qrTask
|
||||
? (latestConfirmXpdBindTaskByAccount.get(qrTask.account_id) || null)
|
||||
: null;
|
||||
@@ -1616,11 +1621,7 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
};
|
||||
|
||||
const queryQrRole = () => {
|
||||
if (!qrTask) return;
|
||||
if (qrAutoPolling) {
|
||||
message.info('正在自动识别角色,请稍候');
|
||||
return;
|
||||
}
|
||||
if (!qrTask || qrQueryRunning) return;
|
||||
void startTask(isXpdBindTask ? 'query_xpd_bind_info' : 'query_game_name', [qrTask.account_id]);
|
||||
};
|
||||
|
||||
@@ -3172,9 +3173,9 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
icon={<SearchOutlined />}
|
||||
onClick={queryQrRole}
|
||||
loading={qrQueryRunning}
|
||||
disabled={qrAutoPolling}
|
||||
disabled={qrQueryRunning}
|
||||
>
|
||||
{qrAutoPolling ? '自动识别中' : '查询角色'}
|
||||
{qrQueryRunning ? '查询中' : '立即查询角色'}
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
|
||||
Reference in New Issue
Block a user