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
@@ -17,7 +17,7 @@ from sqlalchemy import and_, func, or_
from sqlalchemy.orm import Session
from ....models import Account, AutomationJob
from ...account_lifecycle import MANUAL_STATES, on_ck_verdict
from ...account_lifecycle import MANUAL_STATES
from ...account_value import (
HIGH_VALUE_TIER_MAX,
high_value_recheck_seconds,
@@ -27,7 +27,11 @@ from ...cookie_check_service import (
check_douyu_cookie,
)
from ...cookie_check_service import (
classify_douyu_cookie_result as classify_result,
classify_douyu_cookie_result as classify_result, # noqa: F401 - 兼容诊断入口
)
from ...douyu_account_probe import (
persist_probe_result,
probe_session,
)
from ...douyu_service import cookie_holding_filter, cookie_operable_filter
@@ -109,15 +113,16 @@ def count_remaining(db: Session, job: AutomationJob, now: datetime) -> int:
def _detect(account: Account) -> dict[str, Any]:
try:
return check_douyu_cookie(account.cookie or "")
return probe_session(
account.cookie or "",
checker=check_douyu_cookie,
)
except Exception as exc: # noqa: BLE001 单个账号失败不影响整轮
return {
"valid": False,
"status": "error",
"message": f"检测异常: {exc}",
"fish_ball": None,
"nickname": None,
"level": None,
"checked_at": datetime.now(UTC),
"checked_at": datetime.now(UTC).isoformat(),
"detail": {},
}
@@ -153,16 +158,39 @@ def run_ck_health(db: Session, job: AutomationJob) -> dict[str, Any]:
result = results.get(account.id)
if result is None:
continue
verdict = classify_result(result)
verdict = str(result.get("status") or "error")
if verdict == "valid":
valid += 1
elif verdict == "invalid":
invalid += 1
else:
errors += 1
# 结论落定 = 写 ck_check_* + 由好变坏时记事件 + 重算生命周期状态。
# 三件事的**顺序与口径**收在 `on_ck_verdict` 里,四个检测入口共用。
on_ck_verdict(db, account, verdict, detail=result, occurred_at=now)
# 自动巡检不额外刷 account_probe 事件;统一落库仍会处理 CK 状态变化
# 和生命周期事件,避免每 6 小时给所有账号写一条重复查询事件。
detail = result.get("detail") if isinstance(result.get("detail"), dict) else {}
persist_probe_result(
db,
account,
{
"probe_id": f"ck-health:{now.timestamp()}:{account.id}",
"identity": {
"uid": account.uid,
"username": account.username,
"nickname": detail.get("nickname") or "",
"nickname_source": "session",
},
"session": result,
"elite": {},
"eligibility": {},
"roles": {},
"gold": {},
"goods": {},
"errors": {},
},
source="automation.ck_health",
record_event=False,
commit=False,
)
if index % FLUSH_EVERY == 0:
db.commit()
@@ -20,6 +20,8 @@ AUTH_FAILURE_MARKERS = (
"重新登陆",
"重新登录",
"账户登陆",
"expired",
"ck 失效",
)
File diff suppressed because it is too large Load Diff
+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()
+37 -97
View File
@@ -9,21 +9,24 @@
from __future__ import annotations
from dataclasses import dataclass
from collections.abc import Callable
from typing import Any
from core.douyu import DouyuActivityClient
from core.douyu.cookie_utils import cookie_value
from .account_binding import binding_snapshot
from .douyu_goods_service import serialize_goods
ERROR_MAX_LENGTH = 240
def activity_client(cookie: str = "") -> DouyuActivityClient:
def activity_client(
cookie: str = "",
*,
logger_callback: Callable[[str], None] | None = None,
proxies: dict[str, str] | None = None,
) -> DouyuActivityClient:
"""创建统一活动客户端;空 Cookie 可用于公开商品目录查询。"""
return DouyuActivityClient(cookie)
return DouyuActivityClient(
cookie,
logger=logger_callback,
proxies=proxies,
)
def query_csrf(
@@ -68,6 +71,29 @@ def query_xpd_bind_info(
return client.xpd_bind_info(act_alias=act_alias)
def query_xpd_embed(
client: DouyuActivityClient,
*,
act_alias: str,
rid: str,
) -> dict[str, Any]:
return client.xpd_embed_query(act_alias=act_alias, rid=rid)
def query_xpd_role(
client: DouyuActivityClient,
*,
embed_query: dict[str, str],
act_id: str,
rid: str = "",
) -> dict[str, Any]:
return client.xpd_get_role(
embed_query=embed_query,
act_id=act_id,
rid=rid,
)
def query_gold_account(client: DouyuActivityClient) -> dict[str, Any]:
return client.gold_account()
@@ -203,95 +229,8 @@ def query_exchange_orders(
return [dict(item) for item in result.get("orders") or [] if isinstance(item, dict)]
@dataclass(frozen=True)
class DouyuEligibilityResult:
elite_user_info: dict[str, Any]
points: int
points_response: dict[str, Any]
limited_goods: list[dict[str, Any]]
limited_ids: frozenset[str]
def query_exchange_eligibility(
client: DouyuActivityClient,
*,
cookie: str,
manual_id: str,
rid: str,
uid: str = "",
) -> DouyuEligibilityResult:
"""一次读取兑换资格需要的精英状态、积分和限兑商品。"""
ctn = query_csrf(client)
elite = query_elite_user_info(client, manual_id=manual_id, rid=rid)
resolved_uid = str(uid or cookie_value(cookie, "acf_uid") or "").strip()
points_result = query_points(client, uid=resolved_uid, ctn=ctn)
limited = query_limited_goods(client, manual_id=manual_id, rid=rid)
limited_ids = {
str(item.get("commodityId") or item.get("commodity_id") or "").strip()
for item in limited
}
limited_ids.discard("")
return DouyuEligibilityResult(
elite_user_info=elite,
points=int(points_result.get("points") or 0),
points_response=points_result,
limited_goods=limited,
limited_ids=frozenset(limited_ids),
)
def query_account_overview(
client: DouyuActivityClient,
*,
manual_id: str,
rid: str,
act_alias: str,
with_goods: bool = True,
) -> dict[str, Any]:
"""账号只读探针,单项失败只进入 errors,不阻断其他查询。"""
elite: dict[str, Any] = {}
bind: dict[str, Any] = {}
gold: dict[str, Any] = {}
goods: list[dict[str, Any]] = []
errors: dict[str, str] = {}
try:
elite = query_elite_user_info(client, manual_id=manual_id, rid=rid)
except Exception as exc: # noqa: BLE001 - 外部接口边界
errors["elite"] = _error_text(exc)
try:
bind = query_bind_info(client, act_alias=act_alias)
except Exception as exc: # noqa: BLE001
errors["bind"] = _error_text(exc)
try:
gold = query_gold_account(client)
except Exception as exc: # noqa: BLE001
errors["gold"] = _error_text(exc)
if with_goods:
try:
goods = query_activity_goods(client, manual_id=manual_id, rid=rid)
except Exception as exc: # noqa: BLE001
errors["goods"] = _error_text(exc)
return {
"elite": elite,
"bind": bind,
"bind_snapshot": binding_snapshot(bind),
"gold": gold,
"goods": goods,
"serialized_goods": [serialize_goods(item) for item in goods],
"errors": errors,
}
def _error_text(exc: BaseException) -> str:
return f"{type(exc).__name__}: {exc}"[:ERROR_MAX_LENGTH]
__all__ = [
"DouyuEligibilityResult",
"activity_client",
"query_account_overview",
"query_activity_goods",
"query_bind_info",
"query_csrf",
@@ -300,7 +239,6 @@ __all__ = [
"query_esports_goods",
"query_esports_goods_result",
"query_exchange_balance",
"query_exchange_eligibility",
"query_exchange_orders",
"query_exchange_orders_result",
"query_exchange_records",
@@ -310,4 +248,6 @@ __all__ = [
"query_limited_goods_result",
"query_points",
"query_xpd_bind_info",
"query_xpd_embed",
"query_xpd_role",
]
+208 -87
View File
@@ -49,18 +49,22 @@ from .account_events_service import (
from .audit_service import record_account_action, record_audit
from .business_events import record_account_query
from .collab_common import apply_order_visibility, count_archived
from .douyu_activity_query import (
from .cookie_check_service import check_douyu_cookie
from .douyu_account_probe import (
ROLE_BOUND,
ROLE_ERROR,
ROLE_PENDING,
ROLE_UNKNOWN,
SESSION_INVALID,
SESSION_VALID,
activity_client,
query_account_overview,
query_activity_goods,
query_elite_user_info,
config_mapping,
persist_probe_result,
probe_account,
)
from .douyu_activity_query import (
query_exchange_orders,
query_exchange_records,
query_gold_account,
)
from .douyu_elite_status import (
elite_is_currently_open,
normalize_elite_expire_time,
)
from .douyu_goods_service import (
serialize_live_goods as _serialize_live_goods,
@@ -313,7 +317,12 @@ def _client_for_account(account: Account) -> DouyuActivityClient:
cookie = str(account.cookie or "").strip()
if not cookie:
raise CollabError("该账号没有 CK", code="account_no_cookie")
return activity_client(cookie)
return activity_client(
cookie,
logger_callback=lambda message: logger.debug(
"[douyu-collab] account={} {}", account.id, message
),
)
def serialize_live_goods(goods: list[dict[str, Any]]) -> list[dict[str, Any]]:
@@ -327,6 +336,8 @@ def _probe_with_client(
manual_id: str,
rid: str,
act_alias: str,
confirm_act_alias: str = "",
legacy_act_alias: str = "",
client: Any | None = None,
with_goods: bool = True,
) -> dict[str, Any]:
@@ -341,67 +352,104 @@ def _probe_with_client(
}
active_client = client or _client_for_account(account)
overview = query_account_overview(
active_client,
manual_id=manual_id,
rid=rid,
act_alias=act_alias,
with_goods=with_goods,
caller_supplied_client = client is not None
config_info = config_mapping(
{
"manual_id": manual_id,
"rid": rid,
"bind_act_alias": act_alias,
"confirm_act_alias": confirm_act_alias or act_alias,
"legacy_act_alias": legacy_act_alias,
}
)
elite = overview["elite"]
bind = overview["bind"]
bind_snapshot = overview["bind_snapshot"]
gold = overview["gold"]
goods = overview["serialized_goods"]
result = probe_account(
account,
config_info,
client=active_client,
session_checker=None if caller_supplied_client else check_douyu_cookie,
with_gold=True,
with_goods=with_goods,
use_cache=not caller_supplied_client,
)
elite = result.get("elite") or {}
role = (result.get("roles") or {}).get("elite") or {}
identity = result.get("identity") or {}
session = result.get("session") or {}
gold = result.get("gold") or {}
goods = result.get("goods") or {}
bind_snapshot = role.get("snapshot") or {}
role_status = str(role.get("status") or ROLE_UNKNOWN)
error_labels = {
"elite": "手册状态",
"bind": "绑定角色",
"points": "积分",
"limited_goods": "限兑商品",
"gold": "鱼翅余额",
"goods": "活动商品",
}
errors = [
f"{error_labels.get(key, key)}: {value}"
for key, value in overview["errors"].items()
for key, value in (result.get("errors") or {}).items()
]
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"))
user_info = elite.get("user_info") or {}
profile = DouyuActivityClient.profile_from_cookie(str(account.cookie or ""))
bind_role = _text(bind_snapshot["role_name"], max_length=128)
area_name = _text(bind_snapshot["area_name"], max_length=64)
plat_name = _text(bind_snapshot["plat_name"], max_length=64)
bind_channel = " · ".join(item for item in (area_name, plat_name) if item)
bind_account = _text(bind_snapshot["nickname"], max_length=128)
ck_status = CK_VALID if (elite or bind) else CK_INVALID
ok = bool(bind_snapshot["bind_confirmed"]) and not (elite == {} and bind == {})
errors.extend(role.get("errors") or [])
session_status = str(session.get("status") or "")
if session_status == SESSION_VALID:
ck_status = CK_VALID
elif session_status == SESSION_INVALID:
ck_status = CK_INVALID
else:
ck_status = CK_UNVERIFIED
bind_role = _text(role.get("role_name"), max_length=128)
bind_channel = _text(role.get("game_channel"), max_length=128)
bind_account = _text(role.get("game_account"), max_length=128)
ok = (
session_status == SESSION_VALID
and role_status == ROLE_BOUND
and bool(bind_role)
)
if session_status == SESSION_INVALID:
message = f"CK 已失效:{session.get('message') or '请重新登录'}"
elif session_status not in {SESSION_VALID, ""}:
message = f"CK 状态无法确认:{session.get('message') or '请稍后重试'}"
elif role_status == ROLE_ERROR:
message = "角色查询失败" + (
f":{';'.join(role.get('errors') or [])}" if role.get("errors") else ""
)
elif role_status == ROLE_UNKNOWN:
message = "角色状态无法确认,已保留上次有效结果"
elif role_status == ROLE_PENDING:
message = "已识别角色,待确认绑定"
elif not bind_role:
message = "CK 正常,但账号未绑定角色"
else:
message = ";".join(errors)
if error_labels.get("gold") and gold.get("error"):
message = f"{message};鱼翅余额: {gold['error']}"
return {
"found": True,
"ok": ok,
"ck_status": ck_status,
"message": ";".join(errors) if errors else ("" if ok else "未读到绑定角色"),
"auth_status": session_status,
"role_status": role_status,
"message": message,
"errors": errors,
"account_id": int(account.id),
"account_username": str(account.username or ""),
"account_uid": _text(account.uid or profile.get("uid"), max_length=32),
"account_nickname": _text(
user_info.get("nickname") or account.nickname or profile.get("nickname"),
max_length=128,
),
"manual_type": manual_type,
"manual_score": manual_score,
"expire_time": expire_time,
"manual_opened": elite_is_currently_open(manual_type, expire_time),
"bind_status": bind_snapshot["bind_status"],
"bind_phase": bind_snapshot["bind_phase"],
"account_username": identity.get("username") or str(account.username or ""),
"account_uid": _text(identity.get("uid"), max_length=32),
"account_nickname": _text(identity.get("nickname"), max_length=128),
"manual_type": elite.get("manual_type"),
"manual_score": elite.get("manual_score"),
"expire_time": elite.get("expire_time"),
"manual_opened": bool(elite.get("opened")),
"bind_status": bind_snapshot.get("bind_status"),
"bind_phase": bind_snapshot.get("bind_phase"),
"bind_game_account": bind_account,
"bind_game_role": bind_role,
"bind_game_channel": bind_channel,
"fish_fin_balance": _to_int(gold.get("gold")),
"goods": goods,
"goods_count": len(goods),
"fish_fin_balance": _to_int(gold.get("balance")),
"goods": goods.get("serialized") or [],
"goods_count": int(goods.get("count") or 0),
"_probe_result": result,
}
@@ -426,6 +474,8 @@ def lookup_account(
manual_id=str(config.manual_id or ""),
rid=str(config.rid or ""),
act_alias=str(config.bind_act_alias or ""),
confirm_act_alias=str(config.confirm_act_alias or ""),
legacy_act_alias=str(config.legacy_act_alias or ""),
client=client,
with_goods=with_goods,
)
@@ -444,12 +494,29 @@ def lookup_account(
for order in orders
]
probe["ck_status_label"] = CK_LABELS.get(str(probe.get("ck_status")), "")
probe.pop("_probe_result", None)
return probe
def apply_probe_snapshot(
order: DouyuExternalOrder, account: Account, probe: Mapping[str, Any]
db: Session,
current: User,
order: DouyuExternalOrder,
account: Account,
probe: Mapping[str, Any],
*,
source: str,
) -> None:
canonical = probe.get("_probe_result")
if isinstance(canonical, dict):
persist_probe_result(
db,
account,
canonical,
current=current,
source=source,
record_event=True,
)
order.account_id = int(account.id)
order.account_username = _text(account.username, max_length=128) or _text(
probe.get("account_username"), max_length=128
@@ -458,23 +525,18 @@ def apply_probe_snapshot(
order.account_nickname = _text(
probe.get("account_nickname") or account.nickname, max_length=128
)
order.bind_game_account = _text(probe.get("bind_game_account"), max_length=128)
order.bind_game_role = _text(probe.get("bind_game_role"), max_length=128)
order.bind_game_channel = _text(probe.get("bind_game_channel"), max_length=128)
order.bind_snapshot_at = _now()
role_status = str(probe.get("role_status") or "")
if role_status not in {ROLE_ERROR, ROLE_UNKNOWN}:
order.bind_game_account = _text(probe.get("bind_game_account"), max_length=128)
order.bind_game_role = _text(probe.get("bind_game_role"), max_length=128)
order.bind_game_channel = _text(probe.get("bind_game_channel"), max_length=128)
order.bind_snapshot_at = _now()
fish = _to_int(probe.get("fish_fin_balance"))
points = _to_int(probe.get("manual_score"))
if fish is not None:
order.fish_fin_balance = fish
account.gold_balance = fish
if points is not None:
order.points_balance = points
account.points = points
ck_status = str(probe.get("ck_status") or "")
if ck_status in (CK_VALID, CK_INVALID):
account.ck_check_status = ck_status
account.ck_checked_at = _now()
account.updated_at = _now()
def _assert_version(order: DouyuExternalOrder, expected: int | None) -> None:
@@ -1115,10 +1177,19 @@ def create_order(
manual_id=str(config.manual_id or ""),
rid=str(config.rid or ""),
act_alias=str(config.bind_act_alias or ""),
confirm_act_alias=str(config.confirm_act_alias or ""),
legacy_act_alias=str(config.legacy_act_alias or ""),
client=client,
with_goods=True,
)
apply_probe_snapshot(order, account, probe)
apply_probe_snapshot(
db,
current,
order,
account,
probe,
source="douyu_collab.create",
)
if explicit_points is None and name:
live = next(
(
@@ -1608,6 +1679,8 @@ def update_order(
manual_id=str(config.manual_id or ""),
rid=str(config.rid or ""),
act_alias=str(config.bind_act_alias or ""),
confirm_act_alias=str(config.confirm_act_alias or ""),
legacy_act_alias=str(config.legacy_act_alias or ""),
client=client,
with_goods=True,
)
@@ -1619,7 +1692,14 @@ def update_order(
force_active=order.status in COLLAB_LEASE_STATUSES,
takeover_platform_lease=takeover_platform_lease,
)
apply_probe_snapshot(order, account, probe)
apply_probe_snapshot(
db,
current,
order,
account,
probe,
source="douyu_collab.update",
)
changes["account_id"] = {
"old": previous_account_id or None,
"new": int(account.id),
@@ -1691,6 +1771,8 @@ def set_account(
manual_id=str(config.manual_id or ""),
rid=str(config.rid or ""),
act_alias=str(config.bind_act_alias or ""),
confirm_act_alias=str(config.confirm_act_alias or ""),
legacy_act_alias=str(config.legacy_act_alias or ""),
client=client,
with_goods=True,
)
@@ -1702,7 +1784,14 @@ def set_account(
force_active=order.status in COLLAB_LEASE_STATUSES,
takeover_platform_lease=takeover_platform_lease,
)
apply_probe_snapshot(order, account, probe)
apply_probe_snapshot(
db,
current,
order,
account,
probe,
source="douyu_collab.account",
)
order.updated_by = current.id
order.version = int(order.version or 0) + 1
record_audit(
@@ -1752,10 +1841,19 @@ def verify_order(
manual_id=str(config.manual_id or ""),
rid=str(config.rid or ""),
act_alias=str(config.bind_act_alias or ""),
confirm_act_alias=str(config.confirm_act_alias or ""),
legacy_act_alias=str(config.legacy_act_alias or ""),
client=client,
with_goods=True,
)
apply_probe_snapshot(order, account, probe)
apply_probe_snapshot(
db,
current,
order,
account,
probe,
source="douyu_collab.verify",
)
order.updated_by = current.id
order.version = int(order.version or 0) + 1
record_audit(
@@ -2105,23 +2203,21 @@ def query_activity(
raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found")
config = resolve_config(db)
active_client = client or _client_for_account(account)
errors: list[str] = []
elite: dict[str, Any] = {}
gold: dict[str, Any] = {}
probe = probe_account(
account,
config,
client=active_client,
session_checker=None,
with_gold=True,
with_elite_role=False,
)
elite = (probe.get("elite") or {}).get("raw") or {}
gold = {
"gold": (probe.get("gold") or {}).get("balance"),
}
errors = list((probe.get("errors") or {}).values())
records: list[dict[str, Any]] = []
orders: list[dict[str, Any]] = []
try:
elite = query_elite_user_info(
active_client,
manual_id=str(config.manual_id or ""),
rid=str(config.rid or ""),
)
except Exception as exc: # noqa: BLE001
errors.append(f"积分: {exc}")
try:
gold = query_gold_account(active_client)
except Exception as exc: # noqa: BLE001
errors.append(f"鱼翅: {exc}")
if include_records:
try:
records = query_exchange_records(
@@ -2144,6 +2240,14 @@ def query_activity(
manual_score = _to_int(elite.get("manual_score"))
fish = _to_int(gold.get("gold"))
persist_probe_result(
db,
account,
probe,
current=current,
source="douyu_collab.query_activity",
record_event=False,
)
if manual_score is not None:
order.points_balance = manual_score
account.points = manual_score
@@ -2643,10 +2747,27 @@ def refresh_activity_goods(
raise CollabError("没有带 CK 的斗鱼账号,无法刷新活动商品", code="no_account")
active_client = client or _client_for_account(account)
try:
goods = query_activity_goods(
active_client,
manual_id=str(config.manual_id or ""),
rid=str(config.rid or ""),
probe = probe_account(
account,
config,
client=active_client,
session_checker=None,
with_elite=False,
with_elite_role=False,
with_goods=True,
)
goods = (probe.get("goods") or {}).get("items") or []
if (probe.get("goods") or {}).get("status") == "error":
raise RuntimeError(
(probe.get("goods") or {}).get("error") or "商品查询失败"
)
persist_probe_result(
db,
account,
probe,
current=current,
source="douyu_collab.goods_refresh",
record_event=False,
)
except Exception as exc:
record_account_query(
+32 -8
View File
@@ -10,8 +10,8 @@ from core.douyu import DouyuActivityError
from ..database import SessionLocal
from ..models import DouyuTask
from .account_lifecycle import on_ck_verdict
from .cookie_check_service import check_douyu_cookie
from .douyu_account_probe import persist_probe_result, probe_session
from .douyu_runner_bind import BindMixin
from .douyu_runner_core import ( # noqa: F401 (douyu_batch_registry 供 routers 重导出)
DouyuBatchRunnerCore,
@@ -68,18 +68,42 @@ class DouyuBatchRunner(
)
return
cookie_check = check_douyu_cookie(cookie)
cookie_check = probe_session(cookie, checker=check_douyu_cookie)
ck_verdict = str(cookie_check["status"])
# 执行前的这次检测同样要写结论、由好变坏记事件、重算状态。
on_ck_verdict(
persist_probe_result(
worker_db,
account,
"valid" if cookie_check["valid"] else "invalid",
detail=cookie_check,
occurred_at=cookie_check["checked_at"],
{
"probe_id": f"task-preflight:{task.id}",
"identity": {
"uid": account.uid,
"username": account.username,
"nickname": (
(cookie_check.get("detail") or {}).get("nickname") or ""
),
"nickname_source": "session",
},
"session": cookie_check,
"elite": {},
"eligibility": {},
"roles": {},
"gold": {},
"goods": {},
"errors": {},
},
source="douyu_task.preflight",
record_event=False,
commit=False,
)
worker_db.commit()
if not cookie_check["valid"]:
message = f"Cookie 已失效,请重新登录:{cookie_check['message']}"
if ck_verdict != "valid":
prefix = (
"Cookie 已失效,请重新登录"
if ck_verdict == "invalid"
else "Cookie 状态无法确认"
)
message = f"{prefix}:{cookie_check['message']}"
self._mark_task(worker_db, task, "failed", message)
self._push_log(
"warning", f"[{current}] {self._account_name(account)} {message}"
+138 -123
View File
@@ -25,7 +25,16 @@ from .account_binding import (
set_bind_status,
)
from .business_events import record_bind
from .douyu_activity_query import query_bind_info, query_esports_bind_info
from .douyu_account_probe import (
ROLE_BOUND,
ROLE_ERROR,
ROLE_PENDING,
ROLE_UNKNOWN,
persist_probe_result,
query_elite_bind_candidates,
resolve_elite_role,
)
from .douyu_activity_query import query_esports_bind_info
DOUYU_LEGACY_BIND_ACT_ALIAS = "20250213NQCYX"
DOUYU_BIND_ROLE_POLL_SECONDS = 600
@@ -252,21 +261,15 @@ class BindMixin:
aliases: list[str],
) -> list[dict]:
"""按多个 actAlias 查询绑定信息,保留成功结果。"""
results: list[dict] = []
for alias in aliases:
if not alias:
continue
try:
info = query_bind_info(client, act_alias=alias, v2=True)
except DouyuActivityError as exc:
self._push_log("warning", f"查询绑定信息失败 act={alias}: {exc}")
continue
info = {**info, "act_alias": alias}
results, errors = query_elite_bind_candidates(client, aliases)
for error in errors:
self._push_log("warning", f"查询绑定信息失败 {error}")
for info in results:
self._push_log(
"info",
f"绑定信息 act={alias} {self._format_bind_summary(info)}",
"绑定信息 "
f"act={info.get('act_alias') or '-'} {self._format_bind_summary(info)}",
)
results.append(info)
return results
def _role_alias_priority(self, config: dict, primary_alias: str = "") -> list[str]:
@@ -1270,41 +1273,17 @@ class BindMixin:
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
):
client = self._client(cookie)
query_aliases = self._query_bind_act_aliases(config)
if not query_aliases:
self._mark_task(db, task, "failed", "请先配置绑定活动 actAlias")
return
candidates = self._fetch_bind_info_candidates(client, query_aliases)
if not candidates:
self._mark_task(
db, task, "failed", "查询绑定信息失败,请检查 Cookie 或 actAlias"
)
return
# 1) 优先“已生效绑定”角色(bound_act=1 且有角色名,通常是活动 alias)。
# 避免把扫码后未确认的新角色当成当前绑定结果。
bound_info = self._pick_current_bound_info(candidates, config)
# 2) 待确认角色统一交给共享状态机判断。cjm 中与当前绑定同名的残留
# 不算 pending;同名但活动状态发生 needBindAct 转换才算 pending。
pending_info = self._pick_pending_role_info(
candidates,
prefer_aliases=self._role_alias_priority(config),
baseline_role_name=str((bound_info or {}).get("role_name") or ""),
baseline_is_bound_act=self._is_bound_act(bound_info),
baseline_info=bound_info,
)
pending_role = str((pending_info or {}).get("role_name") or "").strip()
bound_role = str(bound_info.get("role_name") or "") if bound_info else ""
has_pending = pending_info is not None and bool(pending_role)
# 查询结果角色 = 已生效绑定;首次绑定(无绑定)时回退待确认角色
role = resolve_elite_role(client, config)
status = str(role.get("status") or "")
bind_info = (
bound_info if bound_info else (pending_info if has_pending else None)
role.get("bind_info") if isinstance(role.get("bind_info"), dict) else {}
)
snapshot = self._bind_snapshot(bind_info) if bind_info else {}
role_name = snapshot.get("role_name") or ""
is_bound = snapshot.get("is_bound_act", False)
source_alias = str((bind_info or {}).get("act_alias") or "")
snapshot = (
role.get("snapshot") if isinstance(role.get("snapshot"), dict) else {}
)
role_name = str(role.get("role_name") or "")
pending_role = str(role.get("pending_role_name") or "")
source_alias = str(role.get("source_alias") or "")
summary = (
f"act={source_alias or '-'} {self._format_bind_summary(bind_info)}"
if bind_info
@@ -1313,54 +1292,70 @@ class BindMixin:
self._push_log(
"info",
"查询角色 "
f"aliases={','.join(query_aliases)} bound_hit={(bound_info or {}).get('act_alias') or '-'} "
f"pending_hit={(pending_info or {}).get('act_alias') or '-'} "
f"aliases={','.join(role.get('query_act_aliases') or [])} "
f"status={status} source={source_alias or '-'} "
f"{self._format_bind_summary(bind_info) if bind_info else 'role=- bound_act=-'}",
)
# 只有已生效绑定才写账号表;待确认角色不污染 game_name
if bind_info and is_bound:
self._apply_bind_info_to_account(account, bind_info)
else:
account.updated_at = datetime.now(UTC)
persist_probe_result(
db,
account,
{
"probe_id": f"task:{task.id}",
"identity": {"uid": account.uid, "username": account.username},
"session": {},
"elite": {},
"eligibility": {},
"roles": {"elite": role},
"gold": {},
"goods": {},
"errors": {"elite_role": ";".join(role.get("errors") or [])}
if role.get("errors")
else {},
},
source="douyu_task.query_game_name",
record_event=False,
)
result = {
**snapshot,
"act_alias": source_alias,
"query_act_alias": source_alias,
"query_act_aliases": query_aliases,
**snapshot,
"bind_ready_for_confirm": has_pending,
"bind_confirmed": is_bound,
"query_act_aliases": role.get("query_act_aliases") or [],
"role_status": status,
"role_name": role_name,
"bind_ready_for_confirm": status == ROLE_PENDING,
"bind_confirmed": status == ROLE_BOUND,
"bind_phase": (
"confirmed"
if is_bound
if status == ROLE_BOUND
else ("role_ready" if role_name else "waiting_role")
),
"bind_summary": summary,
"bind_candidates": [
{
"act_alias": item.get("act_alias"),
"role_name": item.get("role_name"),
"is_bound_act": self._is_bound_act(item),
}
for item in candidates
],
"bind_candidates": role.get("candidates") or [],
"errors": role.get("errors") or [],
}
# 已绑定角色之外另有待确认新角色时,单独字段展示,不覆盖 role_name
if has_pending and bound_info and pending_role != bound_role:
if pending_role:
result["pending_role_name"] = pending_role
result["pending_area_name"] = str(pending_info.get("area_name") or "")
result["pending_plat_name"] = str(pending_info.get("plat_name") or "")
if not bind_info:
message = f"未获取到游戏名 | {summary}"
elif is_bound:
if has_pending and pending_role != bound_role:
message = (
f"当前已绑定: {bound_role},待确认: {pending_role} | {summary}"
)
else:
message = f"当前已绑定: {bound_role} | {summary}"
else:
result["pending_area_name"] = role.get("pending_area_name") or ""
result["pending_plat_name"] = role.get("pending_plat_name") or ""
if status == ROLE_ERROR:
message = f"查询角色失败: {';'.join(role.get('errors') or ['未知错误'])}"
elif status == ROLE_UNKNOWN:
message = "角色状态无法确认,已保留上次有效结果"
elif status == ROLE_BOUND:
message = f"当前已绑定: {role_name} | {summary}"
elif status == ROLE_PENDING:
message = f"待确认角色: {role_name} | {summary}"
self._mark_task(db, task, "success" if role_name else "failed", message, result)
else:
message = f"未获取到游戏名 | {summary}"
self._mark_task(
db,
task,
"success"
if status in {ROLE_BOUND, ROLE_PENDING} and bool(role_name)
else "failed",
message,
result,
)
def _pick_change_wait_bind_info(
self, candidates: list[dict], config: dict
@@ -1387,39 +1382,74 @@ class BindMixin:
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
):
client = self._client(cookie)
query_aliases = self._query_bind_act_aliases(config)
if not query_aliases:
self._mark_task(db, task, "failed", "请先配置绑定活动 actAlias")
return
candidates = self._fetch_bind_info_candidates(client, query_aliases)
if not candidates:
role = resolve_elite_role(client, config)
status = str(role.get("status") or "")
query_aliases = role.get("query_act_aliases") or []
raw_candidates = role.get("bind_infos") or []
if status == ROLE_ERROR:
self._mark_task(
db, task, "failed", "查询绑定信息失败,请检查 Cookie 或 actAlias"
db,
task,
"failed",
f"查询绑定信息失败: {';'.join(role.get('errors') or ['未知错误'])}",
)
return
for item in candidates:
for item in raw_candidates:
self._push_log(
"info",
f"查询换绑时间候选 act={item.get('act_alias') or '-'} "
f"{self._format_bind_summary(item)}",
)
current_bound = self._pick_current_bound_info(candidates, config)
pending_info = self._pick_pending_role_info(
candidates,
prefer_aliases=self._role_alias_priority(config),
baseline_role_name=str((current_bound or {}).get("role_name") or ""),
baseline_is_bound_act=self._is_bound_act(current_bound),
baseline_info=current_bound,
)
pending_role = str((pending_info or {}).get("role_name") or "").strip()
# 换绑时间看“当前已绑定”活动态,不要优先 cjm(cjm 常无 changeRoleWaitTime)
action_aliases = self._action_act_aliases(config)
bind_info = next(
(
item
for alias in action_aliases
for item in raw_candidates
if str(item.get("act_alias") or "") == alias
and item.get("change_role_wait_time") is not None
),
None,
)
bind_info = (
self._pick_change_wait_bind_info(candidates, config) or candidates[0]
bind_info
or (
role.get("bind_info")
if isinstance(role.get("bind_info"), dict)
else None
)
or (raw_candidates[0] if raw_candidates else {})
)
snapshot = self._bind_snapshot(bind_info)
wait_time = snapshot["change_role_wait_time"]
account.change_role_wait_time = wait_time
account.updated_at = datetime.now(UTC)
persist_role = {
**role,
"bind_info": bind_info,
"snapshot": snapshot,
"role_name": snapshot.get("role_name") or "",
"game_channel": snapshot.get("game_channel") or "",
"change_role_wait_time": wait_time,
"can_change_role": snapshot.get("can_change_role"),
"can_change_time": snapshot.get("can_change_time"),
}
persist_probe_result(
db,
account,
{
"probe_id": f"task:{task.id}",
"identity": {"uid": account.uid, "username": account.username},
"session": {},
"elite": {},
"eligibility": {},
"roles": {"elite": persist_role},
"gold": {},
"goods": {},
"errors": {},
},
source="douyu_task.query_change_bind_time",
record_event=False,
)
source_alias = str(bind_info.get("act_alias") or "")
wait_text = self._format_wait_time(wait_time)
can_change = snapshot["can_change_role"]
@@ -1442,31 +1472,16 @@ class BindMixin:
"query_act_aliases": query_aliases,
**snapshot,
"change_role_wait_text": wait_text,
# 待确认语义统一由 _pick_pending_role_info 决定;这里不再根据
# “只是有角色名且 bindAct=0”自行推断。
"bind_ready_for_confirm": pending_info is not None,
"role_status": status,
"bind_ready_for_confirm": status == ROLE_PENDING,
"bind_confirmed": snapshot["is_bound_act"],
"bind_summary": f"act={source_alias or '-'} {self._format_bind_summary(bind_info)}",
"bind_candidates": [
{
"act_alias": item.get("act_alias"),
"role_name": item.get("role_name"),
"is_bound_act": self._is_bound_act(item),
"change_role_wait_time": self._to_int(
item.get("change_role_wait_time")
),
"can_change_role": item.get("can_change_role"),
}
for item in candidates
],
"bind_candidates": role.get("candidates") or [],
}
if (
pending_info is not None
and pending_role != str(snapshot["role_name"] or "").strip()
):
result["pending_role_name"] = pending_role
result["pending_area_name"] = str(pending_info.get("area_name") or "")
result["pending_plat_name"] = str(pending_info.get("plat_name") or "")
if role.get("pending_role_name"):
result["pending_role_name"] = role.get("pending_role_name")
result["pending_area_name"] = role.get("pending_area_name") or ""
result["pending_plat_name"] = role.get("pending_plat_name") or ""
self._push_log(
"info",
f"查询换绑时间 hit={source_alias or '-'} role={role_name} "
+3 -2
View File
@@ -23,6 +23,7 @@ from ..models import (
from ..models import (
ProxyConfig as ProxyConfigModel,
)
from .douyu_account_probe import activity_client
from .douyu_goods_service import upsert_goods_snapshot
from .douyu_service import (
DOUYU_CONFIG_FIELDS,
@@ -411,9 +412,9 @@ class DouyuBatchRunnerCore:
def _client(self, cookie: str) -> DouyuActivityClient:
"""任务 HTTP 客户端:写操作任务注入会话级代理(兑换/锁单/支付/充值/送礼),
读操作任务直连;见 DOUYU_PROXY_TASK_TYPES。"""
return DouyuActivityClient(
return activity_client(
cookie,
logger=lambda msg: self._push_log("debug", msg),
logger_callback=lambda msg: self._push_log("debug", msg),
proxies=self._proxies_for_task(),
)
+73 -30
View File
@@ -33,16 +33,27 @@ from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient
from ..models import Account, DouyuTask
from .account_binding import binding_snapshot, set_bind_status
from .account_capability_service import sync_account_goods_states
from .business_events import record_official_exchange
from .douyu_account_probe import (
ROLE_BOUND,
ROLE_ERROR,
ROLE_PENDING,
ROLE_UNBOUND,
ROLE_UNKNOWN,
persist_probe_result,
query_elite_bind_candidates,
resolve_elite_role,
resolve_esports_role,
resolve_peace_role,
)
from .douyu_activity_query import (
query_activity_goods,
query_bind_info,
query_csrf,
query_esports_bind_info,
query_exchange_records,
query_xpd_bind_info,
query_xpd_embed,
)
from .douyu_runner_donate import _parse_expire_at, _points_expire_at
from .high_value_service import (
@@ -199,7 +210,10 @@ class OverviewMixin:
) -> dict[str, Any]:
"""按作用域查绑定信息(三个接口不同,收敛在一处)。"""
if scope == "elite":
return query_bind_info(client, act_alias=alias)
rows, errors = query_elite_bind_candidates(client, [alias])
if errors:
raise RuntimeError(";".join(errors))
return rows[0] if rows else {}
if scope == "esports":
return query_esports_bind_info(client, act_alias=alias)
return query_xpd_bind_info(client, act_alias=alias)
@@ -238,7 +252,8 @@ class OverviewMixin:
esports_manual_id: str,
) -> list[dict[str, Any]]:
"""和平小店:先要一次性短时授权,再查购买记录。"""
embed = client.xpd_embed_query(
embed = query_xpd_embed(
client,
act_alias=str(config["xpd_act_alias"]),
rid=str(config["xpd_rid"]),
)
@@ -383,6 +398,11 @@ class OverviewMixin:
)
overview["bind"] = {}
role_resolvers = {
"elite": resolve_elite_role,
"esports": resolve_esports_role,
"peace": resolve_peace_role,
}
for scope, label, alias_key in (
("elite", "精英宝典", "bind_act_alias"),
("esports", "电竞手册", "esports_act_alias"),
@@ -394,32 +414,55 @@ class OverviewMixin:
if not alias:
errors[f"bind_{scope}"] = f"未配置{label}活动别名"
continue
try:
info = self._fetch_bind_info(client, scope, alias)
snapshot = binding_snapshot(info)
derived = snapshot["bind_status"]
# 把**明细**也带上:运营要看的是"绑的哪个角色、哪个区服、
# 什么时候能换绑",不是一个"已绑定"就完事。
overview["bind"][scope] = {
"derived": derived,
"phase": snapshot["bind_phase"],
"role_name": snapshot["role_name"],
"area_name": snapshot["area_name"],
"plat_name": snapshot["plat_name"],
"nickname": snapshot["nickname"],
"game_id": snapshot["game_id"],
"game_name": snapshot["game_name"],
"is_change_cooling": snapshot["is_change_cooling"],
"can_change_role": snapshot["can_change_role"],
"change_role_wait_time": _ts(snapshot["change_role_wait_time"]),
"can_change_time": _ts(snapshot["can_change_time"]),
}
if derived is not None:
# 唯一写入者;推不出来(None)时**不动原值** —— 宁可留 unknown,
# 也不要把"没查到"写成"没绑定"
set_bind_status(account, scope, derived)
except Exception as exc: # noqa: BLE001 外部接口边界需要宽泛兜底
errors[f"bind_{scope}"] = _err(exc)
role = role_resolvers[scope](
client,
config,
bind_fetcher=lambda selected_alias, selected_scope=scope: (
self._fetch_bind_info(client, selected_scope, selected_alias)
),
)
status = str(role.get("status") or "")
snapshot = (
role.get("snapshot") if isinstance(role.get("snapshot"), dict) else {}
)
overview["bind"][scope] = {
"status": status,
"derived": snapshot.get("bind_status"),
"phase": snapshot.get("bind_phase"),
"role_name": snapshot.get("role_name") or "",
"area_name": snapshot.get("area_name") or "",
"plat_name": snapshot.get("plat_name") or "",
"nickname": snapshot.get("nickname") or "",
"game_id": snapshot.get("game_id") or "",
"game_name": snapshot.get("game_name") or "",
"source_alias": role.get("source_alias") or "",
"is_change_cooling": snapshot.get("is_change_cooling"),
"can_change_role": snapshot.get("can_change_role"),
"change_role_wait_time": _ts(snapshot.get("change_role_wait_time")),
"can_change_time": _ts(snapshot.get("can_change_time")),
}
if status in {ROLE_ERROR, ROLE_UNKNOWN} and role.get("errors"):
errors[f"bind_{scope}"] = ";".join(role.get("errors") or [])
if status == ROLE_ERROR:
continue
if status in {ROLE_BOUND, ROLE_PENDING, ROLE_UNBOUND}:
persist_probe_result(
db,
account,
{
"probe_id": f"task:{task.id}:role:{scope}",
"identity": {"uid": account.uid, "username": account.username},
"session": {},
"elite": {},
"eligibility": {},
"roles": {scope: role},
"gold": {},
"goods": {},
"errors": {},
},
source=f"douyu_task.query_account_overview.{scope}",
record_event=False,
)
# ---- 官方兑换记录(**三个作用域都拉**)----
#
+15 -6
View File
@@ -19,7 +19,11 @@ from .account_binding import (
set_bind_status,
)
from .business_events import record_exchange
from .douyu_activity_query import query_xpd_bind_info
from .douyu_activity_query import (
query_xpd_bind_info,
query_xpd_embed,
query_xpd_role,
)
DOUYU_XPD_BIND_POLL_SECONDS = 300
DOUYU_XPD_BIND_POLL_INTERVAL = 5
@@ -43,11 +47,13 @@ class XpdMixin:
def _xpd_role_context(self, client: DouyuActivityClient, config: dict) -> dict:
"""获取小店 H5 参数 + 绑定角色信息,小店任务共用。"""
embed = client.xpd_embed_query(
embed = query_xpd_embed(
client,
act_alias=str(config["xpd_act_alias"]),
rid=str(config["xpd_rid"]),
)
role = client.xpd_get_role(
role = query_xpd_role(
client,
embed_query=embed["query"],
act_id=str(config["xpd_act_id"]),
rid=str(config["xpd_rid"]),
@@ -456,7 +462,8 @@ class XpdMixin:
):
"""查询和平小店道聚城购买记录。"""
client = self._client(cookie)
embed = client.xpd_embed_query(
embed = query_xpd_embed(
client,
act_alias=str(config["xpd_act_alias"]),
rid=str(config["xpd_rid"]),
)
@@ -528,13 +535,15 @@ class XpdMixin:
return
client = self._client(cookie)
embed = client.xpd_embed_query(
embed = query_xpd_embed(
client,
act_alias=str(config["xpd_act_alias"]),
rid=str(config["xpd_rid"]),
)
role: dict = {}
try:
role = client.xpd_get_role(
role = query_xpd_role(
client,
embed_query=embed["query"],
act_id=str(config["xpd_act_id"]),
rid=str(config["xpd_rid"]),
+3 -6
View File
@@ -10,7 +10,6 @@ from loguru import logger
from sqlalchemy import and_, func, select
from sqlalchemy.orm import Session
from core.douyu.activity_client import DouyuActivityClient
from core.douyu.cookie_utils import cookie_value
from ..models import Account, DouyuConfig, DouyuTask, LoginTask
@@ -362,11 +361,9 @@ def _lock_payment_accounts(
def update_account_profile_from_cookie(account: Account, cookie: str) -> None:
"""从 Cookie 回填 uid/nickname。"""
profile = DouyuActivityClient.profile_from_cookie(cookie)
if profile["uid"]:
account.uid = profile["uid"]
if profile["nickname"]:
account.nickname = profile["nickname"]
from .douyu_account_probe import update_identity_from_cookie
update_identity_from_cookie(account, cookie)
def account_uid(account: Account, cookie: str) -> str:
+36 -10
View File
@@ -26,8 +26,9 @@ from .account_events_service import (
EVENT_RELOGIN_OK,
emit,
)
from .account_lifecycle import on_ck_verdict, on_login_success, sync_status
from .account_lifecycle import on_login_success, sync_status
from .cookie_check_service import check_douyu_cookie
from .douyu_account_probe import persist_probe_result, probe_session
from .douyu_service import LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
from .login_failure import classify_failure, failure_kind_label, is_account_fault
from .proxy_service import build_proxy_runtime
@@ -495,20 +496,45 @@ class LoginBatchRunner:
elif result.success:
message = result.message or "登录成功"
if self.mode == "relogin" and account is not None:
check_result = check_douyu_cookie(result.cookie)
# 复检结论写账号(CK 在哪,健康状态就在哪),走统一入口:
# 写结论 + 由好变坏记事件 + 重算状态。
on_ck_verdict(
check_result = probe_session(
result.cookie,
checker=check_douyu_cookie,
)
detail = (
check_result.get("detail")
if isinstance(check_result.get("detail"), dict)
else {}
)
persist_probe_result(
worker_db,
account,
"valid" if check_result["valid"] else "invalid",
detail=check_result,
occurred_at=check_result["checked_at"],
{
"probe_id": f"relogin:{self.batch_id}:{task.id}",
"identity": {
"uid": account.uid,
"username": account.username,
"nickname": detail.get("nickname") or "",
"nickname_source": "session",
},
"session": check_result,
"elite": {},
"eligibility": {},
"roles": {},
"gold": {},
"goods": {},
"errors": {},
},
source="login.relogin_verify",
record_event=False,
commit=False,
)
if check_result["valid"]:
if check_result["status"] == "valid":
message = "重新登录成功,Cookie 有效"
else:
message = f"重新登录成功,但 Cookie 有效性检测失败: {check_result['message']}"
message = (
"重新登录成功,但 Cookie 有效性检测失败: "
f"{check_result['message']}"
)
# 唯一替换旧 CK 的入口:登录成功后写回账号。
#
# ⚠️ 必须传 **worker_db**(本线程的会话),不能传 self.db:
@@ -37,13 +37,14 @@ from ..account_capability_service import (
record_account_commodity_state,
)
from ..business_events import record_account_query, record_douyu_task_started
from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state
from ..douyu_activity_query import activity_client, query_exchange_eligibility
from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches
from ..douyu_elite_status import (
elite_is_currently_open,
normalize_elite_expire_time,
from ..douyu_account_probe import (
CAPABILITY_OK,
config_mapping,
persist_probe_result,
probe_account,
)
from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state
from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches
from ..douyu_service import (
SUPPORTED_DOUYU_TASK_TYPES,
douyu_config_value,
@@ -2195,24 +2196,32 @@ def refresh_exchange_eligibility(
raise HTTPException(status_code=409, detail="账号 CK 不可用")
config = ensure_douyu_config(db)
try:
cookie = str(account.cookie)
client = activity_client(cookie)
eligibility = query_exchange_eligibility(
client,
cookie=cookie,
manual_id=str(douyu_config_value("manual_id", config.manual_id)),
rid=str(douyu_config_value("rid", config.rid)),
uid=str(account.uid or ""),
probe = probe_account(
account,
config_mapping(config),
session_checker=None,
with_elite_role=False,
with_eligibility=True,
)
elite_expire_time = normalize_elite_expire_time(
eligibility.elite_user_info.get("expire_time")
if (probe.get("elite") or {}).get("status") != CAPABILITY_OK:
raise RuntimeError(
(probe.get("errors") or {}).get("elite") or "精英宝典状态查询失败"
)
if "points" in (probe.get("errors") or {}):
raise RuntimeError((probe.get("errors") or {})["points"])
limited_ids = frozenset(
str(item)
for item in (probe.get("eligibility") or {}).get("limited_ids") or []
if str(item)
)
account.elite_opened = elite_is_currently_open(
eligibility.elite_user_info.get("manual_type"),
elite_expire_time,
persist_probe_result(
db,
account,
probe,
current=current,
source="platform.exchange_eligibility",
record_event=True,
)
account.elite_expire_time = elite_expire_time
account.points = eligibility.points
except Exception as exc: # noqa: BLE001 外部接口错误要落成可重试的检查失败
record_account_query(
db,
@@ -2240,7 +2249,7 @@ def refresh_exchange_eligibility(
db.commit()
return get_task_detail(db, task.id)
if task.commodity_id in eligibility.limited_ids:
if task.commodity_id in limited_ids:
task.exchange_status = "limited"
task.issue_code = "commodity_limit_reached"
task.last_error = "该账号已达到此商品兑换上限"
@@ -2262,15 +2271,13 @@ def refresh_exchange_eligibility(
commodity_id=task.commodity_id,
availability=(
AVAILABILITY_LIMITED
if task.commodity_id in eligibility.limited_ids
if task.commodity_id in limited_ids
else AVAILABILITY_AVAILABLE
),
blocking_reason=(
"该账号已达此商品兑换上限"
if task.commodity_id in eligibility.limited_ids
else ""
"该账号已达此商品兑换上限" if task.commodity_id in limited_ids else ""
),
raw_status="1" if task.commodity_id in eligibility.limited_ids else "0",
raw_status="1" if task.commodity_id in limited_ids else "0",
observed_at=_now(),
source="eligibility_check",
scope=task.scope or SCOPE_ELITE,
@@ -2284,7 +2291,7 @@ def refresh_exchange_eligibility(
detail={
"commodity_id": task.commodity_id,
"exchange_status": task.exchange_status,
"limited": task.commodity_id in eligibility.limited_ids,
"limited": task.commodity_id in limited_ids,
"points": account.points,
"elite_opened": account.elite_opened,
},
@@ -2303,7 +2310,7 @@ def refresh_exchange_eligibility(
actor_id=current.id,
detail={
"exchangeStatus": task.exchange_status,
"limitedCount": len(eligibility.limited_ids),
"limitedCount": len(limited_ids),
},
)
_emit_order_site_binding_state(db, task.id)