diff --git a/core/huya/activity_structs.py b/core/huya/activity_structs.py index 3a3e15b..c8c301d 100644 --- a/core/huya/activity_structs.py +++ b/core/huya/activity_structs.py @@ -139,10 +139,14 @@ class ActInfoItem(TafStruct): def read_from(self, ins: TafInputStream): for tag, attr, reader in ( - (0, "actId", ins.read_int64), (1, "name", ins.read_string), - (2, "startTime", 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), + (0, "actId", ins.read_int64), + (1, "name", ins.read_string), + (2, "startTime", 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))) @@ -157,10 +161,16 @@ class ActInfoItem(TafStruct): os.write_int64(8, self.gid) def to_dict(self) -> dict: - return {"act_id": self.actId, "name": self.name, "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} + return { + "act_id": self.actId, + "name": self.name, + "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): @@ -181,8 +191,11 @@ class GetActInfoResp(TafStruct): os.write_struct(2, self.info) def to_dict(self) -> dict: - return {"status": self.status, "msg": self.msg, - "info": self.info.to_dict() if self.info else None} + return { + "status": self.status, + "msg": self.msg, + "info": self.info.to_dict() if self.info else None, + } class GetActPrizeListReq(TafStruct): @@ -298,18 +311,30 @@ class ActPrizeDetailItem(TafStruct): def read_from(self, ins: TafInputStream): readers = { - 0: ("prizeId", ins.read_int64), 2: ("name", ins.read_string), - 3: ("score", ins.read_int64), 5: ("icon", ins.read_string), - 6: ("frequency", ins.read_int32), 7: ("frequencyLimit", ins.read_int32), - 8: ("num", ins.read_int64), 9: ("status", ins.read_int32), - 10: ("leftNum", ins.read_int64), 11: ("isShowNum", ins.read_int32), - 12: ("percent", ins.read_string), 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), + 0: ("prizeId", ins.read_int64), + 2: ("name", ins.read_string), + 3: ("score", ins.read_int64), + 5: ("icon", ins.read_string), + 6: ("frequency", ins.read_int32), + 7: ("frequencyLimit", ins.read_int32), + 8: ("num", ins.read_int64), + 9: ("status", ins.read_int32), + 10: ("leftNum", ins.read_int64), + 11: ("isShowNum", ins.read_int32), + 12: ("percent", ins.read_string), + 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: pos = ins.buf.tell() @@ -353,19 +378,30 @@ class ActPrizeDetailItem(TafStruct): def to_dict(self) -> dict: return { - "product_id": str(self.prizeId), "name": self.name, "score": self.score, - "icon": self.icon, "frequency": self.frequency, - "frequency_limit": self.frequencyLimit, "num": self.num, - "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, + "product_id": str(self.prizeId), + "name": self.name, + "score": self.score, + "icon": self.icon, + "frequency": self.frequency, + "frequency_limit": self.frequencyLimit, + "num": self.num, + "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, "exchange_start_time": self.exchangeStartTime, "exchange_end_time": self.exchangeEndTime, - "start_time_slot": self.startTimeSlot, "end_time_slot": self.endTimeSlot, - "is_today_limit": self.isTodayLimit, "is_user_limit": self.isUserLimit, + "start_time_slot": self.startTimeSlot, + "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) def to_dict(self) -> dict: - return {"status": self.status, "msg": self.msg, - "prize": self.prize.to_dict() if self.prize else None, - "detail_status": self.detailStatus} + return { + "status": self.status, + "msg": self.msg, + "prize": self.prize.to_dict() if self.prize else None, + "detail_status": self.detailStatus, + } class _ActPrizeDetailEnvelope(TafStruct): @@ -666,10 +705,14 @@ class UserActTaskItem(TafStruct): def read_from(self, ins: TafInputStream): for tag, attr, reader in ( - (0, "actId", ins.read_int64), (1, "taskId", ins.read_int64), - (2, "taskStatus", ins.read_int32), (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), + (0, "actId", ins.read_int64), + (1, "taskId", ins.read_int64), + (2, "taskStatus", ins.read_int32), + (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), ): setattr(self, attr, reader(tag, default=getattr(self, attr))) @@ -695,11 +738,17 @@ class UserActTaskItem(TafStruct): return item def to_dict(self) -> dict: - return {"act_id": self.actId, "task_id": self.taskId, - "task_status": self.taskStatus, "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} + return { + "act_id": self.actId, + "task_id": self.taskId, + "task_status": self.taskStatus, + "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): @@ -719,9 +768,12 @@ class GetActUserTaskDetailResp(TafStruct): os.write_list(2, self.tasks) def to_dict(self) -> dict: - return {"status": self.status, "msg": self.msg, - "task_count": len(self.tasks), - "tasks": [item.to_dict() for item in self.tasks]} + return { + "status": self.status, + "msg": self.msg, + "task_count": len(self.tasks), + "tasks": [item.to_dict() for item in self.tasks], + } class ActTaskPrizeInfo(TafStruct): diff --git a/core/huya/anon_device.py b/core/huya/anon_device.py index ba19c60..755be93 100644 --- a/core/huya/anon_device.py +++ b/core/huya/anon_device.py @@ -16,6 +16,7 @@ ``guid`` / ``_qimei_uuid42`` / ``__yamid_new`` / ``game_did`` 仍无服务端 签发接口,本模块不生成、不伪造它们。 """ + from __future__ import annotations import argparse @@ -92,8 +93,10 @@ def fetch_anonymous_device_state( context = ( "WB-" + secrets.token_hex(16) - + "-" + secrets.token_hex(16) - + "-" + secrets.token_hex(16) + + "-" + + secrets.token_hex(16) + + "-" + + secrets.token_hex(16) ) payload = { "uri": "10013", @@ -142,7 +145,10 @@ def fetch_anonymous_device_state( logger.info( "[huya-anon] 匿名设备态 OK: deviceid={}... guiddata={}... " "anouid={} biztoken={}...", - deviceid[:14], guiddata[:8], anouid, biztoken[:10], + deviceid[:14], + guiddata[:8], + anouid, + biztoken[:10], ) return { "udb_deviceid": deviceid, @@ -169,9 +175,11 @@ def main() -> int: else: for key, value in state.items(): 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 if __name__ == "__main__": - raise SystemExit(main()) \ No newline at end of file + raise SystemExit(main()) diff --git a/core/huya/app_login.py b/core/huya/app_login.py index be730fe..b58a640 100644 --- a/core/huya/app_login.py +++ b/core/huya/app_login.py @@ -568,14 +568,35 @@ class HuyaAppPasswordLogin: # 设备/统计字段不推导、不随机生成;仅转发已知真实值。 optional_keys = ( - "guid", "udb_guiddata", "__yamid_new", - "game_did", "_qimei_uuid42", "_qimei_fingerprint", "_qimei_h38", - "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", + "guid", + "udb_guiddata", + "__yamid_new", + "game_did", + "_qimei_uuid42", + "_qimei_fingerprint", + "_qimei_h38", + "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", ) for key in optional_keys: @@ -591,9 +612,7 @@ class HuyaAppPasswordLogin: set_value("udb_deviceid", web_device_id, overwrite=True) if not include_transient: pairs = [ - (key, value) - for key, value in pairs - if key != "web_qrlogin_confirm_id" + (key, value) for key, value in pairs if key != "web_qrlogin_confirm_id" ] return normalize_cookie_pairs(pairs) @@ -687,8 +706,12 @@ class HuyaAppPasswordLogin: merge_device_info = dict(self.device_info) for key, value in (sdid_obj.cookies or {}).items(): if key in WEB_DEVICE_COOKIE_KEYS or key in { - "udb_appid", "__yasmid", "__yamid_tt1", "udb_anouid", - "udb_anobiztoken", "udb_deviceid", + "udb_appid", + "__yasmid", + "__yamid_tt1", + "udb_anouid", + "udb_anobiztoken", + "udb_deviceid", }: merge_device_info.setdefault(key, value) # 匿名设备态协议补齐(middle + anonymousLogin 签发 4 字段), diff --git a/core/huya/cookie_utils.py b/core/huya/cookie_utils.py index a42f836..8691e7c 100644 --- a/core/huya/cookie_utils.py +++ b/core/huya/cookie_utils.py @@ -82,7 +82,9 @@ def browser_login_script( 脚本把 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) ttl_ms = max(1, ttl_days) * 86_400_000 return ( diff --git a/core/huya/http_client.py b/core/huya/http_client.py index 69cce38..b827b0a 100644 --- a/core/huya/http_client.py +++ b/core/huya/http_client.py @@ -349,7 +349,11 @@ class HuyaHttpClient: # ---------- 业务便捷方法 ---------- 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 @@ -358,7 +362,9 @@ class HuyaHttpClient: req.actId = int(act_id or 0) req.actUuid = act_uuid 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( 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.actId = int(act_id or 0) return self.call_rpc( - "webActUI", "getActUserTaskDetail", req, GetActUserTaskDetailResp, - uid=uid, cookie=cookie, timeout=timeout, + "webActUI", + "getActUserTaskDetail", + req, + GetActUserTaskDetailResp, + uid=uid, + cookie=cookie, + timeout=timeout, ) 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( - self, uid: int, guid: str, cookie: str, spu_id: str, sku_id: int, - supplier_id: int = 87401, timeout: float = 15.0, + self, + 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 @@ -864,8 +881,14 @@ class HuyaHttpClient: req.spuId = spu_id req.skuId = int(sku_id or 0) return self.call_rpc( - "shopMiddleUI", "listPayChannelV5", req, ListPayChannelRsp, - uid, guid, cookie, timeout=timeout, + "shopMiddleUI", + "listPayChannelV5", + req, + ListPayChannelRsp, + uid, + guid, + cookie, + timeout=timeout, ) def check_hy_protocol( @@ -877,12 +900,23 @@ class HuyaHttpClient: req.userId = self._build_shop_user(uid, cookie) req.shopAppInfo = self._build_shop_app("yellowcarlist", 4) return self.call_rpc( - "shopMiddleUI", "checkHyProtocolV5", req, ShopCodeRsp, - uid, guid, cookie, timeout=timeout, + "shopMiddleUI", + "checkHyProtocolV5", + req, + ShopCodeRsp, + uid, + guid, + cookie, + timeout=timeout, ) 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, ): from .shop_structs import CheckUserBuyAuthReq, ShopCodeRsp @@ -893,8 +927,14 @@ class HuyaHttpClient: req.spuId = spu_id req.skuId = int(sku_id or 0) return self.call_rpc( - "shopMiddleUI", "checkUserBuyAuth", req, ShopCodeRsp, - uid, guid, cookie, timeout=timeout, + "shopMiddleUI", + "checkUserBuyAuth", + req, + ShopCodeRsp, + uid, + guid, + cookie, + timeout=timeout, ) def query_user_order_list( diff --git a/tests/test_huya_anon_device.py b/tests/test_huya_anon_device.py index fc5ff0b..45e3b9d 100644 --- a/tests/test_huya_anon_device.py +++ b/tests/test_huya_anon_device.py @@ -17,8 +17,10 @@ def _fake_response(status=200, headers=None, text="", json_body=None): resp.status_code = status resp.headers = headers or {} resp.text = text - resp.json = Mock(return_value=json_body) if json_body is not None else Mock( - side_effect=ValueError("bad json") + resp.json = ( + Mock(return_value=json_body) + if json_body is not None + else Mock(side_effect=ValueError("bad json")) ) return resp @@ -36,7 +38,9 @@ def test_fetches_four_fields_from_middle_and_anon(monkeypatch): session = Mock(spec=requests.Session) deviceid = "w_1147246591246680065" 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()) 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) with pytest.raises(AnonymousDeviceError, match="非 JSON"): - fetch_anonymous_device_state(session=session) \ No newline at end of file + fetch_anonymous_device_state(session=session) diff --git a/tests/test_huya_app_login.py b/tests/test_huya_app_login.py index f546658..5aca4cb 100644 --- a/tests/test_huya_app_login.py +++ b/tests/test_huya_app_login.py @@ -98,10 +98,24 @@ def test_app_login_cookie_does_not_fabricate_browser_state(): ) values = dict(item.split("=", 1) for item in cookie.split("; ")) assert set(values) == { - "udb_cred", "udb_uid", "yyuid", "udb_version", "udb_biztoken", - "udb_origin", "udb_status", "sdid", "hdid", "udb_passport", "username", + "udb_cred", + "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(): @@ -137,12 +151,19 @@ def test_app_login_cookie_contains_web_session_shape(): session = MagicMock() session.cookies = {"udb_uid": "123"} 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}, ) keys = {item.split("=", 1)[0] for item in cookie.split("; ")} expected = { - "udb_biztoken", "sdid", "hdid", "guid", "udb_guiddata", + "udb_biztoken", + "sdid", + "hdid", + "guid", + "udb_guiddata", } assert expected <= keys diff --git a/tests/test_huya_runner_transport.py b/tests/test_huya_runner_transport.py index a8edec9..46fa711 100644 --- a/tests/test_huya_runner_transport.py +++ b/tests/test_huya_runner_transport.py @@ -10,7 +10,9 @@ def test_minimal_app_cookie_reports_only_missing_web_guid(): ) 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) @@ -37,4 +39,4 @@ def test_script_only_fields_do_not_block_wss(): ) assert HuyaBatchRunnerCore._web_wss_cookie_missing(cookie) == () - assert HuyaBatchRunnerCore._has_web_wss_cookie(cookie) \ No newline at end of file + assert HuyaBatchRunnerCore._has_web_wss_cookie(cookie) diff --git a/tests/test_huya_workbench_scopes.py b/tests/test_huya_workbench_scopes.py index e1a82f9..e96d77c 100644 --- a/tests/test_huya_workbench_scopes.py +++ b/tests/test_huya_workbench_scopes.py @@ -26,7 +26,9 @@ class TestHuyaWorkbenchScope: Base.metadata.create_all(self.engine) self.session = sessionmaker(bind=self.engine)() 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.commit() @@ -37,11 +39,15 @@ class TestHuyaWorkbenchScope: def test_accounts_and_tasks_are_scoped(self): 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, 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 self.session.query(HuyaWorkbench).count() == 1 @@ -77,29 +83,39 @@ class TestHuyaWorkbenchScope: self.session.commit() 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, 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], "configured": True, } # 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": [], "configured": False, } # 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} 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 all_ids["total"] == 2 # 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] def test_account_delete_cleans_workbench_membership(self): diff --git a/web/backend/migrations/versions/20260831_0032_huya_elite_workbench.py b/web/backend/migrations/versions/20260831_0032_huya_elite_workbench.py index 337fbeb..5793364 100644 --- a/web/backend/migrations/versions/20260831_0032_huya_elite_workbench.py +++ b/web/backend/migrations/versions/20260831_0032_huya_elite_workbench.py @@ -20,36 +20,69 @@ def upgrade() -> None: if "handbook_scope" not in _columns(bind, "huya_tasks"): op.add_column( "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) if not inspector.has_table("huya_workbench_accounts"): op.create_table( "huya_workbench_accounts", 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("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.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"): op.create_table( "huya_workbenches", 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("updated_at", sa.DateTime(), nullable=True), 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_handbook_scope", "huya_workbenches", ["handbook_scope"]) + op.create_index( + "ix_huya_workbenches_handbook_scope", "huya_workbenches", ["handbook_scope"] + ) def downgrade() -> None: diff --git a/web/backend/migrations/versions/20260901_0034_huya_accounts_raw_cookie.py b/web/backend/migrations/versions/20260901_0034_huya_accounts_raw_cookie.py index 778dacd..352e8aa 100644 --- a/web/backend/migrations/versions/20260901_0034_huya_accounts_raw_cookie.py +++ b/web/backend/migrations/versions/20260901_0034_huya_accounts_raw_cookie.py @@ -19,9 +19,7 @@ depends_on: str | Sequence[str] | None = None def upgrade() -> None: bind = op.get_bind() - columns = { - item["name"] for item in sa.inspect(bind).get_columns("huya_accounts") - } + columns = {item["name"] for item in sa.inspect(bind).get_columns("huya_accounts")} if "raw_cookie" not in columns: # MySQL 的 TEXT 列不允许 server_default;模型层 default="" 负责新行, # 存量行为 NULL(读取处按空处理)。 @@ -33,8 +31,6 @@ def upgrade() -> None: def downgrade() -> None: bind = op.get_bind() - columns = { - item["name"] for item in sa.inspect(bind).get_columns("huya_accounts") - } + columns = {item["name"] for item in sa.inspect(bind).get_columns("huya_accounts")} if "raw_cookie" in columns: - op.drop_column("huya_accounts", "raw_cookie") \ No newline at end of file + op.drop_column("huya_accounts", "raw_cookie") diff --git a/web/backend/models.py b/web/backend/models.py index 499c7f0..d127c40 100644 --- a/web/backend/models.py +++ b/web/backend/models.py @@ -522,14 +522,20 @@ class HuyaWorkbenchAccount(Base): __tablename__ = "huya_workbench_accounts" 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) - 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) __table_args__ = ( UniqueConstraint( - "user_id", "handbook_scope", "account_id", + "user_id", + "handbook_scope", + "account_id", name="uq_huya_workbench_account", ), ) @@ -541,7 +547,9 @@ class HuyaWorkbench(Base): __tablename__ = "huya_workbenches" 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) updated_at: Mapped[datetime] = mapped_column( DateTime, default=_utcnow, onupdate=_utcnow diff --git a/web/backend/routers/huya.py b/web/backend/routers/huya.py index be240a6..01c94c0 100644 --- a/web/backend/routers/huya.py +++ b/web/backend/routers/huya.py @@ -30,7 +30,11 @@ from core.huya import ( login_huya_sms, 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_profile import ( _load_db as _load_profile_db, @@ -119,15 +123,24 @@ def create_browser_exchange_kit( 登录态由前端引导用户在自己的 Chrome/Edge 中写入,服务端不托管浏览器会话。 """ _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: raise HTTPException(status_code=404, detail="虎牙账号不存在或无权操作") if not account.cookie: raise HTTPException(status_code=400, detail="该账号没有可用 Cookie,请先登录") config = ensure_huya_config(db) - target_url = BindMixin._bind_redirect_url({ - "room_pid": huya_config_value("room_pid", config.room_pid), - }) or "https://zt.huya.com/b02faae1/pc/index.html" + target_url = ( + BindMixin._bind_redirect_url( + { + "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))) return { "account_id": account.id, @@ -321,10 +334,13 @@ def _workbench_account_ids(db: Session, current: User, scope: str) -> list[int]: HuyaWorkbenchAccount.handbook_scope == scope, ) if not _can_view_huya_all(current): - query = query.join(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()] + query = query.join( + 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() + ] 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) - configured = db.query(HuyaWorkbench.id).filter( - HuyaWorkbench.user_id == current.id, - HuyaWorkbench.handbook_scope == handbook_scope, - ).first() is not None + configured = ( + db.query(HuyaWorkbench.id) + .filter( + HuyaWorkbench.user_id == current.id, + HuyaWorkbench.handbook_scope == handbook_scope, + ) + .first() + is not None + ) return {"account_ids": ids, "configured": configured} @@ -1866,10 +1887,14 @@ def update_huya_workbench_accounts( raise HTTPException(status_code=400, detail="无效的账号 ID") if ids: _require_huya_task_account_access(db, current, ids) - workbench = db.query(HuyaWorkbench).filter( - HuyaWorkbench.user_id == current.id, - HuyaWorkbench.handbook_scope == req.handbook_scope, - ).first() + workbench = ( + db.query(HuyaWorkbench) + .filter( + HuyaWorkbench.user_id == current.id, + HuyaWorkbench.handbook_scope == req.handbook_scope, + ) + .first() + ) if workbench is None: db.add(HuyaWorkbench(user_id=current.id, handbook_scope=req.handbook_scope)) else: @@ -1878,12 +1903,16 @@ def update_huya_workbench_accounts( HuyaWorkbenchAccount.user_id == current.id, HuyaWorkbenchAccount.handbook_scope == req.handbook_scope, ).delete(synchronize_session=False) - db.add_all([ - HuyaWorkbenchAccount( - user_id=current.id, handbook_scope=req.handbook_scope, account_id=account_id - ) - for account_id in ids - ]) + db.add_all( + [ + HuyaWorkbenchAccount( + user_id=current.id, + handbook_scope=req.handbook_scope, + account_id=account_id, + ) + for account_id in ids + ] + ) db.commit() return {"account_ids": ids, "success": True} @@ -1907,7 +1936,11 @@ def list_recharge_goods( 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 = {} for row in rows: latest.setdefault((row.sid, row.spu_id), row) diff --git a/web/backend/services/huya_runner_core.py b/web/backend/services/huya_runner_core.py index 3fb0377..553aeb9 100644 --- a/web/backend/services/huya_runner_core.py +++ b/web/backend/services/huya_runner_core.py @@ -76,7 +76,10 @@ class HuyaBatchRunnerCore: missing = self._web_wss_cookie_missing(cookie) if 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})") session = self._open_wss_session(uid, cookie, "activity") self._push_log("info", f"[{uid}] 活动链路使用 WSS 会话") @@ -92,8 +95,14 @@ class HuyaBatchRunnerCore: 不阻断 WSS(风控风险自担)。 """ required = ( - "udb_cred", "udb_biztoken", "udb_uid", "yyuid", "sdid", - "udb_deviceid", "udb_guiddata", "udb_anobiztoken", + "udb_cred", + "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)) @@ -107,7 +116,10 @@ class HuyaBatchRunnerCore: missing = self._web_wss_cookie_missing(cookie) if 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})") session = self._open_wss_session(uid, cookie, "shop") self._push_log("info", f"[{uid}] 商城链路使用 WSS 会话") @@ -243,7 +255,9 @@ class HuyaBatchRunnerCore: "result": result, "created_by": task.created_by, "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) diff --git a/web/backend/services/huya_runner_goods.py b/web/backend/services/huya_runner_goods.py index 1f514ef..7e80376 100644 --- a/web/backend/services/huya_runner_goods.py +++ b/web/backend/services/huya_runner_goods.py @@ -56,7 +56,9 @@ class GoodsMixin: result = response.to_dict() result["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: result["act_info"] = act_info.to_dict() if user_tasks is not None: @@ -347,20 +349,28 @@ class GoodsMixin: return now_ts = int(time.time()) if prize.isCanExchange == 0: - self._mark_task(worker_db, task, "failed", "该商品当前不可兑换", detail_result) + self._mark_task( + worker_db, task, "failed", "该商品当前不可兑换", detail_result + ) return if prize.isShowNum and prize.leftNum <= 0: self._mark_task(worker_db, task, "failed", "该商品库存不足", detail_result) return 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 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 score = client.query_user_score(uid=uid, cookie=cookie, sid=sid_int) if score is None: - self._mark_task(worker_db, task, "error", "兑换前积分查询无响应", detail_result) + self._mark_task( + worker_db, task, "error", "兑换前积分查询无响应", detail_result + ) return if score.status != 200 or score.available_score < prize.newScore: detail_result["score"] = score.to_dict() @@ -396,7 +406,9 @@ class GoodsMixin: return 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: result["post_exchange_score"] = post_score.to_dict() account.points = post_score.available_score diff --git a/web/backend/services/huya_runner_recharge.py b/web/backend/services/huya_runner_recharge.py index d46efdb..3bb156e 100644 --- a/web/backend/services/huya_runner_recharge.py +++ b/web/backend/services/huya_runner_recharge.py @@ -109,7 +109,9 @@ class RechargeMixin: "payment_checked_at": checked_at, "payment_order": last_order, "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): @@ -125,25 +127,39 @@ class RechargeMixin: else: # 兼容旧 HTTP 网关不提供 orderDetailV5 的情况。 resp = client.query_user_order_list( - uid=uid, guid=guid, cookie=cookie, offset=0, page_size=10, - order_type=1, status=0, timeout=10.0, + uid=uid, + 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 []: if str(getattr(legacy_order, "orderId", "")) != order_id_text: continue last_order = legacy_order.to_dict() status = int(getattr(legacy_order, "orderStatus", 0) or 0) - result.update({ - "payment_checked_at": checked_at, - "payment_order": last_order, - "payment_order_status": status, - "payment_order_status_label": self._huya_order_status_label(status), - }) + result.update( + { + "payment_checked_at": checked_at, + "payment_order": last_order, + "payment_order_status": status, + "payment_order_status_label": self._huya_order_status_label( + status + ), + } + ) if self._is_huya_order_paid(legacy_order): - result.update({ - "payment_status": "paid", "payment_status_label": "已支付", - "payment_paid": True, "payment_paid_at": checked_at, - }) + result.update( + { + "payment_status": "paid", + "payment_status_label": "已支付", + "payment_paid": True, + "payment_paid_at": checked_at, + } + ) return "paid", last_order result.setdefault("payment_checked_at", checked_at) if self._stop.wait(HUYA_PAYMENT_POLL_INTERVAL): @@ -309,7 +325,8 @@ class RechargeMixin: worker_db.query(HuyaRechargeGoodsSnapshot).filter( 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) for item in goods: worker_db.add( @@ -386,7 +403,8 @@ class RechargeMixin: worker_db.query(HuyaRechargeGoodsSnapshot) .filter( 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, ) .first() @@ -442,7 +460,9 @@ class RechargeMixin: protocol = client.check_hy_protocol(uid=uid, guid="", cookie=cookie) if protocol is None or protocol.code != 200: self._mark_task( - worker_db, task, "failed", + worker_db, + task, + "failed", getattr(protocol, "message", "商城协议校验失败") or "商城协议校验失败", {"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 ) 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( - worker_db, task, "failed", "当前支付渠道不可用", + worker_db, + task, + "failed", + "当前支付渠道不可用", {"goods": detail, "channels": channels.to_dict() if channels else None}, ) return @@ -462,7 +489,9 @@ class RechargeMixin: ) if auth is None or auth.code != 200: self._mark_task( - worker_db, task, "failed", + worker_db, + task, + "failed", getattr(auth, "message", "购买权限校验失败") or "购买权限校验失败", {"goods": detail, "auth": auth.to_dict() if auth else None}, ) diff --git a/web/extension/huya-exchange-helper/generate_icons.py b/web/extension/huya-exchange-helper/generate_icons.py index ef4fcf8..a16c0a9 100644 --- a/web/extension/huya-exchange-helper/generate_icons.py +++ b/web/extension/huya-exchange-helper/generate_icons.py @@ -3,27 +3,30 @@ 128/48 用完整图案;16px 细节会糊,改用去掉蝴蝶结的加粗简化版。 用法: uv run python web/extension/huya-exchange-helper/generate_icons.py """ + from PIL import Image, ImageDraw S = 1024 # 超采样画布,最后缩到目标尺寸 RADIUS = 200 -TOP = (255, 156, 71) # 渐变顶部 -BOTTOM = (240, 84, 0) # 渐变底部 -BOX = (255, 255, 255) # 礼盒 -RIBBON = (234, 74, 8) # 丝带(比背景深,压在白色上可见) +TOP = (255, 156, 71) # 渐变顶部 +BOTTOM = (240, 84, 0) # 渐变底部 +BOX = (255, 255, 255) # 礼盒 +RIBBON = (234, 74, 8) # 丝带(比背景深,压在白色上可见) 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) for y in range(size): 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) - 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) - 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) return out @@ -49,21 +52,28 @@ def draw_gift_simple(img: Image.Image) -> None: d = ImageDraw.Draw(img) cx = img.width // 2 scale = img.width / 512 + def rect(x1, y1, x2, y2, radius): - d.rounded_rectangle([x1 * scale, y1 * scale, x2 * scale, y2 * scale], - radius=radius * scale, fill=BOX) - rect(cx / scale - 144, 96, cx / scale + 144, 206, 24) # 盖 + d.rounded_rectangle( + [x1 * scale, y1 * scale, x2 * scale, y2 * scale], + 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) # 盒身 - 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) draw_gift(full) -base = 'web/extension/huya-exchange-helper/' +base = "web/extension/huya-exchange-helper/" 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) draw_gift_simple(simple) -simple.resize((16, 16), Image.LANCZOS).save(f'{base}icon16.png') -print('icons regenerated') +simple.resize((16, 16), Image.LANCZOS).save(f"{base}icon16.png") +print("icons regenerated")