"""斗鱼外部单协作的共享状态、校验与轻量查询。""" from __future__ import annotations from collections.abc import Mapping from datetime import UTC, datetime from typing import Any from loguru import logger from sqlalchemy.orm import Session from core.douyu import DouyuActivityClient from ..models import Account, DouyuConfig, DouyuExternalOrder, User from .account_query_filters import ACTIVE_COLLAB_STATUSES from .douyu_account_probe import activity_client from .douyu_goods_service import serialize_live_goods as _serialize_live_goods STATUS_INCOMPLETE = "incomplete" STATUS_TO_RECHARGE = "to_recharge" STATUS_RECHARGED = "recharged" STATUS_SCRIPTED = "scripted" STATUS_DONE = "done" STATUS_POINTS_ERROR = "points_error" STATUS_ROLE_ERROR = "role_error" STATUS_FAILED = "failed" STATUS_VOID = "void" LEASE_PURPOSE_DOUYU_COLLAB = "douyu_collab" COLLAB_LEASE_STATUSES = ACTIVE_COLLAB_STATUSES ORDER_STATUSES: tuple[str, ...] = ( STATUS_INCOMPLETE, STATUS_TO_RECHARGE, STATUS_RECHARGED, STATUS_SCRIPTED, STATUS_DONE, STATUS_POINTS_ERROR, STATUS_ROLE_ERROR, STATUS_FAILED, STATUS_VOID, ) ORDER_STATUS_LABELS = { STATUS_INCOMPLETE: "待补资料", STATUS_TO_RECHARGE: "待充值", STATUS_RECHARGED: "已充值", STATUS_SCRIPTED: "已上脚本", STATUS_DONE: "抢购成功", STATUS_POINTS_ERROR: "积分异常", STATUS_ROLE_ERROR: "账号角色异常", STATUS_FAILED: "抢购失败", STATUS_VOID: "已作废", } STATUS_FLOW: tuple[str, ...] = ( STATUS_INCOMPLETE, STATUS_TO_RECHARGE, STATUS_RECHARGED, STATUS_SCRIPTED, STATUS_DONE, ) SOURCE_TYPE_PLATFORM_FULFILLMENT = "platform_fulfillment" ACCOUNT_REPLACE_ROLES = frozenset({"super_admin", "operation"}) ACCOUNT_RECOMMEND_DEFAULT_SCAN_LIMIT = 20 PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES = frozenset( { "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", } ) STAGE_INDEX = { STATUS_INCOMPLETE: 0, STATUS_TO_RECHARGE: 1, STATUS_RECHARGED: 2, STATUS_SCRIPTED: 3, STATUS_DONE: 4, } STATUS_TIMESTAMP_FIELDS = { STATUS_RECHARGED: "recharged_at", STATUS_SCRIPTED: "scripted_at", STATUS_DONE: "done_at", } SUCCESS_PURCHASE_FIELDS = frozenset( { "order_no", "account_username", "gift_name", "commodity_id", "required_points", } ) ARCHIVABLE_STATUSES = (STATUS_DONE,) POINTS_GROUP_STATUSES: tuple[str, ...] = ( STATUS_TO_RECHARGE, STATUS_RECHARGED, STATUS_POINTS_ERROR, ) POINTS_THRESHOLD_DEFAULT = 100 POINTS_THRESHOLD_MAX = 1_000_000 ACTIVITY_RECORD_SETTLE_SECONDS = 300 ACTIVITY_RECORD_TIME_SKEW_SECONDS = 60 ACTIVITY_RECORD_FETCH_LIMIT = 100 ACTIVITY_RECORD_MAX_PAGES = 5 ACTIVITY_METRIC_RECORD_LIMIT = 50 MAX_IMAGES = 20 CK_EXPORT_BATCH_MAX = 50 CK_EXPORT_ACTION = "douyu:collab:ck_export" USERNAME_EXPORT_BATCH_MAX = 500 VERDICT_SUCCESS = "success" VERDICT_FAILED = "failed" VERDICT_UNKNOWN = "unknown" CK_VALID = "valid" CK_INVALID = "invalid" CK_UNVERIFIED = "unverified" CK_LABELS = { CK_VALID: "CK 正常", CK_INVALID: "CK 异常", CK_UNVERIFIED: "未检测", } class CollabError(RuntimeError): def __init__(self, detail: str, *, status_code: int = 400, code: str = ""): super().__init__(detail) self.detail = detail self.status_code = status_code self.code = code def _now() -> datetime: return datetime.now(UTC) def _to_int(value: Any) -> int | None: if value is None or value == "": return None try: return int(float(value)) except (TypeError, ValueError): return None def _text(value: Any, *, max_length: int | None = None) -> str: text = str(value or "").strip() return text[:max_length] if max_length else text def _mark_order_succeeded( order: DouyuExternalOrder, when: datetime | None = None, ) -> None: """记录首次成功时间;状态回退不能清掉这条购买锁定依据。""" if order.succeeded_at is None: order.succeeded_at = when or _now() def _missing_for_recharge(order: DouyuExternalOrder) -> list[str]: missing: list[str] = [] if not order.account_id or not _text(order.account_username): missing.append("斗鱼账号") if not order.gift_name: missing.append("礼包") if not order.home_images: missing.append("主页截图") if not order.bind_game_role: missing.append("绑定角色(先校验账号)") return missing def _json_safe(value: Any) -> Any: if isinstance(value, dict): return {str(k): _json_safe(v) for k, v in value.items()} if isinstance(value, list): return [_json_safe(item) for item in value] if isinstance(value, (str, int, float, bool)) or value is None: return value return str(value) def _first_value(data: Mapping[str, Any], *keys: str) -> Any: """取第一个存在且非 None 的字段;0 是合法值,不能用 `or` 兜。""" for key in keys: if key in data and data.get(key) is not None: return data.get(key) return None def normalize_images(value: Any, *, field: str = "home_images") -> list[str]: if value is None: return [] if not isinstance(value, list): raise CollabError(f"{field} 必须是图片 key 数组", code="images_invalid") keys: list[str] = [] for item in value: key = _text(item, max_length=512) if key and key not in keys: keys.append(key) if len(keys) > MAX_IMAGES: raise CollabError(f"最多 {MAX_IMAGES} 张图片", code="images_too_many") return keys def normalize_threshold(value: Any) -> int: number = _to_int(value) if number is None: return POINTS_THRESHOLD_DEFAULT if number < 0: raise CollabError("积分阈值不能小于 0", code="points_threshold_invalid") return min(number, POINTS_THRESHOLD_MAX) def resolve_config(db: Session) -> DouyuConfig: config = db.query(DouyuConfig).order_by(DouyuConfig.id.asc()).first() if config is None: config = DouyuConfig() db.add(config) db.flush() return config def account_by_username(db: Session, username: str) -> Account | None: name = _text(username, max_length=128) if not name: return None return ( db.query(Account) .filter(Account.username == name) .order_by(Account.id.asc()) .first() ) def account_by_id(db: Session, account_id: int | None) -> Account | None: if not account_id: return None return db.query(Account).filter(Account.id == account_id).first() def users_by_id(db: Session, ids: set[int]) -> dict[int, str]: clean = {int(item) for item in ids if item} if not clean: return {} return { int(user_id): str(username) for user_id, username in db.query(User.id, User.username) .filter(User.id.in_(clean)) .all() } def accounts_by_id(db: Session, ids: set[int]) -> dict[int, Account]: clean = {int(item) for item in ids if item} if not clean: return {} return { int(account.id): account for account in db.query(Account).filter(Account.id.in_(clean)).all() } def _client_for_account(account: Account) -> DouyuActivityClient: cookie = str(account.cookie or "").strip() if not cookie: raise CollabError("该账号没有 CK", code="account_no_cookie") return activity_client( cookie, logger_callback=lambda message: logger.debug( "[douyu-collab] account={} {}", account.id, message, ), ) def serialize_live_goods(goods: list[dict[str, Any]]) -> list[dict[str, Any]]: """把 storehome 原始商品映射成前端稳定字段。""" return _serialize_live_goods(goods) def _assert_version(order: DouyuExternalOrder, expected: int | None) -> None: if expected is not None and int(expected) != int(order.version or 0): raise CollabError( "这行已被别人修改,请刷新后再试", status_code=409, code="version_conflict", ) def _assert_mutable(order: DouyuExternalOrder) -> None: if order.archived_at is not None: raise CollabError("已归档的订单不能再编辑", code="order_archived") if order.status == STATUS_VOID: raise CollabError("已作废的订单不能再编辑", code="order_void") def _assert_account_replace_permission(current: User) -> None: """撤号和推荐属于高风险改号操作,只允许超级管理员和运营。""" if current.role not in ACCOUNT_REPLACE_ROLES: raise CollabError( "仅超级管理员和运营可以解除或推荐账号", status_code=403, code="account_replace_forbidden", ) def _assert_account_replaceable(order: DouyuExternalOrder) -> None: _assert_mutable(order) if order.status == STATUS_DONE or order.done_at is not None: raise CollabError( "已完成订单不能更换账号,请先确认是否需要回退状态", code="order_done_immutable", ) def _assert_success_account_change_allowed( current: User, order: DouyuExternalOrder, ) -> None: if order.succeeded_at is not None and current.role != "super_admin": raise CollabError( "订单已有成功记录,购买账号仅允许超级管理员修改", status_code=403, code="purchase_lock_admin_required", )