修复(CK检测): 统一斗鱼CK有效性检测入口并禁止非鉴权接口覆盖状态

This commit is contained in:
yml
2026-11-26 17:38:50 +08:00
parent 3431705096
commit 7a20c63464
9 changed files with 489 additions and 76 deletions
+75
View File
@@ -109,6 +109,11 @@ def test_execute_work_item_syncs_all_goods_and_completes(db):
session_factory=make_test_session,
client_factory=lambda _cookie: object(),
snapshot_fetcher=lambda *_args, **_kwargs: _snapshot(),
session_checker=lambda _cookie: {
"valid": True,
"message": "有效",
"checked_at": datetime.now(UTC),
},
)
with make_test_session() as verify:
@@ -158,6 +163,11 @@ def test_work_item_failure_returns_to_pending_for_retry(db):
session_factory=make_test_session,
client_factory=lambda _cookie: object(),
snapshot_fetcher=fail,
session_checker=lambda _cookie: {
"valid": True,
"message": "有效",
"checked_at": datetime.now(UTC),
},
)
with make_test_session() as verify:
@@ -212,6 +222,11 @@ def test_esports_profile_sync_persists_data_without_rewriting_ck(db):
session_factory=make_test_session,
client_factory=lambda _cookie: object(),
probe_fetcher=probe,
session_checker=lambda _cookie: {
"valid": True,
"message": "有效",
"checked_at": datetime.now(UTC),
},
)
with make_test_session() as verify:
@@ -262,6 +277,11 @@ def test_exchange_record_work_persists_events_and_raw_projection(db):
work.id,
session_factory=make_test_session,
client_factory=lambda _cookie: _Client(),
session_checker=lambda _cookie: {
"valid": True,
"message": "有效",
"checked_at": datetime.now(UTC),
},
)
with make_test_session() as verify:
@@ -303,6 +323,11 @@ def test_run_account_sync_queue_claims_and_executes(db):
session_factory=make_test_session,
client_factory=lambda _cookie: object(),
snapshot_fetcher=lambda *_args, **_kwargs: _snapshot(),
session_checker=lambda _cookie: {
"valid": True,
"message": "有效",
"checked_at": datetime.now(UTC),
},
)
with make_test_session() as verify:
@@ -403,3 +428,53 @@ def test_expire_stale_login_work(db):
assert expired == 1
assert item.status == "failed"
assert "已转人工" in item.last_error
def test_storehome_sync_rejects_invalid_cookie_without_writing_capability(db):
_config(db)
account = _account("sync-invalid-ck")
db.add(account)
db.commit()
work = enqueue_account_work(
db,
account_id=account.id,
work_type=WORK_STOREHOME_SYNC,
)
db.commit()
claim_account_work(
db,
work_types=(WORK_STOREHOME_SYNC,),
limit=1,
)
db.commit()
called = {"snapshot": 0}
def _fail_if_called(*_args, **_kwargs):
called["snapshot"] += 1
return _snapshot()
result = execute_account_work_item(
work.id,
session_factory=make_test_session,
client_factory=lambda _cookie: object(),
snapshot_fetcher=_fail_if_called,
session_checker=lambda _cookie: {
"valid": False,
"message": "鱼丸接口: 账户登陆异常,请重新登陆;等级接口: 用户未登录",
"checked_at": datetime.now(UTC),
},
)
with make_test_session() as verify:
acc = verify.get(Account, account.id)
states = (
verify.query(AccountCommodityState)
.filter(AccountCommodityState.account_id == account.id)
.all()
)
assert result["ok"] is False
assert called["snapshot"] == 0
assert states == []
assert acc.ck_check_status == "invalid"
assert acc.status == "invalid"
+37
View File
@@ -345,6 +345,43 @@ class TestCookieOperation:
assert result["nickname"] == "new-name"
assert result["level"] == 12
@patch("web.backend.services.cookie_check_service.requests.get")
def test_cookie_check_retries_timeout_and_allows_single_endpoint_fallback(self, mock_get):
import requests as req_lib
from web.backend.services.cookie_check_service import classify_douyu_cookie_result
# fishBall 两次均网络超时,但等级接口明确返回有效 -> 降级判有效
mock_get.side_effect = [
req_lib.ReadTimeout("Read timed out."),
req_lib.ReadTimeout("Read timed out."),
SimpleNamespace(json=lambda: {"error": 0, "data": {"nn": "ok-user", "lv": 10}}),
]
res_degraded = check_douyu_cookie("valid-cookie")
assert res_degraded["valid"] is True
assert res_degraded["nickname"] == "ok-user"
assert res_degraded["level"] == 10
# 若鱼丸明确返回账户登陆异常,即使等级接口 ok 仍判失效(invalid)
mock_get.side_effect = [
SimpleNamespace(json=lambda: {"error": 1, "msg": "账户登陆异常,请重新登陆"}),
SimpleNamespace(json=lambda: {"error": 0, "data": {"nn": "ok-user", "lv": 10}}),
]
res_auth_fail = check_douyu_cookie("half-expired")
assert res_auth_fail["valid"] is False
assert classify_douyu_cookie_result(res_auth_fail) == "invalid"
# 两次全部超时(无鉴权失败)应判 error 而非 invalid
mock_get.side_effect = [
req_lib.ReadTimeout("Read timed out."),
req_lib.ReadTimeout("Read timed out."),
req_lib.ReadTimeout("Read timed out."),
req_lib.ReadTimeout("Read timed out."),
]
res_timeout = check_douyu_cookie("timeout-cookie")
assert res_timeout["valid"] is False
assert classify_douyu_cookie_result(res_timeout) == "error"
assert "网络读取超时" in res_timeout["message"]
@patch("web.backend.routers.cookies._start_relogin_accounts")
def test_relogin_invalid_only_targets_support_visible_accounts(self, start_relogin):
self.owned_account.ck_check_status = "invalid"
+102
View File
@@ -300,3 +300,105 @@ def test_persist_probe_error_preserves_last_known_role(db):
event = db.query(AccountEvent).filter_by(event_type="account_probe").one()
assert event.detail["probe_id"] == "probe-error"
assert event.detail["role"] == ROLE_ERROR
def test_probe_account_uses_unified_ck_check_even_when_client_supplied(monkeypatch):
import web.backend.services.douyu_account_probe as probe_module
checked = []
def _fake_checker(cookie: str):
checked.append(cookie)
return {
"valid": False,
"message": "鱼丸接口: 账户登陆异常,请重新登陆;等级接口: 用户未登录",
"checked_at": datetime.now(UTC),
}
monkeypatch.setattr(probe_module, "check_douyu_cookie", _fake_checker)
account = Account(
id=99,
username="client-with-ck",
password="p",
email="ck@example.com",
email_password="ep",
cookie="acf_uid=99",
)
client = ProbeClient()
result = probe_account(account, CONFIG, client=client)
assert checked == ["acf_uid=99"]
assert result["session"]["status"] == "invalid"
assert client.calls == 0
def test_persist_probe_ignores_unauthoritative_activity_session_and_verify_revalidates(db):
from web.backend.services.douyu_account_probe import verify_account_session
account = Account(
username="legacy-activity-ck",
password="p",
email="legacy@example.com",
email_password="ep",
status="invalid",
ck_check_status="invalid",
ck_checked_at=datetime.now(UTC),
ck_check_result={"message": "活动接口可用"},
cookie="acf_uid=88",
)
db.add(account)
db.commit()
persist_probe_result(
db,
account,
{
"probe_id": "non-auth",
"identity": {"uid": "88", "username": account.username},
"session": {
"status": "valid",
"message": "活动接口可用",
"authoritative": False,
"detail": {},
},
"elite": {},
"eligibility": {},
"roles": {},
"gold": {},
"goods": {},
"errors": {},
},
source="test.non_auth",
record_event=False,
commit=True,
)
db.refresh(account)
assert account.ck_check_status == "invalid"
# 即使历史误记为 valid + "活动接口可用",verify_account_session 也必须忽略缓存重检
account.ck_check_status = "valid"
account.ck_check_result = {"message": "活动接口可用"}
account.ck_checked_at = datetime.now(UTC)
db.commit()
calls = {"n": 0}
def _real_fail(_cookie: str):
calls["n"] += 1
return {
"valid": False,
"message": "鱼丸接口: 账户登陆异常,请重新登陆;等级接口: 用户未登录",
"checked_at": datetime.now(UTC),
}
session = verify_account_session(
db,
account,
source="test.recheck",
checker=_real_fail,
max_age_seconds=3600,
commit=True,
)
assert calls["n"] == 1
assert session["status"] == "invalid"
assert account.ck_check_status == "invalid"
@@ -28,10 +28,12 @@ from .account_work_queue import (
complete_account_work,
fail_account_work,
)
from .cookie_check_service import check_douyu_cookie
from .douyu_account_probe import (
config_mapping,
persist_probe_result,
probe_account,
verify_account_session,
)
from .douyu_activity_query import activity_client
from .douyu_read_gateway import StorehomeSnapshot, fetch_storehome_snapshot
@@ -56,6 +58,34 @@ ACCOUNT_SYNC_WORK_TYPES = (
)
def _ensure_live_session(
db: Session,
account: Account,
*,
work_type: str,
session_checker: Callable[[str], dict[str, Any]] | None,
) -> None:
if session_checker is None:
return
session = verify_account_session(
db,
account,
source=f"account_work.{work_type}",
checker=session_checker,
max_age_seconds=300,
record_event=False,
commit=False,
)
status = str(session.get("status") or "")
if status != "valid":
prefix = (
"账号 CK 已失效,请重新登录"
if status == "invalid"
else "账号 CK 状态无法确认"
)
raise RuntimeError(f"{prefix}:{session.get('message') or '请稍后重试'}")
def _execute_storehome_sync(
db: Session,
*,
@@ -63,11 +93,18 @@ def _execute_storehome_sync(
item: AccountWorkItem,
client_factory: Callable[[str], Any],
snapshot_fetcher: Callable[..., StorehomeSnapshot],
session_checker: Callable[[str], dict[str, Any]] | None = check_douyu_cookie,
) -> dict[str, Any]:
if not account.cookie:
raise RuntimeError("账号没有可用 CK,不能同步商品能力")
if account.ck_check_status in {"invalid", "manual"}:
raise RuntimeError(f"账号 CK 状态为 {account.ck_check_status},暂不能同步商品能力")
_ensure_live_session(
db,
account,
work_type=item.work_type,
session_checker=session_checker,
)
config = ensure_douyu_config(db)
manual_id = str(getattr(config, "manual_id", "") or "")
rid = str(getattr(config, "rid", "") or "")
@@ -160,17 +197,25 @@ def _execute_profile_sync(
item: AccountWorkItem,
client_factory: Callable[[str], Any],
probe_fetcher: Callable[..., dict[str, Any]],
session_checker: Callable[[str], dict[str, Any]] | None = check_douyu_cookie,
) -> dict[str, Any]:
if not account.cookie:
raise RuntimeError("账号没有可用 CK,不能同步账号资料")
if account.ck_check_status in {"invalid", "manual"}:
raise RuntimeError(f"账号 CK 状态为 {account.ck_check_status},暂不能同步")
_ensure_live_session(
db,
account,
work_type=item.work_type,
session_checker=session_checker,
)
config = ensure_douyu_config(db)
client = client_factory(account.cookie)
probe = probe_fetcher(
account,
config,
client=client,
session_checker=None,
**_profile_probe_kwargs(item.work_type, config),
)
errors = probe.get("errors") or {}
@@ -209,6 +254,7 @@ def _execute_exchange_records_sync(
account: Account,
item: AccountWorkItem,
client_factory: Callable[[str], Any],
session_checker: Callable[[str], dict[str, Any]] | None = check_douyu_cookie,
) -> dict[str, Any]:
if not account.cookie:
raise RuntimeError("账号没有可用 CK,不能同步兑换记录")
@@ -216,6 +262,12 @@ def _execute_exchange_records_sync(
raise RuntimeError(
f"账号 CK 状态为 {account.ck_check_status},暂不能同步兑换记录"
)
_ensure_live_session(
db,
account,
work_type=item.work_type,
session_checker=session_checker,
)
config = ensure_douyu_config(db)
result = sync_exchange_records(
db,
@@ -240,6 +292,7 @@ def execute_account_work_item(
client_factory: Callable[[str], Any] = activity_client,
snapshot_fetcher: Callable[..., StorehomeSnapshot] = fetch_storehome_snapshot,
probe_fetcher: Callable[..., dict[str, Any]] = probe_account,
session_checker: Callable[[str], dict[str, Any]] | None = check_douyu_cookie,
) -> dict[str, Any]:
"""在一个短事务中执行单条账号维护工作。"""
session = session_factory()
@@ -258,6 +311,7 @@ def execute_account_work_item(
item=item,
client_factory=client_factory,
snapshot_fetcher=snapshot_fetcher,
session_checker=session_checker,
)
elif item.work_type == WORK_EXCHANGE_RECORDS_SYNC:
result = _execute_exchange_records_sync(
@@ -265,6 +319,7 @@ def execute_account_work_item(
account=account,
item=item,
client_factory=client_factory,
session_checker=session_checker,
)
elif item.work_type in ACCOUNT_SYNC_WORK_TYPES:
result = _execute_profile_sync(
@@ -273,6 +328,7 @@ def execute_account_work_item(
item=item,
client_factory=client_factory,
probe_fetcher=probe_fetcher,
session_checker=session_checker,
)
else:
raise RuntimeError(f"不支持的工作类型: {item.work_type}")
@@ -353,6 +409,7 @@ def run_account_sync_queue(
client_factory: Callable[[str], Any] = activity_client,
snapshot_fetcher: Callable[..., StorehomeSnapshot] = fetch_storehome_snapshot,
probe_fetcher: Callable[..., dict[str, Any]] = probe_account,
session_checker: Callable[[str], dict[str, Any]] | None = check_douyu_cookie,
) -> dict[str, Any]:
"""领取少量到期工作并通过独立账号同步槽执行。"""
moment = now or datetime.now(UTC)
@@ -391,6 +448,7 @@ def run_account_sync_queue(
client_factory=client_factory,
snapshot_fetcher=snapshot_fetcher,
probe_fetcher=probe_fetcher,
session_checker=session_checker,
)
if future is not None:
futures[future] = work_id
+101 -44
View File
@@ -1,6 +1,7 @@
"""斗鱼 Cookie 有效性检测服务。"""
from datetime import UTC, datetime
from typing import Any
import requests
@@ -25,18 +26,78 @@ AUTH_FAILURE_MARKERS = (
)
def _has_auth_failure(message: str) -> bool:
lower = (message or "").lower()
return any(marker in message or marker in lower for marker in AUTH_FAILURE_MARKERS)
def _format_request_error(exc: Exception) -> str:
text = str(exc or "")
lower = text.lower()
if "proxyerror" in lower or "unable to connect to proxy" in lower:
return "请求失败: 代理连接失败"
if "timed out" in lower or "timeouterror" in lower:
return "请求失败: 网络读取超时"
if "max retries exceeded" in lower or "connection" in lower:
return "请求失败: 网络连接异常"
return f"请求失败: {text[:80]}"
def _fetch_cookie_endpoint(
url: str,
*,
params: dict[str, str],
referer: str,
cookie: str,
attempts: int = 2,
) -> tuple[dict[str, Any] | None, str]:
last_error = ""
for attempt in range(max(1, attempts)):
try:
response = requests.get(
url,
params=params,
headers={
"User-Agent": CHECK_UA,
"Accept": "application/json, text/plain, */*",
"Referer": referer,
"Cookie": cookie,
},
timeout=(5, 10),
)
data = response.json()
if isinstance(data, dict):
return data, ""
return None, "响应格式异常"
except requests.RequestException as exc:
last_error = _format_request_error(exc)
if attempt + 1 < attempts:
continue
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
last_error = _format_request_error(exc)
break
return None, last_error or "请求失败"
def classify_douyu_cookie_result(result: dict) -> str:
"""把检测结果分成 valid / invalid / error,区分失效与暂时查不到。"""
if result.get("valid"):
return "valid"
message = str(result.get("message") or "")
if any(marker in message for marker in AUTH_FAILURE_MARKERS):
if _has_auth_failure(message):
return "invalid"
return "error"
def check_douyu_cookie(cookie: str) -> dict:
"""检测斗鱼 Cookie 有效性,鱼丸与等级接口均通过才算有效。"""
"""全系统唯一的斗鱼 Cookie 有效性检测实现。
同时校验强鉴权的鱼丸接口与等级接口:
1. 任一接口明确返回未登录/登陆异常等鉴权失败时判定失效;
2. 双接口均通过时有效;若一个强鉴权接口已确认登录正常、另一端仅偶发网络超时(无鉴权失败),
经过重试仍未拿到另一端响应时也允许降级判定有效,避免单端抖动误杀正常账号;
3. 两端均网络异常(无鉴权失败文案)时判定为状态无法确认(error),不误判 CK 失效。
"""
checked_at = datetime.now(UTC)
base = {
"checked_at": checked_at,
@@ -50,19 +111,14 @@ def check_douyu_cookie(cookie: str) -> dict:
fish_ok = False
fish_msg = ""
fish_ball = None
try:
fish_data = requests.get(
FISH_BALL_API,
params={"appCode": "YJTX"},
headers={
"User-Agent": CHECK_UA,
"Accept": "application/json, text/plain, */*",
"Referer": "https://www.douyu.com/member/walletcenter",
"Cookie": cookie,
},
timeout=(5, 10),
).json()
if isinstance(fish_data, dict) and fish_data.get("error") in (0, "0"):
fish_data, fish_err = _fetch_cookie_endpoint(
FISH_BALL_API,
params={"appCode": "YJTX"},
referer="https://www.douyu.com/member/walletcenter",
cookie=cookie,
)
if fish_data is not None:
if fish_data.get("error") in (0, "0"):
fish_ok = True
fish_ball = (
(fish_data.get("data") or {}).get("count")
@@ -70,48 +126,49 @@ def check_douyu_cookie(cookie: str) -> dict:
else None
)
else:
fish_msg = (
str(fish_data.get("msg") or fish_data.get("error") or "响应异常")
if isinstance(fish_data, dict)
else "响应异常"
)
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
fish_msg = f"请求失败: {exc}"
fish_msg = str(fish_data.get("msg") or fish_data.get("error") or "响应异常")
else:
fish_msg = fish_err
level_ok = False
level_msg = ""
nickname = None
level = None
try:
level_data = requests.get(
USER_LEVEL_API,
params={"rid": "0"},
headers={
"User-Agent": CHECK_UA,
"Accept": "application/json, text/plain, */*",
"Referer": "https://www.douyu.com/pages/ord-user-level?clientType=web",
"Cookie": cookie,
},
timeout=(5, 10),
).json()
if isinstance(level_data, dict) and level_data.get("error") in (0, "0"):
level_data, level_err = _fetch_cookie_endpoint(
USER_LEVEL_API,
params={"rid": "0"},
referer="https://www.douyu.com/pages/ord-user-level?clientType=web",
cookie=cookie,
)
if level_data is not None:
if level_data.get("error") in (0, "0"):
level_ok = True
info_raw = level_data.get("data")
info = info_raw if isinstance(info_raw, dict) else {}
nickname = str(info.get("nn") or "") or None
level = info.get("lv")
else:
level_msg = (
str(level_data.get("msg") or level_data.get("error") or "响应异常")
if isinstance(level_data, dict)
else "响应异常"
)
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
level_msg = f"请求失败: {exc}"
level_msg = str(level_data.get("msg") or level_data.get("error") or "响应异常")
else:
level_msg = level_err
valid = fish_ok and level_ok
if valid:
fish_auth_failed = not fish_ok and _has_auth_failure(fish_msg)
level_auth_failed = not level_ok and _has_auth_failure(level_msg)
if fish_auth_failed or level_auth_failed:
valid = False
elif fish_ok and level_ok:
valid = True
elif fish_ok or level_ok:
# 一端强鉴权接口明确返回有效,另一端仅网络抖动/非鉴权异常
valid = True
else:
valid = False
if fish_ok and level_ok:
message = "有效"
elif valid:
detail_msg = level_msg if fish_ok else fish_msg
message = f"有效(单端网络波动降级通过: {detail_msg})"
else:
message = ";".join(
[
+92 -6
View File
@@ -566,6 +566,8 @@ def _derive_session(
"message": "活动接口可用",
"checked_at": _now().isoformat(),
"detail": {},
# 活动接口(如 storehome / getUserInfo)不完整鉴权,绝不允许直接反写账号 CK 为 valid。
"authoritative": False,
}
text = ";".join(errors.values())
if any(marker in text for marker in ("登录", "Cookie", "重定向")):
@@ -579,9 +581,88 @@ def _derive_session(
"message": _text(text or "没有可用查询结果"),
"checked_at": _now().isoformat(),
"detail": {},
"authoritative": False,
}
def _utc_aware(dt: datetime | None) -> datetime | None:
if dt is None:
return None
return dt if dt.tzinfo else dt.replace(tzinfo=UTC)
def verify_account_session(
db: Session,
account: Account,
*,
source: str,
current: User | None = None,
checker: Callable[[str], dict[str, Any]] | None = None,
max_age_seconds: int | None = None,
record_event: bool = False,
commit: bool = False,
) -> dict[str, Any]:
"""全系统统一的账号 CK 检测与写库入口。"""
cookie = str(account.cookie or "").strip()
if not cookie:
return {
"status": SESSION_UNVERIFIED,
"message": "账号没有可用登录 Cookie",
"checked_at": _now().isoformat(),
"detail": {},
}
now = _now()
if max_age_seconds is not None and max_age_seconds > 0:
checked_at = _utc_aware(account.ck_checked_at)
stored_msg = (
str((account.ck_check_result or {}).get("message") or "")
if isinstance(account.ck_check_result, dict)
else ""
)
if (
account.ck_check_status == SESSION_VALID
and checked_at is not None
and stored_msg != "活动接口可用"
and (now - checked_at).total_seconds() <= max_age_seconds
):
return {
"status": SESSION_VALID,
"message": stored_msg or "有效",
"checked_at": checked_at.isoformat(),
"detail": dict(account.ck_check_result or {}),
}
session = probe_session(cookie, checker=checker or check_douyu_cookie)
detail = session.get("detail") if isinstance(session.get("detail"), dict) else {}
persist_probe_result(
db,
account,
{
"probe_id": f"{source}:{now.timestamp()}:{account.id or 0}",
"identity": {
"uid": account.uid,
"username": account.username,
"nickname": detail.get("nickname") or "",
"nickname_source": "session",
},
"session": session,
"elite": {},
"eligibility": {},
"roles": {},
"gold": {},
"goods": {},
"errors": {},
},
current=current,
source=source,
record_event=record_event,
commit=commit,
update_session=True,
)
return session
def _identity_result(
account: Account,
cookie: str,
@@ -684,7 +765,7 @@ def probe_account(
),
)
if session_checker is _DEFAULT_SESSION_CHECKER:
session_checker = None if client is not None else check_douyu_cookie
session_checker = check_douyu_cookie
session = (
probe_session(cookie, checker=session_checker)
if callable(session_checker)
@@ -1048,11 +1129,15 @@ def persist_probe_result(
session = probe.get("session") or {}
session_status = str(session.get("status") or "")
if update_session and session_status in {
SESSION_VALID,
SESSION_INVALID,
SESSION_ERROR,
}:
session_message = str(session.get("message") or "")
is_authoritative_valid = (
session_status == SESSION_VALID
and session.get("authoritative", True) is not False
and session_message != "活动接口可用"
)
if update_session and (
is_authoritative_valid or session_status in {SESSION_INVALID, SESSION_ERROR}
):
detail = (
session.get("detail") if isinstance(session.get("detail"), dict) else {}
)
@@ -1279,4 +1364,5 @@ __all__ = [
"resolve_esports_role",
"resolve_peace_role",
"update_identity_from_cookie",
"verify_account_session",
]
+5 -25
View File
@@ -12,7 +12,7 @@ from core.douyu import DouyuActivityError
from ..database import WorkerSessionLocal
from ..models import DouyuTask
from .cookie_check_service import check_douyu_cookie
from .douyu_account_probe import persist_probe_result, probe_session
from .douyu_account_probe import verify_account_session
from .douyu_runner_bind import BindMixin
from .douyu_runner_core import ( # noqa: F401 (douyu_batch_registry 供 routers 重导出)
DouyuBatchRunnerCore,
@@ -134,35 +134,15 @@ class DouyuBatchRunner(
)
return
cookie_check = probe_session(cookie, checker=check_douyu_cookie)
ck_verdict = str(cookie_check["status"])
# 执行前的这次检测同样要写结论、由好变坏记事件、重算状态。
persist_probe_result(
cookie_check = verify_account_session(
worker_db,
account,
{
"probe_id": f"task-preflight:{task.id}",
"identity": {
"uid": account.uid,
"username": account.username,
"nickname": (
(cookie_check.get("detail") or {}).get("nickname") or ""
),
"nickname_source": "session",
},
"session": cookie_check,
"elite": {},
"eligibility": {},
"roles": {},
"gold": {},
"goods": {},
"errors": {},
},
source="douyu_task.preflight",
checker=check_douyu_cookie,
record_event=False,
commit=False,
commit=True,
)
worker_db.commit()
ck_verdict = str(cookie_check["status"])
if ck_verdict != "valid":
prefix = (
"Cookie 已失效,请重新登录"
@@ -327,6 +327,8 @@ def _capability_candidate_query(
),
case((Account.ck_check_status == "valid", 0), else_=1),
case((Account.status == "active", 0), else_=1),
Account.ck_checked_at.is_(None).asc(),
Account.ck_checked_at.desc(),
case((Account.elite_opened.is_(True), 0), else_=1),
case(
(Account.points >= max(0, int(required_points)), 0),
@@ -203,10 +203,26 @@ def refresh_exchange_eligibility(
probe = probe_account(
account,
config_mapping(config),
session_checker=None,
with_elite_role=False,
with_eligibility=True,
)
session = probe.get("session") or {}
session_status = str(session.get("status") or "")
if session_status != "valid":
persist_probe_result(
db,
account,
probe,
current=current,
source="platform.exchange_eligibility",
record_event=True,
)
prefix = (
"账号 CK 已失效,请重新登录"
if session_status == "invalid"
else "账号 CK 状态无法确认"
)
raise RuntimeError(f"{prefix}:{session.get('message') or '请稍后重试'}")
if (probe.get("elite") or {}).get("status") != CAPABILITY_OK:
raise RuntimeError(
(probe.get("errors") or {}).get("elite") or "精英宝典状态查询失败"