fix(douyu): 登录后自动复检 CK 并收紧分配池
This commit is contained in:
+9
-1
@@ -61,7 +61,15 @@ CK 本体和健康结果都在账号上:
|
|||||||
2. 只在“由好变坏”时写一条 `ck_invalid` 事件;
|
2. 只在“由好变坏”时写一条 `ck_invalid` 事件;
|
||||||
3. 重新推导账号生命周期状态。
|
3. 重新推导账号生命周期状态。
|
||||||
|
|
||||||
登录成功统一调用 `on_login_success()`:清空重登退避痕迹并重新推导状态。
|
普通登录与重登成功后,都会用本次新 Cookie 立即执行一次 CK 探针:
|
||||||
|
|
||||||
|
1. 网络探针期间不持有数据库事务;
|
||||||
|
2. 在同一事务里写回账号 Cookie、`cookie_updated_at`、`valid / invalid / error`
|
||||||
|
和晚于 Cookie 更新时间的 `ck_checked_at`;
|
||||||
|
3. 清空重登退避痕迹并重新推导状态。
|
||||||
|
|
||||||
|
分配池只接受 `ck_check_status=valid` 且 `ck_checked_at >= cookie_updated_at`
|
||||||
|
的账号。旧 Cookie 的检测结论不能用于新 Cookie。
|
||||||
清空 CK 统一调用 `on_ck_cleared()`:同时清空健康字段、记录 `ck_cleared` 事件并回到未登录。
|
清空 CK 统一调用 `on_ck_cleared()`:同时清空健康字段、记录 `ck_cleared` 事件并回到未登录。
|
||||||
|
|
||||||
## 账号事件流
|
## 账号事件流
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ S4 之前的状态(都是「定义了却从没发过」):
|
|||||||
本文件守住修复后的行为。
|
本文件守住修复后的行为。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
@@ -46,6 +46,10 @@ class _Base:
|
|||||||
email_password="ep",
|
email_password="ep",
|
||||||
cookie=kwargs.pop("cookie", "acf_uid=1"),
|
cookie=kwargs.pop("cookie", "acf_uid=1"),
|
||||||
ck_check_status=kwargs.pop("ck_check_status", "valid"),
|
ck_check_status=kwargs.pop("ck_check_status", "valid"),
|
||||||
|
cookie_updated_at=kwargs.pop(
|
||||||
|
"cookie_updated_at", NOW - timedelta(seconds=1)
|
||||||
|
),
|
||||||
|
ck_checked_at=kwargs.pop("ck_checked_at", NOW),
|
||||||
**kwargs,
|
**kwargs,
|
||||||
)
|
)
|
||||||
self.session.add(account)
|
self.session.add(account)
|
||||||
|
|||||||
@@ -12,14 +12,20 @@
|
|||||||
「筛出未分配 → 一键分给某人」不必先勾选。显式 `account_ids` 的旧路径不变。
|
「筛出未分配 → 一键分给某人」不必先勾选。显式 `account_ids` 的旧路径不变。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
from tests.support.db import get_test_engine, make_test_session
|
from tests.support.db import get_test_engine, make_test_session
|
||||||
from web.backend.models import Account, User
|
from web.backend.models import Account, User
|
||||||
from web.backend.routers.accounts import (
|
from web.backend.routers.accounts import (
|
||||||
|
assign_account,
|
||||||
assignments_summary,
|
assignments_summary,
|
||||||
batch_assign_accounts,
|
batch_assign_accounts,
|
||||||
list_accounts,
|
list_accounts,
|
||||||
)
|
)
|
||||||
from web.backend.schemas import BatchAssign
|
from web.backend.schemas import AccountAssign, BatchAssign
|
||||||
|
|
||||||
|
|
||||||
class _Base:
|
class _Base:
|
||||||
@@ -31,11 +37,13 @@ class _Base:
|
|||||||
self.other = User(username="af-kf2", password_hash="h", role="support")
|
self.other = User(username="af-kf2", password_hash="h", role="support")
|
||||||
self.session.add_all([self.admin, self.support, self.other])
|
self.session.add_all([self.admin, self.support, self.other])
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
|
self.now = datetime.now(UTC)
|
||||||
|
|
||||||
def teardown_method(self):
|
def teardown_method(self):
|
||||||
self.session.close()
|
self.session.close()
|
||||||
|
|
||||||
def make_account(self, name: str, **kwargs) -> Account:
|
def make_account(self, name: str, **kwargs) -> Account:
|
||||||
|
ck_check_status = kwargs.pop("ck_check_status", "valid")
|
||||||
account = Account(
|
account = Account(
|
||||||
username=name,
|
username=name,
|
||||||
password="p",
|
password="p",
|
||||||
@@ -43,6 +51,11 @@ class _Base:
|
|||||||
email_password="ep",
|
email_password="ep",
|
||||||
# 默认持有 CK —— 分配接口只接受「还拿着 CK」的账号
|
# 默认持有 CK —— 分配接口只接受「还拿着 CK」的账号
|
||||||
cookie=kwargs.pop("cookie", "acf_uid=1"),
|
cookie=kwargs.pop("cookie", "acf_uid=1"),
|
||||||
|
ck_check_status=ck_check_status,
|
||||||
|
cookie_updated_at=kwargs.pop(
|
||||||
|
"cookie_updated_at", self.now - timedelta(seconds=1)
|
||||||
|
),
|
||||||
|
ck_checked_at=kwargs.pop("ck_checked_at", self.now),
|
||||||
**kwargs,
|
**kwargs,
|
||||||
)
|
)
|
||||||
self.session.add(account)
|
self.session.add(account)
|
||||||
@@ -102,19 +115,23 @@ class TestAssignFilter(_Base):
|
|||||||
|
|
||||||
|
|
||||||
class TestAssignablePool(_Base):
|
class TestAssignablePool(_Base):
|
||||||
"""分配池口径:CK 失效的号必须先修复,不能混进「未分配」让人误分配。"""
|
"""分配池口径:只收当前 Cookie 的新鲜有效检测结果。"""
|
||||||
|
|
||||||
def test_assignable_only_excludes_invalid_ck(self):
|
def test_assignable_only_requires_fresh_valid_ck(self):
|
||||||
self.make_account("ap-valid", ck_check_status="valid")
|
self.make_account("ap-valid", ck_check_status="valid")
|
||||||
self.make_account("ap-unchecked") # 还没检测过:按可用处理
|
self.make_account("ap-unchecked", ck_check_status="", ck_checked_at=None)
|
||||||
self.make_account("ap-error", ck_check_status="error") # 查不到 ≠ 失效
|
self.make_account("ap-error", ck_check_status="error")
|
||||||
self.make_account("ap-invalid", ck_check_status="invalid")
|
self.make_account("ap-invalid", ck_check_status="invalid")
|
||||||
|
self.make_account(
|
||||||
|
"ap-stale-valid",
|
||||||
|
ck_check_status="valid",
|
||||||
|
cookie_updated_at=self.now,
|
||||||
|
ck_checked_at=self.now - timedelta(seconds=1),
|
||||||
|
)
|
||||||
self.make_account("ap-disabled", ck_check_status="valid", status="disabled")
|
self.make_account("ap-disabled", ck_check_status="valid", status="disabled")
|
||||||
|
|
||||||
assert self.names(assign_status="unassigned", assignable_only=True) == [
|
assert self.names(assign_status="unassigned", assignable_only=True) == [
|
||||||
"ap-valid",
|
"ap-valid",
|
||||||
"ap-unchecked",
|
|
||||||
"ap-error",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
def test_summary_counts_only_assignable(self):
|
def test_summary_counts_only_assignable(self):
|
||||||
@@ -160,6 +177,25 @@ class TestAssignablePool(_Base):
|
|||||||
assert valid.assigned_to == self.support.id
|
assert valid.assigned_to == self.support.id
|
||||||
assert invalid.assigned_to is None
|
assert invalid.assigned_to is None
|
||||||
|
|
||||||
|
def test_single_assign_rejects_stale_valid_verdict(self):
|
||||||
|
stale = self.make_account(
|
||||||
|
"single-stale",
|
||||||
|
ck_check_status="valid",
|
||||||
|
cookie_updated_at=self.now,
|
||||||
|
ck_checked_at=self.now - timedelta(seconds=1),
|
||||||
|
)
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException) as exc_info:
|
||||||
|
assign_account(
|
||||||
|
stale.id,
|
||||||
|
AccountAssign(assigned_to=self.support.id),
|
||||||
|
db=self.session,
|
||||||
|
current=self.admin,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert exc_info.value.status_code == 400
|
||||||
|
assert "有效 CK 检测" in exc_info.value.detail
|
||||||
|
|
||||||
|
|
||||||
class TestAllMatchingAssign(_Base):
|
class TestAllMatchingAssign(_Base):
|
||||||
def test_assigns_every_matching_unassigned(self):
|
def test_assigns_every_matching_unassigned(self):
|
||||||
|
|||||||
@@ -86,8 +86,31 @@ class TestLoginAttemptIsolation:
|
|||||||
def teardown_method(self):
|
def teardown_method(self):
|
||||||
self.session.close()
|
self.session.close()
|
||||||
|
|
||||||
def _run_batch(self, monkeypatch, *, mode="login", account_ids=None, stop=False):
|
def _run_batch(
|
||||||
|
self,
|
||||||
|
monkeypatch,
|
||||||
|
*,
|
||||||
|
mode="login",
|
||||||
|
account_ids=None,
|
||||||
|
stop=False,
|
||||||
|
cookie_check=None,
|
||||||
|
):
|
||||||
monkeypatch.setattr(login_service, "DouyuLogin", _FakeLogin)
|
monkeypatch.setattr(login_service, "DouyuLogin", _FakeLogin)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
login_service,
|
||||||
|
"check_douyu_cookie",
|
||||||
|
cookie_check
|
||||||
|
or (
|
||||||
|
lambda _cookie: {
|
||||||
|
"valid": True,
|
||||||
|
"message": "ok",
|
||||||
|
"fish_ball": 1,
|
||||||
|
"nickname": "n",
|
||||||
|
"level": 1,
|
||||||
|
"checked_at": datetime.now(UTC),
|
||||||
|
}
|
||||||
|
),
|
||||||
|
)
|
||||||
# 批次结束时 runner 会关掉自己的会话,因此单独给它一个。
|
# 批次结束时 runner 会关掉自己的会话,因此单独给它一个。
|
||||||
runner_db = sessionmaker(bind=self.engine)()
|
runner_db = sessionmaker(bind=self.engine)()
|
||||||
runner = login_service.LoginBatchRunner(
|
runner = login_service.LoginBatchRunner(
|
||||||
@@ -163,7 +186,7 @@ class TestLoginAttemptIsolation:
|
|||||||
task = self._fresh(self.task_id)
|
task = self._fresh(self.task_id)
|
||||||
account = self._fresh_account()
|
account = self._fresh_account()
|
||||||
assert task.status == "success"
|
assert task.status == "success"
|
||||||
assert task.message == "登录成功"
|
assert task.message == "登录成功,Cookie 有效"
|
||||||
assert task.attempt_status == "success"
|
assert task.attempt_status == "success"
|
||||||
assert task.attempt_at is not None
|
assert task.attempt_at is not None
|
||||||
assert task.batch_id != "old-batch"
|
assert task.batch_id != "old-batch"
|
||||||
@@ -171,6 +194,9 @@ class TestLoginAttemptIsolation:
|
|||||||
assert account.cookie == "new-cookie"
|
assert account.cookie == "new-cookie"
|
||||||
assert account.cookie_updated_at is not None
|
assert account.cookie_updated_at is not None
|
||||||
assert account.cookie_source == "web"
|
assert account.cookie_source == "web"
|
||||||
|
assert account.ck_check_status == "valid"
|
||||||
|
assert account.ck_checked_at >= account.cookie_updated_at
|
||||||
|
assert account.status == "active"
|
||||||
|
|
||||||
def test_relogin_success_writes_ck_verdict_on_the_account(self, monkeypatch):
|
def test_relogin_success_writes_ck_verdict_on_the_account(self, monkeypatch):
|
||||||
"""重登成功后的复检必须写到账号上,不能写到登录器的临时对象上。
|
"""重登成功后的复检必须写到账号上,不能写到登录器的临时对象上。
|
||||||
@@ -181,19 +207,6 @@ class TestLoginAttemptIsolation:
|
|||||||
"""
|
"""
|
||||||
self.account.ck_check_status = "invalid"
|
self.account.ck_check_status = "invalid"
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
monkeypatch.setattr(
|
|
||||||
login_service,
|
|
||||||
"check_douyu_cookie",
|
|
||||||
lambda _cookie: {
|
|
||||||
"valid": True,
|
|
||||||
"message": "ok",
|
|
||||||
"fish_ball": 1,
|
|
||||||
"nickname": "n",
|
|
||||||
"level": 1,
|
|
||||||
"checked_at": datetime.now(UTC),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
self._run_batch(monkeypatch, mode="relogin")
|
self._run_batch(monkeypatch, mode="relogin")
|
||||||
|
|
||||||
task = self._fresh(self.task_id)
|
task = self._fresh(self.task_id)
|
||||||
@@ -203,6 +216,46 @@ class TestLoginAttemptIsolation:
|
|||||||
assert account.cookie == "new-cookie"
|
assert account.cookie == "new-cookie"
|
||||||
assert account.ck_check_status == "valid"
|
assert account.ck_check_status == "valid"
|
||||||
|
|
||||||
|
def test_normal_login_replaces_stale_invalid_verdict_after_probe(self, monkeypatch):
|
||||||
|
self.account.ck_check_status = "invalid"
|
||||||
|
self.account.status = "invalid"
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
self._run_batch(monkeypatch)
|
||||||
|
|
||||||
|
task = self._fresh(self.task_id)
|
||||||
|
account = self._fresh_account()
|
||||||
|
assert task.attempt_status == "success"
|
||||||
|
assert task.message == "登录成功,Cookie 有效"
|
||||||
|
assert account.cookie == "new-cookie"
|
||||||
|
assert account.ck_check_status == "valid"
|
||||||
|
assert account.ck_checked_at >= account.cookie_updated_at
|
||||||
|
assert account.status == "active"
|
||||||
|
|
||||||
|
def test_login_success_with_failed_probe_keeps_account_out_of_pool(
|
||||||
|
self, monkeypatch
|
||||||
|
):
|
||||||
|
self.account.ck_check_status = "invalid"
|
||||||
|
self.account.status = "invalid"
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
self._run_batch(
|
||||||
|
monkeypatch,
|
||||||
|
cookie_check=lambda _cookie: {
|
||||||
|
"valid": False,
|
||||||
|
"message": "Cookie 已失效",
|
||||||
|
"checked_at": datetime.now(UTC),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
task = self._fresh(self.task_id)
|
||||||
|
account = self._fresh_account()
|
||||||
|
assert task.attempt_status == "success"
|
||||||
|
assert "Cookie 有效性检测失败" in task.message
|
||||||
|
assert account.cookie == "new-cookie"
|
||||||
|
assert account.ck_check_status == "invalid"
|
||||||
|
assert account.status == "invalid"
|
||||||
|
|
||||||
def test_stopped_batch_keeps_existing_cookie(self, monkeypatch):
|
def test_stopped_batch_keeps_existing_cookie(self, monkeypatch):
|
||||||
self._run_batch(monkeypatch, stop=True)
|
self._run_batch(monkeypatch, stop=True)
|
||||||
|
|
||||||
|
|||||||
@@ -87,15 +87,13 @@ def _visible_accounts_query(db: Session, current: User):
|
|||||||
|
|
||||||
|
|
||||||
def _assignable_account_filter():
|
def _assignable_account_filter():
|
||||||
"""分配池口径:有 CK 且 CK **还没被判失效**,并且没被人工停用/归档。
|
"""分配池口径:当前 Cookie 必须有一次不早于它的有效 CK 检测。"""
|
||||||
|
|
||||||
- `ck_check_status` 为空 = 还没检测过(`derive_status` 同样按可用处理);
|
|
||||||
- `error` = 本轮查不到,不代表失效,照常留在池子里;
|
|
||||||
- `invalid` = 巡检已判失效,必须先重登/修复,分配给它也跑不了任何任务。
|
|
||||||
"""
|
|
||||||
return and_(
|
return and_(
|
||||||
cookie_holding_filter(),
|
cookie_holding_filter(),
|
||||||
or_(Account.ck_check_status.is_(None), Account.ck_check_status != "invalid"),
|
Account.ck_check_status == "valid",
|
||||||
|
Account.ck_checked_at.isnot(None),
|
||||||
|
Account.cookie_updated_at.isnot(None),
|
||||||
|
Account.ck_checked_at >= Account.cookie_updated_at,
|
||||||
or_(
|
or_(
|
||||||
Account.status.is_(None),
|
Account.status.is_(None),
|
||||||
Account.status.notin_([STATUS_DISABLED, STATUS_ARCHIVED]),
|
Account.status.notin_([STATUS_DISABLED, STATUS_ARCHIVED]),
|
||||||
@@ -442,7 +440,7 @@ def list_accounts(
|
|||||||
assigned_user_id: int | None = Query(None, description="只看某个客服名下的账号"),
|
assigned_user_id: int | None = Query(None, description="只看某个客服名下的账号"),
|
||||||
assignable_only: bool = Query(
|
assignable_only: bool = Query(
|
||||||
False,
|
False,
|
||||||
description="只看可分配账号:持 CK 且 CK 未失效(排除已停用/归档)",
|
description="只看可分配账号:当前 Cookie 已通过新鲜 CK 检测(排除已停用/归档)",
|
||||||
),
|
),
|
||||||
tag: str = Query(None),
|
tag: str = Query(None),
|
||||||
account_names: str = Query(
|
account_names: str = Query(
|
||||||
@@ -1025,17 +1023,20 @@ def assign_account(
|
|||||||
if target.role != "support":
|
if target.role != "support":
|
||||||
raise HTTPException(status_code=400, detail="只能分配给客服角色")
|
raise HTTPException(status_code=400, detail="只能分配给客服角色")
|
||||||
|
|
||||||
# 只能分配当前仍持有 CK 的账号(CK 现在挂在账号上)
|
# 只能分配当前 Cookie 已通过新鲜 CK 检测的账号。
|
||||||
has_success = (
|
has_success = (
|
||||||
db.query(Account)
|
db.query(Account)
|
||||||
.filter(
|
.filter(
|
||||||
Account.id == account_id,
|
Account.id == account_id,
|
||||||
cookie_holding_filter(),
|
_assignable_account_filter(),
|
||||||
)
|
)
|
||||||
.first()
|
.first()
|
||||||
)
|
)
|
||||||
if not has_success:
|
if not has_success:
|
||||||
raise HTTPException(status_code=400, detail="该账号尚未成功登录,无法分配")
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="该账号尚未通过有效 CK 检测,无法分配",
|
||||||
|
)
|
||||||
|
|
||||||
if acc.assigned_to != req.assigned_to:
|
if acc.assigned_to != req.assigned_to:
|
||||||
acc.assigned_to = req.assigned_to
|
acc.assigned_to = req.assigned_to
|
||||||
@@ -1081,27 +1082,28 @@ def batch_assign_accounts(
|
|||||||
if target.role != "support":
|
if target.role != "support":
|
||||||
raise HTTPException(status_code=400, detail="只能分配给客服角色")
|
raise HTTPException(status_code=400, detail="只能分配给客服角色")
|
||||||
|
|
||||||
# 只能分配当前仍持有 CK 的账号(CK 现在挂在账号上)
|
# 只能分配当前 Cookie 已通过新鲜 CK 检测的账号。
|
||||||
cookie_ids_query = select(Account.id).where(cookie_holding_filter())
|
assignable_ids = {
|
||||||
invalid_ids = (
|
int(account_id)
|
||||||
db.query(Account.id)
|
for (account_id,) in (
|
||||||
.filter(
|
db.query(Account.id)
|
||||||
Account.id.in_(ids),
|
.filter(
|
||||||
Account.id.notin_(cookie_ids_query),
|
Account.id.in_(ids),
|
||||||
)
|
_assignable_account_filter(),
|
||||||
.all()
|
)
|
||||||
)
|
|
||||||
if invalid_ids:
|
|
||||||
names = (
|
|
||||||
db.query(Account.username)
|
|
||||||
.filter(Account.id.in_([i[0] for i in invalid_ids]))
|
|
||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
invalid_ids = [
|
||||||
|
account_id for account_id in ids if account_id not in assignable_ids
|
||||||
|
]
|
||||||
|
if invalid_ids:
|
||||||
|
names = db.query(Account.username).filter(Account.id.in_(invalid_ids)).all()
|
||||||
name_list = ", ".join([n[0] for n in names[:5]])
|
name_list = ", ".join([n[0] for n in names[:5]])
|
||||||
suffix = "..." if len(invalid_ids) > 5 else ""
|
suffix = "..." if len(invalid_ids) > 5 else ""
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=400,
|
status_code=400,
|
||||||
detail=f"以下账号尚未成功登录,无法分配:{name_list}{suffix}",
|
detail=f"以下账号尚未通过有效 CK 检测,无法分配:{name_list}{suffix}",
|
||||||
)
|
)
|
||||||
|
|
||||||
# 先取出账号对象(批量时间线要逐个写事件,光有 count 不够)。
|
# 先取出账号对象(批量时间线要逐个写事件,光有 count 不够)。
|
||||||
@@ -1176,9 +1178,9 @@ def assignments_summary(
|
|||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
current: User = Depends(require_permission("account:assign")),
|
current: User = Depends(require_permission("account:assign")),
|
||||||
):
|
):
|
||||||
"""分配概览:每个客服分到了多少**可分配账号**(持 CK 且 CK 未失效)。
|
"""分配概览:每个客服分到了多少**可分配账号**(当前 Cookie 已通过新鲜 CK 检测)。
|
||||||
|
|
||||||
失效 CK 的账号必须先重登/修复,放进分配池只会让客服以为能跑任务,
|
未检测、检测失败或旧结论的账号必须先重登/复检,放进分配池只会让客服以为能跑任务,
|
||||||
所以列表、全量分配与这里的统计统一用 `_assignable_account_filter()`。
|
所以列表、全量分配与这里的统计统一用 `_assignable_account_filter()`。
|
||||||
"""
|
"""
|
||||||
results = (
|
results = (
|
||||||
|
|||||||
@@ -212,7 +212,7 @@ class AccountBulkSelection(BaseModel):
|
|||||||
assign_status: str = ""
|
assign_status: str = ""
|
||||||
#: 只看某个客服名下的账号(与 assign_status 可叠加)
|
#: 只看某个客服名下的账号(与 assign_status 可叠加)
|
||||||
assigned_user_id: int | None = None
|
assigned_user_id: int | None = None
|
||||||
#: 分配池口径:持 CK 且 CK 未失效(排除停用/归档)
|
#: 分配池口径:当前 Cookie 已有不早于它的 valid CK 检测(排除停用/归档)
|
||||||
assignable_only: bool = False
|
assignable_only: bool = False
|
||||||
has_cookie: bool = False
|
has_cookie: bool = False
|
||||||
status: str = ""
|
status: str = ""
|
||||||
|
|||||||
@@ -239,6 +239,62 @@ def _write_login_success(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _persist_login_cookie_verification(
|
||||||
|
db: Session,
|
||||||
|
task: LoginTask,
|
||||||
|
account: AccountModel,
|
||||||
|
check_result: dict,
|
||||||
|
*,
|
||||||
|
batch_id: str,
|
||||||
|
mode: str,
|
||||||
|
) -> str:
|
||||||
|
"""把新 Cookie 的检测结论落到账号。
|
||||||
|
|
||||||
|
普通登录与重登共享这一入口。登录成功只证明登录流程拿到了 Cookie,不能
|
||||||
|
直接复用账号上一次的 CK 结论;必须让本次新 Cookie 形成 ``valid/invalid/error``
|
||||||
|
的新鲜判定,分配池才能据此放行。
|
||||||
|
"""
|
||||||
|
detail = (
|
||||||
|
check_result.get("detail")
|
||||||
|
if isinstance(check_result.get("detail"), dict)
|
||||||
|
else {}
|
||||||
|
)
|
||||||
|
persist_probe_result(
|
||||||
|
db,
|
||||||
|
account,
|
||||||
|
{
|
||||||
|
"probe_id": f"login-verify:{batch_id}:{task.id}",
|
||||||
|
"identity": {
|
||||||
|
"uid": account.uid,
|
||||||
|
"username": account.username,
|
||||||
|
"nickname": detail.get("nickname") or "",
|
||||||
|
"nickname_source": "session",
|
||||||
|
},
|
||||||
|
"session": check_result,
|
||||||
|
"elite": {},
|
||||||
|
"eligibility": {},
|
||||||
|
"roles": {},
|
||||||
|
"gold": {},
|
||||||
|
"goods": {},
|
||||||
|
"errors": {},
|
||||||
|
},
|
||||||
|
source="login.verify",
|
||||||
|
record_event=False,
|
||||||
|
commit=False,
|
||||||
|
)
|
||||||
|
prefix = "重新登录成功" if mode == "relogin" else "登录成功"
|
||||||
|
if check_result.get("status") == "valid":
|
||||||
|
message = f"{prefix},Cookie 有效"
|
||||||
|
else:
|
||||||
|
message = (
|
||||||
|
f"{prefix},但 Cookie 有效性检测失败: "
|
||||||
|
f"{check_result.get('message') or '状态未知'}"
|
||||||
|
)
|
||||||
|
task.message = message[:512]
|
||||||
|
task.attempt_message = task.message
|
||||||
|
return task.message
|
||||||
|
|
||||||
|
|
||||||
class LoginBatchRunner:
|
class LoginBatchRunner:
|
||||||
"""批量登录执行器,在线程中运行,通过 ThreadPoolExecutor 并发登录多个账号。"""
|
"""批量登录执行器,在线程中运行,通过 ThreadPoolExecutor 并发登录多个账号。"""
|
||||||
|
|
||||||
@@ -495,46 +551,10 @@ class LoginBatchRunner:
|
|||||||
)
|
)
|
||||||
elif result.success:
|
elif result.success:
|
||||||
message = result.message or "登录成功"
|
message = result.message or "登录成功"
|
||||||
if self.mode == "relogin" and account is not None:
|
check_result = probe_session(
|
||||||
check_result = probe_session(
|
result.cookie,
|
||||||
result.cookie,
|
checker=check_douyu_cookie,
|
||||||
checker=check_douyu_cookie,
|
)
|
||||||
)
|
|
||||||
detail = (
|
|
||||||
check_result.get("detail")
|
|
||||||
if isinstance(check_result.get("detail"), dict)
|
|
||||||
else {}
|
|
||||||
)
|
|
||||||
persist_probe_result(
|
|
||||||
worker_db,
|
|
||||||
account,
|
|
||||||
{
|
|
||||||
"probe_id": f"relogin:{self.batch_id}:{task.id}",
|
|
||||||
"identity": {
|
|
||||||
"uid": account.uid,
|
|
||||||
"username": account.username,
|
|
||||||
"nickname": detail.get("nickname") or "",
|
|
||||||
"nickname_source": "session",
|
|
||||||
},
|
|
||||||
"session": check_result,
|
|
||||||
"elite": {},
|
|
||||||
"eligibility": {},
|
|
||||||
"roles": {},
|
|
||||||
"gold": {},
|
|
||||||
"goods": {},
|
|
||||||
"errors": {},
|
|
||||||
},
|
|
||||||
source="login.relogin_verify",
|
|
||||||
record_event=False,
|
|
||||||
commit=False,
|
|
||||||
)
|
|
||||||
if check_result["status"] == "valid":
|
|
||||||
message = "重新登录成功,Cookie 有效"
|
|
||||||
else:
|
|
||||||
message = (
|
|
||||||
"重新登录成功,但 Cookie 有效性检测失败: "
|
|
||||||
f"{check_result['message']}"
|
|
||||||
)
|
|
||||||
# 唯一替换旧 CK 的入口:登录成功后写回账号。
|
# 唯一替换旧 CK 的入口:登录成功后写回账号。
|
||||||
#
|
#
|
||||||
# ⚠️ 必须传 **worker_db**(本线程的会话),不能传 self.db:
|
# ⚠️ 必须传 **worker_db**(本线程的会话),不能传 self.db:
|
||||||
@@ -557,27 +577,30 @@ class LoginBatchRunner:
|
|||||||
else EVENT_LOGIN_OK
|
else EVENT_LOGIN_OK
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
if self.mode == "relogin":
|
if account is not None:
|
||||||
if account is not None and account.ck_check_status == "valid":
|
_persist_login_cookie_verification(
|
||||||
self._push_log(
|
worker_db,
|
||||||
"success",
|
task,
|
||||||
f"[{current}] {acc_info['username']} 重新登录成功,Cookie 已替换并验证有效",
|
account,
|
||||||
)
|
check_result,
|
||||||
else:
|
batch_id=self.batch_id,
|
||||||
detail = (
|
mode=self.mode,
|
||||||
account.ck_check_result.get("message")
|
)
|
||||||
if account is not None and account.ck_check_result
|
if account is not None and account.ck_check_status == "valid":
|
||||||
else ""
|
|
||||||
)
|
|
||||||
self._push_log(
|
|
||||||
"warning",
|
|
||||||
f"[{current}] {acc_info['username']} 重新登录成功,但 Cookie 有效性检测失败: {detail}",
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
self._push_log(
|
self._push_log(
|
||||||
"success",
|
"success",
|
||||||
f"[{current}] {acc_info['username']} {task.message}",
|
f"[{current}] {acc_info['username']} {task.message}",
|
||||||
)
|
)
|
||||||
|
else:
|
||||||
|
detail = (
|
||||||
|
account.ck_check_result.get("message")
|
||||||
|
if account is not None and account.ck_check_result
|
||||||
|
else ""
|
||||||
|
)
|
||||||
|
self._push_log(
|
||||||
|
"warning",
|
||||||
|
f"[{current}] {acc_info['username']} {task.message or detail}",
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
if self.mode == "relogin":
|
if self.mode == "relogin":
|
||||||
# 重登失败不动旧 CK 与成功状态,只记录这次尝试失败
|
# 重登失败不动旧 CK 与成功状态,只记录这次尝试失败
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ export interface AccountBulkSelection {
|
|||||||
assign_status?: string;
|
assign_status?: string;
|
||||||
/** 只看某个客服名下的账号 */
|
/** 只看某个客服名下的账号 */
|
||||||
assigned_user_id?: number;
|
assigned_user_id?: number;
|
||||||
/** 分配池口径:持 CK 且 CK 未失效(排除停用/归档) */
|
/** 分配池口径:当前 Cookie 已通过新鲜 CK 检测(排除停用/归档) */
|
||||||
assignable_only?: boolean;
|
assignable_only?: boolean;
|
||||||
has_cookie?: boolean;
|
has_cookie?: boolean;
|
||||||
status?: string;
|
status?: string;
|
||||||
|
|||||||
@@ -80,8 +80,7 @@ export default function AssignmentsPage() {
|
|||||||
const params: Parameters<typeof accountApi.listPaged>[0] = {
|
const params: Parameters<typeof accountApi.listPaged>[0] = {
|
||||||
page: currentPage,
|
page: currentPage,
|
||||||
page_size: pageSize,
|
page_size: pageSize,
|
||||||
// 分配池只收「有 CK 且 CK 未失效」的账号:失效号的下一步是重登/修复,
|
// 分配池只收当前 Cookie 已通过新鲜 CK 检测的账号。
|
||||||
// 不是分配给客服(分过去也跑不了任务)。
|
|
||||||
assignable_only: true,
|
assignable_only: true,
|
||||||
include_sensitive: false,
|
include_sensitive: false,
|
||||||
search: searchText.trim() || undefined,
|
search: searchText.trim() || undefined,
|
||||||
@@ -316,7 +315,7 @@ export default function AssignmentsPage() {
|
|||||||
</Col>
|
</Col>
|
||||||
<Col span={6}>
|
<Col span={6}>
|
||||||
<Card size="small">
|
<Card size="small">
|
||||||
<Tooltip title="仅统计持 CK 且 CK 未判失效、未停用/归档的账号。批量登录成功写入 CK 后会自动进入;本页每 15 秒刷新一次。">
|
<Tooltip title="仅统计当前 Cookie 已通过有效 CK 检测、且未停用/归档的账号。登录成功后会自动复检 CK;本页每 15 秒刷新一次。">
|
||||||
<Statistic
|
<Statistic
|
||||||
title="未分配"
|
title="未分配"
|
||||||
value={unassignedCount}
|
value={unassignedCount}
|
||||||
|
|||||||
Reference in New Issue
Block a user