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,
|
||||
|
||||
Reference in New Issue
Block a user