Files
live-hub-py/web/backend/services/cookie_check_service.py
T

187 lines
6.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""斗鱼 Cookie 有效性检测服务。"""
from datetime import UTC, datetime
from typing import Any
import requests
CHECK_UA = (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/150.0.0.0 Safari/537.36"
)
FISH_BALL_API = "https://www.douyu.com/wjapi/nc/exchange/fishBall"
USER_LEVEL_API = "https://www.douyu.com/japi/interactnc/web/userLevel/userLevelDetail"
AUTH_FAILURE_MARKERS = (
"登陆异常",
"登录异常",
"未登录",
"登陆失效",
"登录失效",
"重新登陆",
"重新登录",
"账户登陆",
"expired",
"ck 失效",
)
def _has_auth_failure(message: str) -> bool:
lower = (message or "").lower()
return any(marker in message or marker in lower for marker in AUTH_FAILURE_MARKERS)
def _format_request_error(exc: Exception) -> str:
text = str(exc or "")
lower = text.lower()
if "proxyerror" in lower or "unable to connect to proxy" in lower:
return "请求失败: 代理连接失败"
if "timed out" in lower or "timeouterror" in lower:
return "请求失败: 网络读取超时"
if "max retries exceeded" in lower or "connection" in lower:
return "请求失败: 网络连接异常"
return f"请求失败: {text[:80]}"
def _fetch_cookie_endpoint(
url: str,
*,
params: dict[str, str],
referer: str,
cookie: str,
attempts: int = 2,
) -> tuple[dict[str, Any] | None, str]:
last_error = ""
for attempt in range(max(1, attempts)):
try:
response = requests.get(
url,
params=params,
headers={
"User-Agent": CHECK_UA,
"Accept": "application/json, text/plain, */*",
"Referer": referer,
"Cookie": cookie,
},
timeout=(5, 10),
)
data = response.json()
if isinstance(data, dict):
return data, ""
return None, "响应格式异常"
except requests.RequestException as exc:
last_error = _format_request_error(exc)
if attempt + 1 < attempts:
continue
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
last_error = _format_request_error(exc)
break
return None, last_error or "请求失败"
def classify_douyu_cookie_result(result: dict) -> str:
"""把检测结果分成 valid / invalid / error,区分失效与暂时查不到。"""
if result.get("valid"):
return "valid"
message = str(result.get("message") or "")
if _has_auth_failure(message):
return "invalid"
return "error"
def check_douyu_cookie(cookie: str) -> dict:
"""全系统唯一的斗鱼 Cookie 有效性检测实现。
同时校验强鉴权的鱼丸接口与等级接口:
1. 任一接口明确返回未登录/登陆异常等鉴权失败时判定失效;
2. 双接口均通过时有效;若一个强鉴权接口已确认登录正常、另一端仅偶发网络超时(无鉴权失败),
经过重试仍未拿到另一端响应时也允许降级判定有效,避免单端抖动误杀正常账号;
3. 两端均网络异常(无鉴权失败文案)时判定为状态无法确认(error),不误判 CK 失效。
"""
checked_at = datetime.now(UTC)
base = {
"checked_at": checked_at,
"fish_ball": None,
"nickname": None,
"level": None,
}
if not cookie:
return {**base, "valid": False, "message": "Cookie 为空"}
fish_ok = False
fish_msg = ""
fish_ball = None
fish_data, fish_err = _fetch_cookie_endpoint(
FISH_BALL_API,
params={"appCode": "YJTX"},
referer="https://www.douyu.com/member/walletcenter",
cookie=cookie,
)
if fish_data is not None:
if fish_data.get("error") in (0, "0"):
fish_ok = True
fish_ball = (
(fish_data.get("data") or {}).get("count")
if isinstance(fish_data.get("data"), dict)
else None
)
else:
fish_msg = str(fish_data.get("msg") or fish_data.get("error") or "响应异常")
else:
fish_msg = fish_err
level_ok = False
level_msg = ""
nickname = None
level = None
level_data, level_err = _fetch_cookie_endpoint(
USER_LEVEL_API,
params={"rid": "0"},
referer="https://www.douyu.com/pages/ord-user-level?clientType=web",
cookie=cookie,
)
if level_data is not None:
if level_data.get("error") in (0, "0"):
level_ok = True
info_raw = level_data.get("data")
info = info_raw if isinstance(info_raw, dict) else {}
nickname = str(info.get("nn") or "") or None
level = info.get("lv")
else:
level_msg = str(level_data.get("msg") or level_data.get("error") or "响应异常")
else:
level_msg = level_err
fish_auth_failed = not fish_ok and _has_auth_failure(fish_msg)
level_auth_failed = not level_ok and _has_auth_failure(level_msg)
if fish_auth_failed or level_auth_failed:
valid = False
elif fish_ok and level_ok:
valid = True
elif fish_ok or level_ok:
# 一端强鉴权接口明确返回有效,另一端仅网络抖动/非鉴权异常
valid = True
else:
valid = False
if fish_ok and level_ok:
message = "有效"
elif valid:
detail_msg = level_msg if fish_ok else fish_msg
message = f"有效(单端网络波动降级通过: {detail_msg})"
else:
message = ";".join(
[
f"鱼丸接口: {'ok' if fish_ok else (fish_msg or '失败')}",
f"等级接口: {'ok' if level_ok else (level_msg or '失败')}",
]
)
return {
**base,
"valid": valid,
"message": message[:200],
"fish_ball": fish_ball,
"nickname": nickname,
"level": level,
}