feat(douyu): 查询工作台增加宝典状态与到期时间 (v0.4.28)

This commit is contained in:
yml
2026-11-30 18:25:20 +08:00
parent a3529c54a2
commit ecb987fff0
8 changed files with 168 additions and 19 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
# 直播账号运营后台 # 直播账号运营后台
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.27)。 斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.28)。
## 能做什么 ## 能做什么
+1 -1
View File
@@ -1,6 +1,6 @@
[project] [project]
name = "live-hub-py" name = "live-hub-py"
version = "0.4.27" version = "0.4.28"
description = "直播账号运营 Web 后台" description = "直播账号运营 Web 后台"
readme = "README.md" readme = "README.md"
requires-python = ">=3.12,<3.13" requires-python = ">=3.12,<3.13"
+39 -6
View File
@@ -102,6 +102,21 @@ class _QueryHarness(OverviewMixin, BindMixin, DouyuBatchRunnerCore):
"points_query": {"raw": {"data": {"willExpireTime": "1800000000"}}}, "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: class TestQueryAssetsAndBindExecution:
def setup_method(self): def setup_method(self):
@@ -177,15 +192,24 @@ class TestQueryAssetsAndBindExecution:
self.task, self.task,
self.account, self.account,
self.account.cookie, 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" assert h.marked["status"] == "success"
res = h.marked["result"] res = h.marked["result"]
assert res["gold_balance"] == 66 assert res["gold_balance"] == 66
assert res["exchange_balance"] == 12 assert res["exchange_balance"] == 12
assert res["points"] == 888 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.gold_balance == 66
assert self.account.points == 888 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.points_expire_at is not None
assert self.account.role_bind_status == "bound" assert self.account.role_bind_status == "bound"
assert self.account.game_name == "测试召唤师" assert self.account.game_name == "测试召唤师"
@@ -213,7 +237,7 @@ class TestQueryAssetsAndBindExecution:
self.task, self.task,
self.account, self.account,
self.account.cookie, self.account.cookie,
{"bind_act_alias": "B1"}, {"manual_id": "M1", "bind_act_alias": "B1"},
) )
assert h.marked["status"] == "success" assert h.marked["status"] == "success"
assert "gold" in h.marked["result"]["errors"] assert "gold" in h.marked["result"]["errors"]
@@ -231,16 +255,17 @@ class TestQueryAssetsAndBindExecution:
"errors": ["角色接口500"], "errors": ["角色接口500"],
}, },
) )
h = _QueryHarness(fail_helpers={"gold", "points"}) h = _QueryHarness(fail_helpers={"gold", "elite", "points"})
h._execute_query_assets_and_bind( h._execute_query_assets_and_bind(
self.session, self.session,
self.task, self.task,
self.account, self.account,
self.account.cookie, self.account.cookie,
{}, {"manual_id": "M1"},
) )
assert h.marked["status"] == "failed" assert h.marked["status"] == "failed"
assert "gold" in h.marked["message"] assert "gold" in h.marked["message"]
assert "elite" in h.marked["message"]
assert "points" in h.marked["message"] assert "points" in h.marked["message"]
assert "bind" in h.marked["message"] assert "bind" in h.marked["message"]
@@ -286,6 +311,8 @@ class TestQueryWorkbenchRouterAndExport:
game_channel="微信 / 苹果", game_channel="微信 / 苹果",
role_change_available_at=now - timedelta(hours=1), role_change_available_at=now - timedelta(hours=1),
role_change_official_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, assigned_to=self.support_with_login.id,
) )
self.acc_invalid_ck = Account( self.acc_invalid_ck = Account(
@@ -303,6 +330,8 @@ class TestQueryWorkbenchRouterAndExport:
role_bind_status="bound", role_bind_status="bound",
game_name="角色B", game_name="角色B",
role_change_available_at=now + timedelta(hours=5), role_change_available_at=now + timedelta(hours=5),
elite_opened=False,
elite_expire_time=1,
assigned_to=self.support_with_login.id, assigned_to=self.support_with_login.id,
) )
self.acc_no_ck = Account( self.acc_no_ck = Account(
@@ -480,8 +509,12 @@ class TestQueryWorkbenchRouterAndExport:
assert rows[2][2] == '\'=HYPERLINK("https://example.invalid")' assert rows[2][2] == '\'=HYPERLINK("https://example.invalid")'
assert rows[2][8] == "100" assert rows[2][8] == "100"
assert rows[2][10] == "1280" assert rows[2][10] == "1280"
assert rows[2][15] == "可换绑" assert rows[1][12] == "未查询"
assert rows[3][15] == "冷却中" 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): def test_relogin_requires_login_batch_permission(self):
with pytest.raises(HTTPException) as exc: with pytest.raises(HTTPException) as exc:
Generated
+1 -1
View File
@@ -381,7 +381,7 @@ wheels = [
[[package]] [[package]]
name = "live-hub-py" name = "live-hub-py"
version = "0.4.27" version = "0.4.28"
source = { editable = "." } source = { editable = "." }
dependencies = [ dependencies = [
{ name = "alembic" }, { name = "alembic" },
+26
View File
@@ -1303,6 +1303,27 @@ def _csv_safe_cell(value: Any) -> Any:
return value 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") @router.post("/query-workbench/lookup")
def lookup_query_workbench_accounts( def lookup_query_workbench_accounts(
req: DouyuQueryWorkbenchLookupRequest, 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] ordered_accounts = [rows_by_id[aid] for aid in requested_ids if aid in rows_by_id]
now = datetime.now(UTC) now = datetime.now(UTC)
now_seconds = int(now.timestamp())
output = io.StringIO() output = io.StringIO()
writer = csv.writer(output) writer = csv.writer(output)
writer.writerow( 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.exchange_balance if acc.exchange_balance is not None else "",
acc.points if acc.points is not None else "", acc.points if acc.points is not None else "",
_format_shanghai_dt(acc.points_expire_at), _format_shanghai_dt(acc.points_expire_at),
_elite_status_label(acc, now_seconds),
_format_shanghai_unix_seconds(acc.elite_expire_time),
bind_label, bind_label,
acc.game_name or "", acc.game_name or "",
acc.game_channel or "", acc.game_channel or "",
+61 -4
View File
@@ -213,6 +213,14 @@ class OverviewMixin:
*, *,
ctn: Any = None, ctn: Any = None,
) -> dict[str, Any]: ... ) -> 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( def _pick_change_wait_bind_info(
self, candidates: list[dict], config: dict self, candidates: list[dict], config: dict
) -> dict | None: ... ) -> dict | None: ...
@@ -1094,7 +1102,7 @@ class OverviewMixin:
def _execute_query_assets_and_bind( def _execute_query_assets_and_bind(
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
): ):
"""轻量一键查询:仅实查鱼翅余额、积分(含到期)与精英绑定/换绑时间。""" """轻量一键查询:实查鱼翅、积分、宝典状态/到期与精英换绑时间。"""
queried_at = datetime.now(UTC) queried_at = datetime.now(UTC)
client = self._client(cookie) client = self._client(cookie)
errors: dict[str, str] = {} errors: dict[str, str] = {}
@@ -1110,6 +1118,9 @@ class OverviewMixin:
), ),
"role_bind_status": account.role_bind_status or "unknown", "role_bind_status": account.role_bind_status or "unknown",
"game_name": account.game_name or "", "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, "change_role_wait_time": None,
"role_change_available_at": None, "role_change_available_at": None,
"role_change_official_at": None, "role_change_official_at": None,
@@ -1135,7 +1146,49 @@ class OverviewMixin:
except Exception as exc: # noqa: BLE001 外部接口边界需要独立容错 except Exception as exc: # noqa: BLE001 外部接口边界需要独立容错
errors["gold"] = _err(exc) 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 points_ok = False
try: try:
ctn = query_csrf(client) ctn = query_csrf(client)
@@ -1163,7 +1216,7 @@ class OverviewMixin:
except Exception as exc: # noqa: BLE001 except Exception as exc: # noqa: BLE001
errors["points"] = _err(exc) errors["points"] = _err(exc)
# 3. 绑定角色与换绑时间(合并本地 7 天锁) # 4. 绑定角色与换绑时间(合并本地 7 天锁)
bind_ok = False bind_ok = False
bind_label = "" bind_label = ""
try: try:
@@ -1263,13 +1316,17 @@ class OverviewMixin:
f"鱼翅 {payload['gold_balance'] if payload['gold_balance'] is not None else '-'}", f"鱼翅 {payload['gold_balance'] if payload['gold_balance'] is not None else '-'}",
f"积分 {payload['points'] if payload['points'] 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: if bind_label:
parts.append(bind_label) parts.append(bind_label)
elif "bind" in errors: elif "bind" in errors:
parts.append(f"换绑查询失败: {errors['bind']}") parts.append(f"换绑查询失败: {errors['bind']}")
message = " · ".join(parts) 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 "查询失败" fail_msg = ";".join(f"{k}: {v}" for k, v in errors.items()) or "查询失败"
self._mark_task(db, task, "failed", fail_msg, payload) self._mark_task(db, task, "failed", fail_msg, payload)
return return
+1 -1
View File
@@ -53,7 +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_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",
@@ -41,7 +41,7 @@ import {
} from '../api/modules'; } from '../api/modules';
import { usePermissions } from '../hooks/usePermissions'; import { usePermissions } from '../hooks/usePermissions';
import { getErrorMessage } from '../utils/error'; import { getErrorMessage } from '../utils/error';
import { formatTime } from '../utils/time'; import { formatTime, formatUnixSeconds } from '../utils/time';
import { message } from '../utils/antdMessage'; import { message } from '../utils/antdMessage';
import { import {
formatWaitSeconds, formatWaitSeconds,
@@ -734,6 +734,39 @@ export default function DouyuQueryWorkbenchPage() {
</Space> </Space>
), ),
}, },
{
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 (
<Space direction="vertical" size={2} style={{ lineHeight: 1.35 }}>
<Tag color={color} style={{ marginInlineEnd: 0 }}>
{label}
</Tag>
{expireSeconds > 0 ? (
<Text type="secondary" style={{ fontSize: 12 }}>
到期: {formatUnixSeconds(expireSeconds)}
</Text>
) : record.elite_opened === true ? (
<Text type="secondary" style={{ fontSize: 12 }}>
官方未返回到期时间
</Text>
) : null}
</Space>
);
},
},
{ {
title: '绑定角色', title: '绑定角色',
width: 190, width: 190,
@@ -900,7 +933,7 @@ export default function DouyuQueryWorkbenchPage() {
]; ];
return ( return (
<Space size={4}> <Space size={4}>
<Tooltip title={record.has_cookie === false ? '无 CK 需先重登' : '查询该账号鱼翅/积分/换绑'}> <Tooltip title={record.has_cookie === false ? '无 CK 需先重登' : '查询该账号鱼翅/积分/宝典/换绑'}>
<Button <Button
size="small" size="small"
type="link" type="link"
@@ -993,7 +1026,7 @@ export default function DouyuQueryWorkbenchPage() {
) : null} ) : null}
</Space> </Space>
<Text type="secondary" style={{ fontSize: 13 }}> <Text type="secondary" style={{ fontSize: 13 }}>
支持导入斗鱼号(含 CK 失效/无 CK 账号),一键查询鱼翅、积分与换绑时间并导出 CSV;失效 CK 可选中后走人工预算重新登录。 支持导入斗鱼号(含 CK 失效/无 CK 账号),一键查询鱼翅、积分、宝典状态与换绑时间并导出 CSV;失效 CK 可选中后走人工预算重新登录。
</Text> </Text>
</Space> </Space>
@@ -1042,7 +1075,7 @@ export default function DouyuQueryWorkbenchPage() {
> >
{selectedIds.length > 0 {selectedIds.length > 0
? `一键查询已选(${selectedIds.length})` ? `一键查询已选(${selectedIds.length})`
: '一键查询全部(鱼翅/积分/换绑)'} : '一键查询全部(鱼翅/积分/宝典/换绑)'}
</Button> </Button>
<Button <Button
icon={<SafetyCertificateOutlined />} icon={<SafetyCertificateOutlined />}
@@ -1176,7 +1209,7 @@ export default function DouyuQueryWorkbenchPage() {
loading={loading} loading={loading}
columns={columns} columns={columns}
dataSource={accounts} dataSource={accounts}
scroll={{ x: 1480 }} scroll={{ x: 1680 }}
rowSelection={{ rowSelection={{
selectedRowKeys: selectedIds, selectedRowKeys: selectedIds,
preserveSelectedRowKeys: true, preserveSelectedRowKeys: true,