"""斗鱼活动任务路由。""" from __future__ import annotations import asyncio import csv import io import secrets import uuid from datetime import UTC, datetime, timedelta from typing import Any, cast from weakref import WeakKeyDictionary from zoneinfo import ZoneInfo from fastapi import ( APIRouter, Depends, File, HTTPException, Query, Request, Response, UploadFile, WebSocket, WebSocketDisconnect, ) from loguru import logger from sqlalchemy import and_, case, func, or_, select from sqlalchemy.orm import Session, joinedload from sqlalchemy.sql import Select from starlette.concurrency import run_in_threadpool from core.douyu import ( DouyuActivityError, FishFinRechargeClient, FishFinRechargeConfig, FishFinRechargeConfigError, ) from ..database import WorkerSessionLocal, get_db from ..deps import authenticate_websocket, get_current_user, require_permission from ..models import ( Account, AccountSupplyTarget, DouyuConfig, DouyuEsportsGoodsSnapshot, DouyuGoodsSnapshot, DouyuRechargeConfirmation, DouyuTask, DouyuWorkbench, DouyuWorkbenchAccount, DouyuXpdGoodsSnapshot, ExecutionJob, LoginAttempt, LoginTask, PlatformFulfillmentTask, User, ) from ..permissions import user_has_permission from ..schemas import ( CookieReloginRequest, DouyuAccountProtectionTargetOut, DouyuAccountProtectionTargetUpdate, DouyuConfigOut, DouyuConfigUpdate, DouyuExchangeResultImageOut, DouyuGoodsOut, DouyuQueryWorkbenchExportRequest, DouyuQueryWorkbenchLookupRequest, DouyuQueryWorkbenchReloginRequest, DouyuSupplyTargetConfigOut, DouyuSupplyTargetOut, DouyuSupplyTargetUpdate, DouyuSupplyTargetUpsert, DouyuTaskAccountOut, DouyuTaskBatchRequest, DouyuTaskOut, DouyuWorkbenchAccountsUpdate, DouyuXpdGoodsOut, ) from ..services.account_binding import BIND_BOUND, bind_payload from ..services.account_observability import ( account_platform_status, account_platform_trends, account_supply_snapshot, ) from ..services.account_protection_service import ( evaluate_protection_targets, update_protection_group, ) from ..services.account_query_filters import cookie_operable_filter from ..services.account_supply_service import ( SupplyInventory, evaluate_supply_target, load_supply_snapshot_inventories, update_supply_target, upsert_supply_target, ) from ..services.audit_service import record_audit from ..services.automation.scheduler import ensure_jobs from ..services.binding_ownership import ( WORKBENCH_GOODS_MUTATION_TYPES, workbench_force_goods_inspection, ) from ..services.business_events import record_recharge from ..services.douyu_activity_query import activity_client, query_activity_goods from ..services.douyu_batch_launcher import ( DOUYU_BATCH_CREATE_CONCURRENCY, DOUYU_MAX_ACTIVE_BATCHES, ) from ..services.douyu_exchange_result_image import ( ExchangeResultImageError, save_exchange_result_image, ) from ..services.douyu_goods_service import serialize_goods from ..services.douyu_query_workbench import ( DATA_STATE_IMPORTED, DATA_STATES, mark_workbench_stale, pending_query_ids, workbench_state_map, ) from ..services.douyu_runner import DouyuBatchRunner, douyu_batch_registry from ..services.douyu_service import ( DOUYU_ACTIVE_TASK_STATUSES, DOUYU_CONFIG_FIELDS, DOUYU_HANDBOOK_TASK_TYPES, LOGIN_ATTEMPT_IN_FLIGHT_STATUSES, SUPPORTED_DOUYU_TASK_TYPES, DouyuActivePaymentError, DouyuLeaseConflictError, DouyuTaskBackpressureError, apply_douyu_config_defaults, cleanup_orphan_douyu_tasks, cookie_holding_filter, create_douyu_planned_tasks, douyu_config_value, douyu_task_payload, ensure_douyu_config, find_reusable_active_payment_task, visible_douyu_task_accounts, ) from ..services.execution_jobs import ( JOB_DOUYU_BATCH, JOB_LOGIN_BATCH, JOB_RELOGIN_BATCH, LANE_AUTH, LANE_FULFILLMENT, STATUS_QUEUED, STATUS_RUNNING, TERMINAL_STATUSES, enqueue_execution_job, event_payload, execution_events_after, get_execution_job, request_execution_cancel, ) from ..services.file_service import FileUploadError from ..services.file_storage import StorageUnavailableError, max_upload_size_bytes from ..services.login_quota_service import ( CATEGORY_MANUAL, get_login_quota_usage_summary, ) from ..services.login_service import get_relogin_limits from ..services.platform_fulfillment import service as platform_fulfillment_service router = APIRouter(prefix="/api/douyu", tags=["斗鱼活动"]) _BATCH_CREATE_SEMAPHORES: WeakKeyDictionary[ asyncio.AbstractEventLoop, asyncio.Semaphore, ] = WeakKeyDictionary() def _batch_create_semaphore() -> asyncio.Semaphore: """按事件循环复用创建锁,避免测试和开发热重载跨 loop 复用 Semaphore。""" loop = asyncio.get_running_loop() semaphore = _BATCH_CREATE_SEMAPHORES.get(loop) if semaphore is None: semaphore = asyncio.Semaphore(DOUYU_BATCH_CREATE_CONCURRENCY) _BATCH_CREATE_SEMAPHORES[loop] = semaphore return semaphore def _ensure_active_batch_budget(active_count: int) -> None: if active_count >= DOUYU_MAX_ACTIVE_BATCHES: raise HTTPException( status_code=429, detail=( f"斗鱼任务繁忙:当前有 {active_count} 个批次运行中," f"上限 {DOUYU_MAX_ACTIVE_BATCHES} 个,请稍后重试" ), headers={"Retry-After": "5"}, ) def _supplier_response_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 @router.post("/supplier-recharge/callback") async def supplier_recharge_callback(request: Request, db: Session = Depends(get_db)): """接收供应商直充终态通知,验签后按 out_order_id 幂等更新任务。""" try: payload = await request.json() except ValueError as exc: raise HTTPException(status_code=400, detail="供应商回调不是 JSON") from exc if not isinstance(payload, dict): raise HTTPException(status_code=400, detail="供应商回调格式无效") try: client = FishFinRechargeClient(FishFinRechargeConfig.from_env()) except FishFinRechargeConfigError as exc: logger.error("[douyu] 供应商直充回调配置无效: {}", exc) raise HTTPException(status_code=503, detail="供应商直充回调未配置") from exc try: verified = client.verify_response_sign(payload, "POST") finally: close = getattr(client, "close", None) if callable(close): close() if not verified: logger.warning("[douyu] 供应商直充回调验签失败: keys={}", sorted(payload)) raise HTTPException(status_code=401, detail="供应商回调签名无效") out_order_id = str(_supplier_response_value(payload, "out_order_id") or "").strip() if not out_order_id: raise HTTPException(status_code=400, detail="供应商回调缺少 out_order_id") task = ( db.query(DouyuTask) .filter( DouyuTask.supplier_out_order_id == out_order_id, DouyuTask.task_type == "create_gold_qr", ) .first() ) if not task: raise HTTPException(status_code=404, detail="供应商回调订单不存在") status = DouyuBatchRunner._to_int( _supplier_response_value(payload, "order_status", "orderStatus") ) result = dict(task.result) if isinstance(task.result, dict) else {} result.update( { "out_order_id": out_order_id, "order_id": _supplier_response_value(payload, "order_id", "orderId") or result.get("order_id"), "supplier_order_status": status, "supplier_order": DouyuBatchRunner._supplier_result(payload), "supplier_callback_received": True, } ) # 这笔充值到没到账,用**回调自己说的终态**判断,而不是「任务状态有没有被改」。 # 否则会漏掉一个真实黑洞:runner 轮询超时先判了 failed(gold.py 末尾), # 回调随后才到达成功 —— 守卫会跳过状态更新,这笔真金白银永远不进时间线。 recharge_confirmed = status == 2 if task.status not in {"success", "failed", "stopped"}: if status == 2: task.status = "success" task.message = "供应商直充成功(异步通知)" task.finished_at = datetime.now(UTC) task.queue_lane = "" task.next_run_at = None task.run_deadline_at = None if task.account: task.account.updated_at = datetime.now(UTC) elif status in {3, 4}: reason = str( _supplier_response_value(payload, "fail_reason", "message", "msg") or "供应商直充失败" ) task.status = "failed" task.message = reason[:512] task.finished_at = datetime.now(UTC) task.queue_lane = "" task.next_run_at = None task.run_deadline_at = None else: task.status = "running" task.message = ( f"供应商直充订单处理中(状态 {status if status is not None else '-'})" ) task.result = result callback_success = status not in {3, 4} if task.platform_task_id and status in {2, 3, 4}: platform_fulfillment_service.record_douyu_operation_result( db, task, status="success" if status == 2 else "failed", message=task.message, ) # 回调说成功了就补一条充值事件。幂等键与 runner 那条**完全一致** # (business_events.task_ref),所以「runner 也观测到了」时不会重复记账; # 而「runner 已判超时/失败、回调才到」这个黑洞则能被补上。 if recharge_confirmed and task.account is not None: record_recharge( db, task.account, task_id=task.id, amount=_to_int_or_none(result.get("buy_num")), 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=task.account.gold_balance, confirmed=False, ) record_audit( db, None, action="recharge:douyu:callback", target=f"supplier_order:{out_order_id}", detail={ "out_order_id": out_order_id, "task_id": task.id, "order_id": result.get("order_id"), "supplier_order_status": status, "task_status": task.status, "message": task.message, }, success=callback_success, ) db.commit() logger.info( "[douyu] 供应商直充回调已处理: out_order_id={} status={}", out_order_id, status ) acknowledgement = {"code": 200, "message": "success"} acknowledgement["sign"] = client.sign(acknowledgement, "POST") return acknowledgement def _can_view_all(user: User) -> bool: """客服始终只能看自己名下账号,额外权限也不能突破这个角色边界。""" return user.role != "support" and user_has_permission(user, "account:view_all") def _visible_task_accounts_query( db: Session, current: User, *, include_all: bool = False ): """返回当前用户可用于斗鱼任务的账号查询。 只要账号还持有 Cookie 就可见;排队中的普通登录(pending/running)和 重登失败(relogin_failed)都会保留旧 CK,不能让账号从工作台消失。 查询工作台场景(include_all=True)允许展示无 CK / 已失效等全部可见账号。 """ query = db.query(Account).options(joinedload(Account.assigned_user)) if not include_all: cookie_ids = select(Account.id).where(cookie_holding_filter()) query = query.filter(Account.id.in_(cookie_ids)) if _can_view_all(current): return query if user_has_permission(current, "account:view_assigned"): return query.filter(Account.assigned_to == current.id) raise HTTPException(status_code=403, detail="无权查看斗鱼账号") def _visible_tasks_query(db: Session, current: User): """返回当前用户可查看的斗鱼任务查询。""" # 任务列表只展示账号识别信息,避免 joinedload 把密码、邮箱等加密大字段带出。 account_loader = joinedload(DouyuTask.account).load_only( Account.id, Account.username, Account.uid, Account.nickname, Account.assigned_to, ) query = db.query(DouyuTask).options(account_loader) if _can_view_all(current): return query if user_has_permission(current, "account:view_assigned"): # 彻底消除全表 filesort:直接通过 douyu_tasks 上的 account_assigned_to 复合索引倒序定位 return query.filter( or_( DouyuTask.account_assigned_to == current.id, DouyuTask.created_by == current.id, ) ) raise HTTPException(status_code=403, detail="无权查看斗鱼任务") def _split_task_scope_query(query, handbook_scope: str | None) -> list: """Build index-friendly branches for a workbench scope. Legacy rows map to the requested workbench by task type. A single ``task_type IN (...) ORDER BY id DESC`` query makes MySQL scan the broad handbook-scope index, so use one range per task type instead. """ if not handbook_scope: return [query] branches = [query.filter(DouyuTask.handbook_scope == handbook_scope)] branches.extend( query.filter( DouyuTask.handbook_scope == "legacy", DouyuTask.task_type == task_type, ) for task_type in DOUYU_HANDBOOK_TASK_TYPES[handbook_scope] ) return branches def _list_visible_tasks_for_support( db: Session, current: User, *, batch_id: str | None, handbook_scope: str | None, account_scope_query: Select | None, limit: int, offset: int = 0, ) -> list[DouyuTask]: """按归属/创建人和工作台范围拆成索引分支,合并后加载完整任务。""" owner_filters: list[tuple[Any, ...]] = [ (DouyuTask.account_assigned_to == current.id,), (DouyuTask.created_by == current.id,), ] take = offset + limit task_ids: list[int] = [] for owner_filter in owner_filters: base_query = db.query(DouyuTask.id).filter(*owner_filter) if batch_id: base_query = base_query.filter(DouyuTask.batch_id == batch_id) if account_scope_query is not None: base_query = base_query.filter( DouyuTask.account_id.in_(account_scope_query) ) for query in _split_task_scope_query(base_query, handbook_scope): rows = query.order_by(DouyuTask.id.desc()).limit(take).all() task_ids.extend(int(row[0]) for row in rows) page_ids = sorted(set(task_ids), reverse=True)[offset : offset + limit] if not page_ids: return [] account_loader = joinedload(DouyuTask.account).load_only( Account.id, Account.username, Account.uid, Account.nickname, Account.assigned_to, ) tasks_by_id = { task.id: task for task in ( db.query(DouyuTask) .options(account_loader) .filter(DouyuTask.id.in_(page_ids)) .all() ) } return [tasks_by_id[task_id] for task_id in page_ids if task_id in tasks_by_id] def _list_visible_tasks_for_admin( db: Session, *, batch_id: str | None, handbook_scope: str | None, account_scope_query: Select | None, limit: int, offset: int = 0, ) -> list[DouyuTask]: """管理员任务列表按作用域拆索引分支,避免 OR + JOIN 触发大排序。""" take = offset + limit task_ids: list[int] = [] base_query = db.query(DouyuTask.id) if batch_id: base_query = base_query.filter(DouyuTask.batch_id == batch_id) if account_scope_query is not None: base_query = base_query.filter(DouyuTask.account_id.in_(account_scope_query)) for query in _split_task_scope_query(base_query, handbook_scope): rows = query.order_by(DouyuTask.id.desc()).limit(take).all() task_ids.extend(int(row[0]) for row in rows) page_ids = sorted(set(task_ids), reverse=True)[offset : offset + limit] if not page_ids: return [] account_loader = joinedload(DouyuTask.account).load_only( Account.id, Account.username, Account.uid, Account.nickname, Account.assigned_to, ) tasks_by_id = { task.id: task for task in ( db.query(DouyuTask) .options(account_loader) .filter(DouyuTask.id.in_(page_ids)) .all() ) } return [tasks_by_id[task_id] for task_id in page_ids if task_id in tasks_by_id] def _count_visible_tasks_for_admin( db: Session, *, batch_id: str | None, handbook_scope: str | None, account_scope_query: Select | None, ) -> int: """按作用域分支统计管理员任务数,避免 OR 条件走低效排序。""" if handbook_scope: scope_filters: list[tuple[Any, ...]] = [ (DouyuTask.handbook_scope == handbook_scope,), ( DouyuTask.handbook_scope == "legacy", DouyuTask.task_type.in_(DOUYU_HANDBOOK_TASK_TYPES[handbook_scope]), ), ] else: scope_filters = [()] total = 0 for scope_filter in scope_filters: query = db.query(func.count(DouyuTask.id)).filter(*scope_filter) if batch_id: query = query.filter(DouyuTask.batch_id == batch_id) if account_scope_query is not None: query = query.filter(DouyuTask.account_id.in_(account_scope_query)) total += int(query.scalar() or 0) return total def _count_visible_tasks_for_support( db: Session, current: User, *, batch_id: str | None, handbook_scope: str | None, account_scope_query: Select | None, ) -> int: """用索引分支精确计算归属/创建人并集的任务总数。""" if handbook_scope: scope_filters: list[tuple[Any, ...]] = [ (DouyuTask.handbook_scope == handbook_scope,), ( DouyuTask.handbook_scope == "legacy", DouyuTask.task_type.in_(DOUYU_HANDBOOK_TASK_TYPES[handbook_scope]), ), ] else: scope_filters = [()] def count_owner( owner_filter: tuple[Any, ...], scope_filter: tuple[Any, ...] ) -> int: query = db.query(func.count(DouyuTask.id)).filter(*owner_filter, *scope_filter) if batch_id: query = query.filter(DouyuTask.batch_id == batch_id) if account_scope_query is not None: query = query.filter(DouyuTask.account_id.in_(account_scope_query)) return int(query.scalar() or 0) assigned_filter = (DouyuTask.account_assigned_to == current.id,) created_filter = (DouyuTask.created_by == current.id,) both_filter = assigned_filter + created_filter total = 0 for scope_filter in scope_filters: total += count_owner(assigned_filter, scope_filter) total += count_owner(created_filter, scope_filter) total -= count_owner(both_filter, scope_filter) return total def _require_task_account_access( db: Session, current: User, account_ids: list[int], *, platform_task_id: int | None = None, ) -> None: """确保任务只会提交到当前用户可操作的账号。""" requested_ids = set(account_ids) query = db.query(Account.id).filter(Account.id.in_(requested_ids)) if not _can_view_all(current): if not user_has_permission(current, "account:view_assigned"): raise HTTPException(status_code=403, detail="无权操作斗鱼账号") query = query.filter(Account.assigned_to == current.id) allowed_ids = {account_id for (account_id,) in query.all()} if allowed_ids == requested_ids: return if ( platform_task_id and len(requested_ids) == 1 and user_has_permission(current, "platform_fulfillment:use") ): task = ( db.query(PlatformFulfillmentTask) .filter( PlatformFulfillmentTask.id == int(platform_task_id), PlatformFulfillmentTask.account_id.in_(requested_ids), PlatformFulfillmentTask.execution_status.notin_( ["completed", "cancelled"] ), ) .first() ) if task is not None: return raise HTTPException(status_code=403, detail="包含无权操作的斗鱼账号") def _require_batch_owner(db: Session, current: User, batch_id: str) -> None: """除超级管理员外,只能停止或订阅自己创建的任务批次。""" if current.role == "super_admin": return exists = ( db.query(DouyuTask.id) .filter(DouyuTask.batch_id == batch_id, DouyuTask.created_by == current.id) .first() ) if not exists: raise HTTPException(status_code=403, detail="无权操作该斗鱼任务批次") def _parse_account_names(raw_names: str) -> list[str]: """解析前端粘贴的 Excel 账号名,每行一个并去重。""" names: list[str] = [] seen: set[str] = set() for value in ( (raw_names or "").replace("\r\n", "\n").replace("\r", "\n").split("\n") ): name = value.strip() if name and name not in seen: names.append(name) seen.add(name) return names def _apply_task_account_filters( query, *, search: str = "", tag: str = "", account_names: str = "", ids: str = "", ck_status: str = "", ): """按工作台导入弹窗的搜索、标签、多行账号名与 CK/冷却状态筛选任务账号。""" id_list = [ int(item) for item in dict.fromkeys( value.strip() for value in ids.split(",") if value.strip().isdigit() ) ] if id_list: query = query.filter(Account.id.in_(id_list)) tag_text = (tag or "").strip() if tag_text: query = query.filter(Account.tag == tag_text) selected_names = _parse_account_names(account_names) if selected_names: query = query.filter(Account.username.in_(selected_names)) ck_filter = (ck_status or "").strip() if ck_filter == "valid": query = query.filter( Account.cookie.isnot(None), Account.cookie != "", Account.ck_check_status == "valid", ) elif ck_filter == "invalid": query = query.filter( or_(Account.ck_check_status == "invalid", Account.status == "invalid") ) elif ck_filter == "no_cookie": query = query.filter(or_(Account.cookie.is_(None), Account.cookie == "")) elif ck_filter == "unknown": query = query.filter( Account.cookie.isnot(None), Account.cookie != "", or_(Account.status.is_(None), Account.status != "invalid"), or_( Account.ck_check_status.is_(None), Account.ck_check_status.notin_(("valid", "invalid")), ), ) elif ck_filter == "cooldown_ready": now = datetime.now(UTC) query = query.filter( Account.role_bind_status == BIND_BOUND, or_( Account.role_change_available_at <= now, and_( Account.role_change_available_at.is_(None), or_( Account.change_role_wait_time.is_(None), Account.change_role_wait_time <= 0, ), ), ), ) elif ck_filter == "cooldown_waiting": now = datetime.now(UTC) query = query.filter( Account.role_bind_status == BIND_BOUND, or_( Account.role_change_available_at > now, and_( Account.role_change_available_at.is_(None), Account.change_role_wait_time > 0, ), ), ) search_text = (search or "").strip() if search_text: pattern = f"%{search_text}%" query = query.filter( or_( Account.username.ilike(pattern), Account.uid.ilike(pattern), Account.nickname.ilike(pattern), Account.tag.ilike(pattern), Account.game_name.ilike(pattern), Account.esports_game_name.ilike(pattern), Account.xpd_game_name.ilike(pattern), ) ) return query, selected_names, id_list def _order_task_accounts( query, selected_names: list[str], selected_ids: list[int] | None = None, ): """自定义账号名按粘贴顺序排序,未指定时保持最新账号优先。""" if selected_names: input_order = case( {name: index for index, name in enumerate(selected_names)}, value=Account.username, else_=len(selected_names), ) return query.order_by(input_order, Account.id.desc()) if selected_ids: input_order = case( {account_id: index for index, account_id in enumerate(selected_ids)}, value=Account.id, else_=len(selected_ids), ) return query.order_by(input_order, Account.id.desc()) return query.order_by(Account.id.desc()) def _in_flight_login_account_ids(db: Session, account_ids: list[int]) -> set[int]: if not account_ids: return set() wanted = {int(aid) for aid in account_ids} active_task_ids = { int(aid) for (aid,) in db.query(LoginTask.account_id) .filter( LoginTask.account_id.in_(account_ids), or_( LoginTask.attempt_status.in_(LOGIN_ATTEMPT_IN_FLIGHT_STATUSES), LoginTask.status.in_(LOGIN_ATTEMPT_IN_FLIGHT_STATUSES), ), ) .all() } active_attempt_ids = { int(aid) for (aid,) in db.query(LoginAttempt.account_id) .filter( LoginAttempt.account_id.in_(account_ids), LoginAttempt.status.in_(("pending", "running")), ) .all() } active_job_ids: set[int] = set() job_rows = ( db.query(ExecutionJob.payload_json) .filter( ExecutionJob.job_type.in_((JOB_LOGIN_BATCH, JOB_RELOGIN_BATCH)), ExecutionJob.status.in_((STATUS_QUEUED, STATUS_RUNNING)), ) .all() ) for (payload,) in job_rows: if not isinstance(payload, dict): continue for raw_id in payload.get("account_ids") or []: try: aid = int(raw_id) except (TypeError, ValueError): continue if aid in wanted: active_job_ids.add(aid) return active_task_ids | active_attempt_ids | active_job_ids def _account_out( account: Account, *, in_flight_login_ids: set[int] | None = None ) -> DouyuTaskAccountOut: elite_cooldown = account.role_bind_status == BIND_BOUND esports_cooldown = account.esports_bind_status == BIND_BOUND return DouyuTaskAccountOut( id=account.id, username=account.username, uid=account.uid or "", nickname=account.nickname or "", tag=account.tag or "", ck_check_status=account.ck_check_status or "", ck_checked_at=account.ck_checked_at, points=account.points, game_name=account.game_name or "", game_channel=account.game_channel or "", gold_balance=account.gold_balance, exchange_balance=account.exchange_balance, # pydantic 模型字段含 datetime/bool,字典展开只能按 Any 传入。 **cast(dict[str, Any], bind_payload(account)), # 未确认绑定时接口倒计时是占位值;API 出口也做一次归一,兼容历史行。 change_role_wait_time=account.change_role_wait_time if elite_cooldown else 0, elite_opened=account.elite_opened, elite_expire_time=account.elite_expire_time, esports_points=account.esports_points, esports_game_name=account.esports_game_name or "", esports_game_channel=account.esports_game_channel or "", esports_change_role_wait_time=( account.esports_change_role_wait_time if esports_cooldown else 0 ), esports_can_change_time=account.esports_can_change_time if esports_cooldown else None, xpd_game_name=account.xpd_game_name or "", xpd_openid=account.xpd_openid or "", xpd_role_id=account.xpd_role_id or "", xpd_plat_id=account.xpd_plat_id, xpd_area_id=account.xpd_area_id, xpd_balance=account.xpd_balance, xpd_fragments=account.xpd_fragments, assigned_to=account.assigned_to, assigned_username=account.assigned_user.username if account.assigned_user else None, account_status=account.status or "", has_cookie=bool(account.cookie), points_expire_at=account.points_expire_at, role_change_available_at=account.role_change_available_at, role_change_official_at=account.role_change_official_at, overview_queried_at=account.overview_queried_at, updated_at=account.updated_at, in_flight_login=( int(account.id) in in_flight_login_ids if in_flight_login_ids is not None else False ), ) def _task_out(task: DouyuTask, *, include_detail: bool = False) -> DouyuTaskOut: return DouyuTaskOut(**douyu_task_payload(task, include_detail=include_detail)) def _config_out(config: DouyuConfig) -> DouyuConfigOut: text = lambda field: str(douyu_config_value(field, getattr(config, field))) number = lambda field: int(douyu_config_value(field, getattr(config, field))) boolean = lambda field: bool(douyu_config_value(field, getattr(config, field))) return DouyuConfigOut( manual_id=text("manual_id"), rid=text("rid"), bind_act_alias=text("bind_act_alias"), confirm_act_alias=text("confirm_act_alias"), legacy_act_alias=text("legacy_act_alias"), room_id=text("room_id"), elite_amount=number("elite_amount"), esports_manual_id=text("esports_manual_id"), esports_act_alias=text("esports_act_alias"), esports_amount=number("esports_amount"), esports_chicken_gift_id=text("esports_chicken_gift_id"), esports_chicken_skin_id=text("esports_chicken_skin_id"), esports_firework_gift_id=text("esports_firework_gift_id"), esports_firework_skin_id=text("esports_firework_skin_id"), peace_enabled=boolean("peace_enabled"), xpd_act_alias=text("xpd_act_alias"), xpd_act_id=text("xpd_act_id"), xpd_rid=text("xpd_rid"), gold_pay_type=number("gold_pay_type"), gold_recharge_channel=text("gold_recharge_channel"), gold_api_product_id=text("gold_api_product_id"), gold_api_account_template_name=text("gold_api_account_template_name"), recharge_duplicate_confirm_minutes=number("recharge_duplicate_confirm_minutes"), gold_api_max_amount=number("gold_api_max_amount"), gift_id=text("gift_id"), skin_id=text("skin_id"), updated_at=config.updated_at, ) def _supply_target_out( db: Session, target: AccountSupplyTarget, *, inventory: SupplyInventory | None = None, ) -> DouyuSupplyTargetOut: resolved = inventory or evaluate_supply_target(db, target) return DouyuSupplyTargetOut( id=int(target.id), target_id=int(target.id), platform=target.platform, scope=target.scope, commodity_id=target.commodity_id, value_class=target.value_class, target_covered=resolved.target_covered, target_available=resolved.target_available, target_allocatable=resolved.target_allocatable, safety_buffer=resolved.safety_buffer, enabled=bool(target.enabled), covered=resolved.covered, available=resolved.available, allocatable=resolved.allocatable, covered_shortage=resolved.covered_shortage, available_shortage=resolved.available_shortage, allocatable_shortage=resolved.allocatable_shortage, needs_replenishment=resolved.needs_replenishment, updated_by=target.updated_by, updated_at=target.updated_at, ) @router.get("/task-types") def task_types(current: User = Depends(require_permission("douyu:task"))): """返回斗鱼任务类型。""" return SUPPORTED_DOUYU_TASK_TYPES @router.get("/account-platform-status") def get_account_platform_status( include_trends: bool = Query(True), include_supply: bool = Query(True), include_diagnostics: bool = Query(True), db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """账号同步、CK 周期、商品覆盖和供给缺口的统一观测快照。""" return account_platform_status( db, include_trends=include_trends, include_supply=include_supply, include_diagnostics=include_diagnostics, ) @router.get("/account-platform-trends") def get_account_platform_trends( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """延迟加载账号平台 7 天趋势,避免阻塞账号检测首屏。""" return account_platform_trends(db) @router.get("/account-platform-supply") def get_account_platform_supply( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """延迟加载账号供给库存,避免阻塞运行总览首屏。""" return account_supply_snapshot(db) @router.put( "/account-protection-targets/{group_key}", response_model=DouyuAccountProtectionTargetOut, ) def update_account_protection_target( group_key: str, req: DouyuAccountProtectionTargetUpdate, db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:config")), ): """更新履约保护组的 CK 目标与巡检/重登策略。""" ensure_jobs(db) before_rows = evaluate_protection_targets(db) before = next( (row for row in before_rows if row["group_key"] == group_key), None, ) try: job, groups = update_protection_group( db, group_key=group_key, enabled=req.enabled, target_count=req.target_count, probe_interval_minutes=req.probe_interval_minutes, auto_relogin=req.auto_relogin, ) except KeyError: raise HTTPException(status_code=404, detail="履约保护目标不存在") from None except LookupError as exc: raise HTTPException(status_code=409, detail=str(exc)) from None after_config = job.config record_audit( db, current, action="douyu:account-protection-target:update", target=f"automation_job:{job.key}:{group_key}", detail={ "before": before, "after": groups[group_key], }, ) db.commit() rows = evaluate_protection_targets(db, job_config=after_config) return next(row for row in rows if row["group_key"] == group_key) @router.get("/accounts") def list_task_accounts( search: str = Query(""), tag: str = Query(""), ids: str = Query(""), account_names: str = Query(""), ck_status: str = "", workbench_scope: str = "", workbench_state: str = "", include_all: bool = False, page: int | None = Query(None, ge=1), page_size: int = Query(50, ge=1, le=200), db: Session = Depends(get_db), current: User = Depends(get_current_user), ): """查看斗鱼账号。默认只返回持有 Cookie 的可执行账号;include_all=true 时返回全部可见账号(供查询工作台使用)。 `workbench_scope` 传入时会回填该工作台的数据来源(导入未查询 / 已查询 / 重登待重查), `workbench_state` 可按数据来源筛选(跨页生效)。 """ query, selected_names, selected_ids = _apply_task_account_filters( _visible_task_accounts_query(db, current, include_all=include_all), search=search, tag=tag, account_names=account_names, ids=ids, ck_status=ck_status, ) scope = (workbench_scope or "").strip() if scope: member_query = select(DouyuWorkbenchAccount.account_id).where( DouyuWorkbenchAccount.user_id == current.id, DouyuWorkbenchAccount.handbook_scope == scope, ) state = (workbench_state or "").strip() if state: if state not in DATA_STATES: raise HTTPException(status_code=400, detail="无效的数据状态筛选") member_query = member_query.where(DouyuWorkbenchAccount.data_state == state) query = query.filter(Account.id.in_(member_query)) total = None if page is not None: total = query.order_by(None).count() query = _order_task_accounts(query, selected_names, selected_ids) if page is not None: query = query.offset((page - 1) * page_size).limit(page_size) else: query = query.limit(500) rows = query.all() in_flight_ids = ( _in_flight_login_account_ids(db, [int(account.id) for account in rows]) if include_all else None ) state_rows = ( workbench_state_map( db, user_id=int(current.id), account_ids=[int(account.id) for account in rows], handbook_scope=scope, ) if scope else {} ) result = [] for account in rows: item = _account_out(account, in_flight_login_ids=in_flight_ids) state_row = state_rows.get(int(account.id)) if state_row is not None: item.workbench_data_state = state_row.data_state or DATA_STATE_IMPORTED item.workbench_imported_at = state_row.imported_at item.workbench_queried_at = state_row.queried_at item.workbench_relogin_at = state_row.relogin_at result.append(item) if page is not None: return { "items": result, "total": total or 0, "page": page, "page_size": page_size, } return result @router.get("/accounts/ids") def list_task_account_ids( search: str = Query(""), tag: str = Query(""), account_names: str = Query(""), ck_status: str = "", workbench_scope: str = "", workbench_state: str = "", include_all: bool = False, db: Session = Depends(get_db), current: User = Depends(get_current_user), ): """返回当前用户可导入工作台的全部账号 ID,不受列表分页限制。 `workbench_scope` / `workbench_state` 与 `/accounts` 一致:用于「一键查询当前筛选结果」。 """ query, selected_names, selected_ids = _apply_task_account_filters( _visible_task_accounts_query(db, current, include_all=include_all), search=search, tag=tag, account_names=account_names, ck_status=ck_status, ) scope = (workbench_scope or "").strip() if scope: member_query = select(DouyuWorkbenchAccount.account_id).where( DouyuWorkbenchAccount.user_id == current.id, DouyuWorkbenchAccount.handbook_scope == scope, ) state = (workbench_state or "").strip() if state: if state not in DATA_STATES: raise HTTPException(status_code=400, detail="无效的数据状态筛选") member_query = member_query.where(DouyuWorkbenchAccount.data_state == state) query = query.filter(Account.id.in_(member_query)) account_ids = [ account_id for (account_id,) in _order_task_accounts( query.enable_eagerloads(False).with_entities(Account.id), selected_names, selected_ids, ).all() ] return {"account_ids": account_ids, "total": len(account_ids)} @router.post("/accounts/ck-check") def check_task_accounts_ck( ids: str = Query(""), db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """工作台批量检测 CK,只返回有效性,不暴露 Cookie 原文。 复用 CK 操作页的检测逻辑:检测结果会写回 ``accounts.ck_check_status``, 因此导入账号后刷新列表仍能看到「有效 / 失效」。 导入场景会整批传入(包含无 CK / 正在登录的账号),这些账号会被跳过而不是 整体报错 —— 调用方只需要拿到真正能检测的那批结论。 """ from .cookies import _check_cookies requested_ids = [ int(value) for value in dict.fromkeys( item.strip() for item in (ids or "").split(",") if item.strip().isdigit() ) ] if not requested_ids: raise HTTPException(status_code=400, detail="请指定账号ID") checkable_ids = [ int(account_id) for (account_id,) in _visible_task_accounts_query(db, current, include_all=True) .filter(Account.id.in_(requested_ids), cookie_operable_filter()) .enable_eagerloads(False) .with_entities(Account.id) .all() ] skipped = len(requested_ids) - len(checkable_ids) if not checkable_ids: return { "results": [], "success": True, "checked": 0, "skipped": skipped, "message": "所选账号均无可用 CK(待登录或正在登录中)", } result = _check_cookies( ",".join(str(account_id) for account_id in checkable_ids), db, current, detailed=False, ) if isinstance(result, dict): result["skipped"] = skipped result["checked"] = len(result.get("results") or []) return result @router.post("/accounts/relogin-invalid") def relogin_invalid_task_accounts( req: CookieReloginRequest, db: Session = Depends(get_db), current: User = Depends(get_current_user), ): """重登工作台选中的 CK 失效账号(仅超级管理员)。""" if current.role != "super_admin": raise HTTPException(status_code=403, detail="仅超级管理员可重登失效账号") ids = sorted({int(item) for item in req.ids if int(item) > 0}) if not ids: raise HTTPException(status_code=400, detail="请先勾选账号") accounts = ( _visible_task_accounts_query(db, current) .filter( Account.id.in_(ids), Account.ck_check_status == "invalid", ) .all() ) if not accounts: raise HTTPException(status_code=400, detail="选中的账号里没有 CK 失效账号") from .cookies import _start_relogin_accounts return _start_relogin_accounts( accounts, db, current, action="douyu:task:relogin_invalid", ) @router.get("/workbench-accounts") def list_workbench_accounts( handbook_scope: str = Query(..., pattern="^(elite|esports|peace|query)$"), db: Session = Depends(get_db), current: User = Depends(get_current_user), ): """返回当前用户在指定工作台启用的账号,供不同浏览器同步。""" rows = ( db.query(DouyuWorkbenchAccount.account_id) .join(Account, Account.id == DouyuWorkbenchAccount.account_id) .filter( DouyuWorkbenchAccount.user_id == current.id, DouyuWorkbenchAccount.handbook_scope == handbook_scope, ) ) if not _can_view_all(current): rows = rows.filter(Account.assigned_to == current.id) account_ids = [ account_id for (account_id,) in rows.order_by( DouyuWorkbenchAccount.sort_order.asc(), DouyuWorkbenchAccount.id.asc(), ).all() ] configured = ( db.query(DouyuWorkbench.id) .filter( DouyuWorkbench.user_id == current.id, DouyuWorkbench.handbook_scope == handbook_scope, ) .first() is not None ) return {"account_ids": account_ids, "configured": configured} @router.put("/workbench-accounts") def update_workbench_accounts( req: DouyuWorkbenchAccountsUpdate, db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """用当前完整账号集合覆盖一个工作台,作为跨浏览器的同步状态。 保留已有账号行的数据状态(导入/已查询/待重查),只把本次新加入的账号标记为 「导入未查询」,避免每次增删账号都把工作台的查询状态重置。 """ account_ids = list(dict.fromkeys(req.account_ids)) if any(account_id < 1 for account_id in account_ids): raise HTTPException(status_code=400, detail="无效的账号ID") if account_ids: _require_task_account_access(db, current, account_ids) workbench = ( db.query(DouyuWorkbench) .filter( DouyuWorkbench.user_id == current.id, DouyuWorkbench.handbook_scope == req.handbook_scope, ) .first() ) if workbench is None: db.add(DouyuWorkbench(user_id=current.id, handbook_scope=req.handbook_scope)) else: workbench.updated_at = datetime.now(UTC) existing_rows = { int(row.account_id): row for row in db.query(DouyuWorkbenchAccount) .filter( DouyuWorkbenchAccount.user_id == current.id, DouyuWorkbenchAccount.handbook_scope == req.handbook_scope, ) .all() } keep = set(account_ids) removed = [account_id for account_id in existing_rows if account_id not in keep] if removed: db.query(DouyuWorkbenchAccount).filter( DouyuWorkbenchAccount.user_id == current.id, DouyuWorkbenchAccount.handbook_scope == req.handbook_scope, DouyuWorkbenchAccount.account_id.in_(removed), ).delete(synchronize_session=False) now = datetime.now(UTC) imported_account_ids: list[int] = [] for index, account_id in enumerate(account_ids): row = existing_rows.get(account_id) if row is None: db.add( DouyuWorkbenchAccount( user_id=current.id, handbook_scope=req.handbook_scope, account_id=account_id, sort_order=index, data_state=DATA_STATE_IMPORTED, imported_at=now, ) ) imported_account_ids.append(account_id) continue row.sort_order = index if not row.imported_at: row.imported_at = row.created_at or now if not row.data_state: row.data_state = DATA_STATE_IMPORTED db.commit() return { "account_ids": account_ids, "imported_account_ids": imported_account_ids, "success": True, } _SHANGHAI_TZ = ZoneInfo("Asia/Shanghai") _ACCOUNT_STATUS_LABELS = { "active": "正常", "invalid": "CK失效", "imported": "未登录", "manual": "待人工", "disabled": "已停用", } def _manual_budget_summary(db: Session) -> dict[str, Any]: overview = cast(dict[str, Any], get_login_quota_usage_summary(db)) manual_cat = next( ( item for item in overview.get("categories", []) if item.get("category") == CATEGORY_MANUAL ), {}, ) return { "category": CATEGORY_MANUAL, "label": str(manual_cat.get("label") or "人工登录"), "quota_day": overview.get("quota_day", ""), "manual_daily_limit": int(manual_cat.get("limit") or 0), "manual_daily_used": int(manual_cat.get("used") or 0), "manual_daily_remaining": int(manual_cat.get("remaining") or 0), "daily_limit": int(overview.get("daily_limit") or 0), "daily_used": int(overview.get("daily_used") or 0), "daily_remaining": int(overview.get("daily_remaining") or 0), "hourly_limit": int(overview.get("hourly_limit") or 0), "hourly_used": int(overview.get("hourly_used") or 0), "hourly_remaining": int(overview.get("hourly_remaining") or 0), } def _is_invalid_or_missing_ck(account: Account) -> bool: if not account.cookie: return True return account.ck_check_status == "invalid" or account.status == "invalid" def _query_workbench_member_ids(db: Session, current: User) -> list[int]: query = ( db.query(DouyuWorkbenchAccount.account_id) .join(Account, Account.id == DouyuWorkbenchAccount.account_id) .filter( DouyuWorkbenchAccount.user_id == current.id, DouyuWorkbenchAccount.handbook_scope == "query", ) ) if not _can_view_all(current): query = query.filter(Account.assigned_to == current.id) return [ int(aid) for (aid,) in query.order_by( DouyuWorkbenchAccount.sort_order.asc(), DouyuWorkbenchAccount.id.asc(), ).all() ] def _format_shanghai_dt(value: datetime | None) -> str: if value is None: return "" aware = value if value.tzinfo else value.replace(tzinfo=UTC) return aware.astimezone(_SHANGHAI_TZ).strftime("%Y-%m-%d %H:%M:%S") def _format_cooldown_duration(seconds: int) -> str: seconds = max(0, int(seconds)) days, rem = divmod(seconds, 86400) hours, rem = divmod(rem, 3600) minutes, _ = divmod(rem, 60) if days > 0: return f"{days}天{hours}小时{minutes}分" if hours > 0: return f"{hours}小时{minutes}分" return f"{minutes}分" def _csv_safe_cell(value: Any) -> Any: """Prevent spreadsheet apps from evaluating exported text as a formula.""" if isinstance(value, str) and value.lstrip(" \t\r\n").startswith( ("=", "+", "-", "@") ): return f"'{value}" return value def _elite_status_label(account: Account, now_seconds: int) -> str: expire_time = int(account.elite_expire_time or 0) if expire_time > 0 and expire_time <= now_seconds: return "已过期" if account.elite_opened is True: return "已开通" if account.elite_opened is False: return "未开通" return "未查询" def _format_shanghai_unix_seconds(value: int | None) -> str: if value is None or int(value) <= 0: return "" return ( datetime.fromtimestamp(int(value), tz=UTC) .astimezone(_SHANGHAI_TZ) .strftime("%Y-%m-%d %H:%M:%S") ) @router.post("/query-workbench/lookup") def lookup_query_workbench_accounts( req: DouyuQueryWorkbenchLookupRequest, db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """按粘贴的斗鱼账户名列表批量解析账号(包含 CK 失效与未登录账号),并返回未匹配名清单。""" names = _parse_account_names("\n".join(req.account_names)) if not names: raise HTTPException(status_code=400, detail="请先输入至少一个斗鱼账号名") visible_rows = ( _visible_task_accounts_query(db, current, include_all=True) .filter(Account.username.in_(names)) .enable_eagerloads(False) .with_entities(Account.id, Account.username) .all() ) by_name: dict[str, int] = {} for account_id, username in visible_rows: if username and username not in by_name: by_name[str(username)] = int(account_id) matched_ids: list[int] = [] matched_names: list[str] = [] unmatched_names: list[str] = [] for name in names: aid = by_name.get(name) if aid is not None: matched_ids.append(aid) matched_names.append(name) else: unmatched_names.append(name) return { "account_ids": matched_ids, "matched_names": matched_names, "unmatched_names": unmatched_names, "total_input": len(names), } @router.get("/query-workbench/invalid-ids") def list_query_workbench_invalid_ids( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """返回当前用户查询工作台内全部 CK 失效或无 CK 账号 ID,供一键「选中失效 CK」。""" member_ids = _query_workbench_member_ids(db, current) if not member_ids: return { "account_ids": [], "invalid_ck_ids": [], "no_cookie_ids": [], "total_invalid": 0, } rows = ( _visible_task_accounts_query(db, current, include_all=True) .filter(Account.id.in_(member_ids)) .enable_eagerloads(False) .with_entities( Account.id, Account.cookie, Account.ck_check_status, Account.status ) .all() ) row_by_id = {int(r[0]): r for r in rows} invalid_ck_ids: list[int] = [] no_cookie_ids: list[int] = [] account_ids: list[int] = [] for aid in member_ids: row = row_by_id.get(aid) if row is None: continue _id, cookie, ck_check_status, status = row if not cookie: no_cookie_ids.append(aid) account_ids.append(aid) elif ck_check_status == "invalid" or status == "invalid": invalid_ck_ids.append(aid) account_ids.append(aid) return { "account_ids": account_ids, "invalid_ck_ids": invalid_ck_ids, "no_cookie_ids": no_cookie_ids, "total_invalid": len(account_ids), } @router.get("/query-workbench/pending-ids") def list_query_workbench_pending_ids( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """返回工作台内「待查询」账号:导入未查 + 重登成功后待重查(均有可用 CK)。 重登成功后的账号只选这一批回查,不会把整个工作台再跑一遍。 """ member_ids = _query_workbench_member_ids(db, current) if not member_ids: return { "account_ids": [], "imported_ids": [], "stale_ids": [], "total": 0, } return pending_query_ids( db, user_id=int(current.id), visible_account_ids=member_ids, ) @router.get("/query-workbench/manual-budget") def get_query_workbench_manual_budget( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """查询今日「人工登录」预算额度,供重新登录前展示。""" return _manual_budget_summary(db) @router.post("/query-workbench/relogin-invalid") def relogin_query_workbench_invalid_accounts( req: DouyuQueryWorkbenchReloginRequest, db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """从查询工作台发起失效/无 CK 账号重新登录,强制走「人工登录」预算(manual_login)。""" if current.role != "super_admin" and not user_has_permission( current, "login:batch" ): raise HTTPException( status_code=403, detail="无权限发起重登(需超级管理员或 login:batch 权限)" ) target_ids = list(dict.fromkeys(int(item) for item in req.ids if int(item) > 0)) if not target_ids and req.select_all_invalid: target_ids = _query_workbench_member_ids(db, current) if not target_ids: raise HTTPException(status_code=400, detail="请先勾选失效 CK 账号") accounts = ( _visible_task_accounts_query(db, current, include_all=True) .filter(Account.id.in_(target_ids)) .order_by(Account.id.asc()) .all() ) if not accounts: raise HTTPException(status_code=404, detail="没有找到可操作的账号") in_flight_ids = _in_flight_login_account_ids( db, [int(account.id) for account in accounts] ) relogin_ids: list[int] = [] login_ids: list[int] = [] skipped_valid = 0 skipped_in_flight = 0 skipped_missing_credentials = 0 for acc in accounts: if not _is_invalid_or_missing_ck(acc): skipped_valid += 1 continue if int(acc.id) in in_flight_ids: skipped_in_flight += 1 continue if not acc.password or not acc.email: db.add( LoginTask( batch_id="relogin-precheck" if acc.cookie else "login-precheck", account_id=acc.id, status="failed", attempt_status="failed", attempt_message="重新登录失败: 账号缺少密码或邮箱,无法自动登录", attempt_at=datetime.now(UTC), created_by=current.id, ) ) skipped_missing_credentials += 1 continue if acc.cookie: relogin_ids.append(int(acc.id)) else: login_ids.append(int(acc.id)) if not relogin_ids and not login_ids: db.commit() reasons: list[str] = [] if skipped_valid: reasons.append(f"{skipped_valid} 个 CK 仍有效") if skipped_in_flight: reasons.append(f"{skipped_in_flight} 个已在登录队列中") if skipped_missing_credentials: reasons.append(f"{skipped_missing_credentials} 个缺少密码或邮箱") detail = "没有可重新登录的失效账号" if reasons: detail = f"{detail}({';'.join(reasons)})" raise HTTPException(status_code=400, detail=detail) max_login_retries, max_total_time = get_relogin_limits() batch_ids: list[str] = [] for job_type, mode, batch_account_ids in ( (JOB_RELOGIN_BATCH, "relogin", relogin_ids), (JOB_LOGIN_BATCH, "login", login_ids), ): if not batch_account_ids: continue batch_id = uuid.uuid4().hex[:12] enqueue_execution_job( db, job_type=job_type, lane_scope=LANE_AUTH, batch_id=batch_id, payload={ "account_ids": batch_account_ids, "max_login_retries": max_login_retries, "max_total_time": max_total_time, "concurrency": 3, "api_strategy": "wgapi", "mode": mode, "trigger_source": "manual", "category": CATEGORY_MANUAL, }, created_by=int(current.id), priority=15, max_attempts=2, ) batch_ids.append(batch_id) total_queued = len(relogin_ids) + len(login_ids) # 重登(或首次登录)成功后的账号数据已过期:标记为「待重查」, # 这样重登完成后可以只回查这批账号,而不是把整个工作台重跑一遍。 mark_workbench_stale(db, relogin_ids + login_ids, commit=False) record_audit( db, current, action="douyu:query_workbench:relogin_invalid", target=f"人工预算重登 {total_queued} 个失效/无CK账号", detail={ "category": CATEGORY_MANUAL, "relogin_count": len(relogin_ids), "login_count": len(login_ids), "skipped_valid": skipped_valid, "skipped_in_flight": skipped_in_flight, "skipped_missing_credentials": skipped_missing_credentials, "batch_ids": batch_ids, }, ) db.commit() return { "batch_id": batch_ids[0], "batch_ids": batch_ids, "count": total_queued, "relogin_count": len(relogin_ids), "login_count": len(login_ids), "skipped": skipped_valid + skipped_in_flight + skipped_missing_credentials, "skipped_valid": skipped_valid, "skipped_in_flight": skipped_in_flight, "skipped_missing_credentials": skipped_missing_credentials, "category": CATEGORY_MANUAL, "manual_budget": _manual_budget_summary(db), "success": True, } _WORKBENCH_STATE_LABELS = { "imported": "导入未查询", "queried": "已查询", "stale": "重登待重查", } def _workbench_state_label(row: DouyuWorkbenchAccount | None) -> str: if row is None: return "未在工作台" return _WORKBENCH_STATE_LABELS.get(row.data_state or "", "导入未查询") def _workbench_state_note(row: DouyuWorkbenchAccount | None) -> str: """导出附带「什么时候导入 / 什么时候查的」,避免把旧数据当新结果。""" if row is None: return "" if row.data_state == "queried" and row.queried_at is not None: return f"查询于 {_format_shanghai_dt(row.queried_at)}" if row.data_state == "stale" and row.relogin_at is not None: return f"重登于 {_format_shanghai_dt(row.relogin_at)},待重新查询" if row.imported_at is not None: return f"导入于 {_format_shanghai_dt(row.imported_at)},未查询资产" return "未查询资产" @router.post("/query-workbench/export") def export_query_workbench_csv( req: DouyuQueryWorkbenchExportRequest, db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """导出查询工作台账号的鱼翅、积分、换绑时间等结果为 CSV(UTF-8 BOM)。""" requested_ids = list(dict.fromkeys(int(item) for item in req.ids if int(item) > 0)) if not requested_ids: requested_ids = _query_workbench_member_ids(db, current) rows_by_id: dict[int, Account] = {} if requested_ids: visible_accounts = ( _visible_task_accounts_query(db, current, include_all=True) .filter(Account.id.in_(requested_ids)) .all() ) rows_by_id = {int(acc.id): acc for acc in visible_accounts} ordered_accounts = [rows_by_id[aid] for aid in requested_ids if aid in rows_by_id] now = datetime.now(UTC) now_seconds = int(now.timestamp()) output = io.StringIO() writer = csv.writer(output) writer.writerow( [ "账号", "UID", "昵称", "标签", "归属客服", "账号状态", "CK状态", "CK检测时间", "鱼翅余额", "兑换余额", "积分", "积分到期时间", "宝典状态", "宝典到期时间", "绑定状态", "绑定角色", "绑定渠道", "换绑状态", "可换绑时间", "官方换绑时间", "换绑冷却说明", "最近更新时间", "数据来源", "数据更新说明", ] ) state_rows = workbench_state_map( db, user_id=int(current.id), account_ids=[int(acc.id) for acc in ordered_accounts], ) for acc in ordered_accounts: if not acc.cookie: ck_label = "无CK" elif acc.ck_check_status == "valid": ck_label = "有效" elif acc.ck_check_status == "invalid": ck_label = "失效" else: ck_label = "未检测" bind_info = bind_payload(acc) bind_status = str( bind_info.get("role_bind_status") or acc.role_bind_status or "" ) bind_label = str(bind_info.get("role_bind_label") or "") change_status = "未知" cooldown_note = "" available_at = acc.role_change_available_at if bind_status == "unbound": change_status = "未绑定角色" elif bind_status == "pending": change_status = "待确认绑定" elif bind_status == BIND_BOUND: if available_at is not None: aware = ( available_at if available_at.tzinfo else available_at.replace(tzinfo=UTC) ) if aware > now: change_status = "冷却中" cooldown_note = f"剩余 {_format_cooldown_duration(int((aware - now).total_seconds()))}" else: change_status = "可换绑" cooldown_note = "已过冷却" elif (acc.change_role_wait_time or 0) > 0: change_status = "冷却中" cooldown_note = f"剩余 {_format_cooldown_duration(int(acc.change_role_wait_time or 0))}" else: change_status = "可换绑" cooldown_note = "可直接换绑" writer.writerow( [ _csv_safe_cell(value) for value in [ acc.username or "", acc.uid or "", acc.nickname or "", acc.tag or "", acc.assigned_user.username if acc.assigned_user else "未分配", _ACCOUNT_STATUS_LABELS.get(acc.status or "", acc.status or ""), ck_label, _format_shanghai_dt(acc.ck_checked_at), acc.gold_balance if acc.gold_balance is not None else "", acc.exchange_balance if acc.exchange_balance is not None else "", acc.points if acc.points is not None else "", _format_shanghai_dt(acc.points_expire_at), _elite_status_label(acc, now_seconds), _format_shanghai_unix_seconds(acc.elite_expire_time), bind_label, acc.game_name or "", acc.game_channel or "", change_status, _format_shanghai_dt(acc.role_change_available_at), _format_shanghai_dt(acc.role_change_official_at), cooldown_note, _format_shanghai_dt(acc.updated_at or acc.overview_queried_at), _workbench_state_label(state_rows.get(int(acc.id))), _workbench_state_note(state_rows.get(int(acc.id))), ] ] ) filename = f"douyu_query_workbench_{datetime.now(_SHANGHAI_TZ).strftime('%Y%m%d_%H%M%S')}.csv" csv_content = "\ufeff" + output.getvalue() return Response( content=csv_content, media_type="text/csv; charset=utf-8", headers={ "Content-Disposition": f'attachment; filename="{filename}"', }, ) @router.get("/config", response_model=DouyuConfigOut) def get_config( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:config")), ): """获取斗鱼活动配置。""" return _config_out(ensure_douyu_config(db)) @router.get("/recharge-channel") def get_recharge_channel( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """返回当前鱼翅充值渠道,不暴露供应商商品等配置细节。""" config = ensure_douyu_config(db) return { "gold_recharge_channel": douyu_config_value( "gold_recharge_channel", config.gold_recharge_channel, ), } @router.put("/config", response_model=DouyuConfigOut) def update_config( req: DouyuConfigUpdate, db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:config")), ): """更新斗鱼活动配置。""" config = ensure_douyu_config(db) changed_fields = [] for field in DOUYU_CONFIG_FIELDS: value = getattr(req, field, None) if value is None: continue setattr(config, field, value.strip() if isinstance(value, str) else value) changed_fields.append(field) apply_douyu_config_defaults(config) config.updated_at = datetime.now(UTC) recharge_fields = [field for field in changed_fields if field.startswith("gold_")] if recharge_fields: record_audit( db, current, action="recharge:douyu:config", target="douyu_config", detail={"changed_fields": recharge_fields}, ) db.commit() db.refresh(config) return _config_out(config) @router.get("/supply-targets", response_model=list[DouyuSupplyTargetOut]) def list_supply_targets( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:config")), ): """返回账号供给目标、当前库存和缺口。""" rows = ( db.query(AccountSupplyTarget) .order_by( AccountSupplyTarget.enabled.desc(), AccountSupplyTarget.scope.asc(), AccountSupplyTarget.value_class.asc(), AccountSupplyTarget.commodity_id.asc(), AccountSupplyTarget.id.asc(), ) .all() ) enabled_inventories = { item.target_id: item for item in load_supply_snapshot_inventories(db) } return [ _supply_target_out( db, row, inventory=enabled_inventories.get(int(row.id)), ) for row in rows ] @router.get( "/supply-targets/config", response_model=list[DouyuSupplyTargetConfigOut], ) def list_supply_target_configs( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:config")), ): """只返回供给目标配置,库存由 account-platform-status 统一提供。""" rows = ( db.query(AccountSupplyTarget) .order_by( AccountSupplyTarget.enabled.desc(), AccountSupplyTarget.scope.asc(), AccountSupplyTarget.value_class.asc(), AccountSupplyTarget.commodity_id.asc(), AccountSupplyTarget.id.asc(), ) .all() ) return [ DouyuSupplyTargetConfigOut( id=int(row.id), target_id=int(row.id), platform=row.platform, scope=row.scope, commodity_id=row.commodity_id, value_class=row.value_class, target_covered=int(row.target_covered or 0), target_available=int(row.target_available or 0), target_allocatable=int(row.target_allocatable or 0), safety_buffer=int(row.safety_buffer or 0), enabled=bool(row.enabled), updated_by=row.updated_by, updated_at=row.updated_at, ) for row in rows ] @router.post("/supply-targets", response_model=DouyuSupplyTargetOut) def create_supply_target( req: DouyuSupplyTargetUpsert, db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:config")), ): """新增或覆盖一条账号供给目标。""" target = upsert_supply_target( db, platform=req.platform, scope=req.scope, commodity_id=req.commodity_id.strip(), value_class=req.value_class, target_covered=req.target_covered, target_available=req.target_available, target_allocatable=req.target_allocatable, safety_buffer=req.safety_buffer, enabled=req.enabled, updated_by=current.id, ) record_audit( db, current, action="douyu:supply-target:upsert", target=f"account_supply_target:{target.id}", detail={ "scope": target.scope, "commodity_id": target.commodity_id, "value_class": target.value_class, "target_covered": target.target_covered, "target_available": target.target_available, "target_allocatable": target.target_allocatable, "safety_buffer": target.safety_buffer, "enabled": target.enabled, }, ) db.commit() return _supply_target_out(db, target) @router.put("/supply-targets/{target_id}", response_model=DouyuSupplyTargetOut) def edit_supply_target( target_id: int, req: DouyuSupplyTargetUpdate, db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:config")), ): """修改供给目标数量或启停状态。""" target = db.get(AccountSupplyTarget, target_id) if target is None: raise HTTPException(status_code=404, detail="供给目标不存在") target = update_supply_target( db, target, target_covered=req.target_covered, target_available=req.target_available, target_allocatable=req.target_allocatable, safety_buffer=req.safety_buffer, enabled=req.enabled, updated_by=current.id, ) record_audit( db, current, action="douyu:supply-target:update", target=f"account_supply_target:{target.id}", detail={ "target_covered": target.target_covered, "target_available": target.target_available, "target_allocatable": target.target_allocatable, "safety_buffer": target.safety_buffer, "enabled": target.enabled, }, ) db.commit() return _supply_target_out(db, target) @router.get("/goods", response_model=list[DouyuGoodsOut]) def list_goods( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """查看已缓存的斗鱼商品快照。""" rows = db.query(DouyuGoodsSnapshot).order_by(DouyuGoodsSnapshot.id.asc()).all() return rows @router.get("/goods/live", response_model=list[DouyuGoodsOut]) def list_live_goods( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """实时读取精英宝典活动商品,不依赖账号或本地刷新任务。""" del current config = ensure_douyu_config(db) client = activity_client() try: goods = query_activity_goods( client, manual_id=str(douyu_config_value("manual_id", config.manual_id)), rid=str(douyu_config_value("rid", config.rid)), ) except DouyuActivityError as exc: raise HTTPException(status_code=502, detail=f"活动商品加载失败:{exc}") from exc finally: close = getattr(client, "close", None) if callable(close): close() now = datetime.now(UTC) return [ DouyuGoodsOut( id=-(index + 1), commodity_id=str(item.get("commodity_id") or ""), name=str(item.get("name") or ""), score=item.get("score"), status=str(item.get("status") or ""), raw=item.get("raw") if isinstance(item.get("raw"), dict) else None, updated_at=now, ) for index, item in enumerate(serialize_goods(raw) for raw in goods) ] @router.get("/esports-goods", response_model=list[DouyuGoodsOut]) def list_esports_goods( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """查看已缓存的电竞手册皮肤商城商品。""" rows = ( db.query(DouyuEsportsGoodsSnapshot) .order_by(DouyuEsportsGoodsSnapshot.id.asc()) .all() ) return rows @router.get("/xpd-goods", response_model=list[DouyuXpdGoodsOut]) def list_xpd_goods( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """查看已缓存的和平小店商品。""" rows = ( db.query(DouyuXpdGoodsSnapshot).order_by(DouyuXpdGoodsSnapshot.id.asc()).all() ) return rows def _api_recharge_duplicate_guard( db: Session, *, req: DouyuTaskBatchRequest, current: User, config: DouyuConfig, account_ids: list[int], amount: int, ) -> dict[str, Any] | None: """API 直充二次确认:令牌一次性消费,任务与令牌在同一事务落库。""" normalized_ids = sorted({int(account_id) for account_id in account_ids}) now = datetime.now(UTC) if req.recharge_confirmation_token: confirmation = ( db.query(DouyuRechargeConfirmation) .filter( DouyuRechargeConfirmation.token == req.recharge_confirmation_token, ) .with_for_update() .first() ) stored_ids = ( sorted( { int(account_id) for account_id in (confirmation.account_ids_json or []) } ) if confirmation else [] ) if ( confirmation is None or confirmation.user_id != current.id or confirmation.used_at is not None or confirmation.expires_at <= now or confirmation.amount != amount or stored_ids != normalized_ids ): raise HTTPException( status_code=409, detail="充值确认已失效,请重新发起充值", ) confirmation.used_at = now return None window_minutes = max( 0, int( douyu_config_value( "recharge_duplicate_confirm_minutes", config.recharge_duplicate_confirm_minutes, ) or 0 ), ) if window_minutes <= 0: return None cutoff = now - timedelta(minutes=window_minutes) previous = ( db.query(DouyuTask) .filter( DouyuTask.account_id.in_(normalized_ids), DouyuTask.task_type == "create_gold_qr", DouyuTask.recharge_channel == "supplier_api", DouyuTask.recharge_amount == amount, DouyuTask.recharge_requested_at.isnot(None), DouyuTask.recharge_requested_at >= cutoff, DouyuTask.status.notin_(DOUYU_ACTIVE_TASK_STATUSES), ) .order_by(DouyuTask.id.desc()) .all() ) if not previous: return None duplicate_account_ids = {int(task.account_id) for task in previous} account_rows = ( db.query(Account) .filter(Account.id.in_(duplicate_account_ids)) .order_by(Account.id.asc()) .all() ) token = secrets.token_urlsafe(32) db.add( DouyuRechargeConfirmation( token=token, user_id=int(current.id), amount=amount, account_ids_json=normalized_ids, expires_at=now + timedelta(minutes=5), ) ) db.commit() names = [ row.nickname or row.username or row.uid or f"#{row.id}" for row in account_rows ] return { "batch_id": "", "count": 0, "requires_confirmation": True, "confirmation_token": token, "window_minutes": window_minutes, "amount": amount, "account_names": names, "message": ( f"所选账号在最近 {window_minutes} 分钟内已请求过相同金额的 API 充值," "请确认是否继续" ), "success": False, } def _prepare_task_batch( req: DouyuTaskBatchRequest, db: Session, current: User, ) -> dict[str, Any]: """在线程池中完成全部同步 DB 工作,避免阻塞 Uvicorn 事件循环。""" if not req.account_ids: raise HTTPException(status_code=400, detail="请选择斗鱼账号") _require_task_account_access( db, current, req.account_ids, platform_task_id=req.platform_task_id, ) platform_task = ( db.query(PlatformFulfillmentTask) .filter(PlatformFulfillmentTask.id == int(req.platform_task_id)) .first() if req.platform_task_id else None ) if platform_task is not None and req.task_type == "exchange_goods": eligibility = platform_fulfillment_service.refresh_exchange_eligibility( db, task_id=int(platform_task.id), current=current, ) refreshed_task = eligibility["task"] if refreshed_task.get("exchangeStatus") != "eligible": raise HTTPException( status_code=409, detail=refreshed_task.get("lastError") or "当前账号不满足兑换条件", ) platform_task = db.get(PlatformFulfillmentTask, int(platform_task.id)) active_batches = int( db.query(func.count(ExecutionJob.id)) .filter( ExecutionJob.job_type == JOB_DOUYU_BATCH, ExecutionJob.lane_scope == LANE_FULFILLMENT, ExecutionJob.status.in_((STATUS_QUEUED, STATUS_RUNNING)), ) .scalar() or 0 ) _ensure_active_batch_budget(active_batches) config = ensure_douyu_config(db) recharge_channel = ( str( douyu_config_value( "gold_recharge_channel", config.gold_recharge_channel, ) ).strip() if req.task_type == "create_gold_qr" else "" ) recharge_amount = ( max( 1, int(req.payload.get("amount") or req.payload.get("gold_amount") or 1), ) if req.task_type == "create_gold_qr" else None ) if ( req.reuse_active_payment and len(req.account_ids) == 1 and req.task_type in {"create_elite_qr", "create_esports_qr", "create_gold_qr"} and not ( req.task_type == "create_gold_qr" and recharge_channel == "supplier_api" ) ): reusable = find_reusable_active_payment_task( db, int(req.account_ids[0]), task_type=req.task_type, handbook_scope=req.handbook_scope, recharge_channel=recharge_channel, recharge_amount=recharge_amount, ) if reusable is not None: return { "batch_id": reusable.batch_id, "count": 1, "success": True, "reused": True, "message": "当前已有未过期的支付二维码,已重新打开", } if req.task_type == "create_gold_qr" and recharge_channel == "supplier_api": guard = _api_recharge_duplicate_guard( db, req=req, current=current, config=config, account_ids=req.account_ids, amount=int(recharge_amount or 1), ) if guard is not None: return guard if req.force_occupied: if not user_has_permission(current, "douyu:task:force"): raise HTTPException( status_code=403, detail="仅超级管理员或运营有权限在占用期间强制发放", ) if ( req.handbook_scope != "elite" or req.task_type not in WORKBENCH_GOODS_MUTATION_TYPES or req.platform_task_id is not None ): raise HTTPException( status_code=400, detail="仅精英工作台锁单、支付锁单与兑换商品支持确认角色后强制发放", ) task_payload = dict(req.payload) if req.recharge_confirmation_token: task_payload["recharge_confirmation_used"] = True try: batch_id, count = create_douyu_planned_tasks( db, req.account_ids, req.task_type, req.handbook_scope, current.id, task_payload, platform_task_id=req.platform_task_id, concurrency=req.concurrency, recharge_channel=recharge_channel, recharge_amount=recharge_amount, force_occupied=req.force_occupied, ) except DouyuLeaseConflictError as exc: if ( not req.force_occupied and req.platform_task_id is None and req.handbook_scope == "elite" and req.task_type in WORKBENCH_GOODS_MUTATION_TYPES and user_has_permission(current, "douyu:task:force") ): visible_accounts = visible_douyu_task_accounts(db, req.account_ids) inspections = [ workbench_force_goods_inspection(db, acc) for acc in visible_accounts ] occupied_items = [item for item in inspections if item["occupied"]] blocked = next( (item for item in occupied_items if not item["can_force"]), None, ) if blocked is not None: raise HTTPException(status_code=409, detail=blocked["reason"]) from exc if occupied_items: return { "batch_id": "", "count": 0, "success": False, "requires_force_confirmation": True, "occupied_accounts": occupied_items, "message": ( "所选账号当前由平台履约订单占用,已校验斗鱼号与绑定角色正常," "请核对后确认强制发放" ), } raise HTTPException(status_code=409, detail=str(exc)) from exc except DouyuActivePaymentError as exc: raise HTTPException(status_code=409, detail=str(exc)) from exc except DouyuTaskBackpressureError as exc: raise HTTPException( status_code=429, detail=str(exc), headers={"Retry-After": "5"}, ) from exc except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc if count == 0: raise HTTPException( status_code=400, detail="没有可执行的斗鱼账号,请先登录获取 Cookie" ) if req.force_occupied: commodity_id = str( req.payload.get("commodity_id") or req.payload.get("commodityId") or "" ).strip() snapshot = ( db.query(DouyuGoodsSnapshot) .filter(DouyuGoodsSnapshot.commodity_id == commodity_id) .first() if commodity_id else None ) goods_name = str(snapshot.name or "").strip() if snapshot else "" forced_rows = ( db.query(DouyuTask, Account) .join(Account, Account.id == DouyuTask.account_id) .filter(DouyuTask.batch_id == batch_id) .order_by(DouyuTask.id.asc()) .all() ) forced_pf_details: list[dict[str, Any]] = [] for douyu_task, account in forced_rows: result_data = ( douyu_task.result if isinstance(douyu_task.result, dict) else {} ) raw_payload = result_data.get("payload") payload_meta = raw_payload if isinstance(raw_payload, dict) else {} pf_task_id = payload_meta.get("force_platform_task_id") if not payload_meta.get("force_occupied") or not pf_task_id: continue platform_fulfillment_service.record_workbench_force_exchange( db, task_id=int(pf_task_id), current=current, batch_id=batch_id, douyu_task_id=int(douyu_task.id), task_type=req.task_type, commodity_id=commodity_id, goods_name=goods_name, account_id=int(account.id), account_username=str(account.username or ""), account_role=str(account.game_name or ""), ) forced_pf_details.append( { "douyu_task_id": int(douyu_task.id), "platform_task_id": int(pf_task_id), "account_id": int(account.id), "account_username": str(account.username or ""), "account_role": str(account.game_name or ""), } ) if forced_pf_details: record_audit( db, current, action="douyu:workbench:force_exchange", target=f"douyu_batch:{batch_id}", detail={ "batch_id": batch_id, "task_type": req.task_type, "commodity_id": commodity_id, "goods_name": goods_name, "accounts": forced_pf_details, }, ) db.commit() if req.platform_task_id: douyu_task_ids = [ int(task_id) for (task_id,) in ( db.query(DouyuTask.id) .filter(DouyuTask.batch_id == batch_id) .order_by(DouyuTask.id.asc()) .all() ) ] if platform_task is not None: platform_fulfillment_service.record_douyu_operation_started( db, platform_task, current=current, batch_id=batch_id, task_type=req.task_type, douyu_task_ids=douyu_task_ids, payload=req.payload, ) if req.task_type == "create_gold_qr": payment_method = ( "API 直充支付" if recharge_channel == "supplier_api" else "微信扫码支付" ) recharge_accounts = ( db.query(DouyuTask, Account) .join(Account, Account.id == DouyuTask.account_id) .filter( DouyuTask.batch_id == batch_id, DouyuTask.task_type == "create_gold_qr" ) .order_by(DouyuTask.id.asc()) .limit(100) .all() ) record_audit( db, current, action="recharge:douyu:create", target=f"douyu_batch:{batch_id}", detail={ "batch_id": batch_id, "task_type": req.task_type, "count": count, "platform_task_id": req.platform_task_id, "account_count": len(req.account_ids), "handbook_scope": req.handbook_scope, "recharge_channel": recharge_channel, "recharge_amount": recharge_amount, "recharge_confirmed": bool(req.recharge_confirmation_token), "payment_method": payment_method, # 仅记录充值身份,禁止在审计中写入 Cookie、密码等凭据。 "recharge_accounts": [ { "task_id": task.id, "username": account.username, "douyu_uid": account.uid or "", "douyu_nickname": account.nickname or "", } for task, account in recharge_accounts ], "recharge_accounts_truncated": count > len(recharge_accounts), }, ) db.commit() return {"batch_id": batch_id, "count": count, "success": True} @router.post("/tasks/batch") async def create_task_batch( req: DouyuTaskBatchRequest, db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """创建斗鱼任务记录和持久 execution job。""" async with _batch_create_semaphore(): return await run_in_threadpool( _prepare_task_batch, req, db, current, ) @router.get("/tasks") def list_tasks( batch_id: str | None = None, handbook_scope: str | None = Query(None, pattern="^(elite|esports|peace|query)$"), workbench_only: bool = False, include_detail: bool = Query( False, description="是否返回完整任务结果(默认否,轮询请保持 false)" ), page: int | None = Query(None, ge=1), page_size: int = Query(100, ge=1, le=500), db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """查看斗鱼任务记录,默认只返回最近 100 条。""" total = None offset = (page - 1) * page_size if page is not None else 0 account_scope_query: Select | None = None if workbench_only: if not handbook_scope: raise HTTPException( status_code=400, detail="工作台任务查询必须指定手册类型" ) account_scope_query = select(DouyuWorkbenchAccount.account_id).where( DouyuWorkbenchAccount.user_id == current.id, DouyuWorkbenchAccount.handbook_scope == handbook_scope, ) if _can_view_all(current): tasks = _list_visible_tasks_for_admin( db, batch_id=batch_id, handbook_scope=handbook_scope, account_scope_query=account_scope_query, limit=page_size, offset=offset, ) if page is not None: total = _count_visible_tasks_for_admin( db, batch_id=batch_id, handbook_scope=handbook_scope, account_scope_query=account_scope_query, ) else: if not user_has_permission(current, "account:view_assigned"): raise HTTPException(status_code=403, detail="无权查看斗鱼任务") tasks = _list_visible_tasks_for_support( db, current, batch_id=batch_id, handbook_scope=handbook_scope, account_scope_query=account_scope_query, limit=page_size, offset=offset, ) if page is not None: total = _count_visible_tasks_for_support( db, current, batch_id=batch_id, handbook_scope=handbook_scope, account_scope_query=account_scope_query, ) result = [_task_out(task, include_detail=include_detail) for task in tasks] if page is not None: return { "items": result, "total": total or 0, "page": page, "page_size": page_size, } return result @router.post("/tasks/cleanup-orphans") def cleanup_orphan_tasks( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """手动清理没有内存执行器或持久队列接管的斗鱼任务。""" durable_batch_ids = { str(batch_id) for (batch_id,) in ( db.query(ExecutionJob.batch_id) .filter(ExecutionJob.status.in_((STATUS_QUEUED, STATUS_RUNNING))) .all() ) } cleaned = cleanup_orphan_douyu_tasks( db, active_batch_ids=douyu_batch_registry.active_ids() | durable_batch_ids, statuses=DOUYU_ACTIVE_TASK_STATUSES, message="任务已中断(无执行器接管)", ) return { "message": f"已清理 {cleaned} 个残留任务", "cleaned": cleaned, "success": True, } @router.post( "/tasks/{task_id}/exchange-result-image", response_model=DouyuExchangeResultImageOut, ) def upload_exchange_result_image( task_id: int, file: UploadFile = File(...), db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ) -> DouyuExchangeResultImageOut: """保存兑换结果 PNG,并绑定到对应履约任务供后续查看。""" task = _visible_tasks_query(db, current).filter(DouyuTask.id == task_id).first() if task is None: raise HTTPException(status_code=404, detail="任务不存在") platform_task = ( db.query(PlatformFulfillmentTask) .filter(PlatformFulfillmentTask.id == int(task.platform_task_id)) .with_for_update() .first() if task.platform_task_id else None ) limit = max_upload_size_bytes() data = file.file.read(limit + 1) if len(data) > limit: raise HTTPException( status_code=413, detail=f"文件不能超过 {limit // (1024 * 1024)}MB", ) try: saved = save_exchange_result_image( db, task, data=data, filename=(file.filename or "").strip(), uploader_id=int(current.id), platform_task=platform_task, ) except ExchangeResultImageError as exc: raise HTTPException(status_code=409, detail=str(exc)) from exc except FileUploadError as exc: raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc except StorageUnavailableError as exc: raise HTTPException(status_code=503, detail="文件存储暂时不可用") from exc record_audit( db, current, action="douyu:task:exchange_result_image", target=f"douyu_task:{task.id}", detail={ "platform_task_id": task.platform_task_id, "object_key": saved["objectKey"], }, ) db.commit() return DouyuExchangeResultImageOut( object_key=str(saved["objectKey"]), url=str(saved["url"]), saved_at=cast(datetime, saved["savedAt"]), ) @router.get("/tasks/{task_id}", response_model=DouyuTaskOut) def get_task( task_id: int, db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """获取单条斗鱼任务详情。""" task = _visible_tasks_query(db, current).filter(DouyuTask.id == task_id).first() if not task: raise HTTPException(status_code=404, detail="任务不存在") return _task_out(task, include_detail=True) @router.post("/stop/{batch_id}") def stop_batch( batch_id: str, db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): """停止正在运行的斗鱼批次。""" _require_batch_owner(db, current, batch_id) is_recharge_batch = ( db.query(DouyuTask.id) .filter(DouyuTask.batch_id == batch_id, DouyuTask.task_type == "create_gold_qr") .first() is not None ) job = get_execution_job(db, batch_id=batch_id) if job is not None: if job.status not in TERMINAL_STATUSES: request_execution_cancel(db, batch_id=batch_id) if is_recharge_batch: record_audit( db, current, action="recharge:douyu:stop", target=f"douyu_batch:{batch_id}", detail={"batch_id": batch_id, "mode": "durable_queue"}, ) db.commit() return {"message": "已发送停止信号", "success": True} cleaned = cleanup_orphan_douyu_tasks( db, batch_id=batch_id, include_durable=True, message="批次已结束", ) if cleaned: return { "message": f"批次已结束,已清理 {cleaned} 个残留任务", "success": True, } raise HTTPException(status_code=404, detail="批次已结束") batch = douyu_batch_registry.get(batch_id) if batch: if batch.get("finished"): douyu_batch_registry.pop(batch_id) cleaned = cleanup_orphan_douyu_tasks( db, batch_id=batch_id, include_durable=True, message="批次已结束", ) if cleaned: return { "message": f"批次已结束,已清理 {cleaned} 个残留任务", "success": True, } raise HTTPException(status_code=404, detail="批次已结束") batch["runner"].stop() if is_recharge_batch: record_audit( db, current, action="recharge:douyu:stop", target=f"douyu_batch:{batch_id}", detail={"batch_id": batch_id, "mode": "running"}, ) db.commit() return {"message": "已发送停止信号", "success": True} cleaned = cleanup_orphan_douyu_tasks( db, batch_id=batch_id, include_durable=True, message="任务已停止(批次不存在)", ) if cleaned: if is_recharge_batch: record_audit( db, current, action="recharge:douyu:stop", target=f"douyu_batch:{batch_id}", detail={ "batch_id": batch_id, "mode": "orphan_cleanup", "cleaned": cleaned, }, ) db.commit() return {"message": f"已清理 {cleaned} 个残留任务", "success": True} raise HTTPException(status_code=404, detail="批次不存在或已结束") @router.websocket("/ws/{batch_id}") async def ws_douyu_logs(websocket: WebSocket, batch_id: str): """斗鱼实时日志推送通道。""" user = authenticate_websocket(websocket) if not user: await websocket.close(code=1008, reason="未授权") return if not user_has_permission(user, "douyu:task"): await websocket.close(code=1008, reason="无权限") return db = WorkerSessionLocal() try: _require_batch_owner(db, user, batch_id) except HTTPException: await websocket.close(code=1008, reason="无权访问该任务批次") return finally: db.close() await websocket.accept() batch = douyu_batch_registry.get(batch_id) if not batch: initial_db = WorkerSessionLocal() try: job = get_execution_job(initial_db, batch_id=batch_id) finally: initial_db.close() if job is None: await websocket.send_json( {"level": "error", "message": "批次不存在或已结束"} ) await websocket.close() return last_event_id = 0 idle_seconds = 0 while True: poll_db = WorkerSessionLocal() try: events = execution_events_after( poll_db, batch_id=batch_id, after_id=last_event_id, limit=200, ) job = get_execution_job(poll_db, batch_id=batch_id) finally: poll_db.close() if events: idle_seconds = 0 for event in events: last_event_id = int(event.id) payload = event_payload(event) await websocket.send_json(payload) if payload.get("level") == "result": await asyncio.sleep(0.1) return continue if job is None or job.status in TERMINAL_STATUSES: await websocket.send_json({"level": "result", "message": "批次已结束"}) return await asyncio.sleep(0.5) idle_seconds += 0.5 if idle_seconds >= 30: await websocket.send_json({"level": "heartbeat", "message": ""}) idle_seconds = 0 log_queue: asyncio.Queue = batch["log_queue"] try: while True: try: msg = await asyncio.wait_for(log_queue.get(), timeout=30) await websocket.send_json(msg) if msg.get("level") == "result": await asyncio.sleep(0.1) break except TimeoutError: await websocket.send_json({"level": "heartbeat", "message": ""}) except WebSocketDisconnect: pass finally: latest = douyu_batch_registry.get(batch_id) if latest and latest.get("finished"): douyu_batch_registry.pop(batch_id) def _to_int_or_none(value: object) -> int | None: """回调里的 `buy_num` 可能是字符串/Decimal,安全转 int。""" try: return int(float(str(value))) except (TypeError, ValueError): return None