feat(fulfillment): 实时刷新斗鱼账号并支持租约时长设置
This commit is contained in:
@@ -0,0 +1,310 @@
|
||||
"""斗鱼账号实时状态刷新。
|
||||
|
||||
选号不能依赖账号上的缓存字段。只要账号持有 CK,本模块就实时检测 CK、
|
||||
查询精英宝典、积分、限兑商品和绑定冷却,并把结果写回账号生命周期与账号
|
||||
快照。业务调用方只消费返回的实时结论。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.douyu import DouyuActivityClient
|
||||
|
||||
from ..models import Account
|
||||
from .account_binding import (
|
||||
SCOPE_ELITE,
|
||||
derive_from_bind_info,
|
||||
is_role_change_cooling,
|
||||
set_bind_status,
|
||||
)
|
||||
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_bind_info,
|
||||
query_exchange_eligibility,
|
||||
)
|
||||
|
||||
|
||||
@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)
|
||||
cookie = str(account.cookie or "").strip()
|
||||
account_name = account.nickname or account.username or f"#{account.id}"
|
||||
ck_result = cookie_checker(cookie)
|
||||
ck_verdict = classify_douyu_cookie_result(ck_result)
|
||||
ck_message = str(ck_result.get("message") or "")
|
||||
on_ck_verdict(
|
||||
db,
|
||||
account,
|
||||
ck_verdict,
|
||||
detail=ck_result,
|
||||
occurred_at=now,
|
||||
)
|
||||
|
||||
if ck_verdict != "valid":
|
||||
snapshot = {
|
||||
"queried_at": now.isoformat(),
|
||||
"ck": ck_result,
|
||||
"errors": ["CK 检测未通过,未继续查询活动状态"],
|
||||
}
|
||||
account.overview_snapshot = _json_safe(snapshot)
|
||||
account.updated_at = now
|
||||
if commit:
|
||||
db.commit()
|
||||
return DouyuLiveAccountState(
|
||||
account_id=int(account.id),
|
||||
account_name=account_name,
|
||||
checked_at=now,
|
||||
ck_verdict=ck_verdict,
|
||||
ck_message=ck_message,
|
||||
elite_opened=account.elite_opened,
|
||||
points=account.points,
|
||||
limited_ids=frozenset(),
|
||||
role_change_available_at=account.role_change_available_at,
|
||||
)
|
||||
|
||||
active_client = client or activity_client(cookie)
|
||||
try:
|
||||
eligibility = query_exchange_eligibility(
|
||||
active_client,
|
||||
cookie=cookie,
|
||||
manual_id=manual_id,
|
||||
rid=rid,
|
||||
uid=str(account.uid or ""),
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 外部接口边界需要保留单项诊断
|
||||
error = f"{type(exc).__name__}: {exc}"[:240]
|
||||
snapshot = {
|
||||
"queried_at": now.isoformat(),
|
||||
"ck": ck_result,
|
||||
"errors": [error],
|
||||
}
|
||||
account.overview_snapshot = _json_safe(snapshot)
|
||||
account.overview_queried_at = now
|
||||
account.updated_at = now
|
||||
if commit:
|
||||
db.commit()
|
||||
return DouyuLiveAccountState(
|
||||
account_id=int(account.id),
|
||||
account_name=account_name,
|
||||
checked_at=now,
|
||||
ck_verdict=ck_verdict,
|
||||
ck_message=ck_message,
|
||||
elite_opened=account.elite_opened,
|
||||
points=account.points,
|
||||
limited_ids=frozenset(),
|
||||
role_change_available_at=account.role_change_available_at,
|
||||
error=error,
|
||||
)
|
||||
|
||||
errors: list[str] = []
|
||||
bind_info: dict[str, Any] = {}
|
||||
try:
|
||||
bind_info = query_bind_info(
|
||||
active_client,
|
||||
act_alias=act_alias,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 绑定查询失败不应丢弃资产查询结果
|
||||
errors.append(f"绑定状态查询失败: {type(exc).__name__}: {exc}"[:240])
|
||||
|
||||
elite_opened = bool(eligibility.elite_user_info.get("manual_type"))
|
||||
elite_expire_time = _to_int(eligibility.elite_user_info.get("expire_time"))
|
||||
account.elite_opened = elite_opened
|
||||
account.elite_expire_time = elite_expire_time or None
|
||||
account.points = eligibility.points
|
||||
account.points_expire_at = _points_expire_at(
|
||||
eligibility.points_response,
|
||||
checked_at=now,
|
||||
)
|
||||
role_change_available_at = account.role_change_available_at
|
||||
if bind_info:
|
||||
role_change_available_at = _apply_bind_state(
|
||||
account,
|
||||
bind_info,
|
||||
checked_at=now,
|
||||
)
|
||||
account.overview_snapshot = _json_safe(
|
||||
{
|
||||
"queried_at": now.isoformat(),
|
||||
"ck": ck_result,
|
||||
"elite": eligibility.elite_user_info,
|
||||
"points": eligibility.points_response,
|
||||
"limited_goods": eligibility.limited_goods,
|
||||
"bind": bind_info,
|
||||
"errors": errors,
|
||||
}
|
||||
)
|
||||
account.overview_queried_at = now
|
||||
account.high_value_checked_at = now
|
||||
account.updated_at = now
|
||||
if commit:
|
||||
db.commit()
|
||||
|
||||
return DouyuLiveAccountState(
|
||||
account_id=int(account.id),
|
||||
account_name=account_name,
|
||||
checked_at=now,
|
||||
ck_verdict=ck_verdict,
|
||||
ck_message=ck_message,
|
||||
elite_opened=elite_opened,
|
||||
points=eligibility.points,
|
||||
limited_ids=eligibility.limited_ids,
|
||||
role_change_available_at=role_change_available_at,
|
||||
error=";".join(errors),
|
||||
role_change_blocked=is_role_change_cooling(bind_info),
|
||||
)
|
||||
|
||||
|
||||
def _apply_bind_state(
|
||||
account: Account,
|
||||
bind_info: dict[str, Any],
|
||||
*,
|
||||
checked_at: datetime,
|
||||
) -> datetime | None:
|
||||
derived = derive_from_bind_info(bind_info)
|
||||
if derived is not None:
|
||||
set_bind_status(account, SCOPE_ELITE, derived)
|
||||
|
||||
role_name = str(bind_info.get("role_name") or bind_info.get("role") or "").strip()
|
||||
if role_name:
|
||||
account.game_name = role_name[:128]
|
||||
area_name = str(bind_info.get("area_name") or "").strip()
|
||||
plat_name = str(bind_info.get("plat_name") or "").strip()
|
||||
channel = " · ".join(item for item in (area_name, plat_name) if item)
|
||||
if channel:
|
||||
account.game_channel = channel[:128]
|
||||
|
||||
wait_seconds = _to_int(bind_info.get("change_role_wait_time"))
|
||||
can_change_time = _to_int(bind_info.get("can_change_time"))
|
||||
account.change_role_wait_time = wait_seconds
|
||||
if not is_role_change_cooling(bind_info):
|
||||
available_at = None
|
||||
elif can_change_time is not None and can_change_time > 0:
|
||||
available_at = datetime.fromtimestamp(can_change_time, tz=UTC)
|
||||
elif wait_seconds is not None and wait_seconds > 0:
|
||||
available_at = checked_at + timedelta(seconds=wait_seconds)
|
||||
else:
|
||||
available_at = account.role_change_available_at
|
||||
account.role_change_available_at = available_at
|
||||
return available_at
|
||||
|
||||
|
||||
def _points_expire_at(
|
||||
points_response: dict[str, Any],
|
||||
*,
|
||||
checked_at: datetime,
|
||||
) -> datetime | None:
|
||||
raw = (
|
||||
points_response.get("willExpireTime")
|
||||
or points_response.get("will_expire_time")
|
||||
or points_response.get("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 _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 _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",
|
||||
]
|
||||
Reference in New Issue
Block a user