feat(douyu): unify account probes and lifecycle writes

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.
This commit is contained in:
yml
2026-11-20 01:55:25 +08:00
parent e9937419cb
commit 1a49bcd481
24 changed files with 2162 additions and 639 deletions
+58 -181
View File
@@ -17,24 +17,9 @@ from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient
from ..models import Account
from .account_binding import (
SCOPE_ELITE,
binding_snapshot,
is_role_change_cooling,
role_change_available_at,
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,
)
from .douyu_elite_status import (
elite_is_currently_open,
normalize_elite_expire_time,
)
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)
@@ -107,192 +92,84 @@ def refresh_douyu_account_state(
) -> 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(
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,
ck_verdict,
detail=ck_result,
occurred_at=now,
probe,
source="platform.live_check",
record_event=False,
commit=False,
)
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_expire_time = normalize_elite_expire_time(
eligibility.elite_user_info.get("expire_time")
)
elite_opened = elite_is_currently_open(
eligibility.elite_user_info.get("manual_type"),
elite_expire_time,
now=now,
)
account.elite_opened = elite_opened
account.elite_expire_time = elite_expire_time
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,
"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
account.high_value_checked_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_name,
account_name=account.nickname
or (probe.get("identity") or {}).get("nickname")
or account.username
or f"#{account.id}",
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,
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 _apply_bind_state(
account: Account,
bind_info: dict[str, Any],
*,
checked_at: datetime,
) -> datetime | None:
snapshot = binding_snapshot(bind_info)
derived = snapshot["bind_status"]
if derived is not None:
set_bind_status(account, SCOPE_ELITE, derived)
role_name = snapshot["role_name"]
if role_name:
account.game_name = role_name[:128]
channel = snapshot["game_channel"]
if channel:
account.game_channel = channel.replace(" / ", " · ")[:128]
account.change_role_wait_time = snapshot["change_role_wait_time"]
available_at = role_change_available_at(bind_info, checked_at=checked_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()