feat(douyu): 新增斗鱼查询工作台与失效CK人工重登预算支持 (v0.4.26)
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
# 直播账号运营后台
|
# 直播账号运营后台
|
||||||
|
|
||||||
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.25)。
|
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.26)。
|
||||||
|
|
||||||
## 能做什么
|
## 能做什么
|
||||||
|
|
||||||
|
|||||||
@@ -82,4 +82,8 @@
|
|||||||
- Go 前端复用同一套 `web/frontend`,合并 `main` 后需确认以下能力在 Go 网关路由下全部接通并跑过契约测试:
|
- Go 前端复用同一套 `web/frontend`,合并 `main` 后需确认以下能力在 Go 网关路由下全部接通并跑过契约测试:
|
||||||
1. `efcbd9a`:斗鱼批量支付弹窗双码大间距扫码样式与补位刷新(纯前端 + 既有用例对齐);
|
1. `efcbd9a`:斗鱼批量支付弹窗双码大间距扫码样式与补位刷新(纯前端 + 既有用例对齐);
|
||||||
2. `cc78208`:`DouyuCollabPage.tsx`「查看归档 → 释放归档账号回池」弹窗(预览 / 执行两接口需在 Go 路由及网关白名单注册);
|
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`。
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "live-hub-py"
|
name = "live-hub-py"
|
||||||
version = "0.4.25"
|
version = "0.4.26"
|
||||||
description = "直播账号运营 Web 后台"
|
description = "直播账号运营 Web 后台"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.12,<3.13"
|
requires-python = ">=3.12,<3.13"
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -381,7 +381,7 @@ wheels = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "live-hub-py"
|
name = "live-hub-py"
|
||||||
version = "0.4.25"
|
version = "0.4.26"
|
||||||
source = { editable = "." }
|
source = { editable = "." }
|
||||||
dependencies = [
|
dependencies = [
|
||||||
{ name = "alembic" },
|
{ name = "alembic" },
|
||||||
|
|||||||
+593
-20
@@ -3,10 +3,14 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
import secrets
|
import secrets
|
||||||
|
import uuid
|
||||||
from datetime import UTC, datetime, timedelta
|
from datetime import UTC, datetime, timedelta
|
||||||
from typing import Any, cast
|
from typing import Any, cast
|
||||||
from weakref import WeakKeyDictionary
|
from weakref import WeakKeyDictionary
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
from fastapi import (
|
from fastapi import (
|
||||||
APIRouter,
|
APIRouter,
|
||||||
@@ -15,6 +19,7 @@ from fastapi import (
|
|||||||
HTTPException,
|
HTTPException,
|
||||||
Query,
|
Query,
|
||||||
Request,
|
Request,
|
||||||
|
Response,
|
||||||
UploadFile,
|
UploadFile,
|
||||||
WebSocket,
|
WebSocket,
|
||||||
WebSocketDisconnect,
|
WebSocketDisconnect,
|
||||||
@@ -46,6 +51,8 @@ from ..models import (
|
|||||||
DouyuWorkbenchAccount,
|
DouyuWorkbenchAccount,
|
||||||
DouyuXpdGoodsSnapshot,
|
DouyuXpdGoodsSnapshot,
|
||||||
ExecutionJob,
|
ExecutionJob,
|
||||||
|
LoginAttempt,
|
||||||
|
LoginTask,
|
||||||
PlatformFulfillmentTask,
|
PlatformFulfillmentTask,
|
||||||
User,
|
User,
|
||||||
)
|
)
|
||||||
@@ -58,6 +65,9 @@ from ..schemas import (
|
|||||||
DouyuConfigUpdate,
|
DouyuConfigUpdate,
|
||||||
DouyuExchangeResultImageOut,
|
DouyuExchangeResultImageOut,
|
||||||
DouyuGoodsOut,
|
DouyuGoodsOut,
|
||||||
|
DouyuQueryWorkbenchExportRequest,
|
||||||
|
DouyuQueryWorkbenchLookupRequest,
|
||||||
|
DouyuQueryWorkbenchReloginRequest,
|
||||||
DouyuSupplyTargetConfigOut,
|
DouyuSupplyTargetConfigOut,
|
||||||
DouyuSupplyTargetOut,
|
DouyuSupplyTargetOut,
|
||||||
DouyuSupplyTargetUpdate,
|
DouyuSupplyTargetUpdate,
|
||||||
@@ -107,6 +117,7 @@ from ..services.douyu_service import (
|
|||||||
DOUYU_ACTIVE_TASK_STATUSES,
|
DOUYU_ACTIVE_TASK_STATUSES,
|
||||||
DOUYU_CONFIG_FIELDS,
|
DOUYU_CONFIG_FIELDS,
|
||||||
DOUYU_HANDBOOK_TASK_TYPES,
|
DOUYU_HANDBOOK_TASK_TYPES,
|
||||||
|
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES,
|
||||||
SUPPORTED_DOUYU_TASK_TYPES,
|
SUPPORTED_DOUYU_TASK_TYPES,
|
||||||
DouyuActivePaymentError,
|
DouyuActivePaymentError,
|
||||||
DouyuLeaseConflictError,
|
DouyuLeaseConflictError,
|
||||||
@@ -123,10 +134,14 @@ from ..services.douyu_service import (
|
|||||||
)
|
)
|
||||||
from ..services.execution_jobs import (
|
from ..services.execution_jobs import (
|
||||||
JOB_DOUYU_BATCH,
|
JOB_DOUYU_BATCH,
|
||||||
|
JOB_LOGIN_BATCH,
|
||||||
|
JOB_RELOGIN_BATCH,
|
||||||
|
LANE_AUTH,
|
||||||
LANE_FULFILLMENT,
|
LANE_FULFILLMENT,
|
||||||
STATUS_QUEUED,
|
STATUS_QUEUED,
|
||||||
STATUS_RUNNING,
|
STATUS_RUNNING,
|
||||||
TERMINAL_STATUSES,
|
TERMINAL_STATUSES,
|
||||||
|
enqueue_execution_job,
|
||||||
event_payload,
|
event_payload,
|
||||||
execution_events_after,
|
execution_events_after,
|
||||||
get_execution_job,
|
get_execution_job,
|
||||||
@@ -134,6 +149,11 @@ from ..services.execution_jobs import (
|
|||||||
)
|
)
|
||||||
from ..services.file_service import FileUploadError
|
from ..services.file_service import FileUploadError
|
||||||
from ..services.file_storage import StorageUnavailableError, max_upload_size_bytes
|
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
|
from ..services.platform_fulfillment import service as platform_fulfillment_service
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/douyu", tags=["斗鱼活动"])
|
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")
|
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,不能让账号从工作台消失。
|
重登失败(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))
|
||||||
query = (
|
if not include_all:
|
||||||
db.query(Account)
|
cookie_ids = select(Account.id).where(cookie_holding_filter())
|
||||||
.options(joinedload(Account.assigned_user))
|
query = query.filter(Account.id.in_(cookie_ids))
|
||||||
.filter(Account.id.in_(cookie_ids))
|
|
||||||
)
|
|
||||||
if _can_view_all(current):
|
if _can_view_all(current):
|
||||||
return query
|
return query
|
||||||
if user_has_permission(current, "account:view_assigned"):
|
if user_has_permission(current, "account:view_assigned"):
|
||||||
@@ -617,8 +638,9 @@ def _apply_task_account_filters(
|
|||||||
tag: str = "",
|
tag: str = "",
|
||||||
account_names: str = "",
|
account_names: str = "",
|
||||||
ids: str = "",
|
ids: str = "",
|
||||||
|
ck_status: str = "",
|
||||||
):
|
):
|
||||||
"""按工作台导入弹窗的搜索、标签、多行账号名筛选任务账号。"""
|
"""按工作台导入弹窗的搜索、标签、多行账号名与 CK/冷却状态筛选任务账号。"""
|
||||||
id_list = [
|
id_list = [
|
||||||
int(item)
|
int(item)
|
||||||
for item in dict.fromkeys(
|
for item in dict.fromkeys(
|
||||||
@@ -633,6 +655,43 @@ def _apply_task_account_filters(
|
|||||||
selected_names = _parse_account_names(account_names)
|
selected_names = _parse_account_names(account_names)
|
||||||
if selected_names:
|
if selected_names:
|
||||||
query = query.filter(Account.username.in_(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()
|
search_text = (search or "").strip()
|
||||||
if search_text:
|
if search_text:
|
||||||
pattern = f"%{search_text}%"
|
pattern = f"%{search_text}%"
|
||||||
@@ -673,7 +732,56 @@ def _order_task_accounts(
|
|||||||
return query.order_by(Account.id.desc())
|
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
|
elite_cooldown = account.role_bind_status == BIND_BOUND
|
||||||
esports_cooldown = account.esports_bind_status == BIND_BOUND
|
esports_cooldown = account.esports_bind_status == BIND_BOUND
|
||||||
return DouyuTaskAccountOut(
|
return DouyuTaskAccountOut(
|
||||||
@@ -714,6 +822,18 @@ def _account_out(account: Account) -> DouyuTaskAccountOut:
|
|||||||
assigned_username=account.assigned_user.username
|
assigned_username=account.assigned_user.username
|
||||||
if account.assigned_user
|
if account.assigned_user
|
||||||
else None,
|
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(""),
|
tag: str = Query(""),
|
||||||
ids: str = Query(""),
|
ids: str = Query(""),
|
||||||
account_names: str = Query(""),
|
account_names: str = Query(""),
|
||||||
|
ck_status: str = "",
|
||||||
|
include_all: bool = False,
|
||||||
page: int | None = Query(None, ge=1),
|
page: int | None = Query(None, ge=1),
|
||||||
page_size: int = Query(50, ge=1, le=200),
|
page_size: int = Query(50, ge=1, le=200),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
current: User = Depends(get_current_user),
|
current: User = Depends(get_current_user),
|
||||||
):
|
):
|
||||||
"""查看可执行斗鱼任务的账号(必须有成功 Cookie)。
|
"""查看斗鱼账号。默认只返回持有 Cookie 的可执行账号;include_all=true 时返回全部可见账号(供查询工作台使用)。"""
|
||||||
|
|
||||||
tag 按账号标签精确筛选;ids 为逗号分隔的账号 ID,用于工作台按已导入账号过滤;
|
|
||||||
account_names 为多行斗鱼账户名(每行一个),按粘贴顺序精确匹配;为空时返回全部。
|
|
||||||
"""
|
|
||||||
query, selected_names, selected_ids = _apply_task_account_filters(
|
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,
|
search=search,
|
||||||
tag=tag,
|
tag=tag,
|
||||||
account_names=account_names,
|
account_names=account_names,
|
||||||
ids=ids,
|
ids=ids,
|
||||||
|
ck_status=ck_status,
|
||||||
)
|
)
|
||||||
total = None
|
total = None
|
||||||
if page is not None:
|
if page is not None:
|
||||||
@@ -906,7 +1025,15 @@ def list_task_accounts(
|
|||||||
query = query.offset((page - 1) * page_size).limit(page_size)
|
query = query.offset((page - 1) * page_size).limit(page_size)
|
||||||
else:
|
else:
|
||||||
query = query.limit(500)
|
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:
|
if page is not None:
|
||||||
return {
|
return {
|
||||||
"items": result,
|
"items": result,
|
||||||
@@ -922,15 +1049,18 @@ def list_task_account_ids(
|
|||||||
search: str = Query(""),
|
search: str = Query(""),
|
||||||
tag: str = Query(""),
|
tag: str = Query(""),
|
||||||
account_names: str = Query(""),
|
account_names: str = Query(""),
|
||||||
|
ck_status: str = "",
|
||||||
|
include_all: bool = False,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
current: User = Depends(get_current_user),
|
current: User = Depends(get_current_user),
|
||||||
):
|
):
|
||||||
"""返回当前用户可导入工作台的全部账号 ID,不受列表分页限制。"""
|
"""返回当前用户可导入工作台的全部账号 ID,不受列表分页限制。"""
|
||||||
query, selected_names, selected_ids = _apply_task_account_filters(
|
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,
|
search=search,
|
||||||
tag=tag,
|
tag=tag,
|
||||||
account_names=account_names,
|
account_names=account_names,
|
||||||
|
ck_status=ck_status,
|
||||||
)
|
)
|
||||||
account_ids = [
|
account_ids = [
|
||||||
account_id
|
account_id
|
||||||
@@ -993,7 +1123,7 @@ def relogin_invalid_task_accounts(
|
|||||||
|
|
||||||
@router.get("/workbench-accounts")
|
@router.get("/workbench-accounts")
|
||||||
def list_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),
|
db: Session = Depends(get_db),
|
||||||
current: User = Depends(get_current_user),
|
current: User = Depends(get_current_user),
|
||||||
):
|
):
|
||||||
@@ -1070,6 +1200,449 @@ def update_workbench_accounts(
|
|||||||
return {"account_ids": account_ids, "success": True}
|
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)
|
@router.get("/config", response_model=DouyuConfigOut)
|
||||||
def get_config(
|
def get_config(
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
@@ -1792,7 +2365,7 @@ async def create_task_batch(
|
|||||||
@router.get("/tasks")
|
@router.get("/tasks")
|
||||||
def list_tasks(
|
def list_tasks(
|
||||||
batch_id: str | None = None,
|
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,
|
workbench_only: bool = False,
|
||||||
include_detail: bool = Query(
|
include_detail: bool = Query(
|
||||||
False, description="是否返回完整任务结果(默认否,轮询请保持 false)"
|
False, description="是否返回完整任务结果(默认否,轮询请保持 false)"
|
||||||
|
|||||||
+23
-2
@@ -1887,7 +1887,7 @@ class PlatformFulfillmentCollabSyncRequest(BaseModel):
|
|||||||
class DouyuTaskBatchRequest(BaseModel):
|
class DouyuTaskBatchRequest(BaseModel):
|
||||||
account_ids: list[int]
|
account_ids: list[int]
|
||||||
task_type: str
|
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)
|
concurrency: int = Field(5, ge=1, le=15)
|
||||||
payload: dict[str, Any] = Field(default_factory=dict)
|
payload: dict[str, Any] = Field(default_factory=dict)
|
||||||
platform_task_id: int | None = Field(None, gt=0)
|
platform_task_id: int | None = Field(None, gt=0)
|
||||||
@@ -1897,10 +1897,23 @@ class DouyuTaskBatchRequest(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class DouyuWorkbenchAccountsUpdate(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)
|
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):
|
class DouyuTaskOut(BaseModel):
|
||||||
id: int
|
id: int
|
||||||
batch_id: str
|
batch_id: str
|
||||||
@@ -2010,6 +2023,14 @@ class DouyuTaskAccountOut(BaseModel):
|
|||||||
xpd_bind_label: str = ""
|
xpd_bind_label: str = ""
|
||||||
assigned_to: int | None = None
|
assigned_to: int | None = None
|
||||||
assigned_username: str | 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):
|
class DouyuXpdGoodsOut(BaseModel):
|
||||||
|
|||||||
@@ -68,6 +68,7 @@ RETIRED_NOISE_TASK_TYPES: tuple[str, ...] = (
|
|||||||
#: 只读、看一眼就走,且前端**不**拿它派生账号状态 → 短保留。
|
#: 只读、看一眼就走,且前端**不**拿它派生账号状态 → 短保留。
|
||||||
NOISE_TASK_TYPES: tuple[str, ...] = (
|
NOISE_TASK_TYPES: tuple[str, ...] = (
|
||||||
*RETIRED_NOISE_TASK_TYPES,
|
*RETIRED_NOISE_TASK_TYPES,
|
||||||
|
"query_assets_and_bind",
|
||||||
"query_change_bind_time",
|
"query_change_bind_time",
|
||||||
"query_gold_balance",
|
"query_gold_balance",
|
||||||
"query_xpd_balance",
|
"query_xpd_balance",
|
||||||
|
|||||||
@@ -237,6 +237,7 @@ class DouyuBatchRunner(
|
|||||||
"query_game_name": self._execute_query_game_name,
|
"query_game_name": self._execute_query_game_name,
|
||||||
"query_change_bind_time": self._execute_query_change_bind_time,
|
"query_change_bind_time": self._execute_query_change_bind_time,
|
||||||
"query_account_overview": self._execute_query_account_overview,
|
"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_gold_balance": self._execute_query_gold_balance,
|
||||||
"query_exchange_records": self._execute_query_exchange_records,
|
"query_exchange_records": self._execute_query_exchange_records,
|
||||||
"prefetch_csrf_token": self._execute_prefetch_csrf_token,
|
"prefetch_csrf_token": self._execute_prefetch_csrf_token,
|
||||||
|
|||||||
@@ -202,6 +202,11 @@ class OverviewMixin:
|
|||||||
def _client(self, cookie: str) -> DouyuActivityClient: ...
|
def _client(self, cookie: str) -> DouyuActivityClient: ...
|
||||||
def _mark_task(self, *args: Any, **kwargs: Any) -> None: ...
|
def _mark_task(self, *args: Any, **kwargs: Any) -> None: ...
|
||||||
def _push_log(self, level: str, message: str) -> 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:
|
def _overview_view(self, task: DouyuTask) -> str:
|
||||||
result = task.result if isinstance(task.result, dict) else {}
|
result = task.result if isinstance(task.result, dict) else {}
|
||||||
@@ -1083,3 +1088,193 @@ class OverviewMixin:
|
|||||||
|
|
||||||
logger.info(f"[douyu] 一键查询账号 {account.id}: {message}")
|
logger.info(f"[douyu] 一键查询账号 {account.id}: {message}")
|
||||||
self._mark_task(db, task, "success", message, overview)
|
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_change_bind_time": "一键查询换绑时间",
|
||||||
# 跨域聚合查询:鱼翅/积分/精英/电竞/小店/兑换记录/高价值套装是否已拥有
|
# 跨域聚合查询:鱼翅/积分/精英/电竞/小店/兑换记录/高价值套装是否已拥有
|
||||||
"query_account_overview": "一键查询账号信息",
|
"query_account_overview": "一键查询账号信息",
|
||||||
|
"query_assets_and_bind": "一键查询鱼翅/积分/换绑时间",
|
||||||
"query_gold_balance": "一键查询鱼翅余额",
|
"query_gold_balance": "一键查询鱼翅余额",
|
||||||
"query_exchange_records": "一键查询兑换记录",
|
"query_exchange_records": "一键查询兑换记录",
|
||||||
"prefetch_csrf_token": "一键获取兑换 CSRF Token",
|
"prefetch_csrf_token": "一键获取兑换 CSRF Token",
|
||||||
@@ -69,7 +70,7 @@ SUPPORTED_DOUYU_TASK_TYPES = {
|
|||||||
|
|
||||||
BINDING_POLL_CLEANUP_GRACE_SECONDS = 120
|
BINDING_POLL_CLEANUP_GRACE_SECONDS = 120
|
||||||
|
|
||||||
DOUYU_HANDBOOK_SCOPES = {"elite", "esports", "peace"}
|
DOUYU_HANDBOOK_SCOPES = {"elite", "esports", "peace", "query"}
|
||||||
DOUYU_HANDBOOK_TASK_TYPES = {
|
DOUYU_HANDBOOK_TASK_TYPES = {
|
||||||
"elite": {
|
"elite": {
|
||||||
"get_bind_qr",
|
"get_bind_qr",
|
||||||
@@ -88,6 +89,7 @@ DOUYU_HANDBOOK_TASK_TYPES = {
|
|||||||
"query_exchange_records",
|
"query_exchange_records",
|
||||||
"prefetch_csrf_token",
|
"prefetch_csrf_token",
|
||||||
"query_account_overview",
|
"query_account_overview",
|
||||||
|
"query_assets_and_bind",
|
||||||
},
|
},
|
||||||
"esports": {
|
"esports": {
|
||||||
"prepare_esports_bind",
|
"prepare_esports_bind",
|
||||||
@@ -117,6 +119,13 @@ DOUYU_HANDBOOK_TASK_TYPES = {
|
|||||||
"exchange_xpd_goods",
|
"exchange_xpd_goods",
|
||||||
"query_account_overview",
|
"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(
|
trigger_source=str(
|
||||||
payload.get("trigger_source", "manual") or "manual"
|
payload.get("trigger_source", "manual") or "manual"
|
||||||
),
|
),
|
||||||
|
category=str(payload.get("category", "") or ""),
|
||||||
batch_id=current_batch_id,
|
batch_id=current_batch_id,
|
||||||
log_sink=log_sink,
|
log_sink=log_sink,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -528,7 +528,21 @@ def get_login_quota_usage_summary(
|
|||||||
quota_day, quota_hour = _bucket(moment)
|
quota_day, quota_hour = _bucket(moment)
|
||||||
setting = db.query(LoginQuotaSetting).filter(LoginQuotaSetting.id == 1).first()
|
setting = db.query(LoginQuotaSetting).filter(LoginQuotaSetting.id == 1).first()
|
||||||
if setting is None:
|
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)
|
protection = load_protection_snapshot(db)
|
||||||
per_account_limit = int(setting.per_account_daily_limit)
|
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 UsersPage = lazy(() => import('./pages/UsersPage'));
|
||||||
const CookiePage = lazy(() => import('./pages/CookiePage'));
|
const CookiePage = lazy(() => import('./pages/CookiePage'));
|
||||||
const DouyuWorkbenchPage = lazy(() => import('./pages/DouyuWorkbenchPage'));
|
const DouyuWorkbenchPage = lazy(() => import('./pages/DouyuWorkbenchPage'));
|
||||||
|
const DouyuQueryWorkbenchPage = lazy(() => import('./pages/DouyuQueryWorkbenchPage'));
|
||||||
const DouyuCollabPage = lazy(() => import('./pages/DouyuCollabPage'));
|
const DouyuCollabPage = lazy(() => import('./pages/DouyuCollabPage'));
|
||||||
const HuyaAccountsPage = lazy(() => import('./pages/HuyaAccountsPage'));
|
const HuyaAccountsPage = lazy(() => import('./pages/HuyaAccountsPage'));
|
||||||
const HuyaAssignmentsPage = lazy(() => import('./pages/HuyaAssignmentsPage'));
|
const HuyaAssignmentsPage = lazy(() => import('./pages/HuyaAssignmentsPage'));
|
||||||
@@ -96,6 +97,7 @@ function AppContent() {
|
|||||||
<Route path="douyu" element={<Navigate to="/douyu/workbench" replace />} />
|
<Route path="douyu" element={<Navigate to="/douyu/workbench" replace />} />
|
||||||
<Route path="douyu/tasks" 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/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/elite" element={<Navigate to="/douyu/workbench?tab=elite" replace />} />
|
||||||
<Route path="douyu/esports" element={<Navigate to="/douyu/workbench?tab=esports" 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 />} />
|
<Route path="douyu/peace" element={<Navigate to="/douyu/workbench?tab=peace" replace />} />
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ import type {
|
|||||||
DouyuConfig,
|
DouyuConfig,
|
||||||
DouyuExchangeResultImage,
|
DouyuExchangeResultImage,
|
||||||
DouyuGoodsItem,
|
DouyuGoodsItem,
|
||||||
|
DouyuQueryWorkbenchInvalidIdsResult,
|
||||||
|
DouyuQueryWorkbenchLookupResult,
|
||||||
|
DouyuQueryWorkbenchManualBudget,
|
||||||
|
DouyuQueryWorkbenchReloginResult,
|
||||||
DouyuRechargeChannel,
|
DouyuRechargeChannel,
|
||||||
DouyuSupplyTarget,
|
DouyuSupplyTarget,
|
||||||
DouyuSupplyTargetConfig,
|
DouyuSupplyTargetConfig,
|
||||||
@@ -63,11 +67,11 @@ export const douyuApi = {
|
|||||||
api.post<DouyuSupplyTarget, DouyuSupplyTarget>('/douyu/supply-targets', data),
|
api.post<DouyuSupplyTarget, DouyuSupplyTarget>('/douyu/supply-targets', data),
|
||||||
updateSupplyTarget: (targetId: number, data: DouyuSupplyTargetUpdate) =>
|
updateSupplyTarget: (targetId: number, data: DouyuSupplyTargetUpdate) =>
|
||||||
api.put<DouyuSupplyTarget, DouyuSupplyTarget>(`/douyu/supply-targets/${targetId}`, data),
|
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 }),
|
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 }),
|
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 }),
|
api.get<{ account_ids: number[]; total: number }, { account_ids: number[]; total: number }>('/douyu/accounts/ids', { params }),
|
||||||
checkAccountsCk: (ids: number[]) =>
|
checkAccountsCk: (ids: number[]) =>
|
||||||
api.post<
|
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 },
|
||||||
{ batch_id: string; count: number; skipped: number; success: boolean }
|
{ batch_id: string; count: number; skipped: number; success: boolean }
|
||||||
>('/douyu/accounts/relogin-invalid', { ids }),
|
>('/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'),
|
getConfig: () => api.get<DouyuConfig, DouyuConfig>('/douyu/config'),
|
||||||
getRechargeChannel: () => api.get<DouyuRechargeChannel, DouyuRechargeChannel>('/douyu/recharge-channel'),
|
getRechargeChannel: () => api.get<DouyuRechargeChannel, DouyuRechargeChannel>('/douyu/recharge-channel'),
|
||||||
updateConfig: (data: Partial<DouyuConfig>) => api.put<DouyuConfig, DouyuConfig>('/douyu/config', data),
|
updateConfig: (data: Partial<DouyuConfig>) => api.put<DouyuConfig, DouyuConfig>('/douyu/config', data),
|
||||||
@@ -89,7 +113,7 @@ export const douyuApi = {
|
|||||||
createTasks: (data: DouyuTaskBatchRequest) =>
|
createTasks: (data: DouyuTaskBatchRequest) =>
|
||||||
api.post<DouyuTaskBatchResult, DouyuTaskBatchResult>('/douyu/tasks/batch', data),
|
api.post<DouyuTaskBatchResult, DouyuTaskBatchResult>('/douyu/tasks/batch', data),
|
||||||
listTasks: (
|
listTasks: (
|
||||||
handbookScope: 'elite' | 'esports' | 'peace',
|
handbookScope: 'elite' | 'esports' | 'peace' | 'query',
|
||||||
batchId?: string,
|
batchId?: string,
|
||||||
workbenchOnly = false,
|
workbenchOnly = false,
|
||||||
pageSize = 100,
|
pageSize = 100,
|
||||||
@@ -102,11 +126,11 @@ export const douyuApi = {
|
|||||||
page_size: pageSize,
|
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', {
|
api.get<{ account_ids: number[]; configured: boolean }, { account_ids: number[]; configured: boolean }>('/douyu/workbench-accounts', {
|
||||||
params: { handbook_scope: handbookScope },
|
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 }>(
|
api.put<{ account_ids: number[]; success: boolean }, { account_ids: number[]; success: boolean }>(
|
||||||
'/douyu/workbench-accounts', { handbook_scope: handbookScope, account_ids: accountIds },
|
'/douyu/workbench-accounts', { handbook_scope: handbookScope, account_ids: accountIds },
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -795,6 +795,14 @@ export interface DouyuTaskAccountItem {
|
|||||||
xpd_bind_label: string;
|
xpd_bind_label: string;
|
||||||
assigned_to: number | null;
|
assigned_to: number | null;
|
||||||
assigned_username: string | 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 {
|
export interface DouyuSupplyTargetStatus {
|
||||||
@@ -1024,7 +1032,7 @@ export interface DouyuRechargeChannel {
|
|||||||
export interface DouyuTaskBatchRequest {
|
export interface DouyuTaskBatchRequest {
|
||||||
account_ids: number[];
|
account_ids: number[];
|
||||||
task_type: string;
|
task_type: string;
|
||||||
handbook_scope: "elite" | "esports" | "peace";
|
handbook_scope: "elite" | "esports" | "peace" | "query";
|
||||||
concurrency?: number;
|
concurrency?: number;
|
||||||
payload?: Record<string, unknown>;
|
payload?: Record<string, unknown>;
|
||||||
platform_task_id?: number;
|
platform_task_id?: number;
|
||||||
@@ -1033,6 +1041,49 @@ export interface DouyuTaskBatchRequest {
|
|||||||
reuse_active_payment?: boolean;
|
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 {
|
export interface DouyuOccupiedForceCandidate {
|
||||||
account_id: number;
|
account_id: number;
|
||||||
account_name: string;
|
account_name: string;
|
||||||
@@ -1067,7 +1118,7 @@ export interface DouyuTaskItem {
|
|||||||
account_uid: string;
|
account_uid: string;
|
||||||
account_nickname: string;
|
account_nickname: string;
|
||||||
task_type: string;
|
task_type: string;
|
||||||
handbook_scope: "elite" | "esports" | "peace" | "legacy";
|
handbook_scope: "elite" | "esports" | "peace" | "query" | "legacy";
|
||||||
status: string;
|
status: string;
|
||||||
message: string;
|
message: string;
|
||||||
binding: DouyuBindingView;
|
binding: DouyuBindingView;
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import {
|
|||||||
SunOutlined, MoonOutlined, DesktopOutlined, GiftOutlined, ApartmentOutlined, MobileOutlined, ShoppingCartOutlined,
|
SunOutlined, MoonOutlined, DesktopOutlined, GiftOutlined, ApartmentOutlined, MobileOutlined, ShoppingCartOutlined,
|
||||||
BookOutlined, GlobalOutlined,
|
BookOutlined, GlobalOutlined,
|
||||||
SafetyCertificateOutlined, FileSearchOutlined, RobotOutlined, FileExcelOutlined, ThunderboltOutlined,
|
SafetyCertificateOutlined, FileSearchOutlined, RobotOutlined, FileExcelOutlined, ThunderboltOutlined,
|
||||||
ReloadOutlined,
|
ReloadOutlined, SearchOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
||||||
import { getUser, clearAuth, type AuthUser } from '../store/auth';
|
import { getUser, clearAuth, type AuthUser } from '../store/auth';
|
||||||
@@ -95,6 +95,7 @@ export default function MainLayout({ onLogout }: { onLogout?: () => void }) {
|
|||||||
}
|
}
|
||||||
if (can('douyu:task')) {
|
if (can('douyu:task')) {
|
||||||
douyuItems.push({ key: '/douyu/workbench', label: '斗鱼总工作台', icon: <DesktopOutlined /> });
|
douyuItems.push({ key: '/douyu/workbench', label: '斗鱼总工作台', icon: <DesktopOutlined /> });
|
||||||
|
douyuItems.push({ key: '/douyu/query-workbench', label: '查询工作台', icon: <SearchOutlined /> });
|
||||||
}
|
}
|
||||||
|
|
||||||
// 外部单协作:权限独立,客服没有 douyu:task 也要能进共享台账。
|
// 外部单协作:权限独立,客服没有 douyu:task 也要能进共享台账。
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user