452 lines
17 KiB
Python
452 lines
17 KiB
Python
"""角色绑定状态:把三个「垃圾场」列收敛成明确枚举。
|
||
|
||
## 背景:`bind_status` 崩掉的方式
|
||
|
||
历史上账号的绑定状态存在**一个自由文本列** `accounts.bind_status` 里,写入方遍布
|
||
6 个文件、29 处,取值 20 多种,而且**语义混杂**:
|
||
|
||
- 真正的状态:`bind_confirmed` / `game_not_bound`
|
||
- 动作痕迹:`bind_qr_generated` / `goods_locked` / `elite_opened`
|
||
- 纯查询痕迹:`points_queried` / `change_time_queried` / `csrf_token_ready`
|
||
|
||
因为它是**覆盖式**的,`bind_confirmed` 会被之后任意一次查询(例如
|
||
`limited_goods_queried`)盖掉 —— 于是「这个账号到底绑没绑」查不出来。
|
||
`esports_bind_status` / `xpd_bind_status` 是同一个病。
|
||
|
||
## 收敛规则(设计文档 §3.6)
|
||
|
||
1. **状态列只放「现在是什么」**:`unknown` / `unbound` / `pending` / `bound`;
|
||
2. **动作与查询痕迹一律不再写状态列** —— 动作已经进 `account_events`
|
||
(S5 的直发事件),查询痕迹本来就不该是状态;
|
||
3. 三列各管一个作用域,**一列一义**:
|
||
|
||
| 列 | 作用域 |
|
||
| --- | --- |
|
||
| `accounts.role_bind_status` | 精英宝典角色绑定 |
|
||
| `accounts.esports_bind_status` | 电竞手册角色绑定 |
|
||
| `accounts.xpd_bind_status` | 和平小店角色绑定 |
|
||
|
||
> ⚠️ `pending` 的含义是「角色已就绪 / 二维码已出,但**还没确认生效**」。
|
||
> 斗鱼侧的疑点宁可为 `unknown`,也不要冒充 `bound`。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from datetime import UTC, datetime, timedelta
|
||
from typing import Any
|
||
|
||
from ..models import Account
|
||
|
||
# ── 作用域 ──────────────────────────────────────────────
|
||
SCOPE_ELITE = "elite"
|
||
SCOPE_ESPORTS = "esports"
|
||
SCOPE_PEACE = "peace"
|
||
ALL_SCOPES = (SCOPE_ELITE, SCOPE_ESPORTS, SCOPE_PEACE)
|
||
|
||
# ── 取值域(**只有这四个**)────────────────────────────
|
||
BIND_UNKNOWN = "unknown" # 还没查过 / 旧数据不可信
|
||
BIND_UNBOUND = "unbound" # 明确没绑定
|
||
BIND_PENDING = "pending" # 角色就绪或二维码已出,尚未确认生效
|
||
BIND_BOUND = "bound" # 确认生效
|
||
|
||
ALL_BIND_STATES = (BIND_UNKNOWN, BIND_UNBOUND, BIND_PENDING, BIND_BOUND)
|
||
|
||
BIND_LABELS = {
|
||
BIND_UNKNOWN: "未知",
|
||
BIND_UNBOUND: "未绑定",
|
||
BIND_PENDING: "待确认",
|
||
BIND_BOUND: "已绑定",
|
||
}
|
||
|
||
#: 作用域 → `accounts` 上的列名
|
||
SCOPE_COLUMNS = {
|
||
SCOPE_ELITE: "role_bind_status",
|
||
SCOPE_ESPORTS: "esports_bind_status",
|
||
SCOPE_PEACE: "xpd_bind_status",
|
||
}
|
||
|
||
#: 作用域 → 接口载荷里的字段前缀。
|
||
#: ⚠️ **必须与列名一致**(`role_bind_status` / `esports_bind_status` / `xpd_bind_status`)。
|
||
#: 第一版这里按作用域名拼成了 `elite_bind_status` / `peace_bind_status`,
|
||
#: 与 schema 声明的字段名对不上 —— Pydantic 会静默用默认值,
|
||
#: 表现为「接口永远返回 unknown」,且**不报错**。有一条用例比对 schema 字段名。
|
||
SCOPE_PAYLOAD_PREFIX = {
|
||
SCOPE_ELITE: "role",
|
||
SCOPE_ESPORTS: "esports",
|
||
SCOPE_PEACE: "xpd",
|
||
}
|
||
|
||
SCOPE_LABELS = {
|
||
SCOPE_ELITE: "精英宝典角色",
|
||
SCOPE_ESPORTS: "电竞手册角色",
|
||
SCOPE_PEACE: "和平小店角色",
|
||
}
|
||
|
||
# ── 旧自由文本 → 新枚举 ─────────────────────────────────
|
||
#
|
||
# 只映射**无歧义**的取值;其余一律 `unknown`。判定标准是「这个旧值是不是
|
||
# 明确陈述了绑定关系」:
|
||
# - `bind_confirmed` 是「确认绑定成功」那一刻写的,而绑定不会被之后的查询撤销
|
||
# → 可以确信是 bound;
|
||
# - `game_not_bound` 明确说没绑 → unbound;
|
||
# - `bind_qr_generated` / `xpd_bind_qr_ready` 只是出了二维码 → pending;
|
||
# - `game_queried` / `points_queried` / `goods_locked` 之类**什么都没说**
|
||
# → unknown(设计文档 §5.5:不猜测性回填)。
|
||
#
|
||
# ⚠️ 这三张表**必须与迁移 `20261004_0044` 里的 CASE 逐字对应**,有一条用例
|
||
# 真跑那段 SQL 与它们比对(分叉了不会报错,只会让回填结果与运行时不一致)。
|
||
|
||
LEGACY_ROLE_BIND_MAP: dict[str, str] = {
|
||
"bind_confirmed": BIND_BOUND,
|
||
"bind_qr_generated": BIND_PENDING,
|
||
"game_not_bound": BIND_UNBOUND,
|
||
}
|
||
|
||
LEGACY_ESPORTS_BIND_MAP: dict[str, str] = {
|
||
"esports_bound": BIND_BOUND,
|
||
"esports_bind_ready": BIND_PENDING,
|
||
"esports_bind_confirming": BIND_PENDING,
|
||
"esports_qr_created": BIND_PENDING,
|
||
"esports_role_switching": BIND_PENDING,
|
||
# ⚠️ 这一条是**连生产库看真实数据**才发现的:电竞列里确实存在
|
||
# `game_not_bound`(生产 26 行)。漏了它就会被归成 `unknown`,
|
||
# 而它明明在说「没绑定」。教训:映射表必须拿**真实取值全集**核对,
|
||
# 不能只看文档里举的几个例子。
|
||
"game_not_bound": BIND_UNBOUND,
|
||
}
|
||
|
||
LEGACY_XPD_BIND_MAP: dict[str, str] = {
|
||
"xpd_bound": BIND_BOUND,
|
||
"xpd_bind_qr_ready": BIND_PENDING,
|
||
"xpd_not_bound": BIND_UNBOUND,
|
||
}
|
||
|
||
LEGACY_MAPS = {
|
||
SCOPE_ELITE: LEGACY_ROLE_BIND_MAP,
|
||
SCOPE_ESPORTS: LEGACY_ESPORTS_BIND_MAP,
|
||
SCOPE_PEACE: LEGACY_XPD_BIND_MAP,
|
||
}
|
||
|
||
|
||
def map_legacy_bind_status(scope: str, legacy: str | None) -> str:
|
||
"""旧自由文本 → 新枚举;认不出来就是 `unknown`(**不猜**)。"""
|
||
return LEGACY_MAPS.get(scope, {}).get((legacy or "").strip(), BIND_UNKNOWN)
|
||
|
||
|
||
def _assert_prefixes_match_columns() -> None:
|
||
"""自检:载荷前缀必须等于列名前缀(`role_bind_status` ↔ `role_bind_*`)。
|
||
|
||
这是被真实 bug 逼出来的 —— 前缀写错只会让接口静默返回默认值。
|
||
"""
|
||
for scope, column in SCOPE_COLUMNS.items():
|
||
expected = column.removesuffix("_bind_status")
|
||
assert SCOPE_PAYLOAD_PREFIX[scope] == expected, (
|
||
f"{scope}: 载荷前缀 {SCOPE_PAYLOAD_PREFIX[scope]!r} "
|
||
f"与列名 {column!r} 不一致"
|
||
)
|
||
|
||
|
||
_assert_prefixes_match_columns()
|
||
|
||
|
||
def get_bind_status(account: Account, scope: str) -> str:
|
||
column = SCOPE_COLUMNS.get(scope)
|
||
if not column:
|
||
raise ValueError(f"未知的绑定作用域: {scope}")
|
||
value = getattr(account, column, "") or ""
|
||
# 兼容:迁移之前的库或测试构造的对象可能还没有新列的值
|
||
return value if value in ALL_BIND_STATES else BIND_UNKNOWN
|
||
|
||
|
||
def set_bind_status(account: Account, scope: str, state: str) -> bool:
|
||
"""设置某个作用域的绑定状态,返回是否真的变化。
|
||
|
||
**这是三个绑定状态列的唯一写入口**(同 `account_lifecycle` 之于 `status`)。
|
||
`state` 必须是四个枚举值之一;传旧自由文本会直接报错,避免又把垃圾写回去。
|
||
"""
|
||
if state not in ALL_BIND_STATES:
|
||
raise ValueError(
|
||
f"绑定状态只能是 {ALL_BIND_STATES} 之一,收到 {state!r}。"
|
||
"动作/查询痕迹请进 account_events,不要写状态列。"
|
||
)
|
||
column = SCOPE_COLUMNS.get(scope)
|
||
if not column:
|
||
raise ValueError(f"未知的绑定作用域: {scope}")
|
||
if getattr(account, column, None) == state:
|
||
return False
|
||
setattr(account, column, state)
|
||
return True
|
||
|
||
|
||
def bind_payload(account: Account) -> dict[str, str]:
|
||
"""给接口/前端用的三列快照(值 + 中文标签)。"""
|
||
payload: dict[str, str] = {}
|
||
for scope in ALL_SCOPES:
|
||
prefix = SCOPE_PAYLOAD_PREFIX[scope]
|
||
state = get_bind_status(account, scope)
|
||
payload[f"{prefix}_bind_status"] = state
|
||
payload[f"{prefix}_bind_label"] = BIND_LABELS[state]
|
||
return payload
|
||
|
||
|
||
def derive_from_bind_info(info: dict | None) -> str | None:
|
||
"""从斗鱼腾讯绑定信息推导唯一业务状态。
|
||
|
||
最新抓包证明 `bindRole` 与 `bindAct` 不是同一阶段:
|
||
|
||
- 扫码选中角色后:`bindRole=1, bindAct=0`,此时应为 `pending`;
|
||
- 调用 `actBind` 后:`bindAct=1`,此时才是 `bound`;
|
||
- 两个标志都是 0:明确未绑定。
|
||
|
||
兼容旧接口:如果响应里完全没有 `is_bound_act`,才回退到
|
||
`is_bound_role` 判断。新接口始终会带上 `is_bound_act`。
|
||
"""
|
||
if not isinstance(info, dict):
|
||
return None
|
||
bound_act = _explicit_flag(info.get("is_bound_act"))
|
||
bound_role = _explicit_flag(info.get("is_bound_role"))
|
||
role_name = _binding_role_name(info)
|
||
if bound_act is True:
|
||
return BIND_BOUND
|
||
if bound_act is False:
|
||
if bound_role is True or bool(role_name):
|
||
return BIND_PENDING
|
||
return BIND_UNBOUND
|
||
# 旧接口没有 is_bound_act,保留原行为。
|
||
if bound_role is True:
|
||
return BIND_BOUND
|
||
if bound_role is False:
|
||
return BIND_UNBOUND
|
||
return None
|
||
|
||
|
||
def is_confirmed_binding(info: dict | None) -> bool:
|
||
"""是否已经完成最终绑定。
|
||
|
||
新接口以 `bindAct=1` 为准;旧接口缺少该字段时才回退到 `bindRole`。
|
||
"""
|
||
if not isinstance(info, dict):
|
||
return False
|
||
bound_act = _explicit_flag(info.get("is_bound_act"))
|
||
if bound_act is not None:
|
||
return bound_act
|
||
return _explicit_flag(info.get("is_bound_role")) is True
|
||
|
||
|
||
def is_bound_act(info: dict | None) -> bool:
|
||
"""接口原始 `bindAct` 标志,仅供绑定状态机和候选筛选使用。"""
|
||
return isinstance(info, dict) and _explicit_flag(info.get("is_bound_act")) is True
|
||
|
||
|
||
def can_change_role(info: dict | None, *, now: datetime | None = None) -> bool:
|
||
"""是否允许换绑。未绑定状态永远不受接口倒计时影响。"""
|
||
if not is_confirmed_binding(info):
|
||
return True
|
||
assert isinstance(info, dict)
|
||
moment = now or datetime.now(UTC)
|
||
can_change_time = _to_int(info.get("can_change_time"))
|
||
if can_change_time is not None and can_change_time > 0:
|
||
return can_change_time <= int(moment.timestamp())
|
||
wait_time = _to_int(info.get("change_role_wait_time"))
|
||
if wait_time is not None and wait_time > 0:
|
||
return False
|
||
raw_can_change = _explicit_flag(info.get("can_change_role"))
|
||
if raw_can_change is not None:
|
||
return raw_can_change
|
||
return True
|
||
|
||
|
||
def is_role_change_cooling(
|
||
info: dict | None,
|
||
*,
|
||
now: datetime | None = None,
|
||
) -> bool:
|
||
"""是否处于真实换绑冷却:最终绑定已完成且当前不可换绑。"""
|
||
return is_confirmed_binding(info) and not can_change_role(info, now=now)
|
||
|
||
|
||
def role_change_available_at(
|
||
info: dict | None,
|
||
*,
|
||
checked_at: datetime | None = None,
|
||
) -> datetime | None:
|
||
"""统一的换绑可用时间;未确认绑定或没有冷却时返回 None。"""
|
||
if not is_role_change_cooling(info, now=checked_at):
|
||
return None
|
||
assert isinstance(info, dict)
|
||
moment = checked_at or datetime.now(UTC)
|
||
can_change_time = _to_int(info.get("can_change_time"))
|
||
if can_change_time is not None and can_change_time > 0:
|
||
return datetime.fromtimestamp(can_change_time, tz=UTC)
|
||
wait_time = _to_int(info.get("change_role_wait_time"))
|
||
if wait_time is not None and wait_time > 0:
|
||
return moment + timedelta(seconds=wait_time)
|
||
return None
|
||
|
||
|
||
def is_pending_binding_role(
|
||
info: dict | None,
|
||
*,
|
||
baseline_role_name: str = "",
|
||
baseline_is_bound_act: bool = False,
|
||
baseline_info: dict | None = None,
|
||
) -> bool:
|
||
"""是否出现了本次扫码产生的可确认角色。
|
||
|
||
角色名不是唯一事实:用户可能换绑到同名角色。判断还要对比扫码前后的
|
||
活动绑定状态,尤其是活动 alias 从 ``bindAct=1`` 转为
|
||
``bindAct=0 + needBindAct=1`` 的待确认转换。
|
||
"""
|
||
if not isinstance(info, dict):
|
||
return False
|
||
snapshot = binding_snapshot(info)
|
||
role_name = snapshot["role_name"]
|
||
if not role_name:
|
||
return False
|
||
baseline = baseline_role_name.strip()
|
||
if not baseline:
|
||
return True
|
||
if role_name.casefold() != baseline.casefold():
|
||
return True
|
||
if snapshot["is_bound_act"]:
|
||
return False
|
||
if not isinstance(baseline_info, dict):
|
||
return False
|
||
|
||
baseline_snapshot = binding_snapshot(baseline_info)
|
||
same_alias = str(info.get("act_alias") or "") == str(
|
||
baseline_info.get("act_alias") or ""
|
||
)
|
||
return bool(
|
||
same_alias and baseline_snapshot["is_bound_act"] and snapshot["need_bind_act"]
|
||
)
|
||
|
||
|
||
def pending_binding_role_from_result(result: dict[str, Any] | None) -> str:
|
||
"""从执行器结果中提取“本次扫码产生的待确认角色”。
|
||
|
||
执行器结果已经是归一化快照,但仍必须复用 :func:`is_pending_binding_role`
|
||
判断,避免履约 API、客户页和任务工作台各自实现一套同名角色规则。
|
||
"""
|
||
if not isinstance(result, dict) or bool(result.get("bind_confirmed")):
|
||
return ""
|
||
role_name = str(result.get("role_name") or "").strip()
|
||
if not role_name or not bool(result.get("bind_ready_for_confirm")):
|
||
return ""
|
||
|
||
baseline = str(
|
||
result.get("baseline_role_name") or result.get("current_role_name") or ""
|
||
).strip()
|
||
baseline_info = result.get("before_bind_info")
|
||
# 没有完整 before_bind_info 时无法证明同名角色发生过状态转换。
|
||
# 此时宁可先不展示,也不能把账号历史角色误报成本次绑定结果。
|
||
if is_pending_binding_role(
|
||
result,
|
||
baseline_role_name=baseline,
|
||
baseline_is_bound_act=bool(result.get("baseline_is_bound_act")),
|
||
baseline_info=baseline_info,
|
||
):
|
||
return role_name
|
||
return ""
|
||
|
||
|
||
def binding_role_from_result(result: dict[str, Any] | None) -> str:
|
||
"""返回页面可展示的本次绑定角色。
|
||
|
||
- 待确认:只返回本次扫码产生的新角色。
|
||
- 已确认:返回最终 ``bindAct=1`` 回查角色。
|
||
- 其他状态:返回空,绝不把账号历史角色当成本次结果展示。
|
||
"""
|
||
if not isinstance(result, dict):
|
||
return ""
|
||
pending_role = pending_binding_role_from_result(result)
|
||
if pending_role:
|
||
return pending_role
|
||
if bool(result.get("bind_confirmed")):
|
||
return str(
|
||
result.get("role_name") or result.get("current_role_name") or ""
|
||
).strip()
|
||
return ""
|
||
|
||
|
||
def binding_channel(info: dict | None) -> str:
|
||
"""统一游戏渠道展示:区服 / 平台。"""
|
||
if not isinstance(info, dict):
|
||
return ""
|
||
return " / ".join(
|
||
part
|
||
for part in (
|
||
str(info.get("area_name") or "").strip(),
|
||
str(info.get("plat_name") or "").strip(),
|
||
)
|
||
if part
|
||
)
|
||
|
||
|
||
def binding_snapshot(info: dict | None) -> dict[str, Any]:
|
||
"""斗鱼腾讯绑定的唯一业务快照,供执行器、账号刷新和概览复用。"""
|
||
data = info if isinstance(info, dict) else {}
|
||
role_name = _binding_role_name(data)
|
||
bound_status = derive_from_bind_info(data)
|
||
phase = {
|
||
BIND_BOUND: "confirmed",
|
||
BIND_PENDING: "role_ready",
|
||
BIND_UNBOUND: "unbound",
|
||
}.get(bound_status or "", "unknown")
|
||
bound_act = _explicit_flag(data.get("is_bound_act")) is True
|
||
return {
|
||
"role_name": role_name,
|
||
"area_name": str(data.get("area_name") or "").strip(),
|
||
"plat_name": str(data.get("plat_name") or "").strip(),
|
||
"partition_name": str(data.get("partition_name") or "").strip(),
|
||
"game_channel": binding_channel(data),
|
||
"nickname": str(data.get("nickname") or "").strip(),
|
||
"account_type": str(data.get("account_type") or "").strip(),
|
||
"account_avatar": str(data.get("account_avatar") or "").strip(),
|
||
"is_bound_account": _truthy_flag(data.get("is_bound_account")),
|
||
"is_bound_role": _truthy_flag(data.get("is_bound_role")),
|
||
"is_bound_act": bound_act,
|
||
"need_bind_act": _truthy_flag(data.get("need_bind_act")),
|
||
"need_bind_role": _truthy_flag(data.get("need_bind_role")),
|
||
"change_role_wait_time": _to_int(data.get("change_role_wait_time")),
|
||
"can_change_time": _to_int(data.get("can_change_time")),
|
||
"can_change_role": can_change_role(data),
|
||
"is_change_cooling": is_role_change_cooling(data),
|
||
"bind_status": bound_status,
|
||
"bind_phase": phase,
|
||
"bind_confirmed": bound_status == BIND_BOUND,
|
||
"bind_ready_for_confirm": bound_status == BIND_PENDING and bool(role_name),
|
||
"game_id": str(data.get("game_id") or "").strip(),
|
||
"game_name": str(data.get("game_name") or "").strip(),
|
||
"tx_act_id": _to_int(data.get("tx_act_id")) or 0,
|
||
"bind_info": data,
|
||
}
|
||
|
||
|
||
def _binding_role_name(info: dict) -> str:
|
||
return str(info.get("role_name") or info.get("role") or "").strip()
|
||
|
||
|
||
def _explicit_flag(value: Any) -> bool | None:
|
||
if value is None or value == "":
|
||
return None
|
||
if isinstance(value, bool):
|
||
return value
|
||
text = str(value).strip().lower()
|
||
if text in {"1", "true", "yes", "y"}:
|
||
return True
|
||
if text in {"0", "false", "no", "n", ""}:
|
||
return False
|
||
return None
|
||
|
||
|
||
def _truthy_flag(value: Any) -> bool:
|
||
return _explicit_flag(value) is True
|
||
|
||
|
||
def _to_int(value: Any) -> int | None:
|
||
try:
|
||
return int(float(value))
|
||
except (TypeError, ValueError):
|
||
return None
|