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:
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user