feat(check): 账号检测新增「按账号选择」—— 旧的手动输入与逻辑完整保留
按反馈是**增加**而不是**替换**:旧路径一行未动,新路径另起一条。 ## 两套来源并存 | | 手动输入(旧,默认) | 选择账号(新) | | --- | --- | --- | | 来源 | 粘贴文本 | 库里账号的凭据(不用人工粘贴) | | 条目 `account_id` | **无** | 有 | | 结果落账号时间线 | **否**(保持旧行为) | 是,新事件类型 `account_check` | | 批次 / 并发 / 重试 / 代理 / 导出 zip | 完全不变 | 完全不变 | **旧路径的「不发事件」是刻意的**:粘贴进来的账号没有归属,凭空造一条没有账号的 事件只是污染时间线。`parse_account_check_lines`、`export_line`、zip 分组全部未动, 有用例专门钉住这一点。 ## 「选择账号」支持筛选(按反馈补充) 不是给一个扁平下拉,而是先按条件缩小范围再决定选法: - 筛选:**标签 / 生命周期状态 / CK 健康**(复用账号列表同一套 `_filter_accounts_query`, 两处口径不会不一致) - 选法:手动多选(选项随筛选刷新)**或**「按筛选全选」(含列表里没显示出来的) 服务端支持 `select_all_matching + 各筛选条件`,与账号列表批量操作的字段形状一致。 可见性沿用账号域口径:客服只能检测自己名下的账号(越权 id 直接 403)。 ## 结果表加账号回链 「选择账号」模式下条目带 `account_id`,账号列变成可点链接 → 直接跳到账号详情, 结果也在那里的时间线上。 ## 排查中修掉两个 bug(都不是测试发现的) **① `registry.create` 漏传 `account_id`** 它构造 `AccountCheckItemState` 时没把 `account_id` 从输入复制过去。 后果:批次照跑、结果照显示、zip 照导出,**事件永远不发且没有任何报错**。 是「跑一次真实检测再查事件表」才发现的(查出来 0 条)。已补,并加了用例。 **② 终态判断写成「键存在」而不是「非空」** `_run_one` 置 `running` 时会显式传 `finished_at=None`,而判断写的是 `"finished_at" in updates` → **中间态也发事件**,于是时间线上记的是 `账号检查:running`;真正的终态再发时撞同一个幂等键被**静默丢弃** —— 结果是「只有一条,但记错了」,比没有更糟。 改成判非空。此处暴露了一个**假绿的用例**:我原来的「中间态不发事件」用例 没传 `finished_at=None`(与真实调用不一致),所以放过了这个 bug; 而且它还缺 `session.commit()`,在 MySQL REPEATABLE READ 下根本看不到 另一个会话刚提交的行 —— 双重假绿。两处都修了,并做了反向验证 (改回旧判断 → 用例立刻红)。 ## 验证 - `TZ=Asia/Shanghai`:**520 passed / 6 skipped**(新增 17 条检测模式用例) - `TZ=UTC`(检测 + 迁移)20 passed;ruff 全绿;前端 build 通过、lint 0 errors - **真实端到端**:用真实库账号起批次 → 检测跑完(斗鱼返回「账号已认证」)→ 事件确实落库;清掉脏数据后用**与 `_run_one` 完全相同的调用序列**复验: 两次 `_set_item` 只产生一条事件,且 title 是 `账号检测:账号已认证`、`status=account_verified`(不再记成 running) 注:验证时真实触发了几次斗鱼登录检测(开发库那两个账号),结果都是「已认证」。
This commit is contained in:
@@ -10,12 +10,13 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..deps import get_current_user
|
||||
from ..models import Account, User
|
||||
from ..models import ProxyConfig as ProxyConfigModel
|
||||
from ..models import User
|
||||
from ..permissions import user_has_permission
|
||||
from ..schemas import AccountCheckBatchOut, AccountCheckBatchRequest
|
||||
from ..services.account_check_service import (
|
||||
account_check_registry,
|
||||
build_inputs_from_accounts,
|
||||
parse_account_check_lines,
|
||||
)
|
||||
|
||||
@@ -45,12 +46,60 @@ def create_account_check_batch(
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(get_current_user),
|
||||
):
|
||||
"""启动斗鱼账号检测批次。"""
|
||||
"""启动斗鱼账号检测批次。
|
||||
|
||||
两种来源**二选一**:
|
||||
- `text`:手动粘贴(旧模式,逻辑一字未动);
|
||||
- `account_ids`:按账号选择(新模式)—— 凭据从库里取,结果写回账号时间线。
|
||||
"""
|
||||
_require_account_check_perm(current)
|
||||
try:
|
||||
accounts = parse_account_check_lines(req.text)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
has_text = bool((req.text or "").strip())
|
||||
has_ids = bool(req.account_ids)
|
||||
has_filter = bool(req.select_all_matching)
|
||||
picked = has_ids or has_filter
|
||||
if has_text and picked:
|
||||
raise HTTPException(status_code=400, detail="手动输入与选择账号只能二选一")
|
||||
if not has_text and not picked:
|
||||
raise HTTPException(status_code=400, detail="请粘贴账号或选择要检测的账号")
|
||||
|
||||
if picked:
|
||||
# 可见性沿用账号域的口径:客服只能检测自己名下的账号。
|
||||
from .accounts import _filter_accounts_query, _visible_accounts_query
|
||||
|
||||
query = _visible_accounts_query(db, current)
|
||||
if has_filter:
|
||||
# 「按筛选全选」:与账号列表同一套筛选条件(标签/状态/CK/绑定/搜索),
|
||||
# 所以列表上筛出什么,这里就检测什么,不会两处口径不一致。
|
||||
query = _filter_accounts_query(
|
||||
db,
|
||||
query,
|
||||
current,
|
||||
search=req.search,
|
||||
tag=req.tag,
|
||||
status=req.status,
|
||||
ck_status=req.ck_status,
|
||||
bind_status=req.bind_status,
|
||||
)
|
||||
rows = query.order_by(Account.id.asc()).all()
|
||||
ordered_ids = [int(a.id) for a in rows]
|
||||
else:
|
||||
ordered_ids = [int(i) for i in req.account_ids]
|
||||
rows = query.filter(Account.id.in_(ordered_ids)).all()
|
||||
found = {int(a.id) for a in rows}
|
||||
missing = [i for i in ordered_ids if i not in found]
|
||||
if missing:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail=f"以下账号不存在或无权查看:{missing[:10]}",
|
||||
)
|
||||
if not rows:
|
||||
raise HTTPException(status_code=400, detail="当前条件下没有可检测的账号")
|
||||
accounts = build_inputs_from_accounts(rows, ordered_ids)
|
||||
else:
|
||||
try:
|
||||
accounts = parse_account_check_lines(req.text)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
if not accounts:
|
||||
raise HTTPException(status_code=400, detail="没有识别到有效账号")
|
||||
|
||||
+18
-1
@@ -287,7 +287,23 @@ class LoginTaskOut(BaseModel):
|
||||
|
||||
# ---- 账号检测 ----
|
||||
class AccountCheckBatchRequest(BaseModel):
|
||||
text: str = Field(..., min_length=1)
|
||||
"""两种来源二选一(**旧的粘贴输入完整保留**)。
|
||||
|
||||
- `text`:手动粘贴(旧模式)—— 条目没有 account_id,结果只在批次里与 zip 里,
|
||||
不写账号时间线(保持旧行为);
|
||||
- `account_ids`:按账号选择(新模式)—— 凭据从库里取,结果写回账号时间线。
|
||||
"""
|
||||
|
||||
text: str = ""
|
||||
# 「选择账号」的两种选法(与账号列表的批量操作保持同一套字段):
|
||||
# ① 手动挑几个 → account_ids;② 按筛选全选 → select_all_matching + 各筛选条件
|
||||
account_ids: list[int] = Field(default_factory=list)
|
||||
select_all_matching: bool = False
|
||||
search: str = ""
|
||||
tag: str = ""
|
||||
status: str = ""
|
||||
ck_status: str = ""
|
||||
bind_status: str = ""
|
||||
concurrency: int = Field(3, ge=1, le=10)
|
||||
max_login_retries: int = Field(0, ge=0, le=50)
|
||||
max_total_time: float = Field(300, ge=0, le=3600)
|
||||
@@ -298,6 +314,7 @@ class AccountCheckItemOut(BaseModel):
|
||||
line: int
|
||||
username: str
|
||||
email: str
|
||||
account_id: int | None = None
|
||||
status: str
|
||||
message: str
|
||||
started_at: datetime | None = None
|
||||
|
||||
@@ -12,11 +12,15 @@ from datetime import UTC, datetime
|
||||
from types import SimpleNamespace
|
||||
from typing import cast
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from core.douyu import DouyuLogin, WgapiLoginAPI
|
||||
from core.douyu.login import AccountLike
|
||||
from core.douyu.proxy_fetcher import ProxyFetcher
|
||||
|
||||
from ..database import SessionLocal
|
||||
from ..models import ProxyConfig as ProxyConfigModel
|
||||
from .account_events_service import CATEGORY_AUTH, emit
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
@@ -24,6 +28,10 @@ def _now() -> datetime:
|
||||
return datetime.now(UTC)
|
||||
|
||||
|
||||
#: 账号检测结果写进账号时间线的事件类型(仅「按账号选择」模式会有,
|
||||
#: 模式下手动粘贴的文本**没有 account_id**,无从归属,保持原样不落库)。
|
||||
EVENT_ACCOUNT_CHECK = "account_check"
|
||||
|
||||
STATUS_LABELS = {
|
||||
"account_cancelled": "账号已注销",
|
||||
"password_wrong": "账号密码错误",
|
||||
@@ -54,6 +62,9 @@ class AccountCheckInput:
|
||||
password: str
|
||||
email: str
|
||||
email_password: str
|
||||
#: 「按账号选择」模式下才有:把检测结果归回库里的账号。
|
||||
#: 手动粘贴的文本没有它 —— 那正是旧模式与账号域脱节的地方,保留原样。
|
||||
account_id: int | None = None
|
||||
|
||||
def export_line(self) -> str:
|
||||
"""导出为统一四段格式。"""
|
||||
@@ -68,6 +79,7 @@ class AccountCheckItemState:
|
||||
username: str
|
||||
email: str
|
||||
export_text: str
|
||||
account_id: int | None = None
|
||||
status: str = "pending"
|
||||
message: str = "等待开始"
|
||||
started_at: datetime | None = None
|
||||
@@ -78,6 +90,7 @@ class AccountCheckItemState:
|
||||
"line": self.line,
|
||||
"username": self.username,
|
||||
"email": self.email,
|
||||
"account_id": self.account_id,
|
||||
"status": self.status,
|
||||
"message": self.message,
|
||||
"started_at": self.started_at,
|
||||
@@ -103,6 +116,36 @@ class AccountCheckBatch:
|
||||
finished_at: datetime | None = None
|
||||
|
||||
|
||||
def build_inputs_from_accounts(
|
||||
accounts: list, account_ids: list[int]
|
||||
) -> list[AccountCheckInput]:
|
||||
"""把库里的账号转成检测输入(**按账号选择**模式)。
|
||||
|
||||
凭据直接取账号自己的字段 —— 这正是与旧模式的区别:旧模式要人工把凭据
|
||||
粘贴进来,检测完结果无处可归;这里每个条目都带着 `account_id`,
|
||||
结果能写回该账号的时间线。
|
||||
|
||||
只接受调用方已经按可见性筛过的账号列表(路由层负责过滤)。
|
||||
"""
|
||||
by_id = {int(a.id): a for a in accounts}
|
||||
inputs: list[AccountCheckInput] = []
|
||||
for line_no, account_id in enumerate(account_ids, 1):
|
||||
account = by_id.get(int(account_id))
|
||||
if account is None:
|
||||
continue
|
||||
inputs.append(
|
||||
AccountCheckInput(
|
||||
line=line_no,
|
||||
username=str(account.username or ""),
|
||||
password=str(account.password or ""),
|
||||
email=str(account.email or ""),
|
||||
email_password=str(account.email_password or ""),
|
||||
account_id=int(account.id),
|
||||
)
|
||||
)
|
||||
return inputs
|
||||
|
||||
|
||||
def parse_account_check_lines(text: str) -> list[AccountCheckInput]:
|
||||
"""解析账号检测导入文本,支持 ---- 和 | 两种分隔符。"""
|
||||
accounts: list[AccountCheckInput] = []
|
||||
@@ -210,6 +253,54 @@ class AccountCheckRunner:
|
||||
item = self.batch.items[index]
|
||||
for key, value in updates.items():
|
||||
setattr(item, key, value)
|
||||
# ⚠️ 必须判**非空**而不是「键存在」:`_run_one` 置 running 时会显式传
|
||||
# `finished_at=None`,用 `in` 判断会把中间态也当终态 —— 于是事件记为
|
||||
# 「running」,而真正的终态撞同一个幂等键被静默丢弃(只剩一条错的)。
|
||||
snapshot = dict(item.to_dict()) if updates.get("finished_at") else None
|
||||
|
||||
# 终态(带 finished_at)且这个条目归属于某个库内账号时,把结果写进它的时间线。
|
||||
# 手动粘贴的条目没有 account_id → 保持旧行为(只在批次里 / 导出 zip),
|
||||
# 这正是「旧逻辑保留」的部分。
|
||||
if snapshot and snapshot.get("account_id"):
|
||||
self._emit_result(snapshot)
|
||||
|
||||
def _emit_result(self, item: dict) -> None:
|
||||
"""把一个条目的检测结果写成账号事件。
|
||||
|
||||
**绝不影响检测**:事件是旁路,任何失败都只记日志。
|
||||
线程里自己开一个会话(批次跑在后台线程,不能借用请求的 session)。
|
||||
"""
|
||||
status = str(item.get("status") or "")
|
||||
message = str(item.get("message") or "")
|
||||
try:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
emit(
|
||||
db,
|
||||
account_id=int(item["account_id"]),
|
||||
event_type=EVENT_ACCOUNT_CHECK,
|
||||
title=f"账号检测:{STATUS_LABELS.get(status, status)}",
|
||||
category=CATEGORY_AUTH,
|
||||
occurred_at=item.get("finished_at") or _now(),
|
||||
detail={
|
||||
"batch_id": self.batch.batch_id,
|
||||
"status": status,
|
||||
"message": message,
|
||||
},
|
||||
source="account_check",
|
||||
# 幂等键带上批次:同一次检测重试/重放不会写两条,
|
||||
# 但再次检测同一账号是**新的事实**,应该各留一条。
|
||||
source_ref=(
|
||||
f"account_check:{self.batch.batch_id}:{item['account_id']}"
|
||||
),
|
||||
)
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
except Exception as exc: # noqa: BLE001 旁路,绝不能影响检测
|
||||
logger.warning(
|
||||
f"账号检测结果写事件失败(account={item.get('account_id')}):{exc}"
|
||||
)
|
||||
|
||||
def _set_batch(self, **updates):
|
||||
with self._lock:
|
||||
@@ -411,6 +502,9 @@ class AccountCheckRegistry:
|
||||
username=account.username,
|
||||
email=account.email,
|
||||
export_text=account.export_line(),
|
||||
# ⚠️ 必须带上:`_set_item` 靠它决定要不要把结果写进账号时间线。
|
||||
# 漏了这一行 → 条目看着有账号,事件却永远不发(静默)。
|
||||
account_id=account.account_id,
|
||||
)
|
||||
for account in accounts
|
||||
],
|
||||
|
||||
Reference in New Issue
Block a user