统一推送前Python代码格式

This commit is contained in:
yml2213
2026-09-05 19:25:46 +08:00
parent 90a0065918
commit 8309072120
17 changed files with 492 additions and 189 deletions
@@ -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
View File
@@ -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
+57 -24
View File
@@ -30,7 +30,11 @@ from core.huya import (
login_huya_sms,
send_huya_sms_code,
)
from core.huya.cookie_utils import browser_login_script, cookie_pairs, normalize_huya_cookie
from core.huya.cookie_utils import (
browser_login_script,
cookie_pairs,
normalize_huya_cookie,
)
from core.huya.device_fingerprint import account_state_dir as _fp_state_dir
from core.huya.device_profile import (
_load_db as _load_profile_db,
@@ -119,15 +123,24 @@ def create_browser_exchange_kit(
登录态由前端引导用户在自己的 Chrome/Edge 中写入,服务端不托管浏览器会话。
"""
_require_huya_perm(current, "huya:task")
account = _visible_huya_accounts_query(db, current).filter(HuyaAccount.id == account_id).first()
account = (
_visible_huya_accounts_query(db, current)
.filter(HuyaAccount.id == account_id)
.first()
)
if account is None:
raise HTTPException(status_code=404, detail="虎牙账号不存在或无权操作")
if not account.cookie:
raise HTTPException(status_code=400, detail="该账号没有可用 Cookie,请先登录")
config = ensure_huya_config(db)
target_url = BindMixin._bind_redirect_url({
"room_pid": huya_config_value("room_pid", config.room_pid),
}) or "https://zt.huya.com/b02faae1/pc/index.html"
target_url = (
BindMixin._bind_redirect_url(
{
"room_pid": huya_config_value("room_pid", config.room_pid),
}
)
or "https://zt.huya.com/b02faae1/pc/index.html"
)
pairs = dict(cookie_pairs(normalize_huya_cookie(account.cookie)))
return {
"account_id": account.id,
@@ -321,10 +334,13 @@ def _workbench_account_ids(db: Session, current: User, scope: str) -> list[int]:
HuyaWorkbenchAccount.handbook_scope == scope,
)
if not _can_view_huya_all(current):
query = query.join(HuyaAccount, HuyaAccount.id == HuyaWorkbenchAccount.account_id).filter(
HuyaAccount.assigned_to == current.id
)
return [account_id for (account_id,) in query.order_by(HuyaWorkbenchAccount.id.asc()).all()]
query = query.join(
HuyaAccount, HuyaAccount.id == HuyaWorkbenchAccount.account_id
).filter(HuyaAccount.assigned_to == current.id)
return [
account_id
for (account_id,) in query.order_by(HuyaWorkbenchAccount.id.asc()).all()
]
def _require_huya_batch_owner(db: Session, current: User, batch_id: str) -> None:
@@ -1847,10 +1863,15 @@ def list_huya_workbench_accounts(
):
"""读取当前用户指定工作台(精英宝典/浏览器兑换)的账号集合。"""
ids = _workbench_account_ids(db, current, handbook_scope)
configured = db.query(HuyaWorkbench.id).filter(
HuyaWorkbench.user_id == current.id,
HuyaWorkbench.handbook_scope == handbook_scope,
).first() is not None
configured = (
db.query(HuyaWorkbench.id)
.filter(
HuyaWorkbench.user_id == current.id,
HuyaWorkbench.handbook_scope == handbook_scope,
)
.first()
is not None
)
return {"account_ids": ids, "configured": configured}
@@ -1866,10 +1887,14 @@ def update_huya_workbench_accounts(
raise HTTPException(status_code=400, detail="无效的账号 ID")
if ids:
_require_huya_task_account_access(db, current, ids)
workbench = db.query(HuyaWorkbench).filter(
HuyaWorkbench.user_id == current.id,
HuyaWorkbench.handbook_scope == req.handbook_scope,
).first()
workbench = (
db.query(HuyaWorkbench)
.filter(
HuyaWorkbench.user_id == current.id,
HuyaWorkbench.handbook_scope == req.handbook_scope,
)
.first()
)
if workbench is None:
db.add(HuyaWorkbench(user_id=current.id, handbook_scope=req.handbook_scope))
else:
@@ -1878,12 +1903,16 @@ def update_huya_workbench_accounts(
HuyaWorkbenchAccount.user_id == current.id,
HuyaWorkbenchAccount.handbook_scope == req.handbook_scope,
).delete(synchronize_session=False)
db.add_all([
HuyaWorkbenchAccount(
user_id=current.id, handbook_scope=req.handbook_scope, account_id=account_id
)
for account_id in ids
])
db.add_all(
[
HuyaWorkbenchAccount(
user_id=current.id,
handbook_scope=req.handbook_scope,
account_id=account_id,
)
for account_id in ids
]
)
db.commit()
return {"account_ids": ids, "success": True}
@@ -1907,7 +1936,11 @@ def list_recharge_goods(
current: User = Depends(require_permission("huya:task")),
):
"""查看已缓存的虎牙充值商品快照。"""
rows = db.query(HuyaRechargeGoodsSnapshot).order_by(HuyaRechargeGoodsSnapshot.id.desc()).all()
rows = (
db.query(HuyaRechargeGoodsSnapshot)
.order_by(HuyaRechargeGoodsSnapshot.id.desc())
.all()
)
latest = {}
for row in rows:
latest.setdefault((row.sid, row.spu_id), row)
+19 -5
View File
@@ -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)
+18 -6
View File
@@ -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
+48 -19
View File
@@ -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},
)
@@ -3,27 +3,30 @@
128/48 用完整图案;16px 细节会糊,改用去掉蝴蝶结的加粗简化版。
用法: uv run python web/extension/huya-exchange-helper/generate_icons.py
"""
from PIL import Image, ImageDraw
S = 1024 # 超采样画布,最后缩到目标尺寸
RADIUS = 200
TOP = (255, 156, 71) # 渐变顶部
BOTTOM = (240, 84, 0) # 渐变底部
BOX = (255, 255, 255) # 礼盒
RIBBON = (234, 74, 8) # 丝带(比背景深,压在白色上可见)
TOP = (255, 156, 71) # 渐变顶部
BOTTOM = (240, 84, 0) # 渐变底部
BOX = (255, 255, 255) # 礼盒
RIBBON = (234, 74, 8) # 丝带(比背景深,压在白色上可见)
def gradient_rounded(size: int, radius: int) -> Image.Image:
grad = Image.new('RGBA', (size, size))
grad = Image.new("RGBA", (size, size))
g = ImageDraw.Draw(grad)
for y in range(size):
t = y / (size - 1)
color = tuple(round(TOP[i] + (BOTTOM[i] - TOP[i]) * t) for i in range(3)) + (255,)
color = tuple(round(TOP[i] + (BOTTOM[i] - TOP[i]) * t) for i in range(3)) + (
255,
)
g.line([(0, y), (size, y)], fill=color)
mask = Image.new('L', (size, size), 0)
mask = Image.new("L", (size, size), 0)
ImageDraw.Draw(mask).rounded_rectangle([0, 0, size, size], radius=radius, fill=255)
out = Image.new('RGBA', (size, size), (0, 0, 0, 0))
out = Image.new("RGBA", (size, size), (0, 0, 0, 0))
out.paste(grad, (0, 0), mask)
return out
@@ -49,21 +52,28 @@ def draw_gift_simple(img: Image.Image) -> None:
d = ImageDraw.Draw(img)
cx = img.width // 2
scale = img.width / 512
def rect(x1, y1, x2, y2, radius):
d.rounded_rectangle([x1 * scale, y1 * scale, x2 * scale, y2 * scale],
radius=radius * scale, fill=BOX)
rect(cx / scale - 144, 96, cx / scale + 144, 206, 24) # 盖
d.rounded_rectangle(
[x1 * scale, y1 * scale, x2 * scale, y2 * scale],
radius=radius * scale,
fill=BOX,
)
rect(cx / scale - 144, 96, cx / scale + 144, 206, 24) # 盖
rect(cx / scale - 112, 230, cx / scale + 112, 420, 28) # 盒身
d.rectangle([cx - 34 * scale, 96 * scale, cx + 34 * scale, 420 * scale], fill=RIBBON)
d.rectangle(
[cx - 34 * scale, 96 * scale, cx + 34 * scale, 420 * scale], fill=RIBBON
)
full = gradient_rounded(S, RADIUS)
draw_gift(full)
base = 'web/extension/huya-exchange-helper/'
base = "web/extension/huya-exchange-helper/"
for size in (128, 48):
full.resize((size, size), Image.LANCZOS).save(f'{base}icon{size}.png')
full.resize((size, size), Image.LANCZOS).save(f"{base}icon{size}.png")
simple = gradient_rounded(512, 100)
draw_gift_simple(simple)
simple.resize((16, 16), Image.LANCZOS).save(f'{base}icon16.png')
print('icons regenerated')
simple.resize((16, 16), Image.LANCZOS).save(f"{base}icon16.png")
print("icons regenerated")