feat(douyu): 新增斗鱼查询工作台与失效CK人工重登预算支持 (v0.4.26)
This commit is contained in:
+593
-20
@@ -3,10 +3,14 @@
|
||||
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,
|
||||
@@ -15,6 +19,7 @@ from fastapi import (
|
||||
HTTPException,
|
||||
Query,
|
||||
Request,
|
||||
Response,
|
||||
UploadFile,
|
||||
WebSocket,
|
||||
WebSocketDisconnect,
|
||||
@@ -46,6 +51,8 @@ from ..models import (
|
||||
DouyuWorkbenchAccount,
|
||||
DouyuXpdGoodsSnapshot,
|
||||
ExecutionJob,
|
||||
LoginAttempt,
|
||||
LoginTask,
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
)
|
||||
@@ -58,6 +65,9 @@ from ..schemas import (
|
||||
DouyuConfigUpdate,
|
||||
DouyuExchangeResultImageOut,
|
||||
DouyuGoodsOut,
|
||||
DouyuQueryWorkbenchExportRequest,
|
||||
DouyuQueryWorkbenchLookupRequest,
|
||||
DouyuQueryWorkbenchReloginRequest,
|
||||
DouyuSupplyTargetConfigOut,
|
||||
DouyuSupplyTargetOut,
|
||||
DouyuSupplyTargetUpdate,
|
||||
@@ -107,6 +117,7 @@ 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,
|
||||
@@ -123,10 +134,14 @@ from ..services.douyu_service import (
|
||||
)
|
||||
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,
|
||||
@@ -134,6 +149,11 @@ from ..services.execution_jobs import (
|
||||
)
|
||||
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=["斗鱼活动"])
|
||||
@@ -315,18 +335,19 @@ 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):
|
||||
def _visible_task_accounts_query(
|
||||
db: Session, current: User, *, include_all: bool = False
|
||||
):
|
||||
"""返回当前用户可用于斗鱼任务的账号查询。
|
||||
|
||||
只要账号还持有 Cookie 就可见:排队中的普通登录(pending/running)和
|
||||
只要账号还持有 Cookie 就可见;排队中的普通登录(pending/running)和
|
||||
重登失败(relogin_failed)都会保留旧 CK,不能让账号从工作台消失。
|
||||
查询工作台场景(include_all=True)允许展示无 CK / 已失效等全部可见账号。
|
||||
"""
|
||||
cookie_ids = select(Account.id).where(cookie_holding_filter())
|
||||
query = (
|
||||
db.query(Account)
|
||||
.options(joinedload(Account.assigned_user))
|
||||
.filter(Account.id.in_(cookie_ids))
|
||||
)
|
||||
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"):
|
||||
@@ -617,8 +638,9 @@ def _apply_task_account_filters(
|
||||
tag: str = "",
|
||||
account_names: str = "",
|
||||
ids: str = "",
|
||||
ck_status: str = "",
|
||||
):
|
||||
"""按工作台导入弹窗的搜索、标签、多行账号名筛选任务账号。"""
|
||||
"""按工作台导入弹窗的搜索、标签、多行账号名与 CK/冷却状态筛选任务账号。"""
|
||||
id_list = [
|
||||
int(item)
|
||||
for item in dict.fromkeys(
|
||||
@@ -633,6 +655,43 @@ def _apply_task_account_filters(
|
||||
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.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.is_(None),
|
||||
Account.role_change_available_at <= now,
|
||||
),
|
||||
)
|
||||
elif ck_filter == "cooldown_waiting":
|
||||
now = datetime.now(UTC)
|
||||
query = query.filter(
|
||||
Account.role_bind_status == BIND_BOUND,
|
||||
Account.role_change_available_at > now,
|
||||
)
|
||||
search_text = (search or "").strip()
|
||||
if search_text:
|
||||
pattern = f"%{search_text}%"
|
||||
@@ -673,7 +732,56 @@ def _order_task_accounts(
|
||||
return query.order_by(Account.id.desc())
|
||||
|
||||
|
||||
def _account_out(account: Account) -> DouyuTaskAccountOut:
|
||||
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(
|
||||
@@ -714,6 +822,18 @@ def _account_out(account: Account) -> DouyuTaskAccountOut:
|
||||
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
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -881,22 +1001,21 @@ def list_task_accounts(
|
||||
tag: str = Query(""),
|
||||
ids: str = Query(""),
|
||||
account_names: str = Query(""),
|
||||
ck_status: 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)。
|
||||
|
||||
tag 按账号标签精确筛选;ids 为逗号分隔的账号 ID,用于工作台按已导入账号过滤;
|
||||
account_names 为多行斗鱼账户名(每行一个),按粘贴顺序精确匹配;为空时返回全部。
|
||||
"""
|
||||
"""查看斗鱼账号。默认只返回持有 Cookie 的可执行账号;include_all=true 时返回全部可见账号(供查询工作台使用)。"""
|
||||
query, selected_names, selected_ids = _apply_task_account_filters(
|
||||
_visible_task_accounts_query(db, current),
|
||||
_visible_task_accounts_query(db, current, include_all=include_all),
|
||||
search=search,
|
||||
tag=tag,
|
||||
account_names=account_names,
|
||||
ids=ids,
|
||||
ck_status=ck_status,
|
||||
)
|
||||
total = None
|
||||
if page is not None:
|
||||
@@ -906,7 +1025,15 @@ def list_task_accounts(
|
||||
query = query.offset((page - 1) * page_size).limit(page_size)
|
||||
else:
|
||||
query = query.limit(500)
|
||||
result = [_account_out(account) for account in query.all()]
|
||||
rows = query.all()
|
||||
in_flight_ids = (
|
||||
_in_flight_login_account_ids(db, [int(account.id) for account in rows])
|
||||
if include_all
|
||||
else None
|
||||
)
|
||||
result = [
|
||||
_account_out(account, in_flight_login_ids=in_flight_ids) for account in rows
|
||||
]
|
||||
if page is not None:
|
||||
return {
|
||||
"items": result,
|
||||
@@ -922,15 +1049,18 @@ def list_task_account_ids(
|
||||
search: str = Query(""),
|
||||
tag: str = Query(""),
|
||||
account_names: str = Query(""),
|
||||
ck_status: str = "",
|
||||
include_all: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(get_current_user),
|
||||
):
|
||||
"""返回当前用户可导入工作台的全部账号 ID,不受列表分页限制。"""
|
||||
query, selected_names, selected_ids = _apply_task_account_filters(
|
||||
_visible_task_accounts_query(db, current),
|
||||
_visible_task_accounts_query(db, current, include_all=include_all),
|
||||
search=search,
|
||||
tag=tag,
|
||||
account_names=account_names,
|
||||
ck_status=ck_status,
|
||||
)
|
||||
account_ids = [
|
||||
account_id
|
||||
@@ -993,7 +1123,7 @@ def relogin_invalid_task_accounts(
|
||||
|
||||
@router.get("/workbench-accounts")
|
||||
def list_workbench_accounts(
|
||||
handbook_scope: str = Query(..., pattern="^(elite|esports|peace)$"),
|
||||
handbook_scope: str = Query(..., pattern="^(elite|esports|peace|query)$"),
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(get_current_user),
|
||||
):
|
||||
@@ -1070,6 +1200,449 @@ def update_workbench_accounts(
|
||||
return {"account_ids": 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 = 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}分"
|
||||
|
||||
|
||||
@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/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)
|
||||
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,
|
||||
}
|
||||
|
||||
|
||||
@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)
|
||||
output = io.StringIO()
|
||||
writer = csv.writer(output)
|
||||
writer.writerow(
|
||||
[
|
||||
"账号",
|
||||
"UID",
|
||||
"昵称",
|
||||
"标签",
|
||||
"归属客服",
|
||||
"账号状态",
|
||||
"CK状态",
|
||||
"CK检测时间",
|
||||
"鱼翅余额",
|
||||
"兑换余额",
|
||||
"积分",
|
||||
"积分到期时间",
|
||||
"绑定状态",
|
||||
"绑定角色",
|
||||
"绑定渠道",
|
||||
"换绑状态",
|
||||
"可换绑时间",
|
||||
"官方换绑时间",
|
||||
"换绑冷却说明",
|
||||
"最近更新时间",
|
||||
]
|
||||
)
|
||||
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(
|
||||
[
|
||||
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),
|
||||
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),
|
||||
]
|
||||
)
|
||||
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),
|
||||
@@ -1792,7 +2365,7 @@ async def create_task_batch(
|
||||
@router.get("/tasks")
|
||||
def list_tasks(
|
||||
batch_id: str | None = None,
|
||||
handbook_scope: str | None = Query(None, pattern="^(elite|esports|peace)$"),
|
||||
handbook_scope: str | None = Query(None, pattern="^(elite|esports|peace|query)$"),
|
||||
workbench_only: bool = False,
|
||||
include_detail: bool = Query(
|
||||
False, description="是否返回完整任务结果(默认否,轮询请保持 false)"
|
||||
|
||||
+23
-2
@@ -1887,7 +1887,7 @@ class PlatformFulfillmentCollabSyncRequest(BaseModel):
|
||||
class DouyuTaskBatchRequest(BaseModel):
|
||||
account_ids: list[int]
|
||||
task_type: str
|
||||
handbook_scope: str = Field(..., pattern="^(elite|esports|peace)$")
|
||||
handbook_scope: str = Field(..., pattern="^(elite|esports|peace|query)$")
|
||||
concurrency: int = Field(5, ge=1, le=15)
|
||||
payload: dict[str, Any] = Field(default_factory=dict)
|
||||
platform_task_id: int | None = Field(None, gt=0)
|
||||
@@ -1897,10 +1897,23 @@ class DouyuTaskBatchRequest(BaseModel):
|
||||
|
||||
|
||||
class DouyuWorkbenchAccountsUpdate(BaseModel):
|
||||
handbook_scope: str = Field(..., pattern="^(elite|esports|peace)$")
|
||||
handbook_scope: str = Field(..., pattern="^(elite|esports|peace|query)$")
|
||||
account_ids: list[int] = Field(default_factory=list)
|
||||
|
||||
|
||||
class DouyuQueryWorkbenchLookupRequest(BaseModel):
|
||||
account_names: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class DouyuQueryWorkbenchReloginRequest(BaseModel):
|
||||
ids: list[int] = Field(default_factory=list)
|
||||
select_all_invalid: bool = False
|
||||
|
||||
|
||||
class DouyuQueryWorkbenchExportRequest(BaseModel):
|
||||
ids: list[int] = Field(default_factory=list)
|
||||
|
||||
|
||||
class DouyuTaskOut(BaseModel):
|
||||
id: int
|
||||
batch_id: str
|
||||
@@ -2010,6 +2023,14 @@ class DouyuTaskAccountOut(BaseModel):
|
||||
xpd_bind_label: str = ""
|
||||
assigned_to: int | None = None
|
||||
assigned_username: str | None = None
|
||||
account_status: str = ""
|
||||
has_cookie: bool = False
|
||||
points_expire_at: datetime | None = None
|
||||
role_change_available_at: datetime | None = None
|
||||
role_change_official_at: datetime | None = None
|
||||
overview_queried_at: datetime | None = None
|
||||
updated_at: datetime | None = None
|
||||
in_flight_login: bool = False
|
||||
|
||||
|
||||
class DouyuXpdGoodsOut(BaseModel):
|
||||
|
||||
@@ -68,6 +68,7 @@ RETIRED_NOISE_TASK_TYPES: tuple[str, ...] = (
|
||||
#: 只读、看一眼就走,且前端**不**拿它派生账号状态 → 短保留。
|
||||
NOISE_TASK_TYPES: tuple[str, ...] = (
|
||||
*RETIRED_NOISE_TASK_TYPES,
|
||||
"query_assets_and_bind",
|
||||
"query_change_bind_time",
|
||||
"query_gold_balance",
|
||||
"query_xpd_balance",
|
||||
|
||||
@@ -237,6 +237,7 @@ class DouyuBatchRunner(
|
||||
"query_game_name": self._execute_query_game_name,
|
||||
"query_change_bind_time": self._execute_query_change_bind_time,
|
||||
"query_account_overview": self._execute_query_account_overview,
|
||||
"query_assets_and_bind": self._execute_query_assets_and_bind,
|
||||
"query_gold_balance": self._execute_query_gold_balance,
|
||||
"query_exchange_records": self._execute_query_exchange_records,
|
||||
"prefetch_csrf_token": self._execute_prefetch_csrf_token,
|
||||
|
||||
@@ -202,6 +202,11 @@ class OverviewMixin:
|
||||
def _client(self, cookie: str) -> DouyuActivityClient: ...
|
||||
def _mark_task(self, *args: Any, **kwargs: Any) -> None: ...
|
||||
def _push_log(self, level: str, message: str) -> None: ...
|
||||
def _pick_change_wait_bind_info(
|
||||
self, candidates: list[dict], config: dict
|
||||
) -> dict | None: ...
|
||||
def _bind_snapshot(self, bind_info: dict | None) -> dict[str, Any]: ...
|
||||
def _format_wait_time(self, seconds: int | None) -> str: ...
|
||||
|
||||
def _overview_view(self, task: DouyuTask) -> str:
|
||||
result = task.result if isinstance(task.result, dict) else {}
|
||||
@@ -1083,3 +1088,193 @@ class OverviewMixin:
|
||||
|
||||
logger.info(f"[douyu] 一键查询账号 {account.id}: {message}")
|
||||
self._mark_task(db, task, "success", message, overview)
|
||||
|
||||
def _execute_query_assets_and_bind(
|
||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||
):
|
||||
"""轻量一键查询:仅实查鱼翅余额、积分(含到期)与精英绑定/换绑时间。"""
|
||||
queried_at = datetime.now(UTC)
|
||||
client = self._client(cookie)
|
||||
errors: dict[str, str] = {}
|
||||
payload: dict[str, Any] = {
|
||||
"queried_at": queried_at.isoformat(),
|
||||
"gold_balance": account.gold_balance,
|
||||
"exchange_balance": account.exchange_balance,
|
||||
"points": account.points,
|
||||
"points_expire_at": (
|
||||
account.points_expire_at.isoformat()
|
||||
if account.points_expire_at
|
||||
else None
|
||||
),
|
||||
"role_bind_status": account.role_bind_status or "unknown",
|
||||
"game_name": account.game_name or "",
|
||||
"change_role_wait_time": None,
|
||||
"role_change_available_at": None,
|
||||
"role_change_official_at": None,
|
||||
"errors": errors,
|
||||
}
|
||||
|
||||
# 1. 鱼翅余额
|
||||
gold_ok = False
|
||||
try:
|
||||
gold = self._refresh_account_gold_balance(client, account)
|
||||
payload["gold_balance"] = gold.get("gold_balance")
|
||||
payload["exchange_balance"] = gold.get("exchange_balance")
|
||||
record_sync_success(
|
||||
db,
|
||||
account_id=int(account.id),
|
||||
domain=DOMAIN_GOLD,
|
||||
source="douyu_task.query_assets_and_bind",
|
||||
observed_at=queried_at,
|
||||
raw_payload=gold,
|
||||
task_id=task.id,
|
||||
)
|
||||
gold_ok = True
|
||||
except Exception as exc: # noqa: BLE001 外部接口边界需要独立容错
|
||||
errors["gold"] = _err(exc)
|
||||
|
||||
# 2. 积分与到期时间
|
||||
points_ok = False
|
||||
try:
|
||||
ctn = query_csrf(client)
|
||||
points = self._refresh_account_points(client, account, cookie, ctn=ctn)
|
||||
payload["points"] = points.get("points")
|
||||
expire_raw = _ts(_points_expire_at(points))
|
||||
if expire_raw is not None:
|
||||
expire_raw = str(expire_raw)
|
||||
expire_dt = _parse_expire_at(expire_raw)
|
||||
if expire_dt is not None:
|
||||
account.points_expire_at = expire_dt
|
||||
payload["points_expire_at"] = expire_dt.isoformat()
|
||||
record_sync_success(
|
||||
db,
|
||||
account_id=int(account.id),
|
||||
domain=DOMAIN_POINTS,
|
||||
source="douyu_task.query_assets_and_bind",
|
||||
observed_at=queried_at,
|
||||
raw_payload=points.get("points_query")
|
||||
if isinstance(points.get("points_query"), dict)
|
||||
else points,
|
||||
task_id=task.id,
|
||||
)
|
||||
points_ok = True
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors["points"] = _err(exc)
|
||||
|
||||
# 3. 绑定角色与换绑时间(合并本地 7 天锁)
|
||||
bind_ok = False
|
||||
bind_label = ""
|
||||
try:
|
||||
role = resolve_elite_role(client, config)
|
||||
status = str(role.get("status") or "")
|
||||
raw_candidates = role.get("bind_infos") or []
|
||||
if status == ROLE_ERROR:
|
||||
errors["bind"] = ";".join(role.get("errors") or ["查询绑定失败"])[
|
||||
:_ERROR_MAX
|
||||
]
|
||||
else:
|
||||
bind_info = (
|
||||
self._pick_change_wait_bind_info(raw_candidates, config)
|
||||
or (
|
||||
role.get("bind_info")
|
||||
if isinstance(role.get("bind_info"), dict)
|
||||
else None
|
||||
)
|
||||
or (raw_candidates[0] if raw_candidates else {})
|
||||
)
|
||||
snapshot = self._bind_snapshot(bind_info)
|
||||
wait_time = snapshot["change_role_wait_time"]
|
||||
persist_role = {
|
||||
**role,
|
||||
"bind_info": bind_info,
|
||||
"snapshot": snapshot,
|
||||
"role_name": snapshot.get("role_name") or "",
|
||||
"game_channel": snapshot.get("game_channel") or "",
|
||||
"change_role_wait_time": wait_time,
|
||||
"can_change_role": snapshot.get("can_change_role"),
|
||||
"can_change_time": snapshot.get("can_change_time"),
|
||||
}
|
||||
persist_probe_result(
|
||||
db,
|
||||
account,
|
||||
{
|
||||
"probe_id": f"task:{task.id}",
|
||||
"identity": {"uid": account.uid, "username": account.username},
|
||||
"session": {},
|
||||
"elite": {},
|
||||
"eligibility": {},
|
||||
"roles": {"elite": persist_role},
|
||||
"gold": {},
|
||||
"goods": {},
|
||||
"errors": {},
|
||||
},
|
||||
source="douyu_task.query_assets_and_bind",
|
||||
record_event=False,
|
||||
)
|
||||
bind_ok = True
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors["bind"] = _err(exc)
|
||||
|
||||
account.updated_at = datetime.now(UTC)
|
||||
payload["role_bind_status"] = account.role_bind_status or "unknown"
|
||||
payload["game_name"] = account.game_name or ""
|
||||
payload["change_role_wait_time"] = (
|
||||
account.change_role_wait_time if account.role_bind_status == "bound" else 0
|
||||
)
|
||||
payload["role_change_available_at"] = (
|
||||
account.role_change_available_at.isoformat()
|
||||
if account.role_change_available_at
|
||||
else None
|
||||
)
|
||||
payload["role_change_official_at"] = (
|
||||
account.role_change_official_at.isoformat()
|
||||
if account.role_change_official_at
|
||||
else None
|
||||
)
|
||||
|
||||
if bind_ok:
|
||||
if account.role_bind_status == "unbound":
|
||||
bind_label = "未绑定角色"
|
||||
elif account.role_bind_status == "bound":
|
||||
available_at = account.role_change_available_at
|
||||
if available_at is not None:
|
||||
aware = (
|
||||
available_at
|
||||
if available_at.tzinfo
|
||||
else available_at.replace(tzinfo=UTC)
|
||||
)
|
||||
if aware > queried_at:
|
||||
rem_sec = int((aware - queried_at).total_seconds())
|
||||
bind_label = f"换绑冷却 {self._format_wait_time(rem_sec)}"
|
||||
else:
|
||||
bind_label = "可换绑"
|
||||
elif (account.change_role_wait_time or 0) > 0:
|
||||
bind_label = (
|
||||
f"换绑冷却 {self._format_wait_time(account.change_role_wait_time)}"
|
||||
)
|
||||
else:
|
||||
bind_label = "可换绑"
|
||||
elif account.role_bind_status == "pending":
|
||||
bind_label = "待确认绑定"
|
||||
else:
|
||||
bind_label = "绑定未知"
|
||||
|
||||
parts = [
|
||||
f"鱼翅 {payload['gold_balance'] if payload['gold_balance'] is not None else '-'}",
|
||||
f"积分 {payload['points'] if payload['points'] is not None else '-'}",
|
||||
]
|
||||
if bind_label:
|
||||
parts.append(bind_label)
|
||||
elif "bind" in errors:
|
||||
parts.append(f"换绑查询失败: {errors['bind']}")
|
||||
message = " · ".join(parts)
|
||||
|
||||
if not (gold_ok or points_ok or bind_ok):
|
||||
fail_msg = ";".join(f"{k}: {v}" for k, v in errors.items()) or "查询失败"
|
||||
self._mark_task(db, task, "failed", fail_msg, payload)
|
||||
return
|
||||
|
||||
if errors:
|
||||
message = f"{message}(部分异常: {', '.join(errors.keys())})"
|
||||
logger.info(f"[douyu] 查询工作台账号 {account.id}: {message}")
|
||||
self._mark_task(db, task, "success", message, payload)
|
||||
|
||||
@@ -53,6 +53,7 @@ SUPPORTED_DOUYU_TASK_TYPES = {
|
||||
"query_change_bind_time": "一键查询换绑时间",
|
||||
# 跨域聚合查询:鱼翅/积分/精英/电竞/小店/兑换记录/高价值套装是否已拥有
|
||||
"query_account_overview": "一键查询账号信息",
|
||||
"query_assets_and_bind": "一键查询鱼翅/积分/换绑时间",
|
||||
"query_gold_balance": "一键查询鱼翅余额",
|
||||
"query_exchange_records": "一键查询兑换记录",
|
||||
"prefetch_csrf_token": "一键获取兑换 CSRF Token",
|
||||
@@ -69,7 +70,7 @@ SUPPORTED_DOUYU_TASK_TYPES = {
|
||||
|
||||
BINDING_POLL_CLEANUP_GRACE_SECONDS = 120
|
||||
|
||||
DOUYU_HANDBOOK_SCOPES = {"elite", "esports", "peace"}
|
||||
DOUYU_HANDBOOK_SCOPES = {"elite", "esports", "peace", "query"}
|
||||
DOUYU_HANDBOOK_TASK_TYPES = {
|
||||
"elite": {
|
||||
"get_bind_qr",
|
||||
@@ -88,6 +89,7 @@ DOUYU_HANDBOOK_TASK_TYPES = {
|
||||
"query_exchange_records",
|
||||
"prefetch_csrf_token",
|
||||
"query_account_overview",
|
||||
"query_assets_and_bind",
|
||||
},
|
||||
"esports": {
|
||||
"prepare_esports_bind",
|
||||
@@ -117,6 +119,13 @@ DOUYU_HANDBOOK_TASK_TYPES = {
|
||||
"exchange_xpd_goods",
|
||||
"query_account_overview",
|
||||
},
|
||||
"query": {
|
||||
"query_assets_and_bind",
|
||||
"query_gold_balance",
|
||||
"query_points",
|
||||
"query_change_bind_time",
|
||||
"query_account_overview",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -309,6 +309,7 @@ class ExecutionJobWorker:
|
||||
trigger_source=str(
|
||||
payload.get("trigger_source", "manual") or "manual"
|
||||
),
|
||||
category=str(payload.get("category", "") or ""),
|
||||
batch_id=current_batch_id,
|
||||
log_sink=log_sink,
|
||||
)
|
||||
|
||||
@@ -528,7 +528,21 @@ def get_login_quota_usage_summary(
|
||||
quota_day, quota_hour = _bucket(moment)
|
||||
setting = db.query(LoginQuotaSetting).filter(LoginQuotaSetting.id == 1).first()
|
||||
if setting is None:
|
||||
setting = LoginQuotaSetting(id=1)
|
||||
setting = LoginQuotaSetting(
|
||||
id=1,
|
||||
daily_attempt_limit=1500,
|
||||
hourly_attempt_limit=100,
|
||||
per_account_daily_limit=2,
|
||||
onboarding_daily_limit=150,
|
||||
relogin_high_value_daily_limit=300,
|
||||
relogin_ordinary_daily_limit=500,
|
||||
relogin_protected_daily_limit=500,
|
||||
lease_refresh_daily_limit=300,
|
||||
manual_daily_limit=300,
|
||||
login_concurrency=3,
|
||||
failure_pause_ratio=40,
|
||||
enabled=True,
|
||||
)
|
||||
protection = load_protection_snapshot(db)
|
||||
per_account_limit = int(setting.per_account_daily_limit)
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ const AutomationPage = lazy(() => import('./pages/AutomationPage'));
|
||||
const UsersPage = lazy(() => import('./pages/UsersPage'));
|
||||
const CookiePage = lazy(() => import('./pages/CookiePage'));
|
||||
const DouyuWorkbenchPage = lazy(() => import('./pages/DouyuWorkbenchPage'));
|
||||
const DouyuQueryWorkbenchPage = lazy(() => import('./pages/DouyuQueryWorkbenchPage'));
|
||||
const DouyuCollabPage = lazy(() => import('./pages/DouyuCollabPage'));
|
||||
const HuyaAccountsPage = lazy(() => import('./pages/HuyaAccountsPage'));
|
||||
const HuyaAssignmentsPage = lazy(() => import('./pages/HuyaAssignmentsPage'));
|
||||
@@ -96,6 +97,7 @@ function AppContent() {
|
||||
<Route path="douyu" element={<Navigate to="/douyu/workbench" replace />} />
|
||||
<Route path="douyu/tasks" element={<Navigate to="/douyu/workbench" replace />} />
|
||||
<Route path="douyu/workbench" element={lazyRoute(<DouyuWorkbenchPage />)} />
|
||||
<Route path="douyu/query-workbench" element={lazyRoute(<DouyuQueryWorkbenchPage />)} />
|
||||
<Route path="douyu/elite" element={<Navigate to="/douyu/workbench?tab=elite" replace />} />
|
||||
<Route path="douyu/esports" element={<Navigate to="/douyu/workbench?tab=esports" replace />} />
|
||||
<Route path="douyu/peace" element={<Navigate to="/douyu/workbench?tab=peace" replace />} />
|
||||
|
||||
@@ -8,6 +8,10 @@ import type {
|
||||
DouyuConfig,
|
||||
DouyuExchangeResultImage,
|
||||
DouyuGoodsItem,
|
||||
DouyuQueryWorkbenchInvalidIdsResult,
|
||||
DouyuQueryWorkbenchLookupResult,
|
||||
DouyuQueryWorkbenchManualBudget,
|
||||
DouyuQueryWorkbenchReloginResult,
|
||||
DouyuRechargeChannel,
|
||||
DouyuSupplyTarget,
|
||||
DouyuSupplyTargetConfig,
|
||||
@@ -63,11 +67,11 @@ export const douyuApi = {
|
||||
api.post<DouyuSupplyTarget, DouyuSupplyTarget>('/douyu/supply-targets', data),
|
||||
updateSupplyTarget: (targetId: number, data: DouyuSupplyTargetUpdate) =>
|
||||
api.put<DouyuSupplyTarget, DouyuSupplyTarget>(`/douyu/supply-targets/${targetId}`, data),
|
||||
listAccounts: (params?: { search?: string; tag?: string; ids?: string }) =>
|
||||
listAccounts: (params?: { search?: string; tag?: string; ids?: string; include_all?: boolean; ck_status?: string }) =>
|
||||
api.get<DouyuTaskAccountItem[], DouyuTaskAccountItem[]>('/douyu/accounts', { params }),
|
||||
listAccountsPaged: (params: PageParams & { ids?: string; tag?: string }) =>
|
||||
listAccountsPaged: (params: PageParams & { ids?: string; tag?: string; include_all?: boolean; ck_status?: string }) =>
|
||||
api.get<PaginatedResponse<DouyuTaskAccountItem>, PaginatedResponse<DouyuTaskAccountItem>>('/douyu/accounts', { params }),
|
||||
listAccountIds: (params: { search?: string; tag?: string; account_names?: string } = {}) =>
|
||||
listAccountIds: (params: { search?: string; tag?: string; account_names?: string; include_all?: boolean; ck_status?: string } = {}) =>
|
||||
api.get<{ account_ids: number[]; total: number }, { account_ids: number[]; total: number }>('/douyu/accounts/ids', { params }),
|
||||
checkAccountsCk: (ids: number[]) =>
|
||||
api.post<
|
||||
@@ -79,6 +83,26 @@ export const douyuApi = {
|
||||
{ batch_id: string; count: number; skipped: number; success: boolean },
|
||||
{ batch_id: string; count: number; skipped: number; success: boolean }
|
||||
>('/douyu/accounts/relogin-invalid', { ids }),
|
||||
lookupQueryWorkbenchAccounts: (accountNames: string[]) =>
|
||||
api.post<DouyuQueryWorkbenchLookupResult, DouyuQueryWorkbenchLookupResult>(
|
||||
'/douyu/query-workbench/lookup',
|
||||
{ account_names: accountNames },
|
||||
),
|
||||
getQueryWorkbenchInvalidIds: () =>
|
||||
api.get<DouyuQueryWorkbenchInvalidIdsResult, DouyuQueryWorkbenchInvalidIdsResult>(
|
||||
'/douyu/query-workbench/invalid-ids',
|
||||
),
|
||||
getQueryWorkbenchManualBudget: () =>
|
||||
api.get<DouyuQueryWorkbenchManualBudget, DouyuQueryWorkbenchManualBudget>(
|
||||
'/douyu/query-workbench/manual-budget',
|
||||
),
|
||||
reloginQueryWorkbenchInvalid: (ids: number[], selectAllInvalid = false) =>
|
||||
api.post<DouyuQueryWorkbenchReloginResult, DouyuQueryWorkbenchReloginResult>(
|
||||
'/douyu/query-workbench/relogin-invalid',
|
||||
{ ids, select_all_invalid: selectAllInvalid },
|
||||
),
|
||||
exportQueryWorkbenchCsv: (ids: number[]) =>
|
||||
api.post<Blob, Blob>('/douyu/query-workbench/export', { ids }, { responseType: 'blob' }),
|
||||
getConfig: () => api.get<DouyuConfig, DouyuConfig>('/douyu/config'),
|
||||
getRechargeChannel: () => api.get<DouyuRechargeChannel, DouyuRechargeChannel>('/douyu/recharge-channel'),
|
||||
updateConfig: (data: Partial<DouyuConfig>) => api.put<DouyuConfig, DouyuConfig>('/douyu/config', data),
|
||||
@@ -89,7 +113,7 @@ export const douyuApi = {
|
||||
createTasks: (data: DouyuTaskBatchRequest) =>
|
||||
api.post<DouyuTaskBatchResult, DouyuTaskBatchResult>('/douyu/tasks/batch', data),
|
||||
listTasks: (
|
||||
handbookScope: 'elite' | 'esports' | 'peace',
|
||||
handbookScope: 'elite' | 'esports' | 'peace' | 'query',
|
||||
batchId?: string,
|
||||
workbenchOnly = false,
|
||||
pageSize = 100,
|
||||
@@ -102,11 +126,11 @@ export const douyuApi = {
|
||||
page_size: pageSize,
|
||||
},
|
||||
}),
|
||||
listWorkbenchAccounts: (handbookScope: 'elite' | 'esports' | 'peace') =>
|
||||
listWorkbenchAccounts: (handbookScope: 'elite' | 'esports' | 'peace' | 'query') =>
|
||||
api.get<{ account_ids: number[]; configured: boolean }, { account_ids: number[]; configured: boolean }>('/douyu/workbench-accounts', {
|
||||
params: { handbook_scope: handbookScope },
|
||||
}),
|
||||
updateWorkbenchAccounts: (handbookScope: 'elite' | 'esports' | 'peace', accountIds: number[]) =>
|
||||
updateWorkbenchAccounts: (handbookScope: 'elite' | 'esports' | 'peace' | 'query', accountIds: number[]) =>
|
||||
api.put<{ account_ids: number[]; success: boolean }, { account_ids: number[]; success: boolean }>(
|
||||
'/douyu/workbench-accounts', { handbook_scope: handbookScope, account_ids: accountIds },
|
||||
),
|
||||
|
||||
@@ -795,6 +795,14 @@ export interface DouyuTaskAccountItem {
|
||||
xpd_bind_label: string;
|
||||
assigned_to: number | null;
|
||||
assigned_username: string | null;
|
||||
account_status?: string;
|
||||
has_cookie?: boolean;
|
||||
points_expire_at?: string | null;
|
||||
role_change_available_at?: string | null;
|
||||
role_change_official_at?: string | null;
|
||||
overview_queried_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
in_flight_login?: boolean;
|
||||
}
|
||||
|
||||
export interface DouyuSupplyTargetStatus {
|
||||
@@ -1024,7 +1032,7 @@ export interface DouyuRechargeChannel {
|
||||
export interface DouyuTaskBatchRequest {
|
||||
account_ids: number[];
|
||||
task_type: string;
|
||||
handbook_scope: "elite" | "esports" | "peace";
|
||||
handbook_scope: "elite" | "esports" | "peace" | "query";
|
||||
concurrency?: number;
|
||||
payload?: Record<string, unknown>;
|
||||
platform_task_id?: number;
|
||||
@@ -1033,6 +1041,49 @@ export interface DouyuTaskBatchRequest {
|
||||
reuse_active_payment?: boolean;
|
||||
}
|
||||
|
||||
export interface DouyuQueryWorkbenchLookupResult {
|
||||
account_ids: number[];
|
||||
matched_names: string[];
|
||||
unmatched_names: string[];
|
||||
total_input: number;
|
||||
}
|
||||
|
||||
export interface DouyuQueryWorkbenchInvalidIdsResult {
|
||||
account_ids: number[];
|
||||
invalid_ck_ids: number[];
|
||||
no_cookie_ids: number[];
|
||||
total_invalid: number;
|
||||
}
|
||||
|
||||
export interface DouyuQueryWorkbenchManualBudget {
|
||||
category: string;
|
||||
label: string;
|
||||
manual_daily_limit: number;
|
||||
manual_daily_used: number;
|
||||
manual_daily_remaining: number;
|
||||
daily_limit: number;
|
||||
daily_used: number;
|
||||
daily_remaining: number;
|
||||
hourly_limit: number;
|
||||
hourly_used: number;
|
||||
hourly_remaining: number;
|
||||
}
|
||||
|
||||
export interface DouyuQueryWorkbenchReloginResult {
|
||||
batch_id: string;
|
||||
batch_ids: string[];
|
||||
count: number;
|
||||
relogin_count: number;
|
||||
login_count: number;
|
||||
skipped: number;
|
||||
skipped_valid: number;
|
||||
skipped_in_flight: number;
|
||||
skipped_missing_credentials: number;
|
||||
category: string;
|
||||
manual_budget: DouyuQueryWorkbenchManualBudget;
|
||||
success: boolean;
|
||||
}
|
||||
|
||||
export interface DouyuOccupiedForceCandidate {
|
||||
account_id: number;
|
||||
account_name: string;
|
||||
@@ -1067,7 +1118,7 @@ export interface DouyuTaskItem {
|
||||
account_uid: string;
|
||||
account_nickname: string;
|
||||
task_type: string;
|
||||
handbook_scope: "elite" | "esports" | "peace" | "legacy";
|
||||
handbook_scope: "elite" | "esports" | "peace" | "query" | "legacy";
|
||||
status: string;
|
||||
message: string;
|
||||
binding: DouyuBindingView;
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
SunOutlined, MoonOutlined, DesktopOutlined, GiftOutlined, ApartmentOutlined, MobileOutlined, ShoppingCartOutlined,
|
||||
BookOutlined, GlobalOutlined,
|
||||
SafetyCertificateOutlined, FileSearchOutlined, RobotOutlined, FileExcelOutlined, ThunderboltOutlined,
|
||||
ReloadOutlined,
|
||||
ReloadOutlined, SearchOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
||||
import { getUser, clearAuth, type AuthUser } from '../store/auth';
|
||||
@@ -95,6 +95,7 @@ export default function MainLayout({ onLogout }: { onLogout?: () => void }) {
|
||||
}
|
||||
if (can('douyu:task')) {
|
||||
douyuItems.push({ key: '/douyu/workbench', label: '斗鱼总工作台', icon: <DesktopOutlined /> });
|
||||
douyuItems.push({ key: '/douyu/query-workbench', label: '查询工作台', icon: <SearchOutlined /> });
|
||||
}
|
||||
|
||||
// 外部单协作:权限独立,客服没有 douyu:task 也要能进共享台账。
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user