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"

Not Found

{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/", methods=["GET"]) def web_pfp_history_image(history_id): from email.utils import formatdate from core.auth import _jwt_decode pid = get_current_profile_id() if pid is None: token = request.args.get("token", "") if token: try: import core.auth as _auth payload = _auth._jwt_decode(token, _auth.JWT_SECRET) pid = payload.get("sub") except Exception: pid = None if pid is None: return Response(b"", 401) image_data = db.get_pfp_history_image(history_id, pid) if image_data is None: return Response(b"", 404) return Response(image_data, 200, { "Content-Type": "image/jpeg", "Cache-Control": "private, max-age=3600", "Last-Modified": formatdate(usegmt=True), }) @bp.route("/web/restore-pfp/", methods=["POST"]) def web_restore_pfp(history_id): 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 image_data = db.get_pfp_history_image(history_id, pid) if image_data is None: return jsonify({"error": "Not found"}), 404 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) 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) return jsonify({"success": True, "image_name": image_name}) @bp.route("/web/heartbeat", methods=["POST"]) @limiter.limit("60 per minute") def web_heartbeat(): pid = get_current_profile_id() if pid is None: return jsonify({"error": "Not authenticated"}), 401 _web_heartbeat(pid) return jsonify({"ok": True}) @bp.route("/web/token-balance", methods=["GET"]) def web_token_balance(): pid = get_current_profile_id() if pid is None: return jsonify({"error": "Not authenticated"}), 401 return jsonify({"tokens": db.get_tokens(pid)}) @bp.route("/web/my-photos", methods=["GET"]) def web_my_photos(): pid = get_current_profile_id() if pid is None: return jsonify({"error": "Not authenticated"}), 401 try: offset = max(0, int(request.args.get("offset", 0))) limit = min(48, max(1, int(request.args.get("limit", 24)))) except (ValueError, TypeError): offset, limit = 0, 24 photos = db.get_photos_paginated(profile_id=pid, limit=limit, offset=offset) total = db.get_photo_count(profile_id=pid) return jsonify({ "photos": [{"name": p["name"], "room_name": p["room_name"], "created_at": p["created_at"]} for p in photos], "total": total, "offset": offset, "limit": limit, }) @bp.route("/web/notifications", methods=["GET"]) def web_notifications(): from core.constants import REL_RECEIVED, MSG_FRIEND_INVITE, MSG_FRIEND_REQUEST_ACCEPTED, MSG_GAME_INVITE, MSG_TEXT pid = get_current_profile_id() if pid is None: return jsonify({"error": "Not authenticated"}), 401 online_ids = _all_online_ids() result = [] rels = db.get_relationships(pid) for r in rels: if r["RelationshipType"] != REL_RECEIVED: continue p = db.get_profile(r["PlayerID"]) if not p: continue result.append({ "kind": "friend_request", "id": r["PlayerID"], "from_id": r["PlayerID"], "from_name": p["DisplayName"] or p["Username"], "from_username": p["Username"], "has_image": bool(p.get("ProfileImageName", "")), "sent_at": None, }) msgs = db.get_messages(pid) skip_types = {MSG_FRIEND_INVITE} for m in reversed(msgs[-50:]): t = m["Type"] if t in skip_types: continue from_pid = m["FromPlayerId"] p = db.get_profile(from_pid) if from_pid else None from_name = (p["DisplayName"] or p["Username"]) if p else "KittyRec" has_image = bool(p.get("ProfileImageName", "")) if p else False if t == MSG_FRIEND_REQUEST_ACCEPTED: label = f"{from_name} accepted your friend request" elif t == MSG_GAME_INVITE: label = f"{from_name} invited you to a room" elif t == MSG_TEXT: label = m["Data"][:120] if m.get("Data") else "New message" else: label = m.get("Data", "Notification")[:120] result.append({ "kind": "notification", "id": m["Id"], "from_id": from_pid, "from_name": from_name, "has_image": has_image, "label": label, "type": t, "sent_at": m["SentTime"], "room_id": m.get("RoomId"), }) return jsonify(result) @bp.route("/web/notifications/dismiss/", methods=["POST"]) def web_dismiss_notification(msg_id): pid = get_current_profile_id() if pid is None: return jsonify({"error": "Not authenticated"}), 401 db.delete_message(msg_id, pid) return jsonify({"ok": True}) def _player_summary(pid: int, online_ids: set) -> dict: p = db.get_profile(pid) if not p: return {"id": pid, "username": "Unknown", "display_name": "Unknown", "online": False, "has_image": False} return { "id": p["Id"], "username": p["Username"], "display_name": p["DisplayName"], "online": p["Id"] in online_ids, "has_image": bool(p.get("ProfileImageName", "")), } @bp.route("/web/chats", methods=["GET"]) @limiter.limit("60 per minute") def web_chats(): pid = get_current_profile_id() if pid is None: return jsonify({"error": "Not authenticated"}), 401 online_ids = _all_online_ids() threads = db.get_player_chats(pid) result = [] for t in threads: players = [_player_summary(p, online_ids) for p in t["PlayerIds"] if p != pid] unread = 0 latest = t.get("LatestMessage") if latest and t.get("LastReadMessageId", 0) < latest.get("ChatMessageId", 0): conn = db._get_conn() unread = conn.execute( "SELECT COUNT(*) AS c FROM chat_messages WHERE thread_id = ? AND id > ?", (t["ChatThreadId"], t.get("LastReadMessageId", 0)), ).fetchone()["c"] result.append({ "thread_id": t["ChatThreadId"], "players": players, "latest_message": latest, "unread": unread, }) result.sort(key=lambda x: (x["latest_message"] or {}).get("ChatMessageId", 0), reverse=True) return jsonify(result) @bp.route("/web/chats/", methods=["GET"]) @limiter.limit("60 per minute") def web_chat_thread(thread_id): pid = get_current_profile_id() if pid is None: return jsonify({"error": "Not authenticated"}), 401 if pid not in db.get_chat_thread_players(thread_id): return jsonify({"error": "Not found"}), 404 before_id = request.args.get("before_id", type=int) messages = db.get_chat_messages(thread_id, count=50, before_id=before_id) messages = list(reversed(messages)) online_ids = _all_online_ids() players = [_player_summary(p, online_ids) for p in db.get_chat_thread_players(thread_id)] if messages: db.mark_chat_read(thread_id, pid, messages[-1]["ChatMessageId"]) return jsonify({"thread_id": thread_id, "players": players, "messages": messages}) @bp.route("/web/chats//send", methods=["POST"]) @limiter.limit("30 per minute") def web_chat_send(thread_id): pid = get_current_profile_id() if pid is None: return jsonify({"error": "Not authenticated"}), 401 if db.is_banned(pid): return jsonify({"error": "Forbidden"}), 403 if pid not in db.get_chat_thread_players(thread_id): return jsonify({"error": "Not in thread"}), 403 data = request.get_json(silent=True) or {} text = str(data.get("text", "")).strip()[:2000] if not text: return jsonify({"error": "Empty message"}), 400 msg_id = db.send_chat_message(thread_id, pid, text) msg = db.get_chat_message(msg_id) for member_pid in db.get_chat_thread_players(thread_id): ws_registry.send(member_pid, {"Id": 90, "Msg": msg}) if member_pid != pid: ws_registry.send(member_pid, {"Id": 2, "Msg": msg}) db.mark_chat_read(thread_id, pid, msg_id) return jsonify(msg) @bp.route("/web/chats/start", methods=["POST"]) @limiter.limit("10 per minute") def web_chat_start(): pid = get_current_profile_id() if pid is None: return jsonify({"error": "Not authenticated"}), 401 data = request.get_json(silent=True) or {} other_id = int(data.get("player_id", 0)) if not other_id or other_id == pid: return jsonify({"error": "Invalid player"}), 400 if not db.get_profile(other_id): return jsonify({"error": "Player not found"}), 404 thread_id = db.get_or_create_chat([pid, other_id]) return jsonify({"thread_id": thread_id}) @bp.route("/web/chats//poll", methods=["GET"]) @limiter.limit("60 per minute") def web_chat_poll(thread_id): pid = get_current_profile_id() if pid is None: return jsonify({"error": "Not authenticated"}), 401 if pid not in db.get_chat_thread_players(thread_id): return jsonify({"error": "Not found"}), 404 after_id = request.args.get("after_id", type=int, default=0) conn = db._get_conn() rows = conn.execute( "SELECT * FROM chat_messages WHERE thread_id = ? AND id > ? ORDER BY id ASC LIMIT 50", (thread_id, after_id), ).fetchall() msgs = [db._chat_msg_row_to_dict(r) for r in rows] if msgs: db.mark_chat_read(thread_id, pid, msgs[-1]["ChatMessageId"]) return jsonify(msgs)