Centralize Douyu client creation, CK session probing, identity refresh, role alias resolution, capability persistence, cache and batch throttling across collaboration, fulfillment, tasks and cookie management. Add the account-name copy action in the collaboration table.
189 lines
6.1 KiB
Python
189 lines
6.1 KiB
Python
"""斗鱼账号实时状态刷新。
|
||
|
||
选号不能依赖账号上的缓存字段。只要账号持有 CK,本模块就实时检测 CK、
|
||
查询精英宝典、积分、限兑商品和绑定冷却,并把结果写回账号生命周期与账号
|
||
快照。业务调用方只消费返回的实时结论。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from collections.abc import Callable
|
||
from dataclasses import dataclass
|
||
from datetime import UTC, datetime
|
||
from typing import Any
|
||
|
||
from sqlalchemy.orm import Session
|
||
|
||
from core.douyu import DouyuActivityClient
|
||
|
||
from ..models import Account
|
||
from .account_binding import is_role_change_cooling
|
||
from .cookie_check_service import check_douyu_cookie
|
||
from .douyu_account_probe import config_mapping, persist_probe_result, probe_account
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class DouyuLiveAccountState:
|
||
account_id: int
|
||
account_name: str
|
||
checked_at: datetime
|
||
ck_verdict: str
|
||
ck_message: str
|
||
elite_opened: bool | None
|
||
points: int | None
|
||
limited_ids: frozenset[str]
|
||
role_change_available_at: datetime | None
|
||
error: str = ""
|
||
role_change_blocked: bool = False
|
||
|
||
def blocking_reasons(
|
||
self,
|
||
*,
|
||
commodity_id: str,
|
||
) -> list[str]:
|
||
reasons: list[str] = []
|
||
if self.ck_verdict != "valid":
|
||
reasons.append(f"CK {self.ck_verdict}: {self.ck_message}")
|
||
if self.error:
|
||
reasons.append(self.error)
|
||
if commodity_id in self.limited_ids:
|
||
reasons.append("该商品已达限兑上限")
|
||
if self.role_change_blocked:
|
||
available_text = (
|
||
self.role_change_available_at.isoformat()
|
||
if self.role_change_available_at
|
||
else "未知时间"
|
||
)
|
||
reasons.append(f"角色换绑冷却至 {available_text}")
|
||
return reasons
|
||
|
||
def soft_requirement_reasons(self, *, required_points: int) -> list[str]:
|
||
"""积分/开通不淘汰账号,只决定后续需要充值还是开通。"""
|
||
reasons: list[str] = []
|
||
if self.elite_opened is not True:
|
||
reasons.append("精英宝典未开通")
|
||
if self.points is None or self.points < required_points:
|
||
reasons.append(f"积分不足({self.points or 0}/{required_points})")
|
||
return reasons
|
||
|
||
def readiness_rank(self, *, required_points: int) -> int:
|
||
"""数值越小越接近直接兑换,用于软条件排序。"""
|
||
opened = self.elite_opened is True
|
||
enough = self.points is not None and self.points >= required_points
|
||
if opened and enough:
|
||
return 0
|
||
if opened:
|
||
return 1
|
||
if enough:
|
||
return 2
|
||
return 3
|
||
|
||
|
||
def refresh_douyu_account_state(
|
||
db: Session,
|
||
account: Account,
|
||
*,
|
||
manual_id: str,
|
||
rid: str,
|
||
act_alias: str,
|
||
client: DouyuActivityClient | None = None,
|
||
cookie_checker: Callable[[str], dict[str, Any]] = check_douyu_cookie,
|
||
commit: bool = True,
|
||
) -> DouyuLiveAccountState:
|
||
"""实时刷新单个账号,并把所有可落库状态写回账号。"""
|
||
now = datetime.now(UTC)
|
||
config_info = config_mapping(
|
||
{
|
||
"manual_id": manual_id,
|
||
"rid": rid,
|
||
"bind_act_alias": act_alias,
|
||
"confirm_act_alias": act_alias,
|
||
}
|
||
)
|
||
probe = probe_account(
|
||
account,
|
||
config_info,
|
||
client=client,
|
||
session_checker=cookie_checker,
|
||
with_eligibility=True,
|
||
)
|
||
session = probe.get("session") or {}
|
||
role = (probe.get("roles") or {}).get("elite") or {}
|
||
elite = probe.get("elite") or {}
|
||
eligibility = probe.get("eligibility") or {}
|
||
session_status = str(session.get("status") or "")
|
||
bind_info = role.get("bind_info") if isinstance(role.get("bind_info"), dict) else {}
|
||
errors = list((probe.get("errors") or {}).values())
|
||
errors.extend(role.get("errors") or [])
|
||
if session_status != "valid":
|
||
errors.append(
|
||
f"CK 检测未通过: {session.get('message') or '状态未知'},未继续查询活动状态"
|
||
)
|
||
|
||
persist_probe_result(
|
||
db,
|
||
account,
|
||
probe,
|
||
source="platform.live_check",
|
||
record_event=False,
|
||
commit=False,
|
||
)
|
||
account.overview_snapshot = _json_safe(
|
||
{
|
||
"queried_at": now.isoformat(),
|
||
"ck": session.get("detail") or {"message": session.get("message")},
|
||
"elite": elite.get("raw") or {},
|
||
"points": eligibility.get("points_response") or {},
|
||
"limited_goods": eligibility.get("limited_goods") or [],
|
||
"bind": bind_info,
|
||
"errors": errors,
|
||
"probe_id": probe.get("probe_id"),
|
||
}
|
||
)
|
||
account.overview_queried_at = now
|
||
if session_status == "valid":
|
||
account.high_value_checked_at = now
|
||
account.updated_at = now
|
||
if commit:
|
||
db.commit()
|
||
|
||
limited_ids = frozenset(
|
||
str(item) for item in eligibility.get("limited_ids") or [] if str(item)
|
||
)
|
||
return DouyuLiveAccountState(
|
||
account_id=int(account.id),
|
||
account_name=account.nickname
|
||
or (probe.get("identity") or {}).get("nickname")
|
||
or account.username
|
||
or f"#{account.id}",
|
||
checked_at=now,
|
||
ck_verdict=session_status
|
||
if session_status in {"valid", "invalid", "error"}
|
||
else "error",
|
||
ck_message=str(session.get("message") or ""),
|
||
elite_opened=account.elite_opened,
|
||
points=account.points,
|
||
limited_ids=limited_ids,
|
||
role_change_available_at=account.role_change_available_at,
|
||
error=";".join(errors),
|
||
role_change_blocked=is_role_change_cooling(bind_info),
|
||
)
|
||
|
||
|
||
def _json_safe(value: Any) -> Any:
|
||
if isinstance(value, datetime):
|
||
return value.isoformat()
|
||
if isinstance(value, dict):
|
||
return {str(key): _json_safe(item) for key, item in value.items()}
|
||
if isinstance(value, (list, tuple, set, frozenset)):
|
||
return [_json_safe(item) for item in value]
|
||
if isinstance(value, (str, int, float, bool)) or value is None:
|
||
return value
|
||
return str(value)
|
||
|
||
|
||
__all__ = [
|
||
"DouyuLiveAccountState",
|
||
"refresh_douyu_account_state",
|
||
]
|