feat(huya): 统一积分兑换并完善兑换记录
This commit is contained in:
@@ -11,6 +11,14 @@ from sqlalchemy.orm import Session
|
||||
from core.huya.wss_client import POINTS_REDEEM_GOODS_NUM
|
||||
|
||||
from ..models import HuyaAccount, HuyaGoodsSnapshot, HuyaTask
|
||||
from .huya_pay_link import pay_qr_path, resolve_pay_targets
|
||||
from .huya_points_exchange import (
|
||||
EXCHANGE_STATUS_EXCHANGED,
|
||||
EXCHANGE_STATUS_PAYMENT_REQUIRED,
|
||||
complete_exchange_after_payment,
|
||||
normalize_spu_id,
|
||||
prepare_exchange,
|
||||
)
|
||||
|
||||
# 积分查询超时:HTTP 通道正常几百毫秒,10 秒足够;失败时别让整批任务长时间挂住。
|
||||
HUYA_POINTS_QUERY_TIMEOUT_SECONDS = 10.0
|
||||
@@ -37,6 +45,8 @@ class GoodsMixin:
|
||||
self, uid: int, cookie: str, b_act_id_int: int, outer_act_id: str = ""
|
||||
): ...
|
||||
def _mark_task(self, *args: Any, **kwargs: Any) -> None: ...
|
||||
def _update_task_progress(self, *args: Any, **kwargs: Any) -> None: ...
|
||||
def _wait_recharge_payment(self, *args: Any, **kwargs: Any): ...
|
||||
def _wait_until(self, when: datetime, uid: int) -> bool: ...
|
||||
def _parse_scheduled_time(self, value: Any) -> datetime | None: ...
|
||||
|
||||
@@ -216,16 +226,6 @@ class GoodsMixin:
|
||||
account_info: dict,
|
||||
config_info: dict,
|
||||
):
|
||||
sid = str(self.payload.get("sid") or config_info.get("sid") or "").strip()
|
||||
if not sid:
|
||||
self._mark_task(worker_db, task, "failed", "请先配置虎牙活动 SID")
|
||||
return
|
||||
|
||||
sid_int = self._to_int(sid)
|
||||
if not sid_int:
|
||||
self._mark_task(worker_db, task, "failed", f"虎牙活动 SID 无效: {sid}")
|
||||
return
|
||||
|
||||
uid = self._resolve_uid(account_info)
|
||||
if not uid:
|
||||
self._mark_task(worker_db, task, "failed", "无法从账号或 Cookie 解析 yyuid")
|
||||
@@ -236,7 +236,50 @@ class GoodsMixin:
|
||||
self._mark_task(worker_db, task, "failed", "账号 Cookie 为空")
|
||||
return
|
||||
|
||||
client: Any = self._activity_client(uid, cookie)
|
||||
from core.huya.shop_structs import extract_points_center_sid
|
||||
|
||||
client: Any = self._http_client()
|
||||
configured_sid = self._to_int(self.payload.get("sid") or config_info.get("sid"))
|
||||
sid_int = configured_sid
|
||||
sid_source = "config"
|
||||
try:
|
||||
page_code = (
|
||||
str(config_info.get("points_page_code") or "").strip()
|
||||
or "heping_baodian_credit_center_page"
|
||||
)
|
||||
source_id = (
|
||||
str(config_info.get("points_source_id") or "").strip()
|
||||
or "yellowcarlist"
|
||||
)
|
||||
scene = self._to_int(config_info.get("points_scene")) or 7
|
||||
allocation = client.play_mall_query_allocation(
|
||||
uid=uid,
|
||||
guid="",
|
||||
cookie=cookie,
|
||||
page_code=page_code,
|
||||
source_id=source_id,
|
||||
scene=scene,
|
||||
deep=True,
|
||||
)
|
||||
payload = getattr(allocation, "payload", None)
|
||||
discovered_sid = extract_points_center_sid(payload)
|
||||
if discovered_sid:
|
||||
sid_int = discovered_sid
|
||||
sid_source = "queryAllocation"
|
||||
except Exception as exc: # noqa: BLE001 自动发现失败时回退配置值
|
||||
self._push_log(
|
||||
"warning",
|
||||
f"[{uid}] 自动发现兑换活动 SID 失败,回退配置值: {exc}",
|
||||
)
|
||||
if not sid_int:
|
||||
self._mark_task(
|
||||
worker_db,
|
||||
task,
|
||||
"failed",
|
||||
"无法确定当前兑换活动 SID,请先刷新积分中心商品",
|
||||
)
|
||||
return
|
||||
|
||||
response = client.get_user_prize_records(uid=uid, cookie=cookie, sid=sid_int)
|
||||
if response is None:
|
||||
self._mark_task(worker_db, task, "error", "虎牙兑换记录接口无响应")
|
||||
@@ -244,6 +287,8 @@ class GoodsMixin:
|
||||
|
||||
result = response.to_dict()
|
||||
result["sid"] = sid_int
|
||||
result["sid_source"] = sid_source
|
||||
result["configured_sid"] = configured_sid
|
||||
if response.status != 200:
|
||||
self._mark_task(
|
||||
worker_db,
|
||||
@@ -277,16 +322,6 @@ class GoodsMixin:
|
||||
account_info: dict,
|
||||
config_info: dict,
|
||||
):
|
||||
sid = str(self.payload.get("sid") or config_info.get("sid") or "").strip()
|
||||
if not sid:
|
||||
self._mark_task(worker_db, task, "failed", "请先配置虎牙活动 SID")
|
||||
return
|
||||
|
||||
sid_int = self._to_int(sid)
|
||||
if not sid_int:
|
||||
self._mark_task(worker_db, task, "failed", f"虎牙活动 SID 无效: {sid}")
|
||||
return
|
||||
|
||||
uid = self._resolve_uid(account_info)
|
||||
if not uid:
|
||||
self._mark_task(worker_db, task, "failed", "无法从账号或 Cookie 解析 yyuid")
|
||||
@@ -297,29 +332,36 @@ class GoodsMixin:
|
||||
self._mark_task(worker_db, task, "failed", "账号 Cookie 为空")
|
||||
return
|
||||
|
||||
client: Any = self._activity_client(uid, cookie)
|
||||
response = client.get_act_prize_list(uid=uid, cookie=cookie, sid=sid_int)
|
||||
if response is None:
|
||||
self._mark_task(worker_db, task, "error", "虎牙商品列表接口无响应")
|
||||
return
|
||||
from .huya_collab_service import fetch_points_center_gifts
|
||||
|
||||
result = response.to_dict()
|
||||
result["sid"] = sid_int
|
||||
if response.status != 200:
|
||||
self._mark_task(
|
||||
worker_db,
|
||||
task,
|
||||
"failed",
|
||||
response.msg or f"虎牙商品列表刷新失败: {response.status}",
|
||||
result,
|
||||
)
|
||||
return
|
||||
|
||||
goods = [
|
||||
item
|
||||
for item in result.get("goods", [])
|
||||
if item.get("product_id") and item.get("name")
|
||||
sid_int = self._to_int(config_info.get("sid")) or 2203
|
||||
page_code = (
|
||||
str(config_info.get("points_page_code") or "").strip()
|
||||
or "heping_baodian_credit_center_page"
|
||||
)
|
||||
source_id = (
|
||||
str(config_info.get("points_source_id") or "").strip() or "yellowcarlist"
|
||||
)
|
||||
scene = self._to_int(config_info.get("points_scene")) or 7
|
||||
page_id = self._to_int(config_info.get("points_page_id")) or None
|
||||
tab_ids = [
|
||||
int(part)
|
||||
for part in str(config_info.get("points_tab_ids") or "")
|
||||
.replace(",", ",")
|
||||
.replace(" ", ",")
|
||||
.split(",")
|
||||
if part.isdigit()
|
||||
]
|
||||
goods, message = fetch_points_center_gifts(
|
||||
uid,
|
||||
cookie,
|
||||
client=self._http_client(),
|
||||
page_code=page_code,
|
||||
source_id=source_id,
|
||||
scene=scene,
|
||||
page_id=page_id,
|
||||
tab_ids=tab_ids or None,
|
||||
)
|
||||
now = datetime.now(UTC)
|
||||
worker_db.query(HuyaGoodsSnapshot).filter(
|
||||
HuyaGoodsSnapshot.account_id == account.id,
|
||||
@@ -339,10 +381,26 @@ class GoodsMixin:
|
||||
)
|
||||
)
|
||||
|
||||
result = {
|
||||
"source": "PlayMallUI.queryAllocation",
|
||||
"sid": sid_int,
|
||||
"page_code": page_code,
|
||||
"source_id": source_id,
|
||||
"scene": scene,
|
||||
"goods": goods,
|
||||
}
|
||||
if not goods:
|
||||
self._mark_task(worker_db, task, "failed", message, result)
|
||||
return
|
||||
account.status = "goods_refreshed"
|
||||
account.updated_at = now
|
||||
message = f"已刷新商品 {len(goods)} 个"
|
||||
self._mark_task(worker_db, task, "success", message, {**result, "goods": goods})
|
||||
self._mark_task(
|
||||
worker_db,
|
||||
task,
|
||||
"success",
|
||||
f"已刷新积分中心商品 {len(goods)} 个",
|
||||
result,
|
||||
)
|
||||
|
||||
def _execute_exchange_goods(
|
||||
self,
|
||||
@@ -352,18 +410,8 @@ class GoodsMixin:
|
||||
account_info: dict,
|
||||
config_info: dict,
|
||||
):
|
||||
sid = str(self.payload.get("sid") or config_info.get("sid") or "").strip()
|
||||
if not sid:
|
||||
self._mark_task(worker_db, task, "failed", "请先配置虎牙活动 SID")
|
||||
return
|
||||
|
||||
sid_int = self._to_int(sid)
|
||||
if not sid_int:
|
||||
self._mark_task(worker_db, task, "failed", f"虎牙活动 SID 无效: {sid}")
|
||||
return
|
||||
|
||||
product_id = self._to_int(self.payload.get("product_id"))
|
||||
if not product_id:
|
||||
spu_id = normalize_spu_id(self.payload.get("product_id"))
|
||||
if not spu_id:
|
||||
self._mark_task(worker_db, task, "failed", "请选择兑换商品")
|
||||
return
|
||||
|
||||
@@ -377,20 +425,6 @@ class GoodsMixin:
|
||||
self._mark_task(worker_db, task, "failed", "账号 Cookie 为空")
|
||||
return
|
||||
|
||||
snapshot = (
|
||||
worker_db.query(HuyaGoodsSnapshot)
|
||||
.filter(
|
||||
HuyaGoodsSnapshot.account_id == account.id,
|
||||
HuyaGoodsSnapshot.sid == sid_int,
|
||||
HuyaGoodsSnapshot.product_id == str(product_id),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
product_name = str(
|
||||
self.payload.get("product_name")
|
||||
or (snapshot.name if snapshot else "")
|
||||
or product_id
|
||||
)
|
||||
scheduled_at = self._parse_scheduled_time(self.payload.get("scheduled_at"))
|
||||
if self.payload.get("scheduled_at") and scheduled_at is None:
|
||||
self._mark_task(worker_db, task, "failed", "定时兑换时间格式无效")
|
||||
@@ -403,92 +437,153 @@ class GoodsMixin:
|
||||
self._mark_task(worker_db, task, "stopped", "兑换任务已停止")
|
||||
return
|
||||
|
||||
client: Any = self._activity_client(uid, cookie)
|
||||
detail = client.get_act_prize_detail(
|
||||
uid=uid, cookie=cookie, sid=sid_int, pid=product_id
|
||||
)
|
||||
if detail is None:
|
||||
self._mark_task(worker_db, task, "error", "虎牙兑换详情接口无响应")
|
||||
pid = self._to_int(config_info.get("room_pid"))
|
||||
if not pid:
|
||||
self._mark_task(worker_db, task, "failed", "请先配置虎牙直播间 ID")
|
||||
return
|
||||
detail_result = detail.to_dict()
|
||||
prize = detail.prize
|
||||
if detail.status != 200 or prize is None:
|
||||
pay_channel = self._normalize_pay_channel(
|
||||
self.payload.get("pay_channel") or config_info.get("pay_channel")
|
||||
)
|
||||
client: Any = self._http_client()
|
||||
prepared = prepare_exchange(
|
||||
client,
|
||||
uid=uid,
|
||||
cookie=cookie,
|
||||
pid=pid,
|
||||
spu_id=spu_id,
|
||||
pay_channel=pay_channel,
|
||||
stopped=self._stop.is_set,
|
||||
log=lambda message: self._push_log("info", message),
|
||||
)
|
||||
common = {
|
||||
"spu_id": spu_id,
|
||||
"product_name": (prepared.target.get("name") if prepared.target else "")
|
||||
or str(self.payload.get("product_name") or spu_id),
|
||||
"scheduled_at": scheduled_at.isoformat() if scheduled_at else "",
|
||||
"executed_at": datetime.now(UTC).isoformat(),
|
||||
"redeem_state": prepared.state.to_dict() if prepared.state else None,
|
||||
"target": prepared.target,
|
||||
"exchange_plan": prepared.plan,
|
||||
}
|
||||
if prepared.status == EXCHANGE_STATUS_EXCHANGED:
|
||||
result = {
|
||||
**common,
|
||||
"exchange_mode": "points_only",
|
||||
"exchange_order": prepared.order,
|
||||
"payment_status": "not_required",
|
||||
"payment_status_label": "积分直兑",
|
||||
}
|
||||
account.status = "goods_exchanged"
|
||||
account.updated_at = datetime.now(UTC)
|
||||
if prepared.state:
|
||||
account.points = prepared.state.user_score
|
||||
self._mark_task(worker_db, task, "success", prepared.message, result)
|
||||
return
|
||||
if prepared.status != EXCHANGE_STATUS_PAYMENT_REQUIRED or not prepared.purchase:
|
||||
self._mark_task(
|
||||
worker_db,
|
||||
task,
|
||||
"failed",
|
||||
detail.msg or f"虎牙兑换详情获取失败: {detail.status}",
|
||||
detail_result,
|
||||
prepared.message,
|
||||
{**common, **prepared.detail},
|
||||
)
|
||||
return
|
||||
now_ts = int(time.time())
|
||||
if prize.isCanExchange == 0:
|
||||
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
|
||||
)
|
||||
return
|
||||
if prize.exchangeEndTime and now_ts > prize.exchangeEndTime:
|
||||
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
|
||||
)
|
||||
return
|
||||
if score.status != 200 or score.available_score < prize.newScore:
|
||||
detail_result["score"] = score.to_dict()
|
||||
self._mark_task(worker_db, task, "failed", "可用积分不足", detail_result)
|
||||
return
|
||||
response = client.score_exchange_prize(
|
||||
uid=uid, cookie=cookie, sid=sid_int, pid=product_id
|
||||
)
|
||||
if response is None:
|
||||
self._mark_task(worker_db, task, "error", "虎牙兑换接口无响应")
|
||||
return
|
||||
|
||||
result = response.to_dict()
|
||||
result.update(
|
||||
{
|
||||
"sid": sid_int,
|
||||
"product_id": str(product_id),
|
||||
"product_name": product_name,
|
||||
"scheduled_at": scheduled_at.isoformat() if scheduled_at else "",
|
||||
"executed_at": datetime.now(UTC).isoformat(),
|
||||
"goods": snapshot.raw if snapshot else None,
|
||||
"prize_detail": detail_result,
|
||||
}
|
||||
purchase = prepared.purchase
|
||||
pay_targets = resolve_pay_targets(purchase.pay_url)
|
||||
result = {
|
||||
**common,
|
||||
"exchange_mode": "buy_points_then_exchange",
|
||||
"points_package": prepared.plan,
|
||||
"points_purchase": {
|
||||
"order_id": purchase.order_id,
|
||||
"app_order_id": purchase.app_order_id,
|
||||
"pay_order_id": purchase.pay_order_id,
|
||||
"product_name": purchase.product_name,
|
||||
"count": purchase.count,
|
||||
"unit_price": purchase.unit_price,
|
||||
"amount": purchase.amount,
|
||||
"supplier_name": purchase.supplier_name,
|
||||
"order": purchase.order_raw,
|
||||
"pay": purchase.pay_raw,
|
||||
},
|
||||
"pay_url": purchase.pay_url,
|
||||
"pay_qr_code": pay_targets.qr_code,
|
||||
"pay_cashier_url": pay_targets.cashier_url,
|
||||
"pay_qr_path": pay_qr_path(task.id) if task is not None else "",
|
||||
"payment_status": "pending",
|
||||
"payment_status_label": "等待支付积分包",
|
||||
"payment_paid": False,
|
||||
}
|
||||
account.status = "exchange_payment_pending"
|
||||
account.updated_at = datetime.now(UTC)
|
||||
self._update_task_progress(
|
||||
worker_db,
|
||||
task,
|
||||
"running",
|
||||
f"积分不足,需先购买 {prepared.plan['name'] if prepared.plan else '积分包'},等待扫码支付",
|
||||
result,
|
||||
)
|
||||
if response.status != 200:
|
||||
payment_status, _payment_order = self._wait_recharge_payment(
|
||||
client=client,
|
||||
uid=uid,
|
||||
guid="",
|
||||
cookie=cookie,
|
||||
order_id=purchase.order_id,
|
||||
sid=self._to_int(config_info.get("sid")) or 2203,
|
||||
result=result,
|
||||
)
|
||||
if payment_status == "paid":
|
||||
completed = complete_exchange_after_payment(
|
||||
client,
|
||||
uid=uid,
|
||||
cookie=cookie,
|
||||
pid=pid,
|
||||
spu_id=spu_id,
|
||||
)
|
||||
result.update(
|
||||
{
|
||||
"post_payment_redeem_state": (
|
||||
completed.state.to_dict() if completed.state else None
|
||||
),
|
||||
"exchange_order": completed.order,
|
||||
"target": completed.target or prepared.target,
|
||||
}
|
||||
)
|
||||
if completed.status == EXCHANGE_STATUS_EXCHANGED:
|
||||
account.status = "goods_exchanged"
|
||||
account.updated_at = datetime.now(UTC)
|
||||
if completed.state:
|
||||
account.points = completed.state.user_score
|
||||
self._mark_task(
|
||||
worker_db,
|
||||
task,
|
||||
"success",
|
||||
f"积分包支付成功,{completed.message}",
|
||||
result,
|
||||
)
|
||||
else:
|
||||
self._mark_task(
|
||||
worker_db,
|
||||
task,
|
||||
"failed",
|
||||
f"积分包支付成功,但兑换失败:{completed.message}",
|
||||
result,
|
||||
)
|
||||
return
|
||||
if payment_status == "stopped":
|
||||
self._mark_task(
|
||||
worker_db,
|
||||
task,
|
||||
"failed",
|
||||
response.msg or f"虎牙兑换失败: {response.status}",
|
||||
"stopped",
|
||||
"积分包支付监听已停止",
|
||||
result,
|
||||
)
|
||||
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
|
||||
self._mark_task(
|
||||
worker_db,
|
||||
task,
|
||||
"timeout",
|
||||
f"积分包支付超时,订单 #{purchase.order_id} 仍未完成",
|
||||
result,
|
||||
)
|
||||
if post_score is not None:
|
||||
result["post_exchange_score"] = post_score.to_dict()
|
||||
account.points = post_score.available_score
|
||||
if post_records is not None:
|
||||
result["post_exchange_records"] = post_records.to_dict()
|
||||
account.status = "goods_exchanged"
|
||||
account.updated_at = datetime.now(UTC)
|
||||
message = response.msg or f"兑换成功: {product_name}"
|
||||
self._mark_task(worker_db, task, "success", message, result)
|
||||
|
||||
Reference in New Issue
Block a user