统一推送前Python代码格式

This commit is contained in:
yml2213
2026-09-05 19:25:46 +08:00
parent 90a0065918
commit 8309072120
17 changed files with 492 additions and 189 deletions
+99 -47
View File
@@ -139,10 +139,14 @@ class ActInfoItem(TafStruct):
def read_from(self, ins: TafInputStream): def read_from(self, ins: TafInputStream):
for tag, attr, reader in ( for tag, attr, reader in (
(0, "actId", ins.read_int64), (1, "name", ins.read_string), (0, "actId", ins.read_int64),
(2, "startTime", ins.read_int64), (3, "endTime", ins.read_int64), (1, "name", ins.read_string),
(4, "moduleId", ins.read_int64), (5, "outerActId", ins.read_string), (2, "startTime", ins.read_int64),
(6, "gameIdList", ins.read_string), (8, "gid", ins.read_int64), (3, "endTime", ins.read_int64),
(4, "moduleId", ins.read_int64),
(5, "outerActId", ins.read_string),
(6, "gameIdList", ins.read_string),
(8, "gid", ins.read_int64),
): ):
setattr(self, attr, reader(tag, default=getattr(self, attr))) setattr(self, attr, reader(tag, default=getattr(self, attr)))
@@ -157,10 +161,16 @@ class ActInfoItem(TafStruct):
os.write_int64(8, self.gid) os.write_int64(8, self.gid)
def to_dict(self) -> dict: def to_dict(self) -> dict:
return {"act_id": self.actId, "name": self.name, "start_time": self.startTime, return {
"end_time": self.endTime, "module_id": self.moduleId, "act_id": self.actId,
"outer_act_id": self.outerActId, "game_id_list": self.gameIdList, "name": self.name,
"gid": self.gid} "start_time": self.startTime,
"end_time": self.endTime,
"module_id": self.moduleId,
"outer_act_id": self.outerActId,
"game_id_list": self.gameIdList,
"gid": self.gid,
}
class GetActInfoResp(TafStruct): class GetActInfoResp(TafStruct):
@@ -181,8 +191,11 @@ class GetActInfoResp(TafStruct):
os.write_struct(2, self.info) os.write_struct(2, self.info)
def to_dict(self) -> dict: def to_dict(self) -> dict:
return {"status": self.status, "msg": self.msg, return {
"info": self.info.to_dict() if self.info else None} "status": self.status,
"msg": self.msg,
"info": self.info.to_dict() if self.info else None,
}
class GetActPrizeListReq(TafStruct): class GetActPrizeListReq(TafStruct):
@@ -298,18 +311,30 @@ class ActPrizeDetailItem(TafStruct):
def read_from(self, ins: TafInputStream): def read_from(self, ins: TafInputStream):
readers = { readers = {
0: ("prizeId", ins.read_int64), 2: ("name", ins.read_string), 0: ("prizeId", ins.read_int64),
3: ("score", ins.read_int64), 5: ("icon", ins.read_string), 2: ("name", ins.read_string),
6: ("frequency", ins.read_int32), 7: ("frequencyLimit", ins.read_int32), 3: ("score", ins.read_int64),
8: ("num", ins.read_int64), 9: ("status", ins.read_int32), 5: ("icon", ins.read_string),
10: ("leftNum", ins.read_int64), 11: ("isShowNum", ins.read_int32), 6: ("frequency", ins.read_int32),
12: ("percent", ins.read_string), 13: ("newScore", ins.read_int64), 7: ("frequencyLimit", ins.read_int32),
14: ("categoryId", ins.read_string), 17: ("usedNum", ins.read_int64), 8: ("num", ins.read_int64),
18: ("goodType", ins.read_int32), 22: ("commonPrizeId", ins.read_int64), 9: ("status", ins.read_int32),
23: ("updateTime", ins.read_int64), 24: ("isCanExchange", ins.read_int32), 10: ("leftNum", ins.read_int64),
25: ("exchangeStartTime", ins.read_int64), 26: ("exchangeEndTime", ins.read_int64), 11: ("isShowNum", ins.read_int32),
27: ("startTimeSlot", ins.read_string), 28: ("endTimeSlot", ins.read_string), 12: ("percent", ins.read_string),
29: ("isTodayLimit", ins.read_int32), 30: ("isUserLimit", ins.read_int32), 13: ("newScore", ins.read_int64),
14: ("categoryId", ins.read_string),
17: ("usedNum", ins.read_int64),
18: ("goodType", ins.read_int32),
22: ("commonPrizeId", ins.read_int64),
23: ("updateTime", ins.read_int64),
24: ("isCanExchange", ins.read_int32),
25: ("exchangeStartTime", ins.read_int64),
26: ("exchangeEndTime", ins.read_int64),
27: ("startTimeSlot", ins.read_string),
28: ("endTimeSlot", ins.read_string),
29: ("isTodayLimit", ins.read_int32),
30: ("isUserLimit", ins.read_int32),
} }
while True: while True:
pos = ins.buf.tell() pos = ins.buf.tell()
@@ -353,19 +378,30 @@ class ActPrizeDetailItem(TafStruct):
def to_dict(self) -> dict: def to_dict(self) -> dict:
return { return {
"product_id": str(self.prizeId), "name": self.name, "score": self.score, "product_id": str(self.prizeId),
"icon": self.icon, "frequency": self.frequency, "name": self.name,
"frequency_limit": self.frequencyLimit, "num": self.num, "score": self.score,
"status": self.status, "left_num": self.leftNum, "icon": self.icon,
"is_show_num": self.isShowNum, "percent": self.percent, "frequency": self.frequency,
"new_score": self.newScore, "category_id": self.categoryId, "frequency_limit": self.frequencyLimit,
"used_num": self.usedNum, "good_type": self.goodType, "num": self.num,
"common_prize_id": self.commonPrizeId, "update_time": self.updateTime, "status": self.status,
"left_num": self.leftNum,
"is_show_num": self.isShowNum,
"percent": self.percent,
"new_score": self.newScore,
"category_id": self.categoryId,
"used_num": self.usedNum,
"good_type": self.goodType,
"common_prize_id": self.commonPrizeId,
"update_time": self.updateTime,
"is_can_exchange": self.isCanExchange, "is_can_exchange": self.isCanExchange,
"exchange_start_time": self.exchangeStartTime, "exchange_start_time": self.exchangeStartTime,
"exchange_end_time": self.exchangeEndTime, "exchange_end_time": self.exchangeEndTime,
"start_time_slot": self.startTimeSlot, "end_time_slot": self.endTimeSlot, "start_time_slot": self.startTimeSlot,
"is_today_limit": self.isTodayLimit, "is_user_limit": self.isUserLimit, "end_time_slot": self.endTimeSlot,
"is_today_limit": self.isTodayLimit,
"is_user_limit": self.isUserLimit,
} }
@@ -395,9 +431,12 @@ class GetActPrizeDetailResp(TafStruct):
os.write_struct(2, envelope) os.write_struct(2, envelope)
def to_dict(self) -> dict: def to_dict(self) -> dict:
return {"status": self.status, "msg": self.msg, return {
"prize": self.prize.to_dict() if self.prize else None, "status": self.status,
"detail_status": self.detailStatus} "msg": self.msg,
"prize": self.prize.to_dict() if self.prize else None,
"detail_status": self.detailStatus,
}
class _ActPrizeDetailEnvelope(TafStruct): class _ActPrizeDetailEnvelope(TafStruct):
@@ -666,10 +705,14 @@ class UserActTaskItem(TafStruct):
def read_from(self, ins: TafInputStream): def read_from(self, ins: TafInputStream):
for tag, attr, reader in ( for tag, attr, reader in (
(0, "actId", ins.read_int64), (1, "taskId", ins.read_int64), (0, "actId", ins.read_int64),
(2, "taskStatus", ins.read_int32), (3, "prizeStatus", ins.read_int32), (1, "taskId", ins.read_int64),
(4, "taskValue", ins.read_string), (5, "taskCount", ins.read_int64), (2, "taskStatus", ins.read_int32),
(6, "prizeCount", ins.read_int64), (8, "subTaskDetail", ins.read_int64), (3, "prizeStatus", ins.read_int32),
(4, "taskValue", ins.read_string),
(5, "taskCount", ins.read_int64),
(6, "prizeCount", ins.read_int64),
(8, "subTaskDetail", ins.read_int64),
(9, "extraStatus", ins.read_int64), (9, "extraStatus", ins.read_int64),
): ):
setattr(self, attr, reader(tag, default=getattr(self, attr))) setattr(self, attr, reader(tag, default=getattr(self, attr)))
@@ -695,11 +738,17 @@ class UserActTaskItem(TafStruct):
return item return item
def to_dict(self) -> dict: def to_dict(self) -> dict:
return {"act_id": self.actId, "task_id": self.taskId, return {
"task_status": self.taskStatus, "prize_status": self.prizeStatus, "act_id": self.actId,
"task_value": self.taskValue, "task_count": self.taskCount, "task_id": self.taskId,
"prize_count": self.prizeCount, "sub_task_detail": self.subTaskDetail, "task_status": self.taskStatus,
"extra_status": self.extraStatus} "prize_status": self.prizeStatus,
"task_value": self.taskValue,
"task_count": self.taskCount,
"prize_count": self.prizeCount,
"sub_task_detail": self.subTaskDetail,
"extra_status": self.extraStatus,
}
class GetActUserTaskDetailResp(TafStruct): class GetActUserTaskDetailResp(TafStruct):
@@ -719,9 +768,12 @@ class GetActUserTaskDetailResp(TafStruct):
os.write_list(2, self.tasks) os.write_list(2, self.tasks)
def to_dict(self) -> dict: def to_dict(self) -> dict:
return {"status": self.status, "msg": self.msg, return {
"task_count": len(self.tasks), "status": self.status,
"tasks": [item.to_dict() for item in self.tasks]} "msg": self.msg,
"task_count": len(self.tasks),
"tasks": [item.to_dict() for item in self.tasks],
}
class ActTaskPrizeInfo(TafStruct): class ActTaskPrizeInfo(TafStruct):
+13 -5
View File
@@ -16,6 +16,7 @@
``guid`` / ``_qimei_uuid42`` / ``__yamid_new`` / ``game_did`` 仍无服务端 ``guid`` / ``_qimei_uuid42`` / ``__yamid_new`` / ``game_did`` 仍无服务端
签发接口,本模块不生成、不伪造它们。 签发接口,本模块不生成、不伪造它们。
""" """
from __future__ import annotations from __future__ import annotations
import argparse import argparse
@@ -92,8 +93,10 @@ def fetch_anonymous_device_state(
context = ( context = (
"WB-" "WB-"
+ secrets.token_hex(16) + secrets.token_hex(16)
+ "-" + secrets.token_hex(16) + "-"
+ "-" + secrets.token_hex(16) + secrets.token_hex(16)
+ "-"
+ secrets.token_hex(16)
) )
payload = { payload = {
"uri": "10013", "uri": "10013",
@@ -142,7 +145,10 @@ def fetch_anonymous_device_state(
logger.info( logger.info(
"[huya-anon] 匿名设备态 OK: deviceid={}... guiddata={}... " "[huya-anon] 匿名设备态 OK: deviceid={}... guiddata={}... "
"anouid={} biztoken={}...", "anouid={} biztoken={}...",
deviceid[:14], guiddata[:8], anouid, biztoken[:10], deviceid[:14],
guiddata[:8],
anouid,
biztoken[:10],
) )
return { return {
"udb_deviceid": deviceid, "udb_deviceid": deviceid,
@@ -169,9 +175,11 @@ def main() -> int:
else: else:
for key, value in state.items(): for key, value in state.items():
print(f"{key} = {value}") print(f"{key} = {value}")
print("\n(4/7 字段;guid/_qimei_uuid42/__yamid_new/game_did 无服务端签发,不生成)") print(
"\n(4/7 字段;guid/_qimei_uuid42/__yamid_new/game_did 无服务端签发,不生成)"
)
return 0 return 0
if __name__ == "__main__": if __name__ == "__main__":
raise SystemExit(main()) raise SystemExit(main())
+36 -13
View File
@@ -568,14 +568,35 @@ class HuyaAppPasswordLogin:
# 设备/统计字段不推导、不随机生成;仅转发已知真实值。 # 设备/统计字段不推导、不随机生成;仅转发已知真实值。
optional_keys = ( optional_keys = (
"guid", "udb_guiddata", "__yamid_new", "guid",
"game_did", "_qimei_uuid42", "_qimei_fingerprint", "_qimei_h38", "udb_guiddata",
"udb_anouid", "udb_anobiztoken", "__yasmid", "__yamid_tt1", "__yamid_new",
"SoundValue", "alphaValue", "isInLiveRoom", "udb_deviceid", "game_did",
"udb_passdata", "_rep_cnt", "Hm_lvt_51700b6c722f5bb4cf39906a596ea41f", "_qimei_uuid42",
"HMACCOUNT", "udb_appid", "rep_cnt", "udb_accdata", "h_unt", "_qimei_fingerprint",
"__yaoldyyuid", "_yasids", "huya_flash_rep_cnt", "huyasp_rep_cnt", "_qimei_h38",
"huya_hd_rep_cnt", "Hm_lpvt_51700b6c722f5bb4cf39906a596ea41f", "udb_anouid",
"udb_anobiztoken",
"__yasmid",
"__yamid_tt1",
"SoundValue",
"alphaValue",
"isInLiveRoom",
"udb_deviceid",
"udb_passdata",
"_rep_cnt",
"Hm_lvt_51700b6c722f5bb4cf39906a596ea41f",
"HMACCOUNT",
"udb_appid",
"rep_cnt",
"udb_accdata",
"h_unt",
"__yaoldyyuid",
"_yasids",
"huya_flash_rep_cnt",
"huyasp_rep_cnt",
"huya_hd_rep_cnt",
"Hm_lpvt_51700b6c722f5bb4cf39906a596ea41f",
"huya_web_rep_cnt", "huya_web_rep_cnt",
) )
for key in optional_keys: for key in optional_keys:
@@ -591,9 +612,7 @@ class HuyaAppPasswordLogin:
set_value("udb_deviceid", web_device_id, overwrite=True) set_value("udb_deviceid", web_device_id, overwrite=True)
if not include_transient: if not include_transient:
pairs = [ pairs = [
(key, value) (key, value) for key, value in pairs if key != "web_qrlogin_confirm_id"
for key, value in pairs
if key != "web_qrlogin_confirm_id"
] ]
return normalize_cookie_pairs(pairs) return normalize_cookie_pairs(pairs)
@@ -687,8 +706,12 @@ class HuyaAppPasswordLogin:
merge_device_info = dict(self.device_info) merge_device_info = dict(self.device_info)
for key, value in (sdid_obj.cookies or {}).items(): for key, value in (sdid_obj.cookies or {}).items():
if key in WEB_DEVICE_COOKIE_KEYS or key in { if key in WEB_DEVICE_COOKIE_KEYS or key in {
"udb_appid", "__yasmid", "__yamid_tt1", "udb_anouid", "udb_appid",
"udb_anobiztoken", "udb_deviceid", "__yasmid",
"__yamid_tt1",
"udb_anouid",
"udb_anobiztoken",
"udb_deviceid",
}: }:
merge_device_info.setdefault(key, value) merge_device_info.setdefault(key, value)
# 匿名设备态协议补齐(middle + anonymousLogin 签发 4 字段), # 匿名设备态协议补齐(middle + anonymousLogin 签发 4 字段),
+3 -1
View File
@@ -82,7 +82,9 @@ def browser_login_script(
脚本把 Cookie 写入指定域后跳转目标页;Cookie 值以 JSON 数组内联, 脚本把 Cookie 写入指定域后跳转目标页;Cookie 值以 JSON 数组内联,
保证引号、反斜杠等字符安全转义。 保证引号、反斜杠等字符安全转义。
""" """
payload = json.dumps([[key, value] for key, value in pairs.items()], ensure_ascii=False) payload = json.dumps(
[[key, value] for key, value in pairs.items()], ensure_ascii=False
)
target = json.dumps(target_url, ensure_ascii=False) target = json.dumps(target_url, ensure_ascii=False)
ttl_ms = max(1, ttl_days) * 86_400_000 ttl_ms = max(1, ttl_days) * 86_400_000
return ( return (
+53 -13
View File
@@ -349,7 +349,11 @@ class HuyaHttpClient:
# ---------- 业务便捷方法 ---------- # ---------- 业务便捷方法 ----------
def get_act_info( def get_act_info(
self, act_id: int, act_uuid: str = "", app_source: str = "", timeout: float = 15.0 self,
act_id: int,
act_uuid: str = "",
app_source: str = "",
timeout: float = 15.0,
): ):
"""读取活动主信息,用于驱动当前活动配置。""" """读取活动主信息,用于驱动当前活动配置。"""
from .activity_structs import GetActInfoReq, GetActInfoResp from .activity_structs import GetActInfoReq, GetActInfoResp
@@ -358,7 +362,9 @@ class HuyaHttpClient:
req.actId = int(act_id or 0) req.actId = int(act_id or 0)
req.actUuid = act_uuid req.actUuid = act_uuid
req.appSource = app_source req.appSource = app_source
return self.call_rpc("webActUI", "getActInfo", req, GetActInfoResp, timeout=timeout) return self.call_rpc(
"webActUI", "getActInfo", req, GetActInfoResp, timeout=timeout
)
def get_act_user_task_detail( def get_act_user_task_detail(
self, uid: int, cookie: str, act_id: int, timeout: float = 15.0 self, uid: int, cookie: str, act_id: int, timeout: float = 15.0
@@ -370,8 +376,13 @@ class HuyaHttpClient:
req.userId = self._build_activity_user(uid, cookie) req.userId = self._build_activity_user(uid, cookie)
req.actId = int(act_id or 0) req.actId = int(act_id or 0)
return self.call_rpc( return self.call_rpc(
"webActUI", "getActUserTaskDetail", req, GetActUserTaskDetailResp, "webActUI",
uid=uid, cookie=cookie, timeout=timeout, "getActUserTaskDetail",
req,
GetActUserTaskDetailResp,
uid=uid,
cookie=cookie,
timeout=timeout,
) )
def query_user_score(self, uid: int, cookie: str, sid: int, timeout: float = 15.0): def query_user_score(self, uid: int, cookie: str, sid: int, timeout: float = 15.0):
@@ -852,8 +863,14 @@ class HuyaHttpClient:
) )
def list_pay_channels( def list_pay_channels(
self, uid: int, guid: str, cookie: str, spu_id: str, sku_id: int, self,
supplier_id: int = 87401, timeout: float = 15.0, uid: int,
guid: str,
cookie: str,
spu_id: str,
sku_id: int,
supplier_id: int = 87401,
timeout: float = 15.0,
): ):
from .shop_structs import ListPayChannelReq, ListPayChannelRsp from .shop_structs import ListPayChannelReq, ListPayChannelRsp
@@ -864,8 +881,14 @@ class HuyaHttpClient:
req.spuId = spu_id req.spuId = spu_id
req.skuId = int(sku_id or 0) req.skuId = int(sku_id or 0)
return self.call_rpc( return self.call_rpc(
"shopMiddleUI", "listPayChannelV5", req, ListPayChannelRsp, "shopMiddleUI",
uid, guid, cookie, timeout=timeout, "listPayChannelV5",
req,
ListPayChannelRsp,
uid,
guid,
cookie,
timeout=timeout,
) )
def check_hy_protocol( def check_hy_protocol(
@@ -877,12 +900,23 @@ class HuyaHttpClient:
req.userId = self._build_shop_user(uid, cookie) req.userId = self._build_shop_user(uid, cookie)
req.shopAppInfo = self._build_shop_app("yellowcarlist", 4) req.shopAppInfo = self._build_shop_app("yellowcarlist", 4)
return self.call_rpc( return self.call_rpc(
"shopMiddleUI", "checkHyProtocolV5", req, ShopCodeRsp, "shopMiddleUI",
uid, guid, cookie, timeout=timeout, "checkHyProtocolV5",
req,
ShopCodeRsp,
uid,
guid,
cookie,
timeout=timeout,
) )
def check_user_buy_auth( def check_user_buy_auth(
self, uid: int, guid: str, cookie: str, spu_id: str, sku_id: int, self,
uid: int,
guid: str,
cookie: str,
spu_id: str,
sku_id: int,
timeout: float = 15.0, timeout: float = 15.0,
): ):
from .shop_structs import CheckUserBuyAuthReq, ShopCodeRsp from .shop_structs import CheckUserBuyAuthReq, ShopCodeRsp
@@ -893,8 +927,14 @@ class HuyaHttpClient:
req.spuId = spu_id req.spuId = spu_id
req.skuId = int(sku_id or 0) req.skuId = int(sku_id or 0)
return self.call_rpc( return self.call_rpc(
"shopMiddleUI", "checkUserBuyAuth", req, ShopCodeRsp, "shopMiddleUI",
uid, guid, cookie, timeout=timeout, "checkUserBuyAuth",
req,
ShopCodeRsp,
uid,
guid,
cookie,
timeout=timeout,
) )
def query_user_order_list( def query_user_order_list(
+8 -4
View File
@@ -17,8 +17,10 @@ def _fake_response(status=200, headers=None, text="", json_body=None):
resp.status_code = status resp.status_code = status
resp.headers = headers or {} resp.headers = headers or {}
resp.text = text resp.text = text
resp.json = Mock(return_value=json_body) if json_body is not None else Mock( resp.json = (
side_effect=ValueError("bad json") Mock(return_value=json_body)
if json_body is not None
else Mock(side_effect=ValueError("bad json"))
) )
return resp return resp
@@ -36,7 +38,9 @@ def test_fetches_four_fields_from_middle_and_anon(monkeypatch):
session = Mock(spec=requests.Session) session = Mock(spec=requests.Session)
deviceid = "w_1147246591246680065" deviceid = "w_1147246591246680065"
session.get.return_value = _fake_response( session.get.return_value = _fake_response(
headers={"Set-Cookie": f"udb_deviceid={deviceid}; Max-Age=315360000; Domain=huya.com"} headers={
"Set-Cookie": f"udb_deviceid={deviceid}; Max-Age=315360000; Domain=huya.com"
}
) )
session.post.return_value = _fake_response(json_body=_fake_anon_body()) session.post.return_value = _fake_response(json_body=_fake_anon_body())
monkeypatch.setattr("core.huya.anon_device._new_session", lambda **kw: session) monkeypatch.setattr("core.huya.anon_device._new_session", lambda **kw: session)
@@ -129,4 +133,4 @@ def test_non_json_anon_body_raises(monkeypatch):
monkeypatch.setattr("core.huya.anon_device._new_session", lambda **kw: session) monkeypatch.setattr("core.huya.anon_device._new_session", lambda **kw: session)
with pytest.raises(AnonymousDeviceError, match="非 JSON"): with pytest.raises(AnonymousDeviceError, match="非 JSON"):
fetch_anonymous_device_state(session=session) fetch_anonymous_device_state(session=session)
+26 -5
View File
@@ -98,10 +98,24 @@ def test_app_login_cookie_does_not_fabricate_browser_state():
) )
values = dict(item.split("=", 1) for item in cookie.split("; ")) values = dict(item.split("=", 1) for item in cookie.split("; "))
assert set(values) == { assert set(values) == {
"udb_cred", "udb_uid", "yyuid", "udb_version", "udb_biztoken", "udb_cred",
"udb_origin", "udb_status", "sdid", "hdid", "udb_passport", "username", "udb_uid",
"yyuid",
"udb_version",
"udb_biztoken",
"udb_origin",
"udb_status",
"sdid",
"hdid",
"udb_passport",
"username",
} }
assert not {"_qimei_uuid42", "_qimei_fingerprint", "_qimei_h38", "udb_anobiztoken"} & set(values) assert not {
"_qimei_uuid42",
"_qimei_fingerprint",
"_qimei_h38",
"udb_anobiztoken",
} & set(values)
def test_app_login_cookie_overwrites_auth_but_keeps_distinct_explicit_device_values(): def test_app_login_cookie_overwrites_auth_but_keeps_distinct_explicit_device_values():
@@ -137,12 +151,19 @@ def test_app_login_cookie_contains_web_session_shape():
session = MagicMock() session = MagicMock()
session.cookies = {"udb_uid": "123"} session.cookies = {"udb_uid": "123"}
cookie = HuyaAppPasswordLogin._merge_web_cookie( cookie = HuyaAppPasswordLogin._merge_web_cookie(
session, "web-token", "s" * 193, "h" * 40, session,
"web-token",
"s" * 193,
"h" * 40,
{"guid": "a" * 32, "udb_guiddata": "b" * 32}, {"guid": "a" * 32, "udb_guiddata": "b" * 32},
) )
keys = {item.split("=", 1)[0] for item in cookie.split("; ")} keys = {item.split("=", 1)[0] for item in cookie.split("; ")}
expected = { expected = {
"udb_biztoken", "sdid", "hdid", "guid", "udb_guiddata", "udb_biztoken",
"sdid",
"hdid",
"guid",
"udb_guiddata",
} }
assert expected <= keys assert expected <= keys
+4 -2
View File
@@ -10,7 +10,9 @@ def test_minimal_app_cookie_reports_only_missing_web_guid():
) )
assert HuyaBatchRunnerCore._web_wss_cookie_missing(cookie) == ( assert HuyaBatchRunnerCore._web_wss_cookie_missing(cookie) == (
"udb_deviceid", "udb_guiddata", "udb_anobiztoken", "udb_deviceid",
"udb_guiddata",
"udb_anobiztoken",
) )
assert not HuyaBatchRunnerCore._has_web_wss_cookie(cookie) assert not HuyaBatchRunnerCore._has_web_wss_cookie(cookie)
@@ -37,4 +39,4 @@ def test_script_only_fields_do_not_block_wss():
) )
assert HuyaBatchRunnerCore._web_wss_cookie_missing(cookie) == () assert HuyaBatchRunnerCore._web_wss_cookie_missing(cookie) == ()
assert HuyaBatchRunnerCore._has_web_wss_cookie(cookie) assert HuyaBatchRunnerCore._has_web_wss_cookie(cookie)
+24 -8
View File
@@ -26,7 +26,9 @@ class TestHuyaWorkbenchScope:
Base.metadata.create_all(self.engine) Base.metadata.create_all(self.engine)
self.session = sessionmaker(bind=self.engine)() self.session = sessionmaker(bind=self.engine)()
self.user = User(username="operator", password_hash="hash", role="super_admin") self.user = User(username="operator", password_hash="hash", role="super_admin")
self.account = HuyaAccount(uid="100", yyuid="100", cookie="yyuid=100; udb_uid=100") self.account = HuyaAccount(
uid="100", yyuid="100", cookie="yyuid=100; udb_uid=100"
)
self.session.add_all([self.user, self.account]) self.session.add_all([self.user, self.account])
self.session.commit() self.session.commit()
@@ -37,11 +39,15 @@ class TestHuyaWorkbenchScope:
def test_accounts_and_tasks_are_scoped(self): def test_accounts_and_tasks_are_scoped(self):
update_huya_workbench_accounts( update_huya_workbench_accounts(
HuyaWorkbenchAccountsUpdate(handbook_scope="elite", account_ids=[self.account.id]), HuyaWorkbenchAccountsUpdate(
handbook_scope="elite", account_ids=[self.account.id]
),
db=self.session, db=self.session,
current=self.user, current=self.user,
) )
result = list_huya_workbench_accounts("elite", db=self.session, current=self.user) result = list_huya_workbench_accounts(
"elite", db=self.session, current=self.user
)
assert result == {"account_ids": [self.account.id], "configured": True} assert result == {"account_ids": [self.account.id], "configured": True}
assert self.session.query(HuyaWorkbench).count() == 1 assert self.session.query(HuyaWorkbench).count() == 1
@@ -77,29 +83,39 @@ class TestHuyaWorkbenchScope:
self.session.commit() self.session.commit()
update_huya_workbench_accounts( update_huya_workbench_accounts(
HuyaWorkbenchAccountsUpdate(handbook_scope="browser_exchange", account_ids=[self.account.id]), HuyaWorkbenchAccountsUpdate(
handbook_scope="browser_exchange", account_ids=[self.account.id]
),
db=self.session, db=self.session,
current=self.user, current=self.user,
) )
assert list_huya_workbench_accounts("browser_exchange", db=self.session, current=self.user) == { assert list_huya_workbench_accounts(
"browser_exchange", db=self.session, current=self.user
) == {
"account_ids": [self.account.id], "account_ids": [self.account.id],
"configured": True, "configured": True,
} }
# browser_exchange 与 elite 两个 scope 的账号集合互不影响 # browser_exchange 与 elite 两个 scope 的账号集合互不影响
assert list_huya_workbench_accounts("elite", db=self.session, current=self.user) == { assert list_huya_workbench_accounts(
"elite", db=self.session, current=self.user
) == {
"account_ids": [], "account_ids": [],
"configured": False, "configured": False,
} }
# ids 接口:has_cookie=True 只返回有 Cookie 的账号 # ids 接口:has_cookie=True 只返回有 Cookie 的账号
result = list_huya_account_ids(has_cookie=True, db=self.session, current=self.user) result = list_huya_account_ids(
has_cookie=True, db=self.session, current=self.user
)
assert result == {"account_ids": [self.account.id], "total": 1} assert result == {"account_ids": [self.account.id], "total": 1}
all_ids = list_huya_account_ids(db=self.session, current=self.user) all_ids = list_huya_account_ids(db=self.session, current=self.user)
assert sorted(all_ids["account_ids"]) == sorted([self.account.id, no_cookie.id]) assert sorted(all_ids["account_ids"]) == sorted([self.account.id, no_cookie.id])
assert all_ids["total"] == 2 assert all_ids["total"] == 2
# ids 接口:search 匹配 uid # ids 接口:search 匹配 uid
searched = list_huya_account_ids(search="200", db=self.session, current=self.user) searched = list_huya_account_ids(
search="200", db=self.session, current=self.user
)
assert searched["account_ids"] == [no_cookie.id] assert searched["account_ids"] == [no_cookie.id]
def test_account_delete_cleans_workbench_membership(self): def test_account_delete_cleans_workbench_membership(self):
@@ -20,36 +20,69 @@ def upgrade() -> None:
if "handbook_scope" not in _columns(bind, "huya_tasks"): if "handbook_scope" not in _columns(bind, "huya_tasks"):
op.add_column( op.add_column(
"huya_tasks", "huya_tasks",
sa.Column("handbook_scope", sa.String(length=16), nullable=False, server_default="legacy"), sa.Column(
"handbook_scope",
sa.String(length=16),
nullable=False,
server_default="legacy",
),
)
op.create_index(
"ix_huya_tasks_handbook_scope", "huya_tasks", ["handbook_scope"]
) )
op.create_index("ix_huya_tasks_handbook_scope", "huya_tasks", ["handbook_scope"])
inspector = sa.inspect(bind) inspector = sa.inspect(bind)
if not inspector.has_table("huya_workbench_accounts"): if not inspector.has_table("huya_workbench_accounts"):
op.create_table( op.create_table(
"huya_workbench_accounts", "huya_workbench_accounts",
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True), sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
sa.Column("user_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=False), sa.Column(
"user_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=False
),
sa.Column("handbook_scope", sa.String(length=16), nullable=False), sa.Column("handbook_scope", sa.String(length=16), nullable=False),
sa.Column("account_id", sa.Integer(), sa.ForeignKey("huya_accounts.id"), nullable=False), sa.Column(
"account_id",
sa.Integer(),
sa.ForeignKey("huya_accounts.id"),
nullable=False,
),
sa.Column("created_at", sa.DateTime(), nullable=True), sa.Column("created_at", sa.DateTime(), nullable=True),
sa.UniqueConstraint("user_id", "handbook_scope", "account_id", name="uq_huya_workbench_account"), sa.UniqueConstraint(
"user_id",
"handbook_scope",
"account_id",
name="uq_huya_workbench_account",
),
)
op.create_index(
"ix_huya_workbench_accounts_user_id", "huya_workbench_accounts", ["user_id"]
)
op.create_index(
"ix_huya_workbench_accounts_handbook_scope",
"huya_workbench_accounts",
["handbook_scope"],
)
op.create_index(
"ix_huya_workbench_accounts_account_id",
"huya_workbench_accounts",
["account_id"],
) )
op.create_index("ix_huya_workbench_accounts_user_id", "huya_workbench_accounts", ["user_id"])
op.create_index("ix_huya_workbench_accounts_handbook_scope", "huya_workbench_accounts", ["handbook_scope"])
op.create_index("ix_huya_workbench_accounts_account_id", "huya_workbench_accounts", ["account_id"])
if not inspector.has_table("huya_workbenches"): if not inspector.has_table("huya_workbenches"):
op.create_table( op.create_table(
"huya_workbenches", "huya_workbenches",
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True), sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
sa.Column("user_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=False), sa.Column(
"user_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=False
),
sa.Column("handbook_scope", sa.String(length=16), nullable=False), sa.Column("handbook_scope", sa.String(length=16), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=True), sa.Column("updated_at", sa.DateTime(), nullable=True),
sa.UniqueConstraint("user_id", "handbook_scope", name="uq_huya_workbench"), sa.UniqueConstraint("user_id", "handbook_scope", name="uq_huya_workbench"),
) )
op.create_index("ix_huya_workbenches_user_id", "huya_workbenches", ["user_id"]) op.create_index("ix_huya_workbenches_user_id", "huya_workbenches", ["user_id"])
op.create_index("ix_huya_workbenches_handbook_scope", "huya_workbenches", ["handbook_scope"]) op.create_index(
"ix_huya_workbenches_handbook_scope", "huya_workbenches", ["handbook_scope"]
)
def downgrade() -> None: def downgrade() -> None:
@@ -19,9 +19,7 @@ depends_on: str | Sequence[str] | None = None
def upgrade() -> None: def upgrade() -> None:
bind = op.get_bind() bind = op.get_bind()
columns = { columns = {item["name"] for item in sa.inspect(bind).get_columns("huya_accounts")}
item["name"] for item in sa.inspect(bind).get_columns("huya_accounts")
}
if "raw_cookie" not in columns: if "raw_cookie" not in columns:
# MySQL 的 TEXT 列不允许 server_default;模型层 default="" 负责新行, # MySQL 的 TEXT 列不允许 server_default;模型层 default="" 负责新行,
# 存量行为 NULL(读取处按空处理)。 # 存量行为 NULL(读取处按空处理)。
@@ -33,8 +31,6 @@ def upgrade() -> None:
def downgrade() -> None: def downgrade() -> None:
bind = op.get_bind() bind = op.get_bind()
columns = { columns = {item["name"] for item in sa.inspect(bind).get_columns("huya_accounts")}
item["name"] for item in sa.inspect(bind).get_columns("huya_accounts")
}
if "raw_cookie" in columns: if "raw_cookie" in columns:
op.drop_column("huya_accounts", "raw_cookie") op.drop_column("huya_accounts", "raw_cookie")
+12 -4
View File
@@ -522,14 +522,20 @@ class HuyaWorkbenchAccount(Base):
__tablename__ = "huya_workbench_accounts" __tablename__ = "huya_workbench_accounts"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False, index=True) user_id: Mapped[int] = mapped_column(
ForeignKey("users.id"), nullable=False, index=True
)
handbook_scope: Mapped[str] = mapped_column(String(16), nullable=False, index=True) handbook_scope: Mapped[str] = mapped_column(String(16), nullable=False, index=True)
account_id: Mapped[int] = mapped_column(ForeignKey("huya_accounts.id"), nullable=False, index=True) account_id: Mapped[int] = mapped_column(
ForeignKey("huya_accounts.id"), nullable=False, index=True
)
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utcnow) created_at: Mapped[datetime] = mapped_column(DateTime, default=_utcnow)
__table_args__ = ( __table_args__ = (
UniqueConstraint( UniqueConstraint(
"user_id", "handbook_scope", "account_id", "user_id",
"handbook_scope",
"account_id",
name="uq_huya_workbench_account", name="uq_huya_workbench_account",
), ),
) )
@@ -541,7 +547,9 @@ class HuyaWorkbench(Base):
__tablename__ = "huya_workbenches" __tablename__ = "huya_workbenches"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False, index=True) user_id: Mapped[int] = mapped_column(
ForeignKey("users.id"), nullable=False, index=True
)
handbook_scope: Mapped[str] = mapped_column(String(16), nullable=False, index=True) handbook_scope: Mapped[str] = mapped_column(String(16), nullable=False, index=True)
updated_at: Mapped[datetime] = mapped_column( updated_at: Mapped[datetime] = mapped_column(
DateTime, default=_utcnow, onupdate=_utcnow DateTime, default=_utcnow, onupdate=_utcnow
+57 -24
View File
@@ -30,7 +30,11 @@ from core.huya import (
login_huya_sms, login_huya_sms,
send_huya_sms_code, send_huya_sms_code,
) )
from core.huya.cookie_utils import browser_login_script, cookie_pairs, normalize_huya_cookie from core.huya.cookie_utils import (
browser_login_script,
cookie_pairs,
normalize_huya_cookie,
)
from core.huya.device_fingerprint import account_state_dir as _fp_state_dir from core.huya.device_fingerprint import account_state_dir as _fp_state_dir
from core.huya.device_profile import ( from core.huya.device_profile import (
_load_db as _load_profile_db, _load_db as _load_profile_db,
@@ -119,15 +123,24 @@ def create_browser_exchange_kit(
登录态由前端引导用户在自己的 Chrome/Edge 中写入,服务端不托管浏览器会话。 登录态由前端引导用户在自己的 Chrome/Edge 中写入,服务端不托管浏览器会话。
""" """
_require_huya_perm(current, "huya:task") _require_huya_perm(current, "huya:task")
account = _visible_huya_accounts_query(db, current).filter(HuyaAccount.id == account_id).first() account = (
_visible_huya_accounts_query(db, current)
.filter(HuyaAccount.id == account_id)
.first()
)
if account is None: if account is None:
raise HTTPException(status_code=404, detail="虎牙账号不存在或无权操作") raise HTTPException(status_code=404, detail="虎牙账号不存在或无权操作")
if not account.cookie: if not account.cookie:
raise HTTPException(status_code=400, detail="该账号没有可用 Cookie,请先登录") raise HTTPException(status_code=400, detail="该账号没有可用 Cookie,请先登录")
config = ensure_huya_config(db) config = ensure_huya_config(db)
target_url = BindMixin._bind_redirect_url({ target_url = (
"room_pid": huya_config_value("room_pid", config.room_pid), BindMixin._bind_redirect_url(
}) or "https://zt.huya.com/b02faae1/pc/index.html" {
"room_pid": huya_config_value("room_pid", config.room_pid),
}
)
or "https://zt.huya.com/b02faae1/pc/index.html"
)
pairs = dict(cookie_pairs(normalize_huya_cookie(account.cookie))) pairs = dict(cookie_pairs(normalize_huya_cookie(account.cookie)))
return { return {
"account_id": account.id, "account_id": account.id,
@@ -321,10 +334,13 @@ def _workbench_account_ids(db: Session, current: User, scope: str) -> list[int]:
HuyaWorkbenchAccount.handbook_scope == scope, HuyaWorkbenchAccount.handbook_scope == scope,
) )
if not _can_view_huya_all(current): if not _can_view_huya_all(current):
query = query.join(HuyaAccount, HuyaAccount.id == HuyaWorkbenchAccount.account_id).filter( query = query.join(
HuyaAccount.assigned_to == current.id HuyaAccount, HuyaAccount.id == HuyaWorkbenchAccount.account_id
) ).filter(HuyaAccount.assigned_to == current.id)
return [account_id for (account_id,) in query.order_by(HuyaWorkbenchAccount.id.asc()).all()] return [
account_id
for (account_id,) in query.order_by(HuyaWorkbenchAccount.id.asc()).all()
]
def _require_huya_batch_owner(db: Session, current: User, batch_id: str) -> None: def _require_huya_batch_owner(db: Session, current: User, batch_id: str) -> None:
@@ -1847,10 +1863,15 @@ def list_huya_workbench_accounts(
): ):
"""读取当前用户指定工作台(精英宝典/浏览器兑换)的账号集合。""" """读取当前用户指定工作台(精英宝典/浏览器兑换)的账号集合。"""
ids = _workbench_account_ids(db, current, handbook_scope) ids = _workbench_account_ids(db, current, handbook_scope)
configured = db.query(HuyaWorkbench.id).filter( configured = (
HuyaWorkbench.user_id == current.id, db.query(HuyaWorkbench.id)
HuyaWorkbench.handbook_scope == handbook_scope, .filter(
).first() is not None HuyaWorkbench.user_id == current.id,
HuyaWorkbench.handbook_scope == handbook_scope,
)
.first()
is not None
)
return {"account_ids": ids, "configured": configured} return {"account_ids": ids, "configured": configured}
@@ -1866,10 +1887,14 @@ def update_huya_workbench_accounts(
raise HTTPException(status_code=400, detail="无效的账号 ID") raise HTTPException(status_code=400, detail="无效的账号 ID")
if ids: if ids:
_require_huya_task_account_access(db, current, ids) _require_huya_task_account_access(db, current, ids)
workbench = db.query(HuyaWorkbench).filter( workbench = (
HuyaWorkbench.user_id == current.id, db.query(HuyaWorkbench)
HuyaWorkbench.handbook_scope == req.handbook_scope, .filter(
).first() HuyaWorkbench.user_id == current.id,
HuyaWorkbench.handbook_scope == req.handbook_scope,
)
.first()
)
if workbench is None: if workbench is None:
db.add(HuyaWorkbench(user_id=current.id, handbook_scope=req.handbook_scope)) db.add(HuyaWorkbench(user_id=current.id, handbook_scope=req.handbook_scope))
else: else:
@@ -1878,12 +1903,16 @@ def update_huya_workbench_accounts(
HuyaWorkbenchAccount.user_id == current.id, HuyaWorkbenchAccount.user_id == current.id,
HuyaWorkbenchAccount.handbook_scope == req.handbook_scope, HuyaWorkbenchAccount.handbook_scope == req.handbook_scope,
).delete(synchronize_session=False) ).delete(synchronize_session=False)
db.add_all([ db.add_all(
HuyaWorkbenchAccount( [
user_id=current.id, handbook_scope=req.handbook_scope, account_id=account_id HuyaWorkbenchAccount(
) user_id=current.id,
for account_id in ids handbook_scope=req.handbook_scope,
]) account_id=account_id,
)
for account_id in ids
]
)
db.commit() db.commit()
return {"account_ids": ids, "success": True} return {"account_ids": ids, "success": True}
@@ -1907,7 +1936,11 @@ def list_recharge_goods(
current: User = Depends(require_permission("huya:task")), current: User = Depends(require_permission("huya:task")),
): ):
"""查看已缓存的虎牙充值商品快照。""" """查看已缓存的虎牙充值商品快照。"""
rows = db.query(HuyaRechargeGoodsSnapshot).order_by(HuyaRechargeGoodsSnapshot.id.desc()).all() rows = (
db.query(HuyaRechargeGoodsSnapshot)
.order_by(HuyaRechargeGoodsSnapshot.id.desc())
.all()
)
latest = {} latest = {}
for row in rows: for row in rows:
latest.setdefault((row.sid, row.spu_id), row) latest.setdefault((row.sid, row.spu_id), row)
+19 -5
View File
@@ -76,7 +76,10 @@ class HuyaBatchRunnerCore:
missing = self._web_wss_cookie_missing(cookie) missing = self._web_wss_cookie_missing(cookie)
if missing: if missing:
detail = ", ".join(missing) detail = ", ".join(missing)
self._push_log("error", f"[{uid}] Cookie 缺少网页设备态({detail}),已停止活动 HTTP 回退") self._push_log(
"error",
f"[{uid}] Cookie 缺少网页设备态({detail}),已停止活动 HTTP 回退",
)
raise RuntimeError(f"COOKIE_INCOMPLETE: 缺少网页设备态({detail})") raise RuntimeError(f"COOKIE_INCOMPLETE: 缺少网页设备态({detail})")
session = self._open_wss_session(uid, cookie, "activity") session = self._open_wss_session(uid, cookie, "activity")
self._push_log("info", f"[{uid}] 活动链路使用 WSS 会话") self._push_log("info", f"[{uid}] 活动链路使用 WSS 会话")
@@ -92,8 +95,14 @@ class HuyaBatchRunnerCore:
不阻断 WSS(风控风险自担)。 不阻断 WSS(风控风险自担)。
""" """
required = ( required = (
"udb_cred", "udb_biztoken", "udb_uid", "yyuid", "sdid", "udb_cred",
"udb_deviceid", "udb_guiddata", "udb_anobiztoken", "udb_biztoken",
"udb_uid",
"yyuid",
"sdid",
"udb_deviceid",
"udb_guiddata",
"udb_anobiztoken",
) )
return tuple(key for key in required if not cookie_value(cookie, key)) return tuple(key for key in required if not cookie_value(cookie, key))
@@ -107,7 +116,10 @@ class HuyaBatchRunnerCore:
missing = self._web_wss_cookie_missing(cookie) missing = self._web_wss_cookie_missing(cookie)
if missing: if missing:
detail = ", ".join(missing) detail = ", ".join(missing)
self._push_log("error", f"[{uid}] Cookie 缺少网页设备态({detail}),已停止商城 HTTP 回退") self._push_log(
"error",
f"[{uid}] Cookie 缺少网页设备态({detail}),已停止商城 HTTP 回退",
)
raise RuntimeError(f"COOKIE_INCOMPLETE: 缺少网页设备态({detail})") raise RuntimeError(f"COOKIE_INCOMPLETE: 缺少网页设备态({detail})")
session = self._open_wss_session(uid, cookie, "shop") session = self._open_wss_session(uid, cookie, "shop")
self._push_log("info", f"[{uid}] 商城链路使用 WSS 会话") self._push_log("info", f"[{uid}] 商城链路使用 WSS 会话")
@@ -243,7 +255,9 @@ class HuyaBatchRunnerCore:
"result": result, "result": result,
"created_by": task.created_by, "created_by": task.created_by,
"created_at": task.created_at.isoformat() if task.created_at else None, "created_at": task.created_at.isoformat() if task.created_at else None,
"finished_at": task.finished_at.isoformat() if task.finished_at else None, "finished_at": task.finished_at.isoformat()
if task.finished_at
else None,
}, },
} }
asyncio.run_coroutine_threadsafe(self.log_queue.put(event), self.loop) asyncio.run_coroutine_threadsafe(self.log_queue.put(event), self.loop)
+18 -6
View File
@@ -56,7 +56,9 @@ class GoodsMixin:
result = response.to_dict() result = response.to_dict()
result["act_id"] = act_id result["act_id"] = act_id
act_info = client.get_act_info(act_id=act_id) act_info = client.get_act_info(act_id=act_id)
user_tasks = client.get_act_user_task_detail(uid=uid, cookie=cookie, act_id=act_id) user_tasks = client.get_act_user_task_detail(
uid=uid, cookie=cookie, act_id=act_id
)
if act_info is not None: if act_info is not None:
result["act_info"] = act_info.to_dict() result["act_info"] = act_info.to_dict()
if user_tasks is not None: if user_tasks is not None:
@@ -347,20 +349,28 @@ class GoodsMixin:
return return
now_ts = int(time.time()) now_ts = int(time.time())
if prize.isCanExchange == 0: if prize.isCanExchange == 0:
self._mark_task(worker_db, task, "failed", "该商品当前不可兑换", detail_result) self._mark_task(
worker_db, task, "failed", "该商品当前不可兑换", detail_result
)
return return
if prize.isShowNum and prize.leftNum <= 0: if prize.isShowNum and prize.leftNum <= 0:
self._mark_task(worker_db, task, "failed", "该商品库存不足", detail_result) self._mark_task(worker_db, task, "failed", "该商品库存不足", detail_result)
return return
if prize.exchangeStartTime and now_ts < prize.exchangeStartTime: if prize.exchangeStartTime and now_ts < prize.exchangeStartTime:
self._mark_task(worker_db, task, "failed", "该商品尚未开始兑换", detail_result) self._mark_task(
worker_db, task, "failed", "该商品尚未开始兑换", detail_result
)
return return
if prize.exchangeEndTime and now_ts > prize.exchangeEndTime: if prize.exchangeEndTime and now_ts > prize.exchangeEndTime:
self._mark_task(worker_db, task, "failed", "该商品兑换已结束", detail_result) self._mark_task(
worker_db, task, "failed", "该商品兑换已结束", detail_result
)
return return
score = client.query_user_score(uid=uid, cookie=cookie, sid=sid_int) score = client.query_user_score(uid=uid, cookie=cookie, sid=sid_int)
if score is None: if score is None:
self._mark_task(worker_db, task, "error", "兑换前积分查询无响应", detail_result) self._mark_task(
worker_db, task, "error", "兑换前积分查询无响应", detail_result
)
return return
if score.status != 200 or score.available_score < prize.newScore: if score.status != 200 or score.available_score < prize.newScore:
detail_result["score"] = score.to_dict() detail_result["score"] = score.to_dict()
@@ -396,7 +406,9 @@ class GoodsMixin:
return return
post_score = client.query_user_score(uid=uid, cookie=cookie, sid=sid_int) post_score = client.query_user_score(uid=uid, cookie=cookie, sid=sid_int)
post_records = client.get_user_prize_records(uid=uid, cookie=cookie, sid=sid_int) post_records = client.get_user_prize_records(
uid=uid, cookie=cookie, sid=sid_int
)
if post_score is not None: if post_score is not None:
result["post_exchange_score"] = post_score.to_dict() result["post_exchange_score"] = post_score.to_dict()
account.points = post_score.available_score account.points = post_score.available_score
+48 -19
View File
@@ -109,7 +109,9 @@ class RechargeMixin:
"payment_checked_at": checked_at, "payment_checked_at": checked_at,
"payment_order": last_order, "payment_order": last_order,
"payment_order_status": status, "payment_order_status": status,
"payment_order_status_label": self._huya_order_status_label(status), "payment_order_status_label": self._huya_order_status_label(
status
),
} }
) )
if self._is_huya_order_paid(order): if self._is_huya_order_paid(order):
@@ -125,25 +127,39 @@ class RechargeMixin:
else: else:
# 兼容旧 HTTP 网关不提供 orderDetailV5 的情况。 # 兼容旧 HTTP 网关不提供 orderDetailV5 的情况。
resp = client.query_user_order_list( resp = client.query_user_order_list(
uid=uid, guid=guid, cookie=cookie, offset=0, page_size=10, uid=uid,
order_type=1, status=0, timeout=10.0, guid=guid,
cookie=cookie,
offset=0,
page_size=10,
order_type=1,
status=0,
timeout=10.0,
) )
for legacy_order in getattr(resp, "orders", []) if resp else []: for legacy_order in getattr(resp, "orders", []) if resp else []:
if str(getattr(legacy_order, "orderId", "")) != order_id_text: if str(getattr(legacy_order, "orderId", "")) != order_id_text:
continue continue
last_order = legacy_order.to_dict() last_order = legacy_order.to_dict()
status = int(getattr(legacy_order, "orderStatus", 0) or 0) status = int(getattr(legacy_order, "orderStatus", 0) or 0)
result.update({ result.update(
"payment_checked_at": checked_at, {
"payment_order": last_order, "payment_checked_at": checked_at,
"payment_order_status": status, "payment_order": last_order,
"payment_order_status_label": self._huya_order_status_label(status), "payment_order_status": status,
}) "payment_order_status_label": self._huya_order_status_label(
status
),
}
)
if self._is_huya_order_paid(legacy_order): if self._is_huya_order_paid(legacy_order):
result.update({ result.update(
"payment_status": "paid", "payment_status_label": "已支付", {
"payment_paid": True, "payment_paid_at": checked_at, "payment_status": "paid",
}) "payment_status_label": "已支付",
"payment_paid": True,
"payment_paid_at": checked_at,
}
)
return "paid", last_order return "paid", last_order
result.setdefault("payment_checked_at", checked_at) result.setdefault("payment_checked_at", checked_at)
if self._stop.wait(HUYA_PAYMENT_POLL_INTERVAL): if self._stop.wait(HUYA_PAYMENT_POLL_INTERVAL):
@@ -309,7 +325,8 @@ class RechargeMixin:
worker_db.query(HuyaRechargeGoodsSnapshot).filter( worker_db.query(HuyaRechargeGoodsSnapshot).filter(
HuyaRechargeGoodsSnapshot.account_id == account.id, HuyaRechargeGoodsSnapshot.account_id == account.id,
HuyaRechargeGoodsSnapshot.sid == (self._to_int(config_info.get("sid")) or 2203), HuyaRechargeGoodsSnapshot.sid
== (self._to_int(config_info.get("sid")) or 2203),
).delete(synchronize_session=False) ).delete(synchronize_session=False)
for item in goods: for item in goods:
worker_db.add( worker_db.add(
@@ -386,7 +403,8 @@ class RechargeMixin:
worker_db.query(HuyaRechargeGoodsSnapshot) worker_db.query(HuyaRechargeGoodsSnapshot)
.filter( .filter(
HuyaRechargeGoodsSnapshot.account_id == account.id, HuyaRechargeGoodsSnapshot.account_id == account.id,
HuyaRechargeGoodsSnapshot.sid == (self._to_int(config_info.get("sid")) or 2203), HuyaRechargeGoodsSnapshot.sid
== (self._to_int(config_info.get("sid")) or 2203),
HuyaRechargeGoodsSnapshot.spu_id == spu_id, HuyaRechargeGoodsSnapshot.spu_id == spu_id,
) )
.first() .first()
@@ -442,7 +460,9 @@ class RechargeMixin:
protocol = client.check_hy_protocol(uid=uid, guid="", cookie=cookie) protocol = client.check_hy_protocol(uid=uid, guid="", cookie=cookie)
if protocol is None or protocol.code != 200: if protocol is None or protocol.code != 200:
self._mark_task( self._mark_task(
worker_db, task, "failed", worker_db,
task,
"failed",
getattr(protocol, "message", "商城协议校验失败") or "商城协议校验失败", getattr(protocol, "message", "商城协议校验失败") or "商城协议校验失败",
{"goods": detail, "protocol": protocol.to_dict() if protocol else None}, {"goods": detail, "protocol": protocol.to_dict() if protocol else None},
) )
@@ -451,9 +471,16 @@ class RechargeMixin:
uid=uid, guid="", cookie=cookie, spu_id=spu_id, sku_id=0 uid=uid, guid="", cookie=cookie, spu_id=spu_id, sku_id=0
) )
available_channels = set(getattr(channels, "channels", []) or []) available_channels = set(getattr(channels, "channels", []) or [])
if channels is None or channels.code != 200 or pay_channel not in available_channels: if (
channels is None
or channels.code != 200
or pay_channel not in available_channels
):
self._mark_task( self._mark_task(
worker_db, task, "failed", "当前支付渠道不可用", worker_db,
task,
"failed",
"当前支付渠道不可用",
{"goods": detail, "channels": channels.to_dict() if channels else None}, {"goods": detail, "channels": channels.to_dict() if channels else None},
) )
return return
@@ -462,7 +489,9 @@ class RechargeMixin:
) )
if auth is None or auth.code != 200: if auth is None or auth.code != 200:
self._mark_task( self._mark_task(
worker_db, task, "failed", worker_db,
task,
"failed",
getattr(auth, "message", "购买权限校验失败") or "购买权限校验失败", getattr(auth, "message", "购买权限校验失败") or "购买权限校验失败",
{"goods": detail, "auth": auth.to_dict() if auth else None}, {"goods": detail, "auth": auth.to_dict() if auth else None},
) )
@@ -3,27 +3,30 @@
128/48 用完整图案;16px 细节会糊,改用去掉蝴蝶结的加粗简化版。 128/48 用完整图案;16px 细节会糊,改用去掉蝴蝶结的加粗简化版。
用法: uv run python web/extension/huya-exchange-helper/generate_icons.py 用法: uv run python web/extension/huya-exchange-helper/generate_icons.py
""" """
from PIL import Image, ImageDraw from PIL import Image, ImageDraw
S = 1024 # 超采样画布,最后缩到目标尺寸 S = 1024 # 超采样画布,最后缩到目标尺寸
RADIUS = 200 RADIUS = 200
TOP = (255, 156, 71) # 渐变顶部 TOP = (255, 156, 71) # 渐变顶部
BOTTOM = (240, 84, 0) # 渐变底部 BOTTOM = (240, 84, 0) # 渐变底部
BOX = (255, 255, 255) # 礼盒 BOX = (255, 255, 255) # 礼盒
RIBBON = (234, 74, 8) # 丝带(比背景深,压在白色上可见) RIBBON = (234, 74, 8) # 丝带(比背景深,压在白色上可见)
def gradient_rounded(size: int, radius: int) -> Image.Image: def gradient_rounded(size: int, radius: int) -> Image.Image:
grad = Image.new('RGBA', (size, size)) grad = Image.new("RGBA", (size, size))
g = ImageDraw.Draw(grad) g = ImageDraw.Draw(grad)
for y in range(size): for y in range(size):
t = y / (size - 1) t = y / (size - 1)
color = tuple(round(TOP[i] + (BOTTOM[i] - TOP[i]) * t) for i in range(3)) + (255,) color = tuple(round(TOP[i] + (BOTTOM[i] - TOP[i]) * t) for i in range(3)) + (
255,
)
g.line([(0, y), (size, y)], fill=color) g.line([(0, y), (size, y)], fill=color)
mask = Image.new('L', (size, size), 0) mask = Image.new("L", (size, size), 0)
ImageDraw.Draw(mask).rounded_rectangle([0, 0, size, size], radius=radius, fill=255) ImageDraw.Draw(mask).rounded_rectangle([0, 0, size, size], radius=radius, fill=255)
out = Image.new('RGBA', (size, size), (0, 0, 0, 0)) out = Image.new("RGBA", (size, size), (0, 0, 0, 0))
out.paste(grad, (0, 0), mask) out.paste(grad, (0, 0), mask)
return out return out
@@ -49,21 +52,28 @@ def draw_gift_simple(img: Image.Image) -> None:
d = ImageDraw.Draw(img) d = ImageDraw.Draw(img)
cx = img.width // 2 cx = img.width // 2
scale = img.width / 512 scale = img.width / 512
def rect(x1, y1, x2, y2, radius): def rect(x1, y1, x2, y2, radius):
d.rounded_rectangle([x1 * scale, y1 * scale, x2 * scale, y2 * scale], d.rounded_rectangle(
radius=radius * scale, fill=BOX) [x1 * scale, y1 * scale, x2 * scale, y2 * scale],
rect(cx / scale - 144, 96, cx / scale + 144, 206, 24) # 盖 radius=radius * scale,
fill=BOX,
)
rect(cx / scale - 144, 96, cx / scale + 144, 206, 24) # 盖
rect(cx / scale - 112, 230, cx / scale + 112, 420, 28) # 盒身 rect(cx / scale - 112, 230, cx / scale + 112, 420, 28) # 盒身
d.rectangle([cx - 34 * scale, 96 * scale, cx + 34 * scale, 420 * scale], fill=RIBBON) d.rectangle(
[cx - 34 * scale, 96 * scale, cx + 34 * scale, 420 * scale], fill=RIBBON
)
full = gradient_rounded(S, RADIUS) full = gradient_rounded(S, RADIUS)
draw_gift(full) draw_gift(full)
base = 'web/extension/huya-exchange-helper/' base = "web/extension/huya-exchange-helper/"
for size in (128, 48): for size in (128, 48):
full.resize((size, size), Image.LANCZOS).save(f'{base}icon{size}.png') full.resize((size, size), Image.LANCZOS).save(f"{base}icon{size}.png")
simple = gradient_rounded(512, 100) simple = gradient_rounded(512, 100)
draw_gift_simple(simple) draw_gift_simple(simple)
simple.resize((16, 16), Image.LANCZOS).save(f'{base}icon16.png') simple.resize((16, 16), Image.LANCZOS).save(f"{base}icon16.png")
print('icons regenerated') print("icons regenerated")