Compare commits
4
Commits
95ad900ef0
...
8309072120
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8309072120 | ||
|
|
90a0065918 | ||
|
|
178eba1eea | ||
|
|
230d6c1918 |
@@ -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):
|
||||
|
||||
@@ -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())
|
||||
raise SystemExit(main())
|
||||
|
||||
+36
-13
@@ -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 字段),
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Iterable, Mapping
|
||||
|
||||
from requests.cookies import RequestsCookieJar
|
||||
@@ -67,3 +68,29 @@ def cookie_value(
|
||||
if item_key == key:
|
||||
value = "" if item_value is None else str(item_value).strip()
|
||||
return value
|
||||
|
||||
|
||||
def browser_login_script(
|
||||
pairs: Mapping[str, str],
|
||||
target_url: str,
|
||||
*,
|
||||
domain: str = ".huya.com",
|
||||
ttl_days: int = 180,
|
||||
) -> str:
|
||||
"""生成在用户自己浏览器控制台执行的登录脚本。
|
||||
|
||||
脚本把 Cookie 写入指定域后跳转目标页;Cookie 值以 JSON 数组内联,
|
||||
保证引号、反斜杠等字符安全转义。
|
||||
"""
|
||||
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 (
|
||||
f"(function(){{var c={payload};"
|
||||
f"var e=new Date(Date.now()+{ttl_ms}).toUTCString();"
|
||||
f"for(var i=0;i<c.length;i++){{"
|
||||
f"document.cookie=c[i][0]+'='+c[i][1]+';domain={domain};path=/;expires='+e;"
|
||||
f"}}location.href={target};}})();"
|
||||
)
|
||||
|
||||
+53
-13
@@ -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(
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
# 虎牙浏览器兑换(本机浏览器)
|
||||
|
||||
人工兑换在操作者自己的 Chrome/Edge 中完成:后端下发目标页地址和登录材料,登录态自动(扩展)或手动(控制台脚本)写入本机浏览器,兑换本身始终由人工点击,服务端不托管任何浏览器会话。
|
||||
|
||||
## 入口与账号范围
|
||||
|
||||
独立页面:虎牙 → 浏览器兑换。导航按角色区分:客服只看到浏览器兑换一个入口;管理员/运营仍显示完整的虎牙菜单(账号管理、精英宝典等)。
|
||||
|
||||
- 页面维护一份「兑换账号列表」,通过「导入账号」从自己可见的账号池勾选加入;客服只能看到分配给自己的账号。
|
||||
- 列表按用户隔离保存(工作台 scope `browser_exchange`),与精英宝典的账号集合互不影响。
|
||||
- 账号需已有 Cookie 才能执行兑换;账号的 App 协议登录由管理员在账号管理页(直链 `/huya/accounts`)完成,客服遇到无 Cookie 账号时联系管理员处理。
|
||||
|
||||
## 一键自动注入(推荐):安装内置扩展
|
||||
|
||||
项目自带 Chrome/Edge 扩展 `web/extension/huya-exchange-helper/`,安装一次后即可自动注入:
|
||||
|
||||
1. 打开扩展管理页:Chrome 为 `chrome://extensions`,Edge 为 `edge://extensions`。
|
||||
2. 开启「开发者模式」,点击「加载已解压的扩展程序」,选择仓库目录 `web/extension/huya-exchange-helper`。
|
||||
3. 刷新后台页面(扩展的内容脚本需要对当前页生效)。
|
||||
|
||||
之后的流程:
|
||||
|
||||
1. 在兑换列表点击账号的「浏览器兑换」→ 后端返回兑换材料 → 扩展自动把该账号 Cookie 写入 `.huya.com` 域并在新标签页打开已登录的兑换页。
|
||||
2. 确认页面右上角账号无误后,手动完成兑换。
|
||||
3. 回到后台点击「完成」。
|
||||
|
||||
扩展只在注入时覆盖与登录态同名的旧 Cookie,其余虎牙 Cookie 不动;扩展图标点击可作为兜底(读取当前后台页签留存的材料);未检测到材料时图标会显示「无任务」角标。
|
||||
|
||||
## 查询兑换记录
|
||||
|
||||
兑换列表每行的「兑换记录」按钮会为该账号创建 `query_exchange_records` 精英宝典任务(活动 SID 取精英宝典配置),前端轮询任务完成后:
|
||||
|
||||
- 表格新增的「兑换记录」列直接展示奖品名(多条时显示"xxx 等 N 条",悬停可看全部名称),未查询显示"未查询",查询中显示加载图标,失败显示"查询失败"及原因。
|
||||
- 点击单元格中的奖品名可打开详情弹窗,查看每条记录的奖品、消耗积分、发放状态、兑换时间与订单号。
|
||||
|
||||
任务失败(如 SID 未配置、Cookie 失效)时弹窗内直接显示原因,可点击「重新查询」。
|
||||
|
||||
## 手动方式(未装扩展时的兜底)
|
||||
|
||||
1. 在兑换列表点击「浏览器兑换」,弹出「浏览器兑换」窗口。
|
||||
2. 点击「打开兑换页面」在新标签页打开兑换活动页(地址来自配置的 `room_pid`,未配置时回落到活动页 `https://zt.huya.com/b02faae1/pc/index.html`)。
|
||||
3. 点击「复制登录脚本」,在兑换页面按 `F12` 打开控制台,粘贴脚本并回车执行。Chrome/Edge 首次粘贴需先手动输入 `allow pasting` 再回车。脚本把该账号 Cookie 写入 `.huya.com` 域并自动跳转。
|
||||
4. 确认登录态正确后完成兑换,回到系统点击「完成」。
|
||||
|
||||
没有控制台操作习惯时,可安装 Cookie-editor 类扩展,使用「复制 Cookie 字符串」在 `.huya.com` 域下导入。
|
||||
|
||||
## 接口
|
||||
|
||||
`POST /api/huya/accounts/{account_id}/browser-exchange`(权限 `huya:task`)返回:
|
||||
|
||||
```json
|
||||
{
|
||||
"account_id": 1,
|
||||
"username": "xxx",
|
||||
"target_url": "https://...",
|
||||
"cookie_string": "yyuid=...; ...",
|
||||
"cookie_script": "(function(){...})();"
|
||||
}
|
||||
```
|
||||
|
||||
- 脚本由 `core.huya.cookie_utils.browser_login_script` 生成:Cookie 以 JSON 数组内联(自动转义),逐条 `document.cookie` 写入 `domain=.huya.com; path=/`,有效期 180 天,最后跳转目标页。
|
||||
- 扩展注入走同一条接口:前端解析 `cookie_string` 后通过 DOM 事件交给扩展,由 `chrome.cookies` API 写入。
|
||||
- 兑换账号列表复用 `/api/huya/workbench-accounts`(`handbook_scope=browser_exchange`)。
|
||||
- 服务端不保存任何会话状态。
|
||||
|
||||
## 安全说明
|
||||
|
||||
- 接口受 `huya:task` 权限与账号可见范围约束;脚本、Cookie 字符串与扩展注入等同账号凭证,仅在授权用户点击时下发。
|
||||
- 登录态只写入操作者自己的浏览器,不会在服务器留存浏览器进程或 Profile。
|
||||
- 扩展为内部工具,通过开发者模式加载;其内容脚本在所有页面注入通信桥(manifest `<all_urls>`),但只响应本后台页面派发的固定事件,且只写 `huya.com` 域的 Cookie。
|
||||
- 请勿把脚本、Cookie 或扩展转给无关人员;如需共享操作,建议使用系统的账号授权机制而非转发凭证。
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "live-hub-py"
|
||||
version = "0.2.1"
|
||||
version = "0.3.0"
|
||||
description = "直播账号运营 Web 后台"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12,<3.13"
|
||||
|
||||
@@ -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)
|
||||
fetch_anonymous_device_state(session=session)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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)
|
||||
assert HuyaBatchRunnerCore._has_web_wss_cookie(cookie)
|
||||
|
||||
@@ -6,6 +6,7 @@ from web.backend.database import Base
|
||||
from web.backend.models import HuyaAccount, HuyaWorkbench, HuyaWorkbenchAccount, User
|
||||
from web.backend.routers.huya import (
|
||||
delete_account,
|
||||
list_huya_account_ids,
|
||||
list_huya_workbench_accounts,
|
||||
list_tasks,
|
||||
update_huya_workbench_accounts,
|
||||
@@ -25,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()
|
||||
|
||||
@@ -36,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
|
||||
|
||||
@@ -70,6 +77,47 @@ class TestHuyaWorkbenchScope:
|
||||
handbook_scope="invalid",
|
||||
)
|
||||
|
||||
def test_browser_exchange_scope_and_account_ids(self):
|
||||
no_cookie = HuyaAccount(uid="200", yyuid="200", cookie="")
|
||||
self.session.add(no_cookie)
|
||||
self.session.commit()
|
||||
|
||||
update_huya_workbench_accounts(
|
||||
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
|
||||
) == {
|
||||
"account_ids": [self.account.id],
|
||||
"configured": True,
|
||||
}
|
||||
# browser_exchange 与 elite 两个 scope 的账号集合互不影响
|
||||
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
|
||||
)
|
||||
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
|
||||
)
|
||||
assert searched["account_ids"] == [no_cookie.id]
|
||||
|
||||
def test_account_delete_cleans_workbench_membership(self):
|
||||
self.session.add(
|
||||
HuyaWorkbenchAccount(
|
||||
|
||||
@@ -320,7 +320,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "live-hub-py"
|
||||
version = "0.2.1"
|
||||
version = "0.3.0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "alembic" },
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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")
|
||||
op.drop_column("huya_accounts", "raw_cookie")
|
||||
|
||||
+12
-4
@@ -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
|
||||
|
||||
+128
-28
@@ -30,7 +30,11 @@ from core.huya import (
|
||||
login_huya_sms,
|
||||
send_huya_sms_code,
|
||||
)
|
||||
from core.huya.cookie_utils import 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,
|
||||
@@ -90,6 +94,7 @@ from ..services.huya_register_runner import (
|
||||
list_success_logs,
|
||||
)
|
||||
from ..services.huya_runner import HuyaBatchRunner, huya_batch_registry
|
||||
from ..services.huya_runner_bind import BindMixin
|
||||
from ..services.huya_service import (
|
||||
HUYA_CONFIG_FIELDS,
|
||||
SUPPORTED_TASK_TYPES,
|
||||
@@ -107,6 +112,45 @@ from ..services.huya_service import (
|
||||
router = APIRouter(prefix="/api/huya", tags=["虎牙"])
|
||||
|
||||
|
||||
@router.post("/accounts/{account_id}/browser-exchange")
|
||||
def create_browser_exchange_kit(
|
||||
account_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(get_current_user),
|
||||
):
|
||||
"""生成指定账号的本机浏览器人工兑换材料。
|
||||
|
||||
登录态由前端引导用户在自己的 Chrome/Edge 中写入,服务端不托管浏览器会话。
|
||||
"""
|
||||
_require_huya_perm(current, "huya:task")
|
||||
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"
|
||||
)
|
||||
pairs = dict(cookie_pairs(normalize_huya_cookie(account.cookie)))
|
||||
return {
|
||||
"account_id": account.id,
|
||||
"username": account.username or account.yyuid or "",
|
||||
"target_url": target_url,
|
||||
"cookie_string": "; ".join(f"{key}={value}" for key, value in pairs.items()),
|
||||
"cookie_script": browser_login_script(pairs, target_url),
|
||||
}
|
||||
|
||||
|
||||
def _has_huya_perm(user: User, permission: str) -> bool:
|
||||
"""虎牙新权限兼容旧的 huya:account 大权限。"""
|
||||
return user_has_permission(user, permission) or user_has_permission(
|
||||
@@ -284,16 +328,19 @@ def _require_huya_task_account_access(
|
||||
raise HTTPException(status_code=403, detail="包含无权操作的虎牙账号")
|
||||
|
||||
|
||||
def _elite_workbench_account_ids(db: Session, current: User) -> list[int]:
|
||||
def _workbench_account_ids(db: Session, current: User, scope: str) -> list[int]:
|
||||
query = db.query(HuyaWorkbenchAccount.account_id).filter(
|
||||
HuyaWorkbenchAccount.user_id == current.id,
|
||||
HuyaWorkbenchAccount.handbook_scope == "elite",
|
||||
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:
|
||||
@@ -323,6 +370,7 @@ def _account_out(account: HuyaAccount, include_cookie: bool = True) -> HuyaAccou
|
||||
yyuid=account.yyuid or "",
|
||||
username=account.username or "",
|
||||
has_password=bool(account.account_password),
|
||||
has_cookie=bool(account.cookie),
|
||||
nickname=account.nickname or "",
|
||||
cookie=cookie if include_cookie else "",
|
||||
cookie_preview=_fmt_cookie_preview(cookie) if include_cookie else "***",
|
||||
@@ -344,7 +392,7 @@ def _account_out(account: HuyaAccount, include_cookie: bool = True) -> HuyaAccou
|
||||
|
||||
|
||||
def _account_out_light(
|
||||
account: HuyaAccount, *, has_password: bool = False
|
||||
account: HuyaAccount, *, has_password: bool = False, has_cookie: bool = False
|
||||
) -> HuyaAccountOut:
|
||||
"""虎牙账号列表轻量输出,不读取加密字段。"""
|
||||
return HuyaAccountOut(
|
||||
@@ -353,6 +401,7 @@ def _account_out_light(
|
||||
yyuid=account.yyuid or "",
|
||||
username=account.username or "",
|
||||
has_password=has_password,
|
||||
has_cookie=has_cookie,
|
||||
nickname=account.nickname or "",
|
||||
cookie="",
|
||||
cookie_preview="***",
|
||||
@@ -480,6 +529,17 @@ def _huya_password_state_map(db: Session, account_ids: list[int]) -> dict[int, b
|
||||
return {account_id: bool(has_password) for account_id, has_password in rows}
|
||||
|
||||
|
||||
def _huya_cookie_state_map(db: Session, account_ids: list[int]) -> dict[int, bool]:
|
||||
if not account_ids:
|
||||
return {}
|
||||
rows = (
|
||||
db.query(HuyaAccount.id, (HuyaAccount.cookie != "").label("has_cookie"))
|
||||
.filter(HuyaAccount.id.in_(account_ids))
|
||||
.all()
|
||||
)
|
||||
return {account_id: bool(has_cookie) for account_id, has_cookie in rows}
|
||||
|
||||
|
||||
@router.get("/task-types")
|
||||
def task_types(current: User = Depends(require_permission("huya:task"))):
|
||||
"""返回当前规划的虎牙任务类型。"""
|
||||
@@ -531,9 +591,12 @@ def list_accounts(
|
||||
password_map = _huya_password_state_map(
|
||||
db, [account.id for account in accounts]
|
||||
)
|
||||
cookie_map = _huya_cookie_state_map(db, [account.id for account in accounts])
|
||||
result = [
|
||||
_account_out_light(
|
||||
account, has_password=password_map.get(account.id, False)
|
||||
account,
|
||||
has_password=password_map.get(account.id, False),
|
||||
has_cookie=cookie_map.get(account.id, False),
|
||||
)
|
||||
for account in accounts
|
||||
]
|
||||
@@ -582,6 +645,26 @@ def accounts_summary(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/accounts/ids")
|
||||
def list_huya_account_ids(
|
||||
search: str = "",
|
||||
tag: str = "",
|
||||
has_cookie: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("huya:task")),
|
||||
):
|
||||
"""返回当前用户可见的全部账号 ID(不受分页限制),供工作台一键导入。"""
|
||||
query = _filter_huya_accounts_query(
|
||||
_visible_huya_accounts_query(db, current),
|
||||
current,
|
||||
tag=tag or None,
|
||||
has_cookie=has_cookie,
|
||||
search=search,
|
||||
)
|
||||
rows = query.with_entities(HuyaAccount.id).all()
|
||||
return {"account_ids": [row[0] for row in rows], "total": len(rows)}
|
||||
|
||||
|
||||
@router.post("/accounts/import-cookies")
|
||||
def import_cookies(
|
||||
req: HuyaCookieImport,
|
||||
@@ -1774,16 +1857,21 @@ def update_config(
|
||||
|
||||
@router.get("/workbench-accounts")
|
||||
def list_huya_workbench_accounts(
|
||||
handbook_scope: str = Query(..., pattern="^elite$"),
|
||||
handbook_scope: str = Query(..., pattern="^elite$|^browser_exchange$"),
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("huya:task")),
|
||||
):
|
||||
"""读取当前用户的虎牙精英宝典账号集合。"""
|
||||
ids = _elite_workbench_account_ids(db, current)
|
||||
configured = db.query(HuyaWorkbench.id).filter(
|
||||
HuyaWorkbench.user_id == current.id,
|
||||
HuyaWorkbench.handbook_scope == handbook_scope,
|
||||
).first() is not None
|
||||
"""读取当前用户指定工作台(精英宝典/浏览器兑换)的账号集合。"""
|
||||
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
|
||||
)
|
||||
return {"account_ids": ids, "configured": configured}
|
||||
|
||||
|
||||
@@ -1793,16 +1881,20 @@ def update_huya_workbench_accounts(
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("huya:task")),
|
||||
):
|
||||
"""覆盖虎牙精英宝典账号集合,支持跨浏览器同步。"""
|
||||
"""覆盖当前用户指定工作台(精英宝典/浏览器兑换)的账号集合,支持跨浏览器同步。"""
|
||||
ids = sorted(set(req.account_ids))
|
||||
if any(account_id < 1 for account_id in ids):
|
||||
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:
|
||||
@@ -1811,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}
|
||||
|
||||
@@ -1840,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)
|
||||
|
||||
@@ -428,6 +428,7 @@ class HuyaAccountOut(BaseModel):
|
||||
yyuid: str = ""
|
||||
username: str = ""
|
||||
has_password: bool = False
|
||||
has_cookie: bool = False
|
||||
nickname: str = ""
|
||||
cookie: str = ""
|
||||
cookie_preview: str = ""
|
||||
@@ -455,6 +456,7 @@ class HuyaAccountOut(BaseModel):
|
||||
"yyuid": self.yyuid,
|
||||
"username": self.username,
|
||||
"has_password": self.has_password,
|
||||
"has_cookie": self.has_cookie,
|
||||
"nickname": self.nickname,
|
||||
"cookie": self.cookie,
|
||||
"cookie_preview": self.cookie_preview,
|
||||
@@ -509,7 +511,7 @@ class HuyaTaskBatchRequest(BaseModel):
|
||||
|
||||
|
||||
class HuyaWorkbenchAccountsUpdate(BaseModel):
|
||||
handbook_scope: str = Field(..., pattern="^elite$")
|
||||
handbook_scope: str = Field(..., pattern="^elite$|^browser_exchange$")
|
||||
account_ids: list[int] = Field(default_factory=list)
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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},
|
||||
)
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// 虎牙兑换助手后台:接收后台页面 relay 转发的登录材料,
|
||||
// 覆盖写入 huya.com 同名 Cookie 后打开已登录的兑换页。
|
||||
const HUYA_COOKIE_URL = 'https://www.huya.com/';
|
||||
const TTL_SECONDS = 180 * 86400;
|
||||
|
||||
function badge(tabId, text) {
|
||||
if (!tabId) return;
|
||||
chrome.action.setBadgeText({ tabId, text });
|
||||
setTimeout(() => {
|
||||
chrome.action.setBadgeText({ tabId, text: '' });
|
||||
}, 2500);
|
||||
}
|
||||
|
||||
async function injectKit(kit) {
|
||||
const cookies = Array.isArray(kit && kit.cookies) ? kit.cookies : [];
|
||||
const wanted = new Set(cookies.map(([name]) => String(name)).filter(Boolean));
|
||||
// 只清理与登录态同名的旧 Cookie(覆盖所有域/路径变体),其余 huya Cookie 保持不动,
|
||||
// 行为与控制台脚本方案一致,避免误伤浏览器里已有的其他虎牙状态。
|
||||
const existing = await chrome.cookies.getAll({ domain: 'huya.com' });
|
||||
for (const cookie of existing) {
|
||||
if (!wanted.has(cookie.name)) continue;
|
||||
const url = 'https://' + cookie.domain.replace(/^\./, '') + (cookie.path || '/');
|
||||
try {
|
||||
await chrome.cookies.remove({ url, name: cookie.name });
|
||||
} catch (e) { /* 单个失败不阻断 */ }
|
||||
}
|
||||
const expirationDate = Math.floor(Date.now() / 1000) + TTL_SECONDS;
|
||||
for (const [name, value] of cookies) {
|
||||
if (!name) continue;
|
||||
try {
|
||||
await chrome.cookies.set({
|
||||
url: HUYA_COOKIE_URL,
|
||||
domain: '.huya.com',
|
||||
path: '/',
|
||||
name: String(name),
|
||||
value: value == null ? '' : String(value),
|
||||
secure: true,
|
||||
expirationDate,
|
||||
});
|
||||
} catch (e) { /* 单个失败不阻断 */ }
|
||||
}
|
||||
if (kit && kit.target_url) {
|
||||
chrome.tabs.create({ url: kit.target_url });
|
||||
}
|
||||
}
|
||||
|
||||
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
||||
if (msg && msg.type === 'inject' && msg.kit) {
|
||||
injectKit(msg.kit).then(() => badge(sender.tab && sender.tab.id, 'OK'));
|
||||
sendResponse({ ok: true });
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
// 兜底:后台页面把材料存到 window.__huyaExchangeKit,点击扩展图标时读取。
|
||||
chrome.action.onClicked.addListener(async (tab) => {
|
||||
if (!tab || !tab.id) return;
|
||||
let payload = null;
|
||||
try {
|
||||
const [result] = await chrome.scripting.executeScript({
|
||||
target: { tabId: tab.id },
|
||||
func: () => window.__huyaExchangeKit || null,
|
||||
});
|
||||
payload = result ? result.result : null;
|
||||
} catch (e) {
|
||||
return; // 无权访问当前页面
|
||||
}
|
||||
if (!payload) {
|
||||
badge(tab.id, '无任务');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await injectKit(JSON.parse(payload));
|
||||
badge(tab.id, 'OK');
|
||||
} catch (e) {
|
||||
badge(tab.id, '失败');
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
"""生成虎牙兑换助手扩展图标:橙色渐变圆角底 + 白色礼盒。
|
||||
|
||||
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) # 丝带(比背景深,压在白色上可见)
|
||||
|
||||
|
||||
def gradient_rounded(size: int, radius: int) -> Image.Image:
|
||||
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,
|
||||
)
|
||||
g.line([(0, y), (size, y)], fill=color)
|
||||
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.paste(grad, (0, 0), mask)
|
||||
return out
|
||||
|
||||
|
||||
def draw_gift(img: Image.Image) -> None:
|
||||
d = ImageDraw.Draw(img)
|
||||
cx = S // 2
|
||||
# 蝴蝶结:左右两个椭圆
|
||||
d.ellipse([348, 235, 512, 365], fill=BOX)
|
||||
d.ellipse([512, 235, 676, 365], fill=BOX)
|
||||
# 盒盖(比盒身宽)
|
||||
d.rounded_rectangle([cx - 235, 375, cx + 235, 485], radius=30, fill=BOX)
|
||||
# 盒身
|
||||
d.rounded_rectangle([cx - 200, 509, cx + 200, 789], radius=36, fill=BOX)
|
||||
# 竖向丝带贯穿盖与盒身
|
||||
d.rectangle([cx - 44, 375, cx + 44, 789], fill=RIBBON)
|
||||
# 结口圆点,压在蝴蝶结与盒盖交界
|
||||
d.ellipse([cx - 46, 330, cx + 46, 422], fill=RIBBON)
|
||||
|
||||
|
||||
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) # 盖
|
||||
rect(cx / scale - 112, 230, cx / scale + 112, 420, 28) # 盒身
|
||||
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/"
|
||||
for size in (128, 48):
|
||||
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")
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.7 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 653 B |
Binary file not shown.
|
After Width: | Height: | Size: 1.9 KiB |
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "虎牙兑换助手",
|
||||
"version": "1.0.0",
|
||||
"description": "配合直播后台使用:一键把所选虎牙账号的登录态写入本机浏览器(仅 huya.com 域),兑换操作仍由用户手动完成。",
|
||||
"permissions": ["cookies", "scripting", "activeTab"],
|
||||
"host_permissions": ["*://*.huya.com/*"],
|
||||
"background": {
|
||||
"service_worker": "background.js"
|
||||
},
|
||||
"content_scripts": [
|
||||
{
|
||||
"matches": ["<all_urls>"],
|
||||
"js": ["relay.js"],
|
||||
"run_at": "document_start"
|
||||
}
|
||||
],
|
||||
"action": {
|
||||
"default_title": "虎牙兑换助手"
|
||||
},
|
||||
"icons": {
|
||||
"16": "icon16.png",
|
||||
"48": "icon48.png",
|
||||
"128": "icon128.png"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// 内容脚本:在所有页面标记扩展存在,并把后台页面派发的兑换材料转发给 service worker。
|
||||
// 后台页面通过 documentElement.dataset.huyaExchangeHelper === '1' 检测扩展是否可用。
|
||||
document.documentElement.dataset.huyaExchangeHelper = '1';
|
||||
|
||||
window.addEventListener('huya-exchange-kit', (event) => {
|
||||
const detail = event.detail;
|
||||
if (typeof detail !== 'string') return;
|
||||
try {
|
||||
const kit = JSON.parse(detail);
|
||||
if (kit && kit.target_url && Array.isArray(kit.cookies)) {
|
||||
const sending = chrome.runtime.sendMessage({ type: 'inject', kit });
|
||||
if (sending && typeof sending.catch === 'function') {
|
||||
sending.catch(() => { /* 扩展上下文失效等场景忽略 */ });
|
||||
}
|
||||
}
|
||||
} catch (e) { /* 忽略非法消息 */ }
|
||||
}, true);
|
||||
@@ -26,6 +26,7 @@ const HuyaRegisterPage = lazy(() => import('./pages/HuyaRegisterPage'));
|
||||
const HuyaDeviceBindingsPage = lazy(() => import('./pages/HuyaDeviceBindingsPage'));
|
||||
const HuyaTasksPage = lazy(() => import('./pages/HuyaTasksPage'));
|
||||
const HuyaElitePage = lazy(() => import('./pages/HuyaElitePage'));
|
||||
const HuyaBrowserExchangePage = lazy(() => import('./pages/HuyaBrowserExchangePage'));
|
||||
const YybRechargePage = lazy(() => import('./pages/YybRechargePage'));
|
||||
const AuditLogsPage = lazy(() => import('./pages/AuditLogsPage'));
|
||||
|
||||
@@ -96,6 +97,7 @@ function AppContent() {
|
||||
<Route path="huya/cookies" element={lazyRoute(<HuyaCookiePage />)} />
|
||||
<Route path="huya/tasks" element={lazyRoute(<HuyaTasksPage />)} />
|
||||
<Route path="huya/elite" element={lazyRoute(<HuyaElitePage />)} />
|
||||
<Route path="huya/browser-exchange" element={lazyRoute(<HuyaBrowserExchangePage />)} />
|
||||
<Route path="yyb/recharge" element={lazyRoute(<YybRechargePage />)} />
|
||||
<Route path="proxy" element={lazyRoute(<ProxyPage />)} />
|
||||
<Route path="users" element={lazyRoute(<UsersPage />)} />
|
||||
|
||||
@@ -29,6 +29,8 @@ import type {
|
||||
HuyaTaskBatchRequest,
|
||||
HuyaTaskBatchResult,
|
||||
HuyaTaskItem,
|
||||
HuyaBrowserExchangeKit,
|
||||
HuyaWorkbenchScope,
|
||||
MessageCountResponse,
|
||||
MessageDeletedResponse,
|
||||
MessageResponse,
|
||||
@@ -41,8 +43,10 @@ export const huyaApi = {
|
||||
taskTypes: () => api.get<Record<string, string>, Record<string, string>>('/huya/task-types'),
|
||||
listAccounts: (params?: { assigned_only?: boolean; tag?: string; has_cookie?: boolean; include_cookie?: boolean }) =>
|
||||
api.get<HuyaAccountItem[], HuyaAccountItem[]>('/huya/accounts', { params }),
|
||||
listAccountsPaged: (params: PageParams & { assigned_only?: boolean; tag?: string; has_cookie?: boolean; include_cookie?: boolean }) =>
|
||||
listAccountsPaged: (params: PageParams & { assigned_only?: boolean; tag?: string; has_cookie?: boolean; search?: string; include_cookie?: boolean }) =>
|
||||
api.get<PaginatedResponse<HuyaAccountItem>, PaginatedResponse<HuyaAccountItem>>('/huya/accounts', { params }),
|
||||
listAccountIds: (params?: { search?: string; tag?: string; has_cookie?: boolean }) =>
|
||||
api.get<{ account_ids: number[]; total: number }, { account_ids: number[]; total: number }>('/huya/accounts/ids', { params }),
|
||||
accountsSummary: () => api.get<HuyaAccountSummary, HuyaAccountSummary>('/huya/accounts/summary'),
|
||||
/** 设备绑定: 账号 ↔ 环境列表 (画像+指纹状态+账号表合并) */
|
||||
listDeviceBindings: () =>
|
||||
@@ -118,11 +122,11 @@ export const huyaApi = {
|
||||
updateConfig: (data: Partial<HuyaConfig>) => api.put<HuyaConfig, HuyaConfig>('/huya/config', data),
|
||||
listGoods: () => api.get<HuyaGoodsItem[], HuyaGoodsItem[]>('/huya/goods'),
|
||||
listRechargeGoods: () => api.get<HuyaRechargeGoodsItem[], HuyaRechargeGoodsItem[]>('/huya/recharge-goods'),
|
||||
listWorkbenchAccounts: (scope: 'elite' = 'elite') =>
|
||||
listWorkbenchAccounts: (scope: HuyaWorkbenchScope = 'elite') =>
|
||||
api.get<{ account_ids: number[]; configured: boolean }, { account_ids: number[]; configured: boolean }>(
|
||||
'/huya/workbench-accounts', { params: { handbook_scope: scope } },
|
||||
),
|
||||
updateWorkbenchAccounts: (accountIds: number[], scope: 'elite' = 'elite') =>
|
||||
updateWorkbenchAccounts: (accountIds: number[], scope: HuyaWorkbenchScope = 'elite') =>
|
||||
api.put<{ account_ids: number[]; success: boolean }, { account_ids: number[]; success: boolean }>(
|
||||
'/huya/workbench-accounts', { handbook_scope: scope, account_ids: accountIds },
|
||||
),
|
||||
@@ -142,4 +146,7 @@ export const huyaApi = {
|
||||
api.get<HuyaTaskItem, HuyaTaskItem>(`/huya/tasks/${taskId}`),
|
||||
cleanupOrphans: () =>
|
||||
api.post<{ message: string; cleaned: number; success: boolean }, { message: string; cleaned: number; success: boolean }>('/huya/tasks/cleanup-orphans'),
|
||||
/** 本机浏览器兑换: 获取目标页与登录脚本, 由用户在自己浏览器的控制台执行 */
|
||||
createBrowserExchange: (accountId: number) =>
|
||||
api.post<HuyaBrowserExchangeKit, HuyaBrowserExchangeKit>(`/huya/accounts/${accountId}/browser-exchange`, {}),
|
||||
};
|
||||
|
||||
@@ -445,6 +445,7 @@ export interface HuyaAccountItem {
|
||||
yyuid: string;
|
||||
username: string;
|
||||
has_password: boolean;
|
||||
has_cookie?: boolean;
|
||||
nickname: string;
|
||||
cookie: string;
|
||||
cookie_preview: string;
|
||||
@@ -463,6 +464,18 @@ export interface HuyaAccountItem {
|
||||
updated_at: string | null;
|
||||
}
|
||||
|
||||
/** 工作台账号集合范围: elite=精英宝典 / browser_exchange=浏览器兑换 */
|
||||
export type HuyaWorkbenchScope = 'elite' | 'browser_exchange';
|
||||
|
||||
/** 本机浏览器人工兑换材料 (登录脚本在用户自己的 Chrome/Edge 控制台执行) */
|
||||
export interface HuyaBrowserExchangeKit {
|
||||
account_id: number;
|
||||
username: string;
|
||||
target_url: string;
|
||||
cookie_string: string;
|
||||
cookie_script: string;
|
||||
}
|
||||
|
||||
/** 账号 ↔ 设备环境绑定 (一号一环境, 后端 data/huya_device_profiles.json + huya_fp_states) */
|
||||
export interface HuyaDeviceBindingItem {
|
||||
account: string;
|
||||
@@ -693,6 +706,22 @@ export interface HuyaTaskBatchResult {
|
||||
success: boolean;
|
||||
}
|
||||
|
||||
/** 兑换记录条目 (query_exchange_records 任务结果 records) */
|
||||
export interface HuyaExchangeRecord {
|
||||
record_id: number;
|
||||
prize_name: string;
|
||||
score: number | null;
|
||||
score_text?: string;
|
||||
exchange_time: number | null;
|
||||
exchange_time_text?: string;
|
||||
prize_status: number;
|
||||
status_label: string;
|
||||
order_id?: string;
|
||||
icon?: string;
|
||||
index?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface HuyaTaskItem {
|
||||
id: number;
|
||||
batch_id: string;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Layout, Menu, Avatar, Space, Typography, Button, Modal, Dropdown } from 'antd';
|
||||
import { Layout, Menu, Avatar, Space, Typography, Button, App, Dropdown } from 'antd';
|
||||
import type { MenuProps } from 'antd';
|
||||
import {
|
||||
DashboardOutlined, UserOutlined, LogoutOutlined,
|
||||
CloudServerOutlined, TeamOutlined, ApiOutlined, KeyOutlined,
|
||||
MenuFoldOutlined, MenuUnfoldOutlined, SwapOutlined,
|
||||
SunOutlined, MoonOutlined, DesktopOutlined, GiftOutlined, ShoppingCartOutlined, ApartmentOutlined, MobileOutlined,
|
||||
BookOutlined, TrophyOutlined, ShopOutlined,
|
||||
SunOutlined, MoonOutlined, DesktopOutlined, GiftOutlined, ApartmentOutlined, MobileOutlined, ShoppingCartOutlined,
|
||||
BookOutlined, TrophyOutlined, ShopOutlined, GlobalOutlined,
|
||||
SafetyCertificateOutlined, FileSearchOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
||||
@@ -40,6 +40,8 @@ export default function MainLayout({ onLogout }: { onLogout?: () => void }) {
|
||||
const { mode, isDark, setMode } = useTheme();
|
||||
const { can, canAny } = usePermissions(user);
|
||||
const appInfo = useAppInfo();
|
||||
// App.useApp() 的 modal 实例会继承 ConfigProvider 主题(静态 Modal.confirm 不会,暗色模式下是白底)
|
||||
const { modal } = App.useApp();
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) navigate('/login');
|
||||
@@ -80,23 +82,28 @@ export default function MainLayout({ onLogout }: { onLogout?: () => void }) {
|
||||
douyuItems.push({ key: '/douyu/peace', label: '和平小店', icon: <ShopOutlined /> });
|
||||
}
|
||||
|
||||
// 虎牙
|
||||
if (canAny(['huya:account', 'huya:view_all', 'huya:view_assigned'])) {
|
||||
huyaItems.push({ key: '/huya/accounts', label: '账号管理', icon: <GiftOutlined /> });
|
||||
huyaItems.push({ key: '/huya/device-bindings', label: '设备绑定', icon: <ApiOutlined /> });
|
||||
}
|
||||
if (canAny(['huya:account', 'huya:import'])) {
|
||||
huyaItems.push({ key: '/huya/register', label: '自动注册', icon: <MobileOutlined /> });
|
||||
}
|
||||
if (canAny(['huya:account', 'huya:assign'])) {
|
||||
huyaItems.push({ key: '/huya/assignments', label: '分配管理', icon: <SwapOutlined /> });
|
||||
}
|
||||
if (canAny(['huya:account', 'huya:cookie:view', 'huya:cookie:export'])) {
|
||||
huyaItems.push({ key: '/huya/cookies', label: 'Cookie 管理', icon: <KeyOutlined /> });
|
||||
}
|
||||
// 虎牙:客服只保留浏览器兑换;管理员/运营显示完整入口
|
||||
if (can('huya:task')) {
|
||||
huyaItems.push({ key: '/huya/elite', label: '精英宝典', icon: <BookOutlined /> });
|
||||
huyaItems.push({ key: '/huya/tasks', label: '旧版任务台', icon: <ShoppingCartOutlined /> });
|
||||
if (user?.role === 'support') {
|
||||
huyaItems.push({ key: '/huya/browser-exchange', label: '浏览器兑换', icon: <GlobalOutlined /> });
|
||||
} else {
|
||||
if (canAny(['huya:account', 'huya:view_all', 'huya:view_assigned'])) {
|
||||
huyaItems.push({ key: '/huya/accounts', label: '账号管理', icon: <GiftOutlined /> });
|
||||
huyaItems.push({ key: '/huya/device-bindings', label: '设备绑定', icon: <ApiOutlined /> });
|
||||
}
|
||||
if (canAny(['huya:account', 'huya:import'])) {
|
||||
huyaItems.push({ key: '/huya/register', label: '自动注册', icon: <MobileOutlined /> });
|
||||
}
|
||||
if (canAny(['huya:account', 'huya:assign'])) {
|
||||
huyaItems.push({ key: '/huya/assignments', label: '分配管理', icon: <SwapOutlined /> });
|
||||
}
|
||||
if (canAny(['huya:account', 'huya:cookie:view', 'huya:cookie:export'])) {
|
||||
huyaItems.push({ key: '/huya/cookies', label: 'Cookie 管理', icon: <KeyOutlined /> });
|
||||
}
|
||||
huyaItems.push({ key: '/huya/elite', label: '精英宝典', icon: <BookOutlined /> });
|
||||
huyaItems.push({ key: '/huya/browser-exchange', label: '浏览器兑换', icon: <GlobalOutlined /> });
|
||||
huyaItems.push({ key: '/huya/tasks', label: '旧版任务台', icon: <ShoppingCartOutlined /> });
|
||||
}
|
||||
}
|
||||
|
||||
if (canAny(['yyb:session', 'yyb:history'])) {
|
||||
@@ -125,7 +132,7 @@ export default function MainLayout({ onLogout }: { onLogout?: () => void }) {
|
||||
}
|
||||
|
||||
const handleLogout = () => {
|
||||
Modal.confirm({
|
||||
modal.confirm({
|
||||
title: '确认退出',
|
||||
content: '确定要退出登录吗?',
|
||||
okText: '退出',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState, useMemo, useCallback } from 'react';
|
||||
import {
|
||||
Alert, Table, Button, Modal, Input, Select, Popconfirm, Typography, Tag, Space,
|
||||
Row, Col, Card, Statistic,
|
||||
Row, Col, Card, Statistic, App,
|
||||
} from 'antd';
|
||||
import { message } from '../utils/antdMessage';
|
||||
import type { TableProps } from 'antd';
|
||||
@@ -19,6 +19,8 @@ const TAG_COLORS = [
|
||||
];
|
||||
|
||||
export default function AccountsPage() {
|
||||
// App.useApp() 的 modal 实例继承主题,静态 Modal.confirm 在暗色模式下是白底
|
||||
const { modal } = App.useApp();
|
||||
const [accounts, setAccounts] = useState<AccountItem[]>([]);
|
||||
const [users, setUsers] = useState<UserInfo[]>([]);
|
||||
const [tags, setTags] = useState<string[]>([]);
|
||||
@@ -238,7 +240,7 @@ export default function AccountsPage() {
|
||||
setSensitiveVisible(false);
|
||||
return;
|
||||
}
|
||||
Modal.confirm({
|
||||
modal.confirm({
|
||||
title: '显示账号凭据?',
|
||||
content: '密码、邮箱和邮箱密码将临时显示在当前页面。关闭或刷新页面后会恢复脱敏。',
|
||||
okText: '显示',
|
||||
|
||||
@@ -858,7 +858,6 @@ export default function HuyaAccountsPage() {
|
||||
</Paragraph>
|
||||
</Space>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="批量设置标签"
|
||||
open={batchTagVisible}
|
||||
|
||||
@@ -0,0 +1,550 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
Alert, Button, Card, Empty, Input, Modal, Popconfirm, Select, Space, Spin, Table, Tag, Tooltip, Typography,
|
||||
} from 'antd';
|
||||
import type { TableProps } from 'antd';
|
||||
import {
|
||||
CopyOutlined, DeleteOutlined, GlobalOutlined, HistoryOutlined, ImportOutlined, ReloadOutlined, SearchOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
huyaApi,
|
||||
type HuyaAccountItem,
|
||||
type HuyaBrowserExchangeKit,
|
||||
type HuyaExchangeRecord,
|
||||
} from '../api/modules';
|
||||
import { getErrorMessage } from '../utils/error';
|
||||
import { message } from '../utils/antdMessage';
|
||||
import { copyTextToClipboard } from '../utils/clipboard';
|
||||
import { huyaExchangeHelperReady, openExchangeTarget, requestExtensionInject } from '../utils/huyaExchange';
|
||||
|
||||
const { Text, Paragraph } = Typography;
|
||||
const SCOPE = 'browser_exchange' as const;
|
||||
const IMPORT_PAGE_SIZE = 20;
|
||||
|
||||
/** 表格"兑换记录"列的单元格状态(按账号缓存最近一次查询结果) */
|
||||
interface RecordsCell {
|
||||
phase: 'loading' | 'done' | 'error';
|
||||
records: HuyaExchangeRecord[];
|
||||
errorMsg?: string;
|
||||
}
|
||||
|
||||
export default function HuyaBrowserExchangePage() {
|
||||
const [pool, setPool] = useState<HuyaAccountItem[]>([]);
|
||||
const [accounts, setAccounts] = useState<HuyaAccountItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
// 导入弹窗:候选池走服务端分页筛选(搜索/标签/仅有 CK),与斗鱼操作台导入一致
|
||||
const [importOpen, setImportOpen] = useState(false);
|
||||
const [importPool, setImportPool] = useState<HuyaAccountItem[]>([]);
|
||||
const [importTotal, setImportTotal] = useState(0);
|
||||
const [importPage, setImportPage] = useState(1);
|
||||
const [importLoading, setImportLoading] = useState(false);
|
||||
const [importSearch, setImportSearch] = useState('');
|
||||
const [importTag, setImportTag] = useState('');
|
||||
const [importTags, setImportTags] = useState<string[]>([]);
|
||||
const [importSelectedIds, setImportSelectedIds] = useState<number[]>([]);
|
||||
const [importAllLoading, setImportAllLoading] = useState(false);
|
||||
const [exchangeKit, setExchangeKit] = useState<HuyaBrowserExchangeKit | null>(null);
|
||||
const [exchangeTitle, setExchangeTitle] = useState('');
|
||||
const [exchangeId, setExchangeId] = useState<number | null>(null);
|
||||
const [recordsState, setRecordsState] = useState<{
|
||||
account: HuyaAccountItem;
|
||||
phase: 'loading' | 'done' | 'error';
|
||||
records: HuyaExchangeRecord[];
|
||||
errorMsg: string;
|
||||
} | null>(null);
|
||||
const [recordsMap, setRecordsMap] = useState<Record<number, RecordsCell>>({});
|
||||
// 查询序号:重新发起查询或关闭弹窗时自增,使进行中的轮询失效
|
||||
const recordsSeqRef = useRef(0);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [poolResult, workbenchResult] = await Promise.all([
|
||||
huyaApi.listAccounts({ include_cookie: false }),
|
||||
huyaApi.listWorkbenchAccounts(SCOPE),
|
||||
]);
|
||||
setPool(poolResult);
|
||||
const byId = new Map(poolResult.map((item) => [item.id, item]));
|
||||
setAccounts(
|
||||
workbenchResult.account_ids
|
||||
.map((id) => byId.get(Number(id)))
|
||||
.filter((item): item is HuyaAccountItem => Boolean(item)),
|
||||
);
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadImportPool = useCallback(async () => {
|
||||
setImportLoading(true);
|
||||
try {
|
||||
// 候选池 = 账号库按搜索/标签过滤且必须有 Cookie,剔除已加入兑换列表的账号
|
||||
const result = await huyaApi.listAccountsPaged({
|
||||
search: importSearch.trim() || undefined,
|
||||
tag: importTag || undefined,
|
||||
has_cookie: true,
|
||||
page: importPage,
|
||||
page_size: IMPORT_PAGE_SIZE,
|
||||
});
|
||||
const exclude = new Set(accounts.map((item) => item.id));
|
||||
setImportPool(result.items.filter((item) => !exclude.has(item.id)));
|
||||
setImportTotal(result.total);
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setImportLoading(false);
|
||||
}
|
||||
}, [accounts, importPage, importSearch, importTag]);
|
||||
|
||||
useEffect(() => { void load(); }, [load]);
|
||||
useEffect(() => { if (importOpen) void loadImportPool(); }, [importOpen, loadImportPool]);
|
||||
useEffect(() => {
|
||||
if (!importOpen) return;
|
||||
void huyaApi.listTags().then(setImportTags).catch(() => {});
|
||||
}, [importOpen]);
|
||||
// 切换搜索/标签/翻页时清空已选,避免计数与可见行不一致
|
||||
useEffect(() => {
|
||||
setImportPage(1);
|
||||
setImportSelectedIds([]);
|
||||
}, [importSearch, importTag]);
|
||||
useEffect(() => { setImportSelectedIds([]); }, [importPage]);
|
||||
|
||||
const persistAccounts = async (ids: number[]): Promise<number[]> => {
|
||||
const saved = await huyaApi.updateWorkbenchAccounts(ids, SCOPE);
|
||||
const byId = new Map(pool.map((item) => [item.id, item]));
|
||||
setAccounts(
|
||||
saved.account_ids
|
||||
.map((id) => byId.get(Number(id)))
|
||||
.filter((item): item is HuyaAccountItem => Boolean(item)),
|
||||
);
|
||||
return saved.account_ids;
|
||||
};
|
||||
|
||||
const removeAccount = async (record: HuyaAccountItem) => {
|
||||
try {
|
||||
await persistAccounts(accounts.filter((item) => item.id !== record.id).map((item) => item.id));
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
}
|
||||
};
|
||||
|
||||
const importAccounts = async (ids: number[]) => {
|
||||
const toImport = importPool.filter((item) => ids.includes(item.id));
|
||||
if (!toImport.length) return;
|
||||
try {
|
||||
await persistAccounts([...new Set([...accounts.map((item) => item.id), ...toImport.map((item) => item.id)])]);
|
||||
setImportSelectedIds([]);
|
||||
setImportOpen(false);
|
||||
message.success(`已导入 ${toImport.length} 个账号`);
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
}
|
||||
};
|
||||
|
||||
const importAllAccounts = async () => {
|
||||
setImportAllLoading(true);
|
||||
try {
|
||||
const result = await huyaApi.listAccountIds({
|
||||
search: importSearch.trim() || undefined,
|
||||
tag: importTag || undefined,
|
||||
has_cookie: true,
|
||||
});
|
||||
const existing = new Set(accounts.map((item) => item.id));
|
||||
const imported = result.account_ids.filter((id) => !existing.has(id));
|
||||
if (!imported.length) {
|
||||
message.info('当前筛选条件下没有可新增的账号');
|
||||
return;
|
||||
}
|
||||
await persistAccounts([...accounts.map((item) => item.id), ...imported]);
|
||||
setImportSelectedIds([]);
|
||||
setImportOpen(false);
|
||||
message.success(`已一键导入 ${imported.length} 个账号`);
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setImportAllLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExchange = async (record: HuyaAccountItem) => {
|
||||
setExchangeId(record.id);
|
||||
try {
|
||||
const kit = await huyaApi.createBrowserExchange(record.id);
|
||||
requestExtensionInject(kit);
|
||||
setExchangeKit(kit);
|
||||
setExchangeTitle(record.nickname || record.username || record.yyuid || `账号#${record.id}`);
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setExchangeId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const copyExchangeText = async (text: string, tip: string) => {
|
||||
try {
|
||||
await copyTextToClipboard(text);
|
||||
message.success(tip);
|
||||
} catch {
|
||||
message.error('复制失败,请重试');
|
||||
}
|
||||
};
|
||||
|
||||
const queryExchangeRecords = async (record: HuyaAccountItem) => {
|
||||
const seq = ++recordsSeqRef.current;
|
||||
const alive = () => seq === recordsSeqRef.current;
|
||||
const patch = (update: Partial<RecordsCell>) => {
|
||||
setRecordsMap((prev) => {
|
||||
const current = prev[record.id];
|
||||
const merged: RecordsCell = {
|
||||
phase: update.phase ?? current?.phase ?? 'loading',
|
||||
records: update.records ?? current?.records ?? [],
|
||||
errorMsg: update.errorMsg ?? current?.errorMsg,
|
||||
};
|
||||
return { ...prev, [record.id]: merged };
|
||||
});
|
||||
setRecordsState((prev) => (prev && prev.account.id === record.id ? { ...prev, ...update } : prev));
|
||||
};
|
||||
setRecordsMap((prev) => ({ ...prev, [record.id]: { phase: 'loading', records: [] } }));
|
||||
setRecordsState({ account: record, phase: 'loading', records: [], errorMsg: '' });
|
||||
try {
|
||||
const batch = await huyaApi.createTasks({
|
||||
account_ids: [record.id],
|
||||
task_type: 'query_exchange_records',
|
||||
handbook_scope: 'elite',
|
||||
});
|
||||
const startedAt = Date.now();
|
||||
for (;;) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
if (!alive()) return;
|
||||
if (Date.now() - startedAt > 60_000) {
|
||||
patch({ phase: 'error', errorMsg: '查询超时,请稍后重试' });
|
||||
return;
|
||||
}
|
||||
const tasks = await huyaApi.listTasks(batch.batch_id, 'elite');
|
||||
const task = tasks.find((item) => item.account_id === record.id);
|
||||
if (!task) continue;
|
||||
if (task.status === 'success') {
|
||||
const result = (task.result || {}) as { records?: HuyaExchangeRecord[] };
|
||||
patch({ phase: 'done', records: result.records || [] });
|
||||
return;
|
||||
}
|
||||
if (['failed', 'error', 'stopped', 'timeout'].includes(task.status)) {
|
||||
patch({ phase: 'error', errorMsg: task.message || '查询失败' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (alive()) patch({ phase: 'error', errorMsg: getErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
|
||||
const closeRecordsModal = () => {
|
||||
recordsSeqRef.current += 1;
|
||||
setRecordsState(null);
|
||||
};
|
||||
|
||||
/** 点击表格单元格时用缓存结果打开详情弹窗(不重新查询) */
|
||||
const openCachedRecords = (record: HuyaAccountItem, cell: RecordsCell) => {
|
||||
if (cell.phase !== 'done') return;
|
||||
recordsSeqRef.current += 1;
|
||||
setRecordsState({ account: record, phase: 'done', records: cell.records, errorMsg: '' });
|
||||
};
|
||||
|
||||
const exchangeHelperReady = huyaExchangeHelperReady();
|
||||
|
||||
const columns: TableProps<HuyaAccountItem>['columns'] = [
|
||||
{
|
||||
title: '账号',
|
||||
render: (_value, record) => (
|
||||
<Space size={6}>
|
||||
<Text strong>{record.nickname || record.username || record.uid}</Text>
|
||||
{record.username && record.username !== (record.nickname || record.username) && (
|
||||
<Text type="secondary">{record.username}</Text>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{ title: '标签', dataIndex: 'tag', render: (tag: string) => (tag ? <Tag>{tag}</Tag> : '-') },
|
||||
{
|
||||
title: '登录态',
|
||||
render: (_value, record) => (record.has_cookie
|
||||
? <Tag color="success">有 Cookie</Tag>
|
||||
: <Tag color="warning">无 Cookie</Tag>),
|
||||
},
|
||||
{
|
||||
title: '兑换记录',
|
||||
render: (_value, record) => {
|
||||
const cell = recordsMap[record.id];
|
||||
if (!cell) return <Text type="secondary">未查询</Text>;
|
||||
if (cell.phase === 'loading') return <Spin size="small" />;
|
||||
if (cell.phase === 'error') {
|
||||
return (
|
||||
<Tooltip title={cell.errorMsg}>
|
||||
<Text type="danger">查询失败</Text>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
if (!cell.records.length) return <Text type="secondary">暂无记录</Text>;
|
||||
const names = cell.records.map((item) => item.prize_name || '未命名奖品');
|
||||
const summary = names.length > 1 ? `${names[0]} 等 ${names.length} 条` : names[0];
|
||||
return (
|
||||
<Tooltip title={names.join('、')}>
|
||||
<Text
|
||||
style={{ cursor: 'pointer' }}
|
||||
onClick={() => openCachedRecords(record, cell)}
|
||||
>
|
||||
{summary}
|
||||
</Text>
|
||||
</Tooltip>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 200,
|
||||
render: (_value, record) => (
|
||||
<Space size={6}>
|
||||
<Tooltip title={record.has_cookie
|
||||
? '自动写入登录态并打开兑换页面(用你自己的 Chrome/Edge 完成)'
|
||||
: '该账号没有 Cookie,请联系管理员在账号管理中完成登录'}>
|
||||
<Button
|
||||
size="small"
|
||||
type="primary"
|
||||
ghost
|
||||
icon={<GlobalOutlined />}
|
||||
disabled={!record.has_cookie}
|
||||
loading={exchangeId === record.id}
|
||||
onClick={() => void handleExchange(record)}
|
||||
>
|
||||
浏览器兑换
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Tooltip title="查询该账号的兑换记录">
|
||||
<Button
|
||||
size="small"
|
||||
icon={<HistoryOutlined />}
|
||||
loading={recordsState?.phase === 'loading' && recordsState.account.id === record.id}
|
||||
onClick={() => void queryExchangeRecords(record)}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Popconfirm title="确认从兑换列表移除该账号?" onConfirm={() => void removeAccount(record)}>
|
||||
<Button size="small" danger icon={<DeleteOutlined />} />
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
|
||||
<div>
|
||||
<h2 style={{ margin: 0 }}>浏览器兑换</h2>
|
||||
<Text type="secondary">把账号登录态写入你自己的 Chrome/Edge 后打开兑换页,兑换手动完成;客服仅可见已分配给自己的账号。</Text>
|
||||
</div>
|
||||
<Space>
|
||||
<Button icon={<ImportOutlined />} onClick={() => setImportOpen(true)}>导入账号</Button>
|
||||
<Button icon={<ReloadOutlined />} onClick={() => void load()} loading={loading}>刷新</Button>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
{!exchangeHelperReady && (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
style={{ marginBottom: 12 }}
|
||||
message="未检测到「虎牙兑换助手」扩展"
|
||||
description="安装后点「浏览器兑换」即可自动写入登录态并打开兑换页(见 docs/HUYA_BROWSER_EXCHANGE.md,开发者模式加载 web/extension/huya-exchange-helper 并刷新本页);未安装时可走兑换弹窗里的手动脚本流程。"
|
||||
/>
|
||||
)}
|
||||
|
||||
<Card size="small" styles={{ body: { padding: '4px 6px' } }}>
|
||||
<Table<HuyaAccountItem>
|
||||
rowKey="id"
|
||||
size="small"
|
||||
columns={columns}
|
||||
dataSource={accounts}
|
||||
loading={loading}
|
||||
pagination={accounts.length > 20 ? { pageSize: 20 } : false}
|
||||
locale={{ emptyText: '还没有账号,点击右上角「导入账号」开始' }}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<Modal
|
||||
title="导入兑换账号"
|
||||
open={importOpen}
|
||||
onCancel={() => setImportOpen(false)}
|
||||
footer={null}
|
||||
width={700}
|
||||
>
|
||||
<div style={{ marginBottom: 12, display: 'flex', flexWrap: 'wrap', gap: 8 }}>
|
||||
<Space wrap>
|
||||
<Input
|
||||
placeholder="搜索账号/昵称"
|
||||
prefix={<SearchOutlined />}
|
||||
allowClear
|
||||
value={importSearch}
|
||||
onChange={(event) => setImportSearch(event.target.value)}
|
||||
style={{ width: 220 }}
|
||||
/>
|
||||
<Select
|
||||
placeholder="按标签筛选"
|
||||
allowClear
|
||||
showSearch
|
||||
value={importTag || undefined}
|
||||
onChange={(value) => setImportTag(value || '')}
|
||||
style={{ width: 160 }}
|
||||
options={importTags.map((tag) => ({ value: tag, label: tag }))}
|
||||
/>
|
||||
</Space>
|
||||
<Space wrap style={{ width: '100%' }}>
|
||||
<Button onClick={() => void importAccounts(importPool.map((item) => item.id))}>
|
||||
导入本页 ({importPool.length})
|
||||
</Button>
|
||||
<Button loading={importAllLoading} onClick={() => void importAllAccounts()}>
|
||||
一键导入全部
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
disabled={!importSelectedIds.length}
|
||||
onClick={() => void importAccounts(importSelectedIds)}
|
||||
>
|
||||
导入选中 ({importSelectedIds.length})
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
<Table
|
||||
rowKey="id"
|
||||
size="small"
|
||||
loading={importLoading}
|
||||
rowSelection={{ selectedRowKeys: importSelectedIds, onChange: (keys) => setImportSelectedIds(keys.map(Number)) }}
|
||||
dataSource={importPool}
|
||||
columns={[
|
||||
{ title: '账号', render: (_value, row) => row.nickname || row.username || row.uid },
|
||||
{ title: '用户名', dataIndex: 'username', render: (value: string) => value || '-' },
|
||||
{ title: '标签', dataIndex: 'tag', width: 140, render: (value: string) => (value ? <Tag color="blue">{value}</Tag> : '-') },
|
||||
]}
|
||||
pagination={{
|
||||
current: importPage,
|
||||
pageSize: IMPORT_PAGE_SIZE,
|
||||
total: importTotal,
|
||||
size: 'small',
|
||||
showLessItems: true,
|
||||
showTotal: (total) => `共 ${total} 条`,
|
||||
onChange: setImportPage,
|
||||
}}
|
||||
locale={{ emptyText: '没有可导入的账号' }}
|
||||
/>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title={`兑换记录 · ${recordsState?.account.nickname || recordsState?.account.username || `账号#${recordsState?.account.id}` || ''}`}
|
||||
open={recordsState !== null}
|
||||
onCancel={closeRecordsModal}
|
||||
width={760}
|
||||
footer={[
|
||||
<Button
|
||||
key="retry"
|
||||
loading={recordsState?.phase === 'loading'}
|
||||
onClick={() => recordsState && void queryExchangeRecords(recordsState.account)}
|
||||
>
|
||||
重新查询
|
||||
</Button>,
|
||||
<Button key="close" type="primary" onClick={closeRecordsModal}>关闭</Button>,
|
||||
]}
|
||||
>
|
||||
{recordsState?.phase === 'loading' && (
|
||||
<div style={{ padding: '48px 0', textAlign: 'center' }}>
|
||||
<Spin size="large" />
|
||||
<Paragraph type="secondary" style={{ marginTop: 12 }}>正在通过精英宝典任务查询兑换记录…</Paragraph>
|
||||
</div>
|
||||
)}
|
||||
{recordsState?.phase === 'error' && (
|
||||
<Alert type="error" showIcon message="兑换记录查询失败" description={recordsState.errorMsg} />
|
||||
)}
|
||||
{recordsState?.phase === 'done' && (
|
||||
recordsState.records.length ? (
|
||||
<Table
|
||||
rowKey="record_id"
|
||||
size="small"
|
||||
dataSource={recordsState.records}
|
||||
pagination={false}
|
||||
scroll={{ y: 420 }}
|
||||
columns={[
|
||||
{ title: '#', dataIndex: 'index', width: 48 },
|
||||
{ title: '奖品', dataIndex: 'prize_name', render: (value: string) => value || '-' },
|
||||
{ title: '积分', dataIndex: 'score', width: 90, render: (value: number) => (value != null ? `${value}积分` : '-') },
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status_label',
|
||||
width: 90,
|
||||
render: (value: string) => (
|
||||
<Tag color={value === '已发放' ? 'success' : 'warning'}>{value}</Tag>
|
||||
),
|
||||
},
|
||||
{ title: '兑换时间', dataIndex: 'exchange_time_text', width: 170, render: (value: string) => value || '-' },
|
||||
{ title: '订单号', dataIndex: 'order_id', render: (value: string) => value || '-' },
|
||||
]}
|
||||
/>
|
||||
) : (
|
||||
<Empty description="暂无兑换记录" />
|
||||
)
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title={`浏览器兑换 · ${exchangeTitle}`}
|
||||
open={exchangeKit !== null}
|
||||
width={720}
|
||||
centered
|
||||
onCancel={() => setExchangeKit(null)}
|
||||
footer={exchangeKit ? [
|
||||
<Button key="open" type="primary" icon={<GlobalOutlined />} onClick={() => openExchangeTarget(exchangeKit.target_url)}>打开兑换页面</Button>,
|
||||
<Button key="done" onClick={() => { setExchangeKit(null); message.success('兑换完成后可在精英宝典任务中刷新积分'); }}>完成</Button>,
|
||||
] : null}
|
||||
>
|
||||
{exchangeKit && (
|
||||
<Space orientation="vertical" style={{ width: '100%' }} size={12}>
|
||||
{exchangeHelperReady ? (
|
||||
<Alert
|
||||
type="success"
|
||||
showIcon
|
||||
message="已检测到「虎牙兑换助手」扩展"
|
||||
description="点击「浏览器兑换」时已自动写入该账号登录态并在新标签页打开兑换页面。请确认页面右上角账号无误后手动完成兑换;若页面未自动打开,按下方手动步骤操作。"
|
||||
/>
|
||||
) : (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
message="未检测到「虎牙兑换助手」扩展"
|
||||
description="安装后可一键自动写入登录态(见 docs/HUYA_BROWSER_EXCHANGE.md)。当前请按下方手动步骤操作。"
|
||||
/>
|
||||
)}
|
||||
<Paragraph style={{ marginBottom: 0 }}>
|
||||
<Text strong>手动步骤 1:</Text>
|
||||
点击下方「打开兑换页面」,在新标签页打开兑换活动页。
|
||||
</Paragraph>
|
||||
<Paragraph style={{ marginBottom: 0 }}>
|
||||
<Text strong>手动步骤 2:</Text>
|
||||
点击「复制登录脚本」,在兑换页面按 <Text code>F12</Text> 打开控制台,粘贴脚本并回车执行。
|
||||
Chrome/Edge 首次粘贴需先手动输入 <Text code>allow pasting</Text> 再回车。脚本会写入该账号的登录态并自动跳转。
|
||||
</Paragraph>
|
||||
<Space wrap>
|
||||
<Button icon={<CopyOutlined />} onClick={() => void copyExchangeText(exchangeKit.cookie_script, '登录脚本已复制')}>复制登录脚本</Button>
|
||||
<Button icon={<CopyOutlined />} onClick={() => void copyExchangeText(exchangeKit.cookie_string, 'Cookie 字符串已复制')}>复制 Cookie 字符串</Button>
|
||||
</Space>
|
||||
<Paragraph type="secondary" style={{ marginBottom: 0 }}>
|
||||
备选:安装 Cookie-editor 类扩展后,在 .huya.com 域下导入 Cookie 字符串。脚本和 Cookie 等同账号凭证,请勿泄露给他人。
|
||||
</Paragraph>
|
||||
<Paragraph style={{ marginBottom: 0 }}>
|
||||
<Text strong>手动步骤 3:</Text>
|
||||
确认页面右上角登录态为目标账号后完成兑换,回到此处点击「完成」。
|
||||
</Paragraph>
|
||||
</Space>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/** 复制文本到剪贴板,兼容非安全上下文(http:// 非 localhost) */
|
||||
export function copyTextToClipboard(text: string): Promise<void> {
|
||||
if (navigator.clipboard?.writeText) {
|
||||
return navigator.clipboard.writeText(text);
|
||||
}
|
||||
// fallback:利用 textarea + execCommand,兼容 http 远程访问
|
||||
return new Promise((resolve, reject) => {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
ta.style.position = 'fixed';
|
||||
ta.style.left = '-9999px';
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
try {
|
||||
const ok = document.execCommand('copy');
|
||||
document.body.removeChild(ta);
|
||||
if (ok) {
|
||||
resolve();
|
||||
} else {
|
||||
reject(new Error('copy failed'));
|
||||
}
|
||||
} catch (err) {
|
||||
document.body.removeChild(ta);
|
||||
reject(err as Error);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/** 虎牙浏览器兑换:与内置扩展(web/extension/huya-exchange-helper)的通信桥。 */
|
||||
|
||||
import type { HuyaBrowserExchangeKit } from '../api/modules';
|
||||
|
||||
/** 解析后端 Cookie 字符串为 [name, value] 数组,供兑换扩展注入 */
|
||||
export function parseCookieString(cookieString: string): [string, string][] {
|
||||
return cookieString
|
||||
.split(';')
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.includes('='))
|
||||
.map((part) => {
|
||||
const idx = part.indexOf('=');
|
||||
return [part.slice(0, idx), part.slice(idx + 1)];
|
||||
});
|
||||
}
|
||||
|
||||
/** 内置扩展的内容脚本会在所有页面打上此标记 */
|
||||
export function huyaExchangeHelperReady(): boolean {
|
||||
return document.documentElement.dataset.huyaExchangeHelper === '1';
|
||||
}
|
||||
|
||||
/** 请求内置扩展自动注入登录态;同时留存到 window 供扩展图标点击兜底读取 */
|
||||
export function requestExtensionInject(kit: HuyaBrowserExchangeKit): void {
|
||||
const payload = JSON.stringify({ target_url: kit.target_url, cookies: parseCookieString(kit.cookie_string) });
|
||||
(window as unknown as { __huyaExchangeKit?: string }).__huyaExchangeKit = payload;
|
||||
window.dispatchEvent(new CustomEvent('huya-exchange-kit', { detail: payload }));
|
||||
}
|
||||
|
||||
/** 在新标签页打开兑换页面(noopener 避免反向标签劫持) */
|
||||
export function openExchangeTarget(targetUrl: string): void {
|
||||
window.open(targetUrl, '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
Reference in New Issue
Block a user