From ecb987fff049c4ba7f4b4db50a69bc969dc338db Mon Sep 17 00:00:00 2001 From: yml Date: Mon, 30 Nov 2026 18:25:20 +0800 Subject: [PATCH] =?UTF-8?q?feat(douyu):=20=E6=9F=A5=E8=AF=A2=E5=B7=A5?= =?UTF-8?q?=E4=BD=9C=E5=8F=B0=E5=A2=9E=E5=8A=A0=E5=AE=9D=E5=85=B8=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E4=B8=8E=E5=88=B0=E6=9C=9F=E6=97=B6=E9=97=B4=20(v0.4.?= =?UTF-8?q?28)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- pyproject.toml | 2 +- tests/test_douyu_query_workbench.py | 45 +++++++++++-- uv.lock | 2 +- web/backend/routers/douyu.py | 26 ++++++++ web/backend/services/douyu_runner_overview.py | 65 +++++++++++++++++-- web/backend/services/douyu_service.py | 2 +- .../src/pages/DouyuQueryWorkbenchPage.tsx | 43 ++++++++++-- 8 files changed, 168 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index ed7b3b9..01c623b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 直播账号运营后台 -斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.27)。 +斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.28)。 ## 能做什么 diff --git a/pyproject.toml b/pyproject.toml index c59621a..f5aaf5b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "live-hub-py" -version = "0.4.27" +version = "0.4.28" 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 index b664f8b..00a14c2 100644 --- a/tests/test_douyu_query_workbench.py +++ b/tests/test_douyu_query_workbench.py @@ -102,6 +102,21 @@ class _QueryHarness(OverviewMixin, BindMixin, DouyuBatchRunnerCore): "points_query": {"raw": {"data": {"willExpireTime": "1800000000"}}}, } + def _refresh_elite_handbook(self, client, account, *, manual_id, rid=""): + del client, manual_id, rid + if "elite" in self.fail_helpers: + raise RuntimeError("模拟宝典接口异常") + account.elite_opened = True + account.elite_expire_time = 1800000000 + return { + "elite_manual_type": 1, + "elite_manual_score": 888, + "elite_expire_time": 1800000000, + "elite_opened": True, + "elite_expired": False, + "points": 888, + } + class TestQueryAssetsAndBindExecution: def setup_method(self): @@ -177,15 +192,24 @@ class TestQueryAssetsAndBindExecution: self.task, self.account, self.account.cookie, - {"bind_act_alias": "B1", "confirm_act_alias": "C1"}, + { + "manual_id": "M1", + "rid": "R1", + "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 res["elite_opened"] is True + assert res["elite_expire_time"] == 1800000000 assert self.account.gold_balance == 66 assert self.account.points == 888 + assert self.account.elite_opened is True + assert self.account.elite_expire_time == 1800000000 assert self.account.points_expire_at is not None assert self.account.role_bind_status == "bound" assert self.account.game_name == "测试召唤师" @@ -213,7 +237,7 @@ class TestQueryAssetsAndBindExecution: self.task, self.account, self.account.cookie, - {"bind_act_alias": "B1"}, + {"manual_id": "M1", "bind_act_alias": "B1"}, ) assert h.marked["status"] == "success" assert "gold" in h.marked["result"]["errors"] @@ -231,16 +255,17 @@ class TestQueryAssetsAndBindExecution: "errors": ["角色接口500"], }, ) - h = _QueryHarness(fail_helpers={"gold", "points"}) + h = _QueryHarness(fail_helpers={"gold", "elite", "points"}) h._execute_query_assets_and_bind( self.session, self.task, self.account, self.account.cookie, - {}, + {"manual_id": "M1"}, ) assert h.marked["status"] == "failed" assert "gold" in h.marked["message"] + assert "elite" in h.marked["message"] assert "points" in h.marked["message"] assert "bind" in h.marked["message"] @@ -286,6 +311,8 @@ class TestQueryWorkbenchRouterAndExport: game_channel="微信 / 苹果", role_change_available_at=now - timedelta(hours=1), role_change_official_at=now - timedelta(hours=1), + elite_opened=True, + elite_expire_time=1893456000, assigned_to=self.support_with_login.id, ) self.acc_invalid_ck = Account( @@ -303,6 +330,8 @@ class TestQueryWorkbenchRouterAndExport: role_bind_status="bound", game_name="角色B", role_change_available_at=now + timedelta(hours=5), + elite_opened=False, + elite_expire_time=1, assigned_to=self.support_with_login.id, ) self.acc_no_ck = Account( @@ -480,8 +509,12 @@ class TestQueryWorkbenchRouterAndExport: assert rows[2][2] == '\'=HYPERLINK("https://example.invalid")' assert rows[2][8] == "100" assert rows[2][10] == "1280" - assert rows[2][15] == "可换绑" - assert rows[3][15] == "冷却中" + assert rows[1][12] == "未查询" + assert rows[2][12] == "已开通" + assert rows[2][13].startswith("2030-01-01") + assert rows[3][12] == "已过期" + assert rows[2][17] == "可换绑" + assert rows[3][17] == "冷却中" def test_relogin_requires_login_batch_permission(self): with pytest.raises(HTTPException) as exc: diff --git a/uv.lock b/uv.lock index b509169..08eca9b 100644 --- a/uv.lock +++ b/uv.lock @@ -381,7 +381,7 @@ wheels = [ [[package]] name = "live-hub-py" -version = "0.4.27" +version = "0.4.28" source = { editable = "." } dependencies = [ { name = "alembic" }, diff --git a/web/backend/routers/douyu.py b/web/backend/routers/douyu.py index b23167b..1b8859a 100644 --- a/web/backend/routers/douyu.py +++ b/web/backend/routers/douyu.py @@ -1303,6 +1303,27 @@ def _csv_safe_cell(value: Any) -> Any: return value +def _elite_status_label(account: Account, now_seconds: int) -> str: + expire_time = int(account.elite_expire_time or 0) + if expire_time > 0 and expire_time <= now_seconds: + return "已过期" + if account.elite_opened is True: + return "已开通" + if account.elite_opened is False: + return "未开通" + return "未查询" + + +def _format_shanghai_unix_seconds(value: int | None) -> str: + if value is None or int(value) <= 0: + return "" + return ( + datetime.fromtimestamp(int(value), tz=UTC) + .astimezone(_SHANGHAI_TZ) + .strftime("%Y-%m-%d %H:%M:%S") + ) + + @router.post("/query-workbench/lookup") def lookup_query_workbench_accounts( req: DouyuQueryWorkbenchLookupRequest, @@ -1559,6 +1580,7 @@ def export_query_workbench_csv( ordered_accounts = [rows_by_id[aid] for aid in requested_ids if aid in rows_by_id] now = datetime.now(UTC) + now_seconds = int(now.timestamp()) output = io.StringIO() writer = csv.writer(output) writer.writerow( @@ -1575,6 +1597,8 @@ def export_query_workbench_csv( "兑换余额", "积分", "积分到期时间", + "宝典状态", + "宝典到期时间", "绑定状态", "绑定角色", "绑定渠道", @@ -1644,6 +1668,8 @@ def export_query_workbench_csv( acc.exchange_balance if acc.exchange_balance is not None else "", acc.points if acc.points is not None else "", _format_shanghai_dt(acc.points_expire_at), + _elite_status_label(acc, now_seconds), + _format_shanghai_unix_seconds(acc.elite_expire_time), bind_label, acc.game_name or "", acc.game_channel or "", diff --git a/web/backend/services/douyu_runner_overview.py b/web/backend/services/douyu_runner_overview.py index f85a558..d588d49 100644 --- a/web/backend/services/douyu_runner_overview.py +++ b/web/backend/services/douyu_runner_overview.py @@ -213,6 +213,14 @@ class OverviewMixin: *, ctn: Any = None, ) -> dict[str, Any]: ... + def _refresh_elite_handbook( + self, + client: DouyuActivityClient, + account: Account, + *, + manual_id: str, + rid: str = "", + ) -> dict[str, Any]: ... def _pick_change_wait_bind_info( self, candidates: list[dict], config: dict ) -> dict | None: ... @@ -1094,7 +1102,7 @@ class OverviewMixin: 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] = {} @@ -1110,6 +1118,9 @@ class OverviewMixin: ), "role_bind_status": account.role_bind_status or "unknown", "game_name": account.game_name or "", + "elite_opened": account.elite_opened, + "elite_expire_time": account.elite_expire_time, + "elite_expired": False, "change_role_wait_time": None, "role_change_available_at": None, "role_change_official_at": None, @@ -1135,7 +1146,49 @@ class OverviewMixin: except Exception as exc: # noqa: BLE001 外部接口边界需要独立容错 errors["gold"] = _err(exc) - # 2. 积分与到期时间 + # 2. 精英宝典状态与官方到期时间 + elite_ok = False + elite_label = "" + try: + manual_id = str(config.get("manual_id") or "").strip() + if not manual_id: + raise RuntimeError("未配置精英宝典 manualID") + elite = self._refresh_elite_handbook( + client, + account, + manual_id=manual_id, + rid=str(config.get("rid") or ""), + ) + expire_time = elite.get("elite_expire_time") + payload["elite_opened"] = elite.get("elite_opened") + payload["elite_expire_time"] = expire_time or None + payload["elite_expired"] = bool(elite.get("elite_expired")) + payload["points"] = account.points + record_sync_success( + db, + account_id=int(account.id), + domain=DOMAIN_ELITE, + source="douyu_task.query_assets_and_bind", + observed_at=queried_at, + raw_payload=elite, + task_id=task.id, + ) + elite_ok = True + if elite.get("elite_expired"): + elite_label = "宝典已过期" + elif elite.get("elite_opened"): + elite_label = "宝典已开通" + else: + elite_label = "宝典未开通" + if expire_time: + expire_at = datetime.fromtimestamp( + int(expire_time), tz=UTC + ).astimezone() + elite_label += f"(到期 {expire_at:%Y-%m-%d %H:%M})" + except Exception as exc: # noqa: BLE001 + errors["elite"] = _err(exc) + + # 3. 积分与到期时间 points_ok = False try: ctn = query_csrf(client) @@ -1163,7 +1216,7 @@ class OverviewMixin: except Exception as exc: # noqa: BLE001 errors["points"] = _err(exc) - # 3. 绑定角色与换绑时间(合并本地 7 天锁) + # 4. 绑定角色与换绑时间(合并本地 7 天锁) bind_ok = False bind_label = "" try: @@ -1263,13 +1316,17 @@ class OverviewMixin: f"鱼翅 {payload['gold_balance'] if payload['gold_balance'] is not None else '-'}", f"积分 {payload['points'] if payload['points'] is not None else '-'}", ] + if elite_label: + parts.append(elite_label) + elif "elite" in errors: + parts.append(f"宝典查询失败: {errors['elite']}") 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): + if not (gold_ok or elite_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 diff --git a/web/backend/services/douyu_service.py b/web/backend/services/douyu_service.py index 18a4241..7628cc9 100644 --- a/web/backend/services/douyu_service.py +++ b/web/backend/services/douyu_service.py @@ -53,7 +53,7 @@ SUPPORTED_DOUYU_TASK_TYPES = { "query_change_bind_time": "一键查询换绑时间", # 跨域聚合查询:鱼翅/积分/精英/电竞/小店/兑换记录/高价值套装是否已拥有 "query_account_overview": "一键查询账号信息", - "query_assets_and_bind": "一键查询鱼翅/积分/换绑时间", + "query_assets_and_bind": "一键查询鱼翅/积分/宝典/换绑时间", "query_gold_balance": "一键查询鱼翅余额", "query_exchange_records": "一键查询兑换记录", "prefetch_csrf_token": "一键获取兑换 CSRF Token", diff --git a/web/frontend/src/pages/DouyuQueryWorkbenchPage.tsx b/web/frontend/src/pages/DouyuQueryWorkbenchPage.tsx index f0be77b..56b2a1e 100644 --- a/web/frontend/src/pages/DouyuQueryWorkbenchPage.tsx +++ b/web/frontend/src/pages/DouyuQueryWorkbenchPage.tsx @@ -41,7 +41,7 @@ import { } from '../api/modules'; import { usePermissions } from '../hooks/usePermissions'; import { getErrorMessage } from '../utils/error'; -import { formatTime } from '../utils/time'; +import { formatTime, formatUnixSeconds } from '../utils/time'; import { message } from '../utils/antdMessage'; import { formatWaitSeconds, @@ -734,6 +734,39 @@ export default function DouyuQueryWorkbenchPage() { ), }, + { + title: '宝典状态 / 到期', + width: 190, + render: (_, record) => { + const expireSeconds = Number(record.elite_expire_time || 0); + const expired = expireSeconds > 0 && expireSeconds <= nowSeconds; + const opened = record.elite_opened === true && !expired; + const label = expired + ? '已过期' + : opened + ? '已开通' + : record.elite_opened === false + ? '未开通' + : '未查询'; + const color = expired ? 'error' : opened ? 'success' : 'default'; + return ( + + + {label} + + {expireSeconds > 0 ? ( + + 到期: {formatUnixSeconds(expireSeconds)} + + ) : record.elite_opened === true ? ( + + 官方未返回到期时间 + + ) : null} + + ); + }, + }, { title: '绑定角色', width: 190, @@ -900,7 +933,7 @@ export default function DouyuQueryWorkbenchPage() { ]; return ( - +