the_goth_cardgame_collection/models/online_session.py

206 lines
6.9 KiB
Python

# -*- coding: utf-8 -*-
# models/online_session.py
from __future__ import annotations
import json
import socket
import ssl
import urllib.error
import urllib.parse
import urllib.request
from resources.code_res.i18n import t
class OnlineSessionClient:
"""
Verwaltet Verbindungsaufbau, Adress-Parsing (URL inkl. Port ODER IP + Port)
und Einzelaccount-Authentifizierung für den zentralen Online-Modus.
Unterstützt sowohl HTTPS/HTTP-JSON-Endpunkte als auch rohe JSON-TCP-Server.
"""
DEFAULT_TIMEOUT_SEC = 4.5
def __init__(self):
self.connected: bool = False
self.scheme: str = "https"
self.host: str = ""
self.port: int = 0
self.base_url: str = ""
self.username: str = ""
self.token: str = ""
self.server_profile: dict | None = None
@staticmethod
def parse_endpoint(
addr_mode: str,
raw_url: str = "",
raw_ip: str = "",
raw_port: str = "",
) -> tuple[bool, dict | str]:
if addr_mode == "ip":
host = raw_ip.strip().strip("[]")
port_s = str(raw_port).strip()
if not host or not port_s:
return False, t("online_err_fields")
if not port_s.isdigit() or not (1 <= int(port_s) <= 65535):
return False, t("online_err_port")
port = int(port_s)
return True, {
"scheme": "tcp",
"host": host,
"port": port,
"base_url": f"tcp://{host}:{port}",
}
u = raw_url.strip()
if not u:
return False, t("online_err_fields")
if "://" not in u:
u = f"https://{u}"
parsed = urllib.parse.urlparse(u)
scheme = (parsed.scheme or "https").lower()
host = (parsed.hostname or "").strip()
try:
port = parsed.port
except ValueError:
return False, t("online_err_port")
if port is None:
if scheme == "https":
port = 443
elif scheme == "http":
port = 80
else:
return False, t("online_err_port")
if not host or not (1 <= int(port) <= 65535):
return False, t("online_err_port")
clean_path = parsed.path.rstrip("/")
base_url = f"{scheme}://{host}:{port}{clean_path}"
return True, {
"scheme": scheme,
"host": host,
"port": int(port),
"base_url": base_url,
}
def authenticate(
self,
addr_mode: str,
raw_url: str,
raw_ip: str,
raw_port: str,
username: str,
password: str,
) -> tuple[bool, str]:
clean_user = username.strip()
if not clean_user or not password:
return False, t("online_err_fields")
ok, ep = self.parse_endpoint(addr_mode, raw_url, raw_ip, raw_port)
if not ok or not isinstance(ep, dict):
return False, str(ep)
scheme = ep["scheme"]
host = ep["host"]
port = ep["port"]
base_url = ep["base_url"]
if scheme in ("http", "https"):
success, result = self._auth_via_http(base_url, host, port, clean_user, password)
else:
success, result = self._auth_via_tcp(host, port, clean_user, password, use_tls=(scheme == "tcps"))
if not success:
self.disconnect()
return False, str(result)
self.connected = True
self.scheme = scheme
self.host = host
self.port = port
self.base_url = base_url
self.username = clean_user
self.token = str(result.get("token", ""))
self.server_profile = result
return True, ""
def _auth_via_http(
self, base_url: str, host: str, port: int, username: str, password: str
) -> tuple[bool, dict | str]:
login_url = (
base_url
if base_url.endswith("/login")
else f"{base_url}/api/v1/auth/login"
)
body = json.dumps({
"username": username,
"password": password,
"client": "goth_cardgame_collection",
}).encode("utf-8")
req = urllib.request.Request(
login_url,
data=body,
headers={"Content-Type": "application/json", "Accept": "application/json"},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=self.DEFAULT_TIMEOUT_SEC) as resp:
raw = resp.read().decode("utf-8", errors="replace")
data = json.loads(raw) if raw.strip() else {}
if isinstance(data, dict) and data.get("ok", True):
return True, data
return False, t("online_err_auth", data.get("error", "Invalid credentials"))
except urllib.error.HTTPError as he:
try:
err_payload = json.loads(he.read().decode("utf-8", errors="replace"))
msg = err_payload.get("error") or err_payload.get("message") or f"HTTP {he.code}"
except Exception:
msg = f"HTTP {he.code}"
return False, t("online_err_auth", msg)
except Exception as exc:
return False, t("online_err_unreachable", host, port, str(exc))
def _auth_via_tcp(
self, host: str, port: int, username: str, password: str, use_tls: bool = False
) -> tuple[bool, dict | str]:
try:
with socket.create_connection((host, port), timeout=self.DEFAULT_TIMEOUT_SEC) as raw_sock:
sock: socket.socket = raw_sock
if use_tls:
ctx = ssl.create_default_context()
sock = ctx.wrap_socket(raw_sock, server_hostname=host)
payload = json.dumps({
"cmd": "AUTH_LOGIN",
"username": username,
"password": password,
"client": "goth_cardgame_collection",
}) + "\n"
sock.sendall(payload.encode("utf-8"))
buf = b""
while b"\n" not in buf and len(buf) < 65536:
chunk = sock.recv(4096)
if not chunk:
break
buf += chunk
if not buf:
return False, t("online_err_unreachable", host, port, "Empty response")
resp = json.loads(buf.split(b"\n", 1)[0].decode("utf-8", errors="replace"))
if isinstance(resp, dict) and resp.get("ok"):
return True, resp
return False, t("online_err_auth", resp.get("error", "Auth failed"))
except Exception as exc:
return False, t("online_err_unreachable", host, port, str(exc))
@property
def endpoint_label(self) -> str:
return f"{self.host}:{self.port}" if self.host else ""
def disconnect(self) -> None:
self.connected = False
self.token = ""
self.server_profile = None