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:
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user