Files
live-hub-py/web/backend/services/douyu_runner_gold.py
T

624 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""斗鱼任务执行器:鱼翅充值(由 douyu_runner.py 按功能域拆分)。"""
from __future__ import annotations
import re
from datetime import UTC, datetime
from decimal import Decimal
from typing import TYPE_CHECKING, Any, cast
from sqlalchemy.orm import Session
from core.douyu import (
DouyuActivityClient,
FishFinRechargeClient,
FishFinRechargeConfig,
FishFinRechargeError,
)
from ..models import Account, DouyuTask
from .business_events import record_recharge
from .douyu_activity_query import query_exchange_balance, query_gold_account
from .douyu_service import update_account_profile_from_cookie
class GoldMixin:
"""鱼翅充值域:扫码充值、供应商直充与到账轮询。"""
if TYPE_CHECKING:
_stop: Any
@staticmethod
def _to_int(value: Any) -> int | None: ...
def _client(
self, cookie: str, *, direct: bool = False
) -> DouyuActivityClient: ...
def _task_payload(self, task: DouyuTask) -> dict: ...
def _push_log(self, level: str, message: str) -> None: ...
def _mark_task(self, *args: Any, **kwargs: Any) -> None: ...
def _update_task_progress(self, *args: Any, **kwargs: Any) -> None: ...
def _refresh_account_gold_balance(
self, client: DouyuActivityClient, account: Account
) -> dict:
"""刷新鱼翅和钱包兑换余额并写回账号表。"""
gold = query_gold_account(client)
exchange = query_exchange_balance(client)
account.gold_balance = self._to_int(gold.get("gold"))
account.exchange_balance = self._to_int(exchange.get("count"))
account.updated_at = datetime.now(UTC)
return {
"gold_balance": account.gold_balance,
"exchange_balance": account.exchange_balance,
"gold": gold,
"exchange_balance_query": exchange,
}
def _poll_create_gold_qr_once(
self,
db: Session,
task: DouyuTask,
account: Account,
cookie: str,
config: dict,
) -> None:
"""查询一次鱼翅扫码充值是否到账,然后释放 worker。"""
result = dict(task.result or {})
result["payment_polling"] = True
result["payment_poll_count"] = int(result.get("payment_poll_count") or 0) + 1
try:
client = self._client(cookie, direct=True)
balance_result = self._refresh_account_gold_balance(client, account)
db.commit()
result.update(balance_result)
last_gold = balance_result["gold_balance"]
baseline_gold = self._to_int(result.get("baseline_gold_balance"))
if baseline_gold is None:
result["baseline_gold_balance"] = last_gold
self._schedule_payment_poll(
db,
task,
result,
f"鱼翅支付码已生成,已记录当前余额 {last_gold if last_gold is not None else '-'},等待到账",
)
return
# 余额必须增加才算到账,下降可能来自同账号送礼等消费。
if last_gold is not None and last_gold > baseline_gold:
result.pop("payment_poll_error", None)
result["gold_recharged"] = True
result["payment_polling"] = False
amount = int(
result.get("payment_amount")
or self._task_payload(task).get("amount")
or self._task_payload(task).get("gold_amount")
or 1
)
channel = str(
result.get("payment_channel")
or config.get("gold_recharge_channel")
or "wechat_qr"
)
account.updated_at = datetime.now(UTC)
record_recharge(
db,
account,
task_id=task.id,
amount=amount,
channel=channel,
balance_after=account.gold_balance,
confirmed=True,
actor_id=int(task.created_by),
)
self._mark_task(
db,
task,
"success",
f"鱼翅已到账,当前余额: {account.gold_balance if account.gold_balance is not None else '-'}",
result,
)
return
result.pop("payment_poll_error", None)
self._schedule_payment_poll(
db,
task,
result,
f"鱼翅支付码已生成,等待到账(当前鱼翅 {last_gold if last_gold is not None else '-'})",
)
except Exception as exc: # noqa: BLE001 外部接口失败继续等待
result["payment_poll_error"] = str(exc)
self._schedule_payment_poll(
db,
task,
result,
f"等待鱼翅到账: {exc}",
)
@staticmethod
def _supplier_value(payload: dict, *keys: str):
"""兼容供应商将订单字段放在响应根节点、data 或 result 节点。"""
data_raw = payload.get("data")
data = cast(dict[str, Any], data_raw) if isinstance(data_raw, dict) else {}
result_raw = payload.get("result")
result = (
cast(dict[str, Any], result_raw) if isinstance(result_raw, dict) else {}
)
for source in (payload, data, result):
for key in keys:
if source.get(key) is not None:
return source[key]
return None
@classmethod
def _supplier_order_status(cls, payload: dict) -> int | None:
"""提取供应商订单状态,文档约定 0-4。"""
return cls._to_int(
cls._supplier_value(
payload, "order_status", "orderStatus", "supplier_order_status"
)
)
@classmethod
def _supplier_message(cls, payload: dict) -> str:
"""提取供应商可展示的业务消息。"""
value = cls._supplier_value(payload, "msg", "message", "error_msg")
return str(value or "")[:256]
@staticmethod
def _supplier_result(payload: dict) -> dict:
"""保存必要订单状态,避免把完整供应商响应或签名暴露到任务结果。"""
data_raw = payload.get("data")
data = cast(dict[str, Any], data_raw) if isinstance(data_raw, dict) else {}
result_raw = payload.get("result")
response_result = (
cast(dict[str, Any], result_raw) if isinstance(result_raw, dict) else {}
)
result = {
key: value
for key, value in {**payload, **data, **response_result}.items()
if key not in {"sign", "cards", "card_no", "card_pwd", "recharge_arg"}
}
return result
@staticmethod
def _supplier_out_order_id(task: DouyuTask) -> str:
"""生成可追踪的供应商外部订单号;已有订单号必须在重试时复用。"""
existing = str(task.supplier_out_order_id or "").strip()
if existing:
return existing
batch_token = (
re.sub(r"[^A-Za-z0-9]", "", str(task.batch_id or "")).upper()[:16]
or "LOCAL"
)
return f"DYGF{batch_token}T{task.id}"
def _poll_create_gold_supplier_once(
self,
db: Session,
task: DouyuTask,
account: Account,
cookie: str,
*,
amount: int,
) -> None:
"""同时核对供应商订单和斗鱼余额,任一证明到账即可收口。"""
db.refresh(task)
if task.status in {"success", "failed", "error", "stopped"}:
return
task_id = int(task.id)
result = dict(task.result or {})
order_no = str(result["out_order_id"])
result["payment_polling"] = True
result["payment_poll_count"] = int(result.get("payment_poll_count") or 0) + 1
code: int | None = None
status: int | None = None
supplier_error = ""
gold_result: dict[str, Any] = {}
gold_error = ""
try:
gold_result = self._refresh_account_gold_balance(
self._client(cookie, direct=True),
account,
)
except Exception as exc: # noqa: BLE001 余额核对失败仍继续查供应商
gold_error = str(exc)
try:
client = FishFinRechargeClient(FishFinRechargeConfig.from_env())
payload = client.query_order(order_no)
code = self._to_int(self._supplier_value(payload, "code"))
status = self._supplier_order_status(payload)
result.update(
{
"supplier_code": code,
"supplier_order_status": status,
"supplier_order": self._supplier_result(payload),
}
)
except Exception as exc: # noqa: BLE001 供应商查询异常由持久调度继续重试
supplier_error = str(exc)
# 查询期间供应商回调可能已经把任务收口。重新锁行后再决定是否写入,
# 避免长时间 HTTP 调用结束后用旧状态覆盖回调结果。
db.rollback()
locked = (
db.query(DouyuTask)
.filter(
DouyuTask.id == task_id,
DouyuTask.status == "running",
DouyuTask.queue_lane == "payment_poll",
)
.with_for_update()
.first()
)
if locked is None:
return
task = locked
locked_account = db.query(Account).filter(Account.id == task.account_id).first()
if locked_account is None:
self._mark_task(
db,
task,
"failed",
"账号不存在,无法继续核对供应商充值到账",
result,
)
return
account = locked_account
if gold_result:
result.update(gold_result)
account.gold_balance = self._to_int(gold_result.get("gold_balance"))
account.exchange_balance = self._to_int(gold_result.get("exchange_balance"))
account.updated_at = datetime.now(UTC)
baseline = self._to_int(result.get("baseline_gold_balance"))
baseline_ready = bool(
result.get("baseline_gold_ready")
and result.get("baseline_gold_source") == "pre_order"
and baseline is not None
)
current_gold = (
account.gold_balance
if gold_result
else self._to_int(result.get("gold_balance"))
)
balance_confirmed = bool(
baseline_ready
and current_gold is not None
and baseline is not None
and current_gold > baseline
)
result["supplier_balance_confirmed"] = balance_confirmed
if balance_confirmed:
result.pop("payment_poll_error", None)
result["gold_recharged"] = True
self._finish_supplier_gold_order(
db,
task,
account,
result,
amount=amount,
status=2,
balance_confirmed=True,
cookie=cookie,
gold_already_refreshed=bool(gold_result),
)
return
if supplier_error:
result["payment_poll_error"] = supplier_error
self._schedule_payment_poll(
db,
task,
result,
f"查询供应商订单失败: {supplier_error}",
)
return
if code != 200:
self._finish_supplier_gold_order(
db,
task,
account,
result,
amount=amount,
status=(status if status in {2, 3, 4} else 4),
)
return
if status in {2, 3, 4}:
self._finish_supplier_gold_order(
db,
task,
account,
result,
amount=amount,
status=status,
cookie=cookie,
gold_already_refreshed=bool(gold_result),
)
return
if gold_error:
result["payment_poll_error"] = gold_error
else:
result.pop("payment_poll_error", None)
self._schedule_payment_poll(
db,
task,
result,
"供应商直充订单处理中"
f"(状态 {status if status is not None else '-'},"
f"斗鱼余额 {current_gold if current_gold is not None else '-'})",
)
def _finish_supplier_gold_order(
self,
db: Session,
task: DouyuTask,
account: Account,
result: dict,
*,
amount: int,
status: int | None,
balance_confirmed: bool = False,
cookie: str | None = None,
gold_already_refreshed: bool = False,
) -> None:
if status == 2 or balance_confirmed:
refreshed_after_success = balance_confirmed or gold_already_refreshed
if status == 2 and not refreshed_after_success and cookie:
try:
result.update(
self._refresh_account_gold_balance(
self._client(cookie, direct=True),
account,
)
)
refreshed_after_success = True
self._push_log(
"info",
"供应商直充成功,已刷新鱼翅余额: "
f"{account.gold_balance if account.gold_balance is not None else '-'}",
)
except Exception as exc: # noqa: BLE001 充值成功后刷新失败不翻盘
result["gold_refresh_after_success_error"] = str(exc)
self._push_log("warning", f"供应商直充成功后刷新鱼翅失败: {exc}")
result["gold_refreshed_after_success"] = refreshed_after_success
account.updated_at = datetime.now(UTC)
record_recharge(
db,
account,
task_id=task.id,
amount=amount,
order_id=str(result.get("out_order_id") or ""),
supplier_order_id=str(result.get("order_id") or ""),
channel="supplier_api",
douyu_uid=str(result.get("douyu_uid") or ""),
balance_after=account.gold_balance,
actor_id=int(task.created_by),
confirmed=balance_confirmed,
)
self._mark_task(
db,
task,
"success",
(
"供应商直充到账成功(斗鱼余额已增加)"
if balance_confirmed
else "供应商直充成功"
),
result,
)
return
self._mark_task(db, task, "failed", "供应商直充失败", result)
def _execute_create_gold_qr(
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
):
payload = self._task_payload(task)
amount = int(payload.get("amount") or payload.get("gold_amount") or 1)
channel = str(config.get("gold_recharge_channel") or "wechat_qr")
if channel == "supplier_api":
try:
self._execute_create_gold_supplier_order(
db, task, account, cookie, config, amount
)
except FishFinRechargeError as exc:
self._mark_task(
db, task, "failed", str(exc), {"recharge_channel": "supplier_api"}
)
return
client = self._client(cookie)
baseline_gold = account.gold_balance
try:
baseline = self._refresh_account_gold_balance(client, account)
baseline_gold = baseline["gold_balance"]
db.commit()
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
self._push_log("warning", f"生成鱼翅码前刷新余额失败: {exc}")
result = client.create_gold_qr(
amount=amount, pay_type=int(config["gold_pay_type"])
)
result.update(
{
"payment_amount": amount,
"payment_channel": channel,
"baseline_gold_balance": baseline_gold,
}
)
account.updated_at = datetime.now(UTC)
self._schedule_payment_poll(
db,
task,
result,
f"鱼翅 {amount} 元支付码已生成,等待到账",
)
def _execute_create_gold_supplier_order(
self,
db: Session,
task: DouyuTask,
account: Account,
cookie: str,
config: dict,
amount: int,
) -> None:
"""创建供应商鱼翅直充订单并轮询订单状态。"""
product_id = str(config.get("gold_api_product_id") or "").strip()
template_name = str(
config.get("gold_api_account_template_name") or "斗鱼昵称"
).strip()
if not product_id:
raise FishFinRechargeError("请先在配置中填写供应商直充商品 ID")
# 充值商品按斗鱼昵称识别账号,UID 只能作为审计信息,不能作为充值值。
update_account_profile_from_cookie(account, cookie)
recharge_account = str(account.nickname or "").strip()
if not recharge_account:
raise FishFinRechargeError("账号缺少斗鱼昵称,无法发起供应商直充")
# 供应商订单可能很快到账;基线必须在下单前读取,否则首轮轮询看到的
# 已到账余额会被误当成充值前余额,之后永远等不到“余额增加”。
baseline_gold = account.gold_balance
baseline_gold_ready = False
try:
balance_result = self._refresh_account_gold_balance(
self._client(cookie, direct=True),
account,
)
baseline_gold = self._to_int(balance_result.get("gold_balance"))
baseline_gold_ready = baseline_gold is not None
db.commit()
except Exception as exc: # noqa: BLE001 供应商下单不能被基线查询阻塞
self._push_log("warning", f"供应商直充下单前刷新鱼翅基线失败: {exc}")
# 首次生成后持久化,网络重试或进程重启都继续查询同一笔订单。
order_no = self._supplier_out_order_id(task)
task.supplier_out_order_id = order_no
db.commit()
# pay_amount 是用户选择的充值面值;goodsFaceValue=0.993 是供货成本,不能作为支付金额。
pay_amount = Decimal(amount)
def trace(event: dict) -> None:
"""将脱敏供应商协议信息输出到任务日志,便于线上联调。"""
stage = event.get("stage")
if stage == "request":
params = event.get("params") or {}
self._push_log(
"info",
"供应商直充 | 下单 "
f"| 外部单号={params.get('out_order_id') or '-'} "
f"| 数量={params.get('buy_num') or '-'} "
f"| 金额={params.get('pay_amount') or '-'} "
f"| 商品={params.get('product_id') or '-'}",
)
if event.get("json_body"):
self._push_log(
"debug",
"供应商协议 | 请求 "
f"| {event.get('method')} {event.get('path')} "
f"| 签名摘要={event.get('sign_digest')} "
f"| 参数={FishFinRechargeClient._json_text(event['json_body'])}",
)
elif stage == "response":
status = self._to_int(event.get("order_status"))
status_labels = {
0: "待处理",
1: "处理中",
2: "成功",
3: "失败",
4: "异常",
}
status_text = status_labels.get(
status if status is not None else -1, "-"
)
reason = str(event.get("fail_reason") or event.get("message") or "-")
self._push_log(
"info",
"供应商直充 | 响应 "
f"| HTTP={event.get('http_status') or '-'} "
f"| 业务码={event.get('code') or '-'} "
f"| 外部单号={event.get('out_order_id') or '-'} "
f"| 供应商单号={event.get('order_id') or '-'} "
f"| 状态={status_text} "
f"| 提示={reason}",
)
if event.get("response_body"):
self._push_log(
"debug",
"供应商协议 | 响应 "
f"| HTTP={event.get('http_status')} "
f"| 内容={FishFinRechargeClient._json_text(event['response_body'])}",
)
client = FishFinRechargeClient(FishFinRechargeConfig.from_env(), trace=trace)
order_payload = client.create_order(
buy_num=amount,
pay_amount=pay_amount,
out_order_id=order_no,
product_id=product_id,
recharge_arg=[
{"templateName": template_name, "templateVal": recharge_account}
],
order_type=0,
notify_url=client.config.notify_url,
)
code = self._to_int(self._supplier_value(order_payload, "code"))
status = self._supplier_order_status(order_payload)
result = {
"recharge_channel": "supplier_api",
"out_order_id": order_no,
"order_id": self._supplier_value(order_payload, "order_id", "orderId"),
"recharge_account": recharge_account,
"douyu_uid": str(account.uid or "").strip(),
"buy_num": amount,
"product_id": product_id,
"pay_amount": format(pay_amount.normalize(), "f"),
"order_type": 0,
"baseline_gold_balance": baseline_gold,
"baseline_gold_ready": baseline_gold_ready,
"baseline_gold_source": "pre_order" if baseline_gold_ready else "",
"supplier_code": code,
"supplier_order_status": status,
"supplier_order": self._supplier_result(order_payload),
}
if code != 200:
self._mark_task(
db,
task,
"failed",
self._supplier_message(order_payload) or "供应商创建直充订单失败",
result,
)
return
account.updated_at = datetime.now(UTC)
if status in {2, 3, 4}:
self._finish_supplier_gold_order(
db,
task,
account,
result,
amount=amount,
status=status,
cookie=cookie,
)
return
self._schedule_payment_poll(
db,
task,
result,
"供应商直充订单已创建,等待到账",
)
def _execute_query_gold_balance(
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
):
client = self._client(cookie)
result = self._refresh_account_gold_balance(client, account)
account.updated_at = datetime.now(UTC)
self._mark_task(
db,
task,
"success",
f"鱼翅余额: {account.gold_balance if account.gold_balance is not None else '-'}",
result,
)