From fdc01826a38c99c12a57cbb594ee1c78c74356a1 Mon Sep 17 00:00:00 2001 From: yml Date: Mon, 30 Nov 2026 17:11:14 +0800 Subject: [PATCH] =?UTF-8?q?feat(douyu):=20=E6=96=B0=E5=A2=9E=E6=96=97?= =?UTF-8?q?=E9=B1=BC=E6=9F=A5=E8=AF=A2=E5=B7=A5=E4=BD=9C=E5=8F=B0=E4=B8=8E?= =?UTF-8?q?=E5=A4=B1=E6=95=88CK=E4=BA=BA=E5=B7=A5=E9=87=8D=E7=99=BB?= =?UTF-8?q?=E9=A2=84=E7=AE=97=E6=94=AF=E6=8C=81=20(v0.4.26)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/斗鱼/Go版本同步优化清单.md | 6 +- pyproject.toml | 2 +- tests/test_douyu_query_workbench.py | 592 ++++++++ uv.lock | 2 +- web/backend/routers/douyu.py | 613 +++++++- web/backend/schemas.py | 25 +- .../automation/jobs/douyu_tasks_retention.py | 1 + web/backend/services/douyu_runner.py | 1 + web/backend/services/douyu_runner_overview.py | 195 +++ web/backend/services/douyu_service.py | 11 +- web/backend/services/execution_worker.py | 1 + web/backend/services/login_quota_service.py | 16 +- web/frontend/src/App.tsx | 2 + web/frontend/src/api/douyu.ts | 36 +- web/frontend/src/api/types.ts | 55 +- web/frontend/src/layouts/MainLayout.tsx | 3 +- .../src/pages/DouyuQueryWorkbenchPage.tsx | 1337 +++++++++++++++++ 18 files changed, 2863 insertions(+), 37 deletions(-) create mode 100644 tests/test_douyu_query_workbench.py create mode 100644 web/frontend/src/pages/DouyuQueryWorkbenchPage.tsx diff --git a/README.md b/README.md index a115ad7..ed3559c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 直播账号运营后台 -斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.25)。 +斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.26)。 ## 能做什么 diff --git a/docs/斗鱼/Go版本同步优化清单.md b/docs/斗鱼/Go版本同步优化清单.md index 06b6b5a..343ae47 100644 --- a/docs/斗鱼/Go版本同步优化清单.md +++ b/docs/斗鱼/Go版本同步优化清单.md @@ -82,4 +82,8 @@ - Go 前端复用同一套 `web/frontend`,合并 `main` 后需确认以下能力在 Go 网关路由下全部接通并跑过契约测试: 1. `efcbd9a`:斗鱼批量支付弹窗双码大间距扫码样式与补位刷新(纯前端 + 既有用例对齐); 2. `cc78208`:`DouyuCollabPage.tsx`「查看归档 → 释放归档账号回池」弹窗(预览 / 执行两接口需在 Go 路由及网关白名单注册); - 3. 后续补齐:给 `archived-account-release`(及其他长耗时批量操作)增加独立更长请求超时或异步进度条。 + 3. 后续补齐:给 `archived-account-release`(及其他长耗时批量操作)增加独立更长请求超时或异步进度条; + 4. `v0.4.26` **斗鱼查询工作台(`handbook_scope="query"`)**: + - 后端任务与工作台:`query_assets_and_bind`(鱼翅 + 积分 + 换绑冷却合并查询)、`/api/douyu/accounts`(`include_all` / `ck_status`)、`/api/douyu/query-workbench/{lookup,invalid-ids,manual-budget,relogin-invalid,export}`; + - 登录预算透传:`execution_worker` 对 `JOB_LOGIN_BATCH` / `JOB_RELOGIN_BATCH` 透传 `payload.category`(强制人工重登走 `CATEGORY_MANUAL`); + - 前端页面:`DouyuQueryWorkbenchPage.tsx`、路由 `/douyu/query-workbench`。 diff --git a/pyproject.toml b/pyproject.toml index 4481da4..1468898 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "live-hub-py" -version = "0.4.25" +version = "0.4.26" description = "直播账号运营 Web 后台" readme = "README.md" requires-python = ">=3.12,<3.13" diff --git a/tests/test_douyu_query_workbench.py b/tests/test_douyu_query_workbench.py new file mode 100644 index 0000000..a3fb3f3 --- /dev/null +++ b/tests/test_douyu_query_workbench.py @@ -0,0 +1,592 @@ +"""斗鱼「查询工作台」单元与集成测试: + +1. query_assets_and_bind:鱼翅/积分/换绑时间单次聚合查询、部分失败容错、全败判定与 runner 分发; +2. 账号可见性与筛选:include_all=true 包含 CK 失效/无 CK 账号,lookup 返回匹配与未匹配账号,invalid-ids 跨页提取; +3. 失效 CK 人工预算重登:权限校验、有 CK 重登 vs 无 CK 登录拆批、强制 category=CATEGORY_MANUAL、execution_worker 透传; +4. CSV 导出:UTF-8 BOM、表头与冷却字段、保持工作台/传入顺序。 +""" + +from __future__ import annotations + +import csv +import io +from datetime import UTC, datetime, timedelta + +import pytest +from fastapi import HTTPException + +from tests.support.db import get_test_engine, make_test_session +from web.backend.models import ( + Account, + AccountSyncState, + DouyuTask, + DouyuWorkbenchAccount, + ExecutionJob, + LoginTask, + User, +) +from web.backend.routers.douyu import ( + export_query_workbench_csv, + get_query_workbench_manual_budget, + list_query_workbench_invalid_ids, + list_task_accounts, + lookup_query_workbench_accounts, + relogin_query_workbench_invalid_accounts, + update_workbench_accounts, +) +from web.backend.schemas import ( + DouyuQueryWorkbenchExportRequest, + DouyuQueryWorkbenchLookupRequest, + DouyuQueryWorkbenchReloginRequest, + DouyuWorkbenchAccountsUpdate, +) +from web.backend.services import douyu_runner_overview, execution_worker +from web.backend.services.douyu_runner_bind import BindMixin +from web.backend.services.douyu_runner_core import DouyuBatchRunnerCore +from web.backend.services.douyu_runner_overview import OverviewMixin +from web.backend.services.douyu_service import ( + DOUYU_HANDBOOK_SCOPES, + DOUYU_HANDBOOK_TASK_TYPES, + SUPPORTED_DOUYU_TASK_TYPES, + create_douyu_planned_tasks, +) +from web.backend.services.execution_jobs import ( + JOB_LOGIN_BATCH, + JOB_RELOGIN_BATCH, + LANE_AUTH, + claim_execution_jobs, +) +from web.backend.services.login_quota_service import CATEGORY_MANUAL + + +class _QueryFakeClient: + def acf_ccn(self, **_): + return "ctn-123" + + +class _QueryHarness(OverviewMixin, BindMixin, DouyuBatchRunnerCore): + def __init__( + self, *, fail_helpers: set[str] | None = None, wait_seconds: int = 3600 + ): + self.client = _QueryFakeClient() + self.fail_helpers = fail_helpers or set() + self.wait_seconds = wait_seconds + self.marked: dict = {} + + def _client(self, cookie: str): + return self.client + + def _mark_task(self, db, task, status, message, result=None): + self.marked = { + "status": status, + "message": message, + "result": result, + } + + def _push_log(self, *a, **k): + pass + + def _refresh_account_gold_balance(self, client, account): + if "gold" in self.fail_helpers: + raise RuntimeError("模拟鱼翅接口超时") + account.gold_balance = 66 + account.exchange_balance = 12 + return {"gold_balance": 66, "exchange_balance": 12} + + def _refresh_account_points(self, client, account, cookie, *, ctn=None): + if "points" in self.fail_helpers: + raise RuntimeError("模拟积分接口异常") + account.points = 888 + return { + "points": 888, + "points_query": {"raw": {"data": {"willExpireTime": "1800000000"}}}, + } + + +class TestQueryAssetsAndBindExecution: + def setup_method(self): + self.engine = get_test_engine() + self.session = make_test_session(self.engine) + self.user = User(username="qw-admin", password_hash="h", role="super_admin") + self.session.add(self.user) + self.session.flush() + self.account = Account( + username="qw-acc", + uid="10086", + password="p", + email="q@e.com", + email_password="ep", + cookie="acf_uid=10086; acf_ltkid=1; acf_stk=2", + ) + self.session.add(self.account) + self.session.commit() + self.task = DouyuTask( + batch_id="qw-batch", + account_id=self.account.id, + task_type="query_assets_and_bind", + handbook_scope="query", + status="running", + message="", + created_by=self.user.id, + ) + self.session.add(self.task) + self.session.commit() + + def teardown_method(self): + self.session.close() + + def test_scope_and_task_registration(self): + assert "query" in DOUYU_HANDBOOK_SCOPES + assert "query_assets_and_bind" in SUPPORTED_DOUYU_TASK_TYPES + assert "query_assets_and_bind" in DOUYU_HANDBOOK_TASK_TYPES["query"] + batch_id, count = create_douyu_planned_tasks( + self.session, + [self.account.id], + "query_assets_and_bind", + "query", + self.user.id, + ) + assert count == 1 + row = self.session.query(DouyuTask).filter(DouyuTask.batch_id == batch_id).one() + assert row.handbook_scope == "query" + assert row.task_type == "query_assets_and_bind" + + def test_updates_gold_points_and_bind_cooldown(self, monkeypatch): + def fake_resolve(client, config): + return { + "status": "bound", + "bind_infos": [ + { + "act_alias": "B1", + "role_name": "测试召唤师", + "plat_name": "微信", + "area_name": "安卓一区", + "is_bound_role": True, + "is_bound_act": True, + "change_role_wait_time": 7200, + "can_change_time": 1800003600, + } + ], + "errors": [], + } + + monkeypatch.setattr(douyu_runner_overview, "resolve_elite_role", fake_resolve) + h = _QueryHarness() + h._execute_query_assets_and_bind( + self.session, + self.task, + self.account, + self.account.cookie, + {"bind_act_alias": "B1", "confirm_act_alias": "C1"}, + ) + assert h.marked["status"] == "success" + res = h.marked["result"] + assert res["gold_balance"] == 66 + assert res["exchange_balance"] == 12 + assert res["points"] == 888 + assert self.account.gold_balance == 66 + assert self.account.points == 888 + assert self.account.points_expire_at is not None + assert self.account.role_bind_status == "bound" + assert self.account.game_name == "测试召唤师" + assert self.account.role_change_available_at is not None + assert ( + self.session.query(AccountSyncState) + .filter(AccountSyncState.account_id == self.account.id) + .count() + >= 2 + ) + + def test_partial_failure_still_succeeds_with_other_fields(self, monkeypatch): + monkeypatch.setattr( + douyu_runner_overview, + "resolve_elite_role", + lambda client, config: { + "status": "unbound", + "bind_infos": [], + "errors": [], + }, + ) + h = _QueryHarness(fail_helpers={"gold"}) + h._execute_query_assets_and_bind( + self.session, + self.task, + self.account, + self.account.cookie, + {"bind_act_alias": "B1"}, + ) + assert h.marked["status"] == "success" + assert "gold" in h.marked["result"]["errors"] + assert "部分异常: gold" in h.marked["message"] + assert h.marked["result"]["points"] == 888 + assert self.account.role_bind_status == "unbound" + + def test_all_failed_marks_task_failed(self, monkeypatch): + monkeypatch.setattr( + douyu_runner_overview, + "resolve_elite_role", + lambda client, config: { + "status": "error", + "bind_infos": [], + "errors": ["角色接口500"], + }, + ) + h = _QueryHarness(fail_helpers={"gold", "points"}) + h._execute_query_assets_and_bind( + self.session, + self.task, + self.account, + self.account.cookie, + {}, + ) + assert h.marked["status"] == "failed" + assert "gold" in h.marked["message"] + assert "points" in h.marked["message"] + assert "bind" in h.marked["message"] + + +class TestQueryWorkbenchRouterAndExport: + def setup_method(self): + self.engine = get_test_engine() + self.session = make_test_session(self.engine) + self.admin = User(username="qw-admin", password_hash="h", role="super_admin") + self.support_no_login = User( + username="kf-no-login", + password_hash="h", + role="support", + custom_permissions=["account:view_assigned", "douyu:task"], + ) + self.support_with_login = User( + username="kf-with-login", + password_hash="h", + role="support", + custom_permissions=["account:view_assigned", "douyu:task", "login:batch"], + ) + self.session.add_all( + [self.admin, self.support_no_login, self.support_with_login] + ) + self.session.flush() + + now = datetime.now(UTC) + self.acc_valid = Account( + username="dy_valid", + uid="111", + nickname="有效号", + password="pw", + email="v@e.com", + email_password="ep", + cookie="acf_uid=111", + ck_check_status="valid", + gold_balance=100, + exchange_balance=5, + points=1280, + points_expire_at=now + timedelta(days=30), + role_bind_status="bound", + game_name="角色A", + game_channel="微信 / 苹果", + role_change_available_at=now - timedelta(hours=1), + role_change_official_at=now - timedelta(hours=1), + assigned_to=self.support_with_login.id, + ) + self.acc_invalid_ck = Account( + username="dy_invalid", + uid="222", + nickname="失效号", + password="pw", + email="i@e.com", + email_password="ep", + cookie="acf_uid=222", + ck_check_status="invalid", + status="invalid", + gold_balance=20, + points=300, + role_bind_status="bound", + game_name="角色B", + role_change_available_at=now + timedelta(hours=5), + assigned_to=self.support_with_login.id, + ) + self.acc_no_ck = Account( + username="dy_nock", + uid="", + nickname="无CK号", + password="pw", + email="n@e.com", + email_password="ep", + cookie="", + status="imported", + assigned_to=self.support_with_login.id, + ) + self.acc_missing_cred = Account( + username="dy_nocred", + password="", + email="", + email_password="", + cookie="", + status="imported", + assigned_to=self.support_with_login.id, + ) + self.session.add_all( + [self.acc_valid, self.acc_invalid_ck, self.acc_no_ck, self.acc_missing_cred] + ) + self.session.commit() + + def teardown_method(self): + self.session.close() + + def test_lookup_includes_invalid_and_nock_and_reports_unmatched(self): + res = lookup_query_workbench_accounts( + DouyuQueryWorkbenchLookupRequest( + account_names=["dy_invalid", "not_exists", "dy_nock", "dy_valid"] + ), + db=self.session, + current=self.admin, + ) + assert res["account_ids"] == [ + self.acc_invalid_ck.id, + self.acc_no_ck.id, + self.acc_valid.id, + ] + assert res["matched_names"] == ["dy_invalid", "dy_nock", "dy_valid"] + assert res["unmatched_names"] == ["not_exists"] + + def test_list_accounts_include_all_and_ck_status_filters(self): + default_items = list_task_accounts( + search="", + tag="", + ids="", + account_names="", + page=None, + db=self.session, + current=self.admin, + ) + assert {item.username for item in default_items} == {"dy_valid", "dy_invalid"} + + all_items = list_task_accounts( + search="", + tag="", + ids="", + account_names="", + include_all=True, + page=None, + db=self.session, + current=self.admin, + ) + assert {item.username for item in all_items} == { + "dy_valid", + "dy_invalid", + "dy_nock", + "dy_nocred", + } + + invalid_only = list_task_accounts( + search="", + tag="", + ids="", + account_names="", + include_all=True, + ck_status="invalid", + page=None, + db=self.session, + current=self.admin, + ) + assert [item.username for item in invalid_only] == ["dy_invalid"] + + cooldown_waiting = list_task_accounts( + search="", + tag="", + ids="", + account_names="", + include_all=True, + ck_status="cooldown_waiting", + page=None, + db=self.session, + current=self.admin, + ) + assert [item.username for item in cooldown_waiting] == ["dy_invalid"] + + cooldown_ready = list_task_accounts( + search="", + tag="", + ids="", + account_names="", + include_all=True, + ck_status="cooldown_ready", + page=None, + db=self.session, + current=self.admin, + ) + assert [item.username for item in cooldown_ready] == ["dy_valid"] + + def test_select_invalid_ids_and_export_csv_order(self): + desired = [self.acc_no_ck.id, self.acc_valid.id, self.acc_invalid_ck.id] + update_workbench_accounts( + DouyuWorkbenchAccountsUpdate(handbook_scope="query", account_ids=desired), + db=self.session, + current=self.admin, + ) + assert ( + self.session.query(DouyuWorkbenchAccount) + .filter(DouyuWorkbenchAccount.handbook_scope == "query") + .count() + == 3 + ) + + invalid_res = list_query_workbench_invalid_ids( + db=self.session, current=self.admin + ) + assert invalid_res["account_ids"] == [self.acc_no_ck.id, self.acc_invalid_ck.id] + assert invalid_res["invalid_ck_ids"] == [self.acc_invalid_ck.id] + assert invalid_res["no_cookie_ids"] == [self.acc_no_ck.id] + + resp = export_query_workbench_csv( + DouyuQueryWorkbenchExportRequest(ids=[]), + db=self.session, + current=self.admin, + ) + raw = resp.body.decode("utf-8-sig") + rows = list(csv.reader(io.StringIO(raw))) + assert rows[0][0] == "账号" + assert [r[0] for r in rows[1:]] == ["dy_nock", "dy_valid", "dy_invalid"] + assert rows[2][6] == "有效" + assert rows[2][8] == "100" + assert rows[2][10] == "1280" + assert rows[2][15] == "可换绑" + assert rows[3][15] == "冷却中" + + def test_relogin_requires_login_batch_permission(self): + with pytest.raises(HTTPException) as exc: + relogin_query_workbench_invalid_accounts( + DouyuQueryWorkbenchReloginRequest(ids=[self.acc_invalid_ck.id]), + db=self.session, + current=self.support_no_login, + ) + assert exc.value.status_code == 403 + + def test_relogin_splits_batches_skips_inflight_and_uses_manual_category(self): + # 构造一个已在排队登录的账号不应重复入队;valid 账号应跳过;缺凭据账号跳过 + acc_queued = Account( + username="dy_queued", + password="pw", + email="q@e.com", + email_password="ep", + cookie="acf_uid=999", + ck_check_status="invalid", + assigned_to=self.support_with_login.id, + ) + self.session.add(acc_queued) + self.session.flush() + self.session.add( + LoginTask( + batch_id="existing-pending", + account_id=acc_queued.id, + status="pending", + attempt_status="pending", + created_by=self.admin.id, + ) + ) + self.session.commit() + + budget = get_query_workbench_manual_budget( + db=self.session, current=self.support_with_login + ) + assert budget["category"] == CATEGORY_MANUAL + + res = relogin_query_workbench_invalid_accounts( + DouyuQueryWorkbenchReloginRequest( + ids=[ + self.acc_valid.id, + self.acc_invalid_ck.id, + self.acc_no_ck.id, + self.acc_missing_cred.id, + acc_queued.id, + ] + ), + db=self.session, + current=self.support_with_login, + ) + assert res["success"] is True + assert res["category"] == CATEGORY_MANUAL + assert res["relogin_count"] == 1 + assert res["login_count"] == 1 + assert res["skipped_valid"] == 1 + assert res["skipped_in_flight"] == 1 + assert res["skipped_missing_credentials"] == 1 + assert len(res["batch_ids"]) == 2 + + jobs = ( + self.session.query(ExecutionJob) + .filter(ExecutionJob.batch_id.in_(res["batch_ids"])) + .all() + ) + by_type = {job.job_type: job for job in jobs} + assert set(by_type.keys()) == {JOB_RELOGIN_BATCH, JOB_LOGIN_BATCH} + assert by_type[JOB_RELOGIN_BATCH].payload_json["mode"] == "relogin" + assert by_type[JOB_RELOGIN_BATCH].payload_json["category"] == CATEGORY_MANUAL + assert by_type[JOB_RELOGIN_BATCH].payload_json["trigger_source"] == "manual" + assert by_type[JOB_LOGIN_BATCH].payload_json["mode"] == "login" + assert by_type[JOB_LOGIN_BATCH].payload_json["category"] == CATEGORY_MANUAL + + # 重复提交应识别已入队的 ExecutionJob 并拦截重复入队 + with pytest.raises(HTTPException) as dup_exc: + relogin_query_workbench_invalid_accounts( + DouyuQueryWorkbenchReloginRequest( + ids=[self.acc_invalid_ck.id, self.acc_no_ck.id] + ), + db=self.session, + current=self.support_with_login, + ) + assert dup_exc.value.status_code == 400 + assert "已在登录队列中" in str(dup_exc.value.detail) + + +def test_execution_worker_forwards_manual_category_for_relogin_batch(db, monkeypatch): + """验证 ExecutionJobWorker 执行 JOB_RELOGIN_BATCH 时会透传 payload.category=manual_login。""" + user = User( + username="exec-manual-user", + password_hash="h", + role="super_admin", + is_active=True, + ) + db.add(user) + db.commit() + acc = Account( + username="exec-manual-acc", + password="pw", + email="m@e.com", + email_password="ep", + cookie="acf_uid=321", + ck_check_status="invalid", + assigned_to=user.id, + ) + db.add(acc) + db.commit() + + res = relogin_query_workbench_invalid_accounts( + DouyuQueryWorkbenchReloginRequest(ids=[acc.id]), + db=db, + current=user, + ) + job = db.query(ExecutionJob).filter(ExecutionJob.batch_id == res["batch_id"]).one() + worker = execution_worker.ExecutionJobWorker() + claimed = claim_execution_jobs( + lane_scopes=(LANE_AUTH,), + owner=worker._owner, + limit=1, + ) + assert [row.id for row in claimed] == [job.id] + + captured: dict = {} + + class FakeLoginRunner: + def __init__(self, **kwargs): + captured.update(kwargs) + + def run(self): + captured["ran"] = True + + monkeypatch.setattr(execution_worker, "LoginBatchRunner", FakeLoginRunner) + worker._run_job(int(job.id)) + assert captured.get("ran") is True + assert captured.get("mode") == "relogin" + assert captured.get("trigger_source") == "manual" + assert captured.get("category") == CATEGORY_MANUAL diff --git a/uv.lock b/uv.lock index f60fd52..642cfa1 100644 --- a/uv.lock +++ b/uv.lock @@ -381,7 +381,7 @@ wheels = [ [[package]] name = "live-hub-py" -version = "0.4.25" +version = "0.4.26" source = { editable = "." } dependencies = [ { name = "alembic" }, diff --git a/web/backend/routers/douyu.py b/web/backend/routers/douyu.py index 524e7c4..bcf4313 100644 --- a/web/backend/routers/douyu.py +++ b/web/backend/routers/douyu.py @@ -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)" diff --git a/web/backend/schemas.py b/web/backend/schemas.py index ae763ab..381ed4c 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -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): diff --git a/web/backend/services/automation/jobs/douyu_tasks_retention.py b/web/backend/services/automation/jobs/douyu_tasks_retention.py index 3e266d4..53d78e0 100644 --- a/web/backend/services/automation/jobs/douyu_tasks_retention.py +++ b/web/backend/services/automation/jobs/douyu_tasks_retention.py @@ -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", diff --git a/web/backend/services/douyu_runner.py b/web/backend/services/douyu_runner.py index 64e390e..53fbc94 100644 --- a/web/backend/services/douyu_runner.py +++ b/web/backend/services/douyu_runner.py @@ -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, diff --git a/web/backend/services/douyu_runner_overview.py b/web/backend/services/douyu_runner_overview.py index 5104e7f..feb01c4 100644 --- a/web/backend/services/douyu_runner_overview.py +++ b/web/backend/services/douyu_runner_overview.py @@ -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) diff --git a/web/backend/services/douyu_service.py b/web/backend/services/douyu_service.py index c8f047c..18a4241 100644 --- a/web/backend/services/douyu_service.py +++ b/web/backend/services/douyu_service.py @@ -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", + }, } diff --git a/web/backend/services/execution_worker.py b/web/backend/services/execution_worker.py index 1ddf0e1..fd6d4b0 100644 --- a/web/backend/services/execution_worker.py +++ b/web/backend/services/execution_worker.py @@ -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, ) diff --git a/web/backend/services/login_quota_service.py b/web/backend/services/login_quota_service.py index 0ded0e3..8b71f39 100644 --- a/web/backend/services/login_quota_service.py +++ b/web/backend/services/login_quota_service.py @@ -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) diff --git a/web/frontend/src/App.tsx b/web/frontend/src/App.tsx index 7c61d3b..b5c3f9b 100644 --- a/web/frontend/src/App.tsx +++ b/web/frontend/src/App.tsx @@ -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() { } /> } /> )} /> + )} /> } /> } /> } /> diff --git a/web/frontend/src/api/douyu.ts b/web/frontend/src/api/douyu.ts index c1efd9c..58da117 100644 --- a/web/frontend/src/api/douyu.ts +++ b/web/frontend/src/api/douyu.ts @@ -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('/douyu/supply-targets', data), updateSupplyTarget: (targetId: number, data: DouyuSupplyTargetUpdate) => api.put(`/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('/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>('/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( + '/douyu/query-workbench/lookup', + { account_names: accountNames }, + ), + getQueryWorkbenchInvalidIds: () => + api.get( + '/douyu/query-workbench/invalid-ids', + ), + getQueryWorkbenchManualBudget: () => + api.get( + '/douyu/query-workbench/manual-budget', + ), + reloginQueryWorkbenchInvalid: (ids: number[], selectAllInvalid = false) => + api.post( + '/douyu/query-workbench/relogin-invalid', + { ids, select_all_invalid: selectAllInvalid }, + ), + exportQueryWorkbenchCsv: (ids: number[]) => + api.post('/douyu/query-workbench/export', { ids }, { responseType: 'blob' }), getConfig: () => api.get('/douyu/config'), getRechargeChannel: () => api.get('/douyu/recharge-channel'), updateConfig: (data: Partial) => api.put('/douyu/config', data), @@ -89,7 +113,7 @@ export const douyuApi = { createTasks: (data: DouyuTaskBatchRequest) => api.post('/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 }, ), diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index 2c5c0b8..f1d953b 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -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; 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; diff --git a/web/frontend/src/layouts/MainLayout.tsx b/web/frontend/src/layouts/MainLayout.tsx index 6fb0290..b6f6983 100644 --- a/web/frontend/src/layouts/MainLayout.tsx +++ b/web/frontend/src/layouts/MainLayout.tsx @@ -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: }); + douyuItems.push({ key: '/douyu/query-workbench', label: '查询工作台', icon: }); } // 外部单协作:权限独立,客服没有 douyu:task 也要能进共享台账。 diff --git a/web/frontend/src/pages/DouyuQueryWorkbenchPage.tsx b/web/frontend/src/pages/DouyuQueryWorkbenchPage.tsx new file mode 100644 index 0000000..f0be77b --- /dev/null +++ b/web/frontend/src/pages/DouyuQueryWorkbenchPage.tsx @@ -0,0 +1,1337 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { + Alert, + App, + Button, + Card, + Dropdown, + Input, + InputNumber, + Modal, + Popconfirm, + Segmented, + Select, + Space, + Table, + Tag, + Tooltip, + Typography, +} from 'antd'; +import type { MenuProps, TableProps } from 'antd'; +import { + CheckSquareOutlined, + ClearOutlined, + CopyOutlined, + DeleteOutlined, + DownloadOutlined, + ImportOutlined, + LoadingOutlined, + MoreOutlined, + ReloadOutlined, + SafetyCertificateOutlined, + SearchOutlined, + SyncOutlined, +} from '@ant-design/icons'; +import { + accountApi, + douyuApi, + type DouyuQueryWorkbenchManualBudget, + type DouyuTaskAccountItem, + type DouyuTaskItem, +} from '../api/modules'; +import { usePermissions } from '../hooks/usePermissions'; +import { getErrorMessage } from '../utils/error'; +import { formatTime } from '../utils/time'; +import { message } from '../utils/antdMessage'; +import { + formatWaitSeconds, + TASK_STATUS_COLORS, + TASK_STATUS_LABELS, +} from './douyu-tasks/config'; + +const { Text, Title } = Typography; + +type StatusFilterValue = + | '' + | 'valid' + | 'invalid' + | 'no_cookie' + | 'cooldown_ready' + | 'cooldown_waiting'; + +const STATUS_FILTER_OPTIONS: Array<{ label: string; value: StatusFilterValue }> = [ + { label: '全部', value: '' }, + { label: 'CK 有效', value: 'valid' }, + { label: 'CK 失效', value: 'invalid' }, + { label: '无 CK/待登录', value: 'no_cookie' }, + { label: '可换绑', value: 'cooldown_ready' }, + { label: '冷却中', value: 'cooldown_waiting' }, +]; + +function parseAccountNames(text: string): string[] { + const seen = new Set(); + return text + .replace(/\r\n/g, '\n') + .replace(/\r/g, '\n') + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0 && !seen.has(line) && seen.add(line)); +} + +function isInvalidOrNoCookie(account: DouyuTaskAccountItem): boolean { + if (account.has_cookie === false) return true; + if (account.ck_check_status === 'invalid') return true; + if (account.account_status === 'invalid') return true; + return false; +} + +function parseIsoSeconds(value: string | null | undefined): number | null { + if (!value) return null; + const ms = Date.parse(value); + if (!Number.isFinite(ms)) return null; + return Math.floor(ms / 1000); +} + +function copyText(value: string, label: string) { + if (!value) return; + navigator.clipboard.writeText(value).then( + () => message.success(`已复制${label}`), + () => message.error('复制失败,请手动复制'), + ); +} + +function downloadCsvBlob(blob: Blob, filename: string) { + const normalized = blob instanceof Blob + ? blob + : new Blob([blob as unknown as BlobPart], { type: 'text/csv;charset=utf-8' }); + const url = window.URL.createObjectURL(normalized); + const a = document.createElement('a'); + a.href = url; + a.download = filename; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + window.URL.revokeObjectURL(url); +} + +export default function DouyuQueryWorkbenchPage() { + const { modal } = App.useApp(); + const { can, user } = usePermissions(); + const isAdmin = user?.role === 'super_admin'; + const canRelogin = isAdmin || can('login:batch'); + + const [workbenchIds, setWorkbenchIds] = useState([]); + const [workbenchReady, setWorkbenchReady] = useState(false); + const [accounts, setAccounts] = useState([]); + const [accountTotal, setAccountTotal] = useState(0); + const [accountPage, setAccountPage] = useState(1); + const [accountPageSize, setAccountPageSize] = useState(() => { + const saved = Number(localStorage.getItem('douyu_query_workbench_page_size')); + return [10, 20, 50, 100].includes(saved) ? saved : 20; + }); + const [loading, setLoading] = useState(false); + const [selectedIds, setSelectedIds] = useState([]); + + const [searchText, setSearchText] = useState(''); + const [statusFilter, setStatusFilter] = useState(''); + const [concurrency, setConcurrency] = useState(5); + + const [tasks, setTasks] = useState([]); + const [runningBatchIds, setRunningBatchIds] = useState>(() => new Set()); + const [queryStarting, setQueryStarting] = useState(false); + const [ckCheckingIds, setCkCheckingIds] = useState>(() => new Set()); + const [selectingInvalid, setSelectingInvalid] = useState(false); + const [reloginSubmitting, setReloginSubmitting] = useState(false); + const [exporting, setExporting] = useState(false); + + const [manualBudget, setManualBudget] = useState(null); + const [budgetLoading, setBudgetLoading] = useState(false); + + // 导入弹窗 + const [importOpen, setImportOpen] = useState(false); + const [pasteNamesText, setPasteNamesText] = useState(''); + const [pasteImporting, setPasteImporting] = useState(false); + const [unmatchedNames, setUnmatchedNames] = useState([]); + const [importSearch, setImportSearch] = useState(''); + const [importTag, setImportTag] = useState(''); + const [importCkStatus, setImportCkStatus] = useState(''); + const [importTags, setImportTags] = useState([]); + const [importPool, setImportPool] = useState([]); + const [importTotal, setImportTotal] = useState(0); + const [importPage, setImportPage] = useState(1); + const [importSelectedIds, setImportSelectedIds] = useState([]); + const [importLoading, setImportLoading] = useState(false); + const [importAllLoading, setImportAllLoading] = useState(false); + const importPageSize = 20; + + const [nowSeconds, setNowSeconds] = useState(() => Math.floor(Date.now() / 1000)); + const tasksLoadingRef = useRef(false); + + useEffect(() => { + const timer = window.setInterval(() => { + setNowSeconds(Math.floor(Date.now() / 1000)); + }, 1000); + return () => window.clearInterval(timer); + }, []); + + const loadManualBudget = useCallback(async () => { + setBudgetLoading(true); + try { + const budget = await douyuApi.getQueryWorkbenchManualBudget(); + setManualBudget(budget); + } catch { + // 仅用于顶部展示,失败不阻塞主体查询 + } finally { + setBudgetLoading(false); + } + }, []); + + const loadWorkbench = useCallback(async () => { + try { + const res = await douyuApi.listWorkbenchAccounts('query'); + setWorkbenchIds(res.account_ids || []); + } catch (error) { + message.error(`加载查询工作台列表失败: ${getErrorMessage(error)}`); + } finally { + setWorkbenchReady(true); + } + }, []); + + useEffect(() => { + void loadWorkbench(); + void loadManualBudget(); + }, [loadManualBudget, loadWorkbench]); + + const saveWorkbenchIds = useCallback(async (nextIds: number[], toast?: string) => { + const deduped = Array.from(new Set(nextIds.filter((id) => Number.isInteger(id) && id > 0))); + const res = await douyuApi.updateWorkbenchAccounts('query', deduped); + setWorkbenchIds(res.account_ids); + setSelectedIds((prev) => prev.filter((id) => res.account_ids.includes(id))); + if (toast) message.success(toast); + return res.account_ids; + }, []); + + const loadAccountsPage = useCallback(async () => { + if (!workbenchReady) return; + if (workbenchIds.length === 0) { + setAccounts([]); + setAccountTotal(0); + return; + } + setLoading(true); + try { + const res = await douyuApi.listAccountsPaged({ + ids: workbenchIds.join(','), + search: searchText.trim() || undefined, + ck_status: statusFilter || undefined, + include_all: true, + page: accountPage, + page_size: accountPageSize, + }); + setAccounts(res.items); + setAccountTotal(res.total); + if (accountPage > 1 && res.items.length === 0 && res.total > 0) { + setAccountPage(Math.max(1, Math.ceil(res.total / accountPageSize))); + } + } catch (error) { + message.error(`加载账号列表失败: ${getErrorMessage(error)}`); + } finally { + setLoading(false); + } + }, [accountPage, accountPageSize, searchText, statusFilter, workbenchIds, workbenchReady]); + + const loadTasks = useCallback(async () => { + if (!workbenchReady || tasksLoadingRef.current) return; + tasksLoadingRef.current = true; + try { + const data = await douyuApi.listTasks('query', undefined, true, 300); + setTasks(data); + const stillRunning = new Set(); + for (const task of data) { + if (['planned', 'pending', 'running'].includes(task.status)) { + stillRunning.add(task.batch_id); + } + } + setRunningBatchIds(stillRunning); + } catch { + // ignore transient polling failures + } finally { + tasksLoadingRef.current = false; + } + }, [workbenchReady]); + + useEffect(() => { + void loadAccountsPage(); + }, [loadAccountsPage]); + + useEffect(() => { + void loadTasks(); + }, [loadTasks]); + + const hasInFlightActivity = useMemo( + () => + runningBatchIds.size > 0 + || tasks.some((t) => ['planned', 'pending', 'running'].includes(t.status)) + || accounts.some((a) => Boolean(a.in_flight_login)), + [accounts, runningBatchIds, tasks], + ); + + useEffect(() => { + if (!hasInFlightActivity) return undefined; + const timer = window.setInterval(() => { + void loadTasks(); + void loadAccountsPage(); + void loadManualBudget(); + }, 2200); + return () => window.clearInterval(timer); + }, [hasInFlightActivity, loadAccountsPage, loadManualBudget, loadTasks]); + + const latestTaskByAccount = useMemo(() => { + const map = new Map(); + for (const task of tasks) { + const prev = map.get(task.account_id); + if (!prev || task.id > prev.id) { + map.set(task.account_id, task); + } + } + return map; + }, [tasks]); + + const visibleInvalidCount = useMemo( + () => accounts.filter(isInvalidOrNoCookie).length, + [accounts], + ); + + // 导入弹窗池查询 + const loadImportPool = useCallback(async (page = importPage) => { + setImportLoading(true); + try { + const res = await douyuApi.listAccountsPaged({ + search: importSearch.trim() || undefined, + tag: importTag || undefined, + ck_status: importCkStatus || undefined, + include_all: true, + page, + page_size: importPageSize, + }); + setImportPool(res.items); + setImportTotal(res.total); + } catch (error) { + message.error(`加载可导入账号失败: ${getErrorMessage(error)}`); + } finally { + setImportLoading(false); + } + }, [importCkStatus, importPage, importSearch, importTag]); + + const openImportModal = () => { + setImportOpen(true); + setImportSelectedIds([]); + setImportPage(1); + setUnmatchedNames([]); + void loadImportPool(1); + accountApi.listTags().then(setImportTags).catch(() => {}); + }; + + useEffect(() => { + if (!importOpen) return; + void loadImportPool(importPage); + }, [importOpen, importPage, loadImportPool]); + + const handlePasteImport = async () => { + const names = parseAccountNames(pasteNamesText); + if (names.length === 0) { + message.warning('请先粘贴斗鱼账号名(每行一个)'); + return; + } + setPasteImporting(true); + try { + const lookup = await douyuApi.lookupQueryWorkbenchAccounts(names); + setUnmatchedNames(lookup.unmatched_names || []); + if (lookup.account_ids.length > 0) { + const beforeSet = new Set(workbenchIds); + const addedCount = lookup.account_ids.filter((id) => !beforeSet.has(id)).length; + await saveWorkbenchIds([...workbenchIds, ...lookup.account_ids]); + setAccountPage(1); + message.success( + addedCount > 0 + ? `已匹配 ${lookup.account_ids.length} 个账号,新导入 ${addedCount} 个到查询工作台` + : `已匹配 ${lookup.account_ids.length} 个账号(均已在工作台中)`, + ); + } else { + message.warning('未匹配到任何可见的斗鱼账号'); + } + if ((lookup.unmatched_names || []).length === 0) { + setPasteNamesText(''); + setImportOpen(false); + } + } catch (error) { + message.error(`导入失败: ${getErrorMessage(error)}`); + } finally { + setPasteImporting(false); + } + }; + + const handleImportSelectedFromPool = async () => { + if (importSelectedIds.length === 0) { + message.warning('请先勾选要导入的账号'); + return; + } + const beforeSet = new Set(workbenchIds); + const addedCount = importSelectedIds.filter((id) => !beforeSet.has(id)).length; + await saveWorkbenchIds( + [...workbenchIds, ...importSelectedIds], + addedCount > 0 ? `新导入 ${addedCount} 个账号到查询工作台` : '所选账号均已在工作台中', + ); + setImportOpen(false); + }; + + const handleImportAllFiltered = async () => { + setImportAllLoading(true); + try { + const res = await douyuApi.listAccountIds({ + search: importSearch.trim() || undefined, + tag: importTag || undefined, + ck_status: importCkStatus || undefined, + include_all: true, + }); + if (res.account_ids.length === 0) { + message.warning('当前筛选条件下没有可导入的账号'); + return; + } + const beforeSet = new Set(workbenchIds); + const addedCount = res.account_ids.filter((id) => !beforeSet.has(id)).length; + await saveWorkbenchIds( + [...workbenchIds, ...res.account_ids], + `已按筛选导入 ${res.account_ids.length} 个账号(新增 ${addedCount} 个)`, + ); + setImportOpen(false); + } catch (error) { + message.error(`按筛选导入失败: ${getErrorMessage(error)}`); + } finally { + setImportAllLoading(false); + } + }; + + const handleOneClickQuery = async (overrideIds?: number[]) => { + const rawTargetIds = overrideIds ?? (selectedIds.length > 0 ? selectedIds : workbenchIds); + if (rawTargetIds.length === 0) { + message.warning('工作台暂无账号,请先导入斗鱼账号'); + return; + } + // 尽量过滤已知无 CK 的账号,若选中项跨页则由后端继续剔除无 CK 账号 + const knownNoCookie = new Set( + accounts.filter((a) => a.has_cookie === false).map((a) => a.id), + ); + const eligibleIds = rawTargetIds.filter((id) => !knownNoCookie.has(id)); + if (eligibleIds.length === 0) { + message.warning('所选账号均没有有效 Cookie,请先选中失效 CK 并重新登录'); + return; + } + setQueryStarting(true); + try { + const res = await douyuApi.createTasks({ + account_ids: eligibleIds, + task_type: 'query_assets_and_bind', + handbook_scope: 'query', + concurrency, + }); + setRunningBatchIds((prev) => new Set(prev).add(res.batch_id)); + message.success( + `已下发一键查询(共 ${res.count} 个有 CK 账号,批次 ${res.batch_id}),查询结果将自动刷新`, + ); + void loadTasks(); + } catch (error) { + message.error(`发起一键查询失败: ${getErrorMessage(error)}`); + } finally { + setQueryStarting(false); + } + }; + + const handleCheckCk = async (overrideIds?: number[]) => { + const candidateRows = overrideIds + ? accounts.filter((a) => overrideIds.includes(a.id)) + : (selectedIds.length > 0 + ? accounts.filter((a) => selectedIds.includes(a.id)) + : accounts); + const checkableIds = candidateRows + .filter((a) => a.has_cookie !== false && !a.in_flight_login) + .map((a) => a.id); + if (checkableIds.length === 0) { + message.warning('当前选中的账号没有可检测的 Cookie(无 CK 或正在登录中)'); + return; + } + setCkCheckingIds((prev) => { + const next = new Set(prev); + checkableIds.forEach((id) => next.add(id)); + return next; + }); + try { + const res = await douyuApi.checkAccountsCk(checkableIds); + const validCount = res.results.filter((r) => r.valid).length; + const invalidCount = res.results.length - validCount; + message.success(`CK 检测完成:有效 ${validCount} 个,失效 ${invalidCount} 个`); + await loadAccountsPage(); + } catch (error) { + message.error(`检测 CK 失败: ${getErrorMessage(error)}`); + } finally { + setCkCheckingIds((prev) => { + const next = new Set(prev); + checkableIds.forEach((id) => next.delete(id)); + return next; + }); + } + }; + + const handleSelectInvalidCks = async () => { + if (workbenchIds.length === 0) { + message.warning('工作台暂无账号'); + return; + } + setSelectingInvalid(true); + try { + const res = await douyuApi.getQueryWorkbenchInvalidIds(); + setSelectedIds(res.account_ids); + if (res.total_invalid === 0) { + message.info('当前工作台内没有 CK 失效或无 CK 的账号'); + } else { + message.success( + `已全选工作台内 ${res.total_invalid} 个待处理账号(CK 失效 ${res.invalid_ck_ids.length} 个,无 CK ${res.no_cookie_ids.length} 个)`, + ); + } + } catch (error) { + message.error(`获取失效 CK 列表失败: ${getErrorMessage(error)}`); + } finally { + setSelectingInvalid(false); + } + }; + + const handleReloginInvalid = async () => { + if (!canRelogin) { + message.error('无权限发起重登(需超级管理员或 login:batch 权限)'); + return; + } + if (selectedIds.length === 0) { + message.warning('请先点击「选择失效 CK」或手动勾选需要重登的账号'); + return; + } + let latestBudget = manualBudget; + try { + latestBudget = await douyuApi.getQueryWorkbenchManualBudget(); + setManualBudget(latestBudget); + } catch { + // fallback to cached budget state + } + + const remaining = latestBudget?.manual_daily_remaining ?? 0; + const limit = latestBudget?.manual_daily_limit ?? 0; + const overflowWarning = limit > 0 && selectedIds.length > remaining; + + modal.confirm({ + title: '确认重新登录失效/无 CK 账号(走人工登录预算)', + width: 520, + okText: '确认提交重登', + cancelText: '取消', + content: ( + + + 本次已选中 {selectedIds.length} 个账号,将自动跳过其中 CK 仍有效或已在队列中的账号; + 有旧 CK 的走重登流程,无 CK 的走首次登录流程。 + + + + ), + onOk: async () => { + setReloginSubmitting(true); + try { + const res = await douyuApi.reloginQueryWorkbenchInvalid(selectedIds, false); + if (res.manual_budget) setManualBudget(res.manual_budget); + const parts = [ + res.relogin_count > 0 ? `失效重登 ${res.relogin_count} 个` : '', + res.login_count > 0 ? `无CK登录 ${res.login_count} 个` : '', + ].filter(Boolean); + const skipParts = [ + res.skipped_valid > 0 ? `有效跳过 ${res.skipped_valid}` : '', + res.skipped_in_flight > 0 ? `排队中 ${res.skipped_in_flight}` : '', + res.skipped_missing_credentials > 0 ? `缺密码/邮箱 ${res.skipped_missing_credentials}` : '', + ].filter(Boolean); + message.success( + `已加入人工登录队列:${parts.join(',')}${skipParts.length ? `(${skipParts.join(',')})` : ''}`, + ); + await loadAccountsPage(); + } catch (error) { + message.error(`提交重登失败: ${getErrorMessage(error)}`); + } finally { + setReloginSubmitting(false); + } + }, + }); + }; + + const handleExportCsv = async () => { + if (workbenchIds.length === 0) { + message.warning('工作台暂无可导出的账号'); + return; + } + setExporting(true); + try { + const targetIds = selectedIds.length > 0 ? selectedIds : workbenchIds; + const blob = await douyuApi.exportQueryWorkbenchCsv(targetIds); + const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, ''); + downloadCsvBlob(blob, `douyu_query_workbench_${stamp}.csv`); + message.success( + selectedIds.length > 0 + ? `已导出选中的 ${selectedIds.length} 个账号 CSV` + : `已导出工作台全部 ${workbenchIds.length} 个账号 CSV`, + ); + } catch (error) { + message.error(`导出 CSV 失败: ${getErrorMessage(error)}`); + } finally { + setExporting(false); + } + }; + + const handleRemoveAccounts = async (idsToRemove: number[]) => { + const removeSet = new Set(idsToRemove); + const nextIds = workbenchIds.filter((id) => !removeSet.has(id)); + await saveWorkbenchIds(nextIds, `已从查询工作台移出 ${idsToRemove.length} 个账号`); + }; + + const handleClearWorkbench = async () => { + await saveWorkbenchIds([], '已清空查询工作台'); + setSelectedIds([]); + }; + + const columns: TableProps['columns'] = [ + { + title: '#', + width: 56, + render: (_, __, index) => ( + {(accountPage - 1) * accountPageSize + index + 1} + ), + }, + { + title: '斗鱼账号', + dataIndex: 'username', + width: 210, + render: (_, record) => ( + + + + {record.username} + + + + {record.nickname ? `${record.nickname} · ` : ''} + UID {record.uid || '-'} + + + ), + }, + { + title: '标签 / 归属', + width: 145, + render: (_, record) => ( + + {record.tag ? {record.tag} : -} + {record.assigned_username ? ( + + 归属: {record.assigned_username} + + ) : null} + + ), + }, + { + title: 'CK 状态', + width: 135, + render: (_, record) => { + if (ckCheckingIds.has(record.id)) { + return }>检测中; + } + const inFlightTag = record.in_flight_login ? ( + } style={{ marginInlineEnd: 0 }}> + 登录队列中 + + ) : null; + if (record.has_cookie === false) { + return ( + + 无 CK / 待登录 + {inFlightTag} + + ); + } + if (record.ck_check_status === 'valid') { + return ( + + + 有效 + + {record.ck_checked_at ? ( + + {formatTime(record.ck_checked_at)} + + ) : null} + + ); + } + if (record.ck_check_status === 'invalid' || record.account_status === 'invalid') { + return ( + + + 失效 + + {inFlightTag} + + ); + } + return ( + + 未检测 + {inFlightTag} + + ); + }, + }, + { + title: '鱼翅', + width: 115, + render: (_, record) => ( + + {record.gold_balance != null ? record.gold_balance : '-'} + {record.exchange_balance != null ? ( + + 兑换: {record.exchange_balance} + + ) : null} + + ), + }, + { + title: '积分', + width: 145, + render: (_, record) => ( + + {record.points != null ? record.points : '-'} + {record.points_expire_at ? ( + + 到期: {formatTime(record.points_expire_at)} + + ) : null} + + ), + }, + { + title: '绑定角色', + width: 190, + render: (_, record) => { + const bindColor = record.role_bind_status === 'bound' + ? 'green' + : record.role_bind_status === 'pending' + ? 'orange' + : record.role_bind_status === 'unbound' + ? 'red' + : 'default'; + return ( + + {record.game_name ? ( + + {record.game_name} + + ) : ( + + {record.role_bind_status === 'unbound' ? '未绑定' : '未查询'} + + )} + + + {record.role_bind_label || record.role_bind_status} + + {record.game_channel ? ( + + {record.game_channel} + + ) : null} + + + ); + }, + }, + { + title: '换绑时间 / 冷却', + width: 210, + render: (_, record) => { + if (record.role_bind_status === 'unbound') { + return 未绑定角色; + } + if (record.role_bind_status === 'pending') { + return 待确认绑定; + } + if (record.role_bind_status !== 'bound') { + return 待查询; + } + + const availEpoch = parseIsoSeconds(record.role_change_available_at); + if (availEpoch != null) { + const remaining = availEpoch - nowSeconds; + const officialTip = record.role_change_official_at + ? `官方返回时间: ${formatTime(record.role_change_official_at)}` + : undefined; + if (remaining <= 0) { + return ( + + + 可换绑 + + 解绑时间: {formatTime(record.role_change_available_at)} + + + + ); + } + return ( + + + + 冷却中 · 剩 {formatWaitSeconds(remaining)} + + + 可换绑: {formatTime(record.role_change_available_at)} + + + + ); + } + + if (record.change_role_wait_time != null) { + if (record.change_role_wait_time <= 0) { + return 可换绑; + } + return ( + + 冷却中 · {formatWaitSeconds(record.change_role_wait_time)} + + ); + } + + return 待查询; + }, + }, + { + title: '最近查询结果', + width: 220, + render: (_, record) => { + const latestTask = latestTaskByAccount.get(record.id); + if (!latestTask) { + return record.overview_queried_at ? ( + + 同步: {formatTime(record.overview_queried_at)} + + ) : ( + 暂无查询记录 + ); + } + const statusColor = TASK_STATUS_COLORS[latestTask.status] || 'default'; + const statusLabel = TASK_STATUS_LABELS[latestTask.status] || latestTask.status; + return ( + + + + {statusLabel} + + + {formatTime(latestTask.finished_at || latestTask.created_at)} + + + {latestTask.message ? ( + + + {latestTask.message} + + + ) : null} + + ); + }, + }, + { + title: '操作', + width: 110, + fixed: 'right', + render: (_, record) => { + const items: MenuProps['items'] = [ + { + key: 'copy-username', + icon: , + label: '复制账号名', + onClick: () => copyText(record.username, '账号名'), + }, + { + key: 'check-ck', + icon: , + label: '检测 CK', + disabled: record.has_cookie === false || Boolean(record.in_flight_login), + onClick: () => void handleCheckCk([record.id]), + }, + { + key: 'remove', + icon: , + label: '移出工作台', + danger: true, + onClick: () => void handleRemoveAccounts([record.id]), + }, + ]; + return ( + + + + + + + + + + + + + + + + + + 并发 + setConcurrency(Number(v) || 5)} + style={{ width: 64 }} + /> + + {selectedIds.length > 0 ? ( + void handleRemoveAccounts(selectedIds)} + > + + + ) : null} + {workbenchIds.length > 0 ? ( + void handleClearWorkbench()} + > + + + ) : null} + + + + +
+ { + setStatusFilter(val as StatusFilterValue); + setAccountPage(1); + }} + /> + + { + setSearchText(e.target.value); + setAccountPage(1); + }} + onSearch={() => setAccountPage(1)} + /> + {selectedIds.length > 0 ? ( + + ) : null} + +
+ + + rowKey="id" + size="small" + loading={loading} + columns={columns} + dataSource={accounts} + scroll={{ x: 1480 }} + rowSelection={{ + selectedRowKeys: selectedIds, + preserveSelectedRowKeys: true, + onChange: (keys) => setSelectedIds(keys.map(Number)), + }} + pagination={{ + current: accountPage, + pageSize: accountPageSize, + total: accountTotal, + showSizeChanger: true, + pageSizeOptions: ['10', '20', '50', '100'], + showTotal: (t) => `共 ${t} 个账号`, + onChange: (page, size) => { + setAccountPage(page); + if (size !== accountPageSize) { + setAccountPageSize(size); + localStorage.setItem('douyu_query_workbench_page_size', String(size)); + } + }, + }} + locale={{ + emptyText: workbenchReady + ? '当前查询工作台还没有账号,点击上方「导入账号」即可粘贴斗鱼号或按标签导入' + : '加载中...', + }} + /> + + + + setImportOpen(false)} + footer={null} + > + + + + setPasteNamesText(e.target.value)} + /> + + + {unmatchedNames.length > 0 ? ( + + ) : null} + + {unmatchedNames.length > 0 ? ( + + ) : null} + + + + + + + { + setImportSearch(e.target.value); + setImportPage(1); + }} + /> + { + setImportCkStatus(val || ''); + setImportPage(1); + }} + /> + + + + + + rowKey="id" + size="small" + loading={importLoading} + columns={importColumns} + dataSource={importPool} + rowSelection={{ + selectedRowKeys: importSelectedIds, + preserveSelectedRowKeys: true, + onChange: (keys) => setImportSelectedIds(keys.map(Number)), + }} + pagination={{ + current: importPage, + pageSize: importPageSize, + total: importTotal, + showSizeChanger: false, + showTotal: (t) => `共 ${t} 条`, + onChange: (p) => setImportPage(p), + }} + /> + + + + + + ); +}