import os import time import threading from flask import Blueprint, request, jsonify, Response from core.auth import check_auth, get_current_profile_id from core.limiter import limiter from core.state import db, session_mgr, ws_registry, APP_VERSION from core.config import base_url as _base_url, server as _server_cfg bp = Blueprint("nameserver", __name__) _web_presence: dict[int, float] = {} _web_presence_lock = threading.Lock() _WEB_PRESENCE_TTL = 150 def _web_heartbeat(pid: int) -> None: cutoff = time.monotonic() - _WEB_PRESENCE_TTL with _web_presence_lock: _web_presence[pid] = time.monotonic() expired = [k for k, v in _web_presence.items() if v < cutoff] for k in expired: del _web_presence[k] def _web_online_ids() -> set[int]: cutoff = time.monotonic() - _WEB_PRESENCE_TTL with _web_presence_lock: return {pid for pid, ts in _web_presence.items() if ts >= cutoff} _SYSTEM_PIDS = {23} def _all_online_ids() -> set[int]: return (set(ws_registry.connected_ids()) | _web_online_ids()) - _SYSTEM_PIDS _BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def _load_html(filename: str) -> str: try: with open(os.path.join(_BASE_DIR, filename), "r", encoding="utf-8") as f: html = f.read() except FileNotFoundError: return f"
{filename} missing.
" return (html .replace("{{BUILD_DATE_HUMAN}}", _server_cfg.get("build_date_human", "")) .replace("{{APP_VERSION}}", _server_cfg.get("app_version", "")) .replace("{{APP_VERSION_LONG}}", _server_cfg.get("app_version_long", ""))) @bp.route("/", methods=["GET"]) def nameserver(): proto = request.headers.get("X-Forwarded-Proto", "http").lower() is_https = proto == "https" http_base = f"{'https' if is_https else 'http'}://{request.host}/" ws_base = f"{'wss' if is_https else 'ws'}://{request.host}/" if request.args.get("v"): return jsonify({ "Auth": http_base, "API": http_base, "WWW": http_base, "Notifications": ws_base, "Images": http_base, }) return Response(_load_html("pages/web_portal.html"), 200, {"Content-Type": "text/html; charset=utf-8"}) @bp.route("/welcome", methods=["GET"]) def welcome(): return Response(_load_html("pages/welcome.html"), 200, {"Content-Type": "text/html; charset=utf-8"}) @bp.route("/dashboard", methods=["GET"]) def dashboard(): return Response(_load_html("pages/dashboard.html"), 200, {"Content-Type": "text/html; charset=utf-8"}) @bp.route("/recnet", methods=["GET"]) def recnet_page(): return Response(_load_html("pages/recnet.html"), 200, {"Content-Type": "text/html; charset=utf-8"}) @bp.route("/api-docs", methods=["GET"]) def api_docs_page(): return Response(_load_html("pages/api_page.html"), 200, {"Content-Type": "text/html; charset=utf-8"}) @bp.route("/web/status", methods=["GET"]) def web_status(): sessions = session_mgr.all_public_sessions() return jsonify({ "online": len(_all_online_ids()), "session_count": len(sessions), "version": APP_VERSION, "rooms": [ { "name": s.name, "activity": s.activity_key, "players": len(s.players), "max": s.max_capacity, } for s in sessions ], }) @bp.route("/web/leaderboard", methods=["GET"]) @limiter.limit("30 per minute") def web_leaderboard(): online_ids = _all_online_ids() conn = db._get_conn() rows = conn.execute( "SELECT id, display_name, username, level, xp, profile_image_name " "FROM profiles ORDER BY xp DESC" ).fetchall() return jsonify([ { "id": r["id"], "display_name": r["display_name"], "username": r["username"], "level": r["level"], "xp": r["xp"], "online": r["id"] in online_ids, "has_image": bool(r["profile_image_name"]), } for r in rows ]) @bp.route("/web/players", methods=["GET"]) @check_auth def web_players(): pid = get_current_profile_id() online_ids = _all_online_ids() my_rels = {} if pid: for r in db.get_relationships(pid): my_rels[r["PlayerID"]] = r["RelationshipType"] conn = db._get_conn() rows = conn.execute( "SELECT id, username, display_name, level, xp, created_at, profile_image_name " "FROM profiles ORDER BY id" ).fetchall() return jsonify([ { "id": r["id"], "username": r["username"], "display_name": r["display_name"], "level": r["level"], "xp": r["xp"], "online": r["id"] in online_ids, "created_at": r["created_at"], "relationship": my_rels.get(r["id"], 0), "has_image": bool(r["profile_image_name"]), } for r in rows ]) @bp.route("/web/friends", methods=["GET"]) def web_friends(): from core.constants import REL_FRIEND, REL_RECEIVED pid = get_current_profile_id() if pid is None: return jsonify([]) online_ids = _all_online_ids() rels = db.get_relationships(pid) friends = [] for r in rels: if r["RelationshipType"] == REL_FRIEND: profile = db.get_profile(r["PlayerID"]) if profile: friends.append({ "id": profile["Id"], "username": profile["Username"], "display_name": profile["DisplayName"], "level": profile["Level"], "online": profile["Id"] in online_ids, "has_image": bool(profile.get("ProfileImageName", "")), }) elif r["RelationshipType"] == REL_RECEIVED: profile = db.get_profile(r["PlayerID"]) if profile: friends.append({ "id": profile["Id"], "username": profile["Username"], "display_name": profile["DisplayName"], "level": profile["Level"], "online": profile["Id"] in online_ids, "has_image": bool(profile.get("ProfileImageName", "")), "pending_request": True, }) return jsonify(friends) @bp.route("/leaderboard", methods=["GET"]) def leaderboard_page(): return Response(_load_html("pages/leaderboard.html"), 200, {"Content-Type": "text/html; charset=utf-8"}) @bp.route("/account", methods=["GET"]) def account_page(): return Response(_load_html("pages/dashboard.html"), 200, {"Content-Type": "text/html; charset=utf-8"}) @bp.route("/web/change-password", methods=["POST"]) def web_change_password(): from werkzeug.security import generate_password_hash from core.password_crypto import check_password as crypto_check_password pid = get_current_profile_id() if pid is None: return jsonify({"error": "Not authenticated"}), 401 data = request.get_json(silent=True) or {} current = data.get("current_password", "") new_pw = data.get("new_password", "") if not current or not new_pw: return jsonify({"error": "Both fields are required"}), 400 if len(new_pw) < 8 or len(new_pw) > 128: return jsonify({"error": "Password must be 8-128 characters"}), 400 conn = db._get_conn() row = conn.execute("SELECT password FROM profiles WHERE id = ?", (pid,)).fetchone() if not row: return jsonify({"error": "Account not found"}), 404 stored = row["password"] if stored: if not crypto_check_password(stored, current): return jsonify({"error": "Current password is incorrect"}), 403 conn.execute( "UPDATE profiles SET password = ?, registration_status = 2 WHERE id = ?", (generate_password_hash(new_pw), pid), ) conn.commit() from core.state import _KITTYREC_SYSTEM_PID from datetime import datetime, timezone profile = db.get_profile(pid) uname = (profile or {}).get("Username", f"Player {pid}") msg_text = f"Your account has been verified, {uname}! You can now change your name in-game. Login to your account at {_base_url}/ Thanks for playing :D" db.delete_messages_of_type(pid, _KITTYREC_SYSTEM_PID, 30) msg_id = db.send_message(_KITTYREC_SYSTEM_PID, pid, 30, msg_text) sent = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") ws_registry.send(pid, {"Id": 2, "Msg": { "Id": msg_id, "FromPlayerId": _KITTYREC_SYSTEM_PID, "SentTime": sent, "Type": 30, "Data": msg_text, "RoomId": None, "PlayerEventId": None, }}) from core.ws_helpers import push_profile_update push_profile_update(pid) return jsonify({"success": True}) _PFP_UPLOAD_COST = 9000 _MAX_PFP_BYTES = 2 * 1024 * 1024 _IMAGE_MAGIC = (b"\x89PNG", b"\xff\xd8\xff", b"GIF87a", b"GIF89a", b"RIFF") @bp.route("/web/upload-pfp", methods=["POST"]) def web_upload_pfp(): import time as _time from core.ws_helpers import push_profile_update pid = get_current_profile_id() if pid is None: return jsonify({"error": "Not authenticated"}), 401 tokens = db.get_tokens(pid) if tokens < _PFP_UPLOAD_COST: return jsonify({"error": f"Not enough tokens. Need {_PFP_UPLOAD_COST}, have {tokens}"}), 402 f = request.files.get("image") if not f: return jsonify({"error": "No image provided"}), 400 image_data = f.read(_MAX_PFP_BYTES + 1) if len(image_data) > _MAX_PFP_BYTES: return jsonify({"error": "Image too large (max 2MB)"}), 400 if not any(image_data[:len(m)] == m for m in _IMAGE_MAGIC): return jsonify({"error": "Invalid image format"}), 400 old_image = db.get_profile_image(pid) old_profile = db.get_profile(pid) old_name = (old_profile or {}).get("ProfileImageName", "") if old_profile else "" if old_image and old_name: db.add_pfp_to_history(pid, old_name, old_image) db.update_tokens(pid, -_PFP_UPLOAD_COST) image_name = f"{pid}_{int(_time.time())}" db.set_profile_image(pid, image_data, image_name) db.update_profile(pid, {"profile_image_name": image_name}) push_profile_update(pid) new_tokens = db.get_tokens(pid) return jsonify({"success": True, "image_name": image_name, "tokens": new_tokens}) @bp.route("/web/pfp-history", methods=["GET"]) def web_pfp_history(): pid = get_current_profile_id() if pid is None: return jsonify({"error": "Not authenticated"}), 401 history = db.get_pfp_history(pid) return jsonify([{"id": h["id"], "created_at": h["created_at"]} for h in history]) @bp.route("/web/pfp-history/