103 lines
2.8 KiB
Python
103 lines
2.8 KiB
Python
"""斗鱼只读查询网关。
|
|
|
|
所有账号同步都从这里获取结构化快照,避免页面、Runner 和自动化各自解释原始响应。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
from datetime import UTC, datetime
|
|
from typing import Any
|
|
|
|
from core.douyu import DouyuActivityClient
|
|
|
|
from .douyu_activity_query import query_limited_goods_result
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class StorehomeSnapshot:
|
|
"""单账号完整商城资格快照。"""
|
|
|
|
manual_id: str
|
|
rid: str
|
|
observed_at: datetime
|
|
items: tuple[dict[str, Any], ...]
|
|
limited_ids: frozenset[str]
|
|
raw: dict[str, Any]
|
|
|
|
@property
|
|
def item_count(self) -> int:
|
|
return len(self.items)
|
|
|
|
|
|
def extract_storehome_goods(raw: Any) -> list[dict[str, Any]]:
|
|
"""从官方 ``storehome`` 响应中提取完整商品列表。"""
|
|
if not isinstance(raw, dict):
|
|
return []
|
|
data = raw.get("data")
|
|
if not isinstance(data, dict):
|
|
return []
|
|
rows = data.get("list")
|
|
if not isinstance(rows, list):
|
|
return []
|
|
return [dict(item) for item in rows if isinstance(item, dict)]
|
|
|
|
|
|
def storehome_snapshot_from_result(
|
|
result: dict[str, Any],
|
|
*,
|
|
manual_id: str,
|
|
rid: str,
|
|
observed_at: datetime | None = None,
|
|
) -> StorehomeSnapshot:
|
|
"""把已经拿到的官方响应归一成可落库的完整快照。"""
|
|
raw = result.get("raw") if isinstance(result.get("raw"), dict) else {}
|
|
if raw and raw.get("error") not in (None, 0, "0"):
|
|
raise RuntimeError(str(raw.get("msg") or "查询商城商品列表失败"))
|
|
items = extract_storehome_goods(raw)
|
|
if not items and isinstance(result.get("goods"), list):
|
|
items = [
|
|
dict(item) for item in result["goods"] if isinstance(item, dict)
|
|
]
|
|
limited_ids = frozenset(
|
|
str(item.get("commodityId") or item.get("commodity_id") or "")
|
|
for item in items
|
|
if str(item.get("status") or "") == "1"
|
|
and str(item.get("commodityId") or item.get("commodity_id") or "").strip()
|
|
)
|
|
return StorehomeSnapshot(
|
|
manual_id=str(manual_id),
|
|
rid=str(rid or ""),
|
|
observed_at=observed_at or datetime.now(UTC),
|
|
items=tuple(items),
|
|
limited_ids=limited_ids,
|
|
raw=raw,
|
|
)
|
|
|
|
|
|
def fetch_storehome_snapshot(
|
|
client: DouyuActivityClient,
|
|
*,
|
|
manual_id: str,
|
|
rid: str,
|
|
) -> StorehomeSnapshot:
|
|
"""一次请求返回当前账号全部商品资格。"""
|
|
result = query_limited_goods_result(
|
|
client,
|
|
manual_id=manual_id,
|
|
rid=str(rid or ""),
|
|
)
|
|
return storehome_snapshot_from_result(
|
|
result,
|
|
manual_id=manual_id,
|
|
rid=rid,
|
|
)
|
|
|
|
|
|
__all__ = [
|
|
"StorehomeSnapshot",
|
|
"extract_storehome_goods",
|
|
"fetch_storehome_snapshot",
|
|
"storehome_snapshot_from_result",
|
|
]
|