feat(douyu): 查询工作台区分导入/查询数据、导入后自动查CK并修复登录刷新闪烁 (v0.4.29)
1) 闪烁修复:轮询(loadAccountsPage/loadManualBudget)改为静默模式, 不再每 2.2s 点亮表格 loading 遮罩与预算 Tag spinner;活动结束后保留 12s 宽限期继续静默刷新,避免登录刚完成就停刷导致行上残留「登录队列中」。 2) 导入后自动检测 CK:工作台 PUT 返回 imported_account_ids,前端分片 并发检测并显示进度,失效/无 CK 账号直接标红;/accounts/ck-check 对 无 CK、登录中的账号改为跳过(返回 checked/skipped)而不是整批报错。 行内新增「重登/人工登录该账号」入口,走既有人工登录预算。 3) 数据来源区分:douyu_workbench_accounts 新增 data_state/imported_at/ queried_at/relogin_at(迁移 20261130_0142)。导入标 imported,查询任务 成功由 _mark_task 标 queried,人工重登入队标 stale;PUT 工作台改为 upsert,不再整删整建以免重置状态。账号列表新增 workbench_scope/ workbench_state 入参与 workbench_* 回填字段。 4) 重登后只查重登账号:新增 /query-workbench/pending-ids(导入未查 + 重登待重查,仅含有可用 CK 者)与「只查待查询(N)」下拉;一键查询改为 尊重当前筛选(跨页),修正原来无视筛选直接查整台的问题。 5) CSV 末尾追加「数据来源 / 数据更新说明」两列,保持原有列序不变。
This commit is contained in:
@@ -565,6 +565,10 @@
|
||||
"20261129_0141_douyu_slow_query_indexes.py": {
|
||||
"revision": "20261129_0141",
|
||||
"sha256": "537ffb0a472c80d3a499c3c268aa62a2f5235ccc5399a81955a0e14d8721ea1f"
|
||||
},
|
||||
"20261130_0142_douyu_workbench_data_state.py": {
|
||||
"revision": "20261130_0142",
|
||||
"sha256": "eb2225861566f91a521edaf290ea29a638d173a833c49d41f3a7e0d9b629f4e6"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""查询工作台区分「导入后的数据」与「一键查询后的数据」
|
||||
|
||||
`douyu_workbench_accounts` 之前只记录「哪个账号在这个工作台里」,因此界面无法
|
||||
区分某一行是刚导入(只检测过 CK)还是已经跑过一键查询;重登成功后也没法只挑
|
||||
重新登录的账号再查一次。
|
||||
|
||||
新增四列:
|
||||
|
||||
- `data_state`:imported / queried / stale
|
||||
- `imported_at`:加入工作台的时间
|
||||
- `queried_at`:最近一次在本工作台查询成功的时间
|
||||
- `relogin_at`:最近一次发起人工重登的时间
|
||||
|
||||
Revision ID: 20261130_0142
|
||||
Revises: 20261129_0141
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261130_0142"
|
||||
down_revision: str | None = "20261129_0141"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
|
||||
def _has_column(inspector: sa.Inspector, table: str, column: str) -> bool:
|
||||
return any(col["name"] == column for col in inspector.get_columns(table))
|
||||
|
||||
|
||||
def _has_index(inspector: sa.Inspector, table: str, index_name: str) -> bool:
|
||||
return any(idx["name"] == index_name for idx in inspector.get_indexes(table))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
table = "douyu_workbench_accounts"
|
||||
if not inspector.has_table(table):
|
||||
return
|
||||
|
||||
if not _has_column(inspector, table, "data_state"):
|
||||
op.add_column(
|
||||
table,
|
||||
sa.Column(
|
||||
"data_state",
|
||||
sa.String(length=16),
|
||||
nullable=False,
|
||||
server_default="imported",
|
||||
comment="imported/queried/stale:区分导入数据与一键查询数据",
|
||||
),
|
||||
)
|
||||
if not _has_column(inspector, table, "imported_at"):
|
||||
op.add_column(
|
||||
table,
|
||||
sa.Column("imported_at", sa.DateTime(), nullable=True, comment="导入工作台时间"),
|
||||
)
|
||||
if not _has_column(inspector, table, "queried_at"):
|
||||
op.add_column(
|
||||
table,
|
||||
sa.Column("queried_at", sa.DateTime(), nullable=True, comment="最近一次查询成功时间"),
|
||||
)
|
||||
if not _has_column(inspector, table, "relogin_at"):
|
||||
op.add_column(
|
||||
table,
|
||||
sa.Column("relogin_at", sa.DateTime(), nullable=True, comment="最近一次人工重登时间"),
|
||||
)
|
||||
|
||||
# 历史行:`created_at` 就是导入时间;已有 `overview_queried_at` 的账号视为已查询过。
|
||||
# 用 SQL 分批回填,避免 ORM 逐行加载。
|
||||
op.execute(
|
||||
sa.text(
|
||||
f"UPDATE {table} SET imported_at = created_at WHERE imported_at IS NULL"
|
||||
)
|
||||
)
|
||||
op.execute(
|
||||
sa.text(
|
||||
f"""
|
||||
UPDATE {table} AS w
|
||||
JOIN accounts AS a ON a.id = w.account_id
|
||||
SET w.data_state = 'queried', w.queried_at = a.overview_queried_at
|
||||
WHERE w.data_state = 'imported'
|
||||
AND a.overview_queried_at IS NOT NULL
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
inspector = sa.inspect(bind)
|
||||
if not _has_index(inspector, table, "ix_douyu_workbench_accounts_state"):
|
||||
op.create_index(
|
||||
"ix_douyu_workbench_accounts_state",
|
||||
table,
|
||||
["user_id", "handbook_scope", "data_state"],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
table = "douyu_workbench_accounts"
|
||||
if not inspector.has_table(table):
|
||||
return
|
||||
if _has_index(inspector, table, "ix_douyu_workbench_accounts_state"):
|
||||
op.drop_index("ix_douyu_workbench_accounts_state", table_name=table)
|
||||
for column in ("relogin_at", "queried_at", "imported_at", "data_state"):
|
||||
if _has_column(inspector, table, column):
|
||||
op.drop_column(table, column)
|
||||
@@ -549,11 +549,27 @@ class DouyuWorkbenchAccount(Base):
|
||||
Integer, nullable=False, default=0, server_default="0"
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||
# 「导入后的数据」与「一键查询后的数据」必须能区分开:
|
||||
# imported = 只导入并检测过 CK,资产/换绑仍是导入前的旧值;
|
||||
# queried = 已在本工作台跑过一键查询;
|
||||
# stale = 重登成功或 CK 重新生效,账号数据需要重新查询。
|
||||
data_state: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default="imported", server_default="imported"
|
||||
)
|
||||
imported_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
queried_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
relogin_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"user_id", "handbook_scope", "account_id", name="uq_douyu_workbench_account"
|
||||
),
|
||||
Index(
|
||||
"ix_douyu_workbench_accounts_state",
|
||||
"user_id",
|
||||
"handbook_scope",
|
||||
"data_state",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
|
||||
+216
-23
@@ -88,6 +88,7 @@ from ..services.account_protection_service import (
|
||||
evaluate_protection_targets,
|
||||
update_protection_group,
|
||||
)
|
||||
from ..services.account_query_filters import cookie_operable_filter
|
||||
from ..services.account_supply_service import (
|
||||
SupplyInventory,
|
||||
evaluate_supply_target,
|
||||
@@ -112,6 +113,13 @@ from ..services.douyu_exchange_result_image import (
|
||||
save_exchange_result_image,
|
||||
)
|
||||
from ..services.douyu_goods_service import serialize_goods
|
||||
from ..services.douyu_query_workbench import (
|
||||
DATA_STATE_IMPORTED,
|
||||
DATA_STATES,
|
||||
mark_workbench_stale,
|
||||
pending_query_ids,
|
||||
workbench_state_map,
|
||||
)
|
||||
from ..services.douyu_runner import DouyuBatchRunner, douyu_batch_registry
|
||||
from ..services.douyu_service import (
|
||||
DOUYU_ACTIVE_TASK_STATUSES,
|
||||
@@ -810,7 +818,8 @@ def _account_out(
|
||||
game_channel=account.game_channel or "",
|
||||
gold_balance=account.gold_balance,
|
||||
exchange_balance=account.exchange_balance,
|
||||
**bind_payload(account),
|
||||
# pydantic 模型字段含 datetime/bool,字典展开只能按 Any 传入。
|
||||
**cast(dict[str, Any], bind_payload(account)),
|
||||
# 未确认绑定时接口倒计时是占位值;API 出口也做一次归一,兼容历史行。
|
||||
change_role_wait_time=account.change_role_wait_time if elite_cooldown else 0,
|
||||
elite_opened=account.elite_opened,
|
||||
@@ -1015,13 +1024,19 @@ def list_task_accounts(
|
||||
ids: str = Query(""),
|
||||
account_names: str = Query(""),
|
||||
ck_status: str = "",
|
||||
workbench_scope: str = "",
|
||||
workbench_state: str = "",
|
||||
include_all: bool = False,
|
||||
page: int | None = Query(None, ge=1),
|
||||
page_size: int = Query(50, ge=1, le=200),
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(get_current_user),
|
||||
):
|
||||
"""查看斗鱼账号。默认只返回持有 Cookie 的可执行账号;include_all=true 时返回全部可见账号(供查询工作台使用)。"""
|
||||
"""查看斗鱼账号。默认只返回持有 Cookie 的可执行账号;include_all=true 时返回全部可见账号(供查询工作台使用)。
|
||||
|
||||
`workbench_scope` 传入时会回填该工作台的数据来源(导入未查询 / 已查询 / 重登待重查),
|
||||
`workbench_state` 可按数据来源筛选(跨页生效)。
|
||||
"""
|
||||
query, selected_names, selected_ids = _apply_task_account_filters(
|
||||
_visible_task_accounts_query(db, current, include_all=include_all),
|
||||
search=search,
|
||||
@@ -1030,6 +1045,18 @@ def list_task_accounts(
|
||||
ids=ids,
|
||||
ck_status=ck_status,
|
||||
)
|
||||
scope = (workbench_scope or "").strip()
|
||||
if scope:
|
||||
member_query = select(DouyuWorkbenchAccount.account_id).where(
|
||||
DouyuWorkbenchAccount.user_id == current.id,
|
||||
DouyuWorkbenchAccount.handbook_scope == scope,
|
||||
)
|
||||
state = (workbench_state or "").strip()
|
||||
if state:
|
||||
if state not in DATA_STATES:
|
||||
raise HTTPException(status_code=400, detail="无效的数据状态筛选")
|
||||
member_query = member_query.where(DouyuWorkbenchAccount.data_state == state)
|
||||
query = query.filter(Account.id.in_(member_query))
|
||||
total = None
|
||||
if page is not None:
|
||||
total = query.order_by(None).count()
|
||||
@@ -1044,9 +1071,26 @@ def list_task_accounts(
|
||||
if include_all
|
||||
else None
|
||||
)
|
||||
result = [
|
||||
_account_out(account, in_flight_login_ids=in_flight_ids) for account in rows
|
||||
]
|
||||
state_rows = (
|
||||
workbench_state_map(
|
||||
db,
|
||||
user_id=int(current.id),
|
||||
account_ids=[int(account.id) for account in rows],
|
||||
handbook_scope=scope,
|
||||
)
|
||||
if scope
|
||||
else {}
|
||||
)
|
||||
result = []
|
||||
for account in rows:
|
||||
item = _account_out(account, in_flight_login_ids=in_flight_ids)
|
||||
state_row = state_rows.get(int(account.id))
|
||||
if state_row is not None:
|
||||
item.workbench_data_state = state_row.data_state or DATA_STATE_IMPORTED
|
||||
item.workbench_imported_at = state_row.imported_at
|
||||
item.workbench_queried_at = state_row.queried_at
|
||||
item.workbench_relogin_at = state_row.relogin_at
|
||||
result.append(item)
|
||||
if page is not None:
|
||||
return {
|
||||
"items": result,
|
||||
@@ -1063,11 +1107,16 @@ def list_task_account_ids(
|
||||
tag: str = Query(""),
|
||||
account_names: str = Query(""),
|
||||
ck_status: str = "",
|
||||
workbench_scope: str = "",
|
||||
workbench_state: str = "",
|
||||
include_all: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(get_current_user),
|
||||
):
|
||||
"""返回当前用户可导入工作台的全部账号 ID,不受列表分页限制。"""
|
||||
"""返回当前用户可导入工作台的全部账号 ID,不受列表分页限制。
|
||||
|
||||
`workbench_scope` / `workbench_state` 与 `/accounts` 一致:用于「一键查询当前筛选结果」。
|
||||
"""
|
||||
query, selected_names, selected_ids = _apply_task_account_filters(
|
||||
_visible_task_accounts_query(db, current, include_all=include_all),
|
||||
search=search,
|
||||
@@ -1075,6 +1124,18 @@ def list_task_account_ids(
|
||||
account_names=account_names,
|
||||
ck_status=ck_status,
|
||||
)
|
||||
scope = (workbench_scope or "").strip()
|
||||
if scope:
|
||||
member_query = select(DouyuWorkbenchAccount.account_id).where(
|
||||
DouyuWorkbenchAccount.user_id == current.id,
|
||||
DouyuWorkbenchAccount.handbook_scope == scope,
|
||||
)
|
||||
state = (workbench_state or "").strip()
|
||||
if state:
|
||||
if state not in DATA_STATES:
|
||||
raise HTTPException(status_code=400, detail="无效的数据状态筛选")
|
||||
member_query = member_query.where(DouyuWorkbenchAccount.data_state == state)
|
||||
query = query.filter(Account.id.in_(member_query))
|
||||
account_ids = [
|
||||
account_id
|
||||
for (account_id,) in _order_task_accounts(
|
||||
@@ -1096,10 +1157,46 @@ def check_task_accounts_ck(
|
||||
|
||||
复用 CK 操作页的检测逻辑:检测结果会写回 ``accounts.ck_check_status``,
|
||||
因此导入账号后刷新列表仍能看到「有效 / 失效」。
|
||||
|
||||
导入场景会整批传入(包含无 CK / 正在登录的账号),这些账号会被跳过而不是
|
||||
整体报错 —— 调用方只需要拿到真正能检测的那批结论。
|
||||
"""
|
||||
from .cookies import _check_cookies
|
||||
|
||||
return _check_cookies(ids, db, current, detailed=False)
|
||||
requested_ids = [
|
||||
int(value) for value in dict.fromkeys(
|
||||
item.strip() for item in (ids or "").split(",") if item.strip().isdigit()
|
||||
)
|
||||
]
|
||||
if not requested_ids:
|
||||
raise HTTPException(status_code=400, detail="请指定账号ID")
|
||||
checkable_ids = [
|
||||
int(account_id)
|
||||
for (account_id,) in _visible_task_accounts_query(db, current, include_all=True)
|
||||
.filter(Account.id.in_(requested_ids), cookie_operable_filter())
|
||||
.enable_eagerloads(False)
|
||||
.with_entities(Account.id)
|
||||
.all()
|
||||
]
|
||||
skipped = len(requested_ids) - len(checkable_ids)
|
||||
if not checkable_ids:
|
||||
return {
|
||||
"results": [],
|
||||
"success": True,
|
||||
"checked": 0,
|
||||
"skipped": skipped,
|
||||
"message": "所选账号均无可用 CK(待登录或正在登录中)",
|
||||
}
|
||||
result = _check_cookies(
|
||||
",".join(str(account_id) for account_id in checkable_ids),
|
||||
db,
|
||||
current,
|
||||
detailed=False,
|
||||
)
|
||||
if isinstance(result, dict):
|
||||
result["skipped"] = skipped
|
||||
result["checked"] = len(result.get("results") or [])
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/accounts/relogin-invalid")
|
||||
@@ -1176,7 +1273,11 @@ def update_workbench_accounts(
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("douyu:task")),
|
||||
):
|
||||
"""用当前完整账号集合覆盖一个工作台,作为跨浏览器的同步状态。"""
|
||||
"""用当前完整账号集合覆盖一个工作台,作为跨浏览器的同步状态。
|
||||
|
||||
保留已有账号行的数据状态(导入/已查询/待重查),只把本次新加入的账号标记为
|
||||
「导入未查询」,避免每次增删账号都把工作台的查询状态重置。
|
||||
"""
|
||||
account_ids = list(dict.fromkeys(req.account_ids))
|
||||
if any(account_id < 1 for account_id in account_ids):
|
||||
raise HTTPException(status_code=400, detail="无效的账号ID")
|
||||
@@ -1194,23 +1295,53 @@ def update_workbench_accounts(
|
||||
db.add(DouyuWorkbench(user_id=current.id, handbook_scope=req.handbook_scope))
|
||||
else:
|
||||
workbench.updated_at = datetime.now(UTC)
|
||||
db.query(DouyuWorkbenchAccount).filter(
|
||||
DouyuWorkbenchAccount.user_id == current.id,
|
||||
DouyuWorkbenchAccount.handbook_scope == req.handbook_scope,
|
||||
).delete(synchronize_session=False)
|
||||
db.add_all(
|
||||
[
|
||||
DouyuWorkbenchAccount(
|
||||
user_id=current.id,
|
||||
handbook_scope=req.handbook_scope,
|
||||
account_id=account_id,
|
||||
sort_order=index,
|
||||
|
||||
existing_rows = {
|
||||
int(row.account_id): row
|
||||
for row in db.query(DouyuWorkbenchAccount)
|
||||
.filter(
|
||||
DouyuWorkbenchAccount.user_id == current.id,
|
||||
DouyuWorkbenchAccount.handbook_scope == req.handbook_scope,
|
||||
)
|
||||
.all()
|
||||
}
|
||||
keep = set(account_ids)
|
||||
removed = [account_id for account_id in existing_rows if account_id not in keep]
|
||||
if removed:
|
||||
db.query(DouyuWorkbenchAccount).filter(
|
||||
DouyuWorkbenchAccount.user_id == current.id,
|
||||
DouyuWorkbenchAccount.handbook_scope == req.handbook_scope,
|
||||
DouyuWorkbenchAccount.account_id.in_(removed),
|
||||
).delete(synchronize_session=False)
|
||||
|
||||
now = datetime.now(UTC)
|
||||
imported_account_ids: list[int] = []
|
||||
for index, account_id in enumerate(account_ids):
|
||||
row = existing_rows.get(account_id)
|
||||
if row is None:
|
||||
db.add(
|
||||
DouyuWorkbenchAccount(
|
||||
user_id=current.id,
|
||||
handbook_scope=req.handbook_scope,
|
||||
account_id=account_id,
|
||||
sort_order=index,
|
||||
data_state=DATA_STATE_IMPORTED,
|
||||
imported_at=now,
|
||||
)
|
||||
)
|
||||
for index, account_id in enumerate(account_ids)
|
||||
]
|
||||
)
|
||||
imported_account_ids.append(account_id)
|
||||
continue
|
||||
row.sort_order = index
|
||||
if not row.imported_at:
|
||||
row.imported_at = row.created_at or now
|
||||
if not row.data_state:
|
||||
row.data_state = DATA_STATE_IMPORTED
|
||||
db.commit()
|
||||
return {"account_ids": account_ids, "success": True}
|
||||
return {
|
||||
"account_ids": account_ids,
|
||||
"imported_account_ids": imported_account_ids,
|
||||
"success": True,
|
||||
}
|
||||
|
||||
|
||||
_SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
|
||||
@@ -1409,6 +1540,30 @@ def list_query_workbench_invalid_ids(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/query-workbench/pending-ids")
|
||||
def list_query_workbench_pending_ids(
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("douyu:task")),
|
||||
):
|
||||
"""返回工作台内「待查询」账号:导入未查 + 重登成功后待重查(均有可用 CK)。
|
||||
|
||||
重登成功后的账号只选这一批回查,不会把整个工作台再跑一遍。
|
||||
"""
|
||||
member_ids = _query_workbench_member_ids(db, current)
|
||||
if not member_ids:
|
||||
return {
|
||||
"account_ids": [],
|
||||
"imported_ids": [],
|
||||
"stale_ids": [],
|
||||
"total": 0,
|
||||
}
|
||||
return pending_query_ids(
|
||||
db,
|
||||
user_id=int(current.id),
|
||||
visible_account_ids=member_ids,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/query-workbench/manual-budget")
|
||||
def get_query_workbench_manual_budget(
|
||||
db: Session = Depends(get_db),
|
||||
@@ -1526,6 +1681,9 @@ def relogin_query_workbench_invalid_accounts(
|
||||
batch_ids.append(batch_id)
|
||||
|
||||
total_queued = len(relogin_ids) + len(login_ids)
|
||||
# 重登(或首次登录)成功后的账号数据已过期:标记为「待重查」,
|
||||
# 这样重登完成后可以只回查这批账号,而不是把整个工作台重跑一遍。
|
||||
mark_workbench_stale(db, relogin_ids + login_ids, commit=False)
|
||||
record_audit(
|
||||
db,
|
||||
current,
|
||||
@@ -1558,6 +1716,32 @@ def relogin_query_workbench_invalid_accounts(
|
||||
}
|
||||
|
||||
|
||||
_WORKBENCH_STATE_LABELS = {
|
||||
"imported": "导入未查询",
|
||||
"queried": "已查询",
|
||||
"stale": "重登待重查",
|
||||
}
|
||||
|
||||
|
||||
def _workbench_state_label(row: DouyuWorkbenchAccount | None) -> str:
|
||||
if row is None:
|
||||
return "未在工作台"
|
||||
return _WORKBENCH_STATE_LABELS.get(row.data_state or "", "导入未查询")
|
||||
|
||||
|
||||
def _workbench_state_note(row: DouyuWorkbenchAccount | None) -> str:
|
||||
"""导出附带「什么时候导入 / 什么时候查的」,避免把旧数据当新结果。"""
|
||||
if row is None:
|
||||
return ""
|
||||
if row.data_state == "queried" and row.queried_at is not None:
|
||||
return f"查询于 {_format_shanghai_dt(row.queried_at)}"
|
||||
if row.data_state == "stale" and row.relogin_at is not None:
|
||||
return f"重登于 {_format_shanghai_dt(row.relogin_at)},待重新查询"
|
||||
if row.imported_at is not None:
|
||||
return f"导入于 {_format_shanghai_dt(row.imported_at)},未查询资产"
|
||||
return "未查询资产"
|
||||
|
||||
|
||||
@router.post("/query-workbench/export")
|
||||
def export_query_workbench_csv(
|
||||
req: DouyuQueryWorkbenchExportRequest,
|
||||
@@ -1607,8 +1791,15 @@ def export_query_workbench_csv(
|
||||
"官方换绑时间",
|
||||
"换绑冷却说明",
|
||||
"最近更新时间",
|
||||
"数据来源",
|
||||
"数据更新说明",
|
||||
]
|
||||
)
|
||||
state_rows = workbench_state_map(
|
||||
db,
|
||||
user_id=int(current.id),
|
||||
account_ids=[int(acc.id) for acc in ordered_accounts],
|
||||
)
|
||||
for acc in ordered_accounts:
|
||||
if not acc.cookie:
|
||||
ck_label = "无CK"
|
||||
@@ -1678,6 +1869,8 @@ def export_query_workbench_csv(
|
||||
_format_shanghai_dt(acc.role_change_official_at),
|
||||
cooldown_note,
|
||||
_format_shanghai_dt(acc.updated_at or acc.overview_queried_at),
|
||||
_workbench_state_label(state_rows.get(int(acc.id))),
|
||||
_workbench_state_note(state_rows.get(int(acc.id))),
|
||||
]
|
||||
]
|
||||
)
|
||||
|
||||
@@ -2031,6 +2031,12 @@ class DouyuTaskAccountOut(BaseModel):
|
||||
overview_queried_at: datetime | None = None
|
||||
updated_at: datetime | None = None
|
||||
in_flight_login: bool = False
|
||||
# 查询工作台数据来源(仅 `workbench_scope` 入参时回填):
|
||||
# imported = 导入未查询,queried = 已查询,stale = 重登后待重查。
|
||||
workbench_data_state: str = ""
|
||||
workbench_imported_at: datetime | None = None
|
||||
workbench_queried_at: datetime | None = None
|
||||
workbench_relogin_at: datetime | None = None
|
||||
|
||||
|
||||
class DouyuXpdGoodsOut(BaseModel):
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
"""斗鱼「查询工作台」的数据状态维护。
|
||||
|
||||
查询工作台里的一个账号,数据来源必须能区分开:
|
||||
|
||||
- ``imported``:刚导入,只做过 CK 检测;鱼翅/积分/宝典/换绑还是导入前的旧值;
|
||||
- ``queried``:已在本工作台跑过一键查询,界面展示的是本次查询结果;
|
||||
- ``stale``:重登成功或 CK 重新生效,账号数据已过期,需要按「重登的账号」单独再查一次。
|
||||
|
||||
写入口只有三处:导入(`update_workbench_accounts`)、查询成功(任务结束)、
|
||||
人工重登(`relogin-invalid`)。读取入口是账号列表与 `pending-ids`。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Iterable
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import Account, DouyuWorkbenchAccount
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DATA_STATE_IMPORTED = "imported"
|
||||
DATA_STATE_QUERIED = "queried"
|
||||
DATA_STATE_STALE = "stale"
|
||||
DATA_STATES = (DATA_STATE_IMPORTED, DATA_STATE_QUERIED, DATA_STATE_STALE)
|
||||
|
||||
QUERY_WORKBENCH_SCOPE = "query"
|
||||
|
||||
|
||||
def _normalized_ids(account_ids: Iterable[int]) -> list[int]:
|
||||
values: list[int] = []
|
||||
for raw in account_ids:
|
||||
try:
|
||||
account_id = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if account_id > 0:
|
||||
values.append(account_id)
|
||||
return list(dict.fromkeys(values))
|
||||
|
||||
|
||||
def _query_workbench_rows(
|
||||
db: Session, account_ids: list[int], *, user_id: int | None = None
|
||||
):
|
||||
query = db.query(DouyuWorkbenchAccount).filter(
|
||||
DouyuWorkbenchAccount.handbook_scope == QUERY_WORKBENCH_SCOPE,
|
||||
DouyuWorkbenchAccount.account_id.in_(account_ids),
|
||||
)
|
||||
if user_id is not None:
|
||||
query = query.filter(DouyuWorkbenchAccount.user_id == user_id)
|
||||
return query
|
||||
|
||||
|
||||
def mark_workbench_queried(
|
||||
db: Session,
|
||||
account_ids: Iterable[int],
|
||||
*,
|
||||
queried_at: datetime | None = None,
|
||||
commit: bool = True,
|
||||
) -> int:
|
||||
"""一键查询成功后把工作台行标记为「已查询」。
|
||||
|
||||
只更新已经在查询工作台里的账号;其它工作台(精英/电竞/小店)不参与。
|
||||
"""
|
||||
ids = _normalized_ids(account_ids)
|
||||
if not ids:
|
||||
return 0
|
||||
moment = queried_at or datetime.now(UTC)
|
||||
rows = _query_workbench_rows(db, ids).all()
|
||||
for row in rows:
|
||||
row.data_state = DATA_STATE_QUERIED
|
||||
row.queried_at = moment
|
||||
if rows and commit:
|
||||
db.commit()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def mark_workbench_stale(
|
||||
db: Session,
|
||||
account_ids: Iterable[int],
|
||||
*,
|
||||
relogin_at: datetime | None = None,
|
||||
commit: bool = True,
|
||||
) -> int:
|
||||
"""人工重登后把工作台行标记为「待重新查询」。
|
||||
|
||||
重登可能失败(CK 仍失效),此时界面优先展示 CK 状态,`stale` 只在 CK 恢复
|
||||
有效后才作为「重登成功、待重新查询」参与批量查询。
|
||||
"""
|
||||
ids = _normalized_ids(account_ids)
|
||||
if not ids:
|
||||
return 0
|
||||
moment = relogin_at or datetime.now(UTC)
|
||||
rows = _query_workbench_rows(db, ids).all()
|
||||
for row in rows:
|
||||
row.data_state = DATA_STATE_STALE
|
||||
row.relogin_at = moment
|
||||
if rows and commit:
|
||||
db.commit()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def pending_query_ids(
|
||||
db: Session,
|
||||
*,
|
||||
user_id: int,
|
||||
visible_account_ids: Iterable[int] | None = None,
|
||||
) -> dict[str, list[int] | int]:
|
||||
"""返回本工作台里「需要查询」的账号:导入未查 + 重登待重查,且当前有 CK。
|
||||
|
||||
无 CK 的账号查了也会失败,交给重登流程,不进批量查询。
|
||||
"""
|
||||
visible = _normalized_ids(visible_account_ids or [])
|
||||
query = (
|
||||
db.query(
|
||||
DouyuWorkbenchAccount.account_id,
|
||||
DouyuWorkbenchAccount.data_state,
|
||||
Account.cookie,
|
||||
)
|
||||
.join(Account, Account.id == DouyuWorkbenchAccount.account_id)
|
||||
.filter(
|
||||
DouyuWorkbenchAccount.user_id == user_id,
|
||||
DouyuWorkbenchAccount.handbook_scope == QUERY_WORKBENCH_SCOPE,
|
||||
DouyuWorkbenchAccount.data_state.in_(
|
||||
(DATA_STATE_IMPORTED, DATA_STATE_STALE)
|
||||
),
|
||||
Account.cookie.isnot(None),
|
||||
Account.cookie != "",
|
||||
or_(Account.status.is_(None), Account.status != "invalid"),
|
||||
or_(
|
||||
Account.ck_check_status.is_(None),
|
||||
Account.ck_check_status.notin_(("invalid", "error")),
|
||||
),
|
||||
)
|
||||
)
|
||||
if visible:
|
||||
query = query.filter(DouyuWorkbenchAccount.account_id.in_(visible))
|
||||
imported_ids: list[int] = []
|
||||
stale_ids: list[int] = []
|
||||
for account_id, data_state, _cookie in query.order_by(
|
||||
DouyuWorkbenchAccount.sort_order.asc(), DouyuWorkbenchAccount.id.asc()
|
||||
).all():
|
||||
if data_state == DATA_STATE_STALE:
|
||||
stale_ids.append(int(account_id))
|
||||
else:
|
||||
imported_ids.append(int(account_id))
|
||||
return {
|
||||
"imported_ids": imported_ids,
|
||||
"stale_ids": stale_ids,
|
||||
"account_ids": imported_ids + stale_ids,
|
||||
"total": len(imported_ids) + len(stale_ids),
|
||||
}
|
||||
|
||||
|
||||
def workbench_state_map(
|
||||
db: Session,
|
||||
*,
|
||||
user_id: int,
|
||||
account_ids: Iterable[int],
|
||||
handbook_scope: str = QUERY_WORKBENCH_SCOPE,
|
||||
) -> dict[int, DouyuWorkbenchAccount]:
|
||||
"""批量读取工作台行状态,供账号列表回填数据来源标记。"""
|
||||
ids = _normalized_ids(account_ids)
|
||||
if not ids:
|
||||
return {}
|
||||
rows = (
|
||||
db.query(DouyuWorkbenchAccount)
|
||||
.filter(
|
||||
DouyuWorkbenchAccount.user_id == user_id,
|
||||
DouyuWorkbenchAccount.handbook_scope == handbook_scope,
|
||||
DouyuWorkbenchAccount.account_id.in_(ids),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return {int(row.account_id): row for row in rows}
|
||||
@@ -452,6 +452,25 @@ class DouyuBatchRunnerCore:
|
||||
message=message,
|
||||
)
|
||||
db.commit()
|
||||
if (
|
||||
status == "success"
|
||||
and task.account_id
|
||||
and str(task.task_type or "") == "query_assets_and_bind"
|
||||
):
|
||||
# 查询工作台靠这行区分「导入后的旧数据」与「一键查询后的新数据」。
|
||||
try:
|
||||
from .douyu_query_workbench import mark_workbench_queried
|
||||
|
||||
mark_workbench_queried(
|
||||
db,
|
||||
[int(task.account_id)],
|
||||
queried_at=task.finished_at,
|
||||
)
|
||||
except Exception: # noqa: BLE001 - 工作台状态不能反噬任务结果
|
||||
logger.exception(
|
||||
"[douyu] 标记查询工作台已查询失败: task_id={}", task_id
|
||||
)
|
||||
db.rollback()
|
||||
self._push_task_event(task)
|
||||
if account is not None and event_context is not None:
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user