feat(huya): 统一实时商品目录并增加兑换代理开关
This commit is contained in:
@@ -35,9 +35,6 @@ from core.huya.http_client import query_bind_game_account
|
||||
from ..huya_defaults import (
|
||||
HUYA_DEFAULT_BIND_GID,
|
||||
HUYA_DEFAULT_OUTER_ACT_ID,
|
||||
HUYA_DEFAULT_POINTS_PAGE_CODE,
|
||||
HUYA_DEFAULT_POINTS_SCENE,
|
||||
HUYA_DEFAULT_POINTS_SOURCE_ID,
|
||||
HUYA_DEFAULT_SID,
|
||||
)
|
||||
from ..models import (
|
||||
@@ -51,9 +48,12 @@ from ..models import (
|
||||
from .audit_service import record_audit
|
||||
from .file_service import build_file_url
|
||||
from .file_storage import normalize_object_key
|
||||
from .huya_points_center import (
|
||||
fetch_points_center_catalog,
|
||||
resolve_points_center_config,
|
||||
)
|
||||
from .huya_service import (
|
||||
build_web_cookie_from_raw,
|
||||
huya_config_value,
|
||||
parse_huya_cookie_line,
|
||||
)
|
||||
|
||||
@@ -991,12 +991,13 @@ def _resolve_group_required_points(
|
||||
order.order_no for order in missing
|
||||
], "组内没有可用的 CK,无法解析礼包积分"
|
||||
|
||||
catalog, message = fetch_points_center_gifts(
|
||||
result = fetch_points_center_catalog(
|
||||
int(source.uid),
|
||||
str(source.cookie),
|
||||
client=client,
|
||||
client=client or _build_probe_client(),
|
||||
**resolve_points_center_config(db),
|
||||
)
|
||||
catalog, message = result.goods, result.message
|
||||
if not catalog:
|
||||
return [order.order_no for order in missing], message
|
||||
|
||||
@@ -1659,14 +1660,12 @@ PROBE_SNAPSHOT_FIELDS: tuple[str, ...] = (
|
||||
"bind_game_channel",
|
||||
)
|
||||
|
||||
# 活动礼包(get_act_prize_list)用的 SID **兜底值**:真正该用的是工作台配置里的那个
|
||||
# 兑换记录等 webActUI 接口用的 SID **兜底值**:真正该用的是工作台配置里的那个
|
||||
# (``huya_config.sid``,见 :func:`resolve_gifts_sid`)。
|
||||
# 2026-10-16 真机定论:**SID 就是活动 ID,会随活动轮换** —— 库里 9 月的活动是 2203,
|
||||
# 今天是 2277。写死默认值时接口照样 ``status=200`` 但 **0 个商品**,界面上就是
|
||||
# 「礼包列表空白」(换 SID 立刻回到 30 个礼包,跟 CK、UA、解析都无关)。
|
||||
GIFTS_SID = int(HUYA_DEFAULT_SID)
|
||||
# 一次最多回多少个礼包(避免前端下拉塞几百项)。
|
||||
GIFTS_LIMIT = 200
|
||||
# 同一份 CK 的探针结论缓存时长("预览一次 + 提交校验一次" 只打一次接口)。
|
||||
PROBE_CACHE_TTL_SECONDS = 90.0
|
||||
_probe_cache: dict[str, tuple[float, CkProbeResult]] = {}
|
||||
@@ -1911,258 +1910,6 @@ def resolve_gifts_sid(db: Session) -> int:
|
||||
return value or GIFTS_SID
|
||||
|
||||
|
||||
def resolve_points_center_config(db: Session) -> dict[str, Any]:
|
||||
"""积分中心活动参数:优先读虎牙配置,空值/脏值回落到默认。
|
||||
|
||||
页签 ID 默认留空,由 ``queryAllocation`` 响应自动发现;``points_page_id``
|
||||
与 ``points_tab_ids`` 只作为接口改版、自动发现失败时的人工覆盖。
|
||||
"""
|
||||
row = db.query(HuyaConfig).first()
|
||||
|
||||
def value(field: str, default: str) -> str:
|
||||
return (
|
||||
huya_config_value(
|
||||
field, getattr(row, field, None) if row is not None else None
|
||||
)
|
||||
or default
|
||||
)
|
||||
|
||||
try:
|
||||
scene = int(value("points_scene", HUYA_DEFAULT_POINTS_SCENE))
|
||||
except (TypeError, ValueError):
|
||||
scene = int(HUYA_DEFAULT_POINTS_SCENE)
|
||||
|
||||
page_id_text = value("points_page_id", "")
|
||||
try:
|
||||
page_id = int(page_id_text) if page_id_text else None
|
||||
except ValueError:
|
||||
page_id = None
|
||||
|
||||
tab_ids: list[int] = []
|
||||
for part in re.split(r"[,,\s]+", value("points_tab_ids", "")):
|
||||
if part.isdigit():
|
||||
tab_id = int(part)
|
||||
if tab_id not in tab_ids:
|
||||
tab_ids.append(tab_id)
|
||||
|
||||
return {
|
||||
"page_code": value("points_page_code", HUYA_DEFAULT_POINTS_PAGE_CODE),
|
||||
"source_id": value("points_source_id", HUYA_DEFAULT_POINTS_SOURCE_ID),
|
||||
"scene": scene,
|
||||
"page_id": page_id,
|
||||
"tab_ids": tab_ids or None,
|
||||
}
|
||||
|
||||
|
||||
def fetch_activity_gifts(
|
||||
uid: int,
|
||||
cookie: str,
|
||||
*,
|
||||
sid: int | None = None,
|
||||
client: Any | None = None,
|
||||
) -> tuple[list[dict], str]:
|
||||
"""LEGACY:用这份 CK 拉 ``webActUI.getActPrizeList`` 活动礼包。
|
||||
|
||||
外部单协作台账已改用 :func:`fetch_points_center_gifts`
|
||||
(``PlayMallUI.queryAllocation``);本函数保留给旧调用/测试,不再从
|
||||
``preview_ck`` 调用。
|
||||
"""
|
||||
sid_value = int(sid or GIFTS_SID)
|
||||
try:
|
||||
gift_client = client or _build_probe_client()
|
||||
resp = gift_client.get_act_prize_list(
|
||||
uid=int(uid), cookie=cookie, sid=sid_value
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 拉礼包失败不该让整个预览 500
|
||||
logger.debug(f"[huya-collab] 拉取活动礼包异常:{type(exc).__name__}: {exc}")
|
||||
return [], f"拉取礼包失败:{type(exc).__name__}: {_clip(exc)}"
|
||||
|
||||
if resp is None:
|
||||
return [], "拉取礼包失败:接口没有返回数据"
|
||||
status = int(getattr(resp, "status", 0) or 0)
|
||||
if status != 200:
|
||||
msg = _clip(getattr(resp, "msg", ""))
|
||||
return [], f"拉取礼包失败:status={status}{(':' + msg) if msg else ''}"
|
||||
|
||||
raw_goods = (resp.to_dict() or {}).get("goods") or []
|
||||
gifts: list[dict] = []
|
||||
for item in raw_goods:
|
||||
product_id = str(item.get("product_id") or "").strip()
|
||||
name = str(item.get("name") or "").strip()
|
||||
if not product_id or not name:
|
||||
continue
|
||||
gifts.append(
|
||||
{
|
||||
"product_id": product_id,
|
||||
"name": name[:256],
|
||||
"price": item.get("price"),
|
||||
"remain_text": str(item.get("remain_text") or "")[:64],
|
||||
"stock": item.get("stock"),
|
||||
"score": item.get("score"),
|
||||
"category_name": str(item.get("category_name") or "")[:64],
|
||||
"icon": str(item.get("icon") or "")[:512],
|
||||
}
|
||||
)
|
||||
gifts = gifts[:GIFTS_LIMIT]
|
||||
if not gifts:
|
||||
# 200 + 空列表 = 这个 SID 不是当前活动(见 resolve_gifts_sid 的真机定位)。
|
||||
return [], (
|
||||
f"活动 SID={sid_value} 没返回商品:接口通了但列表是空的,"
|
||||
"多半是活动换 ID 了 —— 去工作台「虎牙配置」把活动 SID 改成当前的再试"
|
||||
)
|
||||
return gifts, f"已拉取 {len(gifts)} 个礼包"
|
||||
|
||||
|
||||
def fetch_points_center_gifts(
|
||||
uid: int,
|
||||
cookie: str,
|
||||
*,
|
||||
client: Any | None = None,
|
||||
page_code: str = HUYA_DEFAULT_POINTS_PAGE_CODE,
|
||||
source_id: str = HUYA_DEFAULT_POINTS_SOURCE_ID,
|
||||
scene: int = int(HUYA_DEFAULT_POINTS_SCENE),
|
||||
page_id: int | None = None,
|
||||
tab_ids: Sequence[int] | None = None,
|
||||
) -> tuple[list[dict], str]:
|
||||
"""用这份 CK 拉**积分中心商品**(``PlayMallUI.queryAllocation``,只读)。
|
||||
|
||||
2026-10-19 用户拍板:外部单协作台账改用这个接口,不再调用
|
||||
``webActUI.getActPrizeList``。商品积分取 ``tag75.tag0.tag2``,
|
||||
与积分中心页面显示一致;旧接口保留给精英宝典工作台的兑换链路。
|
||||
|
||||
2026-11-11 HAR 确认:基础请求只返回第一个页签的商品,其余页签定义在
|
||||
``tag2[].tag0_2``,需要带 ``tag9=pageId`` 与
|
||||
``tag7={"waterfallTabId":"tabId"}`` 再查。这里默认自动发现并拉全,
|
||||
``page_id`` / ``tab_ids`` 仅作为配置覆盖。
|
||||
"""
|
||||
from core.huya.shop_structs import (
|
||||
extract_points_center_tabs,
|
||||
parse_points_center_gifts,
|
||||
)
|
||||
|
||||
gift_client = client or _build_probe_client()
|
||||
|
||||
def call(
|
||||
tab_id: int | None = None, tab_page_id: int | None = None
|
||||
) -> tuple[dict | None, str]:
|
||||
kwargs: dict[str, Any] = {
|
||||
"uid": int(uid),
|
||||
"guid": "",
|
||||
"cookie": cookie,
|
||||
"page_code": page_code,
|
||||
"source_id": source_id,
|
||||
"scene": scene,
|
||||
"deep": True,
|
||||
}
|
||||
if tab_id is not None:
|
||||
kwargs["page_id"] = int(page_id or tab_page_id or 0)
|
||||
kwargs["waterfall_tab_id"] = int(tab_id)
|
||||
try:
|
||||
resp = gift_client.play_mall_query_allocation(**kwargs)
|
||||
except Exception as exc: # noqa: BLE001 单个页签失败不该带崩整批
|
||||
logger.debug(
|
||||
f"[huya-collab] 拉取积分中心商品异常:{type(exc).__name__}: {exc}"
|
||||
)
|
||||
return None, f"{type(exc).__name__}: {_clip(exc)}"
|
||||
|
||||
if resp is None:
|
||||
return None, "积分中心接口没有返回数据"
|
||||
|
||||
code = getattr(resp, "code", None)
|
||||
if code is None:
|
||||
code = getattr(resp, "status", 0)
|
||||
code = int(code or 0)
|
||||
if code != 200:
|
||||
msg = _clip(getattr(resp, "message", "") or getattr(resp, "msg", ""))
|
||||
return None, f"code={code}{(':' + msg) if msg else ''}"
|
||||
|
||||
payload = getattr(resp, "payload", None)
|
||||
if payload is None and hasattr(resp, "to_dict"):
|
||||
try:
|
||||
payload = (resp.to_dict() or {}).get("payload")
|
||||
except Exception: # noqa: BLE001 第三方响应结构异常时按空处理
|
||||
payload = None
|
||||
return payload if isinstance(payload, dict) else None, ""
|
||||
|
||||
payload, error = call()
|
||||
if error:
|
||||
return [], f"拉取礼包失败:{error}"
|
||||
|
||||
gifts = parse_points_center_gifts(payload)
|
||||
tabs = extract_points_center_tabs(payload)
|
||||
if not gifts and not tabs:
|
||||
return [], (
|
||||
"积分中心没返回商品:接口通了但列表是空的,"
|
||||
"检查账号是否仍有积分中心访问权限,或稍后重试"
|
||||
)
|
||||
|
||||
discovered = {(int(tab["page_id"]), int(tab["tab_id"])): tab for tab in tabs}
|
||||
loaded_categories = {str(gift.get("category_name") or "").strip() for gift in gifts}
|
||||
tab_errors: list[str] = []
|
||||
if tab_ids:
|
||||
targets: list[dict] = []
|
||||
for tab_id in tab_ids:
|
||||
matched = next(
|
||||
(
|
||||
tab
|
||||
for (tab_page_id, tab_id_value), tab in discovered.items()
|
||||
if tab_id_value == int(tab_id)
|
||||
and (page_id is None or tab_page_id == int(page_id))
|
||||
),
|
||||
None,
|
||||
)
|
||||
if matched is not None:
|
||||
targets.append(matched)
|
||||
elif page_id is not None:
|
||||
targets.append(
|
||||
{
|
||||
"page_id": int(page_id),
|
||||
"tab_id": int(tab_id),
|
||||
"name": f"页签 {tab_id}",
|
||||
}
|
||||
)
|
||||
else:
|
||||
tab_errors.append(f"页签 {tab_id}:响应里没发现,且未配置 pageId")
|
||||
else:
|
||||
targets = [
|
||||
tab
|
||||
for tab in tabs
|
||||
if str(tab.get("name") or "").strip() not in loaded_categories
|
||||
]
|
||||
|
||||
seen_products = {
|
||||
str(gift.get("product_id") or "") for gift in gifts if gift.get("product_id")
|
||||
}
|
||||
loaded_tabs = len(loaded_categories) if gifts else 0
|
||||
for tab in targets:
|
||||
target_page_id = int(page_id or tab["page_id"])
|
||||
tab_payload, tab_error = call(int(tab["tab_id"]), target_page_id)
|
||||
if tab_error:
|
||||
tab_errors.append(f"{tab.get('name') or tab['tab_id']}:{tab_error}")
|
||||
continue
|
||||
tab_gifts = parse_points_center_gifts(tab_payload)
|
||||
added = 0
|
||||
for gift in tab_gifts:
|
||||
product_id = str(gift.get("product_id") or "")
|
||||
if product_id and product_id not in seen_products:
|
||||
seen_products.add(product_id)
|
||||
gifts.append(gift)
|
||||
added += 1
|
||||
if added or tab_gifts:
|
||||
loaded_tabs += 1
|
||||
|
||||
gifts = gifts[:GIFTS_LIMIT]
|
||||
if not gifts:
|
||||
return [], (
|
||||
"积分中心没返回商品:接口通了但列表是空的,"
|
||||
"检查账号是否仍有积分中心访问权限,或稍后重试"
|
||||
)
|
||||
suffix = f",{loaded_tabs} 个页签" if loaded_tabs > 1 else ""
|
||||
if tab_errors:
|
||||
suffix += f";部分页签未加载:{';'.join(tab_errors[:3])}"
|
||||
return gifts, f"已拉取 {len(gifts)} 个礼包(积分中心{suffix})"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 账号全生命周期(积分 / 兑换记录:抢购之后靠它判断到底兑换成功没有)
|
||||
# --------------------------------------------------------------------------
|
||||
@@ -2804,12 +2551,13 @@ def preview_ck(
|
||||
gifts: list[dict] = []
|
||||
gifts_message = ""
|
||||
if with_gifts and result.ok and uid_text:
|
||||
gifts, gifts_message = fetch_points_center_gifts(
|
||||
catalog = fetch_points_center_catalog(
|
||||
int(uid_text),
|
||||
cookie,
|
||||
client=client,
|
||||
client=client or _build_probe_client(),
|
||||
**(dict(points_config) if points_config else {}),
|
||||
)
|
||||
gifts, gifts_message = catalog.goods, catalog.message
|
||||
return {
|
||||
"ok": result.ok,
|
||||
"message": result.message,
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
"""虎牙积分中心唯一目录读取实现。
|
||||
|
||||
2026-11-13 两份 HAR(``11.13-兑换记录.har``、
|
||||
``11.13-虎牙充值2元-兑换幸运币.har``)确认:
|
||||
|
||||
* ``PlayMallUI.queryAllocation`` 是积分中心商品、页签、活动 SID 和赛季配置的
|
||||
唯一权威来源;
|
||||
* 基础响应只返回第一个页签,官方页面随后按 ``pageId + waterfallTabId``
|
||||
补拉其它页签;
|
||||
* ``webActUI.getActPrizeList`` 不在最新兑换链路中,旧实现已删除。
|
||||
|
||||
商品刷新、实时下拉、兑换前校验、外部单积分解析、CK 预览、兑换记录 SID 和
|
||||
宝典赛季都只能调用本模块,避免各入口重复实现后再次出现旧 prize_id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from loguru import logger
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.huya.shop_structs import (
|
||||
extract_points_center_sid,
|
||||
extract_points_center_tabs,
|
||||
parse_points_center_gifts,
|
||||
)
|
||||
|
||||
from ..huya_defaults import (
|
||||
HUYA_DEFAULT_POINTS_PAGE_CODE,
|
||||
HUYA_DEFAULT_POINTS_SCENE,
|
||||
HUYA_DEFAULT_POINTS_SOURCE_ID,
|
||||
)
|
||||
from ..models import HuyaConfig
|
||||
from .huya_service import huya_config_value
|
||||
|
||||
GIFTS_LIMIT = 200
|
||||
POINTS_SEASON_MS_FLOOR = 1_000_000_000_000
|
||||
|
||||
|
||||
def _clip(value: Any, limit: int = 200) -> str:
|
||||
text = str(value if value is not None else "").strip()
|
||||
return text if len(text) <= limit else text[: limit - 3] + "..."
|
||||
|
||||
|
||||
def _walk_season_nodes(node: Any, found: list[dict]) -> None:
|
||||
if isinstance(node, dict):
|
||||
config = node.get("tag0")
|
||||
if isinstance(config, dict):
|
||||
try:
|
||||
start_ms = int(config.get("tag10") or 0)
|
||||
end_ms = int(config.get("tag11") or 0)
|
||||
config_id = int(config.get("tag0") or 0)
|
||||
except (TypeError, ValueError):
|
||||
start_ms = end_ms = config_id = 0
|
||||
if start_ms >= POINTS_SEASON_MS_FLOOR and end_ms > start_ms:
|
||||
found.append(
|
||||
{
|
||||
"name": _clip(config.get("tag2"), 128),
|
||||
"start_ms": start_ms,
|
||||
"end_ms": end_ms,
|
||||
"config_id": config_id,
|
||||
}
|
||||
)
|
||||
for value in node.values():
|
||||
_walk_season_nodes(value, found)
|
||||
elif isinstance(node, list):
|
||||
for value in node:
|
||||
_walk_season_nodes(value, found)
|
||||
|
||||
|
||||
def extract_points_center_season(payload: Any) -> dict | None:
|
||||
"""取积分中心当前宝典赛季;认不出结构时返回 ``None``。"""
|
||||
found: list[dict] = []
|
||||
_walk_season_nodes(payload, found)
|
||||
return max(found, key=lambda item: item["end_ms"]) if found else None
|
||||
|
||||
|
||||
def resolve_points_center_config(db: Session) -> dict[str, Any]:
|
||||
"""读取积分中心请求参数;空配置自动回落到当前页面默认值。"""
|
||||
row = db.query(HuyaConfig).first()
|
||||
|
||||
def value(field: str, default: str) -> str:
|
||||
return (
|
||||
huya_config_value(
|
||||
field, getattr(row, field, None) if row is not None else None
|
||||
)
|
||||
or default
|
||||
)
|
||||
|
||||
try:
|
||||
scene = int(value("points_scene", HUYA_DEFAULT_POINTS_SCENE))
|
||||
except (TypeError, ValueError):
|
||||
scene = int(HUYA_DEFAULT_POINTS_SCENE)
|
||||
|
||||
page_id_text = value("points_page_id", "")
|
||||
try:
|
||||
page_id = int(page_id_text) if page_id_text else None
|
||||
except ValueError:
|
||||
page_id = None
|
||||
|
||||
tab_ids: list[int] = []
|
||||
for part in re.split(r"[,,\s]+", value("points_tab_ids", "")):
|
||||
if part.isdigit():
|
||||
tab_id = int(part)
|
||||
if tab_id not in tab_ids:
|
||||
tab_ids.append(tab_id)
|
||||
|
||||
return points_center_options_from_config(
|
||||
{
|
||||
"points_page_code": value(
|
||||
"points_page_code", HUYA_DEFAULT_POINTS_PAGE_CODE
|
||||
),
|
||||
"points_source_id": value(
|
||||
"points_source_id", HUYA_DEFAULT_POINTS_SOURCE_ID
|
||||
),
|
||||
"points_scene": scene,
|
||||
"points_page_id": page_id or "",
|
||||
"points_tab_ids": ",".join(str(item) for item in tab_ids),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def points_center_options_from_config(
|
||||
config_info: Mapping[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""把配置字段规范的公共入口,任务和路由不再各自解析。"""
|
||||
tab_ids = [
|
||||
int(part)
|
||||
for part in str(config_info.get("points_tab_ids") or "")
|
||||
.replace(",", ",")
|
||||
.replace(" ", ",")
|
||||
.split(",")
|
||||
if part.isdigit()
|
||||
]
|
||||
return {
|
||||
"page_code": (
|
||||
str(config_info.get("points_page_code") or "").strip()
|
||||
or HUYA_DEFAULT_POINTS_PAGE_CODE
|
||||
),
|
||||
"source_id": (
|
||||
str(config_info.get("points_source_id") or "").strip()
|
||||
or HUYA_DEFAULT_POINTS_SOURCE_ID
|
||||
),
|
||||
"scene": int(config_info.get("points_scene") or 0)
|
||||
or int(HUYA_DEFAULT_POINTS_SCENE),
|
||||
"page_id": int(config_info.get("points_page_id") or 0) or None,
|
||||
"tab_ids": tab_ids or None,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class PointsCenterCatalog:
|
||||
goods: list[dict] = field(default_factory=list)
|
||||
tabs: list[dict] = field(default_factory=list)
|
||||
sid: int | None = None
|
||||
season: dict | None = None
|
||||
payload: dict | None = None
|
||||
message: str = ""
|
||||
|
||||
|
||||
def fetch_points_center_catalog(
|
||||
uid: int,
|
||||
cookie: str,
|
||||
*,
|
||||
client: Any | None = None,
|
||||
page_code: str = HUYA_DEFAULT_POINTS_PAGE_CODE,
|
||||
source_id: str = HUYA_DEFAULT_POINTS_SOURCE_ID,
|
||||
scene: int = int(HUYA_DEFAULT_POINTS_SCENE),
|
||||
page_id: int | None = None,
|
||||
tab_ids: list[int] | None = None,
|
||||
include_all_tabs: bool = True,
|
||||
) -> PointsCenterCatalog:
|
||||
"""一次读取积分中心的商品、页签、SID 和赛季配置。
|
||||
|
||||
``include_all_tabs=False`` 仅供只取 SID/赛季的调用方使用,避免为了元数据
|
||||
额外请求所有商品页签。商品列表调用必须保持默认 ``True``。
|
||||
"""
|
||||
if client is None:
|
||||
from core.huya.http_client import HuyaHttpClient
|
||||
|
||||
client = HuyaHttpClient(
|
||||
logger=lambda message: logger.debug(f"[huya-points-center] {message}")
|
||||
)
|
||||
|
||||
def call(
|
||||
tab_id: int | None = None, tab_page_id: int | None = None
|
||||
) -> tuple[dict | None, str]:
|
||||
kwargs: dict[str, Any] = {
|
||||
"uid": int(uid),
|
||||
"guid": "",
|
||||
"cookie": cookie,
|
||||
"page_code": page_code,
|
||||
"source_id": source_id,
|
||||
"scene": scene,
|
||||
"deep": True,
|
||||
}
|
||||
if tab_id is not None:
|
||||
kwargs["page_id"] = int(page_id or tab_page_id or 0)
|
||||
kwargs["waterfall_tab_id"] = int(tab_id)
|
||||
try:
|
||||
response = client.play_mall_query_allocation(**kwargs)
|
||||
except Exception as exc: # noqa: BLE001 外部接口异常收敛为目录消息
|
||||
logger.debug(
|
||||
f"[huya-points-center] queryAllocation 异常:"
|
||||
f"{type(exc).__name__}: {exc}"
|
||||
)
|
||||
return None, f"{type(exc).__name__}: {_clip(exc)}"
|
||||
|
||||
if response is None:
|
||||
return None, "积分中心接口没有返回数据"
|
||||
code = getattr(response, "code", None)
|
||||
if code is None:
|
||||
code = getattr(response, "status", 0)
|
||||
code = int(code or 0)
|
||||
if code != 200:
|
||||
message = _clip(
|
||||
getattr(response, "message", "") or getattr(response, "msg", "")
|
||||
)
|
||||
return None, f"code={code}{(':' + message) if message else ''}"
|
||||
|
||||
payload = getattr(response, "payload", None)
|
||||
if payload is None and hasattr(response, "to_dict"):
|
||||
try:
|
||||
payload = (response.to_dict() or {}).get("payload")
|
||||
except Exception: # noqa: BLE001 第三方响应结构异常时按空处理
|
||||
payload = None
|
||||
return payload if isinstance(payload, dict) else None, ""
|
||||
|
||||
base_payload, error = call()
|
||||
if error:
|
||||
return PointsCenterCatalog(message=f"拉取商品失败:{error}")
|
||||
if base_payload is None:
|
||||
return PointsCenterCatalog(message="积分中心接口没有返回商品数据")
|
||||
|
||||
goods = parse_points_center_gifts(base_payload)
|
||||
tabs = extract_points_center_tabs(base_payload)
|
||||
sid = extract_points_center_sid(base_payload)
|
||||
season = extract_points_center_season(base_payload)
|
||||
if not include_all_tabs or (not goods and not tabs):
|
||||
message = (
|
||||
f"已拉取 {len(goods)} 个礼包(积分中心)"
|
||||
if goods
|
||||
else "积分中心没返回商品:接口通了但列表是空的"
|
||||
)
|
||||
return PointsCenterCatalog(
|
||||
goods=goods[:GIFTS_LIMIT],
|
||||
tabs=tabs,
|
||||
sid=sid,
|
||||
season=season,
|
||||
payload=base_payload,
|
||||
message=message,
|
||||
)
|
||||
|
||||
discovered = {(int(tab["page_id"]), int(tab["tab_id"])): tab for tab in tabs}
|
||||
loaded_categories = {str(gift.get("category_name") or "").strip() for gift in goods}
|
||||
tab_errors: list[str] = []
|
||||
if tab_ids:
|
||||
targets: list[dict] = []
|
||||
for tab_id in tab_ids:
|
||||
matched = next(
|
||||
(
|
||||
tab
|
||||
for (tab_page_id, tab_id_value), tab in discovered.items()
|
||||
if tab_id_value == int(tab_id)
|
||||
and (page_id is None or tab_page_id == int(page_id))
|
||||
),
|
||||
None,
|
||||
)
|
||||
if matched is not None:
|
||||
targets.append(matched)
|
||||
elif page_id is not None:
|
||||
targets.append(
|
||||
{
|
||||
"page_id": int(page_id),
|
||||
"tab_id": int(tab_id),
|
||||
"name": f"页签 {tab_id}",
|
||||
}
|
||||
)
|
||||
else:
|
||||
tab_errors.append(f"页签 {tab_id}:响应里没发现,且未配置 pageId")
|
||||
else:
|
||||
targets = [
|
||||
tab
|
||||
for tab in tabs
|
||||
if str(tab.get("name") or "").strip() not in loaded_categories
|
||||
]
|
||||
|
||||
seen_products = {
|
||||
str(gift.get("product_id") or "") for gift in goods if gift.get("product_id")
|
||||
}
|
||||
loaded_tabs = len(loaded_categories) if goods else 0
|
||||
for tab in targets:
|
||||
target_page_id = int(page_id or tab["page_id"])
|
||||
tab_payload, tab_error = call(int(tab["tab_id"]), target_page_id)
|
||||
if tab_error:
|
||||
tab_errors.append(f"{tab.get('name') or tab['tab_id']}:{tab_error}")
|
||||
continue
|
||||
tab_goods = parse_points_center_gifts(tab_payload)
|
||||
added = 0
|
||||
for gift in tab_goods:
|
||||
product_id = str(gift.get("product_id") or "")
|
||||
if product_id and product_id not in seen_products:
|
||||
seen_products.add(product_id)
|
||||
goods.append(gift)
|
||||
added += 1
|
||||
if added or tab_goods:
|
||||
loaded_tabs += 1
|
||||
|
||||
goods = goods[:GIFTS_LIMIT]
|
||||
if not goods:
|
||||
return PointsCenterCatalog(
|
||||
tabs=tabs,
|
||||
sid=sid,
|
||||
season=season,
|
||||
payload=base_payload,
|
||||
message="积分中心没返回商品:接口通了但列表是空的",
|
||||
)
|
||||
suffix = f",{loaded_tabs} 个页签" if loaded_tabs > 1 else ""
|
||||
if tab_errors:
|
||||
suffix += f";部分页签未加载:{';'.join(tab_errors[:3])}"
|
||||
return PointsCenterCatalog(
|
||||
goods=goods,
|
||||
tabs=tabs,
|
||||
sid=sid,
|
||||
season=season,
|
||||
payload=base_payload,
|
||||
message=f"已拉取 {len(goods)} 个礼包(积分中心{suffix})",
|
||||
)
|
||||
@@ -30,6 +30,10 @@ from sqlalchemy.orm import Session
|
||||
from core.huya.wss_client import POINTS_REDEEM_GOODS_NUM
|
||||
|
||||
from ..models import HuyaAccount, HuyaTask
|
||||
from .huya_points_center import (
|
||||
extract_points_center_season,
|
||||
fetch_points_center_catalog,
|
||||
)
|
||||
|
||||
# 宝典订单识别:spu 白名单 + 订单名兜底(官方换过多次 SKU,历史订单名带赛季,
|
||||
# 例如「精英宝典⎜得300积分⎜26年Q2」)。
|
||||
@@ -45,8 +49,6 @@ ELITE_OPENING_WINDOW_MS = 24 * 60 * 60 * 1000
|
||||
ELITE_PENDING_ORDER_STATUSES = frozenset({10, 1000})
|
||||
ELITE_CANCELLED_ORDER_STATUSES = frozenset({90, 1001})
|
||||
ELITE_PAID_ORDER_STATUSES = frozenset({20, 30, 40, 50, 55, 60, 70, 80})
|
||||
# 赛季(福利季)节点的毫秒时间戳下限:2001-09 之后的值才认
|
||||
ELITE_SEASON_MS_FLOOR = 1_000_000_000_000
|
||||
|
||||
|
||||
class EliteMixin:
|
||||
@@ -205,56 +207,20 @@ class EliteMixin:
|
||||
}
|
||||
return {"status": "unopened", "label": "未开通", "order": order}
|
||||
|
||||
@classmethod
|
||||
def _walk_season_nodes(cls, node: Any, found: list[dict]) -> None:
|
||||
"""递归找「赛季」节点:同时带 tag10/tag11 毫秒起止时间的结构。"""
|
||||
if isinstance(node, dict):
|
||||
start = node.get("tag10")
|
||||
end = node.get("tag11")
|
||||
if (
|
||||
isinstance(start, int)
|
||||
and isinstance(end, int)
|
||||
and start >= ELITE_SEASON_MS_FLOOR
|
||||
and end > start
|
||||
):
|
||||
found.append(
|
||||
{
|
||||
"name": str(node.get("tag2") or node.get("tag1") or ""),
|
||||
"start_ms": start,
|
||||
"end_ms": end,
|
||||
"config_id": node.get("tag0")
|
||||
if isinstance(node.get("tag0"), int)
|
||||
else None,
|
||||
}
|
||||
)
|
||||
for value in node.values():
|
||||
cls._walk_season_nodes(value, found)
|
||||
elif isinstance(node, list):
|
||||
for value in node:
|
||||
cls._walk_season_nodes(value, found)
|
||||
|
||||
@classmethod
|
||||
def _extract_elite_season(cls, payload: Any) -> dict | None:
|
||||
"""从积分中心页面配置里取宝典赛季(= 有效期)信息。
|
||||
|
||||
真机(2026-10-15 抓包)实证:``PlayMallUI.queryAllocation`` 响应里
|
||||
``tag2[1].tag2_2.tag0`` 是本赛季配置 —— tag1/tag2 = 「精英宝典福利季」/
|
||||
「精英宝典福利季丨Q4」,tag10/tag11 = 赛季起止毫秒时间戳
|
||||
(1791475200000 → 2026-10-09 00:00,1798732799000 → 2026-12-31 23:59:59)。
|
||||
这里不写死索引,按「带 tag10/tag11 的节点」找,取结束时间最晚的那个。
|
||||
"""
|
||||
found: list[dict] = []
|
||||
cls._walk_season_nodes(payload, found)
|
||||
if not found:
|
||||
return None
|
||||
return max(found, key=lambda item: item["end_ms"])
|
||||
"""兼容旧测试入口;唯一解析实现位于 ``huya_points_center``。"""
|
||||
return extract_points_center_season(payload)
|
||||
|
||||
def _resolve_elite_season(self, client: Any, uid: int, cookie: str) -> dict | None:
|
||||
"""查询积分中心页面配置并解析本赛季信息;查不到返回 None。"""
|
||||
resp = client.play_mall_query_allocation(uid=uid, guid="", cookie=cookie)
|
||||
if resp is None or getattr(resp, "code", 0) != 200:
|
||||
return None
|
||||
return self._extract_elite_season(getattr(resp, "payload", None))
|
||||
catalog = fetch_points_center_catalog(
|
||||
uid,
|
||||
cookie,
|
||||
client=client,
|
||||
include_all_tabs=False,
|
||||
)
|
||||
return catalog.season
|
||||
|
||||
def _refresh_elite_open_after_payment(
|
||||
self,
|
||||
|
||||
@@ -12,6 +12,10 @@ from core.huya.wss_client import POINTS_REDEEM_GOODS_NUM
|
||||
|
||||
from ..models import HuyaAccount, HuyaGoodsSnapshot, HuyaTask
|
||||
from .huya_pay_link import pay_qr_path, resolve_pay_targets
|
||||
from .huya_points_center import (
|
||||
fetch_points_center_catalog,
|
||||
points_center_options_from_config,
|
||||
)
|
||||
from .huya_points_exchange import (
|
||||
EXCHANGE_STATUS_EXCHANGED,
|
||||
EXCHANGE_STATUS_PAYMENT_REQUIRED,
|
||||
@@ -53,6 +57,54 @@ class GoodsMixin:
|
||||
def _wait_until(self, when: datetime, uid: int) -> bool: ...
|
||||
def _parse_scheduled_time(self, value: Any) -> datetime | None: ...
|
||||
|
||||
def _resolve_live_exchange_goods(
|
||||
self,
|
||||
client: Any,
|
||||
*,
|
||||
uid: int,
|
||||
cookie: str,
|
||||
config_info: dict,
|
||||
submitted_product_id: str,
|
||||
product_name: str,
|
||||
) -> tuple[dict | None, str]:
|
||||
"""用实时积分中心商品把旧 prize_id 或过期选择解析成当前 SPU。
|
||||
|
||||
2026-11-13 两份最新 HAR 确认:页面商品列表使用 queryAllocation 返回的
|
||||
``hy-*`` SPU;旧快照里的数字 prize_id 不能直接用于兑换。
|
||||
"""
|
||||
catalog = fetch_points_center_catalog(
|
||||
uid,
|
||||
cookie,
|
||||
client=client,
|
||||
**points_center_options_from_config(config_info),
|
||||
)
|
||||
goods, message = catalog.goods, catalog.message
|
||||
if not goods:
|
||||
return None, message or "实时商品列表为空"
|
||||
|
||||
wanted_name = product_name.strip()
|
||||
wanted_id = normalize_spu_id(submitted_product_id)
|
||||
if wanted_name:
|
||||
by_name = [
|
||||
item
|
||||
for item in goods
|
||||
if str(item.get("name") or "").strip() == wanted_name
|
||||
]
|
||||
if len(by_name) == 1:
|
||||
return by_name[0], ""
|
||||
if len(by_name) > 1 and wanted_id:
|
||||
for item in by_name:
|
||||
if normalize_spu_id(item.get("product_id")) == wanted_id:
|
||||
return item, ""
|
||||
if wanted_id:
|
||||
for item in goods:
|
||||
if normalize_spu_id(item.get("product_id")) == wanted_id:
|
||||
return item, ""
|
||||
return (
|
||||
None,
|
||||
"商品列表已更新,当前实时列表中找不到所选商品,请重新选择",
|
||||
)
|
||||
|
||||
def _execute_query_act_tasks(
|
||||
self,
|
||||
worker_db: Session,
|
||||
@@ -239,33 +291,21 @@ class GoodsMixin:
|
||||
self._mark_task(worker_db, task, "failed", "账号 Cookie 为空")
|
||||
return
|
||||
|
||||
from core.huya.shop_structs import extract_points_center_sid
|
||||
|
||||
client: Any = self._http_client()
|
||||
configured_sid = self._to_int(self.payload.get("sid") or config_info.get("sid"))
|
||||
sid_int = configured_sid
|
||||
sid_source = "config"
|
||||
try:
|
||||
page_code = (
|
||||
str(config_info.get("points_page_code") or "").strip()
|
||||
or "heping_baodian_credit_center_page"
|
||||
# 2026-11-13 HAR:兑换记录只借 queryAllocation 取活动 SID,
|
||||
# 不重复拉其它商品页签。
|
||||
catalog = fetch_points_center_catalog(
|
||||
uid,
|
||||
cookie,
|
||||
client=client,
|
||||
include_all_tabs=False,
|
||||
**points_center_options_from_config(config_info),
|
||||
)
|
||||
source_id = (
|
||||
str(config_info.get("points_source_id") or "").strip()
|
||||
or "yellowcarlist"
|
||||
)
|
||||
scene = self._to_int(config_info.get("points_scene")) or 7
|
||||
allocation = client.play_mall_query_allocation(
|
||||
uid=uid,
|
||||
guid="",
|
||||
cookie=cookie,
|
||||
page_code=page_code,
|
||||
source_id=source_id,
|
||||
scene=scene,
|
||||
deep=True,
|
||||
)
|
||||
payload = getattr(allocation, "payload", None)
|
||||
discovered_sid = extract_points_center_sid(payload)
|
||||
discovered_sid = catalog.sid
|
||||
if discovered_sid:
|
||||
sid_int = discovered_sid
|
||||
sid_source = "queryAllocation"
|
||||
@@ -335,36 +375,15 @@ class GoodsMixin:
|
||||
self._mark_task(worker_db, task, "failed", "账号 Cookie 为空")
|
||||
return
|
||||
|
||||
from .huya_collab_service import fetch_points_center_gifts
|
||||
|
||||
sid_int = self._to_int(config_info.get("sid")) or 2203
|
||||
page_code = (
|
||||
str(config_info.get("points_page_code") or "").strip()
|
||||
or "heping_baodian_credit_center_page"
|
||||
)
|
||||
source_id = (
|
||||
str(config_info.get("points_source_id") or "").strip() or "yellowcarlist"
|
||||
)
|
||||
scene = self._to_int(config_info.get("points_scene")) or 7
|
||||
page_id = self._to_int(config_info.get("points_page_id")) or None
|
||||
tab_ids = [
|
||||
int(part)
|
||||
for part in str(config_info.get("points_tab_ids") or "")
|
||||
.replace(",", ",")
|
||||
.replace(" ", ",")
|
||||
.split(",")
|
||||
if part.isdigit()
|
||||
]
|
||||
goods, message = fetch_points_center_gifts(
|
||||
query_options = points_center_options_from_config(config_info)
|
||||
catalog = fetch_points_center_catalog(
|
||||
uid,
|
||||
cookie,
|
||||
client=self._http_client(),
|
||||
page_code=page_code,
|
||||
source_id=source_id,
|
||||
scene=scene,
|
||||
page_id=page_id,
|
||||
tab_ids=tab_ids or None,
|
||||
**query_options,
|
||||
)
|
||||
goods, message = catalog.goods, catalog.message
|
||||
now = datetime.now(UTC)
|
||||
worker_db.query(HuyaGoodsSnapshot).filter(
|
||||
HuyaGoodsSnapshot.account_id == account.id,
|
||||
@@ -387,9 +406,9 @@ class GoodsMixin:
|
||||
result = {
|
||||
"source": "PlayMallUI.queryAllocation",
|
||||
"sid": sid_int,
|
||||
"page_code": page_code,
|
||||
"source_id": source_id,
|
||||
"scene": scene,
|
||||
"page_code": query_options["page_code"],
|
||||
"source_id": query_options["source_id"],
|
||||
"scene": query_options["scene"],
|
||||
"goods": goods,
|
||||
}
|
||||
if not goods:
|
||||
@@ -413,8 +432,9 @@ class GoodsMixin:
|
||||
account_info: dict,
|
||||
config_info: dict,
|
||||
):
|
||||
spu_id = normalize_spu_id(self.payload.get("product_id"))
|
||||
if not spu_id:
|
||||
submitted_product_id = normalize_spu_id(self.payload.get("product_id"))
|
||||
requested_product_name = str(self.payload.get("product_name") or "").strip()
|
||||
if not submitted_product_id and not requested_product_name:
|
||||
self._mark_task(worker_db, task, "failed", "请选择兑换商品")
|
||||
return
|
||||
|
||||
@@ -447,7 +467,13 @@ class GoodsMixin:
|
||||
pay_channel = self._normalize_pay_channel(
|
||||
self.payload.get("pay_channel") or config_info.get("pay_channel")
|
||||
)
|
||||
proxies, proxy_source, proxy_error = self._exchange_proxies()
|
||||
exchange_use_proxy = str(
|
||||
config_info.get("exchange_use_proxy") or "0"
|
||||
).strip().lower() in {"1", "true", "on", "yes"}
|
||||
if exchange_use_proxy:
|
||||
proxies, proxy_source, proxy_error = self._exchange_proxies()
|
||||
else:
|
||||
proxies, proxy_source, proxy_error = None, "disabled", ""
|
||||
if proxy_error:
|
||||
self._mark_task(
|
||||
worker_db,
|
||||
@@ -459,7 +485,35 @@ class GoodsMixin:
|
||||
return
|
||||
if proxies:
|
||||
self._push_log("info", f"[{uid}] 兑换任务使用代理: {proxy_source}")
|
||||
elif exchange_use_proxy:
|
||||
self._push_log("info", f"[{uid}] 兑换任务未使用代理: {proxy_source}")
|
||||
else:
|
||||
self._push_log("info", f"[{uid}] 兑换任务直连(兑换代理开关关闭)")
|
||||
client: Any = self._http_client(proxies=proxies)
|
||||
live_goods, live_goods_error = self._resolve_live_exchange_goods(
|
||||
client,
|
||||
uid=uid,
|
||||
cookie=cookie,
|
||||
config_info=config_info,
|
||||
submitted_product_id=submitted_product_id,
|
||||
product_name=requested_product_name,
|
||||
)
|
||||
if live_goods is None:
|
||||
self._mark_task(
|
||||
worker_db,
|
||||
task,
|
||||
"failed",
|
||||
f"实时商品校验失败:{live_goods_error}",
|
||||
{
|
||||
"submitted_product_id": submitted_product_id,
|
||||
"product_name": requested_product_name,
|
||||
"proxy_used": bool(proxies),
|
||||
"proxy_source": proxy_source,
|
||||
},
|
||||
)
|
||||
return
|
||||
spu_id = normalize_spu_id(live_goods.get("product_id"))
|
||||
product_name = str(live_goods.get("name") or requested_product_name or spu_id)
|
||||
prepared = prepare_exchange(
|
||||
client,
|
||||
uid=uid,
|
||||
@@ -472,8 +526,10 @@ class GoodsMixin:
|
||||
)
|
||||
common = {
|
||||
"spu_id": spu_id,
|
||||
"submitted_product_id": submitted_product_id,
|
||||
"resolved_product_id": spu_id,
|
||||
"product_name": (prepared.target.get("name") if prepared.target else "")
|
||||
or str(self.payload.get("product_name") or spu_id),
|
||||
or product_name,
|
||||
"scheduled_at": scheduled_at.isoformat() if scheduled_at else "",
|
||||
"executed_at": datetime.now(UTC).isoformat(),
|
||||
"redeem_state": prepared.state.to_dict() if prepared.state else None,
|
||||
|
||||
Reference in New Issue
Block a user