refactor(douyu): 统一活动查询与直播商品映射
- 收口斗鱼活动、商品、绑定信息和兑换资格查询 - 工作台改为复用统一客户端、快照与实时商品目录 - 补充活动查询与商品映射测试
This commit is contained in:
@@ -0,0 +1,309 @@
|
||||
"""斗鱼活动只读查询的唯一入口。
|
||||
|
||||
账号角色、精英宝典状态、活动商品、积分、限兑商品、鱼翅和官方记录
|
||||
都在这里调用 ``DouyuActivityClient``。业务模块只消费归一化结果,不直接
|
||||
拼接口参数或解析响应,避免工作台、协作台账和任务执行器各自漂移。
|
||||
|
||||
兑换、充值、锁定订单等写操作不在这里实现;它们继续由任务执行器负责。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from core.douyu import DouyuActivityClient
|
||||
from core.douyu.cookie_utils import cookie_value
|
||||
|
||||
from .douyu_goods_service import serialize_goods
|
||||
|
||||
ERROR_MAX_LENGTH = 240
|
||||
|
||||
|
||||
def activity_client(cookie: str = "") -> DouyuActivityClient:
|
||||
"""创建统一活动客户端;空 Cookie 可用于公开商品目录查询。"""
|
||||
return DouyuActivityClient(cookie)
|
||||
|
||||
|
||||
def query_csrf(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
refresh_subscribe: bool = False,
|
||||
) -> str:
|
||||
return client.acf_ccn(refresh_subscribe=refresh_subscribe)
|
||||
|
||||
|
||||
def query_elite_user_info(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
manual_id: str,
|
||||
rid: str = "",
|
||||
) -> dict[str, Any]:
|
||||
return client.elite_user_info(manual_id=manual_id, rid=rid)
|
||||
|
||||
|
||||
def query_bind_info(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
act_alias: str,
|
||||
v2: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
return client.bind_info(act_alias=act_alias, v2=v2)
|
||||
|
||||
|
||||
def query_esports_bind_info(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
act_alias: str,
|
||||
) -> dict[str, Any]:
|
||||
return client.esports_bind_info(act_alias=act_alias)
|
||||
|
||||
|
||||
def query_xpd_bind_info(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
act_alias: str,
|
||||
) -> dict[str, Any]:
|
||||
return client.xpd_bind_info(act_alias=act_alias)
|
||||
|
||||
|
||||
def query_gold_account(client: DouyuActivityClient) -> dict[str, Any]:
|
||||
return client.gold_account()
|
||||
|
||||
|
||||
def query_exchange_balance(client: DouyuActivityClient) -> dict[str, Any]:
|
||||
return client.exchange_balance()
|
||||
|
||||
|
||||
def query_activity_goods(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
manual_id: str,
|
||||
rid: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
result = client.list_goods(manual_id=manual_id, rid=rid)
|
||||
return [dict(item) for item in result.get("goods") or [] if isinstance(item, dict)]
|
||||
|
||||
|
||||
def query_esports_goods_result(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
manual_id: str,
|
||||
rid: str,
|
||||
) -> dict[str, Any]:
|
||||
return client.list_esports_goods(manual_id=manual_id, rid=rid)
|
||||
|
||||
|
||||
def query_esports_goods(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
manual_id: str,
|
||||
rid: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
result = query_esports_goods_result(
|
||||
client,
|
||||
manual_id=manual_id,
|
||||
rid=rid,
|
||||
)
|
||||
return [dict(item) for item in result.get("goods") or [] if isinstance(item, dict)]
|
||||
|
||||
|
||||
def query_points(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
uid: str,
|
||||
ctn: str,
|
||||
) -> dict[str, Any]:
|
||||
return client.query_points(uid=uid, ctn=ctn)
|
||||
|
||||
|
||||
def query_limited_goods_result(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
manual_id: str,
|
||||
rid: str,
|
||||
) -> dict[str, Any]:
|
||||
return client.query_limited_goods(manual_id=manual_id, rid=rid)
|
||||
|
||||
|
||||
def query_limited_goods(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
manual_id: str,
|
||||
rid: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
result = query_limited_goods_result(client, manual_id=manual_id, rid=rid)
|
||||
return [
|
||||
dict(item)
|
||||
for item in result.get("limited_goods") or []
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
|
||||
|
||||
def query_exchange_records_result(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
manual_id: str,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
) -> dict[str, Any]:
|
||||
return client.exchange_records(
|
||||
manual_id=manual_id,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
)
|
||||
|
||||
|
||||
def query_exchange_records(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
manual_id: str,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
) -> list[dict[str, Any]]:
|
||||
result = query_exchange_records_result(
|
||||
client,
|
||||
manual_id=manual_id,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
)
|
||||
return [
|
||||
dict(item) for item in result.get("records") or [] if isinstance(item, dict)
|
||||
]
|
||||
|
||||
|
||||
def query_exchange_orders_result(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
manual_id: str,
|
||||
page: int = 1,
|
||||
page_size: int = 10,
|
||||
) -> dict[str, Any]:
|
||||
return client.exchange_orders(
|
||||
manual_id=manual_id,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
|
||||
def query_exchange_orders(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
manual_id: str,
|
||||
page: int = 1,
|
||||
page_size: int = 10,
|
||||
) -> list[dict[str, Any]]:
|
||||
result = query_exchange_orders_result(
|
||||
client,
|
||||
manual_id=manual_id,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
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
|
||||
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),
|
||||
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,
|
||||
"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",
|
||||
"query_elite_user_info",
|
||||
"query_esports_bind_info",
|
||||
"query_esports_goods",
|
||||
"query_esports_goods_result",
|
||||
"query_exchange_balance",
|
||||
"query_exchange_eligibility",
|
||||
"query_exchange_orders",
|
||||
"query_exchange_orders_result",
|
||||
"query_exchange_records",
|
||||
"query_exchange_records_result",
|
||||
"query_gold_account",
|
||||
"query_limited_goods",
|
||||
"query_limited_goods_result",
|
||||
"query_points",
|
||||
"query_xpd_bind_info",
|
||||
]
|
||||
@@ -35,6 +35,15 @@ from ..models import (
|
||||
)
|
||||
from .audit_service import record_audit
|
||||
from .collab_common import apply_order_visibility, count_archived
|
||||
from .douyu_activity_query import (
|
||||
activity_client,
|
||||
query_account_overview,
|
||||
query_activity_goods,
|
||||
query_elite_user_info,
|
||||
query_exchange_orders,
|
||||
query_exchange_records,
|
||||
query_gold_account,
|
||||
)
|
||||
from .douyu_goods_service import (
|
||||
serialize_live_goods as _serialize_live_goods,
|
||||
)
|
||||
@@ -251,7 +260,7 @@ def _client_for_account(account: Account) -> DouyuActivityClient:
|
||||
cookie = str(account.cookie or "").strip()
|
||||
if not cookie:
|
||||
raise CollabError("该账号没有 CK", code="account_no_cookie")
|
||||
return DouyuActivityClient(cookie)
|
||||
return activity_client(cookie)
|
||||
|
||||
|
||||
def serialize_live_goods(goods: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
@@ -279,35 +288,27 @@ def _probe_with_client(
|
||||
}
|
||||
|
||||
active_client = client or _client_for_account(account)
|
||||
errors: list[str] = []
|
||||
elite: dict[str, Any] = {}
|
||||
bind: dict[str, Any] = {}
|
||||
gold: dict[str, Any] = {}
|
||||
goods: list[dict[str, Any]] = []
|
||||
|
||||
try:
|
||||
elite = active_client.elite_user_info(manual_id=manual_id, rid=rid)
|
||||
except Exception as exc: # noqa: BLE001 - 外部接口边界
|
||||
errors.append(f"手册状态: {exc}")
|
||||
|
||||
try:
|
||||
bind = active_client.bind_info(act_alias=act_alias)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"绑定角色: {exc}")
|
||||
|
||||
try:
|
||||
gold = active_client.gold_account()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"鱼翅余额: {exc}")
|
||||
|
||||
if with_goods:
|
||||
try:
|
||||
goods = (
|
||||
active_client.list_goods(manual_id=manual_id, rid=rid).get("goods")
|
||||
or []
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"活动商品: {exc}")
|
||||
overview = query_account_overview(
|
||||
active_client,
|
||||
manual_id=manual_id,
|
||||
rid=rid,
|
||||
act_alias=act_alias,
|
||||
with_goods=with_goods,
|
||||
)
|
||||
elite = overview["elite"]
|
||||
bind = overview["bind"]
|
||||
gold = overview["gold"]
|
||||
goods = overview["serialized_goods"]
|
||||
error_labels = {
|
||||
"elite": "手册状态",
|
||||
"bind": "绑定角色",
|
||||
"gold": "鱼翅余额",
|
||||
"goods": "活动商品",
|
||||
}
|
||||
errors = [
|
||||
f"{error_labels.get(key, key)}: {value}"
|
||||
for key, value in overview["errors"].items()
|
||||
]
|
||||
|
||||
manual_type = _to_int(elite.get("manual_type"))
|
||||
manual_score = _to_int(elite.get("manual_score"))
|
||||
@@ -343,7 +344,7 @@ def _probe_with_client(
|
||||
"bind_game_role": bind_role,
|
||||
"bind_game_channel": bind_channel,
|
||||
"fish_fin_balance": _to_int(gold.get("gold")),
|
||||
"goods": serialize_live_goods(goods),
|
||||
"goods": goods,
|
||||
"goods_count": len(goods),
|
||||
}
|
||||
|
||||
@@ -1121,31 +1122,33 @@ def query_activity(
|
||||
records: list[dict[str, Any]] = []
|
||||
orders: list[dict[str, Any]] = []
|
||||
try:
|
||||
elite = active_client.elite_user_info(
|
||||
manual_id=str(config.manual_id or ""), rid=str(config.rid or "")
|
||||
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 = active_client.gold_account()
|
||||
gold = query_gold_account(active_client)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"鱼翅: {exc}")
|
||||
if include_records:
|
||||
try:
|
||||
records = (
|
||||
active_client.exchange_records(
|
||||
manual_id=str(config.manual_id or ""), limit=100, offset=0
|
||||
).get("records")
|
||||
or []
|
||||
records = query_exchange_records(
|
||||
active_client,
|
||||
manual_id=str(config.manual_id or ""),
|
||||
limit=100,
|
||||
offset=0,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"兑换记录: {exc}")
|
||||
try:
|
||||
orders = (
|
||||
active_client.exchange_orders(
|
||||
manual_id=str(config.manual_id or ""), page=1, page_size=10
|
||||
).get("orders")
|
||||
or []
|
||||
orders = query_exchange_orders(
|
||||
active_client,
|
||||
manual_id=str(config.manual_id or ""),
|
||||
page=1,
|
||||
page_size=10,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"锁单: {exc}")
|
||||
@@ -1634,10 +1637,9 @@ def refresh_activity_goods(
|
||||
if account is None:
|
||||
raise CollabError("没有带 CK 的斗鱼账号,无法刷新活动商品", code="no_account")
|
||||
active_client = client or _client_for_account(account)
|
||||
result = active_client.list_goods(
|
||||
manual_id=str(config.manual_id or ""), rid=str(config.rid or "")
|
||||
goods = query_activity_goods(
|
||||
active_client, manual_id=str(config.manual_id or ""), rid=str(config.rid or "")
|
||||
)
|
||||
goods = result.get("goods") or []
|
||||
upsert_goods_snapshot(db, goods, commit=False)
|
||||
record_audit(
|
||||
db,
|
||||
@@ -2226,6 +2228,7 @@ def export_cks(
|
||||
)
|
||||
continue
|
||||
|
||||
assert account is not None
|
||||
ck_status = str(account.ck_check_status or "")
|
||||
items.append(
|
||||
{
|
||||
|
||||
@@ -20,6 +20,7 @@ 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
|
||||
|
||||
DOUYU_LEGACY_BIND_ACT_ALIAS = "20250213NQCYX"
|
||||
DOUYU_BIND_ROLE_POLL_SECONDS = 65
|
||||
@@ -277,7 +278,7 @@ class BindMixin:
|
||||
act_alias: str,
|
||||
) -> dict:
|
||||
"""查询电竞手册活动状态,接口同时返回当前角色和换绑冷却信息。"""
|
||||
activity_info = client.esports_bind_info(act_alias)
|
||||
activity_info = query_esports_bind_info(client, act_alias=act_alias)
|
||||
activity_snapshot = self._bind_snapshot(activity_info)
|
||||
esports_bound = activity_snapshot["is_bound_act"]
|
||||
has_selected_role = bool(activity_snapshot["role_name"])
|
||||
@@ -322,7 +323,7 @@ class BindMixin:
|
||||
if not alias:
|
||||
continue
|
||||
try:
|
||||
info = client.bind_info(alias, v2=True)
|
||||
info = query_bind_info(client, act_alias=alias, v2=True)
|
||||
except DouyuActivityError as exc:
|
||||
self._push_log("warning", f"查询绑定信息失败 act={alias}: {exc}")
|
||||
continue
|
||||
|
||||
@@ -11,6 +11,7 @@ from core.douyu import DouyuActivityClient
|
||||
|
||||
from ..models import Account, DouyuTask
|
||||
from .business_events import record_gold_spent, record_points_credit
|
||||
from .douyu_activity_query import query_csrf
|
||||
|
||||
DOUYU_GIFT_POINTS_REFRESH_TIMES = 3
|
||||
DOUYU_GIFT_POINTS_REFRESH_INTERVAL = 2
|
||||
@@ -262,7 +263,7 @@ class DonateMixin:
|
||||
ctn = None
|
||||
baseline_points = account.points
|
||||
try:
|
||||
ctn = client.acf_ccn(refresh_subscribe=False)
|
||||
ctn = query_csrf(client)
|
||||
baseline_result = self._refresh_account_points(
|
||||
client, account, cookie, ctn=ctn
|
||||
)
|
||||
|
||||
@@ -19,6 +19,7 @@ from core.douyu import (
|
||||
|
||||
from ..models import Account, DouyuTask
|
||||
from .business_events import record_recharge
|
||||
from .douyu_activity_query import query_exchange_balance, query_gold_account
|
||||
from .douyu_runner_core import DOUYU_PAYMENT_POLL_INTERVAL, DOUYU_PAYMENT_POLL_SECONDS
|
||||
from .douyu_service import update_account_profile_from_cookie
|
||||
|
||||
@@ -42,8 +43,8 @@ class GoldMixin:
|
||||
self, client: DouyuActivityClient, account: Account
|
||||
) -> dict:
|
||||
"""刷新鱼翅和钱包兑换余额并写回账号表。"""
|
||||
gold = client.gold_account()
|
||||
exchange = client.exchange_balance()
|
||||
gold = query_gold_account(client)
|
||||
exchange = query_exchange_balance(client)
|
||||
account.gold_balance = self._to_int(gold.get("gold"))
|
||||
account.exchange_balance = self._to_int(exchange.get("count"))
|
||||
account.updated_at = datetime.now(UTC)
|
||||
|
||||
@@ -13,6 +13,14 @@ from core.douyu import DouyuActivityClient, DouyuActivityError
|
||||
|
||||
from ..models import Account, DouyuEsportsGoodsSnapshot, DouyuGoodsSnapshot, DouyuTask
|
||||
from .business_events import record_exchange
|
||||
from .douyu_activity_query import (
|
||||
query_activity_goods,
|
||||
query_csrf,
|
||||
query_elite_user_info,
|
||||
query_esports_goods_result,
|
||||
query_exchange_records_result,
|
||||
query_limited_goods_result,
|
||||
)
|
||||
from .high_value_service import (
|
||||
DEFAULT_HIGH_VALUE_GOODS,
|
||||
HIGH_VALUE_STATUS_OWNED,
|
||||
@@ -70,8 +78,11 @@ class GoodsMixin:
|
||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||
):
|
||||
client = self._client(cookie)
|
||||
result = client.list_goods(manual_id=config["manual_id"], rid=config["rid"])
|
||||
goods = result["goods"]
|
||||
goods = query_activity_goods(
|
||||
client,
|
||||
manual_id=str(config["manual_id"]),
|
||||
rid=str(config["rid"]),
|
||||
)
|
||||
self._upsert_goods(db, goods)
|
||||
high_value_goods = extract_high_value_goods(goods, DEFAULT_HIGH_VALUE_GOODS, [])
|
||||
apply_high_value_goods(account, high_value_goods)
|
||||
@@ -99,7 +110,7 @@ class GoodsMixin:
|
||||
) -> None:
|
||||
"""兑换成功后立即刷新官方准入;失败时只标记本次已换套装。"""
|
||||
try:
|
||||
goods = client.list_goods(manual_id=manual_id, rid=rid).get("goods") or []
|
||||
goods = query_activity_goods(client, manual_id=manual_id, rid=rid)
|
||||
evaluated = extract_high_value_goods(goods, DEFAULT_HIGH_VALUE_GOODS, [])
|
||||
apply_high_value_goods(account, evaluated)
|
||||
key = high_value_key(commodity_name)
|
||||
@@ -132,7 +143,8 @@ class GoodsMixin:
|
||||
):
|
||||
"""刷新电竞手册皮肤商城快照。"""
|
||||
client = self._client(cookie)
|
||||
result = client.list_esports_goods(
|
||||
result = query_esports_goods_result(
|
||||
client,
|
||||
manual_id=str(config["esports_manual_id"]),
|
||||
rid=str(config["room_id"]),
|
||||
)
|
||||
@@ -243,7 +255,7 @@ class GoodsMixin:
|
||||
or f"#{account.id}",
|
||||
}
|
||||
try:
|
||||
ctn = client.acf_ccn(refresh_subscribe=False)
|
||||
ctn = query_csrf(client)
|
||||
result.update(
|
||||
self._refresh_account_points(client, account, cookie, ctn=ctn)
|
||||
)
|
||||
@@ -356,7 +368,7 @@ class GoodsMixin:
|
||||
# ---- 对齐浏览器:先查手册状态 + 商品详情,按页面状态机选兑换链路 ----
|
||||
manual_type = None
|
||||
try:
|
||||
user_info = client.elite_user_info(manual_id=manual_id, rid=rid)
|
||||
user_info = query_elite_user_info(client, manual_id=manual_id, rid=rid)
|
||||
manual_type = user_info.get("manual_type")
|
||||
except DouyuActivityError as exc:
|
||||
self._push_log("warning", f"查询手册状态失败,按经典流程继续: {exc}")
|
||||
@@ -554,7 +566,7 @@ class GoodsMixin:
|
||||
# 兑换成功后自动刷新积分,更新账号最新积分信息(失败不阻断兑换成功)
|
||||
points_refresh = None
|
||||
try:
|
||||
ctn = client.acf_ccn(refresh_subscribe=False)
|
||||
ctn = query_csrf(client)
|
||||
points_refresh = self._refresh_account_points(
|
||||
client, account, cookie, ctn=ctn
|
||||
)
|
||||
@@ -704,8 +716,8 @@ class GoodsMixin:
|
||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||
):
|
||||
client = self._client(cookie)
|
||||
result = client.query_limited_goods(
|
||||
manual_id=str(config["manual_id"]), rid=str(config["rid"])
|
||||
result = query_limited_goods_result(
|
||||
client, manual_id=str(config["manual_id"]), rid=str(config["rid"])
|
||||
)
|
||||
limited = result["limited_goods"]
|
||||
goods = (result.get("raw") or {}).get("data", {}).get("list") or []
|
||||
@@ -738,8 +750,13 @@ class GoodsMixin:
|
||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||
):
|
||||
client = self._client(cookie)
|
||||
result = client.exchange_records(manual_id=str(config["manual_id"]))
|
||||
records = result["records"]
|
||||
result = query_exchange_records_result(
|
||||
client,
|
||||
manual_id=str(config["manual_id"]),
|
||||
limit=100,
|
||||
offset=0,
|
||||
)
|
||||
records = result.get("records") or []
|
||||
account.updated_at = datetime.now(UTC)
|
||||
self._mark_task(
|
||||
db,
|
||||
|
||||
@@ -12,6 +12,7 @@ from core.douyu import DouyuActivityClient, DouyuActivityError
|
||||
|
||||
from ..models import Account, DouyuTask
|
||||
from .account_events_service import EVENT_ELITE_OPENED, EVENT_ESPORTS_OPENED, emit
|
||||
from .douyu_activity_query import query_csrf, query_elite_user_info, query_points
|
||||
from .douyu_runner_core import DOUYU_PAYMENT_POLL_INTERVAL, DOUYU_PAYMENT_POLL_SECONDS
|
||||
from .douyu_service import account_uid, update_account_profile_from_cookie
|
||||
|
||||
@@ -49,8 +50,8 @@ class ManualMixin:
|
||||
uid = account_uid(account, cookie)
|
||||
if not uid:
|
||||
raise DouyuActivityError("Cookie 中没有 acf_uid,无法查询积分")
|
||||
ctn_value = ctn or client.acf_ccn(refresh_subscribe=False)
|
||||
result = client.query_points(uid=uid, ctn=ctn_value)
|
||||
ctn_value = ctn or query_csrf(client)
|
||||
result = query_points(client, uid=uid, ctn=ctn_value)
|
||||
points = self._to_int(result.get("points"))
|
||||
account.uid = uid
|
||||
account.points = points
|
||||
@@ -79,7 +80,7 @@ class ManualMixin:
|
||||
积分区分不了「开通后积分花完」和「从未开通」,manualType 才是权威口径:
|
||||
0=未开通,>=1=已开通。
|
||||
"""
|
||||
result = client.elite_user_info(manual_id=manual_id, rid=rid)
|
||||
result = query_elite_user_info(client, manual_id=manual_id, rid=rid)
|
||||
manual_type = self._to_int(result.get("manual_type")) or 0
|
||||
manual_score = self._to_int(result.get("manual_score"))
|
||||
expire_time = self._to_int(result.get("expire_time")) or 0
|
||||
@@ -211,9 +212,7 @@ class ManualMixin:
|
||||
account.esports_opened = manual_type is not None and manual_type >= 1
|
||||
# 到期时间也落库 —— 否则界面只能显示"已开通",看不到什么时候到期
|
||||
expire_raw = result.get("expire_time")
|
||||
expire_int = (
|
||||
int(expire_raw) if str(expire_raw or "").strip().isdigit() else None
|
||||
)
|
||||
expire_int = self._to_int(expire_raw)
|
||||
# ⚠️ 斗鱼用 0 表示「没有到期时间」。直接存 0 的话界面会显示 1970/1/1
|
||||
# (这个坑在积分到期上踩过一次,这里别再踩)。
|
||||
account.esports_expire_time = (
|
||||
@@ -306,7 +305,7 @@ class ManualMixin:
|
||||
client = self._client(cookie)
|
||||
ctn = str(self._task_payload(task).get("ctn") or "")
|
||||
if not ctn:
|
||||
ctn = client.acf_ccn(refresh_subscribe=True)
|
||||
ctn = query_csrf(client, refresh_subscribe=True)
|
||||
act_alias = self._confirm_act_alias(config) or self._bind_qr_act_alias(config)
|
||||
if not act_alias:
|
||||
self._mark_task(db, task, "failed", "请先配置开通宝典活动 actAlias")
|
||||
@@ -435,7 +434,7 @@ class ManualMixin:
|
||||
client = self._client(cookie)
|
||||
ctn = str(self._task_payload(task).get("ctn") or "")
|
||||
if not ctn:
|
||||
ctn = client.acf_ccn(refresh_subscribe=True)
|
||||
ctn = query_csrf(client, refresh_subscribe=True)
|
||||
act_alias = str(config.get("esports_act_alias") or "").strip()
|
||||
manual_id = str(config.get("esports_manual_id") or "").strip()
|
||||
if not act_alias or not manual_id:
|
||||
@@ -561,7 +560,7 @@ class ManualMixin:
|
||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||
):
|
||||
client = self._client(cookie)
|
||||
ctn = client.acf_ccn(refresh_subscribe=False)
|
||||
ctn = query_csrf(client)
|
||||
result = self._refresh_account_points(client, account, cookie, ctn=ctn)
|
||||
account.updated_at = datetime.now(UTC)
|
||||
points = result["points"]
|
||||
|
||||
@@ -35,6 +35,14 @@ from core.douyu import DouyuActivityClient
|
||||
from ..models import Account, DouyuTask
|
||||
from .account_binding import derive_from_bind_info, set_bind_status
|
||||
from .business_events import record_official_exchange
|
||||
from .douyu_activity_query import (
|
||||
query_activity_goods,
|
||||
query_bind_info,
|
||||
query_csrf,
|
||||
query_esports_bind_info,
|
||||
query_exchange_records,
|
||||
query_xpd_bind_info,
|
||||
)
|
||||
from .douyu_runner_donate import _parse_expire_at, _points_expire_at
|
||||
from .high_value_service import (
|
||||
DEFAULT_HIGH_VALUE_GOODS,
|
||||
@@ -189,10 +197,10 @@ class OverviewMixin:
|
||||
) -> dict[str, Any]:
|
||||
"""按作用域查绑定信息(三个接口不同,收敛在一处)。"""
|
||||
if scope == "elite":
|
||||
return client.bind_info(alias)
|
||||
return query_bind_info(client, act_alias=alias)
|
||||
if scope == "esports":
|
||||
return client.esports_bind_info(alias)
|
||||
return client.xpd_bind_info(act_alias=alias)
|
||||
return query_esports_bind_info(client, act_alias=alias)
|
||||
return query_xpd_bind_info(client, act_alias=alias)
|
||||
|
||||
def _fetch_elite_records(
|
||||
self,
|
||||
@@ -201,11 +209,10 @@ class OverviewMixin:
|
||||
manual_id: str,
|
||||
esports_manual_id: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
return (
|
||||
client.exchange_records(
|
||||
manual_id=manual_id, limit=EXCHANGE_RECORD_LIMIT
|
||||
).get("records")
|
||||
or []
|
||||
return query_exchange_records(
|
||||
client,
|
||||
manual_id=manual_id,
|
||||
limit=EXCHANGE_RECORD_LIMIT,
|
||||
)
|
||||
|
||||
def _fetch_esports_records(
|
||||
@@ -215,11 +222,10 @@ class OverviewMixin:
|
||||
manual_id: str,
|
||||
esports_manual_id: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
return (
|
||||
client.exchange_records(
|
||||
manual_id=esports_manual_id, limit=EXCHANGE_RECORD_LIMIT
|
||||
).get("records")
|
||||
or []
|
||||
return query_exchange_records(
|
||||
client,
|
||||
manual_id=esports_manual_id,
|
||||
limit=EXCHANGE_RECORD_LIMIT,
|
||||
)
|
||||
|
||||
def _fetch_xpd_records(
|
||||
@@ -281,7 +287,7 @@ class OverviewMixin:
|
||||
|
||||
# ---- 积分 + 到期时间 ----
|
||||
try:
|
||||
ctn = client.acf_ccn(refresh_subscribe=False)
|
||||
ctn = query_csrf(client)
|
||||
points = self._refresh_account_points(client, account, cookie, ctn=ctn)
|
||||
overview["assets"]["points"] = points.get("points")
|
||||
# `_refresh_account_points` 只回 {"points", "points_query"},
|
||||
@@ -349,8 +355,7 @@ class OverviewMixin:
|
||||
goods_items: list[dict[str, Any]] = []
|
||||
try:
|
||||
# 🎯 拉取完整商城商品列表(含每个商品准确的 status 状态:1=已达兑换上限,0=可兑换)
|
||||
goods = client.list_goods(manual_id=manual_id, rid=rid)
|
||||
goods_items = goods.get("goods") or []
|
||||
goods_items = query_activity_goods(client, manual_id=manual_id, rid=rid)
|
||||
overview["limited_goods_total"] = len(goods_items)
|
||||
goods_query_ok = True
|
||||
except Exception as exc: # noqa: BLE001
|
||||
|
||||
@@ -19,6 +19,7 @@ from .account_binding import (
|
||||
set_bind_status,
|
||||
)
|
||||
from .business_events import record_exchange
|
||||
from .douyu_activity_query import query_xpd_bind_info
|
||||
|
||||
DOUYU_XPD_BIND_POLL_SECONDS = 300
|
||||
DOUYU_XPD_BIND_POLL_INTERVAL = 5
|
||||
@@ -138,7 +139,7 @@ class XpdMixin:
|
||||
db.commit()
|
||||
# 记录绑定前状态:已绑定账号生成二维码后必须等扫码换绑,不能立即成功
|
||||
try:
|
||||
before = client.xpd_bind_info(act_alias=act_alias)
|
||||
before = query_xpd_bind_info(client, act_alias=act_alias)
|
||||
result["before_bound"] = bool(before.get("bind_role"))
|
||||
result["before_role_name"] = str(before.get("role_name") or "")
|
||||
result["before_area_name"] = str(before.get("area_name") or "")
|
||||
@@ -193,7 +194,7 @@ class XpdMixin:
|
||||
poll_count = 0
|
||||
while not self._stop.is_set() and time.monotonic() <= deadline:
|
||||
try:
|
||||
info = client.xpd_bind_info(act_alias=act_alias)
|
||||
info = query_xpd_bind_info(client, act_alias=act_alias)
|
||||
poll_count += 1
|
||||
result["bind_poll_count"] = poll_count
|
||||
result["bind_polling"] = True
|
||||
@@ -246,7 +247,7 @@ class XpdMixin:
|
||||
if not act_alias:
|
||||
self._mark_task(db, task, "failed", "请先配置小店活动代号 actAlias")
|
||||
return
|
||||
result = client.xpd_bind_info(act_alias=act_alias)
|
||||
result = query_xpd_bind_info(client, act_alias=act_alias)
|
||||
role_name = str(result.get("role_name") or "")
|
||||
if not result.get("bind_role") or not role_name:
|
||||
set_bind_status(account, SCOPE_PEACE, BIND_UNBOUND)
|
||||
@@ -294,7 +295,7 @@ class XpdMixin:
|
||||
if not act_alias:
|
||||
self._mark_task(db, task, "failed", "请先配置小店活动代号 actAlias")
|
||||
return
|
||||
result = client.xpd_bind_info(act_alias=act_alias)
|
||||
result = query_xpd_bind_info(client, act_alias=act_alias)
|
||||
status = "已绑定" if result.get("bind_role") else "未绑定"
|
||||
text = str(result.get("role_name") or result.get("nick") or "-")
|
||||
self._mark_task(
|
||||
|
||||
@@ -10,8 +10,7 @@ from fastapi import HTTPException
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.douyu import DouyuActivityClient, DouyuActivityError
|
||||
from core.douyu.cookie_utils import cookie_value
|
||||
from core.douyu import DouyuActivityError
|
||||
|
||||
from ...models import (
|
||||
Account,
|
||||
@@ -23,6 +22,7 @@ from ...models import (
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
)
|
||||
from ..douyu_activity_query import activity_client, query_exchange_eligibility
|
||||
from ..douyu_batch_launcher import start_douyu_batch
|
||||
from ..douyu_service import douyu_config_value, ensure_douyu_config
|
||||
from ..external_order_source import (
|
||||
@@ -103,9 +103,11 @@ def _append_event(
|
||||
|
||||
|
||||
def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask:
|
||||
task = db.query(PlatformFulfillmentTask).filter(
|
||||
PlatformFulfillmentTask.id == int(task_id)
|
||||
).first()
|
||||
task = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.filter(PlatformFulfillmentTask.id == int(task_id))
|
||||
.first()
|
||||
)
|
||||
if task is None:
|
||||
raise HTTPException(status_code=404, detail="直播账号履约任务不存在")
|
||||
return task
|
||||
@@ -339,9 +341,7 @@ def _task_out(
|
||||
"areaName": str(bind_result.get("area_name") or ""),
|
||||
"platName": str(bind_result.get("plat_name") or ""),
|
||||
"bindPhase": str(bind_result.get("bind_phase") or ""),
|
||||
"bindReadyForConfirm": bool(
|
||||
bind_result.get("bind_ready_for_confirm")
|
||||
),
|
||||
"bindReadyForConfirm": bool(bind_result.get("bind_ready_for_confirm")),
|
||||
"bindConfirmed": bool(bind_result.get("bind_confirmed")),
|
||||
}
|
||||
if bind_task
|
||||
@@ -474,12 +474,12 @@ def upsert_mapping(
|
||||
detail={"commodityId": row.commodity_id, "enabled": row.enabled},
|
||||
)
|
||||
db.commit()
|
||||
return next(item for item in list_mappings(db, keyword=sku_key) if item["id"] == row.id)
|
||||
return next(
|
||||
item for item in list_mappings(db, keyword=sku_key) if item["id"] == row.id
|
||||
)
|
||||
|
||||
|
||||
def allocate_task(
|
||||
db: Session, *, task_id: int, current: User
|
||||
) -> dict[str, Any]:
|
||||
def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]:
|
||||
task = _load_task(db, task_id)
|
||||
if task.execution_status in {"completed", "cancelled"}:
|
||||
raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号")
|
||||
@@ -579,9 +579,7 @@ def release_task_account(
|
||||
return get_task_detail(db, task.id)
|
||||
|
||||
|
||||
async def start_binding(
|
||||
db: Session, *, task_id: int, current: User
|
||||
) -> dict[str, Any]:
|
||||
async def start_binding(db: Session, *, task_id: int, current: User) -> dict[str, Any]:
|
||||
task = _load_task(db, task_id)
|
||||
if not task.account_id or not task.lease_id:
|
||||
raise HTTPException(status_code=409, detail="请先分配账号")
|
||||
@@ -728,21 +726,17 @@ def refresh_exchange_eligibility(
|
||||
raise HTTPException(status_code=409, detail="账号 CK 不可用")
|
||||
config = ensure_douyu_config(db)
|
||||
try:
|
||||
client = DouyuActivityClient(cookie=str(account.cookie))
|
||||
ctn = client.acf_ccn(refresh_subscribe=False)
|
||||
user_info = client.elite_user_info(
|
||||
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 ""),
|
||||
)
|
||||
account.elite_opened = bool(user_info.get("manual_type"))
|
||||
uid = account.uid or cookie_value(str(account.cookie), "acf_uid")
|
||||
points_result = client.query_points(uid=uid, ctn=ctn)
|
||||
account.points = int(points_result.get("points") or 0)
|
||||
result = client.query_limited_goods(
|
||||
manual_id=str(douyu_config_value("manual_id", config.manual_id)),
|
||||
rid=str(douyu_config_value("rid", config.rid)),
|
||||
)
|
||||
limited = result.get("limited_goods") or []
|
||||
account.elite_opened = bool(eligibility.elite_user_info.get("manual_type"))
|
||||
account.points = eligibility.points
|
||||
except DouyuActivityError as exc:
|
||||
task.execution_status = "manual_required"
|
||||
task.exchange_status = "check_failed"
|
||||
@@ -760,13 +754,7 @@ def refresh_exchange_eligibility(
|
||||
db.commit()
|
||||
return get_task_detail(db, task.id)
|
||||
|
||||
limited_ids = {
|
||||
str(item.get("commodityId") or item.get("commodity_id") or "")
|
||||
for item in limited
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
limited_ids.discard("")
|
||||
if task.commodity_id in limited_ids:
|
||||
if task.commodity_id in eligibility.limited_ids:
|
||||
task.exchange_status = "limited"
|
||||
task.issue_code = "commodity_limit_reached"
|
||||
task.last_error = "该账号已达到此商品兑换上限"
|
||||
@@ -795,7 +783,7 @@ def refresh_exchange_eligibility(
|
||||
actor_id=current.id,
|
||||
detail={
|
||||
"exchangeStatus": task.exchange_status,
|
||||
"limitedCount": len(limited_ids),
|
||||
"limitedCount": len(eligibility.limited_ids),
|
||||
},
|
||||
)
|
||||
db.commit()
|
||||
|
||||
Reference in New Issue
Block a user