feat: 重做协作台账状态机并支持充值核账

This commit is contained in:
yml2213
2026-10-19 16:06:02 +08:00
parent 781b27e63a
commit 3a6649a054
15 changed files with 2330 additions and 363 deletions
+96 -14
View File
@@ -41,8 +41,15 @@ def _strip_tail(body: bytes) -> bytes:
return body
def _decode_taf_value(ins: TafInputStream, dtype: int, depth: int = 0) -> object:
"""递归解码单个 TAF 值"""
def _decode_taf_value(
ins: TafInputStream,
dtype: int,
depth: int = 0,
*,
max_depth: int = 5,
keep_bytes: bool = False,
) -> object:
"""递归解码单个 TAF 值。"""
if dtype == TafType.ZERO:
return 0
if dtype in (TafType.INT8, TafType.INT16, TafType.INT32, TafType.INT64):
@@ -66,9 +73,21 @@ def _decode_taf_value(ins: TafInputStream, dtype: int, depth: int = 0) -> object
m = {}
for _ in range(cnt):
_, kt = ins.read_head()
k = _decode_taf_value(ins, kt, depth + 1)
k = _decode_taf_value(
ins,
kt,
depth + 1,
max_depth=max_depth,
keep_bytes=keep_bytes,
)
_, vt = ins.read_head()
v = _decode_taf_value(ins, vt, depth + 1)
v = _decode_taf_value(
ins,
vt,
depth + 1,
max_depth=max_depth,
keep_bytes=keep_bytes,
)
m[k] = v
return m
if dtype == TafType.LIST:
@@ -76,19 +95,40 @@ def _decode_taf_value(ins: TafInputStream, dtype: int, depth: int = 0) -> object
items = []
for _ in range(cnt):
_, it = ins.read_head()
items.append(_decode_taf_value(ins, it, depth + 1))
items.append(
_decode_taf_value(
ins,
it,
depth + 1,
max_depth=max_depth,
keep_bytes=keep_bytes,
)
)
return items
if dtype == TafType.SIMPLE_LIST:
ins.read_head() # element type INT8
ln = ins._read_int_len()
if keep_bytes:
return ins.buf.read(ln)
return f"<bytes {ln}B>"
if dtype == TafType.STRUCT_BEGIN:
return _decode_taf_struct(ins, depth + 1)
return _decode_taf_struct(
ins,
depth + 1,
max_depth=max_depth,
keep_bytes=keep_bytes,
)
return f"<0x{dtype:02x}>"
def _decode_taf_struct(ins: TafInputStream, depth: int = 0) -> dict:
"""解码一个 TAF 结构体 (已消费 STRUCT_BEGIN) → 有序字典"""
def _decode_taf_struct(
ins: TafInputStream,
depth: int = 0,
*,
max_depth: int = 5,
keep_bytes: bool = False,
) -> dict:
"""解码一个 TAF 结构体 (已消费 STRUCT_BEGIN) → 有序字典。"""
fields = {}
while True:
try:
@@ -99,10 +139,17 @@ def _decode_taf_struct(ins: TafInputStream, depth: int = 0) -> dict:
ins.read_head()
break
ins.read_head()
# 限制递归深度
if depth < 5:
# 默认只解 5 层,避免日志/通用接口被超深结构拖垮;
# queryAllocation 这类需要完整商品字段的调用方显式传 max_depth。
if depth < max_depth:
try:
val = _decode_taf_value(ins, dtype, depth)
val = _decode_taf_value(
ins,
dtype,
depth,
max_depth=max_depth,
keep_bytes=keep_bytes,
)
except Exception: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
val = f"<decode_err:0x{dtype:02x}>"
else:
@@ -215,11 +262,16 @@ def _decode_wup_body(body: bytes) -> dict:
return result
def decode_struct_bytes(data: bytes) -> dict:
def decode_struct_bytes(
data: bytes,
*,
max_depth: int = 5,
keep_bytes: bool = False,
) -> dict:
"""把裸结构体字节解成通用 dict(``tagN`` → 值);非结构体或解析失败返回 {}。
WSS 与 HTTP 两条通道都要用「未逐字段建模」的通用解码,统一放在这里,
避免两边各写一份。
避免两边各写一份。``max_depth`` 默认保持 5 层;需要完整商品字段时显式传大值。
"""
if not isinstance(data, bytes) or not data:
return {}
@@ -229,11 +281,41 @@ def decode_struct_bytes(data: bytes) -> dict:
if dtype != TafType.STRUCT_BEGIN:
return {}
ins.read_head()
return _decode_taf_struct(ins)
return _decode_taf_struct(
ins,
max_depth=max_depth,
keep_bytes=keep_bytes,
)
except Exception: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
return {}
def decode_value_bytes(
data: bytes,
*,
max_depth: int = 40,
keep_bytes: bool = True,
) -> object:
"""把裸 TAF 值(LIST / STRUCT / MAP 等,含 tag+type 头)解成通用对象。
``queryAllocation`` 的商品列表放在 SIMPLE_LIST 里,内容本身又是一个 TAF LIST;
这里专门给这种嵌套结构用,默认保留字节、放宽深度。
"""
if not isinstance(data, bytes) or not data:
return None
ins = TafInputStream(data)
try:
_tag, dtype = ins.read_head()
return _decode_taf_value(
ins,
dtype,
max_depth=max_depth,
keep_bytes=keep_bytes,
)
except Exception: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
return None
def _truncate(obj, max_str=80):
"""截断过长的值,使日志紧凑"""
if isinstance(obj, str):
+29 -4
View File
@@ -1239,12 +1239,25 @@ class HuyaHttpClient:
# ============================================================
@staticmethod
def _raw_from_wup(wup_resp: WupResponse):
def _raw_from_wup(
wup_resp: WupResponse,
*,
max_depth: int = 5,
keep_bytes: bool = False,
):
"""已解码的 WUP 响应 → ShopRawRsp(未逐字段建模的接口用)。"""
from .shop_structs import ShopRawRsp
data = wup_resp.newdata.get("tRsp") or wup_resp.newdata.get("tResp")
payload = decode_struct_bytes(data) if isinstance(data, bytes) else {}
payload = (
decode_struct_bytes(
data,
max_depth=max_depth,
keep_bytes=keep_bytes,
)
if isinstance(data, bytes)
else {}
)
return ShopRawRsp.from_payload(payload)
def get_supplier_info(
@@ -1339,8 +1352,14 @@ class HuyaHttpClient:
source_id: str = "yellowcarlist",
page_code: str = "heping_baodian_credit_center_page",
timeout: float = 15.0,
*,
deep: bool = False,
):
"""PlayMallUI.queryAllocation(积分中心配额查询)。"""
"""PlayMallUI.queryAllocation(积分中心配额查询)。
``deep=True`` 时保留 ``tag2[].tag5`` 的原始字节并放宽解码深度,
供 :func:`core.huya.shop_structs.parse_points_center_gifts` 解析商品列表。
"""
from .shop_structs import PlayMallQueryAllocationReq
req = PlayMallQueryAllocationReq()
@@ -1357,7 +1376,13 @@ class HuyaHttpClient:
cookie,
timeout=timeout,
)
return self._raw_from_wup(resp) if isinstance(resp, WupResponse) else None
if not isinstance(resp, WupResponse):
return None
return self._raw_from_wup(
resp,
max_depth=40 if deep else 5,
keep_bytes=deep,
)
def play_mall_get_my_promotion(
self,
+102
View File
@@ -7,6 +7,7 @@
from typing import Any
from .frame_decoder import decode_value_bytes
from .taf_protocol import TafInputStream, TafOutputStream, TafStruct, TafType
@@ -1150,6 +1151,107 @@ class ShopRawRsp:
return {"code": self.code, "message": self.message, "payload": self.payload}
def _as_int(value: Any) -> int | None:
"""尽力把 TAF 解出来的数字转成 int;空值/脏值返回 None。"""
if value is None or isinstance(value, bool):
return None
try:
return int(value)
except (TypeError, ValueError):
return None
def _as_text(value: Any) -> str:
return str(value).strip() if value is not None else ""
def parse_points_center_gifts(payload: dict | None) -> list[dict]:
"""解析 ``PlayMallUI.queryAllocation`` 响应里的积分中心商品。
真机(2026-10-19 HAR)结构::
payload.tag2[0].tag5 # SIMPLE_LIST,内容是 TAF LIST
→ 分类 tag6
→ 商品 tag1.tag0
→ tag0 SPU(hy-xxxx)
→ tag2 名称
→ tag4 分类名
→ tag5 图标
→ tag9/tag10 金额(分,不是积分)
→ tag13 库存
→ tag75.tag0.tag2 积分
→ tag34.tag26 积分(重复字段,兜底)
注意:``tag13`` 在这里是库存,不是 ``ActPrizeItem.price`` 的那个 tag13。
"""
if not isinstance(payload, dict):
return []
gifts: list[dict] = []
seen: set[str] = set()
for section in payload.get("tag2") or []:
if not isinstance(section, dict):
continue
blob = section.get("tag5")
if not isinstance(blob, (bytes, bytearray)):
continue
categories = decode_value_bytes(bytes(blob), max_depth=40, keep_bytes=True)
if not isinstance(categories, list):
continue
for category in categories:
if not isinstance(category, dict):
continue
category_name = _as_text(category.get("tag1"))
for good in category.get("tag6") or []:
if not isinstance(good, dict):
continue
info = good.get("tag1")
basic = info.get("tag0") if isinstance(info, dict) else None
if not isinstance(basic, dict):
continue
spu = _as_text(basic.get("tag0"))
name = _as_text(basic.get("tag2"))
if not spu or not name:
continue
if spu in seen:
continue
seen.add(spu)
score_box = basic.get("tag75")
score_info = (
score_box.get("tag0") if isinstance(score_box, dict) else None
)
points = (
_as_int(score_info.get("tag2"))
if isinstance(score_info, dict)
else None
)
if points is None:
game_box = basic.get("tag34")
points = (
_as_int(game_box.get("tag26"))
if isinstance(game_box, dict)
else None
)
stock = _as_int(basic.get("tag13"))
gifts.append(
{
"product_id": spu,
"name": name[:256],
"price": points,
"remain_text": f"剩{stock}" if stock is not None else "",
"stock": stock,
"score": points,
"category_name": (_as_text(basic.get("tag4")) or category_name)[
:64
],
"icon": _as_text(basic.get("tag5"))[:512],
}
)
return gifts
class PlayMallAppInfo(TafStruct):
"""PlayMallUI 系接口的应用信息。
+46 -6
View File
@@ -817,7 +817,12 @@ class HuyaWssClient:
await self.ws.send(msg.encode())
@staticmethod
def _decode_rsp_dict(body: bytes) -> dict:
def _decode_rsp_dict(
body: bytes,
*,
max_depth: int = 5,
keep_bytes: bool = False,
) -> dict:
"""把 RPC 响应的 tRsp 解成通用 dict(未建模的接口用它取字段)。"""
try:
wup_resp = WupResponse()
@@ -825,14 +830,34 @@ class HuyaWssClient:
except Exception: # noqa: BLE001 响应解析失败按空结构处理
return {}
data = wup_resp.newdata.get("tRsp") or wup_resp.newdata.get("tResp")
return decode_struct_bytes(data) if isinstance(data, bytes) else {}
return (
decode_struct_bytes(
data,
max_depth=max_depth,
keep_bytes=keep_bytes,
)
if isinstance(data, bytes)
else {}
)
@classmethod
def _raw_rsp_from_body(cls, body: bytes):
def _raw_rsp_from_body(
cls,
body: bytes,
*,
max_depth: int = 5,
keep_bytes: bool = False,
):
"""响应 → ShopRawRsp(code/message + 通用解码结构)。"""
from .shop_structs import ShopRawRsp
return ShopRawRsp.from_payload(cls._decode_rsp_dict(body))
return ShopRawRsp.from_payload(
cls._decode_rsp_dict(
body,
max_depth=max_depth,
keep_bytes=keep_bytes,
)
)
async def call_rpc_raw(
self,
@@ -1385,15 +1410,30 @@ class HuyaWssClient:
cookie: str,
source_id: str = "yellowcarlist",
page_code: str = POINTS_PAGE_CODE,
*,
deep: bool = False,
):
"""PlayMallUI.queryAllocation — 积分中心页面配额查询。"""
"""PlayMallUI.queryAllocation — 积分中心页面配额查询。
``deep=True`` 时保留 ``tag2[].tag5`` 原始字节并放宽解码深度,
供 ``parse_points_center_gifts`` 解析完整商品列表。
"""
from .shop_structs import PlayMallQueryAllocationReq
req = PlayMallQueryAllocationReq()
req.userId = self._build_biz_user(uid, cookie)
req.appInfo = self._build_play_mall_app(source_id)
req.pageCode = page_code
return await self.call_rpc_raw("PlayMallUI", "queryAllocation", req)
if not deep:
return await self.call_rpc_raw("PlayMallUI", "queryAllocation", req)
body = await self.call_rpc("PlayMallUI", "queryAllocation", req, None)
if body is None:
return None
return self._raw_rsp_from_body(
body,
max_depth=40,
keep_bytes=True,
)
async def play_mall_get_my_promotion(
self,