fix(douyu): 对齐绑定小程序码并修复残留任务停止

This commit is contained in:
yml
2026-11-22 22:15:48 +08:00
parent 5393b668e0
commit d315e983f6
9 changed files with 409 additions and 38 deletions
+111 -2
View File
@@ -497,6 +497,10 @@ def test_latest_elite_binding_endpoints_are_used_once():
def test_qr_and_confirm_requests_follow_latest_har(monkeypatch):
calls: list[dict[str, Any]] = []
expected_referer = (
"https://www.douyu.com/pages/live-peace-handbook/web"
"?ditchname=pass0&roomId=9263298"
)
client = DouyuActivityClient("acf_ccn=ctn")
monkeypatch.setattr(
client,
@@ -524,23 +528,66 @@ def test_qr_and_confirm_requests_follow_latest_har(monkeypatch):
return {"error": 0, "msg": "请求正常", "data": {}}
monkeypatch.setattr(client, "_request_json", request_json)
monkeypatch.setattr(
client,
"get_livelink_mini_qrcode",
lambda _url: {
"mini_qrcode_image": "data:image/png;base64,bWluaS1xcg==",
"qrcode_token": "token-1",
},
)
qr = client.get_bind_qr(ACT_ALIAS)
confirmed = client.confirm_bind(ACT_ALIAS)
assert qr["url"] == "https://livelink.example/bind"
assert qr["url"] == "https://livelink.example/role"
assert qr["mini_qrcode_image"] == "data:image/png;base64,bWluaS1xcg=="
assert qr["qrcode_token"] == "token-1"
assert qr["has_mini_qrcode"] is True
assert qr["role_param_url"] == "https://livelink.example/role"
assert qr["game_role_bind_url"] == "https://livelink.example/bind"
assert confirmed["ctn"] == "ctn"
assert calls[0]["method"] == "get"
assert calls[0]["url"].endswith("/bindRoleParam")
assert calls[0]["params"] == {"actAlias": ACT_ALIAS}
assert calls[0]["headers"]["Referer"] == expected_referer
assert calls[1]["method"] == "post"
assert calls[1]["url"].endswith("/actBind")
assert calls[1]["files"] == {
"actAlias": (None, ACT_ALIAS),
"ctn": (None, "ctn"),
}
assert calls[1]["headers"]["Referer"] == expected_referer
def test_bind_info_uses_game_id_for_legacy_and_full_page_referer(monkeypatch):
calls: list[dict[str, Any]] = []
expected_referer = (
"https://www.douyu.com/pages/live-peace-handbook/web"
"?ditchname=pass0&roomId=9263298"
)
client = DouyuActivityClient("acf_ccn=ctn")
def request_json(method: str, url: str, source: str, **kwargs: Any):
calls.append(
{
"method": method,
"url": url,
"source": source,
**kwargs,
}
)
return {"error": 0, "msg": "请求正常", "data": {}}
monkeypatch.setattr(client, "_request_json", request_json)
client.bind_info(ACT_ALIAS)
client.bind_info("cjm")
assert calls[0]["params"] == {"actAlias": ACT_ALIAS}
assert calls[1]["params"] == {"gameId": "cjm"}
assert calls[0]["headers"]["Referer"] == expected_referer
assert calls[1]["headers"]["Referer"] == expected_referer
def test_confirm_bind_preserves_platform_cooldown_error_code(monkeypatch):
@@ -569,7 +616,7 @@ def test_confirm_bind_preserves_platform_cooldown_error_code(monkeypatch):
assert exc_info.value.payload == payload
def test_get_bind_qr_falls_back_to_role_param_url(monkeypatch):
def test_get_bind_qr_uses_role_param_url_for_mini_qrcode(monkeypatch):
client = DouyuActivityClient("acf_ccn=ctn")
monkeypatch.setattr(
client,
@@ -584,8 +631,70 @@ def test_get_bind_qr_falls_back_to_role_param_url(monkeypatch):
"data": {"url": "https://livelink.example/role"},
},
)
mini_urls: list[str] = []
monkeypatch.setattr(
client,
"get_livelink_mini_qrcode",
lambda url: (
mini_urls.append(url)
or {
"mini_qrcode_image": "data:image/png;base64,bWluaS1xcg==",
"qrcode_token": "token-2",
}
),
)
qr = client.get_bind_qr(ACT_ALIAS)
assert qr["url"] == "https://livelink.example/role"
assert qr["game_role_bind_url"] == ""
assert mini_urls == ["https://livelink.example/role"]
def test_livelink_mini_qrcode_uses_har_query_and_headers(monkeypatch):
calls: list[dict[str, Any]] = []
client = DouyuActivityClient("")
class Response:
@staticmethod
def raise_for_status():
return None
@staticmethod
def json():
return {
"iRet": 0,
"jData": {
"qrcode": "iVBORw0KGgo=",
"qrcodeToken": "token-3",
},
}
class Session:
trust_env = True
def __enter__(self):
return self
def __exit__(self, *_args):
return None
@staticmethod
def post(url: str, **kwargs: Any):
calls.append({"url": url, **kwargs})
return Response()
monkeypatch.setattr("core.douyu.activity_client.requests.Session", Session)
result = client.get_livelink_mini_qrcode(
"https://livelink.example/bind?actId=16046&livePlatId=douyu&fromId=abc"
)
assert result["qrcode_token"] == "token-3"
assert result["mini_qrcode_image"].startswith("data:image/png;base64,")
assert calls[0]["json"]["queryString"].startswith(
"actId=16046&livePlatId=douyu&fromId=abc&sessionId="
)
assert calls[0]["headers"]["Gap-Act-Id"] == "16046"
assert calls[0]["headers"]["Gap-Plat-Id"] == "douyu"
assert calls[0]["headers"]["Origin"] == "https://livelink.qq.com"
+22
View File
@@ -190,6 +190,28 @@ def test_cleanup_preserves_recoverable_binding_poll(db):
assert task.queue_lane == "binding_poll"
def test_force_cleanup_stops_recoverable_binding_poll(db):
_, _, task = _fixtures(db, status="running")
task.queue_lane = "binding_poll"
task.next_run_at = datetime.now(UTC) + timedelta(seconds=5)
task.run_deadline_at = datetime.now(UTC) + timedelta(minutes=10)
db.commit()
cleaned = douyu_service.cleanup_orphan_douyu_tasks(
db,
batch_id=task.batch_id,
statuses=("running",),
include_durable=True,
message="任务已停止(批次不存在)",
)
db.refresh(task)
assert cleaned == 1
assert task.status == "stopped"
assert task.queue_lane == ""
assert task.next_run_at is None
@pytest.mark.parametrize(
("elapsed", "expected"),
[
+23 -1
View File
@@ -12,7 +12,10 @@ from web.backend.routers.douyu import (
_visible_tasks_query,
list_tasks,
)
from web.backend.services.douyu_service import DOUYU_HANDBOOK_TASK_TYPES
from web.backend.services.douyu_service import (
DOUYU_HANDBOOK_TASK_TYPES,
sanitize_douyu_task_result,
)
def _legacy_page(
@@ -54,6 +57,25 @@ def _legacy_page(
return [task.id for task in query.all()], total
def test_task_list_slims_mini_qrcode_and_keeps_detail_image():
result = {
"url": "https://livelink.example/bind",
"has_mini_qrcode": True,
"mini_qrcode_image": "data:image/png;base64,bWluaS1xcg==",
}
listed = sanitize_douyu_task_result(result, "get_bind_qr")
detailed = sanitize_douyu_task_result(
result,
"get_bind_qr",
include_detail=True,
)
assert listed["has_mini_qrcode"] is True
assert "mini_qrcode_image" not in listed
assert detailed["mini_qrcode_image"] == "data:image/png;base64,bWluaS1xcg=="
def _new_page(result):
if isinstance(result, dict):
return [item.id for item in result["items"]], result["total"]