Files
myrzx_bot/ranch_assistant/login.py
T

128 lines
6.8 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.
"""Normal DYD password authentication recovered from the shipped Android SDK."""
from __future__ import annotations
import hashlib
import hmac
import time
import uuid
from pathlib import Path
import requests
from .api import ApiError, Client, Session, server_entries, server_id
SDK_LOGIN_URL = "https://gameapi.diyidan.net/g0.3/users/reallogin"
SDK_APP_ID = "76813411"
# Published client application identity, not an account credential.
SDK_APP_SECRET = "WicgaI9bN0FoQbK5"
DEFAULT_CENTER = "https://myrzx-user.diyidan.net:9099/"
def device_id(folder):
path = Path(folder) / "desktop_device_id.txt"
if path.exists():
return path.read_text(encoding="ascii").strip()
path.parent.mkdir(parents=True, exist_ok=True)
value = str(uuid.uuid4())
path.write_text(value, encoding="ascii")
return value
def sdk_headers(device):
signature = hmac.new(SDK_APP_SECRET.encode(), SDK_APP_ID.encode(), hashlib.sha256).hexdigest()
return {"deviceId": device, "AppID": SDK_APP_ID, "Authorization": signature}
class PasswordLogin:
def __init__(self, catalog, device, *, sdk_url=SDK_LOGIN_URL, center_url=None, channel="DYD", trace=None):
self.catalog, self.device = catalog, device
self.trace = trace
self.sdk_url = sdk_url
self.center_url = center_url or catalog.data["server_info"]["ANDROID"].get(channel, DEFAULT_CENTER)
self.channel = channel
def authenticate(self, account, password):
if not account.strip() or not password:
raise ApiError("请填写账号和密码")
# Cookies remain in this process and are discarded on closing the SDK session.
with requests.Session() as http:
http.trust_env = False
payload = {"account": account.strip(), "password": password}
params = {"versionCode": "1.0.1", "buildNumber": "2016122900", "appChannel": "taptap"}
headers = sdk_headers(self.device)
identifier = self.trace.begin("渠道账号验证", method="POST", url=self.sdk_url, query=params,
headers=headers, body=payload, encoding="application/x-www-form-urlencoded") if self.trace else None
started = time.monotonic()
try:
response = http.post(self.sdk_url, data=payload, params=params,
headers=headers, timeout=(5, 15), allow_redirects=False)
try:
data = response.json()
except ValueError as error:
if self.trace:
self.trace.emit("response", "渠道账号验证", request_id=identifier, url=self.sdk_url, http_status=response.status_code,
elapsed_ms=round((time.monotonic() - started) * 1000), headers=dict(response.headers),
body_preview=response.content[:4000].decode("utf-8", errors="replace"), decoded=False)
if response.status_code != 200:
raise ApiError(f"渠道登录返回 HTTP {response.status_code},尚未登录") from error
raise ApiError("渠道登录响应格式无法识别,请查看调试窗口") from error
if self.trace:
self.trace.emit("response", "渠道账号验证", request_id=identifier, url=self.sdk_url, http_status=response.status_code,
elapsed_ms=round((time.monotonic() - started) * 1000), headers=dict(response.headers), body=data, decoded=True)
if response.status_code != 200:
raise ApiError(f"渠道登录返回 HTTP {response.status_code},尚未登录")
except ApiError as error:
if self.trace:
self.trace.emit("error", "渠道账号验证", request_id=identifier, message=str(error))
raise
except requests.RequestException as error:
if self.trace:
self.trace.emit("error", "渠道账号验证", request_id=identifier, exception_type=type(error).__name__, message=str(error))
raise ApiError("渠道登录连接失败,请检查网络或查看调试窗口后重试") from error
except ValueError as error:
if self.trace:
self.trace.emit("error", "渠道账号验证", request_id=identifier, exception_type=type(error).__name__, message=str(error))
raise ApiError("渠道登录响应格式无法识别") from error
if not isinstance(data, dict):
raise ApiError("渠道登录响应不是 JSON 对象,请查看调试窗口")
code = str(data.get("code", ""))
if code != "200" and self.trace:
self.trace.emit("error", "渠道账号验证", request_id=identifier, message=f"官方登录状态码:{code or '缺失'}")
if code == "407":
raise ApiError("官方要求短信验证(407),本次登录未完成")
if code == "408":
raise ApiError("官方限制此账号登录(408),本次登录未完成")
if code != "200":
raise ApiError(f"渠道账号登录未成功({code or '未知状态'}),请核对账号或验证要求")
content = data.get("data")
users = content.get("userList", []) if isinstance(content, dict) else []
if not isinstance(users, list) or not users or not isinstance(users[0], dict) or not users[0].get("userId") or not users[0].get("token"):
raise ApiError("渠道响应缺少用户会话,尚未登录")
uid, sdk_token = str(users[0]["userId"]), str(users[0]["token"])
client = Client(Session(key=self.catalog.data["game_setting"].get("xyz1", Session().key)), trace=self.trace)
try:
game = client.sdk_login(self.center_url, uid, sdk_token, self.channel, "ANDROID", self.device,
tj_channel=self.catalog.data.get("tjchannel", {}).get("tjchannel", "unknow"))
except Exception:
client.close()
raise
client.session.account_name = account.strip()
return client, game, {"uid": uid, "center_url": self.center_url, "device_id": self.device, "channel": self.channel}
def server_labels(response):
roles = {}
for role in response.get("masterInfos") or []:
if isinstance(role, dict):
try:
# masterInfos.id is the character ID, not the server ID.
roles[server_id({"serverId": role.get("serverId")})] = role
except ApiError:
continue
labels = []
for server in server_entries(response):
role = roles.get(server["id"])
details = role or server
name = details.get("masterName") or details.get("roleName") or ("已有角色" if role or server.get("masterId") else "无已有角色")
labels.append(f"{server['serverName']}({server['id']}) - {name}")
return labels