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

600 lines
21 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 asyncio
import threading
import time
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Any
from loguru import logger
from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient
from core.douyu.proxy_fetcher import ProxyFetcher
from ..models import (
Account,
DouyuEsportsGoodsSnapshot,
DouyuTask,
DouyuXpdGoodsSnapshot,
)
from ..models import (
ProxyConfig as ProxyConfigModel,
)
from .douyu_account_probe import activity_client
from .douyu_concurrency import clamp_douyu_task_concurrency
from .douyu_goods_service import upsert_goods_snapshot
from .douyu_service import (
DOUYU_CONFIG_FIELDS,
SUPPORTED_DOUYU_TASK_TYPES,
douyu_config_value,
douyu_task_payload,
ensure_douyu_config,
)
from .proxy_service import build_proxy_runtime
if TYPE_CHECKING:
from .douyu_runner import DouyuBatchRunner
# 支付/到账轮询(手册与充值共用)
DOUYU_PAYMENT_POLL_SECONDS = 600
DOUYU_PAYMENT_POLL_INTERVAL = 5
AUTO_EXCHANGE_ELIGIBILITY_TASK_TYPES = frozenset(
{
"create_gold_qr",
"donate_elite_gift",
"create_elite_qr",
"confirm_bind",
"query_game_name",
}
)
# 走代理的任务类型:写操作/消耗类(兑换、锁单、支付、开通、充值、送礼)。
# 查询/刷新/绑定/扫码等读操作始终直连——它们不怕 IP 频控,走代理只会浪费代理额度。
DOUYU_PROXY_TASK_TYPES = {
# 兑换链路(IP 频控重点, 对应"精英手册火爆")
"lock_goods",
"pay_locked_order",
"exchange_goods",
"exchange_esports_goods",
"exchange_xpd_goods",
# 消耗类写操作: 开通手册 / 充值 / 送礼
"create_elite_qr",
"create_esports_qr",
"create_gold_qr",
"donate_elite_gift",
"donate_esports_chicken_gift",
"donate_esports_firework_gift",
}
_DOUYU_RESULT_DEBUG_KEYS = {
"raw",
"query_params",
"qq_app_scheme",
"role_param_url",
"game_role_bind_url",
}
def slim_douyu_task_result_for_storage(result: dict | None) -> dict | None:
"""去掉任务结果里的调试大字段,避免每次轮询重复写大 JSON。
运行器在内存中仍使用完整 result;这里只影响落库和 WS 展示。二维码 URL、
角色状态、积分、订单号等业务字段全部保留。
"""
if result is None:
return None
def clean(value: Any) -> Any:
if isinstance(value, dict):
return {
key: clean(item)
for key, item in value.items()
if key not in _DOUYU_RESULT_DEBUG_KEYS
}
if isinstance(value, list):
return [clean(item) for item in value]
return value
return clean(result)
class DouyuBatchRunnerCore:
"""斗鱼任务执行器公共基础:批次状态、日志、任务落库与客户端构造。"""
def __init__(
self,
db: Session,
batch_id: str,
task_type: str,
payload: dict | None = None,
log_queue: asyncio.Queue | None = None,
loop: asyncio.AbstractEventLoop | None = None,
concurrency: int = 3,
close_db: bool = True,
log_sink: Callable[[dict[str, Any]], None] | None = None,
):
self.db = db
self.close_db = close_db
self.batch_id = batch_id
self.task_type = task_type
self.payload = payload or {}
self.log_queue = log_queue
self.loop = loop
self.concurrency = clamp_douyu_task_concurrency(task_type, concurrency)
self.log_sink = log_sink
self._stop = threading.Event()
self._counter_lock = threading.Lock()
self._started = 0
# 代理接入 (配置源 = 代理配置页, 与 CK 检测/虎牙注册同款):
# 仅兑换/锁单/支付/充值/送礼等写操作任务走代理, 查询/刷新/绑定类直连
self._proxy_cfg = db.query(ProxyConfigModel).first() if db else None
self._proxy_runtime = build_proxy_runtime(
self._proxy_cfg,
stop_event=self._stop,
)
self._proxy_fetcher = self._create_proxy_fetcher()
self._static_proxies = self._resolve_static_proxies()
if self._static_proxies:
logger.info(
f"[douyu] 写操作任务将走静态代理: {self._static_proxies.get('https', '')}"
)
elif self._proxy_fetcher:
logger.info("[douyu] 写操作任务将按任务从代理 API 取新代理")
def _create_proxy_fetcher(self) -> ProxyFetcher | None:
"""API 代理模式: 每个任务从代理 API 取 1 个新代理 (与虎牙注册链同款)."""
return self._proxy_runtime.api_fetcher
def _resolve_static_proxies(self) -> dict[str, str] | None:
"""静态代理模式: 代理配置页手填的 http/https 地址."""
return self._proxy_runtime.static_proxies
def _proxies_for_task(self) -> dict[str, str] | None:
"""取本任务出网代理。
写/读分离:仅兑换/锁单/支付/开通/充值/送礼等写操作任务走代理(应对 IP 频控);
查询/刷新/绑定/扫码等读操作任务始终直连,不消耗代理额度。
"""
if self.task_type not in DOUYU_PROXY_TASK_TYPES:
return None
if self._static_proxies:
return self._static_proxies
if self._proxy_fetcher:
try:
proxy_url = self._proxy_fetcher.fetch_new_proxy()
if proxy_url:
return {"http": proxy_url, "https": proxy_url}
self._push_log("warning", "代理 API 未返回可用代理, 本任务降级直连")
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
self._push_log("warning", f"取代理失败, 本任务降级直连: {exc}")
return None
def stop(self):
self._stop.set()
def _push_log(self, level: str, message: str):
if level == "result":
try:
douyu_batch_registry.mark_finished(self.batch_id)
except NameError:
pass
if level != "result" and message:
log_func = getattr(logger, level, logger.info)
log_func(f"[douyu] {message}")
if self.log_queue and self.loop:
asyncio.run_coroutine_threadsafe(
self.log_queue.put({"level": level, "message": message}),
self.loop,
)
if self.log_sink is not None:
try:
self.log_sink({"level": level, "message": message})
except Exception: # noqa: BLE001 - 日志落库不能中断任务
logger.exception("写入斗鱼批次持久日志失败: {}", self.batch_id)
@staticmethod
def _account_name(account: Account) -> str:
return account.nickname or account.username or account.uid or f"#{account.id}"
@staticmethod
def _to_int(value) -> int | None:
if value is None:
return None
try:
return int(value)
except (TypeError, ValueError):
return None
@staticmethod
def _format_wait_time(seconds: int | None) -> str:
if seconds is None:
return ""
seconds = max(0, int(seconds))
days, rem = divmod(seconds, 86400)
hours, rem = divmod(rem, 3600)
minutes, sec = divmod(rem, 60)
if days:
return f"{days}天{hours}小时{minutes}分"
if hours:
return f"{hours}小时{minutes}分{sec}秒"
return f"{minutes}分{sec}秒"
def _push_task_event(self, task: DouyuTask) -> None:
"""向批次 WS 推送任务状态事件(level=task),前端即时更新不依赖轮询。"""
try:
payload = douyu_task_payload(task)
except Exception: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
logger.exception("[douyu] 推送任务状态失败: task_id={}", task.id)
return
event = {
"level": "task",
"message": "",
"task": payload,
}
if self.log_queue and self.loop:
asyncio.run_coroutine_threadsafe(self.log_queue.put(event), self.loop)
if self.log_sink is not None:
try:
self.log_sink(event)
except Exception: # noqa: BLE001 - 日志落库不能中断任务
logger.exception("写入斗鱼任务事件失败: {}", self.batch_id)
def _sync_platform_fulfillment(self, douyu_task_id: int, *, enabled: bool) -> None:
"""绑定/确认任务完成后立即刷新履约投影并写 Outbox。"""
if not enabled:
return
try:
from ..database import WorkerSessionLocal
from .platform_fulfillment.service import sync_task_from_binding_runner
# 当前批次会话刚刚提交过任务结果。履约投影使用独立短会话,避免
# get_task_detail 留下的只读事务在下一轮外部 HTTP 轮询期间占连接。
sync_db = WorkerSessionLocal()
try:
sync_task_from_binding_runner(sync_db, douyu_task_id=int(douyu_task_id))
finally:
sync_db.close()
except Exception: # noqa: BLE001 - 履约投影失败不能覆盖任务执行结果
logger.exception(
"[douyu] 同步直播账号履约状态失败: task_id={}", douyu_task_id
)
def _refresh_platform_exchange_eligibility(
self,
douyu_task_id: int,
*,
enabled: bool,
) -> None:
"""账号积分/宝典变化后,自动刷新当前履约任务的兑换投影。"""
if not enabled:
return
try:
from ..database import WorkerSessionLocal
from .platform_fulfillment.service import (
refresh_active_exchange_eligibility_for_account,
)
refresh_db = WorkerSessionLocal()
try:
task = refresh_db.get(DouyuTask, int(douyu_task_id))
if task is None or task.status != "success":
return
refresh_active_exchange_eligibility_for_account(
refresh_db,
account_id=int(task.account_id),
scope=str(task.handbook_scope or "elite"),
actor_id=int(task.created_by),
)
finally:
refresh_db.close()
except Exception: # noqa: BLE001 - 自动刷新不能覆盖任务执行结果
logger.exception(
"[douyu] 自动刷新直播履约兑换资格失败: task_id={}",
douyu_task_id,
)
def _sync_platform_fulfillment_operation(
self,
db: Session,
task: DouyuTask,
*,
status: str,
message: str,
) -> None:
if not task.platform_task_id:
return
try:
from .platform_fulfillment.service import record_douyu_operation_result
record_douyu_operation_result(
db,
task,
status=status,
message=message,
)
except Exception: # noqa: BLE001 - 履约时间线不能覆盖任务执行结果
logger.exception("[douyu] 写入履约操作时间线失败: task_id={}", task.id)
def _mark_task(
self,
db: Session,
task: DouyuTask,
status: str,
message: str,
result: dict | None = None,
) -> None:
from .platform_fulfillment.service import requires_account_binding_sync
task_id = int(task.id)
has_platform_task = task.platform_task_id is not None
sync_platform_fulfillment = has_platform_task or requires_account_binding_sync(
task.task_type
)
task.status = status
task.message = message[:512]
if status in {"success", "failed", "error", "stopped"}:
task.queue_lane = ""
task.next_run_at = None
task.run_deadline_at = None
if result is not None:
persisted = dict(result)
if (
status in {"success", "failed", "error", "stopped"}
and "payment_polling" in persisted
):
persisted["payment_polling"] = False
task.result = slim_douyu_task_result_for_storage(persisted)
task.finished_at = datetime.now(UTC)
account = (
db.query(Account).filter(Account.id == task.account_id).first()
if task.account_id and status in {"success", "failed", "error", "stopped"}
else None
)
event_context = (
{
"task_id": int(task.id),
"task_type": str(task.task_type or ""),
"task_label": SUPPORTED_DOUYU_TASK_TYPES.get(
str(task.task_type or ""),
str(task.task_type or "斗鱼任务"),
),
"scope": str(task.handbook_scope or ""),
"finished_at": task.finished_at,
"created_by": int(task.created_by),
}
if account is not None
else None
)
self._sync_platform_fulfillment_operation(
db,
task,
status=status,
message=message,
)
db.commit()
self._push_task_event(task)
if account is not None and event_context is not None:
try:
from .business_events import record_douyu_task_result
record_douyu_task_result(
db,
account,
task_id=event_context["task_id"],
task_type=event_context["task_type"],
task_label=event_context["task_label"],
scope=event_context["scope"],
status=status,
message=message,
occurred_at=event_context["finished_at"],
actor_id=event_context["created_by"],
)
db.commit()
except Exception: # noqa: BLE001 - 时间线旁路不能覆盖已提交的任务结果
db.rollback()
logger.exception(
"[douyu] 写入账号任务结果事件失败: task_id={}", task.id
)
self._sync_platform_fulfillment(
task_id,
enabled=sync_platform_fulfillment,
)
self._refresh_platform_exchange_eligibility(
task_id,
enabled=(
status == "success"
and task.task_type in AUTO_EXCHANGE_ELIGIBILITY_TASK_TYPES
),
)
def _schedule_payment_poll(
self,
db: Session,
task: DouyuTask,
result: dict,
message: str,
*,
delay_seconds: int = DOUYU_PAYMENT_POLL_INTERVAL,
) -> None:
"""二维码已生成后释放 worker,由数据库调度器继续查询到账。"""
now = datetime.now(UTC)
result["payment_polling"] = True
task.queue_lane = "payment_poll"
task.next_run_at = now + timedelta(seconds=max(1, int(delay_seconds)))
task.last_run_at = now
if task.run_deadline_at is None:
deadline = now + timedelta(seconds=DOUYU_PAYMENT_POLL_SECONDS)
task.run_deadline_at = deadline
result["payment_deadline_at"] = deadline.isoformat()
self._update_task_progress(db, task, "running", message, result)
def _update_task_progress(
self,
db: Session,
task: DouyuTask,
status: str,
message: str,
result: dict | None = None,
*,
sync_platform: bool = True,
) -> None:
task_id = int(task.id)
has_platform_task = task.platform_task_id is not None
task.status = status
task.message = message[:512]
if result is not None:
task.result = slim_douyu_task_result_for_storage(result)
db.commit()
self._push_task_event(task)
if sync_platform:
self._sync_platform_fulfillment(task_id, enabled=has_platform_task)
def _upsert_goods(self, db: Session, goods: list[dict]) -> None:
upsert_goods_snapshot(db, goods)
def _upsert_esports_goods(self, db: Session, goods: list[dict]) -> None:
now = datetime.now(UTC)
for raw in goods:
commodity_id = str(raw.get("commodityId") or raw.get("commodity_id") or "")
if not commodity_id:
continue
row = (
db.query(DouyuEsportsGoodsSnapshot)
.filter(DouyuEsportsGoodsSnapshot.commodity_id == commodity_id)
.first()
)
if row is None:
row = DouyuEsportsGoodsSnapshot(commodity_id=commodity_id)
db.add(row)
row.name = str(raw.get("commodityName") or raw.get("name") or "")
row.score = self._to_int(raw.get("score"))
row.status = str(raw.get("status") or "")
row.raw = raw
row.updated_at = now
db.commit()
def _upsert_xpd_goods(self, db: Session, goods: list[dict]) -> None:
"""同步和平小店商品快照,移除上一次热门抢购等遗留商品。"""
now = datetime.now(UTC)
commodity_ids = {
str(raw.get("commodity_id") or raw.get("iGoodsId") or "") for raw in goods
}
commodity_ids.discard("")
query = db.query(DouyuXpdGoodsSnapshot)
if commodity_ids:
query.filter(~DouyuXpdGoodsSnapshot.commodity_id.in_(commodity_ids)).delete(
synchronize_session=False,
)
else:
query.delete(synchronize_session=False)
for raw in goods:
commodity_id = str(raw.get("commodity_id") or raw.get("iGoodsId") or "")
if not commodity_id:
continue
row = (
db.query(DouyuXpdGoodsSnapshot)
.filter(DouyuXpdGoodsSnapshot.commodity_id == commodity_id)
.first()
)
if row is None:
row = DouyuXpdGoodsSnapshot(commodity_id=commodity_id)
db.add(row)
row.name = str(raw.get("name") or raw.get("sGoodsName") or "")
row.price = self._to_int(raw.get("price") or raw.get("iPrice"))
row.org_price = self._to_int(raw.get("org_price") or raw.get("iOrgPrice"))
row.category = str(raw.get("category") or raw.get("iCategoryId") or "")
goods_left = raw.get("goods_left")
if goods_left is None:
goods_left = raw.get("iGoodsLeft")
row.goods_left = self._to_int(goods_left)
row.raw = raw
row.updated_at = now
db.commit()
def _config_info(self, db: Session) -> dict:
config = ensure_douyu_config(db)
return {
field: douyu_config_value(field, getattr(config, field, None))
for field in DOUYU_CONFIG_FIELDS
}
def _task_payload(self, task: DouyuTask) -> dict:
result = task.result if isinstance(task.result, dict) else {}
payload_raw = result.get("payload")
payload = payload_raw if isinstance(payload_raw, dict) else {}
return {**payload, **self.payload}
def _client(
self,
cookie: str,
*,
direct: bool = False,
) -> DouyuActivityClient:
"""任务 HTTP 客户端:写操作任务注入会话级代理(兑换/锁单/支付/充值/送礼),
读操作任务直连;持久支付轮询显式 ``direct=True``,不能每轮取新代理。"""
return activity_client(
cookie,
logger_callback=lambda msg: self._push_log("debug", msg),
proxies=None if direct else self._proxies_for_task(),
)
def _sleep_interruptible(self, seconds: float) -> bool:
"""分段睡眠,任务停止时提前返回;返回 False 表示已被停止。"""
waited = 0.0
step = 0.5
while waited < seconds:
if self._stop.is_set():
return False
time.sleep(min(step, seconds - waited))
waited += step
return not self._stop.is_set()
class DouyuBatchRegistry:
"""管理运行中的斗鱼任务批次。"""
def __init__(self):
self._batches: dict[str, dict] = {}
def register(
self,
batch_id: str,
log_queue: asyncio.Queue | None,
loop: asyncio.AbstractEventLoop | None,
runner: DouyuBatchRunner,
):
self._batches[batch_id] = {
"log_queue": log_queue,
"loop": loop,
"runner": runner,
"finished": False,
"updated_at": time.time(),
}
def get(self, batch_id: str):
return self._batches.get(batch_id)
def pop(self, batch_id: str):
return self._batches.pop(batch_id, None)
def mark_finished(self, batch_id: str):
if batch_id in self._batches:
self._batches[batch_id]["finished"] = True
self._batches[batch_id]["updated_at"] = time.time()
def active_ids(self) -> set[str]:
return {
batch_id
for batch_id, info in self._batches.items()
if not info.get("finished")
}
douyu_batch_registry = DouyuBatchRegistry()