feat(douyu): unify account probes and lifecycle writes
Centralize Douyu client creation, CK session probing, identity refresh, role alias resolution, capability persistence, cache and batch throttling across collaboration, fulfillment, tasks and cookie management. Add the account-name copy action in the collaboration table.
This commit is contained in:
@@ -74,6 +74,8 @@ DB_LOCK_WAIT_TIMEOUT=10
|
||||
DOUYU_BATCH_CREATE_CONCURRENCY=2
|
||||
DOUYU_MAX_ACTIVE_BATCHES=20
|
||||
DOUYU_MAX_ACTIVE_TASKS=250
|
||||
DOUYU_PROBE_CACHE_SECONDS=30
|
||||
DOUYU_COLLAB_VERIFY_BATCH_INTERVAL_SECONDS=0.2
|
||||
|
||||
# Cookie 安全标志(生产环境 HTTPS 部署时设为 true)
|
||||
COOKIE_SECURE=false
|
||||
|
||||
@@ -44,6 +44,8 @@ services:
|
||||
- DOUYU_BATCH_CREATE_CONCURRENCY=${DOUYU_BATCH_CREATE_CONCURRENCY:-2}
|
||||
- DOUYU_MAX_ACTIVE_BATCHES=${DOUYU_MAX_ACTIVE_BATCHES:-20}
|
||||
- DOUYU_MAX_ACTIVE_TASKS=${DOUYU_MAX_ACTIVE_TASKS:-250}
|
||||
- DOUYU_PROBE_CACHE_SECONDS=${DOUYU_PROBE_CACHE_SECONDS:-30}
|
||||
- DOUYU_COLLAB_VERIFY_BATCH_INTERVAL_SECONDS=${DOUYU_COLLAB_VERIFY_BATCH_INTERVAL_SECONDS:-0.2}
|
||||
# JWT 密钥(生产环境务必修改,可用 python -c "import secrets; print(secrets.token_urlsafe(32))" 生成)
|
||||
- JWT_SECRET_KEY=${JWT_SECRET_KEY:-}
|
||||
# 后台登录滑动会话:24h 空闲过期,7d 绝对上限。
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
"""斗鱼统一账号探针:能力分离、alias 选择和写回保护。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from web.backend.models import Account, AccountEvent
|
||||
from web.backend.services.douyu_account_probe import (
|
||||
ROLE_BOUND,
|
||||
ROLE_ERROR,
|
||||
ROLE_PENDING,
|
||||
ROLE_UNBOUND,
|
||||
ROLE_UNKNOWN,
|
||||
persist_probe_result,
|
||||
probe_account,
|
||||
resolve_elite_role,
|
||||
)
|
||||
|
||||
CONFIG = {
|
||||
"manual_id": "manual-id",
|
||||
"rid": "room-id",
|
||||
"bind_act_alias": "current-alias",
|
||||
"confirm_act_alias": "current-alias",
|
||||
"legacy_act_alias": "cjm",
|
||||
}
|
||||
|
||||
|
||||
class RoleClient:
|
||||
def __init__(self, responses, errors=None):
|
||||
self.responses = responses
|
||||
self.errors = errors or {}
|
||||
self.calls: list[str] = []
|
||||
|
||||
def bind_info(self, act_alias: str, *, v2: bool = False):
|
||||
self.calls.append(act_alias)
|
||||
if act_alias in self.errors:
|
||||
raise RuntimeError(self.errors[act_alias])
|
||||
return self.responses.get(act_alias, {})
|
||||
|
||||
|
||||
def _bind(
|
||||
role: str = "",
|
||||
*,
|
||||
bound_act: bool = False,
|
||||
bound_role: bool = False,
|
||||
need_act: bool = True,
|
||||
need_role: bool = True,
|
||||
):
|
||||
return {
|
||||
"is_bound_act": bound_act,
|
||||
"is_bound_role": bound_role,
|
||||
"need_bind_act": need_act,
|
||||
"need_bind_role": need_role,
|
||||
"role_name": role,
|
||||
"area_name": "微信" if role else "",
|
||||
"plat_name": "安卓" if role else "",
|
||||
}
|
||||
|
||||
|
||||
def test_role_resolver_prefers_current_bound_and_reports_pending_legacy():
|
||||
client = RoleClient(
|
||||
{
|
||||
"current-alias": _bind("当前角色", bound_act=True, bound_role=True),
|
||||
"cjm": _bind("新角色", bound_role=True),
|
||||
}
|
||||
)
|
||||
|
||||
result = resolve_elite_role(client, CONFIG)
|
||||
|
||||
assert result["status"] == ROLE_BOUND
|
||||
assert result["role_name"] == "当前角色"
|
||||
assert result["source_alias"] == "current-alias"
|
||||
assert result["pending_role_name"] == "新角色"
|
||||
assert client.calls == ["current-alias", "cjm"]
|
||||
|
||||
|
||||
def test_role_resolver_uses_legacy_pending_role_when_current_is_empty():
|
||||
client = RoleClient(
|
||||
{
|
||||
"current-alias": _bind(""),
|
||||
"cjm": _bind("待确认角色", bound_role=True, need_act=False),
|
||||
}
|
||||
)
|
||||
|
||||
result = resolve_elite_role(client, CONFIG)
|
||||
|
||||
assert result["status"] == ROLE_PENDING
|
||||
assert result["role_name"] == "待确认角色"
|
||||
assert result["source_alias"] == "cjm"
|
||||
|
||||
|
||||
def test_role_resolver_partial_failure_does_not_claim_unbound():
|
||||
client = RoleClient(
|
||||
{
|
||||
"current-alias": _bind(""),
|
||||
"cjm": _bind(""),
|
||||
},
|
||||
errors={"current-alias": "登录已失效"},
|
||||
)
|
||||
|
||||
result = resolve_elite_role(client, CONFIG)
|
||||
|
||||
assert result["status"] == ROLE_UNKNOWN
|
||||
assert result["errors"]
|
||||
|
||||
|
||||
def test_role_resolver_official_empty_is_explicitly_unbound():
|
||||
client = RoleClient(
|
||||
{
|
||||
"current-alias": _bind(""),
|
||||
"cjm": _bind(""),
|
||||
}
|
||||
)
|
||||
|
||||
result = resolve_elite_role(client, CONFIG)
|
||||
|
||||
assert result["status"] == ROLE_UNBOUND
|
||||
assert result["role_name"] == ""
|
||||
|
||||
|
||||
class ProbeClient:
|
||||
def __init__(self):
|
||||
self.calls = 0
|
||||
|
||||
def elite_user_info(self, **_kwargs):
|
||||
self.calls += 1
|
||||
return {
|
||||
"manual_type": 1,
|
||||
"manual_score": 100,
|
||||
"expire_time": 0,
|
||||
"user_info": {"nickname": "精英昵称"},
|
||||
}
|
||||
|
||||
def bind_info(self, act_alias: str, *, v2: bool = False):
|
||||
self.calls += 1
|
||||
return _bind("角色A", bound_act=True, bound_role=True)
|
||||
|
||||
|
||||
def test_probe_account_reads_identity_and_does_not_call_activity_for_invalid_ck():
|
||||
account = Account(
|
||||
id=1,
|
||||
username="douyu-user",
|
||||
password="p",
|
||||
email="u@example.com",
|
||||
email_password="ep",
|
||||
cookie="acf_uid=100; acf_nickname=cookie-name",
|
||||
)
|
||||
valid_client = ProbeClient()
|
||||
valid = probe_account(
|
||||
account,
|
||||
CONFIG,
|
||||
client=valid_client,
|
||||
session_checker=lambda _cookie: {
|
||||
"valid": True,
|
||||
"message": "有效",
|
||||
"nickname": "会话昵称",
|
||||
"checked_at": datetime.now(UTC),
|
||||
},
|
||||
)
|
||||
|
||||
assert valid["session"]["status"] == "valid"
|
||||
assert valid["identity"]["nickname"] == "精英昵称"
|
||||
assert valid["identity"]["nickname_source"] == "elite"
|
||||
assert valid["roles"]["elite"]["status"] == ROLE_BOUND
|
||||
|
||||
invalid_client = ProbeClient()
|
||||
invalid = probe_account(
|
||||
account,
|
||||
CONFIG,
|
||||
client=invalid_client,
|
||||
session_checker=lambda _cookie: {
|
||||
"valid": False,
|
||||
"message": "未登录",
|
||||
"checked_at": datetime.now(UTC),
|
||||
},
|
||||
)
|
||||
assert invalid["session"]["status"] == "invalid"
|
||||
assert invalid_client.calls == 0
|
||||
|
||||
|
||||
def test_persist_probe_error_preserves_last_known_role(db):
|
||||
account = Account(
|
||||
username="preserve-role",
|
||||
password="p",
|
||||
email="preserve@example.com",
|
||||
email_password="ep",
|
||||
status="active",
|
||||
cookie="acf_uid=100",
|
||||
game_name="保留角色",
|
||||
game_channel="微信 · 安卓",
|
||||
role_bind_status=ROLE_BOUND,
|
||||
)
|
||||
db.add(account)
|
||||
db.commit()
|
||||
|
||||
persist_probe_result(
|
||||
db,
|
||||
account,
|
||||
{
|
||||
"probe_id": "probe-error",
|
||||
"identity": {"uid": "100", "username": account.username},
|
||||
"session": {},
|
||||
"elite": {},
|
||||
"eligibility": {},
|
||||
"roles": {
|
||||
"elite": {
|
||||
"status": ROLE_ERROR,
|
||||
"errors": ["接口超时"],
|
||||
}
|
||||
},
|
||||
"gold": {},
|
||||
"goods": {},
|
||||
"errors": {"elite_role": "接口超时"},
|
||||
},
|
||||
source="test.role_error",
|
||||
record_event=True,
|
||||
commit=True,
|
||||
)
|
||||
|
||||
db.refresh(account)
|
||||
assert account.game_name == "保留角色"
|
||||
assert account.role_bind_status == ROLE_BOUND
|
||||
event = db.query(AccountEvent).filter_by(event_type="account_probe").one()
|
||||
assert event.detail["probe_id"] == "probe-error"
|
||||
assert event.detail["role"] == ROLE_ERROR
|
||||
@@ -7,9 +7,9 @@ from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
from core.douyu import DouyuActivityClient
|
||||
from web.backend.models import User
|
||||
from web.backend.models import Account, User
|
||||
from web.backend.routers import douyu as douyu_api
|
||||
from web.backend.services import douyu_activity_query as query
|
||||
from web.backend.services.douyu_account_probe import probe_account
|
||||
|
||||
READ_METHODS = {
|
||||
"acf_ccn",
|
||||
@@ -70,19 +70,33 @@ class FakeActivityClient:
|
||||
}
|
||||
|
||||
|
||||
def test_exchange_eligibility_is_normalized_once():
|
||||
def test_account_probe_normalizes_exchange_eligibility_once():
|
||||
client = FakeActivityClient()
|
||||
|
||||
result = query.query_exchange_eligibility(
|
||||
cast(DouyuActivityClient, client),
|
||||
account = Account(
|
||||
id=1,
|
||||
username="probe-account",
|
||||
password="p",
|
||||
email="probe@example.com",
|
||||
email_password="ep",
|
||||
uid="100",
|
||||
cookie="acf_uid=100; acf_nickname=test",
|
||||
manual_id="manual-1",
|
||||
rid="room-1",
|
||||
)
|
||||
|
||||
assert result.elite_user_info["manual_type"] == 1
|
||||
assert result.points == 5200
|
||||
assert result.limited_ids == frozenset({"limited-1"})
|
||||
result = probe_account(
|
||||
account,
|
||||
{
|
||||
"manual_id": "manual-1",
|
||||
"rid": "room-1",
|
||||
},
|
||||
client=cast(DouyuActivityClient, client),
|
||||
session_checker=None,
|
||||
with_elite_role=False,
|
||||
with_eligibility=True,
|
||||
)
|
||||
|
||||
assert result["elite"]["raw"]["manual_type"] == 1
|
||||
assert result["eligibility"]["points"] == 5200
|
||||
assert result["eligibility"]["limited_ids"] == ["limited-1"]
|
||||
assert client.calls == [
|
||||
"acf_ccn",
|
||||
"elite_user_info",
|
||||
@@ -141,3 +155,50 @@ def test_douyu_read_queries_only_call_client_from_shared_module():
|
||||
)
|
||||
|
||||
assert violations == []
|
||||
|
||||
|
||||
def test_douyu_client_factory_and_role_query_stay_centralized():
|
||||
backend = Path(__file__).parents[1] / "web" / "backend"
|
||||
client_factory = backend / "services" / "douyu_activity_query.py"
|
||||
role_probe = backend / "services" / "douyu_account_probe.py"
|
||||
constructor_violations: list[str] = []
|
||||
role_query_violations: list[str] = []
|
||||
lifecycle_write_violations: list[str] = []
|
||||
|
||||
for path in [
|
||||
*backend.glob("services/douyu_*.py"),
|
||||
*backend.glob("routers/douyu*.py"),
|
||||
]:
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
||||
for node in ast.walk(tree):
|
||||
if not isinstance(node, ast.Call):
|
||||
continue
|
||||
func = node.func
|
||||
if (
|
||||
isinstance(func, ast.Name)
|
||||
and func.id == "DouyuActivityClient"
|
||||
and path != client_factory
|
||||
):
|
||||
constructor_violations.append(
|
||||
f"{path.relative_to(backend)}:{node.lineno}"
|
||||
)
|
||||
if (
|
||||
isinstance(func, ast.Name)
|
||||
and func.id == "query_bind_info"
|
||||
and path != role_probe
|
||||
):
|
||||
role_query_violations.append(
|
||||
f"{path.relative_to(backend)}:{node.lineno}"
|
||||
)
|
||||
if (
|
||||
isinstance(func, ast.Name)
|
||||
and func.id == "on_ck_verdict"
|
||||
and path != role_probe
|
||||
):
|
||||
lifecycle_write_violations.append(
|
||||
f"{path.relative_to(backend)}:{node.lineno}"
|
||||
)
|
||||
|
||||
assert constructor_violations == []
|
||||
assert role_query_violations == []
|
||||
assert lifecycle_write_violations == []
|
||||
|
||||
@@ -34,7 +34,6 @@ from web.backend.services.automation.jobs import (
|
||||
platform_fulfillment_lease_reaper as reaper,
|
||||
)
|
||||
from web.backend.services.douyu_account_state import DouyuLiveAccountState
|
||||
from web.backend.services.douyu_activity_query import DouyuEligibilityResult
|
||||
from web.backend.services.platform_fulfillment import account_selector, service
|
||||
|
||||
NOW = datetime.now(UTC).replace(microsecond=0)
|
||||
@@ -2145,14 +2144,26 @@ class TestBindingAndCompletion(_Base):
|
||||
self.session.commit()
|
||||
monkeypatch.setattr(
|
||||
service,
|
||||
"query_exchange_eligibility",
|
||||
lambda *_args, **_kwargs: DouyuEligibilityResult(
|
||||
elite_user_info={"manual_type": 1},
|
||||
points=100,
|
||||
points_response={"points": 100},
|
||||
limited_goods=[],
|
||||
limited_ids=frozenset(),
|
||||
),
|
||||
"probe_account",
|
||||
lambda *_args, **_kwargs: {
|
||||
"probe_id": "points-short",
|
||||
"session": {"status": "valid", "message": "有效"},
|
||||
"elite": {
|
||||
"status": "ok",
|
||||
"raw": {"manual_type": 1},
|
||||
"manual_type": 1,
|
||||
"manual_score": 100,
|
||||
"opened": True,
|
||||
},
|
||||
"eligibility": {
|
||||
"points": 100,
|
||||
"points_response": {"points": 100},
|
||||
"limited_ids": [],
|
||||
"limited_goods": [],
|
||||
},
|
||||
"roles": {},
|
||||
"errors": {},
|
||||
},
|
||||
)
|
||||
|
||||
detail = service.refresh_exchange_eligibility(
|
||||
@@ -2175,14 +2186,27 @@ class TestBindingAndCompletion(_Base):
|
||||
self.session.commit()
|
||||
monkeypatch.setattr(
|
||||
service,
|
||||
"query_exchange_eligibility",
|
||||
lambda *_args, **_kwargs: DouyuEligibilityResult(
|
||||
elite_user_info={"manual_type": 1, "expire_time": 1},
|
||||
points=2000,
|
||||
points_response={"points": 2000},
|
||||
limited_goods=[],
|
||||
limited_ids=frozenset(),
|
||||
),
|
||||
"probe_account",
|
||||
lambda *_args, **_kwargs: {
|
||||
"probe_id": "expired-elite",
|
||||
"session": {"status": "valid", "message": "有效"},
|
||||
"elite": {
|
||||
"status": "ok",
|
||||
"raw": {"manual_type": 1, "expire_time": 1},
|
||||
"manual_type": 1,
|
||||
"manual_score": 2000,
|
||||
"expire_time": 1,
|
||||
"opened": False,
|
||||
},
|
||||
"eligibility": {
|
||||
"points": 2000,
|
||||
"points_response": {"points": 2000},
|
||||
"limited_ids": [],
|
||||
"limited_goods": [],
|
||||
},
|
||||
"roles": {},
|
||||
"errors": {},
|
||||
},
|
||||
)
|
||||
|
||||
detail = service.refresh_exchange_eligibility(
|
||||
|
||||
@@ -33,8 +33,9 @@ from ..models import Account, AuditLog, LoginTask, User
|
||||
from ..models import ProxyConfig as ProxyConfigModel
|
||||
from ..permissions import get_user_permissions, user_has_permission
|
||||
from ..schemas import CookieReloginRequest
|
||||
from ..services.account_lifecycle import on_ck_cleared, on_ck_verdict
|
||||
from ..services.account_lifecycle import on_ck_cleared
|
||||
from ..services.cookie_check_service import check_douyu_cookie
|
||||
from ..services.douyu_account_probe import persist_probe_result, probe_session
|
||||
from ..services.douyu_service import (
|
||||
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES,
|
||||
cookie_holding_filter,
|
||||
@@ -117,9 +118,13 @@ def _relogin_display(account: Account, in_flight_batch_id: str = "") -> dict:
|
||||
|
||||
def _check_one_cookie(account: Account) -> dict:
|
||||
"""将共享检测结果补充为 CK 记录的接口返回格式。"""
|
||||
result = check_douyu_cookie(account.cookie or "")
|
||||
session = probe_session(account.cookie or "", checker=check_douyu_cookie)
|
||||
result = dict(session.get("detail") or {})
|
||||
result["id"] = account.id
|
||||
result["checked_at"] = result["checked_at"].isoformat()
|
||||
result["valid"] = session["status"] == "valid"
|
||||
result["message"] = session["message"]
|
||||
result["checked_at"] = session["checked_at"]
|
||||
result["_session_probe"] = session
|
||||
return result
|
||||
|
||||
|
||||
@@ -502,6 +507,12 @@ def _check_cookies(ids: str, db: Session, current: User, *, detailed: bool) -> d
|
||||
"nickname": None,
|
||||
"level": None,
|
||||
"checked_at": datetime.now(UTC).isoformat(),
|
||||
"_session_probe": {
|
||||
"status": "error",
|
||||
"message": f"检测异常: {exc}",
|
||||
"checked_at": datetime.now(UTC).isoformat(),
|
||||
"detail": {},
|
||||
},
|
||||
}
|
||||
)
|
||||
results.sort(key=lambda item: item["id"])
|
||||
@@ -513,15 +524,47 @@ def _check_cookies(ids: str, db: Session, current: User, *, detailed: bool) -> d
|
||||
acc = accounts_by_id.get(item["id"])
|
||||
if not acc:
|
||||
continue
|
||||
# 人工检测结论同样走统一入口(写结论 + 由好变坏记事件 + 重算状态)
|
||||
on_ck_verdict(
|
||||
session_probe = item.pop("_session_probe", None)
|
||||
if not isinstance(session_probe, dict):
|
||||
session_probe = {
|
||||
"status": "valid" if item.get("valid") else "invalid",
|
||||
"message": item.get("message") or "",
|
||||
"checked_at": item.get("checked_at") or checked_at.isoformat(),
|
||||
"detail": {
|
||||
"valid": bool(item.get("valid")),
|
||||
"message": item.get("message") or "",
|
||||
"fish_ball": item.get("fish_ball"),
|
||||
"nickname": item.get("nickname"),
|
||||
"level": item.get("level"),
|
||||
"checked_at": item.get("checked_at") or checked_at,
|
||||
},
|
||||
}
|
||||
# 人工检测走统一探针落库:CK 能力、生命周期与账号时间线一次完成。
|
||||
persist_probe_result(
|
||||
db,
|
||||
acc,
|
||||
"valid" if item["valid"] else "invalid",
|
||||
detail=item,
|
||||
occurred_at=checked_at,
|
||||
actor_type="user",
|
||||
actor_id=current.id,
|
||||
{
|
||||
"probe_id": f"ck-check:{checked_at.timestamp()}:{acc.id}",
|
||||
"identity": {
|
||||
"uid": acc.uid,
|
||||
"username": acc.username,
|
||||
"nickname": (
|
||||
(session_probe.get("detail") or {}).get("nickname") or ""
|
||||
),
|
||||
"nickname_source": "session",
|
||||
},
|
||||
"session": session_probe,
|
||||
"elite": {},
|
||||
"eligibility": {},
|
||||
"roles": {},
|
||||
"gold": {},
|
||||
"goods": {},
|
||||
"errors": {},
|
||||
},
|
||||
current=current,
|
||||
source="account.ck_check",
|
||||
record_event=True,
|
||||
commit=False,
|
||||
)
|
||||
# 审计带上账号:单个检测时可直接反查(批量时只能落到 target 文本里)
|
||||
db.add(
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import time
|
||||
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
@@ -57,6 +59,14 @@ from ..services.douyu_collab_events import collab_events
|
||||
router = APIRouter(prefix="/api/douyu", tags=["斗鱼外部单协作"])
|
||||
|
||||
|
||||
def _verify_batch_interval() -> float:
|
||||
try:
|
||||
value = float(os.getenv("DOUYU_COLLAB_VERIFY_BATCH_INTERVAL_SECONDS", "0.2"))
|
||||
except ValueError:
|
||||
value = 0.2
|
||||
return max(0.0, min(value, 5.0))
|
||||
|
||||
|
||||
def _http_error(exc: collab.CollabError) -> ApiError:
|
||||
return ApiError(
|
||||
status_code=exc.status_code,
|
||||
@@ -356,7 +366,10 @@ def verify_external_orders_batch(
|
||||
current: User = Depends(require_permission("douyu:collab:edit")),
|
||||
):
|
||||
results: list[dict] = []
|
||||
for order_id in ids:
|
||||
interval = _verify_batch_interval()
|
||||
for index, order_id in enumerate(ids):
|
||||
if index and interval:
|
||||
time.sleep(interval)
|
||||
try:
|
||||
order = collab.get_order(db, order_id)
|
||||
result = collab.verify_order(db, current, order)
|
||||
|
||||
@@ -2535,6 +2535,8 @@ class DouyuCollabAccountLookupOut(BaseModel):
|
||||
account_nickname: str = ""
|
||||
ck_status: str = ""
|
||||
ck_status_label: str = ""
|
||||
auth_status: str = ""
|
||||
role_status: str = ""
|
||||
manual_type: int | None = None
|
||||
manual_score: int | None = None
|
||||
expire_time: int | None = None
|
||||
|
||||
@@ -17,7 +17,7 @@ from sqlalchemy import and_, func, or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ....models import Account, AutomationJob
|
||||
from ...account_lifecycle import MANUAL_STATES, on_ck_verdict
|
||||
from ...account_lifecycle import MANUAL_STATES
|
||||
from ...account_value import (
|
||||
HIGH_VALUE_TIER_MAX,
|
||||
high_value_recheck_seconds,
|
||||
@@ -27,7 +27,11 @@ from ...cookie_check_service import (
|
||||
check_douyu_cookie,
|
||||
)
|
||||
from ...cookie_check_service import (
|
||||
classify_douyu_cookie_result as classify_result,
|
||||
classify_douyu_cookie_result as classify_result, # noqa: F401 - 兼容诊断入口
|
||||
)
|
||||
from ...douyu_account_probe import (
|
||||
persist_probe_result,
|
||||
probe_session,
|
||||
)
|
||||
from ...douyu_service import cookie_holding_filter, cookie_operable_filter
|
||||
|
||||
@@ -109,15 +113,16 @@ def count_remaining(db: Session, job: AutomationJob, now: datetime) -> int:
|
||||
|
||||
def _detect(account: Account) -> dict[str, Any]:
|
||||
try:
|
||||
return check_douyu_cookie(account.cookie or "")
|
||||
return probe_session(
|
||||
account.cookie or "",
|
||||
checker=check_douyu_cookie,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 单个账号失败不影响整轮
|
||||
return {
|
||||
"valid": False,
|
||||
"status": "error",
|
||||
"message": f"检测异常: {exc}",
|
||||
"fish_ball": None,
|
||||
"nickname": None,
|
||||
"level": None,
|
||||
"checked_at": datetime.now(UTC),
|
||||
"checked_at": datetime.now(UTC).isoformat(),
|
||||
"detail": {},
|
||||
}
|
||||
|
||||
|
||||
@@ -153,16 +158,39 @@ def run_ck_health(db: Session, job: AutomationJob) -> dict[str, Any]:
|
||||
result = results.get(account.id)
|
||||
if result is None:
|
||||
continue
|
||||
verdict = classify_result(result)
|
||||
verdict = str(result.get("status") or "error")
|
||||
if verdict == "valid":
|
||||
valid += 1
|
||||
elif verdict == "invalid":
|
||||
invalid += 1
|
||||
else:
|
||||
errors += 1
|
||||
# 结论落定 = 写 ck_check_* + 由好变坏时记事件 + 重算生命周期状态。
|
||||
# 三件事的**顺序与口径**收在 `on_ck_verdict` 里,四个检测入口共用。
|
||||
on_ck_verdict(db, account, verdict, detail=result, occurred_at=now)
|
||||
# 自动巡检不额外刷 account_probe 事件;统一落库仍会处理 CK 状态变化
|
||||
# 和生命周期事件,避免每 6 小时给所有账号写一条重复查询事件。
|
||||
detail = result.get("detail") if isinstance(result.get("detail"), dict) else {}
|
||||
persist_probe_result(
|
||||
db,
|
||||
account,
|
||||
{
|
||||
"probe_id": f"ck-health:{now.timestamp()}:{account.id}",
|
||||
"identity": {
|
||||
"uid": account.uid,
|
||||
"username": account.username,
|
||||
"nickname": detail.get("nickname") or "",
|
||||
"nickname_source": "session",
|
||||
},
|
||||
"session": result,
|
||||
"elite": {},
|
||||
"eligibility": {},
|
||||
"roles": {},
|
||||
"gold": {},
|
||||
"goods": {},
|
||||
"errors": {},
|
||||
},
|
||||
source="automation.ck_health",
|
||||
record_event=False,
|
||||
commit=False,
|
||||
)
|
||||
|
||||
if index % FLUSH_EVERY == 0:
|
||||
db.commit()
|
||||
|
||||
@@ -20,6 +20,8 @@ AUTH_FAILURE_MARKERS = (
|
||||
"重新登陆",
|
||||
"重新登录",
|
||||
"账户登陆",
|
||||
"expired",
|
||||
"ck 失效",
|
||||
)
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -17,24 +17,9 @@ from sqlalchemy.orm import Session
|
||||
from core.douyu import DouyuActivityClient
|
||||
|
||||
from ..models import Account
|
||||
from .account_binding import (
|
||||
SCOPE_ELITE,
|
||||
binding_snapshot,
|
||||
is_role_change_cooling,
|
||||
role_change_available_at,
|
||||
set_bind_status,
|
||||
)
|
||||
from .account_lifecycle import on_ck_verdict
|
||||
from .cookie_check_service import check_douyu_cookie, classify_douyu_cookie_result
|
||||
from .douyu_activity_query import (
|
||||
activity_client,
|
||||
query_bind_info,
|
||||
query_exchange_eligibility,
|
||||
)
|
||||
from .douyu_elite_status import (
|
||||
elite_is_currently_open,
|
||||
normalize_elite_expire_time,
|
||||
)
|
||||
from .account_binding import is_role_change_cooling
|
||||
from .cookie_check_service import check_douyu_cookie
|
||||
from .douyu_account_probe import config_mapping, persist_probe_result, probe_account
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -107,192 +92,84 @@ def refresh_douyu_account_state(
|
||||
) -> DouyuLiveAccountState:
|
||||
"""实时刷新单个账号,并把所有可落库状态写回账号。"""
|
||||
now = datetime.now(UTC)
|
||||
cookie = str(account.cookie or "").strip()
|
||||
account_name = account.nickname or account.username or f"#{account.id}"
|
||||
ck_result = cookie_checker(cookie)
|
||||
ck_verdict = classify_douyu_cookie_result(ck_result)
|
||||
ck_message = str(ck_result.get("message") or "")
|
||||
on_ck_verdict(
|
||||
config_info = config_mapping(
|
||||
{
|
||||
"manual_id": manual_id,
|
||||
"rid": rid,
|
||||
"bind_act_alias": act_alias,
|
||||
"confirm_act_alias": act_alias,
|
||||
}
|
||||
)
|
||||
probe = probe_account(
|
||||
account,
|
||||
config_info,
|
||||
client=client,
|
||||
session_checker=cookie_checker,
|
||||
with_eligibility=True,
|
||||
)
|
||||
session = probe.get("session") or {}
|
||||
role = (probe.get("roles") or {}).get("elite") or {}
|
||||
elite = probe.get("elite") or {}
|
||||
eligibility = probe.get("eligibility") or {}
|
||||
session_status = str(session.get("status") or "")
|
||||
bind_info = role.get("bind_info") if isinstance(role.get("bind_info"), dict) else {}
|
||||
errors = list((probe.get("errors") or {}).values())
|
||||
errors.extend(role.get("errors") or [])
|
||||
if session_status != "valid":
|
||||
errors.append(
|
||||
f"CK 检测未通过: {session.get('message') or '状态未知'},未继续查询活动状态"
|
||||
)
|
||||
|
||||
persist_probe_result(
|
||||
db,
|
||||
account,
|
||||
ck_verdict,
|
||||
detail=ck_result,
|
||||
occurred_at=now,
|
||||
probe,
|
||||
source="platform.live_check",
|
||||
record_event=False,
|
||||
commit=False,
|
||||
)
|
||||
|
||||
if ck_verdict != "valid":
|
||||
snapshot = {
|
||||
"queried_at": now.isoformat(),
|
||||
"ck": ck_result,
|
||||
"errors": ["CK 检测未通过,未继续查询活动状态"],
|
||||
}
|
||||
account.overview_snapshot = _json_safe(snapshot)
|
||||
account.updated_at = now
|
||||
if commit:
|
||||
db.commit()
|
||||
return DouyuLiveAccountState(
|
||||
account_id=int(account.id),
|
||||
account_name=account_name,
|
||||
checked_at=now,
|
||||
ck_verdict=ck_verdict,
|
||||
ck_message=ck_message,
|
||||
elite_opened=account.elite_opened,
|
||||
points=account.points,
|
||||
limited_ids=frozenset(),
|
||||
role_change_available_at=account.role_change_available_at,
|
||||
)
|
||||
|
||||
active_client = client or activity_client(cookie)
|
||||
try:
|
||||
eligibility = query_exchange_eligibility(
|
||||
active_client,
|
||||
cookie=cookie,
|
||||
manual_id=manual_id,
|
||||
rid=rid,
|
||||
uid=str(account.uid or ""),
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 外部接口边界需要保留单项诊断
|
||||
error = f"{type(exc).__name__}: {exc}"[:240]
|
||||
snapshot = {
|
||||
"queried_at": now.isoformat(),
|
||||
"ck": ck_result,
|
||||
"errors": [error],
|
||||
}
|
||||
account.overview_snapshot = _json_safe(snapshot)
|
||||
account.overview_queried_at = now
|
||||
account.updated_at = now
|
||||
if commit:
|
||||
db.commit()
|
||||
return DouyuLiveAccountState(
|
||||
account_id=int(account.id),
|
||||
account_name=account_name,
|
||||
checked_at=now,
|
||||
ck_verdict=ck_verdict,
|
||||
ck_message=ck_message,
|
||||
elite_opened=account.elite_opened,
|
||||
points=account.points,
|
||||
limited_ids=frozenset(),
|
||||
role_change_available_at=account.role_change_available_at,
|
||||
error=error,
|
||||
)
|
||||
|
||||
errors: list[str] = []
|
||||
bind_info: dict[str, Any] = {}
|
||||
try:
|
||||
bind_info = query_bind_info(
|
||||
active_client,
|
||||
act_alias=act_alias,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 绑定查询失败不应丢弃资产查询结果
|
||||
errors.append(f"绑定状态查询失败: {type(exc).__name__}: {exc}"[:240])
|
||||
|
||||
elite_expire_time = normalize_elite_expire_time(
|
||||
eligibility.elite_user_info.get("expire_time")
|
||||
)
|
||||
elite_opened = elite_is_currently_open(
|
||||
eligibility.elite_user_info.get("manual_type"),
|
||||
elite_expire_time,
|
||||
now=now,
|
||||
)
|
||||
account.elite_opened = elite_opened
|
||||
account.elite_expire_time = elite_expire_time
|
||||
account.points = eligibility.points
|
||||
account.points_expire_at = _points_expire_at(
|
||||
eligibility.points_response,
|
||||
checked_at=now,
|
||||
)
|
||||
role_change_available_at = account.role_change_available_at
|
||||
if bind_info:
|
||||
role_change_available_at = _apply_bind_state(
|
||||
account,
|
||||
bind_info,
|
||||
checked_at=now,
|
||||
)
|
||||
account.overview_snapshot = _json_safe(
|
||||
{
|
||||
"queried_at": now.isoformat(),
|
||||
"ck": ck_result,
|
||||
"elite": eligibility.elite_user_info,
|
||||
"points": eligibility.points_response,
|
||||
"limited_goods": eligibility.limited_goods,
|
||||
"ck": session.get("detail") or {"message": session.get("message")},
|
||||
"elite": elite.get("raw") or {},
|
||||
"points": eligibility.get("points_response") or {},
|
||||
"limited_goods": eligibility.get("limited_goods") or [],
|
||||
"bind": bind_info,
|
||||
"errors": errors,
|
||||
"probe_id": probe.get("probe_id"),
|
||||
}
|
||||
)
|
||||
account.overview_queried_at = now
|
||||
account.high_value_checked_at = now
|
||||
if session_status == "valid":
|
||||
account.high_value_checked_at = now
|
||||
account.updated_at = now
|
||||
if commit:
|
||||
db.commit()
|
||||
|
||||
limited_ids = frozenset(
|
||||
str(item) for item in eligibility.get("limited_ids") or [] if str(item)
|
||||
)
|
||||
return DouyuLiveAccountState(
|
||||
account_id=int(account.id),
|
||||
account_name=account_name,
|
||||
account_name=account.nickname
|
||||
or (probe.get("identity") or {}).get("nickname")
|
||||
or account.username
|
||||
or f"#{account.id}",
|
||||
checked_at=now,
|
||||
ck_verdict=ck_verdict,
|
||||
ck_message=ck_message,
|
||||
elite_opened=elite_opened,
|
||||
points=eligibility.points,
|
||||
limited_ids=eligibility.limited_ids,
|
||||
role_change_available_at=role_change_available_at,
|
||||
ck_verdict=session_status
|
||||
if session_status in {"valid", "invalid", "error"}
|
||||
else "error",
|
||||
ck_message=str(session.get("message") or ""),
|
||||
elite_opened=account.elite_opened,
|
||||
points=account.points,
|
||||
limited_ids=limited_ids,
|
||||
role_change_available_at=account.role_change_available_at,
|
||||
error=";".join(errors),
|
||||
role_change_blocked=is_role_change_cooling(bind_info),
|
||||
)
|
||||
|
||||
|
||||
def _apply_bind_state(
|
||||
account: Account,
|
||||
bind_info: dict[str, Any],
|
||||
*,
|
||||
checked_at: datetime,
|
||||
) -> datetime | None:
|
||||
snapshot = binding_snapshot(bind_info)
|
||||
derived = snapshot["bind_status"]
|
||||
if derived is not None:
|
||||
set_bind_status(account, SCOPE_ELITE, derived)
|
||||
|
||||
role_name = snapshot["role_name"]
|
||||
if role_name:
|
||||
account.game_name = role_name[:128]
|
||||
channel = snapshot["game_channel"]
|
||||
if channel:
|
||||
account.game_channel = channel.replace(" / ", " · ")[:128]
|
||||
|
||||
account.change_role_wait_time = snapshot["change_role_wait_time"]
|
||||
available_at = role_change_available_at(bind_info, checked_at=checked_at)
|
||||
account.role_change_available_at = available_at
|
||||
return available_at
|
||||
|
||||
|
||||
def _points_expire_at(
|
||||
points_response: dict[str, Any],
|
||||
*,
|
||||
checked_at: datetime,
|
||||
) -> datetime | None:
|
||||
raw = (
|
||||
points_response.get("willExpireTime")
|
||||
or points_response.get("will_expire_time")
|
||||
or points_response.get("expire_time")
|
||||
)
|
||||
value = _to_int(raw)
|
||||
if value is None or value <= 0:
|
||||
return None
|
||||
if value > 10_000_000_000:
|
||||
value //= 1000
|
||||
if value < int(checked_at.timestamp()) - 60:
|
||||
return None
|
||||
return datetime.fromtimestamp(value, tz=UTC)
|
||||
|
||||
|
||||
def _to_int(value: Any) -> int | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
return int(float(value))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _json_safe(value: Any) -> Any:
|
||||
if isinstance(value, datetime):
|
||||
return value.isoformat()
|
||||
|
||||
@@ -9,21 +9,24 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from core.douyu import DouyuActivityClient
|
||||
from core.douyu.cookie_utils import cookie_value
|
||||
|
||||
from .account_binding import binding_snapshot
|
||||
from .douyu_goods_service import serialize_goods
|
||||
|
||||
ERROR_MAX_LENGTH = 240
|
||||
|
||||
|
||||
def activity_client(cookie: str = "") -> DouyuActivityClient:
|
||||
def activity_client(
|
||||
cookie: str = "",
|
||||
*,
|
||||
logger_callback: Callable[[str], None] | None = None,
|
||||
proxies: dict[str, str] | None = None,
|
||||
) -> DouyuActivityClient:
|
||||
"""创建统一活动客户端;空 Cookie 可用于公开商品目录查询。"""
|
||||
return DouyuActivityClient(cookie)
|
||||
return DouyuActivityClient(
|
||||
cookie,
|
||||
logger=logger_callback,
|
||||
proxies=proxies,
|
||||
)
|
||||
|
||||
|
||||
def query_csrf(
|
||||
@@ -68,6 +71,29 @@ def query_xpd_bind_info(
|
||||
return client.xpd_bind_info(act_alias=act_alias)
|
||||
|
||||
|
||||
def query_xpd_embed(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
act_alias: str,
|
||||
rid: str,
|
||||
) -> dict[str, Any]:
|
||||
return client.xpd_embed_query(act_alias=act_alias, rid=rid)
|
||||
|
||||
|
||||
def query_xpd_role(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
embed_query: dict[str, str],
|
||||
act_id: str,
|
||||
rid: str = "",
|
||||
) -> dict[str, Any]:
|
||||
return client.xpd_get_role(
|
||||
embed_query=embed_query,
|
||||
act_id=act_id,
|
||||
rid=rid,
|
||||
)
|
||||
|
||||
|
||||
def query_gold_account(client: DouyuActivityClient) -> dict[str, Any]:
|
||||
return client.gold_account()
|
||||
|
||||
@@ -203,95 +229,8 @@ def query_exchange_orders(
|
||||
return [dict(item) for item in result.get("orders") or [] if isinstance(item, dict)]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DouyuEligibilityResult:
|
||||
elite_user_info: dict[str, Any]
|
||||
points: int
|
||||
points_response: dict[str, Any]
|
||||
limited_goods: list[dict[str, Any]]
|
||||
limited_ids: frozenset[str]
|
||||
|
||||
|
||||
def query_exchange_eligibility(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
cookie: str,
|
||||
manual_id: str,
|
||||
rid: str,
|
||||
uid: str = "",
|
||||
) -> DouyuEligibilityResult:
|
||||
"""一次读取兑换资格需要的精英状态、积分和限兑商品。"""
|
||||
ctn = query_csrf(client)
|
||||
elite = query_elite_user_info(client, manual_id=manual_id, rid=rid)
|
||||
resolved_uid = str(uid or cookie_value(cookie, "acf_uid") or "").strip()
|
||||
points_result = query_points(client, uid=resolved_uid, ctn=ctn)
|
||||
limited = query_limited_goods(client, manual_id=manual_id, rid=rid)
|
||||
limited_ids = {
|
||||
str(item.get("commodityId") or item.get("commodity_id") or "").strip()
|
||||
for item in limited
|
||||
}
|
||||
limited_ids.discard("")
|
||||
return DouyuEligibilityResult(
|
||||
elite_user_info=elite,
|
||||
points=int(points_result.get("points") or 0),
|
||||
points_response=points_result,
|
||||
limited_goods=limited,
|
||||
limited_ids=frozenset(limited_ids),
|
||||
)
|
||||
|
||||
|
||||
def query_account_overview(
|
||||
client: DouyuActivityClient,
|
||||
*,
|
||||
manual_id: str,
|
||||
rid: str,
|
||||
act_alias: str,
|
||||
with_goods: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""账号只读探针,单项失败只进入 errors,不阻断其他查询。"""
|
||||
elite: dict[str, Any] = {}
|
||||
bind: dict[str, Any] = {}
|
||||
gold: dict[str, Any] = {}
|
||||
goods: list[dict[str, Any]] = []
|
||||
errors: dict[str, str] = {}
|
||||
|
||||
try:
|
||||
elite = query_elite_user_info(client, manual_id=manual_id, rid=rid)
|
||||
except Exception as exc: # noqa: BLE001 - 外部接口边界
|
||||
errors["elite"] = _error_text(exc)
|
||||
try:
|
||||
bind = query_bind_info(client, act_alias=act_alias)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors["bind"] = _error_text(exc)
|
||||
try:
|
||||
gold = query_gold_account(client)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors["gold"] = _error_text(exc)
|
||||
if with_goods:
|
||||
try:
|
||||
goods = query_activity_goods(client, manual_id=manual_id, rid=rid)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors["goods"] = _error_text(exc)
|
||||
|
||||
return {
|
||||
"elite": elite,
|
||||
"bind": bind,
|
||||
"bind_snapshot": binding_snapshot(bind),
|
||||
"gold": gold,
|
||||
"goods": goods,
|
||||
"serialized_goods": [serialize_goods(item) for item in goods],
|
||||
"errors": errors,
|
||||
}
|
||||
|
||||
|
||||
def _error_text(exc: BaseException) -> str:
|
||||
return f"{type(exc).__name__}: {exc}"[:ERROR_MAX_LENGTH]
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DouyuEligibilityResult",
|
||||
"activity_client",
|
||||
"query_account_overview",
|
||||
"query_activity_goods",
|
||||
"query_bind_info",
|
||||
"query_csrf",
|
||||
@@ -300,7 +239,6 @@ __all__ = [
|
||||
"query_esports_goods",
|
||||
"query_esports_goods_result",
|
||||
"query_exchange_balance",
|
||||
"query_exchange_eligibility",
|
||||
"query_exchange_orders",
|
||||
"query_exchange_orders_result",
|
||||
"query_exchange_records",
|
||||
@@ -310,4 +248,6 @@ __all__ = [
|
||||
"query_limited_goods_result",
|
||||
"query_points",
|
||||
"query_xpd_bind_info",
|
||||
"query_xpd_embed",
|
||||
"query_xpd_role",
|
||||
]
|
||||
|
||||
@@ -49,18 +49,22 @@ from .account_events_service import (
|
||||
from .audit_service import record_account_action, record_audit
|
||||
from .business_events import record_account_query
|
||||
from .collab_common import apply_order_visibility, count_archived
|
||||
from .douyu_activity_query import (
|
||||
from .cookie_check_service import check_douyu_cookie
|
||||
from .douyu_account_probe import (
|
||||
ROLE_BOUND,
|
||||
ROLE_ERROR,
|
||||
ROLE_PENDING,
|
||||
ROLE_UNKNOWN,
|
||||
SESSION_INVALID,
|
||||
SESSION_VALID,
|
||||
activity_client,
|
||||
query_account_overview,
|
||||
query_activity_goods,
|
||||
query_elite_user_info,
|
||||
config_mapping,
|
||||
persist_probe_result,
|
||||
probe_account,
|
||||
)
|
||||
from .douyu_activity_query import (
|
||||
query_exchange_orders,
|
||||
query_exchange_records,
|
||||
query_gold_account,
|
||||
)
|
||||
from .douyu_elite_status import (
|
||||
elite_is_currently_open,
|
||||
normalize_elite_expire_time,
|
||||
)
|
||||
from .douyu_goods_service import (
|
||||
serialize_live_goods as _serialize_live_goods,
|
||||
@@ -313,7 +317,12 @@ def _client_for_account(account: Account) -> DouyuActivityClient:
|
||||
cookie = str(account.cookie or "").strip()
|
||||
if not cookie:
|
||||
raise CollabError("该账号没有 CK", code="account_no_cookie")
|
||||
return activity_client(cookie)
|
||||
return activity_client(
|
||||
cookie,
|
||||
logger_callback=lambda message: logger.debug(
|
||||
"[douyu-collab] account={} {}", account.id, message
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def serialize_live_goods(goods: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
@@ -327,6 +336,8 @@ def _probe_with_client(
|
||||
manual_id: str,
|
||||
rid: str,
|
||||
act_alias: str,
|
||||
confirm_act_alias: str = "",
|
||||
legacy_act_alias: str = "",
|
||||
client: Any | None = None,
|
||||
with_goods: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
@@ -341,67 +352,104 @@ def _probe_with_client(
|
||||
}
|
||||
|
||||
active_client = client or _client_for_account(account)
|
||||
overview = query_account_overview(
|
||||
active_client,
|
||||
manual_id=manual_id,
|
||||
rid=rid,
|
||||
act_alias=act_alias,
|
||||
with_goods=with_goods,
|
||||
caller_supplied_client = client is not None
|
||||
config_info = config_mapping(
|
||||
{
|
||||
"manual_id": manual_id,
|
||||
"rid": rid,
|
||||
"bind_act_alias": act_alias,
|
||||
"confirm_act_alias": confirm_act_alias or act_alias,
|
||||
"legacy_act_alias": legacy_act_alias,
|
||||
}
|
||||
)
|
||||
elite = overview["elite"]
|
||||
bind = overview["bind"]
|
||||
bind_snapshot = overview["bind_snapshot"]
|
||||
gold = overview["gold"]
|
||||
goods = overview["serialized_goods"]
|
||||
result = probe_account(
|
||||
account,
|
||||
config_info,
|
||||
client=active_client,
|
||||
session_checker=None if caller_supplied_client else check_douyu_cookie,
|
||||
with_gold=True,
|
||||
with_goods=with_goods,
|
||||
use_cache=not caller_supplied_client,
|
||||
)
|
||||
elite = result.get("elite") or {}
|
||||
role = (result.get("roles") or {}).get("elite") or {}
|
||||
identity = result.get("identity") or {}
|
||||
session = result.get("session") or {}
|
||||
gold = result.get("gold") or {}
|
||||
goods = result.get("goods") or {}
|
||||
bind_snapshot = role.get("snapshot") or {}
|
||||
role_status = str(role.get("status") or ROLE_UNKNOWN)
|
||||
error_labels = {
|
||||
"elite": "手册状态",
|
||||
"bind": "绑定角色",
|
||||
"points": "积分",
|
||||
"limited_goods": "限兑商品",
|
||||
"gold": "鱼翅余额",
|
||||
"goods": "活动商品",
|
||||
}
|
||||
errors = [
|
||||
f"{error_labels.get(key, key)}: {value}"
|
||||
for key, value in overview["errors"].items()
|
||||
for key, value in (result.get("errors") or {}).items()
|
||||
]
|
||||
|
||||
manual_type = _to_int(elite.get("manual_type"))
|
||||
manual_score = _to_int(elite.get("manual_score"))
|
||||
expire_time = normalize_elite_expire_time(elite.get("expire_time"))
|
||||
user_info = elite.get("user_info") or {}
|
||||
profile = DouyuActivityClient.profile_from_cookie(str(account.cookie or ""))
|
||||
bind_role = _text(bind_snapshot["role_name"], max_length=128)
|
||||
area_name = _text(bind_snapshot["area_name"], max_length=64)
|
||||
plat_name = _text(bind_snapshot["plat_name"], max_length=64)
|
||||
bind_channel = " · ".join(item for item in (area_name, plat_name) if item)
|
||||
bind_account = _text(bind_snapshot["nickname"], max_length=128)
|
||||
ck_status = CK_VALID if (elite or bind) else CK_INVALID
|
||||
ok = bool(bind_snapshot["bind_confirmed"]) and not (elite == {} and bind == {})
|
||||
errors.extend(role.get("errors") or [])
|
||||
session_status = str(session.get("status") or "")
|
||||
if session_status == SESSION_VALID:
|
||||
ck_status = CK_VALID
|
||||
elif session_status == SESSION_INVALID:
|
||||
ck_status = CK_INVALID
|
||||
else:
|
||||
ck_status = CK_UNVERIFIED
|
||||
bind_role = _text(role.get("role_name"), max_length=128)
|
||||
bind_channel = _text(role.get("game_channel"), max_length=128)
|
||||
bind_account = _text(role.get("game_account"), max_length=128)
|
||||
ok = (
|
||||
session_status == SESSION_VALID
|
||||
and role_status == ROLE_BOUND
|
||||
and bool(bind_role)
|
||||
)
|
||||
if session_status == SESSION_INVALID:
|
||||
message = f"CK 已失效:{session.get('message') or '请重新登录'}"
|
||||
elif session_status not in {SESSION_VALID, ""}:
|
||||
message = f"CK 状态无法确认:{session.get('message') or '请稍后重试'}"
|
||||
elif role_status == ROLE_ERROR:
|
||||
message = "角色查询失败" + (
|
||||
f":{';'.join(role.get('errors') or [])}" if role.get("errors") else ""
|
||||
)
|
||||
elif role_status == ROLE_UNKNOWN:
|
||||
message = "角色状态无法确认,已保留上次有效结果"
|
||||
elif role_status == ROLE_PENDING:
|
||||
message = "已识别角色,待确认绑定"
|
||||
elif not bind_role:
|
||||
message = "CK 正常,但账号未绑定角色"
|
||||
else:
|
||||
message = ";".join(errors)
|
||||
if error_labels.get("gold") and gold.get("error"):
|
||||
message = f"{message};鱼翅余额: {gold['error']}"
|
||||
|
||||
return {
|
||||
"found": True,
|
||||
"ok": ok,
|
||||
"ck_status": ck_status,
|
||||
"message": ";".join(errors) if errors else ("" if ok else "未读到绑定角色"),
|
||||
"auth_status": session_status,
|
||||
"role_status": role_status,
|
||||
"message": message,
|
||||
"errors": errors,
|
||||
"account_id": int(account.id),
|
||||
"account_username": str(account.username or ""),
|
||||
"account_uid": _text(account.uid or profile.get("uid"), max_length=32),
|
||||
"account_nickname": _text(
|
||||
user_info.get("nickname") or account.nickname or profile.get("nickname"),
|
||||
max_length=128,
|
||||
),
|
||||
"manual_type": manual_type,
|
||||
"manual_score": manual_score,
|
||||
"expire_time": expire_time,
|
||||
"manual_opened": elite_is_currently_open(manual_type, expire_time),
|
||||
"bind_status": bind_snapshot["bind_status"],
|
||||
"bind_phase": bind_snapshot["bind_phase"],
|
||||
"account_username": identity.get("username") or str(account.username or ""),
|
||||
"account_uid": _text(identity.get("uid"), max_length=32),
|
||||
"account_nickname": _text(identity.get("nickname"), max_length=128),
|
||||
"manual_type": elite.get("manual_type"),
|
||||
"manual_score": elite.get("manual_score"),
|
||||
"expire_time": elite.get("expire_time"),
|
||||
"manual_opened": bool(elite.get("opened")),
|
||||
"bind_status": bind_snapshot.get("bind_status"),
|
||||
"bind_phase": bind_snapshot.get("bind_phase"),
|
||||
"bind_game_account": bind_account,
|
||||
"bind_game_role": bind_role,
|
||||
"bind_game_channel": bind_channel,
|
||||
"fish_fin_balance": _to_int(gold.get("gold")),
|
||||
"goods": goods,
|
||||
"goods_count": len(goods),
|
||||
"fish_fin_balance": _to_int(gold.get("balance")),
|
||||
"goods": goods.get("serialized") or [],
|
||||
"goods_count": int(goods.get("count") or 0),
|
||||
"_probe_result": result,
|
||||
}
|
||||
|
||||
|
||||
@@ -426,6 +474,8 @@ def lookup_account(
|
||||
manual_id=str(config.manual_id or ""),
|
||||
rid=str(config.rid or ""),
|
||||
act_alias=str(config.bind_act_alias or ""),
|
||||
confirm_act_alias=str(config.confirm_act_alias or ""),
|
||||
legacy_act_alias=str(config.legacy_act_alias or ""),
|
||||
client=client,
|
||||
with_goods=with_goods,
|
||||
)
|
||||
@@ -444,12 +494,29 @@ def lookup_account(
|
||||
for order in orders
|
||||
]
|
||||
probe["ck_status_label"] = CK_LABELS.get(str(probe.get("ck_status")), "")
|
||||
probe.pop("_probe_result", None)
|
||||
return probe
|
||||
|
||||
|
||||
def apply_probe_snapshot(
|
||||
order: DouyuExternalOrder, account: Account, probe: Mapping[str, Any]
|
||||
db: Session,
|
||||
current: User,
|
||||
order: DouyuExternalOrder,
|
||||
account: Account,
|
||||
probe: Mapping[str, Any],
|
||||
*,
|
||||
source: str,
|
||||
) -> None:
|
||||
canonical = probe.get("_probe_result")
|
||||
if isinstance(canonical, dict):
|
||||
persist_probe_result(
|
||||
db,
|
||||
account,
|
||||
canonical,
|
||||
current=current,
|
||||
source=source,
|
||||
record_event=True,
|
||||
)
|
||||
order.account_id = int(account.id)
|
||||
order.account_username = _text(account.username, max_length=128) or _text(
|
||||
probe.get("account_username"), max_length=128
|
||||
@@ -458,23 +525,18 @@ def apply_probe_snapshot(
|
||||
order.account_nickname = _text(
|
||||
probe.get("account_nickname") or account.nickname, max_length=128
|
||||
)
|
||||
order.bind_game_account = _text(probe.get("bind_game_account"), max_length=128)
|
||||
order.bind_game_role = _text(probe.get("bind_game_role"), max_length=128)
|
||||
order.bind_game_channel = _text(probe.get("bind_game_channel"), max_length=128)
|
||||
order.bind_snapshot_at = _now()
|
||||
role_status = str(probe.get("role_status") or "")
|
||||
if role_status not in {ROLE_ERROR, ROLE_UNKNOWN}:
|
||||
order.bind_game_account = _text(probe.get("bind_game_account"), max_length=128)
|
||||
order.bind_game_role = _text(probe.get("bind_game_role"), max_length=128)
|
||||
order.bind_game_channel = _text(probe.get("bind_game_channel"), max_length=128)
|
||||
order.bind_snapshot_at = _now()
|
||||
fish = _to_int(probe.get("fish_fin_balance"))
|
||||
points = _to_int(probe.get("manual_score"))
|
||||
if fish is not None:
|
||||
order.fish_fin_balance = fish
|
||||
account.gold_balance = fish
|
||||
if points is not None:
|
||||
order.points_balance = points
|
||||
account.points = points
|
||||
ck_status = str(probe.get("ck_status") or "")
|
||||
if ck_status in (CK_VALID, CK_INVALID):
|
||||
account.ck_check_status = ck_status
|
||||
account.ck_checked_at = _now()
|
||||
account.updated_at = _now()
|
||||
|
||||
|
||||
def _assert_version(order: DouyuExternalOrder, expected: int | None) -> None:
|
||||
@@ -1115,10 +1177,19 @@ def create_order(
|
||||
manual_id=str(config.manual_id or ""),
|
||||
rid=str(config.rid or ""),
|
||||
act_alias=str(config.bind_act_alias or ""),
|
||||
confirm_act_alias=str(config.confirm_act_alias or ""),
|
||||
legacy_act_alias=str(config.legacy_act_alias or ""),
|
||||
client=client,
|
||||
with_goods=True,
|
||||
)
|
||||
apply_probe_snapshot(order, account, probe)
|
||||
apply_probe_snapshot(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
account,
|
||||
probe,
|
||||
source="douyu_collab.create",
|
||||
)
|
||||
if explicit_points is None and name:
|
||||
live = next(
|
||||
(
|
||||
@@ -1608,6 +1679,8 @@ def update_order(
|
||||
manual_id=str(config.manual_id or ""),
|
||||
rid=str(config.rid or ""),
|
||||
act_alias=str(config.bind_act_alias or ""),
|
||||
confirm_act_alias=str(config.confirm_act_alias or ""),
|
||||
legacy_act_alias=str(config.legacy_act_alias or ""),
|
||||
client=client,
|
||||
with_goods=True,
|
||||
)
|
||||
@@ -1619,7 +1692,14 @@ def update_order(
|
||||
force_active=order.status in COLLAB_LEASE_STATUSES,
|
||||
takeover_platform_lease=takeover_platform_lease,
|
||||
)
|
||||
apply_probe_snapshot(order, account, probe)
|
||||
apply_probe_snapshot(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
account,
|
||||
probe,
|
||||
source="douyu_collab.update",
|
||||
)
|
||||
changes["account_id"] = {
|
||||
"old": previous_account_id or None,
|
||||
"new": int(account.id),
|
||||
@@ -1691,6 +1771,8 @@ def set_account(
|
||||
manual_id=str(config.manual_id or ""),
|
||||
rid=str(config.rid or ""),
|
||||
act_alias=str(config.bind_act_alias or ""),
|
||||
confirm_act_alias=str(config.confirm_act_alias or ""),
|
||||
legacy_act_alias=str(config.legacy_act_alias or ""),
|
||||
client=client,
|
||||
with_goods=True,
|
||||
)
|
||||
@@ -1702,7 +1784,14 @@ def set_account(
|
||||
force_active=order.status in COLLAB_LEASE_STATUSES,
|
||||
takeover_platform_lease=takeover_platform_lease,
|
||||
)
|
||||
apply_probe_snapshot(order, account, probe)
|
||||
apply_probe_snapshot(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
account,
|
||||
probe,
|
||||
source="douyu_collab.account",
|
||||
)
|
||||
order.updated_by = current.id
|
||||
order.version = int(order.version or 0) + 1
|
||||
record_audit(
|
||||
@@ -1752,10 +1841,19 @@ def verify_order(
|
||||
manual_id=str(config.manual_id or ""),
|
||||
rid=str(config.rid or ""),
|
||||
act_alias=str(config.bind_act_alias or ""),
|
||||
confirm_act_alias=str(config.confirm_act_alias or ""),
|
||||
legacy_act_alias=str(config.legacy_act_alias or ""),
|
||||
client=client,
|
||||
with_goods=True,
|
||||
)
|
||||
apply_probe_snapshot(order, account, probe)
|
||||
apply_probe_snapshot(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
account,
|
||||
probe,
|
||||
source="douyu_collab.verify",
|
||||
)
|
||||
order.updated_by = current.id
|
||||
order.version = int(order.version or 0) + 1
|
||||
record_audit(
|
||||
@@ -2105,23 +2203,21 @@ def query_activity(
|
||||
raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found")
|
||||
config = resolve_config(db)
|
||||
active_client = client or _client_for_account(account)
|
||||
errors: list[str] = []
|
||||
elite: dict[str, Any] = {}
|
||||
gold: dict[str, Any] = {}
|
||||
probe = probe_account(
|
||||
account,
|
||||
config,
|
||||
client=active_client,
|
||||
session_checker=None,
|
||||
with_gold=True,
|
||||
with_elite_role=False,
|
||||
)
|
||||
elite = (probe.get("elite") or {}).get("raw") or {}
|
||||
gold = {
|
||||
"gold": (probe.get("gold") or {}).get("balance"),
|
||||
}
|
||||
errors = list((probe.get("errors") or {}).values())
|
||||
records: list[dict[str, Any]] = []
|
||||
orders: list[dict[str, Any]] = []
|
||||
try:
|
||||
elite = query_elite_user_info(
|
||||
active_client,
|
||||
manual_id=str(config.manual_id or ""),
|
||||
rid=str(config.rid or ""),
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"积分: {exc}")
|
||||
try:
|
||||
gold = query_gold_account(active_client)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"鱼翅: {exc}")
|
||||
if include_records:
|
||||
try:
|
||||
records = query_exchange_records(
|
||||
@@ -2144,6 +2240,14 @@ def query_activity(
|
||||
|
||||
manual_score = _to_int(elite.get("manual_score"))
|
||||
fish = _to_int(gold.get("gold"))
|
||||
persist_probe_result(
|
||||
db,
|
||||
account,
|
||||
probe,
|
||||
current=current,
|
||||
source="douyu_collab.query_activity",
|
||||
record_event=False,
|
||||
)
|
||||
if manual_score is not None:
|
||||
order.points_balance = manual_score
|
||||
account.points = manual_score
|
||||
@@ -2643,10 +2747,27 @@ def refresh_activity_goods(
|
||||
raise CollabError("没有带 CK 的斗鱼账号,无法刷新活动商品", code="no_account")
|
||||
active_client = client or _client_for_account(account)
|
||||
try:
|
||||
goods = query_activity_goods(
|
||||
active_client,
|
||||
manual_id=str(config.manual_id or ""),
|
||||
rid=str(config.rid or ""),
|
||||
probe = probe_account(
|
||||
account,
|
||||
config,
|
||||
client=active_client,
|
||||
session_checker=None,
|
||||
with_elite=False,
|
||||
with_elite_role=False,
|
||||
with_goods=True,
|
||||
)
|
||||
goods = (probe.get("goods") or {}).get("items") or []
|
||||
if (probe.get("goods") or {}).get("status") == "error":
|
||||
raise RuntimeError(
|
||||
(probe.get("goods") or {}).get("error") or "商品查询失败"
|
||||
)
|
||||
persist_probe_result(
|
||||
db,
|
||||
account,
|
||||
probe,
|
||||
current=current,
|
||||
source="douyu_collab.goods_refresh",
|
||||
record_event=False,
|
||||
)
|
||||
except Exception as exc:
|
||||
record_account_query(
|
||||
|
||||
@@ -10,8 +10,8 @@ from core.douyu import DouyuActivityError
|
||||
|
||||
from ..database import SessionLocal
|
||||
from ..models import DouyuTask
|
||||
from .account_lifecycle import on_ck_verdict
|
||||
from .cookie_check_service import check_douyu_cookie
|
||||
from .douyu_account_probe import persist_probe_result, probe_session
|
||||
from .douyu_runner_bind import BindMixin
|
||||
from .douyu_runner_core import ( # noqa: F401 (douyu_batch_registry 供 routers 重导出)
|
||||
DouyuBatchRunnerCore,
|
||||
@@ -68,18 +68,42 @@ class DouyuBatchRunner(
|
||||
)
|
||||
return
|
||||
|
||||
cookie_check = check_douyu_cookie(cookie)
|
||||
cookie_check = probe_session(cookie, checker=check_douyu_cookie)
|
||||
ck_verdict = str(cookie_check["status"])
|
||||
# 执行前的这次检测同样要写结论、由好变坏记事件、重算状态。
|
||||
on_ck_verdict(
|
||||
persist_probe_result(
|
||||
worker_db,
|
||||
account,
|
||||
"valid" if cookie_check["valid"] else "invalid",
|
||||
detail=cookie_check,
|
||||
occurred_at=cookie_check["checked_at"],
|
||||
{
|
||||
"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",
|
||||
record_event=False,
|
||||
commit=False,
|
||||
)
|
||||
worker_db.commit()
|
||||
if not cookie_check["valid"]:
|
||||
message = f"Cookie 已失效,请重新登录:{cookie_check['message']}"
|
||||
if ck_verdict != "valid":
|
||||
prefix = (
|
||||
"Cookie 已失效,请重新登录"
|
||||
if ck_verdict == "invalid"
|
||||
else "Cookie 状态无法确认"
|
||||
)
|
||||
message = f"{prefix}:{cookie_check['message']}"
|
||||
self._mark_task(worker_db, task, "failed", message)
|
||||
self._push_log(
|
||||
"warning", f"[{current}] {self._account_name(account)} {message}"
|
||||
|
||||
@@ -25,7 +25,16 @@ from .account_binding import (
|
||||
set_bind_status,
|
||||
)
|
||||
from .business_events import record_bind
|
||||
from .douyu_activity_query import query_bind_info, query_esports_bind_info
|
||||
from .douyu_account_probe import (
|
||||
ROLE_BOUND,
|
||||
ROLE_ERROR,
|
||||
ROLE_PENDING,
|
||||
ROLE_UNKNOWN,
|
||||
persist_probe_result,
|
||||
query_elite_bind_candidates,
|
||||
resolve_elite_role,
|
||||
)
|
||||
from .douyu_activity_query import query_esports_bind_info
|
||||
|
||||
DOUYU_LEGACY_BIND_ACT_ALIAS = "20250213NQCYX"
|
||||
DOUYU_BIND_ROLE_POLL_SECONDS = 600
|
||||
@@ -252,21 +261,15 @@ class BindMixin:
|
||||
aliases: list[str],
|
||||
) -> list[dict]:
|
||||
"""按多个 actAlias 查询绑定信息,保留成功结果。"""
|
||||
results: list[dict] = []
|
||||
for alias in aliases:
|
||||
if not alias:
|
||||
continue
|
||||
try:
|
||||
info = query_bind_info(client, act_alias=alias, v2=True)
|
||||
except DouyuActivityError as exc:
|
||||
self._push_log("warning", f"查询绑定信息失败 act={alias}: {exc}")
|
||||
continue
|
||||
info = {**info, "act_alias": alias}
|
||||
results, errors = query_elite_bind_candidates(client, aliases)
|
||||
for error in errors:
|
||||
self._push_log("warning", f"查询绑定信息失败 {error}")
|
||||
for info in results:
|
||||
self._push_log(
|
||||
"info",
|
||||
f"绑定信息 act={alias} {self._format_bind_summary(info)}",
|
||||
"绑定信息 "
|
||||
f"act={info.get('act_alias') or '-'} {self._format_bind_summary(info)}",
|
||||
)
|
||||
results.append(info)
|
||||
return results
|
||||
|
||||
def _role_alias_priority(self, config: dict, primary_alias: str = "") -> list[str]:
|
||||
@@ -1270,41 +1273,17 @@ class BindMixin:
|
||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||
):
|
||||
client = self._client(cookie)
|
||||
query_aliases = self._query_bind_act_aliases(config)
|
||||
if not query_aliases:
|
||||
self._mark_task(db, task, "failed", "请先配置绑定活动 actAlias")
|
||||
return
|
||||
candidates = self._fetch_bind_info_candidates(client, query_aliases)
|
||||
if not candidates:
|
||||
self._mark_task(
|
||||
db, task, "failed", "查询绑定信息失败,请检查 Cookie 或 actAlias"
|
||||
)
|
||||
return
|
||||
|
||||
# 1) 优先“已生效绑定”角色(bound_act=1 且有角色名,通常是活动 alias)。
|
||||
# 避免把扫码后未确认的新角色当成当前绑定结果。
|
||||
bound_info = self._pick_current_bound_info(candidates, config)
|
||||
# 2) 待确认角色统一交给共享状态机判断。cjm 中与当前绑定同名的残留
|
||||
# 不算 pending;同名但活动状态发生 needBindAct 转换才算 pending。
|
||||
pending_info = self._pick_pending_role_info(
|
||||
candidates,
|
||||
prefer_aliases=self._role_alias_priority(config),
|
||||
baseline_role_name=str((bound_info or {}).get("role_name") or ""),
|
||||
baseline_is_bound_act=self._is_bound_act(bound_info),
|
||||
baseline_info=bound_info,
|
||||
)
|
||||
pending_role = str((pending_info or {}).get("role_name") or "").strip()
|
||||
bound_role = str(bound_info.get("role_name") or "") if bound_info else ""
|
||||
has_pending = pending_info is not None and bool(pending_role)
|
||||
|
||||
# 查询结果角色 = 已生效绑定;首次绑定(无绑定)时回退待确认角色
|
||||
role = resolve_elite_role(client, config)
|
||||
status = str(role.get("status") or "")
|
||||
bind_info = (
|
||||
bound_info if bound_info else (pending_info if has_pending else None)
|
||||
role.get("bind_info") if isinstance(role.get("bind_info"), dict) else {}
|
||||
)
|
||||
snapshot = self._bind_snapshot(bind_info) if bind_info else {}
|
||||
role_name = snapshot.get("role_name") or ""
|
||||
is_bound = snapshot.get("is_bound_act", False)
|
||||
source_alias = str((bind_info or {}).get("act_alias") or "")
|
||||
snapshot = (
|
||||
role.get("snapshot") if isinstance(role.get("snapshot"), dict) else {}
|
||||
)
|
||||
role_name = str(role.get("role_name") or "")
|
||||
pending_role = str(role.get("pending_role_name") or "")
|
||||
source_alias = str(role.get("source_alias") or "")
|
||||
summary = (
|
||||
f"act={source_alias or '-'} {self._format_bind_summary(bind_info)}"
|
||||
if bind_info
|
||||
@@ -1313,54 +1292,70 @@ class BindMixin:
|
||||
self._push_log(
|
||||
"info",
|
||||
"查询角色 "
|
||||
f"aliases={','.join(query_aliases)} bound_hit={(bound_info or {}).get('act_alias') or '-'} "
|
||||
f"pending_hit={(pending_info or {}).get('act_alias') or '-'} "
|
||||
f"aliases={','.join(role.get('query_act_aliases') or [])} "
|
||||
f"status={status} source={source_alias or '-'} "
|
||||
f"{self._format_bind_summary(bind_info) if bind_info else 'role=- bound_act=-'}",
|
||||
)
|
||||
# 只有已生效绑定才写账号表;待确认角色不污染 game_name
|
||||
if bind_info and is_bound:
|
||||
self._apply_bind_info_to_account(account, bind_info)
|
||||
else:
|
||||
account.updated_at = datetime.now(UTC)
|
||||
persist_probe_result(
|
||||
db,
|
||||
account,
|
||||
{
|
||||
"probe_id": f"task:{task.id}",
|
||||
"identity": {"uid": account.uid, "username": account.username},
|
||||
"session": {},
|
||||
"elite": {},
|
||||
"eligibility": {},
|
||||
"roles": {"elite": role},
|
||||
"gold": {},
|
||||
"goods": {},
|
||||
"errors": {"elite_role": ";".join(role.get("errors") or [])}
|
||||
if role.get("errors")
|
||||
else {},
|
||||
},
|
||||
source="douyu_task.query_game_name",
|
||||
record_event=False,
|
||||
)
|
||||
result = {
|
||||
**snapshot,
|
||||
"act_alias": source_alias,
|
||||
"query_act_alias": source_alias,
|
||||
"query_act_aliases": query_aliases,
|
||||
**snapshot,
|
||||
"bind_ready_for_confirm": has_pending,
|
||||
"bind_confirmed": is_bound,
|
||||
"query_act_aliases": role.get("query_act_aliases") or [],
|
||||
"role_status": status,
|
||||
"role_name": role_name,
|
||||
"bind_ready_for_confirm": status == ROLE_PENDING,
|
||||
"bind_confirmed": status == ROLE_BOUND,
|
||||
"bind_phase": (
|
||||
"confirmed"
|
||||
if is_bound
|
||||
if status == ROLE_BOUND
|
||||
else ("role_ready" if role_name else "waiting_role")
|
||||
),
|
||||
"bind_summary": summary,
|
||||
"bind_candidates": [
|
||||
{
|
||||
"act_alias": item.get("act_alias"),
|
||||
"role_name": item.get("role_name"),
|
||||
"is_bound_act": self._is_bound_act(item),
|
||||
}
|
||||
for item in candidates
|
||||
],
|
||||
"bind_candidates": role.get("candidates") or [],
|
||||
"errors": role.get("errors") or [],
|
||||
}
|
||||
# 已绑定角色之外另有待确认新角色时,单独字段展示,不覆盖 role_name
|
||||
if has_pending and bound_info and pending_role != bound_role:
|
||||
if pending_role:
|
||||
result["pending_role_name"] = pending_role
|
||||
result["pending_area_name"] = str(pending_info.get("area_name") or "")
|
||||
result["pending_plat_name"] = str(pending_info.get("plat_name") or "")
|
||||
if not bind_info:
|
||||
message = f"未获取到游戏名 | {summary}"
|
||||
elif is_bound:
|
||||
if has_pending and pending_role != bound_role:
|
||||
message = (
|
||||
f"当前已绑定: {bound_role},待确认: {pending_role} | {summary}"
|
||||
)
|
||||
else:
|
||||
message = f"当前已绑定: {bound_role} | {summary}"
|
||||
else:
|
||||
result["pending_area_name"] = role.get("pending_area_name") or ""
|
||||
result["pending_plat_name"] = role.get("pending_plat_name") or ""
|
||||
if status == ROLE_ERROR:
|
||||
message = f"查询角色失败: {';'.join(role.get('errors') or ['未知错误'])}"
|
||||
elif status == ROLE_UNKNOWN:
|
||||
message = "角色状态无法确认,已保留上次有效结果"
|
||||
elif status == ROLE_BOUND:
|
||||
message = f"当前已绑定: {role_name} | {summary}"
|
||||
elif status == ROLE_PENDING:
|
||||
message = f"待确认角色: {role_name} | {summary}"
|
||||
self._mark_task(db, task, "success" if role_name else "failed", message, result)
|
||||
else:
|
||||
message = f"未获取到游戏名 | {summary}"
|
||||
self._mark_task(
|
||||
db,
|
||||
task,
|
||||
"success"
|
||||
if status in {ROLE_BOUND, ROLE_PENDING} and bool(role_name)
|
||||
else "failed",
|
||||
message,
|
||||
result,
|
||||
)
|
||||
|
||||
def _pick_change_wait_bind_info(
|
||||
self, candidates: list[dict], config: dict
|
||||
@@ -1387,39 +1382,74 @@ class BindMixin:
|
||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||
):
|
||||
client = self._client(cookie)
|
||||
query_aliases = self._query_bind_act_aliases(config)
|
||||
if not query_aliases:
|
||||
self._mark_task(db, task, "failed", "请先配置绑定活动 actAlias")
|
||||
return
|
||||
candidates = self._fetch_bind_info_candidates(client, query_aliases)
|
||||
if not candidates:
|
||||
role = resolve_elite_role(client, config)
|
||||
status = str(role.get("status") or "")
|
||||
query_aliases = role.get("query_act_aliases") or []
|
||||
raw_candidates = role.get("bind_infos") or []
|
||||
if status == ROLE_ERROR:
|
||||
self._mark_task(
|
||||
db, task, "failed", "查询绑定信息失败,请检查 Cookie 或 actAlias"
|
||||
db,
|
||||
task,
|
||||
"failed",
|
||||
f"查询绑定信息失败: {';'.join(role.get('errors') or ['未知错误'])}",
|
||||
)
|
||||
return
|
||||
for item in candidates:
|
||||
for item in raw_candidates:
|
||||
self._push_log(
|
||||
"info",
|
||||
f"查询换绑时间候选 act={item.get('act_alias') or '-'} "
|
||||
f"{self._format_bind_summary(item)}",
|
||||
)
|
||||
current_bound = self._pick_current_bound_info(candidates, config)
|
||||
pending_info = self._pick_pending_role_info(
|
||||
candidates,
|
||||
prefer_aliases=self._role_alias_priority(config),
|
||||
baseline_role_name=str((current_bound or {}).get("role_name") or ""),
|
||||
baseline_is_bound_act=self._is_bound_act(current_bound),
|
||||
baseline_info=current_bound,
|
||||
)
|
||||
pending_role = str((pending_info or {}).get("role_name") or "").strip()
|
||||
# 换绑时间看“当前已绑定”活动态,不要优先 cjm(cjm 常无 changeRoleWaitTime)
|
||||
action_aliases = self._action_act_aliases(config)
|
||||
bind_info = next(
|
||||
(
|
||||
item
|
||||
for alias in action_aliases
|
||||
for item in raw_candidates
|
||||
if str(item.get("act_alias") or "") == alias
|
||||
and item.get("change_role_wait_time") is not None
|
||||
),
|
||||
None,
|
||||
)
|
||||
bind_info = (
|
||||
self._pick_change_wait_bind_info(candidates, config) or candidates[0]
|
||||
bind_info
|
||||
or (
|
||||
role.get("bind_info")
|
||||
if isinstance(role.get("bind_info"), dict)
|
||||
else None
|
||||
)
|
||||
or (raw_candidates[0] if raw_candidates else {})
|
||||
)
|
||||
snapshot = self._bind_snapshot(bind_info)
|
||||
wait_time = snapshot["change_role_wait_time"]
|
||||
account.change_role_wait_time = wait_time
|
||||
account.updated_at = datetime.now(UTC)
|
||||
persist_role = {
|
||||
**role,
|
||||
"bind_info": bind_info,
|
||||
"snapshot": snapshot,
|
||||
"role_name": snapshot.get("role_name") or "",
|
||||
"game_channel": snapshot.get("game_channel") or "",
|
||||
"change_role_wait_time": wait_time,
|
||||
"can_change_role": snapshot.get("can_change_role"),
|
||||
"can_change_time": snapshot.get("can_change_time"),
|
||||
}
|
||||
persist_probe_result(
|
||||
db,
|
||||
account,
|
||||
{
|
||||
"probe_id": f"task:{task.id}",
|
||||
"identity": {"uid": account.uid, "username": account.username},
|
||||
"session": {},
|
||||
"elite": {},
|
||||
"eligibility": {},
|
||||
"roles": {"elite": persist_role},
|
||||
"gold": {},
|
||||
"goods": {},
|
||||
"errors": {},
|
||||
},
|
||||
source="douyu_task.query_change_bind_time",
|
||||
record_event=False,
|
||||
)
|
||||
source_alias = str(bind_info.get("act_alias") or "")
|
||||
wait_text = self._format_wait_time(wait_time)
|
||||
can_change = snapshot["can_change_role"]
|
||||
@@ -1442,31 +1472,16 @@ class BindMixin:
|
||||
"query_act_aliases": query_aliases,
|
||||
**snapshot,
|
||||
"change_role_wait_text": wait_text,
|
||||
# 待确认语义统一由 _pick_pending_role_info 决定;这里不再根据
|
||||
# “只是有角色名且 bindAct=0”自行推断。
|
||||
"bind_ready_for_confirm": pending_info is not None,
|
||||
"role_status": status,
|
||||
"bind_ready_for_confirm": status == ROLE_PENDING,
|
||||
"bind_confirmed": snapshot["is_bound_act"],
|
||||
"bind_summary": f"act={source_alias or '-'} {self._format_bind_summary(bind_info)}",
|
||||
"bind_candidates": [
|
||||
{
|
||||
"act_alias": item.get("act_alias"),
|
||||
"role_name": item.get("role_name"),
|
||||
"is_bound_act": self._is_bound_act(item),
|
||||
"change_role_wait_time": self._to_int(
|
||||
item.get("change_role_wait_time")
|
||||
),
|
||||
"can_change_role": item.get("can_change_role"),
|
||||
}
|
||||
for item in candidates
|
||||
],
|
||||
"bind_candidates": role.get("candidates") or [],
|
||||
}
|
||||
if (
|
||||
pending_info is not None
|
||||
and pending_role != str(snapshot["role_name"] or "").strip()
|
||||
):
|
||||
result["pending_role_name"] = pending_role
|
||||
result["pending_area_name"] = str(pending_info.get("area_name") or "")
|
||||
result["pending_plat_name"] = str(pending_info.get("plat_name") or "")
|
||||
if role.get("pending_role_name"):
|
||||
result["pending_role_name"] = role.get("pending_role_name")
|
||||
result["pending_area_name"] = role.get("pending_area_name") or ""
|
||||
result["pending_plat_name"] = role.get("pending_plat_name") or ""
|
||||
self._push_log(
|
||||
"info",
|
||||
f"查询换绑时间 hit={source_alias or '-'} role={role_name} "
|
||||
|
||||
@@ -23,6 +23,7 @@ from ..models import (
|
||||
from ..models import (
|
||||
ProxyConfig as ProxyConfigModel,
|
||||
)
|
||||
from .douyu_account_probe import activity_client
|
||||
from .douyu_goods_service import upsert_goods_snapshot
|
||||
from .douyu_service import (
|
||||
DOUYU_CONFIG_FIELDS,
|
||||
@@ -411,9 +412,9 @@ class DouyuBatchRunnerCore:
|
||||
def _client(self, cookie: str) -> DouyuActivityClient:
|
||||
"""任务 HTTP 客户端:写操作任务注入会话级代理(兑换/锁单/支付/充值/送礼),
|
||||
读操作任务直连;见 DOUYU_PROXY_TASK_TYPES。"""
|
||||
return DouyuActivityClient(
|
||||
return activity_client(
|
||||
cookie,
|
||||
logger=lambda msg: self._push_log("debug", msg),
|
||||
logger_callback=lambda msg: self._push_log("debug", msg),
|
||||
proxies=self._proxies_for_task(),
|
||||
)
|
||||
|
||||
|
||||
@@ -33,16 +33,27 @@ from sqlalchemy.orm import Session
|
||||
from core.douyu import DouyuActivityClient
|
||||
|
||||
from ..models import Account, DouyuTask
|
||||
from .account_binding import binding_snapshot, set_bind_status
|
||||
from .account_capability_service import sync_account_goods_states
|
||||
from .business_events import record_official_exchange
|
||||
from .douyu_account_probe import (
|
||||
ROLE_BOUND,
|
||||
ROLE_ERROR,
|
||||
ROLE_PENDING,
|
||||
ROLE_UNBOUND,
|
||||
ROLE_UNKNOWN,
|
||||
persist_probe_result,
|
||||
query_elite_bind_candidates,
|
||||
resolve_elite_role,
|
||||
resolve_esports_role,
|
||||
resolve_peace_role,
|
||||
)
|
||||
from .douyu_activity_query import (
|
||||
query_activity_goods,
|
||||
query_bind_info,
|
||||
query_csrf,
|
||||
query_esports_bind_info,
|
||||
query_exchange_records,
|
||||
query_xpd_bind_info,
|
||||
query_xpd_embed,
|
||||
)
|
||||
from .douyu_runner_donate import _parse_expire_at, _points_expire_at
|
||||
from .high_value_service import (
|
||||
@@ -199,7 +210,10 @@ class OverviewMixin:
|
||||
) -> dict[str, Any]:
|
||||
"""按作用域查绑定信息(三个接口不同,收敛在一处)。"""
|
||||
if scope == "elite":
|
||||
return query_bind_info(client, act_alias=alias)
|
||||
rows, errors = query_elite_bind_candidates(client, [alias])
|
||||
if errors:
|
||||
raise RuntimeError(";".join(errors))
|
||||
return rows[0] if rows else {}
|
||||
if scope == "esports":
|
||||
return query_esports_bind_info(client, act_alias=alias)
|
||||
return query_xpd_bind_info(client, act_alias=alias)
|
||||
@@ -238,7 +252,8 @@ class OverviewMixin:
|
||||
esports_manual_id: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""和平小店:先要一次性短时授权,再查购买记录。"""
|
||||
embed = client.xpd_embed_query(
|
||||
embed = query_xpd_embed(
|
||||
client,
|
||||
act_alias=str(config["xpd_act_alias"]),
|
||||
rid=str(config["xpd_rid"]),
|
||||
)
|
||||
@@ -383,6 +398,11 @@ class OverviewMixin:
|
||||
)
|
||||
|
||||
overview["bind"] = {}
|
||||
role_resolvers = {
|
||||
"elite": resolve_elite_role,
|
||||
"esports": resolve_esports_role,
|
||||
"peace": resolve_peace_role,
|
||||
}
|
||||
for scope, label, alias_key in (
|
||||
("elite", "精英宝典", "bind_act_alias"),
|
||||
("esports", "电竞手册", "esports_act_alias"),
|
||||
@@ -394,32 +414,55 @@ class OverviewMixin:
|
||||
if not alias:
|
||||
errors[f"bind_{scope}"] = f"未配置{label}活动别名"
|
||||
continue
|
||||
try:
|
||||
info = self._fetch_bind_info(client, scope, alias)
|
||||
snapshot = binding_snapshot(info)
|
||||
derived = snapshot["bind_status"]
|
||||
# 把**明细**也带上:运营要看的是"绑的哪个角色、哪个区服、
|
||||
# 什么时候能换绑",不是一个"已绑定"就完事。
|
||||
overview["bind"][scope] = {
|
||||
"derived": derived,
|
||||
"phase": snapshot["bind_phase"],
|
||||
"role_name": snapshot["role_name"],
|
||||
"area_name": snapshot["area_name"],
|
||||
"plat_name": snapshot["plat_name"],
|
||||
"nickname": snapshot["nickname"],
|
||||
"game_id": snapshot["game_id"],
|
||||
"game_name": snapshot["game_name"],
|
||||
"is_change_cooling": snapshot["is_change_cooling"],
|
||||
"can_change_role": snapshot["can_change_role"],
|
||||
"change_role_wait_time": _ts(snapshot["change_role_wait_time"]),
|
||||
"can_change_time": _ts(snapshot["can_change_time"]),
|
||||
}
|
||||
if derived is not None:
|
||||
# 唯一写入者;推不出来(None)时**不动原值** —— 宁可留 unknown,
|
||||
# 也不要把"没查到"写成"没绑定"
|
||||
set_bind_status(account, scope, derived)
|
||||
except Exception as exc: # noqa: BLE001 外部接口边界需要宽泛兜底
|
||||
errors[f"bind_{scope}"] = _err(exc)
|
||||
role = role_resolvers[scope](
|
||||
client,
|
||||
config,
|
||||
bind_fetcher=lambda selected_alias, selected_scope=scope: (
|
||||
self._fetch_bind_info(client, selected_scope, selected_alias)
|
||||
),
|
||||
)
|
||||
status = str(role.get("status") or "")
|
||||
snapshot = (
|
||||
role.get("snapshot") if isinstance(role.get("snapshot"), dict) else {}
|
||||
)
|
||||
overview["bind"][scope] = {
|
||||
"status": status,
|
||||
"derived": snapshot.get("bind_status"),
|
||||
"phase": snapshot.get("bind_phase"),
|
||||
"role_name": snapshot.get("role_name") or "",
|
||||
"area_name": snapshot.get("area_name") or "",
|
||||
"plat_name": snapshot.get("plat_name") or "",
|
||||
"nickname": snapshot.get("nickname") or "",
|
||||
"game_id": snapshot.get("game_id") or "",
|
||||
"game_name": snapshot.get("game_name") or "",
|
||||
"source_alias": role.get("source_alias") or "",
|
||||
"is_change_cooling": snapshot.get("is_change_cooling"),
|
||||
"can_change_role": snapshot.get("can_change_role"),
|
||||
"change_role_wait_time": _ts(snapshot.get("change_role_wait_time")),
|
||||
"can_change_time": _ts(snapshot.get("can_change_time")),
|
||||
}
|
||||
if status in {ROLE_ERROR, ROLE_UNKNOWN} and role.get("errors"):
|
||||
errors[f"bind_{scope}"] = ";".join(role.get("errors") or [])
|
||||
if status == ROLE_ERROR:
|
||||
continue
|
||||
if status in {ROLE_BOUND, ROLE_PENDING, ROLE_UNBOUND}:
|
||||
persist_probe_result(
|
||||
db,
|
||||
account,
|
||||
{
|
||||
"probe_id": f"task:{task.id}:role:{scope}",
|
||||
"identity": {"uid": account.uid, "username": account.username},
|
||||
"session": {},
|
||||
"elite": {},
|
||||
"eligibility": {},
|
||||
"roles": {scope: role},
|
||||
"gold": {},
|
||||
"goods": {},
|
||||
"errors": {},
|
||||
},
|
||||
source=f"douyu_task.query_account_overview.{scope}",
|
||||
record_event=False,
|
||||
)
|
||||
|
||||
# ---- 官方兑换记录(**三个作用域都拉**)----
|
||||
#
|
||||
|
||||
@@ -19,7 +19,11 @@ from .account_binding import (
|
||||
set_bind_status,
|
||||
)
|
||||
from .business_events import record_exchange
|
||||
from .douyu_activity_query import query_xpd_bind_info
|
||||
from .douyu_activity_query import (
|
||||
query_xpd_bind_info,
|
||||
query_xpd_embed,
|
||||
query_xpd_role,
|
||||
)
|
||||
|
||||
DOUYU_XPD_BIND_POLL_SECONDS = 300
|
||||
DOUYU_XPD_BIND_POLL_INTERVAL = 5
|
||||
@@ -43,11 +47,13 @@ class XpdMixin:
|
||||
|
||||
def _xpd_role_context(self, client: DouyuActivityClient, config: dict) -> dict:
|
||||
"""获取小店 H5 参数 + 绑定角色信息,小店任务共用。"""
|
||||
embed = client.xpd_embed_query(
|
||||
embed = query_xpd_embed(
|
||||
client,
|
||||
act_alias=str(config["xpd_act_alias"]),
|
||||
rid=str(config["xpd_rid"]),
|
||||
)
|
||||
role = client.xpd_get_role(
|
||||
role = query_xpd_role(
|
||||
client,
|
||||
embed_query=embed["query"],
|
||||
act_id=str(config["xpd_act_id"]),
|
||||
rid=str(config["xpd_rid"]),
|
||||
@@ -456,7 +462,8 @@ class XpdMixin:
|
||||
):
|
||||
"""查询和平小店道聚城购买记录。"""
|
||||
client = self._client(cookie)
|
||||
embed = client.xpd_embed_query(
|
||||
embed = query_xpd_embed(
|
||||
client,
|
||||
act_alias=str(config["xpd_act_alias"]),
|
||||
rid=str(config["xpd_rid"]),
|
||||
)
|
||||
@@ -528,13 +535,15 @@ class XpdMixin:
|
||||
return
|
||||
|
||||
client = self._client(cookie)
|
||||
embed = client.xpd_embed_query(
|
||||
embed = query_xpd_embed(
|
||||
client,
|
||||
act_alias=str(config["xpd_act_alias"]),
|
||||
rid=str(config["xpd_rid"]),
|
||||
)
|
||||
role: dict = {}
|
||||
try:
|
||||
role = client.xpd_get_role(
|
||||
role = query_xpd_role(
|
||||
client,
|
||||
embed_query=embed["query"],
|
||||
act_id=str(config["xpd_act_id"]),
|
||||
rid=str(config["xpd_rid"]),
|
||||
|
||||
@@ -10,7 +10,6 @@ from loguru import logger
|
||||
from sqlalchemy import and_, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.douyu.activity_client import DouyuActivityClient
|
||||
from core.douyu.cookie_utils import cookie_value
|
||||
|
||||
from ..models import Account, DouyuConfig, DouyuTask, LoginTask
|
||||
@@ -362,11 +361,9 @@ def _lock_payment_accounts(
|
||||
|
||||
def update_account_profile_from_cookie(account: Account, cookie: str) -> None:
|
||||
"""从 Cookie 回填 uid/nickname。"""
|
||||
profile = DouyuActivityClient.profile_from_cookie(cookie)
|
||||
if profile["uid"]:
|
||||
account.uid = profile["uid"]
|
||||
if profile["nickname"]:
|
||||
account.nickname = profile["nickname"]
|
||||
from .douyu_account_probe import update_identity_from_cookie
|
||||
|
||||
update_identity_from_cookie(account, cookie)
|
||||
|
||||
|
||||
def account_uid(account: Account, cookie: str) -> str:
|
||||
|
||||
@@ -26,8 +26,9 @@ from .account_events_service import (
|
||||
EVENT_RELOGIN_OK,
|
||||
emit,
|
||||
)
|
||||
from .account_lifecycle import on_ck_verdict, on_login_success, sync_status
|
||||
from .account_lifecycle import on_login_success, sync_status
|
||||
from .cookie_check_service import check_douyu_cookie
|
||||
from .douyu_account_probe import persist_probe_result, probe_session
|
||||
from .douyu_service import LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
|
||||
from .login_failure import classify_failure, failure_kind_label, is_account_fault
|
||||
from .proxy_service import build_proxy_runtime
|
||||
@@ -495,20 +496,45 @@ class LoginBatchRunner:
|
||||
elif result.success:
|
||||
message = result.message or "登录成功"
|
||||
if self.mode == "relogin" and account is not None:
|
||||
check_result = check_douyu_cookie(result.cookie)
|
||||
# 复检结论写账号(CK 在哪,健康状态就在哪),走统一入口:
|
||||
# 写结论 + 由好变坏记事件 + 重算状态。
|
||||
on_ck_verdict(
|
||||
check_result = probe_session(
|
||||
result.cookie,
|
||||
checker=check_douyu_cookie,
|
||||
)
|
||||
detail = (
|
||||
check_result.get("detail")
|
||||
if isinstance(check_result.get("detail"), dict)
|
||||
else {}
|
||||
)
|
||||
persist_probe_result(
|
||||
worker_db,
|
||||
account,
|
||||
"valid" if check_result["valid"] else "invalid",
|
||||
detail=check_result,
|
||||
occurred_at=check_result["checked_at"],
|
||||
{
|
||||
"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["valid"]:
|
||||
if check_result["status"] == "valid":
|
||||
message = "重新登录成功,Cookie 有效"
|
||||
else:
|
||||
message = f"重新登录成功,但 Cookie 有效性检测失败: {check_result['message']}"
|
||||
message = (
|
||||
"重新登录成功,但 Cookie 有效性检测失败: "
|
||||
f"{check_result['message']}"
|
||||
)
|
||||
# 唯一替换旧 CK 的入口:登录成功后写回账号。
|
||||
#
|
||||
# ⚠️ 必须传 **worker_db**(本线程的会话),不能传 self.db:
|
||||
|
||||
@@ -37,13 +37,14 @@ from ..account_capability_service import (
|
||||
record_account_commodity_state,
|
||||
)
|
||||
from ..business_events import record_account_query, record_douyu_task_started
|
||||
from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state
|
||||
from ..douyu_activity_query import activity_client, query_exchange_eligibility
|
||||
from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches
|
||||
from ..douyu_elite_status import (
|
||||
elite_is_currently_open,
|
||||
normalize_elite_expire_time,
|
||||
from ..douyu_account_probe import (
|
||||
CAPABILITY_OK,
|
||||
config_mapping,
|
||||
persist_probe_result,
|
||||
probe_account,
|
||||
)
|
||||
from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state
|
||||
from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches
|
||||
from ..douyu_service import (
|
||||
SUPPORTED_DOUYU_TASK_TYPES,
|
||||
douyu_config_value,
|
||||
@@ -2195,24 +2196,32 @@ def refresh_exchange_eligibility(
|
||||
raise HTTPException(status_code=409, detail="账号 CK 不可用")
|
||||
config = ensure_douyu_config(db)
|
||||
try:
|
||||
cookie = str(account.cookie)
|
||||
client = activity_client(cookie)
|
||||
eligibility = query_exchange_eligibility(
|
||||
client,
|
||||
cookie=cookie,
|
||||
manual_id=str(douyu_config_value("manual_id", config.manual_id)),
|
||||
rid=str(douyu_config_value("rid", config.rid)),
|
||||
uid=str(account.uid or ""),
|
||||
probe = probe_account(
|
||||
account,
|
||||
config_mapping(config),
|
||||
session_checker=None,
|
||||
with_elite_role=False,
|
||||
with_eligibility=True,
|
||||
)
|
||||
elite_expire_time = normalize_elite_expire_time(
|
||||
eligibility.elite_user_info.get("expire_time")
|
||||
if (probe.get("elite") or {}).get("status") != CAPABILITY_OK:
|
||||
raise RuntimeError(
|
||||
(probe.get("errors") or {}).get("elite") or "精英宝典状态查询失败"
|
||||
)
|
||||
if "points" in (probe.get("errors") or {}):
|
||||
raise RuntimeError((probe.get("errors") or {})["points"])
|
||||
limited_ids = frozenset(
|
||||
str(item)
|
||||
for item in (probe.get("eligibility") or {}).get("limited_ids") or []
|
||||
if str(item)
|
||||
)
|
||||
account.elite_opened = elite_is_currently_open(
|
||||
eligibility.elite_user_info.get("manual_type"),
|
||||
elite_expire_time,
|
||||
persist_probe_result(
|
||||
db,
|
||||
account,
|
||||
probe,
|
||||
current=current,
|
||||
source="platform.exchange_eligibility",
|
||||
record_event=True,
|
||||
)
|
||||
account.elite_expire_time = elite_expire_time
|
||||
account.points = eligibility.points
|
||||
except Exception as exc: # noqa: BLE001 外部接口错误要落成可重试的检查失败
|
||||
record_account_query(
|
||||
db,
|
||||
@@ -2240,7 +2249,7 @@ def refresh_exchange_eligibility(
|
||||
db.commit()
|
||||
return get_task_detail(db, task.id)
|
||||
|
||||
if task.commodity_id in eligibility.limited_ids:
|
||||
if task.commodity_id in limited_ids:
|
||||
task.exchange_status = "limited"
|
||||
task.issue_code = "commodity_limit_reached"
|
||||
task.last_error = "该账号已达到此商品兑换上限"
|
||||
@@ -2262,15 +2271,13 @@ def refresh_exchange_eligibility(
|
||||
commodity_id=task.commodity_id,
|
||||
availability=(
|
||||
AVAILABILITY_LIMITED
|
||||
if task.commodity_id in eligibility.limited_ids
|
||||
if task.commodity_id in limited_ids
|
||||
else AVAILABILITY_AVAILABLE
|
||||
),
|
||||
blocking_reason=(
|
||||
"该账号已达此商品兑换上限"
|
||||
if task.commodity_id in eligibility.limited_ids
|
||||
else ""
|
||||
"该账号已达此商品兑换上限" if task.commodity_id in limited_ids else ""
|
||||
),
|
||||
raw_status="1" if task.commodity_id in eligibility.limited_ids else "0",
|
||||
raw_status="1" if task.commodity_id in limited_ids else "0",
|
||||
observed_at=_now(),
|
||||
source="eligibility_check",
|
||||
scope=task.scope or SCOPE_ELITE,
|
||||
@@ -2284,7 +2291,7 @@ def refresh_exchange_eligibility(
|
||||
detail={
|
||||
"commodity_id": task.commodity_id,
|
||||
"exchange_status": task.exchange_status,
|
||||
"limited": task.commodity_id in eligibility.limited_ids,
|
||||
"limited": task.commodity_id in limited_ids,
|
||||
"points": account.points,
|
||||
"elite_opened": account.elite_opened,
|
||||
},
|
||||
@@ -2303,7 +2310,7 @@ def refresh_exchange_eligibility(
|
||||
actor_id=current.id,
|
||||
detail={
|
||||
"exchangeStatus": task.exchange_status,
|
||||
"limitedCount": len(eligibility.limited_ids),
|
||||
"limitedCount": len(limited_ids),
|
||||
},
|
||||
)
|
||||
_emit_order_site_binding_state(db, task.id)
|
||||
|
||||
@@ -202,6 +202,8 @@ export interface DouyuCollabAccountLookup {
|
||||
account_nickname: string;
|
||||
ck_status: string;
|
||||
ck_status_label: string;
|
||||
auth_status: string;
|
||||
role_status: string;
|
||||
manual_type: number | null;
|
||||
manual_score: number | null;
|
||||
expire_time: number | null;
|
||||
|
||||
@@ -1018,6 +1018,16 @@ export default function DouyuCollabPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const copyAccountUsername = async (row: DouyuCollabOrder) => {
|
||||
if (!row.account_username) return;
|
||||
try {
|
||||
await copyTextToClipboard(row.account_username);
|
||||
message.success(`已复制斗鱼账号 ${row.account_username}`);
|
||||
} catch (error) {
|
||||
message.error(`复制失败:${getErrorMessage(error)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const openUsernameExport = async () => {
|
||||
if (selectedIds.length === 0) {
|
||||
message.warning('请先勾选协作单');
|
||||
@@ -1218,15 +1228,29 @@ export default function DouyuCollabPage() {
|
||||
width: 210,
|
||||
render: (_, row) => (
|
||||
<Space direction="vertical" size={0}>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ padding: 0 }}
|
||||
disabled={!row.account_id}
|
||||
onClick={() => row.account_id && navigate(`/accounts/${row.account_id}`)}
|
||||
>
|
||||
{row.account_username || '未填'}
|
||||
</Button>
|
||||
<Space size={2}>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ padding: 0 }}
|
||||
disabled={!row.account_id}
|
||||
onClick={() => row.account_id && navigate(`/accounts/${row.account_id}`)}
|
||||
>
|
||||
{row.account_username || '未填'}
|
||||
</Button>
|
||||
{row.account_username && (
|
||||
<Tooltip title="复制斗鱼账号">
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
style={{ paddingInline: 4 }}
|
||||
aria-label="复制斗鱼账号"
|
||||
icon={<CopyOutlined />}
|
||||
onClick={() => void copyAccountUsername(row)}
|
||||
/>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Space>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{row.account_nickname || '-'}
|
||||
{row.account_uid ? ` · UID ${row.account_uid}` : ''}
|
||||
|
||||
Reference in New Issue
Block a user