1039 lines
33 KiB
Python
1039 lines
33 KiB
Python
"""斗鱼账号能力探针的唯一实现。
|
||
|
||
CK、斗鱼昵称、游戏角色、积分、鱼翅和商品不是同一个能力。本模块把这些能力
|
||
分别查询、分别判断,并统一负责写回账号与账号时间线。其他业务模块只能调用
|
||
这里,不再自行解释 bindRole/bindAct 或拼 actAlias。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import copy
|
||
import hashlib
|
||
import os
|
||
import time
|
||
from collections.abc import Callable, Mapping, Sequence
|
||
from datetime import UTC, datetime
|
||
from typing import Any
|
||
from uuid import uuid4
|
||
|
||
from loguru import logger
|
||
from sqlalchemy.orm import Session
|
||
|
||
from core.douyu import DouyuActivityClient
|
||
|
||
from ..models import Account, User
|
||
from .account_binding import (
|
||
BIND_BOUND,
|
||
BIND_PENDING,
|
||
BIND_UNBOUND,
|
||
SCOPE_ELITE,
|
||
SCOPE_ESPORTS,
|
||
SCOPE_PEACE,
|
||
binding_snapshot,
|
||
derive_from_bind_info,
|
||
is_bound_act,
|
||
is_pending_binding_role,
|
||
role_change_available_at,
|
||
set_bind_status,
|
||
)
|
||
from .account_events_service import CATEGORY_OPS, emit
|
||
from .account_lifecycle import on_ck_verdict
|
||
from .cookie_check_service import check_douyu_cookie, classify_douyu_cookie_result
|
||
from .douyu_activity_query import (
|
||
activity_client,
|
||
query_activity_goods,
|
||
query_bind_info,
|
||
query_csrf,
|
||
query_elite_user_info,
|
||
query_esports_bind_info,
|
||
query_gold_account,
|
||
query_limited_goods_result,
|
||
query_points,
|
||
query_xpd_bind_info,
|
||
)
|
||
from .douyu_elite_status import (
|
||
elite_is_currently_open,
|
||
normalize_elite_expire_time,
|
||
)
|
||
from .douyu_goods_service import serialize_goods
|
||
|
||
SESSION_VALID = "valid"
|
||
SESSION_INVALID = "invalid"
|
||
SESSION_ERROR = "error"
|
||
SESSION_UNVERIFIED = "unverified"
|
||
SESSION_UNKNOWN = "unknown"
|
||
|
||
ROLE_BOUND = BIND_BOUND
|
||
ROLE_PENDING = BIND_PENDING
|
||
ROLE_UNBOUND = BIND_UNBOUND
|
||
ROLE_ERROR = "error"
|
||
ROLE_UNKNOWN = "unknown"
|
||
|
||
CAPABILITY_OK = "ok"
|
||
CAPABILITY_ERROR = "error"
|
||
CAPABILITY_UNKNOWN = "unknown"
|
||
|
||
CONFIG_KEYS = (
|
||
"manual_id",
|
||
"rid",
|
||
"bind_act_alias",
|
||
"confirm_act_alias",
|
||
"legacy_act_alias",
|
||
"esports_manual_id",
|
||
"esports_act_alias",
|
||
"xpd_act_alias",
|
||
"xpd_rid",
|
||
"xpd_act_id",
|
||
"peace_enabled",
|
||
)
|
||
|
||
_DEFAULT_SESSION_CHECKER = object()
|
||
|
||
|
||
def _env_float(name: str, default: float) -> float:
|
||
try:
|
||
value = float(os.getenv(name, str(default)))
|
||
except ValueError:
|
||
return default
|
||
return value if value >= 0 else default
|
||
|
||
|
||
_CACHE_TTL_SECONDS = _env_float("DOUYU_PROBE_CACHE_SECONDS", 30.0)
|
||
_probe_cache: dict[str, tuple[float, dict[str, Any]]] = {}
|
||
|
||
|
||
def _now() -> datetime:
|
||
return datetime.now(UTC)
|
||
|
||
|
||
def _text(value: Any, limit: int = 240) -> str:
|
||
text = str(value if value is not None else "").strip()
|
||
return text if len(text) <= limit else text[: limit - 3] + "..."
|
||
|
||
|
||
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
|
||
|
||
|
||
def config_mapping(config: Any) -> dict[str, Any]:
|
||
"""把 ORM 配置或普通映射整理成探针使用的只读字典。"""
|
||
if config is None:
|
||
return {}
|
||
if isinstance(config, Mapping):
|
||
source = config
|
||
else:
|
||
source = {key: getattr(config, key, None) for key in CONFIG_KEYS}
|
||
return {key: source.get(key) for key in CONFIG_KEYS}
|
||
|
||
|
||
def profile_from_cookie(cookie: str) -> dict[str, str]:
|
||
"""从 CK 读取稳定身份字段;展示昵称仍以在线接口结果优先。"""
|
||
return DouyuActivityClient.profile_from_cookie(cookie)
|
||
|
||
|
||
def update_identity_from_cookie(account: Account, cookie: str) -> dict[str, str]:
|
||
"""账号导入/登录后的统一身份回填。"""
|
||
profile = profile_from_cookie(cookie)
|
||
if profile.get("uid"):
|
||
account.uid = profile["uid"][:32]
|
||
if profile.get("nickname"):
|
||
account.nickname = profile["nickname"][:128]
|
||
return profile
|
||
|
||
|
||
def _dedupe(values: Sequence[Any]) -> list[str]:
|
||
result: list[str] = []
|
||
for value in values:
|
||
text = str(value or "").strip()
|
||
if text and text not in result:
|
||
result.append(text)
|
||
return result
|
||
|
||
|
||
def elite_action_aliases(config: Mapping[str, Any]) -> list[str]:
|
||
return _dedupe(
|
||
[
|
||
config.get("bind_act_alias"),
|
||
config.get("confirm_act_alias"),
|
||
]
|
||
)
|
||
|
||
|
||
def elite_query_aliases(config: Mapping[str, Any]) -> list[str]:
|
||
return _dedupe(
|
||
[
|
||
*elite_action_aliases(config),
|
||
config.get("legacy_act_alias"),
|
||
]
|
||
)
|
||
|
||
|
||
def query_elite_bind_candidates(
|
||
client: DouyuActivityClient,
|
||
aliases: Sequence[str],
|
||
) -> tuple[list[dict[str, Any]], list[str]]:
|
||
"""按 alias 批量读取绑定候选;单个 alias 失败不阻断其他来源。"""
|
||
candidates: list[dict[str, Any]] = []
|
||
errors: list[str] = []
|
||
for alias in _dedupe(aliases):
|
||
try:
|
||
info = query_bind_info(client, act_alias=alias)
|
||
except Exception as exc: # noqa: BLE001 - 单个 alias 失败不阻断其他来源
|
||
errors.append(f"{alias}: {type(exc).__name__}: {_text(exc)}")
|
||
continue
|
||
candidates.append({**info, "act_alias": alias})
|
||
return candidates, errors
|
||
|
||
|
||
def _role_candidate(info: Mapping[str, Any]) -> dict[str, Any]:
|
||
snapshot = binding_snapshot(dict(info))
|
||
return {
|
||
"act_alias": str(info.get("act_alias") or ""),
|
||
"role_name": snapshot["role_name"],
|
||
"area_name": snapshot["area_name"],
|
||
"plat_name": snapshot["plat_name"],
|
||
"is_bound_act": is_bound_act(dict(info)),
|
||
"is_bound_role": bool(info.get("is_bound_role")),
|
||
"need_bind_act": bool(info.get("need_bind_act")),
|
||
"need_bind_role": bool(info.get("need_bind_role")),
|
||
}
|
||
|
||
|
||
def _role_result(
|
||
*,
|
||
status: str,
|
||
bind_info: Mapping[str, Any] | None,
|
||
candidates: list[dict[str, Any]],
|
||
aliases: list[str],
|
||
errors: list[str],
|
||
pending_info: Mapping[str, Any] | None = None,
|
||
bind_infos: Sequence[Mapping[str, Any]] | None = None,
|
||
) -> dict[str, Any]:
|
||
selected = dict(bind_info) if bind_info else {}
|
||
snapshot = binding_snapshot(selected) if selected else {}
|
||
pending = dict(pending_info) if pending_info else {}
|
||
pending_snapshot = binding_snapshot(pending) if pending else {}
|
||
return {
|
||
"status": status,
|
||
"role_name": str(snapshot.get("role_name") or ""),
|
||
"area_name": str(snapshot.get("area_name") or ""),
|
||
"plat_name": str(snapshot.get("plat_name") or ""),
|
||
"game_channel": str(snapshot.get("game_channel") or ""),
|
||
"game_name": str(snapshot.get("game_name") or ""),
|
||
"game_account": str(snapshot.get("nickname") or ""),
|
||
"source_alias": str(selected.get("act_alias") or ""),
|
||
"is_bound_act": bool(snapshot.get("is_bound_act")),
|
||
"is_bound_role": bool(snapshot.get("is_bound_role")),
|
||
"need_bind_act": bool(snapshot.get("need_bind_act")),
|
||
"need_bind_role": bool(snapshot.get("need_bind_role")),
|
||
"change_role_wait_time": snapshot.get("change_role_wait_time"),
|
||
"can_change_role": snapshot.get("can_change_role"),
|
||
"can_change_time": snapshot.get("can_change_time"),
|
||
"pending_role_name": str(pending_snapshot.get("role_name") or ""),
|
||
"pending_area_name": str(pending_snapshot.get("area_name") or ""),
|
||
"pending_plat_name": str(pending_snapshot.get("plat_name") or ""),
|
||
"query_act_aliases": aliases,
|
||
"candidates": candidates,
|
||
"errors": errors,
|
||
"snapshot": snapshot,
|
||
"bind_info": selected,
|
||
"bind_infos": [dict(item) for item in (bind_infos or [])],
|
||
}
|
||
|
||
|
||
def resolve_elite_role(
|
||
client: DouyuActivityClient,
|
||
config: Mapping[str, Any],
|
||
*,
|
||
bind_fetcher: Callable[[str], dict[str, Any]] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""查询精英宝典角色:活动 alias 优先,legacy 负责最新/待确认状态。"""
|
||
aliases = elite_query_aliases(config)
|
||
if not aliases:
|
||
return _role_result(
|
||
status=ROLE_ERROR,
|
||
bind_info=None,
|
||
candidates=[],
|
||
aliases=[],
|
||
errors=["未配置绑定活动 actAlias"],
|
||
)
|
||
|
||
if bind_fetcher is None:
|
||
candidates_info, errors = query_elite_bind_candidates(client, aliases)
|
||
else:
|
||
candidates_info = []
|
||
errors = []
|
||
for alias in aliases:
|
||
try:
|
||
candidates_info.append({**bind_fetcher(alias), "act_alias": alias})
|
||
except Exception as exc: # noqa: BLE001
|
||
errors.append(f"{alias}: {type(exc).__name__}: {_text(exc)}")
|
||
candidates = [_role_candidate(info) for info in candidates_info]
|
||
|
||
action_aliases = elite_action_aliases(config)
|
||
ordered_aliases = aliases
|
||
bound_info = next(
|
||
(
|
||
info
|
||
for alias in action_aliases
|
||
for info in candidates_info
|
||
if str(info.get("act_alias") or "") == alias
|
||
and derive_from_bind_info(info) == BIND_BOUND
|
||
),
|
||
None,
|
||
)
|
||
pending_info = next(
|
||
(
|
||
info
|
||
for alias in ordered_aliases
|
||
for info in candidates_info
|
||
if str(info.get("act_alias") or "") == alias
|
||
and is_pending_binding_role(
|
||
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,
|
||
)
|
||
),
|
||
None,
|
||
)
|
||
if bound_info is not None:
|
||
return _role_result(
|
||
status=ROLE_BOUND,
|
||
bind_info=bound_info,
|
||
candidates=candidates,
|
||
aliases=aliases,
|
||
errors=errors,
|
||
pending_info=(
|
||
pending_info
|
||
if str((pending_info or {}).get("role_name") or "")
|
||
!= str(bound_info.get("role_name") or "")
|
||
else None
|
||
),
|
||
bind_infos=candidates_info,
|
||
)
|
||
if pending_info is not None:
|
||
return _role_result(
|
||
status=ROLE_PENDING,
|
||
bind_info=pending_info,
|
||
candidates=candidates,
|
||
aliases=aliases,
|
||
errors=errors,
|
||
bind_infos=candidates_info,
|
||
)
|
||
if errors and not candidates_info:
|
||
return _role_result(
|
||
status=ROLE_ERROR,
|
||
bind_info=None,
|
||
candidates=candidates,
|
||
aliases=aliases,
|
||
errors=errors,
|
||
bind_infos=candidates_info,
|
||
)
|
||
if errors:
|
||
return _role_result(
|
||
status=ROLE_UNKNOWN,
|
||
bind_info=None,
|
||
candidates=candidates,
|
||
aliases=aliases,
|
||
errors=errors,
|
||
bind_infos=candidates_info,
|
||
)
|
||
if candidates_info and any(
|
||
derive_from_bind_info(info) == BIND_UNBOUND for info in candidates_info
|
||
):
|
||
first_info = candidates_info[0]
|
||
return _role_result(
|
||
status=ROLE_UNBOUND,
|
||
bind_info=first_info,
|
||
candidates=candidates,
|
||
aliases=aliases,
|
||
errors=[],
|
||
bind_infos=candidates_info,
|
||
)
|
||
return _role_result(
|
||
status=ROLE_UNKNOWN,
|
||
bind_info=None,
|
||
candidates=candidates,
|
||
aliases=aliases,
|
||
errors=[],
|
||
bind_infos=candidates_info,
|
||
)
|
||
|
||
|
||
def _resolve_single_role(
|
||
fetcher: Callable[[], dict[str, Any]],
|
||
*,
|
||
alias: str,
|
||
) -> dict[str, Any]:
|
||
try:
|
||
info = fetcher()
|
||
except Exception as exc: # noqa: BLE001 - 角色查询失败要保留上一快照
|
||
return _role_result(
|
||
status=ROLE_ERROR,
|
||
bind_info=None,
|
||
candidates=[],
|
||
aliases=[alias] if alias else [],
|
||
errors=[f"{alias or '-'}: {type(exc).__name__}: {_text(exc)}"],
|
||
)
|
||
info = {**info, "act_alias": alias}
|
||
candidate = _role_candidate(info)
|
||
if derive_from_bind_info(info) == BIND_BOUND:
|
||
status = ROLE_BOUND
|
||
elif candidate["role_name"]:
|
||
status = ROLE_PENDING
|
||
elif derive_from_bind_info(info) == BIND_UNBOUND:
|
||
status = ROLE_UNBOUND
|
||
else:
|
||
status = ROLE_UNKNOWN
|
||
return _role_result(
|
||
status=status,
|
||
bind_info=info if status != ROLE_UNBOUND else None,
|
||
candidates=[candidate],
|
||
aliases=[alias] if alias else [],
|
||
errors=[],
|
||
bind_infos=[info],
|
||
)
|
||
|
||
|
||
def resolve_esports_role(
|
||
client: DouyuActivityClient,
|
||
config: Mapping[str, Any],
|
||
*,
|
||
bind_fetcher: Callable[[str], dict[str, Any]] | None = None,
|
||
) -> dict[str, Any]:
|
||
alias = str(config.get("esports_act_alias") or "").strip()
|
||
if not alias:
|
||
return _role_result(
|
||
status=ROLE_ERROR,
|
||
bind_info=None,
|
||
candidates=[],
|
||
aliases=[],
|
||
errors=["未配置电竞手册活动别名"],
|
||
)
|
||
return _resolve_single_role(
|
||
(
|
||
(lambda: bind_fetcher(alias))
|
||
if bind_fetcher is not None
|
||
else (lambda: query_esports_bind_info(client, act_alias=alias))
|
||
),
|
||
alias=alias,
|
||
)
|
||
|
||
|
||
def resolve_peace_role(
|
||
client: DouyuActivityClient,
|
||
config: Mapping[str, Any],
|
||
*,
|
||
bind_fetcher: Callable[[str], dict[str, Any]] | None = None,
|
||
) -> dict[str, Any]:
|
||
alias = str(config.get("xpd_act_alias") or "").strip()
|
||
if not alias:
|
||
return _role_result(
|
||
status=ROLE_ERROR,
|
||
bind_info=None,
|
||
candidates=[],
|
||
aliases=[],
|
||
errors=["未配置和平小店活动别名"],
|
||
)
|
||
return _resolve_single_role(
|
||
(
|
||
(lambda: bind_fetcher(alias))
|
||
if bind_fetcher is not None
|
||
else (lambda: query_xpd_bind_info(client, act_alias=alias))
|
||
),
|
||
alias=alias,
|
||
)
|
||
|
||
|
||
def probe_session(
|
||
cookie: str,
|
||
*,
|
||
checker: Callable[[str], dict[str, Any]] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""统一 CK 会话检测。只说明账号会话状态,不冒充角色或资产状态。"""
|
||
if not str(cookie or "").strip():
|
||
return {
|
||
"status": SESSION_UNVERIFIED,
|
||
"message": "账号没有 CK",
|
||
"checked_at": _now().isoformat(),
|
||
"detail": {},
|
||
}
|
||
active_checker = checker or check_douyu_cookie
|
||
try:
|
||
detail = active_checker(cookie)
|
||
except Exception as exc: # noqa: BLE001 - 外部检测边界
|
||
return {
|
||
"status": SESSION_ERROR,
|
||
"message": f"{type(exc).__name__}: {_text(exc)}",
|
||
"checked_at": _now().isoformat(),
|
||
"detail": {},
|
||
}
|
||
status = classify_douyu_cookie_result(detail)
|
||
raw_checked_at = detail.get("checked_at")
|
||
checked_at = (
|
||
raw_checked_at.isoformat()
|
||
if isinstance(raw_checked_at, datetime)
|
||
else str(raw_checked_at or _now().isoformat())
|
||
)
|
||
return {
|
||
"status": status,
|
||
"message": _text(detail.get("message")),
|
||
"checked_at": checked_at,
|
||
"detail": detail,
|
||
}
|
||
|
||
|
||
def _points_expire_at(
|
||
points_response: Mapping[str, Any] | None,
|
||
*,
|
||
checked_at: datetime,
|
||
) -> datetime | None:
|
||
raw = (points_response or {}).get("willExpireTime") or (points_response or {}).get(
|
||
"will_expire_time"
|
||
)
|
||
value = _to_int(raw)
|
||
if value is None or value <= 0:
|
||
return None
|
||
if value > 10_000_000_000:
|
||
value //= 1000
|
||
if value < int(checked_at.timestamp()) - 60:
|
||
return None
|
||
return datetime.fromtimestamp(value, tz=UTC)
|
||
|
||
|
||
def _derive_session(
|
||
*,
|
||
errors: Mapping[str, str],
|
||
capabilities_ok: bool,
|
||
) -> dict[str, Any]:
|
||
if capabilities_ok:
|
||
return {
|
||
"status": SESSION_VALID,
|
||
"message": "活动接口可用",
|
||
"checked_at": _now().isoformat(),
|
||
"detail": {},
|
||
}
|
||
text = ";".join(errors.values())
|
||
if any(marker in text for marker in ("登录", "Cookie", "重定向")):
|
||
status = SESSION_INVALID
|
||
elif errors:
|
||
status = SESSION_ERROR
|
||
else:
|
||
status = SESSION_UNKNOWN
|
||
return {
|
||
"status": status,
|
||
"message": _text(text or "没有可用查询结果"),
|
||
"checked_at": _now().isoformat(),
|
||
"detail": {},
|
||
}
|
||
|
||
|
||
def _identity_result(
|
||
account: Account,
|
||
cookie: str,
|
||
*,
|
||
elite: Mapping[str, Any],
|
||
session: Mapping[str, Any],
|
||
) -> dict[str, str]:
|
||
profile = profile_from_cookie(cookie)
|
||
user_info = (
|
||
elite.get("user_info") if isinstance(elite.get("user_info"), dict) else {}
|
||
)
|
||
session_detail = (
|
||
session.get("detail") if isinstance(session.get("detail"), dict) else {}
|
||
)
|
||
candidates = [
|
||
("elite", str(user_info.get("nickname") or "").strip()),
|
||
("session", str(session_detail.get("nickname") or "").strip()),
|
||
("cookie", str(profile.get("nickname") or "").strip()),
|
||
("account", str(account.nickname or "").strip()),
|
||
]
|
||
nickname, source = next(
|
||
((value, item_source) for item_source, value in candidates if value),
|
||
("", ""),
|
||
)
|
||
return {
|
||
"uid": str(account.uid or profile.get("uid") or "").strip(),
|
||
"username": str(account.username or "").strip(),
|
||
"nickname": nickname,
|
||
"nickname_source": source,
|
||
}
|
||
|
||
|
||
def _cache_key(account: Account, config: Mapping[str, Any], mode: str) -> str:
|
||
raw = "|".join(
|
||
[
|
||
str(account.id or ""),
|
||
hashlib.sha256(str(account.cookie or "").encode()).hexdigest(),
|
||
mode,
|
||
*(str(config.get(key) or "") for key in CONFIG_KEYS),
|
||
]
|
||
)
|
||
return hashlib.sha256(raw.encode()).hexdigest()
|
||
|
||
|
||
def probe_account(
|
||
account: Account,
|
||
config: Any,
|
||
*,
|
||
client: DouyuActivityClient | None = None,
|
||
session_checker: Callable[[str], dict[str, Any]] | None | object = (
|
||
_DEFAULT_SESSION_CHECKER
|
||
),
|
||
with_elite: bool = True,
|
||
with_eligibility: bool = False,
|
||
with_limited_goods: bool = False,
|
||
with_gold: bool = False,
|
||
with_goods: bool = False,
|
||
with_elite_role: bool = True,
|
||
include_esports: bool = False,
|
||
include_peace: bool = False,
|
||
use_cache: bool = False,
|
||
logger_callback: Callable[[str], None] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""读取一个斗鱼账号的身份、会话与按需能力。"""
|
||
config_info = config_mapping(config)
|
||
cache_mode = "|".join(
|
||
[
|
||
f"elite={int(with_elite)}",
|
||
f"elig={int(with_eligibility)}",
|
||
f"limited={int(with_limited_goods)}",
|
||
f"gold={int(with_gold)}",
|
||
f"goods={int(with_goods)}",
|
||
f"role={int(with_elite_role)}",
|
||
f"esports={int(include_esports)}",
|
||
f"peace={int(include_peace)}",
|
||
]
|
||
)
|
||
cache_key = _cache_key(account, config_info, cache_mode)
|
||
if use_cache:
|
||
cached = _probe_cache.get(cache_key)
|
||
if cached and time.time() - cached[0] <= _CACHE_TTL_SECONDS:
|
||
result = copy.deepcopy(cached[1])
|
||
result["probe_id"] = uuid4().hex
|
||
return result
|
||
|
||
cookie = str(account.cookie or "").strip()
|
||
checked_at = _now()
|
||
errors: dict[str, str] = {}
|
||
active_client = client or activity_client(
|
||
cookie,
|
||
logger_callback=logger_callback
|
||
or (
|
||
lambda message: logger.debug(
|
||
"[douyu-probe] account={} {}", account.id, message
|
||
)
|
||
),
|
||
)
|
||
if session_checker is _DEFAULT_SESSION_CHECKER:
|
||
session_checker = None if client is not None else check_douyu_cookie
|
||
session = (
|
||
probe_session(cookie, checker=session_checker)
|
||
if callable(session_checker)
|
||
else {}
|
||
)
|
||
if str(session.get("status") or "") in {SESSION_INVALID, SESSION_UNVERIFIED}:
|
||
identity = _identity_result(
|
||
account,
|
||
cookie,
|
||
elite={},
|
||
session=session,
|
||
)
|
||
probe = {
|
||
"probe_id": uuid4().hex,
|
||
"checked_at": checked_at.isoformat(),
|
||
"identity": identity,
|
||
"session": session,
|
||
"elite": {
|
||
"status": CAPABILITY_UNKNOWN,
|
||
"raw": {},
|
||
"manual_type": None,
|
||
"manual_score": None,
|
||
"expire_time": None,
|
||
"opened": account.elite_opened,
|
||
"error": "",
|
||
},
|
||
"eligibility": {
|
||
"points": account.points,
|
||
"points_response": {},
|
||
"points_expire_at": (
|
||
account.points_expire_at.isoformat()
|
||
if account.points_expire_at
|
||
else None
|
||
),
|
||
"limited_goods": [],
|
||
"limited_ids": [],
|
||
"error": "",
|
||
},
|
||
"roles": (
|
||
{
|
||
"elite": _role_result(
|
||
status=ROLE_UNKNOWN,
|
||
bind_info=None,
|
||
candidates=[],
|
||
aliases=elite_query_aliases(config_info),
|
||
errors=[],
|
||
)
|
||
}
|
||
if with_elite_role
|
||
else {}
|
||
),
|
||
"gold": {"status": CAPABILITY_UNKNOWN, "balance": account.gold_balance},
|
||
"goods": {
|
||
"status": CAPABILITY_UNKNOWN,
|
||
"items": [],
|
||
"serialized": [],
|
||
"count": 0,
|
||
},
|
||
"errors": {},
|
||
}
|
||
if use_cache:
|
||
_probe_cache[cache_key] = (time.time(), probe)
|
||
return probe
|
||
|
||
ctn = ""
|
||
if with_eligibility:
|
||
try:
|
||
ctn = query_csrf(active_client)
|
||
except Exception as exc: # noqa: BLE001
|
||
errors["points"] = f"{type(exc).__name__}: {_text(exc)}"
|
||
|
||
elite: dict[str, Any] = {}
|
||
manual_id = str(config_info.get("manual_id") or "").strip()
|
||
if manual_id and with_elite:
|
||
try:
|
||
elite = query_elite_user_info(
|
||
active_client,
|
||
manual_id=manual_id,
|
||
rid=str(config_info.get("rid") or ""),
|
||
)
|
||
except Exception as exc: # noqa: BLE001 - 单项能力边界
|
||
errors["elite"] = f"{type(exc).__name__}: {_text(exc)}"
|
||
|
||
roles: dict[str, dict[str, Any]] = {}
|
||
if with_elite_role:
|
||
roles["elite"] = resolve_elite_role(active_client, config_info)
|
||
if include_esports:
|
||
roles["esports"] = resolve_esports_role(active_client, config_info)
|
||
if include_peace:
|
||
roles["peace"] = resolve_peace_role(active_client, config_info)
|
||
|
||
points: int | None = None
|
||
points_response: dict[str, Any] = {}
|
||
limited_goods: list[dict[str, Any]] = []
|
||
if with_eligibility:
|
||
uid = str(account.uid or "").strip()
|
||
if ctn:
|
||
try:
|
||
points_result = query_points(active_client, uid=uid, ctn=ctn)
|
||
points = _to_int(points_result.get("points"))
|
||
points_response = points_result
|
||
except Exception as exc: # noqa: BLE001
|
||
errors["points"] = f"{type(exc).__name__}: {_text(exc)}"
|
||
if with_eligibility or with_limited_goods:
|
||
try:
|
||
limited_result = query_limited_goods_result(
|
||
active_client,
|
||
manual_id=manual_id,
|
||
rid=str(config_info.get("rid") or ""),
|
||
)
|
||
limited_goods = [
|
||
dict(item)
|
||
for item in limited_result.get("limited_goods") or []
|
||
if isinstance(item, dict)
|
||
]
|
||
except Exception as exc: # noqa: BLE001
|
||
errors["limited_goods"] = f"{type(exc).__name__}: {_text(exc)}"
|
||
|
||
gold: dict[str, Any] = {"status": CAPABILITY_UNKNOWN, "balance": None}
|
||
if with_gold:
|
||
try:
|
||
gold_response = query_gold_account(active_client)
|
||
gold = {
|
||
"status": CAPABILITY_OK,
|
||
"balance": _to_int(gold_response.get("gold")),
|
||
"raw": gold_response,
|
||
}
|
||
except Exception as exc: # noqa: BLE001
|
||
errors["gold"] = f"{type(exc).__name__}: {_text(exc)}"
|
||
gold = {
|
||
"status": CAPABILITY_ERROR,
|
||
"balance": None,
|
||
"error": errors["gold"],
|
||
}
|
||
|
||
goods: dict[str, Any] = {"status": CAPABILITY_UNKNOWN, "items": [], "count": 0}
|
||
if with_goods:
|
||
try:
|
||
raw_goods = query_activity_goods(
|
||
active_client,
|
||
manual_id=manual_id,
|
||
rid=str(config_info.get("rid") or ""),
|
||
)
|
||
goods = {
|
||
"status": CAPABILITY_OK,
|
||
"items": raw_goods,
|
||
"serialized": [serialize_goods(item) for item in raw_goods],
|
||
"count": len(raw_goods),
|
||
}
|
||
except Exception as exc: # noqa: BLE001
|
||
errors["goods"] = f"{type(exc).__name__}: {_text(exc)}"
|
||
goods = {
|
||
"status": CAPABILITY_ERROR,
|
||
"items": [],
|
||
"serialized": [],
|
||
"count": 0,
|
||
"error": errors["goods"],
|
||
}
|
||
|
||
if not session:
|
||
capabilities_ok = bool(
|
||
elite
|
||
or (roles.get("elite") or {}).get("status") in {ROLE_BOUND, ROLE_PENDING}
|
||
or gold.get("status") == CAPABILITY_OK
|
||
or goods.get("status") == CAPABILITY_OK
|
||
)
|
||
session = _derive_session(errors=errors, capabilities_ok=capabilities_ok)
|
||
|
||
manual_type = _to_int(elite.get("manual_type"))
|
||
manual_score = _to_int(elite.get("manual_score"))
|
||
expire_time = normalize_elite_expire_time(elite.get("expire_time"))
|
||
elite_opened = elite_is_currently_open(manual_type, expire_time, now=checked_at)
|
||
if points is None:
|
||
points = manual_score
|
||
identity = _identity_result(
|
||
account,
|
||
cookie,
|
||
elite=elite,
|
||
session=session,
|
||
)
|
||
points_expire_at = _points_expire_at(points_response, checked_at=checked_at)
|
||
probe = {
|
||
"probe_id": uuid4().hex,
|
||
"checked_at": checked_at.isoformat(),
|
||
"identity": identity,
|
||
"session": session,
|
||
"elite": {
|
||
"status": CAPABILITY_OK
|
||
if elite
|
||
else CAPABILITY_ERROR
|
||
if "elite" in errors
|
||
else CAPABILITY_UNKNOWN,
|
||
"raw": elite,
|
||
"manual_type": manual_type,
|
||
"manual_score": manual_score,
|
||
"expire_time": expire_time,
|
||
"opened": elite_opened,
|
||
"error": errors.get("elite", ""),
|
||
},
|
||
"eligibility": {
|
||
"points": points,
|
||
"points_response": points_response,
|
||
"points_expire_at": (
|
||
points_expire_at.isoformat() if points_expire_at else None
|
||
),
|
||
"limited_goods": limited_goods,
|
||
"limited_ids": sorted(
|
||
{
|
||
str(item.get("commodityId") or item.get("commodity_id") or "")
|
||
for item in limited_goods
|
||
if str(
|
||
item.get("commodityId") or item.get("commodity_id") or ""
|
||
).strip()
|
||
}
|
||
),
|
||
"error": errors.get("points", ""),
|
||
},
|
||
"roles": roles,
|
||
"gold": gold,
|
||
"goods": goods,
|
||
"errors": errors,
|
||
}
|
||
if use_cache:
|
||
_probe_cache[cache_key] = (time.time(), probe)
|
||
logger.info(
|
||
"[douyu-probe] account={} session={} role={} elite={} gold={} goods={} errors={}",
|
||
account.id,
|
||
session.get("status"),
|
||
(roles.get("elite") or {}).get("status"),
|
||
probe["elite"].get("status"),
|
||
gold.get("status"),
|
||
goods.get("status"),
|
||
sorted(errors),
|
||
)
|
||
return probe
|
||
|
||
|
||
def _apply_role_result(
|
||
account: Account,
|
||
scope: str,
|
||
role: Mapping[str, Any],
|
||
) -> None:
|
||
status = str(role.get("status") or ROLE_UNKNOWN)
|
||
if status in {ROLE_BOUND, ROLE_PENDING, ROLE_UNBOUND}:
|
||
set_bind_status(account, scope, status)
|
||
if status in {ROLE_ERROR, ROLE_UNKNOWN}:
|
||
return
|
||
role_name = str(role.get("role_name") or "")[:128]
|
||
channel = str(role.get("game_channel") or "").replace(" / ", " · ")[:128]
|
||
if scope == SCOPE_ELITE:
|
||
account.game_name = role_name
|
||
account.game_channel = channel
|
||
account.change_role_wait_time = _to_int(role.get("change_role_wait_time"))
|
||
account.role_change_available_at = role_change_available_at(
|
||
role.get("bind_info")
|
||
)
|
||
elif scope == SCOPE_ESPORTS:
|
||
account.esports_game_name = role_name
|
||
account.esports_game_channel = channel
|
||
account.esports_change_role_wait_time = _to_int(
|
||
role.get("change_role_wait_time")
|
||
)
|
||
account.esports_can_change_time = _to_int(role.get("can_change_time"))
|
||
elif scope == SCOPE_PEACE:
|
||
account.xpd_game_name = role_name
|
||
bind_info = (
|
||
role.get("bind_info") if isinstance(role.get("bind_info"), dict) else {}
|
||
)
|
||
account.xpd_openid = str(bind_info.get("openid") or account.xpd_openid or "")[
|
||
:128
|
||
]
|
||
account.xpd_role_id = str(
|
||
bind_info.get("role_id") or account.xpd_role_id or ""
|
||
)[:64]
|
||
|
||
|
||
def persist_probe_result(
|
||
db: Session,
|
||
account: Account,
|
||
probe: Mapping[str, Any],
|
||
*,
|
||
current: User | None = None,
|
||
source: str,
|
||
record_event: bool = True,
|
||
commit: bool = False,
|
||
) -> None:
|
||
"""把一次探针结果写回账号和生命周期,是账号能力的唯一落库入口。"""
|
||
now = _now()
|
||
identity = probe.get("identity") or {}
|
||
if identity.get("uid"):
|
||
account.uid = str(identity["uid"])[:32]
|
||
if identity.get("nickname"):
|
||
account.nickname = str(identity["nickname"])[:128]
|
||
|
||
session = probe.get("session") or {}
|
||
session_status = str(session.get("status") or "")
|
||
if session_status in {SESSION_VALID, SESSION_INVALID, SESSION_ERROR}:
|
||
detail = (
|
||
session.get("detail") if isinstance(session.get("detail"), dict) else {}
|
||
)
|
||
on_ck_verdict(
|
||
db,
|
||
account,
|
||
session_status,
|
||
detail={
|
||
**detail,
|
||
"message": session.get("message") or detail.get("message", ""),
|
||
},
|
||
occurred_at=now,
|
||
actor_type="user" if current else "system",
|
||
actor_id=int(current.id) if current else None,
|
||
)
|
||
|
||
elite = probe.get("elite") or {}
|
||
if elite.get("status") == CAPABILITY_OK:
|
||
account.elite_opened = bool(elite.get("opened"))
|
||
account.elite_expire_time = _to_int(elite.get("expire_time"))
|
||
if _to_int(elite.get("manual_score")) is not None:
|
||
account.points = _to_int(elite.get("manual_score"))
|
||
|
||
eligibility = probe.get("eligibility") or {}
|
||
if _to_int(eligibility.get("points")) is not None:
|
||
account.points = _to_int(eligibility.get("points"))
|
||
points_expire_at = eligibility.get("points_expire_at")
|
||
if points_expire_at:
|
||
try:
|
||
account.points_expire_at = datetime.fromisoformat(str(points_expire_at))
|
||
except ValueError:
|
||
pass
|
||
|
||
roles = probe.get("roles") or {}
|
||
for scope in (SCOPE_ELITE, SCOPE_ESPORTS, SCOPE_PEACE):
|
||
role = roles.get(scope)
|
||
if isinstance(role, dict):
|
||
_apply_role_result(account, scope, role)
|
||
|
||
gold = probe.get("gold") or {}
|
||
if gold.get("status") == CAPABILITY_OK and _to_int(gold.get("balance")) is not None:
|
||
account.gold_balance = _to_int(gold.get("balance"))
|
||
|
||
account.updated_at = now
|
||
if record_event and account.id is not None:
|
||
emit(
|
||
db,
|
||
account_id=int(account.id),
|
||
event_type="account_probe",
|
||
title=f"账号查询:{source}",
|
||
category=CATEGORY_OPS,
|
||
occurred_at=now,
|
||
detail={
|
||
"probe_id": probe.get("probe_id"),
|
||
"source": source,
|
||
"session": session_status,
|
||
"role": (roles.get(SCOPE_ELITE) or {}).get("status"),
|
||
"nickname_source": identity.get("nickname_source"),
|
||
"errors": sorted((probe.get("errors") or {}).keys()),
|
||
},
|
||
source=source,
|
||
subject_type="account",
|
||
subject_key=str(account.id),
|
||
actor_type="user" if current else "system",
|
||
actor_id=int(current.id) if current else None,
|
||
source_ref=f"douyu_probe:{probe.get('probe_id')}",
|
||
)
|
||
db.flush()
|
||
if commit:
|
||
db.commit()
|
||
|
||
|
||
def clear_probe_cache() -> None:
|
||
"""测试或手工刷新时清空短期缓存。"""
|
||
_probe_cache.clear()
|
||
|
||
|
||
__all__ = [
|
||
"CAPABILITY_ERROR",
|
||
"CAPABILITY_OK",
|
||
"CAPABILITY_UNKNOWN",
|
||
"ROLE_BOUND",
|
||
"ROLE_ERROR",
|
||
"ROLE_PENDING",
|
||
"ROLE_UNBOUND",
|
||
"ROLE_UNKNOWN",
|
||
"SESSION_ERROR",
|
||
"SESSION_INVALID",
|
||
"SESSION_UNKNOWN",
|
||
"SESSION_UNVERIFIED",
|
||
"SESSION_VALID",
|
||
"activity_client",
|
||
"clear_probe_cache",
|
||
"config_mapping",
|
||
"elite_action_aliases",
|
||
"elite_query_aliases",
|
||
"persist_probe_result",
|
||
"probe_account",
|
||
"probe_session",
|
||
"profile_from_cookie",
|
||
"query_elite_bind_candidates",
|
||
"resolve_elite_role",
|
||
"resolve_esports_role",
|
||
"resolve_peace_role",
|
||
"update_identity_from_cookie",
|
||
]
|