"""一键查询:把账号的关键信息一次性从斗鱼官方拉全并汇总。 ## 定位 一个**只读**聚合任务:鱼翅 / 积分(含到期时间)/ 精英宝典 / 电竞手册 / 小店 / 官方兑换记录 / **限兑商品(重点看高价值套装是否已拥有)**。 查询结果会投影成账号当前状态和商品能力,但不会制造兑换等业务事实。 任务本身由执行器统一写入 `activity` 时间线;轮询过程不逐次刷事件。 ## 为什么「是否已拥有」能直接查官方 `storehome` 商品项里的账号级 `status`(0=可兑换、1=已达上限)才是唯一判据。 `count` / `foreverCount` / `storeStatus` 是全局库存或商店状态,不能拿来判断 当前账号是否已经兑换。 ## 诚实边界 **单项失败不整体失败**:账号没绑电竞手册是常态,不该让整次查询失败。 失败写进 `errors[项]`,并在 UI 如实展示 —— 避免「没查到」被误读成「没有」。 """ from __future__ import annotations import json import os from datetime import UTC, datetime, timedelta from typing import TYPE_CHECKING, Any from loguru import logger from sqlalchemy.orm import Session from core.douyu import DouyuActivityClient from ..models import Account, AccountCommodityState, AccountSyncState, DouyuTask from .account_exchange_sync_service import persist_official_exchange_records from .account_sync_runner import ( WORK_ELITE_SYNC, WORK_ESPORTS_SYNC, WORK_EXCHANGE_RECORDS_SYNC, WORK_GOLD_SYNC, WORK_POINTS_SYNC, WORK_ROLE_SYNC, WORK_STOREHOME_SYNC, ) from .account_sync_service import ( DOMAIN_ELITE, DOMAIN_ESPORTS, DOMAIN_EXCHANGE_RECORDS, DOMAIN_GOLD, DOMAIN_POINTS, DOMAIN_ROLE, DOMAIN_STOREHOME, get_sync_state, is_domain_fresh, record_sync_success, sync_storehome_snapshot, ) from .account_work_queue import enqueue_account_work 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_result, query_csrf, query_esports_bind_info, query_exchange_records, query_xpd_bind_info, query_xpd_embed, ) from .douyu_read_gateway import StorehomeSnapshot, storehome_snapshot_from_result from .douyu_runner_donate import _parse_expire_at, _points_expire_at from .high_value_service import ( DEFAULT_HIGH_VALUE_GOODS, apply_high_value_goods, extract_high_value_goods, ) #: 官方兑换记录单次抓取上限。能力匹配需要更完整的一年记录,详情页只展示前 20 条。 EXCHANGE_RECORD_FETCH_LIMIT = 100 EXCHANGE_RECORD_DISPLAY_LIMIT = 20 DEFAULT_OVERVIEW_CACHE_SECONDS = 10 * 60 #: 单项错误的摘要长度(避免把整个 traceback 塞进 task.result) _ERROR_MAX = 200 def _err(exc: BaseException) -> str: return f"{type(exc).__name__}: {exc}"[:_ERROR_MAX] def _positive_env_int(name: str, default: int) -> int: try: value = int(os.getenv(name, str(default))) except ValueError: return default return value if value > 0 else default def _overview_cache_seconds() -> int: return _positive_env_int( "DOUYU_OVERVIEW_CACHE_SECONDS", DEFAULT_OVERVIEW_CACHE_SECONDS, ) def _group_by_scope( pairs: list[tuple[str, dict[str, Any]]], ) -> dict[str, list[dict[str, Any]]]: """把 (作用域, 记录) 扁平列表按作用域分组。""" grouped: dict[str, list[dict[str, Any]]] = {} for scope, rec in pairs: grouped.setdefault(scope, []).append(rec) return grouped def _overview_success_message( snapshot: dict[str, Any], errors: dict[str, Any], *, view: str = "", ) -> str: if view == "limited_goods": goods = [ str(item.get("commodityName") or item.get("name") or "") for item in (snapshot.get("limited_goods") or []) if isinstance(item, dict) ] names = [name for name in goods if name] message = ( "无受限商品(均可兑换)" if not names else f"已达上限 {len(names)} 个: {', '.join(names[:5])}" ) if errors.get("limited_goods"): message += f"({errors['limited_goods']})" return message owned = [ g["name"] for g in (snapshot.get("high_value_goods") or []) if isinstance(g, dict) and not g.get("missing") and g.get("owned") ] message = f"一键查询完成;高价值套装已拥有 {len(owned)} 个" if owned: message += f": {', '.join(owned)}" if errors: message += f"({len(errors)} 项未取到)" return message def _goods_config(config: dict) -> list[str]: """高价值商品名单:优先用配置,非法/为空则回落默认。""" raw = config.get("high_value_goods") if isinstance(raw, str) and raw.strip(): try: raw = json.loads(raw) except ValueError: raw = [p for p in raw.replace(",", ",").split(",") if p.strip()] if isinstance(raw, (list, tuple)): cleaned = [str(x).strip() for x in raw if str(x).strip()] if cleaned: return cleaned return list(DEFAULT_HIGH_VALUE_GOODS) def _ts(value: Any) -> Any: """斗鱼用 `0` / `"0"` / 空串表示「没有这个时间」。 直接透传的后果:前端把 `0` 当 Unix 时间戳 → 显示成 **1970/1/1 08:00:00**, 运营看到会以为"到期时间是 1970 年"。所以在这里就归成 `None`, 让「没有」和「有一个很早的时间」区分得开。 """ if value is None: return None if isinstance(value, bool): return None if isinstance(value, (int, float)): return None if int(value) <= 0 else value text = str(value).strip() if not text: return None if text.lstrip("-").isdigit() and int(text) <= 0: return None return value class OverviewMixin: """一键查询域:读取官方数据并投影到账号当前状态。""" if TYPE_CHECKING: def _client(self, cookie: str) -> DouyuActivityClient: ... def _mark_task(self, *args: Any, **kwargs: Any) -> None: ... def _push_log(self, level: str, message: str) -> None: ... def _overview_view(self, task: DouyuTask) -> str: result = task.result if isinstance(task.result, dict) else {} payload_raw = result.get("payload") payload = payload_raw if isinstance(payload_raw, dict) else {} runtime_payload = getattr(self, "payload", None) if isinstance(runtime_payload, dict): payload = {**payload, **runtime_payload} return str(payload.get("view") or "").strip() def _refresh_account_gold_balance( self, client: DouyuActivityClient, account: Account ) -> dict: ... def _refresh_account_points( self, client: DouyuActivityClient, account: Account, cookie: str, *, ctn: str = "", ) -> dict: ... def _refresh_elite_handbook( self, client: DouyuActivityClient, account: Account, *, manual_id: str, rid: str = "", ) -> dict: ... def _refresh_esports_handbook( self, client: DouyuActivityClient, account: Account, *, manual_id: str ) -> dict: ... # ---- 三个作用域的官方兑换记录抓取 ---- # # 精英宝典 / 电竞手册 共用 `exchange_records`(只有 manual_id 不同); # 和平小店是另一套(道聚城短时授权 + 购买记录)。 @staticmethod def _scope_configured( scope: str, manual_id: str, esports_manual_id: str, config: dict ) -> bool: if scope == "elite": return bool(manual_id) if scope == "esports": return bool(esports_manual_id) return all( str(config.get(k) or "").strip() for k in ("xpd_act_alias", "xpd_rid", "xpd_act_id") ) def _fetch_bind_info( self, client: DouyuActivityClient, scope: str, alias: str ) -> dict[str, Any]: """按作用域查绑定信息(三个接口不同,收敛在一处)。""" if scope == "elite": 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) def _fetch_elite_records( self, client: DouyuActivityClient, config: dict, manual_id: str, esports_manual_id: str, ) -> list[dict[str, Any]]: return query_exchange_records( client, manual_id=manual_id, limit=EXCHANGE_RECORD_FETCH_LIMIT, ) def _fetch_esports_records( self, client: DouyuActivityClient, config: dict, manual_id: str, esports_manual_id: str, ) -> list[dict[str, Any]]: return query_exchange_records( client, manual_id=esports_manual_id, limit=EXCHANGE_RECORD_FETCH_LIMIT, ) def _fetch_xpd_records( self, client: DouyuActivityClient, config: dict, manual_id: str, esports_manual_id: str, ) -> list[dict[str, Any]]: """和平小店:先要一次性短时授权,再查购买记录。""" embed = query_xpd_embed( client, act_alias=str(config["xpd_act_alias"]), rid=str(config["xpd_rid"]), ) return ( client.xpd_purchase_records( embed_query=embed["query"], act_id=str(config["xpd_act_id"]), ).get("records") or [] ) @staticmethod def _load_storehome_items( db: Session, account: Account, *, fresh_only: bool, now: datetime, ) -> list[dict[str, Any]]: query = db.query(AccountCommodityState).filter( AccountCommodityState.account_id == account.id, AccountCommodityState.platform == "douyu", AccountCommodityState.scope == "elite", AccountCommodityState.observed_at.isnot(None), AccountCommodityState.raw_json.isnot(None), ) if fresh_only: query = query.filter( AccountCommodityState.valid_until.isnot(None), AccountCommodityState.valid_until > now, ) return [ dict(row.raw_json) for row in query.order_by(AccountCommodityState.commodity_id.asc()).all() if isinstance(row.raw_json, dict) ] @staticmethod def _sync_mode( db: Session, account: Account, domain: str, *, now: datetime, ) -> str: if is_domain_fresh( db, account_id=int(account.id), domain=domain, now=now, ): return "fresh" return ( "stale" if get_sync_state(db, account_id=int(account.id), domain=domain) else "missing" ) @staticmethod def _queue_domain_sync( db: Session, *, account: Account, domain: str, now: datetime, ) -> str | None: work_type = { DOMAIN_POINTS: WORK_POINTS_SYNC, DOMAIN_GOLD: WORK_GOLD_SYNC, DOMAIN_ELITE: WORK_ELITE_SYNC, DOMAIN_ESPORTS: WORK_ESPORTS_SYNC, DOMAIN_ROLE: WORK_ROLE_SYNC, DOMAIN_EXCHANGE_RECORDS: WORK_EXCHANGE_RECORDS_SYNC, }.get(domain) if work_type is None: return None enqueue_account_work( db, account_id=int(account.id), work_type=work_type, priority=25, due_at=now, reason=f"一键查询发现 {domain} 查询域过期", ) return work_type @staticmethod def _local_bind_overview(account: Account) -> dict[str, dict[str, Any]]: rows = { "elite": ( account.role_bind_status, account.game_name, account.game_channel, ), "esports": ( account.esports_bind_status, account.esports_game_name, account.esports_game_channel, ), "peace": ( account.xpd_bind_status, account.xpd_game_name, "", ), } return { scope: { "status": status or "unknown", "role_name": role_name or "", "game_channel": channel or "", "source_alias": "local_projection", } for scope, (status, role_name, channel) in rows.items() } @staticmethod def _load_exchange_projection( db: Session, account: Account, *, fallback: dict[str, Any], ) -> dict[str, list[dict[str, Any]]]: state = ( db.query(AccountSyncState) .filter( AccountSyncState.account_id == int(account.id), AccountSyncState.platform == "douyu", AccountSyncState.domain == DOMAIN_EXCHANGE_RECORDS, ) .first() ) raw = state.raw_payload_json if state is not None else None source = raw if isinstance(raw, dict) else fallback return { str(scope): [dict(row) for row in rows if isinstance(row, dict)] for scope, rows in source.items() if isinstance(rows, list) } def _cached_overview( self, account: Account, task: DouyuTask, *, now: datetime, ) -> dict[str, Any] | None: snapshot = account.overview_snapshot if not isinstance(snapshot, dict) or account.overview_queried_at is None: return None payload = ( self._task_payload(task) if hasattr(self, "_task_payload") else {} ) if bool(payload.get("force_refresh")): return None age = (now - account.overview_queried_at).total_seconds() ttl = _overview_cache_seconds() # MySQL DATETIME 只有秒精度,写入时会四舍五入;同一秒内重试可能 # 读到比应用时钟未来不到 1 秒的时间。给它一个小容差,避免新鲜快照 # 被误判为“未来数据”而重复请求官网。 if age < -5 or age > ttl: return None cached = dict(snapshot) cached["cache_hit"] = True cached["cache_source"] = "account.overview_snapshot" cached["fresh_until"] = account.overview_queried_at + timedelta(seconds=ttl) cached["fresh_until"] = cached["fresh_until"].isoformat() return cached def _execute_query_account_overview( self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict ): """一键查询:把该账号的关键信息从斗鱼拉全。 每一项独立 try/except —— 单项失败只记进 `errors`, 绝不因此让整次查询失败(账号没绑电竞手册就是最常见的例子)。 """ started_at = datetime.now(UTC) view = self._overview_view(task) cached = self._cached_overview(account, task, now=started_at) if cached is not None: cached["view"] = view or str(cached.get("view") or "") message = _overview_success_message( cached, cached.get("errors") if isinstance(cached.get("errors"), dict) else {}, view=view, ) self._push_log( "info", f"账号 {account.id} 一键查询命中本地快照,跳过官网请求", ) self._mark_task(db, task, "success", message, cached) return client = self._client(cookie) manual_id = str(config.get("manual_id") or "").strip() esports_manual_id = str(config.get("esports_manual_id") or "").strip() rid = str(config.get("rid") or "").strip() queried_at = datetime.now(UTC) overview: dict[str, Any] = { "queried_at": queried_at.isoformat(), "view": view, "assets": {}, "elite": {}, "esports": {}, "high_value_goods": [], "pending_domains": [], "stale_domains": [], "domain_sources": {}, "exchange_records": {}, "errors": {}, } errors: dict[str, str] = overview["errors"] # (作用域, 官方记录) 扁平列表,便于补事件 all_records: list[tuple[str, dict[str, Any]]] = [] pending_goods: list[dict[str, Any]] = [] goods_query_ok = False local_goods_fresh = False storehome_snapshot: StorehomeSnapshot | None = None previous_overview = ( account.overview_snapshot if isinstance(account.overview_snapshot, dict) else {} ) # ---- 鱼翅 + 钱包兑换余额 ---- gold_mode = self._sync_mode(db, account, DOMAIN_GOLD, now=queried_at) if gold_mode in {"fresh", "stale"}: overview["assets"]["gold_balance"] = account.gold_balance overview["assets"]["exchange_balance"] = account.exchange_balance overview["domain_sources"][DOMAIN_GOLD] = ( "local_fresh" if gold_mode == "fresh" else "queued_stale" ) if gold_mode == "stale": overview["stale_domains"].append(DOMAIN_GOLD) overview["pending_domains"].append(DOMAIN_GOLD) self._queue_domain_sync( db, account=account, domain=DOMAIN_GOLD, now=queried_at, ) else: try: gold = self._refresh_account_gold_balance(client, account) overview["assets"]["gold_balance"] = gold.get("gold_balance") overview["assets"]["exchange_balance"] = gold.get("exchange_balance") overview["domain_sources"][DOMAIN_GOLD] = "official_bootstrap" record_sync_success( db, account_id=int(account.id), domain=DOMAIN_GOLD, source="douyu_task.query_account_overview", observed_at=queried_at, raw_payload=gold, task_id=task.id, ) except Exception as exc: # noqa: BLE001 外部接口边界需要宽泛兜底 errors["gold"] = _err(exc) # ---- 积分 + 到期时间 ---- points_mode = self._sync_mode(db, account, DOMAIN_POINTS, now=queried_at) if points_mode in {"fresh", "stale"}: overview["assets"]["points"] = account.points previous_assets = ( previous_overview.get("assets") if isinstance(previous_overview.get("assets"), dict) else {} ) overview["assets"]["points_expire_at"] = previous_assets.get( "points_expire_at" ) or ( account.points_expire_at.isoformat() if account.points_expire_at else None ) overview["domain_sources"][DOMAIN_POINTS] = ( "local_fresh" if points_mode == "fresh" else "queued_stale" ) if points_mode == "stale": overview["stale_domains"].append(DOMAIN_POINTS) overview["pending_domains"].append(DOMAIN_POINTS) self._queue_domain_sync( db, account=account, domain=DOMAIN_POINTS, now=queried_at, ) else: try: ctn = query_csrf(client) points = self._refresh_account_points(client, account, cookie, ctn=ctn) overview["assets"]["points"] = points.get("points") expire_raw = _ts(_points_expire_at(points)) if expire_raw is not None: # 2026-11-21:新客户端归一成整数时间戳;对外保持原有字符串契约。 expire_raw = str(expire_raw) overview["assets"]["points_expire_at"] = expire_raw expire_dt = _parse_expire_at(expire_raw) account.points_expire_at = expire_dt overview["domain_sources"][DOMAIN_POINTS] = "official_bootstrap" record_sync_success( db, account_id=int(account.id), domain=DOMAIN_POINTS, source="douyu_task.query_account_overview", observed_at=queried_at, raw_payload=points.get("points_query") if isinstance(points.get("points_query"), dict) else points, task_id=task.id, ) except Exception as exc: # noqa: BLE001 errors["points"] = _err(exc) # ---- 精英宝典(开通状态 / 到期时间 / 积分)---- if not manual_id: errors["elite"] = "未配置精英宝典 manualID" else: elite_mode = self._sync_mode(db, account, DOMAIN_ELITE, now=queried_at) if elite_mode in {"fresh", "stale"}: overview["elite"] = { "opened": account.elite_opened, "expire_time": account.elite_expire_time, "points": account.points, } overview["domain_sources"][DOMAIN_ELITE] = ( "local_fresh" if elite_mode == "fresh" else "queued_stale" ) if elite_mode == "stale": overview["stale_domains"].append(DOMAIN_ELITE) overview["pending_domains"].append(DOMAIN_ELITE) self._queue_domain_sync( db, account=account, domain=DOMAIN_ELITE, now=queried_at, ) else: try: elite = self._refresh_elite_handbook( client, account, manual_id=manual_id, rid=rid ) overview["elite"] = { "opened": elite.get("elite_opened"), "expire_time": _ts(elite.get("elite_expire_time")), "points": elite.get("elite_manual_score"), } overview["domain_sources"][DOMAIN_ELITE] = "official_bootstrap" record_sync_success( db, account_id=int(account.id), domain=DOMAIN_ELITE, source="douyu_task.query_account_overview", observed_at=queried_at, raw_payload=elite, task_id=task.id, ) except Exception as exc: # noqa: BLE001 errors["elite"] = _err(exc) # ---- 电竞手册 ---- if not esports_manual_id: errors["esports"] = "未配置电竞手册 manualID" else: esports_mode = self._sync_mode( db, account, DOMAIN_ESPORTS, now=queried_at, ) if esports_mode in {"fresh", "stale"}: overview["esports"] = { "opened": account.esports_opened, "manual_type": 1 if account.esports_opened else 0, "points": account.esports_points, "expire_time": account.esports_expire_time, } overview["domain_sources"][DOMAIN_ESPORTS] = ( "local_fresh" if esports_mode == "fresh" else "queued_stale" ) if esports_mode == "stale": overview["stale_domains"].append(DOMAIN_ESPORTS) overview["pending_domains"].append(DOMAIN_ESPORTS) self._queue_domain_sync( db, account=account, domain=DOMAIN_ESPORTS, now=queried_at, ) else: try: esports = self._refresh_esports_handbook( client, account, manual_id=esports_manual_id ) manual_type = esports.get("esports_manual_type") opened = ( manual_type is not None and int(manual_type) >= 1 if isinstance(manual_type, (int, float)) else None ) overview["esports"] = { "opened": opened, "manual_type": manual_type, "points": esports.get("esports_points"), "expire_time": _ts(esports.get("esports_expire_time")), } overview["domain_sources"][DOMAIN_ESPORTS] = "official_bootstrap" record_sync_success( db, account_id=int(account.id), domain=DOMAIN_ESPORTS, source="douyu_task.query_account_overview", observed_at=queried_at, raw_payload=esports, task_id=task.id, ) except Exception as exc: # noqa: BLE001 errors["esports"] = _err(exc) # ---- 精英宝典商城商品列表(高价值套装的**唯一**判据来源)---- # # ⚠️ 必须用**精英宝典**的 manual_id(与其他商城能力快照一致), # 而且**不能**寄生在上面的「电竞手册」分支里:那是两个无关的活动。 # 之前商品列表被写在电竞手册的 else 分支内 —— 于是一旦没配 # `esports_manual_id`,商城商品就永远拉不到,高价值三态就永远 # 落不到 `available`/`owned`(全部显示「待确认」)。 if not manual_id: errors["limited_goods"] = "未配置精英宝典 manualID" else: goods_items: list[dict[str, Any]] = [] storehome_state = get_sync_state( db, account_id=int(account.id), domain=DOMAIN_STOREHOME, ) if is_domain_fresh( db, account_id=int(account.id), domain=DOMAIN_STOREHOME, now=queried_at, ): goods_items = self._load_storehome_items( db, account, fresh_only=True, now=queried_at, ) if goods_items: local_goods_fresh = True overview["limited_goods_total"] = len(goods_items) overview["goods_source"] = "local_fresh_projection" else: overview["pending_domains"].append(DOMAIN_STOREHOME) errors["limited_goods"] = ( "商品同步状态新鲜,但本地商品明细为空,已加入同步队列" ) enqueue_account_work( db, account_id=int(account.id), work_type=WORK_STOREHOME_SYNC, priority=20, due_at=queried_at, reason="一键查询发现商品投影为空", ) elif storehome_state is not None: goods_items = self._load_storehome_items( db, account, fresh_only=False, now=queried_at, ) if goods_items: overview["limited_goods_total"] = len(goods_items) overview["goods_source"] = "local_stale_projection" overview["high_value_goods"] = list( previous_overview.get("high_value_goods") or [] ) overview["pending_domains"].append(DOMAIN_STOREHOME) errors["limited_goods"] = ( "本地商品快照已过期,已加入后台同步队列" ) enqueue_account_work( db, account_id=int(account.id), work_type=WORK_STOREHOME_SYNC, priority=20, due_at=queried_at, reason="一键查询发现商品快照过期", ) else: try: # 首次同步保留一次实时查询,避免新部署后一键查询直接返回空。 goods_result = query_activity_goods_result( client, manual_id=manual_id, rid=rid, ) storehome_snapshot = storehome_snapshot_from_result( goods_result, manual_id=manual_id, rid=rid, observed_at=queried_at, ) goods_items = list(storehome_snapshot.items) overview["limited_goods_total"] = len(goods_items) overview["goods_source"] = "official_bootstrap" goods_query_ok = True except Exception as exc: # noqa: BLE001 errors["limited_goods"] = _err(exc) # 商品列表带有账号级 status;兑换记录只作历史展示,不参与准入判定。 pending_goods = goods_items limited_goods = [ item for item in goods_items if str(item.get("status") if item.get("status") is not None else "") == "1" ] overview["limited_count"] = len(limited_goods) overview["limited_goods"] = limited_goods # ---- 角色绑定状态(三个作用域都查)---- # # 这三个值以前**从来没人查过** —— 只是 S6 迁移时从旧的垃圾场列 # `bind_status` 能推的推、推不出的留 `unknown`,于是界面上 97% 显示"未知"。 # 实测校准:最终绑定以 `bindAct=1` 为准;只识别到 `bindRole=1` # 但尚未 actBind 的账号必须保持 pending。 # 和平小店总开关:关着时**完全跳过**它的所有请求。 # 小店目前是关闭状态,不跳过的话每个账号都会产生一条 # "Livelink登录态校验失败"(实测 200 个里失败 195 次,100%), # 既淹掉真错误、又让人以为出故障。跳过时**不记 errors** —— # 这是配置成关的,不是失败。 peace_on = bool(config.get("peace_enabled")) if not peace_on: overview["peace_skipped"] = ( "和平小店已关闭(douyu_config.peace_enabled=False)" ) role_mode = self._sync_mode(db, account, DOMAIN_ROLE, now=queried_at) if role_mode in {"fresh", "stale"}: overview["bind"] = self._local_bind_overview(account) if not peace_on: overview["bind"].pop("peace", None) overview["domain_sources"][DOMAIN_ROLE] = ( "local_fresh" if role_mode == "fresh" else "queued_stale" ) if role_mode == "stale": overview["stale_domains"].append(DOMAIN_ROLE) overview["pending_domains"].append(DOMAIN_ROLE) self._queue_domain_sync( db, account=account, domain=DOMAIN_ROLE, now=queried_at, ) else: 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"), ("peace", "和平小店", "xpd_act_alias"), ): if scope == "peace" and not peace_on: continue alias = str(config.get(alias_key) or "").strip() if not alias: errors[f"bind_{scope}"] = f"未配置{label}活动别名" continue 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, ) db.commit() # ---- 官方兑换记录(**三个作用域都拉**)---- # # 精英宝典 / 电竞手册 用的是同一个接口,只是 manual_id 不同; # 和平小店是另一套(先拿道聚城短时授权 query,再查购买记录)。 # 任一作用域失败只记进 errors,不影响其余两个。 exchange_mode = self._sync_mode( db, account, DOMAIN_EXCHANGE_RECORDS, now=queried_at, ) if exchange_mode in {"fresh", "stale"}: fallback_records = ( previous_overview.get("exchange_records") if isinstance(previous_overview.get("exchange_records"), dict) else {} ) cached_records = self._load_exchange_projection( db, account, fallback=fallback_records, ) for scope, rows in cached_records.items(): valid_rows = [dict(row) for row in rows if isinstance(row, dict)] overview["exchange_records"][scope] = valid_rows[ :EXCHANGE_RECORD_DISPLAY_LIMIT ] overview[f"exchange_record_count_{scope}"] = len(valid_rows) all_records.extend((str(scope), row) for row in valid_rows) overview["domain_sources"][DOMAIN_EXCHANGE_RECORDS] = ( "local_fresh" if exchange_mode == "fresh" else "queued_stale" ) if exchange_mode == "stale": overview["stale_domains"].append(DOMAIN_EXCHANGE_RECORDS) overview["pending_domains"].append(DOMAIN_EXCHANGE_RECORDS) self._queue_domain_sync( db, account=account, domain=DOMAIN_EXCHANGE_RECORDS, now=queried_at, ) else: for scope, label, fetcher in ( ("elite", "精英宝典", self._fetch_elite_records), ("esports", "电竞手册", self._fetch_esports_records), ("peace", "和平小店", self._fetch_xpd_records), ): if scope == "peace" and not peace_on: continue key = f"exchange_records_{scope}" if not self._scope_configured( scope, manual_id, esports_manual_id, config, ): errors[key] = f"未配置{label}活动参数,跳过" continue try: rows = fetcher(client, config, manual_id, esports_manual_id) except Exception as exc: # noqa: BLE001 外部接口边界需要宽泛兜底 errors[key] = _err(exc) continue overview["exchange_records"][scope] = rows[ :EXCHANGE_RECORD_DISPLAY_LIMIT ] all_records.extend((scope, r) for r in rows) overview[f"exchange_record_count_{scope}"] = len(rows) overview["domain_sources"][DOMAIN_EXCHANGE_RECORDS] = ( "official_bootstrap" ) overview["exchange_record_count"] = len(all_records) # 兑换记录开始前结束前一步可能留下的角色快照事务。 db.commit() if exchange_mode == "missing": # 把官方记录**补成账号事件**(带真实兑换时间、按作用域去重)。 overview["exchange_events_added"] = persist_official_exchange_records( db, account, all_records ) record_sync_success( db, account_id=int(account.id), domain=DOMAIN_EXCHANGE_RECORDS, source="douyu_task.query_account_overview", observed_at=queried_at, item_count=len(all_records), changed_count=int(overview["exchange_events_added"] or 0), raw_payload=_group_by_scope(all_records), task_id=task.id, ) else: overview["exchange_events_added"] = 0 overview["exchange_records"] = { scope: rows[:EXCHANGE_RECORD_DISPLAY_LIMIT] for scope, rows in _group_by_scope(all_records).items() } # ---- 账号 × 商品能力索引 ---- # 只有完整商城列表查询成功时才更新,避免把网络失败写成“不可兑换”。 if goods_query_ok: try: if storehome_snapshot is None: raise RuntimeError("完整商品响应未形成快照") overview["commodity_states_synced"] = sync_storehome_snapshot( db, account, storehome_snapshot, source="douyu_task.account_overview", task_id=task.id, ).changed_count except Exception as exc: # noqa: BLE001 errors["commodity_states"] = _err(exc) # ---- 🎯 高价值套装判定(依赖兑换记录,必须放在它之后)---- if not manual_id: errors["high_value_goods"] = "未配置精英宝典 manualID" else: try: # ⚠️ 必须传**摊平后的记录**:`all_records` 是 (作用域, 记录) 元组列表, # 直接传进去会被 `isinstance(r, dict)` 全过滤掉 —— 表现为 # "所有高价值套装都判定为未获得"(踩过)。 overview["high_value_goods"] = extract_high_value_goods( pending_goods, _goods_config(config), [rec for _scope, rec in all_records], ) if goods_query_ok or local_goods_fresh: apply_high_value_goods( account, overview["high_value_goods"], checked_at=queried_at, ) overview["high_value_checked_at"] = queried_at.isoformat() except Exception as exc: # noqa: BLE001 errors["high_value_goods"] = _err(exc) # 查询会回写账号上的余额/积分缓存(各 _refresh_* 内部已写), # 但**不改生命周期状态,也不制造业务事实事件**;任务活动由执行器统一记录。 account.updated_at = datetime.now(UTC) message = _overview_success_message(overview, errors, view=view) # 落到账号上:任务会被保留策略清掉,而「这个账号现在什么情况」是账号的信息, # 应该在账号管理里看,不该依赖一条日志的寿命。 account.overview_snapshot = overview account.overview_queried_at = queried_at logger.info(f"[douyu] 一键查询账号 {account.id}: {message}") self._mark_task(db, task, "success", message, overview)