fix(douyu): 修正绑定状态与换绑冷却判定

This commit is contained in:
yml
2026-11-22 02:10:29 +08:00
parent 21956d952c
commit fa75ce66ee
9 changed files with 636 additions and 104 deletions
+22 -2
View File
@@ -26,7 +26,23 @@ PC_UA = (
class DouyuActivityError(RuntimeError):
"""斗鱼活动接口异常。"""
"""斗鱼活动接口异常。
2026-11-22 绑定失败 HAR 证明仅保留中文 msg 不够:同一个“未到换绑时间”
可能是斗鱼平台账号冷却,也可能是游戏角色冷却,后续状态机需要原始 error
code 才能准确分类。其他调用方仍可只依赖 message。
"""
def __init__(
self,
message: str,
*,
code: Any = None,
payload: dict[str, Any] | None = None,
) -> None:
super().__init__(message)
self.code = code
self.payload = payload or {}
class DouyuActivityClient:
@@ -666,7 +682,11 @@ class DouyuActivityClient:
},
)
if payload.get("error") not in (0, "0"):
raise DouyuActivityError(payload.get("msg") or "确认绑定失败")
raise DouyuActivityError(
str(payload.get("msg") or "确认绑定失败"),
code=payload.get("error"),
payload=payload,
)
return {"ctn": ctn, "raw": payload}
def create_elite_qr(
+48 -22
View File
@@ -73,7 +73,7 @@
| `bindAccount=1` | 已绑定腾讯账号 |
| `bindRole=1` | 已选中游戏角色 |
| `bindAct=1` | 最终活动绑定已生效,这是唯一 `bound` 信号 |
| `bindAct=0 + bindRole=1` | 接口观察态是角色已选中但未确认;是否属于本轮扫码仍需 baseline 迁移 |
| `bindAct=0 + bindRole=1` | 角色已选中但未最终生效,是可确认 pending;允许在生成新二维码前已存在 |
| `needBindAct=1` | 当前活动允许继续绑定;这是长期能力标志,不等于本轮刚扫码 |
| `needBindRole=1` | 当前流程仍需要角色选择/角色信息 |
| `changeRoleWaitTime` | 换绑倒计时;只有 `bindAct=1` 时才可能是真实冷却 |
@@ -87,33 +87,37 @@
单个候选按以下顺序解释,详细结果由 `binding_pending_decision()` 返回:
1. 没有角色名:不可确认;
2. 没有扫码前 baseline:不可确认。当前 `bindAct=1` 返回 `already_bound`,
其他情况返回 `pending_without_baseline`;
2. 当前 `bindAct=1`:已经最终绑定,不可确认,原因 `already_bound`;
3. 角色名与 baseline 不同:可确认,原因 `role_changed`;
4. 角色名相同但缺少完整 baseline 快照:不可确认;
5. 同 alias 从 `bindAct=1` 变为 `bindAct=0`:可确认,原因
4. 同 alias 从 `bindAct=1` 变为 `bindAct=0`:可确认,原因
`same_alias_after_bound_transition`;
6. 同 alias 从 `needBindAct=0` 变为 `needBindAct=1`,且当前 `bindAct=0`:
5. 同 alias 从 `needBindAct=0` 变为 `needBindAct=1`,且当前 `bindAct=0`:
可确认,原因 `same_alias_after_pending_transition`;
7. 当前仍是 `bindAct=1`:视为已经绑定,原因 `already_bound`;
8. 其他同名角色:视为旧残留。baseline 本身是 pending 时原因
6. 动作 alias 当前是 `bindAct=0 + needBindAct=1 + roleName`:可确认,原因
`existing_actionable_pending`。即使它在二维码生成前已经存在、没有发生
状态迁移,官网也允许直接 `actBind`;
7. 没有 baseline 且不是动作 alias pending:不可确认,原因
`pending_without_baseline`;
8. 角色名相同但缺少完整 baseline 快照:不可确认;
9. 其他同名角色:视为旧残留。baseline 本身是 pending 时原因
`same_role_stale_pending`,否则为 `same_role_stale`。
2026-11-22 生产历史证明:账号早已 `bind_ok confirmed`,但活动 alias 长期同时返回
`bindAct=1 + needBindAct=1`。因此 `needBindAct=1` 不能单独证明本轮扫码,同名角色
必须看到扫码前后的真实状态迁移,否则确认按钮会把历史角色误报为新 pending。
`bindAct=1 + needBindAct=1`。因此 `needBindAct=1` 不能单独证明 pending;
真正决定 pending 的是 `bindAct=0`,不是角色名是否变化。
二维码预检只建立 baseline,生成二维码后固定进入 `waiting_scan`;只有轮询观察到
上述状态迁移或新角色后才进入 `role_ready`。旧任务如果已经是无迁移的
`role_ready`,`refresh_binding()` 会记录 `binding_stale_role_ignored` 并自动回到
未开始状态,不要求人工改库。
二维码预检若发现动作 alias 已有 `bindAct=0` pending,会发布二维码并立即进入
`role_ready`;没有合法 pending 时才进入 `waiting_scan`。历史错误的
`bindAct=1` `role_ready` 会被 `refresh_binding()` 记录为
`binding_stale_role_ignored` 并自动退回未开始状态。
### 完整流程
```text
查询所有 query_act_aliases
-> 找当前 bindAct=1(bound)
-> 保存扫码前 baseline,不能把静态 pending 直接当成本轮结果
-> 找动作 alias 上真实的 bindAct=0 pending
-> 保存扫码前 baseline,用于识别新角色和状态迁移
-> 生成二维码
-> 持久化 baseline、候选来源、判定原因
-> binding_poll 每轮先查 legacy(cjm)
@@ -340,8 +344,7 @@ docker compose logs douyu-login | grep '确认前状态'
初次修复:只要动作 alias 仍返回 `needBindAct=1`,同名角色也进入可确认状态。
> 2026-11-22 更正:该结论不成立。`needBindAct=1` 在该活动里可以长期存在;同名角色
> 必须依赖扫码前后状态迁移。候选选择仍优先真正变化的新角色,但不会再接受静态
> 同名 pending。
> 不能只靠它进入 pending。最终规则是 `bindAct=0` 才算 pending,`bindAct=1` 已绑定。
### 2026-11-22:历史绑定记录证明静态 pending 会误报
@@ -349,17 +352,40 @@ docker compose logs douyu-login | grep '确认前状态'
但二维码预检仍长期看到同名角色和 `bindAct=1 + needBindAct=1`。旧逻辑把该状态
写成 `role_ready`,随后客服页和履约页都显示“待确认角色”,实际用户尚未扫码。
修复:共享判定器要求 baseline 和状态迁移;二维码预检不再提前推进 `role_ready`;
客服页、履约工作台和账号探针统一消费同一判定结果;账号探针仅在活动 alias 明确
未绑定、legacy alias 为 `bindRole=1 + bindAct=0` 时保留只读观察到的 pending。
初次修复错误地要求所有同名 pending 都必须有状态迁移。这样虽然挡住了
`bindAct=1` 历史角色误报,却也会让合法的已有 `bindAct=0` pending 超时。
### 2026-11-22:最新 HAR 重新确认 pending 与平台冷却
`11.22-绑定成功-1.har`:二维码轮询 70 次都没有出现新的 `isScan=true`,但活动
alias 和 `cjm` 一开始就有 `bindAct=0 + bindRole=1 + roleName=只为爱杰宝`;
官网仍允许直接 `actBind` 并成功,随后回查变为 `bindAct=1`。
`11.22-绑定-换绑失败.har`:扫码已经出现 `isCompleted=true`,`cjm` 也返回了新角色
`巫师基尔斯84`,但活动 alias 仍绑定旧角色,且 `canChangeTime=1795449600`
(2026-11-24 00:00 CST)。`actBind` 返回:
```json
{"error":-200001,"msg":"该平台账号未到可换绑时间,请使用其他平台账号"}
```
这说明 `-200001` 限制的是斗鱼平台账号,不是腾讯游戏角色。失败时必须保留活动
alias 上的旧角色,不能把 `cjm` 的新角色写入账号库。
最终修复:`bindAct=0` 的已有 pending 可确认;`bindAct=1` 永远不是 pending;
二维码预检遇到平台账号冷却时不发码;确认接口保留原始 error code,结构化为
`account_role_cooldown`;失败前后都只写回活动 alias 的原绑定角色。
### 历史固定规则
- 不要把 `bindRole=1` 当成已绑定;
- 不要把未确认时的换绑倒计时当成冷却;
- 不要用 `cjm` 的旧角色覆盖活动 alias 当前状态;
- 不要要求每次绑定都必须换一个不同的角色,但同名重绑必须有扫码前后状态迁移;
- `bindAct=0` 是 pending,可以在发新二维码前已经存在;
- `bindAct=1` 是 bound,即使同时返回 `needBindAct=1` 也不是 pending;
- 不要把 `needBindAct=1` 单独当成本轮扫码结果;
- `actBind=-200001` 是当前斗鱼账号冷却,不是客户游戏角色冷却;
- `actBind` 失败后必须保留旧绑定,不能写入新扫码角色;
- 不要在页面层重新实现 `bindAct/needBindAct` 判断;
- 不要把原始 `bind_summary` 当业务文案,它只用于排障。
@@ -371,4 +397,4 @@ docker compose logs douyu-login | grep '确认前状态'
| 2026-11-21 | 补充 `storehome` 单账号全量商品资格、`storedetail`/`batchExchangeLimit` 边界和抓包证据入口 |
| 2026-11-21 | 补充同名重绑、轮询退避、直接绑定识别和角色接口原始响应留档 |
| 2026-11-21 | 按最新 HAR 更新鱼翅余额/充值二维码/支付状态、积分 multipart、到期批次和积分流水协议 |
| 2026-11-22 | 修正同名待确认误判:静态 `needBindAct` 不再作为扫码证据,二维码预检统一等待状态迁移 |
| 2026-11-22 | 按成功/失败 HAR 重构绑定判定:已有 `bindAct=0` 可确认,`bindAct=1` 不误报,`-200001` 归为斗鱼账号冷却并保留旧角色 |
+22 -3
View File
@@ -89,7 +89,8 @@ def test_role_resolver_uses_legacy_pending_role_when_current_is_empty():
assert result["source_alias"] == "cjm"
def test_role_resolver_does_not_treat_stale_same_role_as_new_pending():
def test_role_resolver_accepts_existing_action_alias_pending():
"""2026-11-22 成功 HAR:已有 bindAct=0 角色仍是可确认 pending。"""
role = "忧郁情潇藏心中"
client = RoleClient(
{
@@ -100,8 +101,26 @@ def test_role_resolver_does_not_treat_stale_same_role_as_new_pending():
result = resolve_elite_role(client, CONFIG)
assert result["status"] == ROLE_UNKNOWN
assert result["role_name"] == ""
assert result["status"] == ROLE_PENDING
assert result["role_name"] == role
assert result["source_alias"] == "current-alias"
assert result["decision"]["reason"] == "existing_actionable_pending"
def test_role_resolver_does_not_treat_bound_need_flag_as_pending():
"""2026-11-22 失败 HAR:bindAct=1 + needBindAct=1 仍是已绑定。"""
role = "狗鼻子弗尼亚bd"
client = RoleClient(
{
"current-alias": _bind(role, bound_act=True, bound_role=True),
"cjm": _bind(role, bound_role=True, need_act=False),
}
)
result = resolve_elite_role(client, CONFIG)
assert result["status"] == ROLE_BOUND
assert result["role_name"] == role
assert result["pending_role_name"] == ""
+64 -5
View File
@@ -5,7 +5,9 @@ from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from core.douyu import DouyuActivityClient
import pytest
from core.douyu import DouyuActivityClient, DouyuActivityError
from web.backend.models import Account
from web.backend.services.account_binding import (
BIND_BOUND,
@@ -195,7 +197,8 @@ def test_existing_pending_role_is_baseline_not_new_scan_result():
)
def test_existing_action_alias_pending_is_stale_without_transition():
def test_existing_action_alias_pending_is_confirmable_without_transition():
"""2026-11-22 成功 HAR:已有 bindAct=0 角色可直接确认。"""
role = "忧郁情潇藏心中"
baseline = _role_candidate(ACT_ALIAS, role, need_bind_act=True)
legacy = _role_candidate(LEGACY_ALIAS, role, need_bind_act=False)
@@ -218,9 +221,23 @@ def test_existing_action_alias_pending_is_stale_without_transition():
actionable_aliases=[ACT_ALIAS],
)
assert decision["confirmable"] is False
assert decision["reason"] == "same_role_stale_pending"
assert selected is None
assert decision["confirmable"] is True
assert decision["reason"] == "existing_actionable_pending"
assert selected is not None
assert selected["act_alias"] == ACT_ALIAS
def test_actionable_pending_without_baseline_is_confirmable():
role = "只为爱杰宝"
activity = _role_candidate(ACT_ALIAS, role, need_bind_act=True)
decision = binding_pending_decision(
activity,
actionable_aliases=[ACT_ALIAS],
)
assert decision["confirmable"] is True
assert decision["reason"] == "existing_actionable_pending"
def test_same_role_after_activity_bind_transition_is_pending():
@@ -323,6 +340,22 @@ def test_task_result_helpers_use_shared_same_role_transition_rule():
assert binding_role_from_result(same_role_scanned) == "少和我较劲"
def test_task_result_helpers_accept_existing_action_alias_pending():
activity = _role_candidate(ACT_ALIAS, "只为爱杰宝", need_bind_act=True)
result = {
**binding_snapshot(activity),
"act_alias": ACT_ALIAS,
"action_act_aliases": [ACT_ALIAS],
"before_bind_info": activity,
"baseline_role_name": "只为爱杰宝",
"bind_ready_for_confirm": True,
"bind_confirmed": False,
}
assert pending_binding_role_from_result(result) == "只为爱杰宝"
assert binding_role_from_result(result) == "只为爱杰宝"
def test_confirmed_new_role_replaces_account_current_role():
account = Account(
username="replace-role",
@@ -507,3 +540,29 @@ def test_qr_and_confirm_requests_follow_latest_har(monkeypatch):
"actAlias": (None, ACT_ALIAS),
"ctn": (None, "ctn"),
}
def test_confirm_bind_preserves_platform_cooldown_error_code(monkeypatch):
"""2026-11-22 失败 HAR:actBind 必须保留 -200001,不能只留中文消息。"""
client = DouyuActivityClient("acf_ccn=ctn")
monkeypatch.setattr(
client,
"acf_ccn",
lambda *, refresh_subscribe=True: "ctn",
)
payload = {
"error": -200001,
"msg": "该平台账号未到可换绑时间,请使用其他平台账号",
"data": None,
}
monkeypatch.setattr(
client,
"_request_json",
lambda *_args, **_kwargs: payload,
)
with pytest.raises(DouyuActivityError) as exc_info:
client.confirm_bind(ACT_ALIAS)
assert exc_info.value.code == -200001
assert exc_info.value.payload == payload
+251 -11
View File
@@ -6,6 +6,7 @@ from fastapi import HTTPException
from pydantic import ValidationError
from sqlalchemy import text
from core.douyu import DouyuActivityError
from tests.support.db import make_test_session
from web.backend.database import engine as app_engine
from web.backend.main import health
@@ -765,9 +766,107 @@ def test_deadline_poll_still_checks_role_once_before_timeout(db, monkeypatch):
assert task.result["bind_ready_for_confirm"] is True
def test_qr_preflight_treats_existing_action_alias_pending_as_baseline(
def test_confirm_bind_maps_platform_cooldown_and_keeps_old_role(
db, monkeypatch
):
"""2026-11-22 失败 HAR:-200001 是斗鱼账号冷却,旧绑定不能被新角色覆盖。"""
_, account, task = _fixtures(db, status="running")
old_role = "狗鼻子弗尼亚bd"
new_role = "巫师基尔斯84"
task.task_type = "confirm_bind"
task.result = {
"expected_role_name": new_role,
"baseline_role_name": old_role,
}
account.game_name = old_role
account.role_bind_status = "bound"
db.commit()
can_change_time = int(
(datetime.now(UTC) + timedelta(days=2)).timestamp()
)
old_bound = {
"act_alias": "20260120QYOOB",
"role_name": old_role,
"area_name": "微信",
"plat_name": "安卓(android)",
"is_bound_account": True,
"is_bound_role": True,
"is_bound_act": True,
"need_bind_act": True,
"need_bind_role": True,
"change_role_wait_time": 172_800,
"can_change_time": can_change_time,
"can_change_role": False,
}
new_pending = {
**old_bound,
"act_alias": "cjm",
"role_name": new_role,
"area_name": "微信",
"plat_name": "苹果(iOS)",
"is_bound_act": False,
"change_role_wait_time": 0,
"can_change_time": 0,
"can_change_role": True,
}
payload = {
"error": -200001,
"msg": "该平台账号未到可换绑时间,请使用其他平台账号",
"data": None,
}
class Client:
@staticmethod
def confirm_bind(_alias):
raise DouyuActivityError(
payload["msg"],
code=payload["error"],
payload=payload,
)
runner = DouyuBatchRunner(
db,
task.batch_id,
"confirm_bind",
close_db=False,
)
monkeypatch.setattr(runner, "_client", lambda _cookie: Client())
monkeypatch.setattr(
runner,
"_fetch_bind_info_candidates",
lambda *_args: [old_bound, new_pending],
)
runner._execute_confirm_bind(
db,
task,
account,
"PHPSESSID=x",
{
"bind_act_alias": "20260120QYOOB",
"confirm_act_alias": "20260120QYOOB",
"legacy_act_alias": "cjm",
},
)
db.refresh(task)
db.refresh(account)
assert task.status == "failed"
assert task.result["issue_code"] == "account_role_cooldown"
assert task.result["confirm_error_code"] == -200001
assert task.result["before_bound_bind_info"]["role_name"] == old_role
assert task.result["role_name"] == new_role
assert task.result["bind_ready_for_confirm"] is False
assert "斗鱼账号" in task.message
assert "更换斗鱼账号" in task.message
assert account.game_name == old_role
assert account.role_bind_status == "bound"
def test_qr_preflight_accepts_existing_action_alias_pending_from_har(
db, monkeypatch
):
"""2026-11-22 成功 HAR:已有 bindAct=0 角色无需等新一轮状态变化。"""
_, account, task = _fixtures(db, status="running")
role = "忧郁情潇藏心中"
legacy = {
@@ -821,17 +920,13 @@ def test_qr_preflight_treats_existing_action_alias_pending_as_baseline(
)
db.refresh(task)
assert task.status == "running"
assert task.status == "success"
assert task.result["url"] == "https://example.test/qr"
assert task.result["bind_phase"] == "waiting_scan"
assert task.result["bind_ready_for_confirm"] is False
assert "pending_role_name" not in task.result
action_decision = next(
item
for item in task.result["bind_candidate_decisions"]
if item["alias"] == "20260120QYOOB"
)
assert action_decision["reason"] == "same_role_stale_pending"
assert task.result["bind_phase"] == "role_ready"
assert task.result["bind_ready_for_confirm"] is True
assert task.result["pending_role_name"] == role
assert task.result["bind_decision"]["alias"] == "20260120QYOOB"
assert task.result["bind_decision"]["reason"] == "existing_actionable_pending"
def test_qr_preflight_keeps_bound_role_waiting_for_new_scan_transition(
@@ -905,6 +1000,77 @@ def test_qr_preflight_keeps_bound_role_waiting_for_new_scan_transition(
assert action_decision["reason"] == "already_bound"
def test_qr_preflight_blocks_platform_account_change_cooldown_from_har(
db, monkeypatch
):
"""2026-11-22 失败 HAR:canChangeTime 限制当前斗鱼号,发码前就必须拦截。"""
_, account, task = _fixtures(db, status="running")
role = "狗鼻子弗尼亚bd"
can_change_time = int(
(datetime.now(UTC) + timedelta(days=2)).timestamp()
)
activity = {
"act_alias": "20260120QYOOB",
"role_name": role,
"area_name": "微信",
"plat_name": "安卓(android)",
"is_bound_account": True,
"is_bound_role": True,
"is_bound_act": True,
"need_bind_act": True,
"need_bind_role": True,
"change_role_wait_time": 172_800,
"can_change_time": can_change_time,
"can_change_role": False,
}
account.game_name = role
account.role_bind_status = "bound"
db.commit()
client = type(
"Client",
(),
{
"get_bind_qr": lambda *_args: (_ for _ in ()).throw(
AssertionError("斗鱼账号冷却时不能生成二维码")
)
},
)()
runner = DouyuBatchRunner(
db,
task.batch_id,
"get_bind_qr",
close_db=False,
)
monkeypatch.setattr(runner, "_client", lambda _cookie: client)
monkeypatch.setattr(
runner,
"_fetch_bind_info_candidates",
lambda *_args: [activity],
)
runner._execute_get_bind_qr(
db,
task,
account,
"PHPSESSID=x",
{
"bind_act_alias": "20260120QYOOB",
"confirm_act_alias": "20260120QYOOB",
"legacy_act_alias": "cjm",
},
)
db.refresh(task)
db.refresh(account)
assert task.status == "failed"
assert task.result["bind_phase"] == "change_waiting"
assert task.result["issue_code"] == "account_role_cooldown"
assert "url" not in task.result
assert "斗鱼账号" in task.message
assert account.game_name == role
assert account.role_bind_status == "bound"
def test_binding_poll_accepts_existing_action_alias_pending_same_role(
db, monkeypatch
):
@@ -983,6 +1149,80 @@ def test_binding_poll_accepts_existing_action_alias_pending_same_role(
}
def test_binding_poll_accepts_unchanged_existing_action_alias_pending(
db, monkeypatch
):
"""2026-11-22 成功 HAR:已有动作 alias pending 不要求本轮状态变化。"""
_, account, task = _fixtures(db, status="running")
role = "只为爱杰宝"
legacy = {
"act_alias": "cjm",
"role_name": role,
"area_name": "手Q",
"plat_name": "安卓(android)",
"is_bound_account": True,
"is_bound_role": True,
"is_bound_act": False,
"need_bind_act": False,
"need_bind_role": True,
"change_role_wait_time": 0,
"can_change_time": 0,
"can_change_role": True,
}
activity = {
**legacy,
"act_alias": "20260120QYOOB",
"need_bind_act": True,
"change_role_wait_time": 2_592_000,
}
task.queue_lane = "binding_poll"
task.next_run_at = datetime.now(UTC)
task.run_deadline_at = datetime.now(UTC) + timedelta(minutes=10)
task.result = {
"url": "https://example.test/qr",
"query_act_aliases": ["cjm", "20260120QYOOB"],
"baseline_role_name": role,
"baseline_is_bound_act": False,
"before_bind_info": activity,
"bind_polling": True,
"qr_generated_at": datetime.now(UTC).isoformat(),
"poll_count": 2,
}
db.commit()
runner = DouyuBatchRunner(
db,
task.batch_id,
"get_bind_qr",
close_db=False,
)
monkeypatch.setattr(runner, "_client", lambda _cookie: object())
monkeypatch.setattr(
runner,
"_fetch_bind_info_candidates",
lambda _client, aliases: [
legacy if alias == "cjm" else activity for alias in aliases
],
)
runner.poll_bind_role_once(
db,
task,
account,
{
"bind_act_alias": "20260120QYOOB",
"confirm_act_alias": "20260120QYOOB",
"legacy_act_alias": "cjm",
},
)
db.refresh(task)
assert task.status == "success"
assert task.result["bind_phase"] == "role_ready"
assert task.result["role_name"] == role
assert task.result["bind_decision"]["alias"] == "20260120QYOOB"
assert task.result["bind_decision"]["reason"] == "existing_actionable_pending"
def test_active_task_budget_rejects_new_batch(db, monkeypatch):
user = User(username="budget-user", password_hash="hash", role="operation")
db.add(user)
+33
View File
@@ -2514,6 +2514,39 @@ class TestBindingAndCompletion(_Base):
live = service.customer_binding_out(self.session, task.id)
assert live["bindReadyForConfirm"] is False
def test_refresh_binding_uses_structured_platform_cooldown_issue(self):
"""2026-11-22 HAR:中文消息即使像角色冷却,也以 -200001 结构化码为准。"""
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-platform-cooldown-error-code",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="failed",
message="待绑定游戏账号(测试角色)未到换绑时间,请重新换账号扫码绑定",
result={
"bind_phase": "confirm_failed",
"issue_code": "account_role_cooldown",
"confirm_error": "该平台账号未到可换绑时间,请使用其他平台账号",
"confirm_error_code": -200001,
"bind_ready_for_confirm": False,
},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
self.session.commit()
detail = service.refresh_binding(self.session, task_id=task.id)
assert detail["task"]["issueCode"] == "account_role_cooldown"
assert detail["task"]["executionStatus"] == "manual_required"
assert "斗鱼账号" in detail["task"]["lastError"]
def test_list_hides_qr_but_detail_returns_it(self):
task = self._allocated()
bind_task = DouyuTask(
+82 -50
View File
@@ -285,6 +285,25 @@ def role_change_available_at(
return None
def is_platform_account_bind_cooldown(
error_code: Any = None,
message: str = "",
) -> bool:
"""是否为斗鱼平台账号自身的换绑冷却。
2026-11-22 换绑失败 HAR 中 ``actBind`` 返回 ``-200001``:
“该平台账号未到可换绑时间,请使用其他平台账号”。它限制的是当前斗鱼号,
不是用户扫码选择的腾讯游戏角色;提示和人工处理都必须区分两者。
"""
try:
normalized_code = int(error_code)
except (TypeError, ValueError):
normalized_code = None
return normalized_code == -200001 or "该平台账号未到可换绑时间" in (
message or ""
)
def binding_pending_decision(
info: dict | None,
*,
@@ -295,9 +314,15 @@ def binding_pending_decision(
) -> dict[str, Any]:
"""解释一个绑定候选是否可进入确认阶段。
角色名不是唯一事实,也不能要求每次都必须换新角色。用户重新绑定同名角色
时,必须观察到二维码生成后的状态变化。``needBindAct=1`` 在本活动里是
持续存在的“仍允许绑定”标志,不能单独证明存在新的扫码结果。
2026-11-22 两份 HAR 证明必须把两类状态分开:
- ``bindAct=0 + roleName``:角色已选中但未最终生效,是可确认 pending。
它可以在生成新二维码前就存在,官网仍允许直接 ``actBind``;
- ``bindAct=1 + needBindAct=1``:最终绑定已经生效。``needBindAct`` 是长期
存在的“仍允许以后换绑”标志,不能当成新的扫码结果。
因此 ``bindAct=1`` 永远不是 pending;``bindAct=0`` 的动作 alias 即使没有
观察到本轮状态迁移,也仍然可以确认。角色名相同不等于已经绑定。
"""
result: dict[str, Any] = {
"alias": str((info or {}).get("act_alias") or ""),
@@ -339,60 +364,67 @@ def binding_pending_decision(
if not role_name:
result["reason"] = "no_role"
return result
baseline = baseline_role_name.strip()
if not baseline:
# 2026-11-22:没有 baseline 无法证明这是本轮扫码产生的新角色。
# 历史库中 bound + needBindAct 会长期并存,不能再次冒充 pending。
result["reason"] = (
"already_bound"
if snapshot["is_bound_act"]
else "pending_without_baseline"
)
if snapshot["is_bound_act"]:
# 2026-11-22 换绑失败 HAR:历史角色会长期返回 bindAct=1 + needBindAct=1。
# 这表示当前绑定仍生效,不是待确认;若官方在扫码后直接完成绑定,轮询层
# 会通过 directly_confirmed 收敛,不需要把它伪装成 pending。
result["reason"] = "already_bound"
return result
if role_name.casefold() != baseline.casefold():
baseline = baseline_role_name.strip()
if baseline and role_name.casefold() != baseline.casefold():
result["role_changed"] = True
result.update({"confirmable": True, "reason": "role_changed"})
return result
if not isinstance(baseline_info, dict):
if snapshot["is_bound_act"]:
result["reason"] = "already_bound"
baseline_snapshot: dict[str, Any] | None = None
if isinstance(baseline_info, dict):
baseline_snapshot = binding_snapshot(baseline_info)
result["baseline_need_bind_act"] = bool(
baseline_snapshot["need_bind_act"]
)
result["baseline_is_pending"] = bool(
baseline_snapshot["role_name"]
and not baseline_snapshot["is_bound_act"]
and baseline_snapshot["need_bind_act"]
)
if result["same_alias"] and baseline_snapshot["is_bound_act"]:
result.update(
{
"confirmable": True,
"reason": "same_alias_after_bound_transition",
}
)
return result
result["reason"] = "same_role_without_baseline_info"
if (
result["same_alias"]
and not baseline_snapshot["need_bind_act"]
and snapshot["need_bind_act"]
):
result.update(
{
"confirmable": True,
"reason": "same_alias_after_pending_transition",
}
)
return result
# 2026-11-22 绑定成功 HAR:官网允许确认二维码生成前就已经存在的
# bindAct=0 角色。这里不能再要求“本轮必须发生状态变化”,否则合法 pending
# 会一直轮询到超时。关键安全边界是上面的 bindAct=1 已提前返回。
if result["actionable_alias"] and snapshot["need_bind_act"]:
result.update(
{
"confirmable": True,
"reason": "existing_actionable_pending",
}
)
return result
baseline_snapshot = binding_snapshot(baseline_info)
result["baseline_need_bind_act"] = bool(
baseline_snapshot["need_bind_act"]
)
result["baseline_is_pending"] = bool(
baseline_snapshot["role_name"]
and not baseline_snapshot["is_bound_act"]
and baseline_snapshot["need_bind_act"]
)
if result["same_alias"] and (
baseline_snapshot["is_bound_act"] and not snapshot["is_bound_act"]
):
result.update(
{
"confirmable": True,
"reason": "same_alias_after_bound_transition",
}
)
if not baseline:
result["reason"] = "pending_without_baseline"
return result
if (
result["same_alias"]
and not snapshot["is_bound_act"]
and snapshot["need_bind_act"]
and not baseline_snapshot["need_bind_act"]
):
result.update(
{
"confirmable": True,
"reason": "same_alias_after_pending_transition",
}
)
return result
if snapshot["is_bound_act"]:
result["reason"] = "already_bound"
if baseline_snapshot is None:
result["reason"] = "same_role_without_baseline_info"
return result
result["reason"] = (
"same_role_stale_pending"
+97 -8
View File
@@ -23,6 +23,7 @@ from .account_binding import (
binding_snapshot,
is_bound_act,
is_pending_binding_role,
is_platform_account_bind_cooldown,
is_role_change_cooling,
role_change_available_at,
set_bind_status,
@@ -1323,6 +1324,9 @@ class BindMixin:
),
"bind_phase": "change_waiting",
"bind_polling": False,
# 2026-11-22 换绑失败 HAR:canChangeTime 限制的是当前斗鱼账号,
# 不是客户扫码后出现的腾讯游戏角色。
"issue_code": "account_role_cooldown",
}
self._apply_bind_info_to_account(
account,
@@ -1333,7 +1337,7 @@ class BindMixin:
db,
task,
"failed",
f"{role_label} 暂不能换绑,剩余 {wait_text}",
f"斗鱼账号当前角色({role_label})未到可换绑时间,剩余 {wait_text}",
result,
)
return
@@ -1386,9 +1390,52 @@ class BindMixin:
)
),
}
# 2026-11-22:二维码生成前的 pending 只能作为 baseline,不能直接
# 推进 role_ready。官方活动 alias 会长期保留 needBindAct=1,必须在
# 二维码生成后观察到绑定状态变化,才能证明这是本轮扫码结果。
# 2026-11-22 绑定成功 HAR:二维码生成前已经存在的 bindAct=0 角色
# 是官网认可的 pending,可以直接确认,不要求本轮再次出现状态迁移。
# 历史 bindAct=1 角色已被上面的 pending 判定排除,不会再误报。
if pending_decision["confirmable"]:
pending_snapshot = self._bind_snapshot(pending_before)
pending_role = str(pending_snapshot["role_name"] or "")
pending_alias = str(pending_before.get("act_alias") or "")
pending_summary = (
f"act={pending_alias or '-'} "
f"{self._format_bind_summary(pending_before, pending=True)}"
)
result.update(
{
**pending_snapshot,
"act_alias": pending_alias,
"query_act_alias": pending_alias,
"pending_role_name": pending_role,
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
"bind_polling": False,
"bind_summary": pending_summary,
"bind_decision": pending_decision,
"bind_candidate_decisions": candidate_decisions,
"action_act_aliases": action_aliases,
"poll_count": 0,
}
)
account.updated_at = qr_generated_at
self._push_log(
"success",
"生成二维码时发现已有可确认角色 "
f"act={pending_alias or '-'} role={pending_role or '-'} "
f"reason={pending_decision['reason']}",
)
self._mark_task(
db,
task,
"success",
f"已识别现有待确认角色: {pending_role},待确认绑定",
result,
)
return
# 没有可确认 pending 时只发布二维码并交给持久化轮询。尤其不能在
# bindAct=1 + needBindAct=1 时提前进入 role_ready。
account.updated_at = datetime.now(UTC)
task.queue_lane = "binding_poll"
task.next_run_at = qr_generated_at + timedelta(
@@ -1558,25 +1605,67 @@ class BindMixin:
confirm_result = client.confirm_bind(use_confirm_alias)
except DouyuActivityError as exc:
confirm_msg = str(exc)
confirm_code = getattr(exc, "code", None)
confirm_payload = getattr(exc, "payload", None)
self._push_log("warning", f"确认绑定接口失败: {confirm_msg}")
# 待绑定游戏账号侧换绑限制(未到换绑时间等)导致确认失败:保留原绑定并给出明确提示
if isinstance(confirm_payload, dict) and confirm_payload:
record_role_api_response(
db,
account_id=account.id,
task_id=task.id,
response=confirm_payload,
scope=SCOPE_ELITE,
stage="confirm_bind.error",
source="douyu_task.confirm_bind",
act_alias=use_confirm_alias,
)
account_cooldown = is_platform_account_bind_cooldown(
confirm_code,
confirm_msg,
)
before_bound_snapshot = self._bind_snapshot(before_bound)
before_bound_role = str(before_bound_snapshot["role_name"] or "")
before_bound_wait = before_bound_snapshot["change_role_wait_time"]
before_bound_wait_text = self._format_wait_time(before_bound_wait)
if account_cooldown:
issue_code = "account_role_cooldown"
role_label = before_bound_role or role_name or "当前角色"
suffix = f",剩余 {before_bound_wait_text}" if before_bound_wait_text else ""
failure_message = (
f"斗鱼账号当前绑定角色({role_label})未到可换绑时间"
f"{suffix},请更换斗鱼账号或稍后重试"
)
else:
issue_code = "customer_role_cooldown"
failure_message = (
f"待绑定游戏账号({role_name or '-'})未到换绑时间"
"(不是斗鱼/虎牙账号),请重新换账号扫码绑定"
)
# 2026-11-22 换绑失败 HAR:actBind 已拒绝时新角色只存在于 cjm 候选态,
# 活动 alias 仍是原绑定。必须保留旧角色,不能让失败角色污染账号库。
if before_bound is not None:
self._apply_bind_info_to_account(account, before_bound)
self._apply_bind_info_to_account(account, before_bound, BIND_BOUND)
else:
account.updated_at = datetime.now(UTC)
self._mark_task(
db,
task,
"failed",
f"待绑定游戏账号({role_name or '-'})未到换绑时间(不是斗鱼/虎牙账号),请重新换账号扫码绑定",
failure_message,
{
"act_alias": use_confirm_alias,
"query_act_alias": query_alias,
"query_act_aliases": query_aliases,
"before_bind_info": before,
"before_bound_bind_info": before_bound,
"before_bound_snapshot": (
before_bound_snapshot if before_bound is not None else None
),
**before_snapshot,
"confirm_error": confirm_msg,
"bind_ready_for_confirm": True,
"confirm_error_code": confirm_code,
"issue_code": issue_code,
"bind_ready_for_confirm": False,
"bind_confirmed": False,
"bind_phase": "confirm_failed",
},
@@ -31,6 +31,7 @@ from ...models import (
from ...permissions import ROLE_LABELS
from ..account_binding import (
binding_role_from_result,
is_platform_account_bind_cooldown,
pending_binding_role_from_result,
)
from ..account_capability_service import (
@@ -1410,7 +1411,7 @@ def _customer_task_message(task: PlatformFulfillmentTask) -> str:
"points_short": "账号正在补充积分,请稍后重试",
"commodity_limit_reached": "当前商品暂时无法兑换,请联系客服",
"binding_failed": "暂未识别到绑定角色,请继续使用当前二维码完成扫码",
"account_role_cooldown": "当前绑定账号暂不可换绑,请截图本页面并联系客服处理",
"account_role_cooldown": "当前斗鱼账号未到换绑时间,请截图本页面并联系客服处理",
"customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理",
"eligibility_check_failed": "状态查询异常,请稍后刷新",
"manual_required": "当前需要人工处理,请联系客服",
@@ -1419,9 +1420,20 @@ def _customer_task_message(task: PlatformFulfillmentTask) -> str:
def _binding_failure_issue(bind_task: DouyuTask, result: dict[str, Any]) -> str:
explicit_issue = str(result.get("issue_code") or "")
if explicit_issue in {"account_role_cooldown", "customer_role_cooldown"}:
return explicit_issue
phase = str(result.get("bind_phase") or "")
message = str(bind_task.message or "")
if phase == "change_waiting" or "暂不能换绑" in message:
confirm_error = str(result.get("confirm_error") or "")
if (
phase == "change_waiting"
or is_platform_account_bind_cooldown(
result.get("confirm_error_code"),
f"{message} {confirm_error}",
)
or "暂不能换绑" in message
):
task_issue = "account_role_cooldown"
elif (
phase == "confirm_failed"
@@ -1432,7 +1444,7 @@ def _binding_failure_issue(bind_task: DouyuTask, result: dict[str, Any]) -> str:
else:
return "binding_failed"
messages = {
"account_role_cooldown": "当前绑定账号暂不可换绑,请截图本页面并联系客服处理",
"account_role_cooldown": "当前斗鱼账号未到换绑时间,请截图本页面并联系客服处理",
"customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理",
}
return task_issue if messages.get(task_issue) else "binding_failed"
@@ -1454,6 +1466,8 @@ def _customer_binding_queue_state(
return "allocation_queued", 2000
if not lease_ready:
return "lease_inactive", 0
if task.binding_status == "failed":
return "failed", 0
if bind_task is None:
return "ready_to_start", 0
result = bind_task.result or {}