diff --git a/routes/portal.py b/routes/portal.py new file mode 100644 index 0000000..ddc0761 --- /dev/null +++ b/routes/portal.py @@ -0,0 +1,2731 @@ +import json +import os +import socket +import time +import urllib.request +from functools import wraps + +from flask import ( + Blueprint, render_template, request, redirect, url_for, + session, jsonify, Response, +) + +from core.state import db, session_mgr, ws_registry, maintenance_lock +import core.state as _state +from core.constants import DORM_ROOM_GUID +from core.ws_helpers import push_gift, push_presence +from core.limiter import limiter +from core.admin_auth import ( + get_admin_account as _get_admin_account, + has_any_admin_scope as _has_any_admin_scope, + SCOPE_ADMIN, SCOPE_MOD, AUTH_LOGIN_URL, make_login_redirect, + probe_auth_server, EMERGENCY_LOGIN_URL, + EMERGENCY_PASSWORD, _EMERGENCY_SESSION_TTL, +) +from core.config import auth as _auth_cfg, base_url as _base_url, discord as _discord_cfg +from routes.avatar import _generate_gift_for_player + +bp = Blueprint("portal", __name__, template_folder="../templates") + +_KITTYREC_SYSTEM_ID = 23 + + +def _now_iso(): + import datetime + return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _send_system_message(to_pid: int, text: str) -> None: + msg_id = db.send_message(_KITTYREC_SYSTEM_ID, to_pid, 30, text) + ws_registry.send(to_pid, {"Id": 2, "Msg": { + "Id": msg_id, "FromPlayerId": _KITTYREC_SYSTEM_ID, + "SentTime": _now_iso(), "Type": 30, "Data": text, + "RoomId": None, "PlayerEventId": None, + }}) + + +def _broadcast_system_message(text: str) -> None: + for p in db.get_all_profiles_summary(): + _send_system_message(p["id"], text) + + +def _server_host(): + try: + return socket.gethostbyname(socket.gethostname()) + except Exception: + return "localhost" + + +def require_scope(needed): + def decorator(f): + @wraps(f) + def decorated(*args, **kwargs): + account, scopes = _get_admin_account() + if not account: + if request.is_json or request.headers.get("X-Requested-With") == "XMLHttpRequest" or request.content_type and "multipart" in request.content_type: + return jsonify({"error": "Unauthorized"}), 403 + if probe_auth_server(): + return redirect(EMERGENCY_LOGIN_URL) + return redirect(make_login_redirect()) + if not _has_any_admin_scope(scopes): + return jsonify({"error": "Unauthorized"}), 403 + if needed not in scopes: + return jsonify({"error": f"Requires {needed} scope"}), 403 + return f(account=account, scopes=scopes, *args, **kwargs) + return decorated + return decorator + + +def require_admin_api(f): + @wraps(f) + def decorated(*args, **kwargs): + account, scopes = _get_admin_account() + if not account or not _has_any_admin_scope(scopes): + return jsonify({"error": "Unauthorized"}), 403 + return f(account=account, scopes=scopes, *args, **kwargs) + return decorated + + +def player_required(f): + @wraps(f) + def decorated(*args, **kwargs): + if not session.get("portal_pid"): + return redirect(url_for("portal.portal_login")) + return f(*args, **kwargs) + return decorated + + +@bp.route("/") +@limiter.limit("30 per minute") +def index(): + online = len(ws_registry.connected_ids()) + sessions = len(session_mgr.all_public_sessions()) + total = len(db.get_all_profiles_summary()) + photos = db.get_recent_photos(48) + return render_template("index.html", + online=online, sessions=sessions, total=total, + host=_server_host(), photos=photos, + ) + + +_LOG_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), "logs", "server.log") +_LOG_INITIAL_BYTES = 128 * 1024 + + +@bp.route("/admin/api/console/read") +@require_admin_api +def console_read(**_kw): + pos = request.args.get("pos", type=int, default=None) + try: + with open(_LOG_PATH, "rb") as f: + f.seek(0, 2) + size = f.tell() + if pos is None: + start = max(0, size - _LOG_INITIAL_BYTES) + else: + start = pos + f.seek(start) + chunk = f.read() + text = chunk.decode("utf-8", errors="replace") + return jsonify({"text": text, "pos": size}) + except FileNotFoundError: + return jsonify({"text": "", "pos": 0}) + + +@bp.route("/admin/api/public_stats") +@require_admin_api +def public_stats(**_kw): + return jsonify({ + "online": len(ws_registry.connected_ids()), + "sessions": len(session_mgr.all_public_sessions()), + }) + + +@bp.route("/api/public/v1/status") +@limiter.limit("60 per minute") +def public_status(): + return jsonify({ + "online": len(ws_registry.connected_ids()), + "sessions": len(session_mgr.all_public_sessions()), + "total_players": len(db.get_all_profiles_summary()), + "maintenance": _state.maintenance_mode, + }) + + +@bp.route("/api/public/v1/sessions") +@limiter.limit("60 per minute") +def public_sessions(): + result = [] + for s in session_mgr.all_public_sessions(): + result.append({ + "session_id": s.session_id, + "name": s.name, + "activity_level_id": s.activity_level_id, + "player_count": len(s.players), + "max_capacity": s.max_capacity, + "sandbox": s.sandbox, + }) + result.sort(key=lambda x: x["player_count"], reverse=True) + return jsonify(result) + + +@bp.route("/api/public/v1/players") +@limiter.limit("30 per minute") +def public_players(): + online_ids = ws_registry.connected_ids() + result = [] + for pid in online_ids: + p = db.get_profile(pid) + if not p: + continue + sess = session_mgr.get_player_session(pid) + result.append({ + "player_id": pid, + "display_name": p.get("DisplayName") or p.get("display_name") or "", + "username": p.get("Username") or p.get("username") or "", + "room_name": sess.name if sess and not sess.private else None, + "activity_level_id": sess.activity_level_id if sess else None, + }) + return jsonify(result) + + +@bp.route("/api/public/v1/leaderboard") +@limiter.limit("60 per minute") +def public_leaderboard(): + from core.state import ws_registry + online_ids = set(ws_registry.connected_ids()) + conn = db._get_conn() + rows = conn.execute( + "SELECT id, username, display_name, level, xp, developer, created_at, profile_image_name " + "FROM profiles ORDER BY xp DESC LIMIT 100" + ).fetchall() + return jsonify([{ + "id": r["id"], + "username": r["username"], + "display_name": r["display_name"], + "level": r["level"], + "xp": r["xp"], + "developer": bool(r["developer"]), + "online": r["id"] in online_ids, + "has_image": bool(r["profile_image_name"]), + } for r in rows]) + + +@bp.route("/api/public/v1/photos") +@limiter.limit("30 per minute") +def public_photos(): + try: + limit = min(int(request.args.get("limit", 48)), 96) + offset = max(int(request.args.get("offset", 0)), 0) + pid_param = request.args.get("pid") + profile_id = int(pid_param) if pid_param and str(pid_param).isdigit() else None + except (ValueError, TypeError): + limit, offset, profile_id = 24, 0, None + photos = db.get_photos_paginated(profile_id=profile_id, limit=limit, offset=offset) + total = db.get_photo_count(profile_id=profile_id) + return jsonify({ + "photos": [{ + "name": p["name"], + "url": f"/alt/{p['name']}", + "uploader": p["display_name"] or p["username"] or "Unknown", + "uploader_id": p["profile_id"], + "room": p.get("room_name") or "", + "created_at": p.get("created_at") or "", + } for p in photos], + "total": total, + "offset": offset, + "limit": limit, + }) + + +@bp.route("/api/public/v1/profile/") +@limiter.limit("60 per minute") +def public_profile(pid): + p = db.get_profile(pid) + if not p: + return jsonify({"error": "Not found"}), 404 + return jsonify({ + "id": p["Id"], + "username": p["Username"], + "display_name": p["DisplayName"], + "level": p.get("Level", 1), + "xp": p.get("XP", 0), + "bio": p.get("Bio", ""), + "developer": bool(p.get("Developer", False)), + "reputation": p.get("Reputation", 0), + "profile_image": p.get("ProfileImageName", ""), + "created_at": p.get("created_at", ""), + }) + + +@bp.route("/api/public/v1/search") +@limiter.limit("20 per minute") +def public_search(): + q = request.args.get("q", "").strip() + if not q or len(q) < 2: + return jsonify([]) + results = db.search_profiles(q, limit=20) + return jsonify([{ + "id": p["Id"], + "username": p["Username"], + "display_name": p["DisplayName"], + "level": p.get("Level", 1), + "xp": p.get("XP", 0), + "has_image": bool(p.get("ProfileImageName")), + } for p in results if not p.get("Banned")]) + + +@bp.route("/api/public/v1/profile//photos") +@limiter.limit("30 per minute") +def public_profile_photos(pid): + try: + limit = min(int(request.args.get("limit", 24)), 96) + offset = max(int(request.args.get("offset", 0)), 0) + except (ValueError, TypeError): + limit, offset = 24, 0 + 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"], + "url": f"/alt/{p['name']}", + "uploader": p["display_name"] or p["username"] or "Unknown", + "room": p.get("room_name") or "", + "created_at": p.get("created_at") or "", + } for p in photos], + "total": total, + "offset": offset, + "limit": limit, + }) + + +@bp.route("/api/public/v1/activity") +@limiter.limit("60 per minute") +def public_activity(): + sessions = session_mgr.all_public_sessions() + activity_map: dict[str, dict] = {} + for s in sessions: + aid = s.activity_level_id + if not aid: + continue + if aid not in activity_map: + activity_map[aid] = { + "activity_level_id": aid, + "name": s.name, + "player_count": 0, + "session_count": 0, + } + activity_map[aid]["player_count"] += len(s.players) + activity_map[aid]["session_count"] += 1 + result = sorted(activity_map.values(), key=lambda x: -x["player_count"]) + return jsonify(result) + + +@bp.route("/api/public/v1/docs") +def public_api_docs(): + import os + path = os.path.join(os.path.dirname(__file__), "..", "data", "public_api.json") + with open(path, "r") as f: + return Response(f.read(), mimetype="application/json") + + +_BOT_SECRET = _discord_cfg.get("bot_secret", "") + + +def _check_bot_auth() -> bool: + if not _BOT_SECRET: + return False + import hmac + provided = request.headers.get("X-Bot-Secret", "") + return hmac.compare_digest(provided.encode("utf-8"), _BOT_SECRET.encode("utf-8")) + + +@bp.route("/api/internal/discord/initiate", methods=["POST"]) +def discord_initiate(): + if not _check_bot_auth(): + return jsonify({"error": "unauthorized"}), 401 + data = request.get_json(silent=True) or {} + username = (data.get("username") or "").strip() + discord_user_id = str(data.get("discord_user_id") or "").strip() + discord_username = str(data.get("discord_username") or "").strip() + if not username or not discord_user_id: + return jsonify({"error": "missing_fields"}), 400 + + existing_discord = db.get_discord_link_by_discord_id(discord_user_id) + if existing_discord: + return jsonify({"status": "already_linked"}), 200 + + profile = db.get_profile_by_username(username) + if not profile: + return jsonify({"status": "not_found"}), 200 + + pid = profile["Id"] + + existing_profile = db.get_discord_link_by_profile_id(pid) + if existing_profile: + return jsonify({"status": "profile_already_linked"}), 200 + + if not ws_registry.is_connected(pid): + return jsonify({"status": "not_online"}), 200 + + age = db.discord_link_code_age_seconds(pid) + if age is not None and age < 60: + return jsonify({"status": "rate_limited", "retry_after": int(60 - age)}), 200 + + code = db.create_discord_link_code(pid, discord_user_id, discord_username) + _send_system_message( + pid, + f"Your Discord link code is: {code}\nDM this code to the KittyNet bot in Discord. Do NOT post it in a public channel. It expires in 10 minutes.", + ) + + return jsonify({"status": "sent", "username": profile["Username"]}), 200 + + +@bp.route("/api/internal/discord/confirm", methods=["POST"]) +def discord_confirm(): + if not _check_bot_auth(): + return jsonify({"error": "unauthorized"}), 401 + data = request.get_json(silent=True) or {} + code = (data.get("code") or "").strip().upper() + discord_user_id = str(data.get("discord_user_id") or "").strip() + discord_username = str(data.get("discord_username") or "").strip() + if not code or not discord_user_id: + return jsonify({"error": "missing_fields"}), 400 + + existing = db.get_discord_link_by_discord_id(discord_user_id) + if existing: + return jsonify({"status": "already_linked"}), 200 + + pid = db.consume_discord_link_code(code, discord_user_id) + if pid is None: + return jsonify({"status": "invalid_code"}), 200 + + profile = db.get_profile(pid) + if not profile: + return jsonify({"status": "invalid_code"}), 200 + + db.create_discord_link(pid, discord_user_id, discord_username) + + _send_system_message( + pid, + f"Your Discord account has been linked! Welcome, {discord_username}! You're all set.", + ) + + return jsonify({ + "status": "linked", + "profile_id": pid, + "username": profile["Username"], + "display_name": profile["DisplayName"], + "level": profile.get("Level", 1), + }), 200 + + +@bp.route("/portal", methods=["GET", "POST"]) +@limiter.limit("10 per minute") +def portal_login(): + import secrets as _secrets + if session.get("portal_pid"): + return redirect(url_for("portal.portal_me")) + error = None + if request.method == "POST": + token = request.form.get("csrf_token", "") + if not token or token != session.get("csrf_token"): + error = "Invalid request. Please try again." + else: + username = request.form.get("username", "").strip() + password = request.form.get("password", "").strip() + profile = db.check_password(username, password) + if profile: + session["portal_pid"] = profile["Id"] + session.pop("csrf_token", None) + return redirect(url_for("portal.portal_me")) + error = "Invalid username or password." + csrf_token = _secrets.token_hex(16) + session["csrf_token"] = csrf_token + return render_template("portal/login.html", error=error, csrf_token=csrf_token) + + +@bp.route("/portal/me") +@player_required +def portal_me(): + pid = session["portal_pid"] + profile = db.get_profile(pid) + if not profile: + session.pop("portal_pid", None) + return redirect(url_for("portal.portal_login")) + gifts = db.get_pending_gifts(pid) + return render_template("portal/profile.html", profile=profile, gifts=gifts) + + +@bp.route("/portal/logout") +def portal_logout(): + session.pop("portal_pid", None) + return redirect(url_for("portal.portal_login")) + + +@bp.route("/portal/api/consume_gift/", methods=["POST"]) +@player_required +def portal_consume_gift(gift_id): + pid = session["portal_pid"] + gift = db.consume_gift(gift_id, pid) + if gift is None: + return jsonify({"ok": False}) + if gift.get("AvatarItemDesc"): + db.unlock_avatar_item(pid, gift["AvatarItemDesc"]) + return jsonify({"ok": True, "xp": gift["Xp"], "item": gift["EquipmentPrefabName"]}) + + +@bp.route("/admin/api/toggle_dev/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_toggle_dev(player_id, account, scopes): + profile = db.get_profile(player_id) + if profile is None: + return jsonify({"error": "Not found"}), 404 + new_val = not profile["Developer"] + db.set_developer(player_id, new_val) + print(f"[Admin] {account.get('username')} set player {player_id} developer={new_val}") + return jsonify({"developer": new_val}) + + +from core.ban_service import cascade_ban as _cascade_ban, cascade_unban as _cascade_unban, kick_player as _kick_player + + +@bp.route("/admin/api/ban/", methods=["POST"]) +@require_admin_api +def api_ban(player_id, account, scopes): + data = request.get_json(force=True, silent=True) or {} + reason = data.get("reason", "Banned by admin")[:256] + duration_h = int(data.get("duration_hours", 0)) + drop_ws = bool(data.get("drop_ws", True)) + admin_name = account.get("username", "admin") + + if duration_h == 0 and SCOPE_ADMIN not in scopes: + return jsonify({"error": "Permanent bans require kittyrec.admin scope"}), 403 + + until = db.ban_player(player_id, reason=reason, duration_hours=duration_h, admin_name=admin_name) + _cascade_ban(player_id, reason, duration_h, admin_name) + p = db.get_profile(player_id) + label = "permaban" if duration_h == 0 else f"ban_{duration_h}h" + db.log_admin_action(admin_name, label, f"Banned {p['Username'] if p else player_id}: {reason}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[Admin] {admin_name} banned player {player_id} reason={reason!r} drop_ws={drop_ws}") + try: + from core.discord import send_admin + uname = p["Username"] if p else str(player_id) + dur_str = "Permanent" if duration_h == 0 else f"{duration_h}h" + send_admin( + title="Player Banned", + color=0xE74C3C, + fields=[{"name": "Player", "value": f"{uname} (id={player_id})", "inline": True}, + {"name": "Duration", "value": dur_str, "inline": True}, + {"name": "Reason", "value": reason, "inline": False}, + {"name": "By", "value": admin_name, "inline": True}], + ) + except Exception: + pass + return jsonify({"ok": True, "banned_until": until}) + + +@bp.route("/admin/api/unban/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_unban(player_id, account, scopes): + name = account.get("username", "admin") + p = db.get_profile(player_id) + db.unban_player(player_id, admin_name=name) + from core.state import db as _db + ips = [ip for ip in _db.get_ips_for_profile(player_id) if ip not in ("127.0.0.1", "::1")] + for pid in set(_db.get_all_profiles_for_ips(ips)): + if _db.is_banned(pid): + _db.unban_player(pid, admin_name=name) + from core.anticheat import reset_offenses + reset_offenses(player_id) + db.log_admin_action(name, "unban", f"Unbanned {p['Username'] if p else player_id}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[Admin] {name} unbanned player {player_id}") + try: + from core.discord import send_admin + uname = p["Username"] if p else str(player_id) + send_admin( + title="Player Unbanned", + color=0x2ECC71, + fields=[{"name": "Player", "value": f"{uname} (id={player_id})", "inline": True}, + {"name": "By", "value": name, "inline": True}], + ) + except Exception: + pass + return jsonify({"ok": True}) + + +@bp.route("/admin/api/disconnect/", methods=["POST"]) +@require_admin_api +def api_disconnect(player_id, account, scopes): + name = account.get("username", "admin") + p = db.get_profile(player_id) + dropped = _kick_player(player_id) + db.log_admin_action(name, "disconnect", f"Disconnected {p['Username'] if p else player_id}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[Admin] {name} disconnected player {player_id} ws") + return jsonify({"ok": True, "was_online": dropped}) + + +@bp.route("/admin/api/gift_player/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_gift_player(player_id, account, scopes): + data = request.get_json(force=True, silent=True) or {} + xp = int(data.get("xp", 0)) + rarity = int(data.get("rarity", 0)) + level = int(data.get("level", 0)) + currency_type = int(data.get("currency_type", 0)) + currency = int(data.get("currency", 0)) + gift = db.add_gift( + player_id, + xp=xp, + gift_rarity=rarity, + level=level, + currency_type=currency_type, + currency=currency, + equipment_prefab_name=data.get("prefab", ""), + equipment_modification_guid=data.get("guid", ""), + avatar_item_desc=data.get("avatar_item_desc", ""), + consumable_item_desc=data.get("consumable_item_desc", ""), + message=data.get("message", "Gift from KittyRec admin"), + gift_context=0, + ) + push_gift(player_id, gift) + name = account.get("username", "admin") + ip = request.headers.get("X-Forwarded-For", request.remote_addr or "") + parts = [] + if xp: parts.append(f"{xp} XP") + if level: parts.append(f"{level} levels") + if currency: parts.append(f"{currency} tokens") + if data.get("consumable_item_desc"): parts.append(f"consumable:{data['consumable_item_desc'][:20]}") + if data.get("avatar_item_desc"): parts.append(f"item:{data['avatar_item_desc'][:20]}") + if data.get("prefab"): parts.append(f"equip:{data['prefab']}") + detail = ", ".join(parts) or "gift" + db.log_admin_action(name, "gift_player", f"Gifted {detail} to player {player_id}", ip) + print(f"[Admin] {name} gifted player {player_id}: {detail}") + return jsonify(gift) + + +@bp.route("/admin/api/reroll_store", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_reroll_store(account, scopes): + from routes.storefronts import reroll_store + offset = reroll_store() + name = account.get("username", "admin") + db.log_admin_action(name, "reroll_store", f"Rerolled store (offset={offset})", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[Admin] {name} rerolled store (offset={offset})") + try: + from core.discord import send_admin + send_admin( + title="Store Rerolled", + color=0x9B59B6, + fields=[{"name": "By", "value": name, "inline": True}, + {"name": "Seed Offset", "value": str(offset), "inline": True}], + ) + except Exception: + pass + return jsonify({"ok": True, "offset": offset}) + + +@bp.route("/admin/api/send_message", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_send_message(account, scopes): + data = request.get_json(force=True, silent=True) or {} + target_id = data.get("player_id") + message = str(data.get("message", "")) + broadcast = data.get("broadcast", False) + if not message: + return jsonify({"error": "No message provided"}), 400 + import datetime + sent_to = [] + if broadcast: + for p in db.get_all_profiles_summary(): + _send_system_message(p["id"], message) + sent_to.append(p["id"]) + elif target_id: + _send_system_message(int(target_id), message) + sent_to.append(int(target_id)) + else: + return jsonify({"error": "No player_id or broadcast flag"}), 400 + name = account.get("username", "admin") + scope = "broadcast" if broadcast else f"player {target_id}" + db.log_admin_action(name, "send_notification", + f"Sent notification to {len(sent_to)} player(s) [{scope}]: {message[:80]}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[Admin] {name} sent message to {len(sent_to)} player(s): {message[:80]}") + return jsonify({"ok": True, "sent_to": len(sent_to)}) + + +def _send_chat_dm(to_pid: int, text: str) -> None: + msg_type = 30 + msg_id = db.send_message(_KITTYREC_SYSTEM_ID, to_pid, msg_type, text) + msg_dict = { + "Id": msg_id, "FromPlayerId": _KITTYREC_SYSTEM_ID, + "SentTime": _now_iso(), "Type": msg_type, "Data": text, + "RoomId": None, "PlayerEventId": None, + } + ws_registry.send(to_pid, {"Id": 2, "Msg": msg_dict}) + + +@bp.route("/admin/api/send_dm", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_send_dm(account, scopes): + data = request.get_json(force=True, silent=True) or {} + target_id = data.get("player_id") + message = str(data.get("message", "")).strip() + broadcast = data.get("broadcast", False) + if not message: + return jsonify({"error": "No message provided"}), 400 + sent_to = [] + if broadcast: + for p in db.get_all_profiles_summary(): + _send_chat_dm(p["id"], message) + sent_to.append(p["id"]) + elif target_id: + pid = int(target_id) + _send_chat_dm(pid, message) + sent_to.append(pid) + else: + return jsonify({"error": "No player_id or broadcast flag"}), 400 + name = account.get("username", "admin") + scope = "broadcast" if broadcast else f"player {target_id}" + db.log_admin_action(name, "send_dm", + f"Sent DM to {len(sent_to)} player(s) [{scope}]: {message[:80]}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[Admin] {name} sent chat DM to {len(sent_to)} player(s): {message[:80]}") + return jsonify({"ok": True, "sent_to": len(sent_to)}) + + +@bp.route("/admin/api/reset_password/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_reset_password(account, scopes, player_id): + import secrets, string + from werkzeug.security import generate_password_hash + profile = db.get_profile(player_id) + if not profile: + return jsonify({"error": "Player not found"}), 404 + alphabet = string.ascii_letters + string.digits + temp_pass = "".join(secrets.choice(alphabet) for _ in range(8)) + conn = db._get_conn() + conn.execute("UPDATE profiles SET password=?, must_change_password=1 WHERE id=?", + (generate_password_hash(temp_pass), player_id)) + conn.commit() + from tracking.password_tracking import clear_password_set + clear_password_set(player_id) + username = profile.get("Username", f"Player{player_id}") + from core.system_messages import send_and_await + send_and_await(player_id, + f"Your password has been reset by an admin.\n\n" + f"Your username: {username}\n" + f"Your new temp password: {temp_pass}\n\n" + f"Reply to this message with a new password (8+ chars) to update it!", + "password_change", expires_in=0) + name = account.get("username", "admin") + db.log_admin_action(name, "reset_password", f"Reset password for {username} (id={player_id})", request.remote_addr) + print(f"[Admin] {name} reset password for pid={player_id} ({username})") + try: + from core.discord import send_admin + send_admin( + title="Password Reset", + color=0xE67E22, + fields=[{"name": "Player", "value": f"{username} (id={player_id})", "inline": True}, + {"name": "By", "value": name, "inline": True}], + ) + except Exception: + pass + return jsonify({"ok": True, "username": username, "temp_password": temp_pass}) + + +@bp.route("/admin/api/gift_all", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_gift_all(account, scopes): + data = request.get_json(force=True, silent=True) or {} + profiles = db.get_all_profiles_summary() + for p in profiles: + gift = db.add_gift( + p["id"], + xp=int(data.get("xp", 1000)), + gift_rarity=int(data.get("rarity", 1)), + equipment_prefab_name=data.get("prefab", ""), + equipment_modification_guid=data.get("guid", ""), + avatar_item_desc=data.get("avatar_item_desc", ""), + consumable_item_desc=data.get("consumable_item_desc", ""), + message=data.get("message", "Gift from KittyRec admin"), + gift_context=0, + ) + push_gift(p["id"], gift) + name = account.get("username", "admin") + db.log_admin_action(name, "gift_all", f"Gifted all {len(profiles)} players ({data.get('xp',1000)} XP)", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[Admin] {name} gifted all {len(profiles)} players") + try: + from core.discord import send_admin + send_admin( + title="Gift All Players", + color=0x9B59B6, + fields=[{"name": "By", "value": name, "inline": True}, + {"name": "Players", "value": str(len(profiles)), "inline": True}, + {"name": "XP", "value": str(data.get("xp", 1000)), "inline": True}], + ) + except Exception: + pass + return jsonify({"count": len(profiles)}) + + +@bp.route("/admin/api/stats") +@require_admin_api +def api_stats(account, scopes): + conn = db._get_conn() + pending = conn.execute("SELECT COUNT(*) AS c FROM gifts WHERE consumed=0").fetchone()["c"] + banned = conn.execute("SELECT COUNT(*) AS c FROM profiles WHERE banned=1").fetchone()["c"] + recent = db.get_admin_action_log(limit=10) + return jsonify({ + "online": len(ws_registry.connected_ids()), + "sessions": len(session_mgr.all_public_sessions()), + "pending_gifts": pending, + "banned": banned, + "recent_actions": recent, + "total_playtime_seconds": db.get_total_playtime(), + }) + + +@bp.route("/admin/api/playtime_leaderboard") +@require_admin_api +def api_playtime_leaderboard(account, scopes): + rows = db.get_playtime_leaderboard(limit=20) + return jsonify(rows) + + +@bp.route("/admin/api/online_players") +@require_admin_api +def api_online_players(account, scopes): + online_ids = ws_registry.connected_ids() + profiles_map = db.get_profiles_batch(online_ids) + result = [] + for pid in online_ids: + p = profiles_map.get(pid) + if p: + s = session_mgr.get_player_session(pid) + result.append({ + "id": p["Id"], + "username": p["Username"], + "display_name": p["DisplayName"], + "level": p["Level"], + "room": s.name if s else "Unknown", + "activity": s.activity_key if s else "", + }) + return jsonify(result) + + +@bp.route("/admin/api/search_players") +@require_admin_api +def api_search_players(account, scopes): + q = request.args.get("q", "").strip() + profiles = db.search_profiles(q, limit=20) + online_ids = set(ws_registry.connected_ids()) + result = [] + for p in profiles: + result.append({ + "id": p["Id"], + "username": p["Username"], + "display_name": p["DisplayName"], + "level": p["Level"], + "online": p["Id"] in online_ids, + }) + return jsonify(result) + + +@bp.route("/admin/api/player_status/") +@require_admin_api +def api_player_status(player_id, account, scopes): + p = db.get_profile(player_id) + if not p: + return jsonify({"error": "Not found"}), 404 + online_ids = set(ws_registry.connected_ids()) + pt = db.get_playtime(player_id) + return jsonify({ + "id": p["Id"], + "username": p["Username"], + "display_name": p["DisplayName"], + "level": p["Level"], + "online": p["Id"] in online_ids, + "banned": bool(p.get("Banned")), + "ban_reason": p.get("BanReason") or "", + "developer": bool(p.get("Developer")), + "playtime_seconds": pt["total_seconds"], + "session_count": pt["session_count"], + }) + + +@bp.route("/admin/api/player_timeline/") +@require_admin_api +def api_player_timeline(player_id, account, scopes): + p = db.get_profile(player_id) + if not p: + return jsonify({"error": "Not found"}), 404 + conn = db._get_conn() + events = [] + if p.get("CreatedAt"): + events.append({"type": "account_created", "timestamp": p["CreatedAt"], "detail": "Account registered"}) + for r in conn.execute( + "SELECT action, reason, admin_name, created_at FROM ban_log WHERE profile_id=? ORDER BY created_at DESC LIMIT 30", + (player_id,) + ).fetchall(): + detail = (r["reason"] or "") + (" (by " + r["admin_name"] + ")" if r["admin_name"] else "") + events.append({"type": r["action"], "timestamp": r["created_at"], "detail": detail.strip()}) + for r in conn.execute( + "SELECT xp, gift_rarity, message, created_at FROM gifts WHERE profile_id=? ORDER BY created_at DESC LIMIT 30", + (player_id,) + ).fetchall(): + parts = [] + if r["xp"]: parts.append(str(r["xp"]) + " XP") + if r["message"]: parts.append('"' + r["message"] + '"') + events.append({"type": "gift", "timestamp": r["created_at"], "detail": ", ".join(parts) or "Gift"}) + events.sort(key=lambda e: e["timestamp"] or "", reverse=True) + return jsonify(events[:50]) + + +@bp.route("/admin/api/player_notes/") +@require_admin_api +def api_player_notes_get(player_id, account, scopes): + if not db.get_profile(player_id): + return jsonify({"error": "Not found"}), 404 + return jsonify(db.get_player_notes(player_id)) + + +@bp.route("/admin/api/player_notes/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_player_notes_add(player_id, account, scopes): + data = request.get_json(force=True, silent=True) or {} + note = (data.get("note") or "").strip() + if not note: + return jsonify({"error": "Note is empty"}), 400 + if not db.get_profile(player_id): + return jsonify({"error": "Not found"}), 404 + note_id = db.add_player_note(player_id, note, account.get("username", "admin")) + return jsonify({"ok": True, "id": note_id}) + + +@bp.route("/admin/api/player_notes//", methods=["DELETE"]) +@require_scope(SCOPE_ADMIN) +def api_player_notes_delete(player_id, note_id, account, scopes): + db.delete_player_note(note_id, player_id) + return jsonify({"ok": True}) + + +@bp.route("/admin/api/shared_ips") +@require_admin_api +def api_shared_ips(account, scopes): + conn = db._get_conn() + rows = conn.execute( + "SELECT profile_id FROM ip_logins WHERE ip_address IN " + "(SELECT ip_address FROM ip_logins GROUP BY ip_address HAVING COUNT(DISTINCT profile_id) > 1) " + "GROUP BY profile_id" + ).fetchall() + return jsonify([r["profile_id"] for r in rows]) + + +@bp.route("/admin/api/anticheat_suspects") +@require_admin_api +def api_anticheat_suspects(account, scopes): + from core.anticheat import get_suspects + return jsonify(get_suspects()) + + +@bp.route("/admin/api/player_security/") +@require_admin_api +def api_player_security(player_id, account, scopes): + if not db.get_profile(player_id): + return jsonify({"error": "Not found"}), 404 + ips = db.get_ips_for_profile(player_id) + assoc = db.get_associated_accounts_with_evidence(player_id) + assoc_profiles = db.get_profiles_batch(list(assoc.keys())) if assoc else {} + assoc_list = [] + for pid, ev in assoc.items(): + p = assoc_profiles.get(pid) + if p: + assoc_list.append({"id": pid, "username": p["Username"], "banned": bool(p.get("Banned")), "shared_ips": ev.get("shared_ips", [])}) + conn = db._get_conn() + recent_ips = [dict(r) for r in conn.execute( + "SELECT ip_address, last_seen FROM ip_logins WHERE profile_id=? ORDER BY last_seen DESC LIMIT 10", + (player_id,) + ).fetchall()] + return jsonify({"ips": recent_ips, "associated": assoc_list}) + + +@bp.route("/admin/api/discord_info/") +@require_admin_api +def api_discord_info(player_id, account, scopes): + conn = db._get_conn() + row = conn.execute("SELECT * FROM discord_links WHERE profile_id=?", (player_id,)).fetchone() + if not row: + return jsonify({"linked": False}) + return jsonify({"linked": True, "discord_user_id": row["discord_user_id"], "discord_username": row["discord_username"], "linked_at": row["linked_at"]}) + + +@bp.route("/admin/api/discord_unlink/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_discord_unlink(player_id, account, scopes): + conn = db._get_conn() + conn.execute("DELETE FROM discord_links WHERE profile_id=?", (player_id,)) + conn.commit() + name = account.get("username", "admin") + db.log_admin_action(name, "discord_unlink", f"Unlinked Discord for player {player_id}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + return jsonify({"ok": True}) + + +@bp.route("/admin/api/player_inventory/") +@require_admin_api +def api_player_inventory(player_id, account, scopes): + if not db.get_profile(player_id): + return jsonify({"error": "Not found"}), 404 + conn = db._get_conn() + favs = {r["modification_guid"] for r in conn.execute( + "SELECT modification_guid FROM equipment_favorites WHERE profile_id=?", (player_id,) + ).fetchall()} + equipment = [] + for r in conn.execute( + "SELECT equipment_prefab_name, equipment_modification_guid, created_at FROM gifts " + "WHERE profile_id=? AND equipment_modification_guid != '' AND equipment_modification_guid IS NOT NULL ORDER BY created_at DESC", + (player_id,) + ).fetchall(): + equipment.append({ + "prefab": r["equipment_prefab_name"], + "guid": r["equipment_modification_guid"], + "favorited": r["equipment_modification_guid"] in favs, + "acquired": r["created_at"], + }) + avatar_items = [dict(r) for r in conn.execute( + "SELECT avatar_item_desc, unlocked_at FROM unlocked_items WHERE profile_id=? ORDER BY unlocked_at DESC LIMIT 50", + (player_id,) + ).fetchall()] + consumables = [dict(r) for r in conn.execute( + "SELECT consumable_item_desc, quantity FROM consumable_inventory WHERE profile_id=? AND quantity > 0 ORDER BY consumable_item_desc", + (player_id,) + ).fetchall()] + return jsonify({"equipment": equipment, "avatar_items": avatar_items, "consumables": consumables}) + + +@bp.route("/admin/api/revoke_tokens/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_revoke_tokens(player_id, account, scopes): + conn = db._get_conn() + count = conn.execute("SELECT COUNT(*) AS c FROM cached_logins WHERE profile_id=?", (player_id,)).fetchone()["c"] + db.remove_cached_login(player_id) + name = account.get("username", "admin") + db.log_admin_action(name, "revoke_tokens", f"Revoked {count} cached token(s) for player {player_id}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + return jsonify({"ok": True, "revoked": count}) + + +@bp.route("/admin/api/player_chats/") +@require_admin_api +def api_player_chats(player_id, account, scopes): + if not db.get_profile(player_id): + return jsonify({"error": "Not found"}), 404 + conn = db._get_conn() + thread_ids = [r["thread_id"] for r in conn.execute( + "SELECT thread_id FROM chat_thread_players WHERE profile_id=?", (player_id,) + ).fetchall()] + if not thread_ids: + return jsonify([]) + placeholders = ",".join("?" * len(thread_ids)) + rows = conn.execute( + f"SELECT cm.id, cm.thread_id, cm.sender_id, cm.contents, cm.sent_at, p.username AS sender_username " + f"FROM chat_messages cm JOIN profiles p ON p.id=cm.sender_id " + f"WHERE cm.thread_id IN ({placeholders}) ORDER BY cm.sent_at DESC LIMIT 50", + thread_ids + ).fetchall() + return jsonify([dict(r) for r in rows]) + + +@bp.route("/admin/api/set_profile_image/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_set_profile_image(player_id, account, scopes): + from core.ws_helpers import push_profile_update + f = request.files.get("image") + if not f: + return jsonify({"ok": False, "error": "No image provided"}), 400 + image_data = f.read(2 * 1024 * 1024 + 1) + if not image_data: + return jsonify({"ok": False, "error": "Empty file"}), 400 + if len(image_data) > 2 * 1024 * 1024: + return jsonify({"ok": False, "error": "Image too large (max 2MB)"}), 413 + db.set_profile_image(player_id, image_data, str(player_id)) + db.update_profile(player_id, {"profile_image_name": str(player_id)}) + push_profile_update(player_id) + name = account.get("username", "admin") + db.log_admin_action(name, "set_profile_image", + f"Set profile image for player {player_id}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + return jsonify({"ok": True}) + + +@bp.route("/admin/api/delete_profile_image/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_delete_profile_image(player_id, account, scopes): + from core.ws_helpers import push_profile_update + db.set_profile_image(player_id, None) + db.update_profile(player_id, {"profile_image_name": ""}) + push_profile_update(player_id) + name = account.get("username", "admin") + db.log_admin_action(name, "delete_profile_image", + f"Deleted profile image for player {player_id}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + return jsonify({"ok": True}) + + +@bp.route("/admin/api/avatar_items") +@require_admin_api +def api_avatar_items(account, scopes): + path = os.path.join(os.path.dirname(__file__), "..", "data", "avataritems.json") + with open(os.path.normpath(path)) as f: + items = json.load(f) + return jsonify(items) + + +@bp.route("/admin/api/consumables") +@require_admin_api +def api_consumables(account, scopes): + path = os.path.join(os.path.dirname(__file__), "..", "data", "consumables.json") + with open(os.path.normpath(path)) as f: + items = json.load(f) + return jsonify(items) + + +@bp.route("/admin/api/equipment") +@require_admin_api +def api_equipment(account, scopes): + path = os.path.join(os.path.dirname(__file__), "..", "data", "equipment.json") + with open(os.path.normpath(path)) as f: + items = json.load(f) + return jsonify(items) + + +@bp.route("/admin/api/maintenance", methods=["GET"]) +@require_admin_api +def api_maintenance_get(account, scopes): + with maintenance_lock: + active = _state.maintenance_mode + exempt = list(_state.maintenance_exempt) + with _schedule_lock: + sat = _scheduled_maintenance_at + sdur = _scheduled_maintenance_duration_min + sexempt = list(_scheduled_maintenance_exempt) + with _reboot_when_empty_lock: + rwe = _reboot_when_empty + return jsonify({ + "maintenance": active, + "exempt_ids": exempt, + "scheduled_at": sat or None, + "scheduled_duration_min": sdur, + "scheduled_exempt_ids": sexempt, + "reboot_when_empty": rwe, + }) + + +@bp.route("/admin/api/region", methods=["GET"]) +@require_admin_api +def api_region_get(account, scopes): + return jsonify({"region": _state.server_region}) + + +@bp.route("/admin/api/region", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_region_set(account, scopes): + data = request.get_json(force=True, silent=True) or {} + region = str(data.get("region", "")).strip().lower() + if not region: + return jsonify({"error": "region required"}), 400 + _state.server_region = region + name = account.get("username", "admin") + db.log_admin_action( + name, "set_region", f"Set server region to '{region}'", + request.headers.get("X-Forwarded-For", request.remote_addr or ""), + ) + print(f"[Admin] {name} set server region to '{region}'") + return jsonify({"ok": True, "region": region}) + + +@bp.route("/admin/api/git_sync", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_git_sync(account, scopes): + import subprocess + name = account.get("username", "admin") + try: + result = subprocess.run( + ["git", "pull"], + cwd="/home/server", + capture_output=True, + text=True, + timeout=30, + ) + output = (result.stdout + result.stderr).strip() + ok = result.returncode == 0 + except subprocess.TimeoutExpired: + output = "git pull timed out after 30 seconds" + ok = False + except Exception as e: + output = str(e) + ok = False + db.log_admin_action( + name, "git_sync", f"Git sync: {'ok' if ok else 'failed'} — {output[:200]}", + request.headers.get("X-Forwarded-For", request.remote_addr or ""), + ) + print(f"[Admin] {name} git sync: {output[:200]}") + try: + from core.discord import send_admin + send_admin( + title=f"Git Sync {'Succeeded' if ok else 'Failed'}", + color=0x2ECC71 if ok else 0xE74C3C, + fields=[{"name": "By", "value": name, "inline": True}, + {"name": "Output", "value": f"```{output[:900]}```", "inline": False}], + ) + except Exception: + pass + return jsonify({"ok": ok, "output": output}) + + +@bp.route("/admin/api/reboot", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_reboot(account, scopes): + import subprocess, threading + name = account.get("username", "admin") + db.log_admin_action( + name, "reboot", "Server reboot triggered via admin panel", + request.headers.get("X-Forwarded-For", request.remote_addr or ""), + ) + print(f"[Admin] {name} triggered server reboot") + try: + from core.discord import send_admin + send_admin( + title="Server Reboot Triggered", + color=0xE67E22, + fields=[{"name": "By", "value": name, "inline": True}], + ) + except Exception: + pass + + def _do_reboot(): + import time as _time + _time.sleep(1) + subprocess.run(["systemctl", "restart", "kittyrec"], check=False) + + threading.Thread(target=_do_reboot, daemon=True).start() + return jsonify({"ok": True, "message": "Server is restarting..."}) + + +_MAINTENANCE_FILE = os.path.join(os.path.dirname(os.path.dirname(__file__)), "tracking", "settings", "maintenance.json") + +_scheduled_maintenance_at: float = 0.0 +_scheduled_maintenance_duration_min: int = 0 +_scheduled_maintenance_exempt: list = [] +_schedule_lock = __import__("threading").Lock() + +_reboot_when_empty: bool = False +_reboot_when_empty_lock = __import__("threading").Lock() + + +def _save_maintenance(enabled: bool, exempt_ids: list, + scheduled_at: float = 0.0, + scheduled_duration_min: int = 0, + scheduled_exempt: list = None, + reboot_when_empty: bool = False) -> None: + import json as _json + try: + with open(_MAINTENANCE_FILE, "w") as f: + _json.dump({ + "enabled": enabled, + "exempt_ids": list(exempt_ids), + "scheduled_at": scheduled_at, + "scheduled_duration_min": scheduled_duration_min, + "scheduled_exempt_ids": list(scheduled_exempt or []), + "reboot_when_empty": reboot_when_empty, + }, f, indent=2) + except Exception as e: + print(f"[Maintenance] Failed to save state: {e}") + + +def _load_maintenance_schedule(): + global _scheduled_maintenance_at, _scheduled_maintenance_duration_min, _scheduled_maintenance_exempt, _reboot_when_empty + try: + with open(_MAINTENANCE_FILE) as f: + d = __import__("json").load(f) + with _schedule_lock: + _scheduled_maintenance_at = float(d.get("scheduled_at", 0)) + _scheduled_maintenance_duration_min = int(d.get("scheduled_duration_min", 0)) + _scheduled_maintenance_exempt = list(d.get("scheduled_exempt_ids", [])) + with _reboot_when_empty_lock: + _reboot_when_empty = bool(d.get("reboot_when_empty", False)) + except Exception: + pass + + +def _maintenance_scheduler(): + global _scheduled_maintenance_at, _scheduled_maintenance_duration_min, _scheduled_maintenance_exempt + import threading as _threading + _load_maintenance_schedule() + while True: + __import__("time").sleep(30) + try: + with _schedule_lock: + sat = _scheduled_maintenance_at + sdur = _scheduled_maintenance_duration_min + sexempt = list(_scheduled_maintenance_exempt) + if sat and time.time() >= sat and not _state.maintenance_mode: + with maintenance_lock: + _state.maintenance_mode = True + _state.maintenance_exempt = set(int(x) for x in sexempt if str(x).isdigit()) + _save_maintenance(True, list(_state.maintenance_exempt), 0, 0, []) + with _schedule_lock: + _scheduled_maintenance_at = 0.0 + _scheduled_maintenance_duration_min = 0 + _scheduled_maintenance_exempt = [] + db.log_admin_action("scheduler", "maintenance_mode", "Scheduled maintenance started", "") + _broadcast_system_message("— Server maintenance has started. You may be disconnected shortly.") + if sdur: + import threading as _t + def _auto_disable(_dur=sdur): + __import__("time").sleep(_dur * 60) + if _state.maintenance_mode: + with maintenance_lock: + _state.maintenance_mode = False + _state.maintenance_exempt.clear() + _save_maintenance(False, []) + db.log_admin_action("scheduler", "maintenance_mode", "Scheduled maintenance ended", "") + _broadcast_system_message("— Server maintenance has ended. Welcome back!") + _t.Thread(target=_auto_disable, daemon=True).start() + try: + from core.discord import send_admin + send_admin(title="Scheduled Maintenance Started", color=0xE67E22, fields=[]) + except Exception: + pass + except Exception as e: + print(f"[MaintenanceScheduler] error: {e}") + + +__import__("threading").Thread(target=_maintenance_scheduler, daemon=True, name="maint-scheduler").start() + + +def _reboot_when_empty_watcher(): + global _reboot_when_empty + import subprocess as _sp, json as _json + while True: + __import__("time").sleep(10) + try: + try: + with open(_MAINTENANCE_FILE) as _f: + armed = bool(_json.load(_f).get("reboot_when_empty", False)) + except Exception: + armed = False + with _reboot_when_empty_lock: + _reboot_when_empty = armed + if not armed: + continue + if ws_registry.player_count() > 0: + continue + print("[RebootWatcher] No players online — rebooting now") + with _reboot_when_empty_lock: + _reboot_when_empty = False + with maintenance_lock: + _save_maintenance( + _state.maintenance_mode, + list(_state.maintenance_exempt), + _scheduled_maintenance_at, + _scheduled_maintenance_duration_min, + _scheduled_maintenance_exempt, + reboot_when_empty=False, + ) + db.log_admin_action("system", "reboot", "Deferred reboot — server empty", "") + try: + from core.discord import send_admin + send_admin(title="Deferred Reboot", color=0xE67E22, + fields=[{"name": "Trigger", "value": "Server became empty", "inline": True}]) + except Exception: + pass + __import__("time").sleep(1) + _sp.run(["systemctl", "restart", "kittyrec"], check=False) + except Exception as e: + print(f"[RebootWatcher] Error: {e}") + + +__import__("threading").Thread(target=_reboot_when_empty_watcher, daemon=True, name="reboot-watcher").start() + + +@bp.route("/admin/api/reboot_when_empty", methods=["GET"]) +@require_admin_api +def api_reboot_when_empty_get(account, scopes): + with _reboot_when_empty_lock: + armed = _reboot_when_empty + return jsonify({"reboot_when_empty": armed}) + + +@bp.route("/admin/api/reboot_when_empty", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_reboot_when_empty_set(account, scopes): + global _reboot_when_empty + data = request.get_json(force=True, silent=True) or {} + value = bool(data.get("enabled", False)) + with _reboot_when_empty_lock: + _reboot_when_empty = value + with maintenance_lock: + _save_maintenance( + _state.maintenance_mode, + list(_state.maintenance_exempt), + _scheduled_maintenance_at, + _scheduled_maintenance_duration_min, + _scheduled_maintenance_exempt, + reboot_when_empty=value, + ) + name = account.get("username", "admin") + db.log_admin_action(name, "reboot", f"Deferred reboot {'armed' if value else 'disarmed'}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[Admin] {name} {'armed' if value else 'disarmed'} deferred reboot") + return jsonify({"ok": True, "reboot_when_empty": value}) + + +@bp.route("/admin/api/maintenance", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_maintenance_set(account, scopes): + data = request.get_json(force=True, silent=True) or {} + enabled = bool(data.get("enabled", False)) + exempt_ids = data.get("exempt_ids", []) + with maintenance_lock: + _state.maintenance_mode = enabled + if enabled: + _state.maintenance_exempt = set(int(x) for x in exempt_ids if str(x).isdigit()) + else: + _state.maintenance_exempt.clear() + with _schedule_lock: + sat = _scheduled_maintenance_at + sdur = _scheduled_maintenance_duration_min + sexempt = list(_scheduled_maintenance_exempt) + _save_maintenance(enabled, list(_state.maintenance_exempt), sat, sdur, sexempt) + db.log_admin_action( + account.get("username", "admin"), + "maintenance_mode", + f"Maintenance mode {'enabled' if enabled else 'disabled'}", + request.headers.get("X-Forwarded-For", request.remote_addr or ""), + ) + print(f"[Admin] Maintenance mode {'ON' if enabled else 'OFF'} by {account.get('username')}") + try: + from core.discord import send_admin + send_admin( + title=f"Maintenance Mode {'Enabled' if enabled else 'Disabled'}", + color=0xE67E22 if enabled else 0x2ECC71, + fields=[{"name": "By", "value": account.get("username", "admin"), "inline": True}, + {"name": "Exempt IDs", "value": str(list(_state.maintenance_exempt)) or "none", "inline": True}], + ) + except Exception: + pass + return jsonify({"ok": True, "maintenance": enabled}) + + +@bp.route("/admin/api/maintenance/schedule", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_maintenance_schedule(account, scopes): + global _scheduled_maintenance_at, _scheduled_maintenance_duration_min, _scheduled_maintenance_exempt + data = request.get_json(force=True, silent=True) or {} + action = data.get("action", "set") + if action == "clear": + with _schedule_lock: + _scheduled_maintenance_at = 0.0 + _scheduled_maintenance_duration_min = 0 + _scheduled_maintenance_exempt = [] + with maintenance_lock: + _save_maintenance(_state.maintenance_mode, list(_state.maintenance_exempt), 0, 0, []) + db.log_admin_action(account.get("username", "admin"), "maintenance_schedule", "Cleared scheduled maintenance", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + return jsonify({"ok": True, "scheduled_at": None}) + scheduled_at_iso = data.get("scheduled_at", "") + duration_min = int(data.get("duration_min", 0)) + exempt_ids = [int(x) for x in data.get("exempt_ids", []) if str(x).isdigit() or (isinstance(x, int))] + if not scheduled_at_iso: + return jsonify({"error": "scheduled_at required"}), 400 + try: + import datetime as _dt + dt = _dt.datetime.fromisoformat(scheduled_at_iso.replace("Z", "+00:00")) + sat = dt.timestamp() + except Exception: + return jsonify({"error": "invalid scheduled_at format, use ISO 8601"}), 400 + if sat <= time.time(): + return jsonify({"error": "scheduled_at must be in the future"}), 400 + with _schedule_lock: + _scheduled_maintenance_at = sat + _scheduled_maintenance_duration_min = duration_min + _scheduled_maintenance_exempt = exempt_ids + with maintenance_lock: + _save_maintenance(_state.maintenance_mode, list(_state.maintenance_exempt), sat, duration_min, exempt_ids) + db.log_admin_action(account.get("username", "admin"), "maintenance_schedule", + f"Scheduled maintenance at {scheduled_at_iso} for {duration_min}min", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + return jsonify({"ok": True, "scheduled_at": sat}) + + +@bp.route("/admin/api/rooms/create", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_create_room(account, scopes): + data = request.get_json(force=True, silent=True) or {} + level_id = str(data.get("level_id", "")).strip() + name = str(data.get("name", "")).strip() + owner_pid = data.get("owner_pid") + if not level_id or not name: + return jsonify({"error": "level_id and name are required"}), 400 + try: + owner_pid = int(owner_pid) if owner_pid else 1 + except (ValueError, TypeError): + return jsonify({"error": "owner_pid must be an integer"}), 400 + room = db.create_room(creator_id=owner_pid, name=name, activity_level_id=level_id) + admin_name = account.get("username", "admin") + db.log_admin_action(admin_name, "create_room", f"Created room '{name}' (level_id={level_id}, owner={owner_pid})", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[Admin] {admin_name} created room '{name}' level_id={level_id} owner={owner_pid}") + return jsonify({"ok": True, "room_id": room["RoomId"]}) + + +@bp.route("/admin/api/rooms/", methods=["GET"]) +@require_admin_api +def api_get_room(room_id, account, scopes): + room = db.get_room(room_id) + if not room: + return jsonify({"error": "Room not found"}), 404 + return jsonify(room) + + +@bp.route("/admin/api/rooms/", methods=["PUT"]) +@require_scope(SCOPE_ADMIN) +def api_update_room(room_id, account, scopes): + data = request.get_json(force=True, silent=True) or {} + room = db.get_room(room_id) + if not room: + return jsonify({"error": "Room not found"}), 404 + updates = {} + for key in ("name", "description", "activity_level_id", "max_players", + "is_sandbox", "instanced", "accessibility", "state", + "special_gamemode", "creator_id", + "unity_asset_bundle_url", "unity_scene_name"): + if key in data: + val = data[key] + if key in ("max_players", "accessibility", "state", "special_gamemode", "creator_id"): + val = int(val) + elif key in ("is_sandbox", "instanced"): + val = 1 if val else 0 + updates[key] = val + if not updates: + return jsonify({"error": "No fields to update"}), 400 + room = db.update_room(room_id, **updates) + admin_name = account.get("username", "admin") + changed = ", ".join(f"{k}={v}" for k, v in updates.items()) + db.log_admin_action(admin_name, "edit_room", + f"Edited room {room_id} ({room['Name']}): {changed}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[Admin] {admin_name} edited room {room_id}: {changed}") + return jsonify({"ok": True, "room": room}) + + +@bp.route("/admin/api/rooms/", methods=["DELETE"]) +@require_scope(SCOPE_ADMIN) +def api_delete_room(room_id, account, scopes): + room = db.get_room(room_id) + if not room: + return jsonify({"error": "Room not found"}), 404 + db.delete_room(room_id) + admin_name = account.get("username", "admin") + db.log_admin_action(admin_name, "delete_room", + f"Deleted room '{room['Name']}' (id={room_id})", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[Admin] {admin_name} deleted room {room_id} ({room['Name']})") + return jsonify({"ok": True}) + + +@bp.route("/admin/api/rooms//image", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_upload_room_image(room_id, account, scopes): + import uuid, io + from PIL import Image + room = db.get_room(room_id) + if not room: + return jsonify({"error": "Room not found"}), 404 + f = request.files.get("image") + if not f: + return jsonify({"error": "No image file provided"}), 400 + image_data = f.read(2 * 1024 * 1024 + 1) + if len(image_data) > 2 * 1024 * 1024: + return jsonify({"error": "Image too large (max 2MB)"}), 400 + TARGET_W, TARGET_H = 1280, 720 + try: + img = Image.open(io.BytesIO(image_data)) + img = img.convert("RGB") + src_w, src_h = img.size + src_ratio = src_w / src_h + target_ratio = TARGET_W / TARGET_H + if src_ratio > target_ratio: + new_h = src_h + new_w = int(src_h * target_ratio) + left = (src_w - new_w) // 2 + img = img.crop((left, 0, left + new_w, new_h)) + elif src_ratio < target_ratio: + new_w = src_w + new_h = int(src_w / target_ratio) + top = (src_h - new_h) // 2 + img = img.crop((0, top, new_w, top + new_h)) + img = img.resize((TARGET_W, TARGET_H), Image.LANCZOS) + buf = io.BytesIO() + img.save(buf, format="JPEG", quality=85) + image_data = buf.getvalue() + except Exception: + pass + image_name = f"room_{room_id}_{uuid.uuid4().hex[:8]}" + db.save_named_image(image_name, 0, image_data, room_name=room["Name"]) + db.update_room_field(room_id, "image_name", image_name) + admin_name = account.get("username", "admin") + db.log_admin_action(admin_name, "upload_room_image", + f"Uploaded image for room '{room['Name']}' (id={room_id}, image={image_name})", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[Admin] {admin_name} uploaded image for room {room_id}: {image_name}") + return jsonify({"ok": True, "image_name": image_name}) + + +@bp.route("/admin/api/rooms//permissions", methods=["GET"]) +@require_admin_api +def api_room_permissions_get(room_id, account, scopes): + room = db.get_room(room_id) + if not room: + return jsonify({"error": "Room not found"}), 404 + perms = db.get_room_permissions(room_id) + result = [] + for p in perms: + profile = db.get_profile(p["player_id"]) + result.append({ + "player_id": p["player_id"], + "username": profile["username"] if profile else f"#{p['player_id']}", + "is_host": bool(p["is_host"]), + "is_owner": bool(p["is_owner"]), + }) + return jsonify({"ok": True, "permissions": result, "creator_id": room.get("CreatorId") or room.get("creator_id")}) + + +@bp.route("/admin/api/rooms//permissions", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_room_permissions_set(room_id, account, scopes): + room = db.get_room(room_id) + if not room: + return jsonify({"error": "Room not found"}), 404 + data = request.get_json(force=True, silent=True) or {} + player_id = data.get("player_id") + if not player_id: + return jsonify({"error": "player_id required"}), 400 + try: + player_id = int(player_id) + except (ValueError, TypeError): + return jsonify({"error": "player_id must be integer"}), 400 + is_host = bool(data.get("is_host", False)) + is_owner = bool(data.get("is_owner", False)) + db.set_room_permission(room_id, player_id, is_host, is_owner) + db.log_admin_action(account.get("username", "admin"), "room_permission", + f"Set room {room_id} perms for player {player_id}: host={is_host} owner={is_owner}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + return jsonify({"ok": True}) + + +@bp.route("/admin/api/rooms//permissions/", methods=["DELETE"]) +@require_scope(SCOPE_ADMIN) +def api_room_permissions_del(room_id, player_id, account, scopes): + room = db.get_room(room_id) + if not room: + return jsonify({"error": "Room not found"}), 404 + db.set_room_permission(room_id, player_id, False, False) + db.log_admin_action(account.get("username", "admin"), "room_permission", + f"Removed room {room_id} perms for player {player_id}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + return jsonify({"ok": True}) + + +@bp.route("/admin/api/rooms//disabled", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_set_room_disabled(room_id, account, scopes): + data = request.get_json(force=True, silent=True) or {} + disabled = bool(data.get("disabled", False)) + room = db.get_room(room_id) + if not room: + return jsonify({"error": "Room not found"}), 404 + db.set_room_disabled(room_id, disabled) + admin_name = account.get("username", "admin") + action = "disabled" if disabled else "enabled" + db.log_admin_action(admin_name, "toggle_room_disabled", + f"{action.title()} joins for room {room_id} ({room['Name']})", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[Admin] {admin_name} {action} joins for room {room_id}") + return jsonify({"ok": True, "disabled": disabled}) + + +@bp.route("/admin/api/player_social/") +@require_admin_api +def api_player_social(pid, account, scopes): + from core.constants import REL_FRIEND, REL_SENT, REL_RECEIVED + rels = db.get_relationships(pid) + friends, sent, received, muted, ignored = [], [], [], [], [] + for r in rels: + target_id = r["PlayerID"] + profile = db.get_profile(target_id) + entry = { + "id": target_id, + "username": profile["Username"] if profile else f"#{target_id}", + "banned": bool(profile["Banned"]) if profile else False, + } + rt = r.get("RelationshipType", 0) + if rt == REL_FRIEND: + friends.append(entry) + elif rt == REL_SENT: + sent.append(entry) + elif rt == REL_RECEIVED: + received.append(entry) + if r.get("Muted"): + muted.append(entry) + if r.get("Ignored"): + ignored.append(entry) + subs = db.get_subscriptions(pid) + subscribers = [{"id": s["PlayerId"], "username": s["Username"]} for s in subs] + sub_count = db.get_subscriber_count(pid) + return jsonify({ + "friends": friends, + "pending_sent": sent, + "pending_received": received, + "muted": muted, + "ignored": ignored, + "subscribers": subscribers, + "subscriber_count": sub_count, + }) + + +@bp.route("/admin/api/player_gift_caps/") +@require_admin_api +def api_player_gift_caps(pid, account, scopes): + import datetime as _dt + today = _dt.datetime.utcnow().strftime("%Y-%m-%d") + today_count = db.get_daily_gift_count(pid, today) + conn = db._get_conn() + rows = conn.execute( + "SELECT date_str, COUNT(*) as cnt FROM daily_gifts WHERE profile_id=? GROUP BY date_str ORDER BY date_str DESC LIMIT 14", + (pid,) + ).fetchall() + history = [{"date": r["date_str"], "count": r["cnt"]} for r in rows] + session_count = db.get_session_gift_count(pid, "") + return jsonify({"today": today_count, "today_date": today, "history": history}) + + +@bp.route("/admin/api/player_gift_caps//reset", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_player_gift_caps_reset(pid, account, scopes): + import datetime as _dt + data = request.get_json(force=True, silent=True) or {} + date_str = data.get("date") or _dt.datetime.utcnow().strftime("%Y-%m-%d") + conn = db._get_conn() + conn.execute("DELETE FROM daily_gifts WHERE profile_id=? AND date_str=?", (pid, date_str)) + conn.commit() + db.reset_session_gift_counts(pid) + db.log_admin_action(account.get("username", "admin"), "reset_gift_cap", + f"Reset gift cap for player {pid} on {date_str}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + return jsonify({"ok": True, "date": date_str}) + + +@bp.route("/admin/api/cdn/files", methods=["GET"]) +@require_admin_api +def api_cdn_list(account, scopes): + conn = db._get_conn() + rows = conn.execute( + "SELECT name, length(image_data) as size, created_at, room_name FROM saved_images WHERE profile_id = -1 ORDER BY created_at DESC" + ).fetchall() + files = [] + for r in rows: + files.append({ + "name": r["name"], + "size": r["size"], + "created_at": r["created_at"], + "label": r["room_name"] if "room_name" in r.keys() else "", + }) + return jsonify(files) + + +@bp.route("/admin/api/cdn/upload", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_cdn_upload(account, scopes): + import uuid + f = request.files.get("file") + if not f: + return jsonify({"error": "No file provided"}), 400 + file_data = f.read(10 * 1024 * 1024 + 1) + if len(file_data) > 10 * 1024 * 1024: + return jsonify({"error": "File too large (max 10MB)"}), 400 + custom_name = request.form.get("name", "").strip() + if custom_name: + import re + custom_name = re.sub(r'[^a-zA-Z0-9_\-.]', '_', custom_name) + else: + ext = "" + if f.filename and "." in f.filename: + ext = "." + f.filename.rsplit(".", 1)[1].lower() + custom_name = f"cdn_{uuid.uuid4().hex[:12]}{ext}" + label = request.form.get("label", "").strip() or f.filename or "" + db.save_named_image(custom_name, -1, file_data, room_name=label) + base = f"{_base_url}/{custom_name}" + admin_name = account.get("username", "admin") + db.log_admin_action(admin_name, "cdn_upload", + f"Uploaded CDN file '{custom_name}' ({len(file_data)} bytes)", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[CDN] {admin_name} uploaded: {custom_name} ({len(file_data)} bytes)") + return jsonify({"ok": True, "name": custom_name, "url": base}) + + +@bp.route("/admin/api/cdn/delete", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_cdn_delete(account, scopes): + data = request.get_json(force=True, silent=True) or {} + name = data.get("name", "") + if not name: + return jsonify({"error": "No name provided"}), 400 + conn = db._get_conn() + conn.execute("DELETE FROM saved_images WHERE name = ? AND profile_id = -1", (name,)) + conn.commit() + admin_name = account.get("username", "admin") + db.log_admin_action(admin_name, "cdn_delete", + f"Deleted CDN file '{name}'", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + return jsonify({"ok": True}) + + +_DLL_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "kittyrec_dlls") +_DLL_JSON = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "KittyRecDlls.json") +_BRANCH_NAMES = { + "bff0c094-2d59-4f81-93dd-fc6f177ca584": "Prod", + "fb4ce906-59c1-4ffd-af5e-6696dfad1be2": "Dev", + "f94fa96b-7438-4323-825f-ff4dc4055db1": "BVT", +} + + +def _read_dll_json(): + try: + with open(_DLL_JSON) as f: + return json.load(f) + except Exception: + return {} + + +def _write_dll_json(data): + with open(_DLL_JSON, "w") as f: + json.dump(data, f, indent=4) + + +@bp.route("/admin/api/dll_archive", methods=["GET"]) +@require_admin_api +def api_dll_archive_list(account, scopes): + entries = db.dll_archive_list() + dll_data = _read_dll_json() + active = {v["file"]: _BRANCH_NAMES.get(k, k) for k, v in dll_data.items() if isinstance(v, dict) and "file" in v} + for e in entries: + e["branch"] = active.get(e["filename"], "") + return jsonify(entries) + + +@bp.route("/admin/api/dll_archive/upload", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_dll_archive_upload(account, scopes): + import uuid, hashlib + f = request.files.get("file") + if not f: + return jsonify({"error": "No file provided"}), 400 + if not (f.filename or "").endswith(".dll"): + return jsonify({"error": "Must be a .dll file"}), 400 + data = f.read() + sha = hashlib.sha512(data).hexdigest() + filename = f"{uuid.uuid4()}.dll" + fpath = os.path.join(_DLL_DIR, filename) + os.makedirs(_DLL_DIR, exist_ok=True) + with open(fpath, "wb") as fh: + fh.write(data) + label = request.form.get("label", "").strip() + admin_name = account.get("username", "admin") + db.dll_archive_add(filename, sha, label, len(data), admin_name) + db.log_admin_action(admin_name, "dll_upload", f"Uploaded DLL '{filename}' ({len(data)} bytes)", request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[DLL] {admin_name} uploaded: {filename} ({len(data)} bytes)") + return jsonify({"ok": True, "filename": filename, "sha512": sha}) + + +@bp.route("/admin/api/dll_archive/assign", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_dll_archive_assign(account, scopes): + data = request.get_json(force=True, silent=True) or {} + filename = data.get("filename", "") + branch_id = data.get("branch_id", "") + if not filename or branch_id not in _BRANCH_NAMES: + return jsonify({"error": "Invalid filename or branch_id"}), 400 + sha = "" + for e in db.dll_archive_list(): + if e["filename"] == filename: + sha = e["sha512"] + break + if not sha: + return jsonify({"error": "DLL not found in archive"}), 404 + dll_data = _read_dll_json() + dll_data[branch_id] = {"file": filename, "hash": sha} + _write_dll_json(dll_data) + admin_name = account.get("username", "admin") + db.log_admin_action(admin_name, "dll_assign", f"Assigned '{filename}' to branch {_BRANCH_NAMES[branch_id]}", request.headers.get("X-Forwarded-For", request.remote_addr or "")) + return jsonify({"ok": True}) + + +@bp.route("/admin/api/dll_archive/update_label", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_dll_archive_update_label(account, scopes): + data = request.get_json(force=True, silent=True) or {} + filename = data.get("filename", "") + label = str(data.get("label", ""))[:200] + if not filename: + return jsonify({"error": "Missing filename"}), 400 + db.dll_archive_update(filename, label) + return jsonify({"ok": True}) + + +@bp.route("/admin/api/gamemode_defaults", methods=["GET"]) +@require_admin_api +def api_get_gamemode_defaults(account, scopes): + return jsonify(db.get_all_gamemode_defaults()) + + +@bp.route("/admin/api/gamemode_defaults", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_set_gamemode_default(account, scopes): + data = request.get_json(force=True, silent=True) or {} + activity_level_id = str(data.get("activity_level_id", "")).strip() + special_gamemode = int(data.get("special_gamemode", 0)) + if not activity_level_id: + return jsonify({"error": "activity_level_id required"}), 400 + db.set_gamemode_default(activity_level_id, special_gamemode) + admin_name = account.get("username", "admin") + db.log_admin_action(admin_name, "set_gamemode_default", + f"Set gamemode default for {activity_level_id}: {special_gamemode}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[Admin] {admin_name} set gamemode default {activity_level_id}={special_gamemode}") + return jsonify({"ok": True}) + + +@bp.route("/admin/api/disabled_activities", methods=["GET"]) +@require_admin_api +def api_get_disabled_activities(account, scopes): + return jsonify(db.get_all_disabled_activities()) + + +@bp.route("/admin/api/disabled_activities", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_set_disabled_activity(account, scopes): + data = request.get_json(force=True, silent=True) or {} + activity_level_id = str(data.get("activity_level_id", "")).strip() + disabled = bool(data.get("disabled", False)) + if not activity_level_id: + return jsonify({"error": "activity_level_id required"}), 400 + db.set_activity_disabled(activity_level_id, disabled) + admin_name = account.get("username", "admin") + action = "disabled" if disabled else "enabled" + db.log_admin_action(admin_name, "toggle_activity", + f"{action.title()} activity {activity_level_id}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + print(f"[Admin] {admin_name} {action} activity {activity_level_id}") + return jsonify({"ok": True, "disabled": disabled}) + + +@bp.route("/admin/api/events", methods=["GET"]) +@require_admin_api +def api_list_events(account, scopes): + return jsonify(db.get_all_events()) + +@bp.route("/admin/api/events", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_create_event(account, scopes): + data = request.get_json(force=True, silent=True) or {} + name = data.get("name", "").strip() + if not name: + return jsonify({"ok": False, "error": "Name required"}), 400 + eid = db.create_event( + name=name, + description=data.get("description", ""), + start_time=data.get("start_time", ""), + end_time=data.get("end_time", ""), + poster_image=data.get("poster_image", ""), + creator_player_id=int(data.get("creator_player_id", 1)), + activity_level_id=data.get("activity_level_id", ""), + ) + print(f"[Admin] Event created: {name} (id={eid}) by {account.get('username')}") + return jsonify({"ok": True, "id": eid}) + +@bp.route("/admin/api/events/", methods=["PUT"]) +@require_scope(SCOPE_ADMIN) +def api_update_event(account, scopes, eid): + data = request.get_json(force=True, silent=True) or {} + db.update_event(eid, **data) + return jsonify({"ok": True}) + +@bp.route("/admin/api/events/", methods=["DELETE"]) +@require_scope(SCOPE_ADMIN) +def api_delete_event(account, scopes, eid): + db.delete_event(eid) + print(f"[Admin] Event {eid} deleted by {account.get('username')}") + return jsonify({"ok": True}) + + +_CLIENT_LOG_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "uploads", "clientlogs") + + +@bp.route("/admin/api/clientlogs", methods=["GET"]) +@require_admin_api +def api_list_clientlogs(account, scopes): + try: + files = sorted(os.listdir(_CLIENT_LOG_DIR), reverse=True) + except FileNotFoundError: + files = [] + result = [] + for name in files: + path = os.path.join(_CLIENT_LOG_DIR, name) + try: + size = os.path.getsize(path) + except OSError: + size = 0 + result.append({"name": name, "size": size}) + return jsonify(result) + + +@bp.route("/admin/api/clientlogs/", methods=["GET"]) +@require_admin_api +def api_download_clientlog(filename, account, scopes): + safe = os.path.basename(filename) + path = os.path.join(_CLIENT_LOG_DIR, safe) + if not os.path.isfile(path): + return Response("Not Found", 404) + with open(path, "rb") as f: + data = f.read() + return Response(data, 200, { + "Content-Type": "text/plain; charset=utf-8", + "Content-Disposition": f"attachment; filename={safe}", + }) + + + + +@bp.route("/admin/api/create_mural", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_create_mural(account, scopes): + import os, math, io, time + from PIL import Image as _Image + _HD_DIR = os.path.join(os.path.dirname(__file__), "..", "uploads", "images", "hd") + _HD_DIR = os.path.abspath(_HD_DIR) + files = [f for f in os.listdir(_HD_DIR) if os.path.isfile(os.path.join(_HD_DIR, f))] + if not files: + return jsonify({"ok": False, "error": "No HD images found"}), 404 + imgs = [] + for fname in files: + try: + img = _Image.open(os.path.join(_HD_DIR, fname)).convert("RGB") + imgs.append(img) + except Exception: + pass + if not imgs: + return jsonify({"ok": False, "error": "Could not open any images"}), 500 + W, H = 3840, 2160 + n = len(imgs) + avg_ar = sum(img.width / img.height for img in imgs) / n + n_rows = max(1, round(math.sqrt(n * avg_ar * H / W))) + n_rows = min(n_rows, n) + per_row = [n // n_rows] * n_rows + for i in range(n % n_rows): + per_row[i] += 1 + groups, raw_heights = [], [] + idx = 0 + for cnt in per_row: + group = imgs[idx:idx + cnt] + idx += cnt + total_ar = sum(img.width / img.height for img in group) + groups.append((group, total_ar)) + raw_heights.append(W / total_ar) + h_scale = H / sum(raw_heights) + mural = _Image.new("RGB", (W, H)) + y = 0 + for (group, total_ar), rh in zip(groups, raw_heights): + row_h = round(rh * h_scale) + x = 0 + for j, img in enumerate(group): + ar = img.width / img.height + tile_w = W - x if j == len(group) - 1 else round(ar / total_ar * W) + tile_w = max(1, tile_w) + resized = img.resize((tile_w, row_h), _Image.LANCZOS) + mural.paste(resized, (x, y)) + x += tile_w + y += row_h + out_name = f"mural_{int(time.time())}.jpg" + out_path = os.path.join(os.path.dirname(__file__), "..", "uploads", "mural", out_name) + os.makedirs(os.path.dirname(out_path), exist_ok=True) + mural.save(out_path, "JPEG", quality=88) + name = account.get("username", "admin") + db.log_admin_action(name, "create_mural", f"Created mural with {len(imgs)} photos → {out_name}", + request.headers.get("X-Forwarded-For", request.remote_addr or "")) + return jsonify({"ok": True, "filename": out_name, "count": len(imgs), "rows": n_rows}) + + +@bp.route("/admin/mural/") +@require_admin_api +def list_murals(account, scopes): + import os + mural_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "uploads", "mural")) + os.makedirs(mural_dir, exist_ok=True) + files = sorted( + [f for f in os.listdir(mural_dir) if os.path.isfile(os.path.join(mural_dir, f))], + reverse=True, + ) + items = [] + for f in files: + stat = os.stat(os.path.join(mural_dir, f)) + items.append({ + "filename": f, + "url": f"/admin/mural/{f}", + "size_kb": round(stat.st_size / 1024), + "created": int(stat.st_mtime), + }) + return jsonify({"murals": items, "count": len(items)}) + + +@bp.route("/admin/mural/") +@require_admin_api +def serve_mural(filename, account, scopes): + import os + from flask import send_from_directory + mural_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "uploads", "mural")) + return send_from_directory(mural_dir, filename) + + +def _require_admin_ui(): + from core.admin_auth import get_admin_account, has_any_admin_scope, make_login_redirect + account, scopes = get_admin_account() + if not account or not has_any_admin_scope(scopes): + return None, None, redirect(make_login_redirect()) + return account, scopes, None + + +@bp.route("/admin/players") +def admin_players_page(): + account, scopes, redir = _require_admin_ui() + if redir: + return redir + profiles = db.get_all_profiles_summary() + online_ids = set(ws_registry.connected_ids()) + return render_template( + "admin/players.html", + profiles=profiles, online_ids=online_ids, + account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, + ) + + +@bp.route("/admin/players/") +def admin_player_detail_page(pid): + account, scopes, redir = _require_admin_ui() + if redir: + return redir + profile = db.get_profile(pid) + if not profile: + return "Player not found", 404 + ban_log = db.get_ban_log(profile_id=pid, limit=30) + conn = db._get_conn() + gifts = [dict(r) for r in conn.execute( + "SELECT * FROM gifts WHERE profile_id=? ORDER BY id DESC LIMIT 30", (pid,) + ).fetchall()] + is_online = pid in ws_registry.connected_ids() + cur_session = session_mgr.get_player_session(pid) if is_online else None + return render_template( + "admin/player_detail.html", + profile=profile, ban_log=ban_log, gifts=gifts, + is_online=is_online, cur_session=cur_session, + account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, + ) + + +@bp.route("/admin/bans") +def admin_bans_page(): + account, scopes, redir = _require_admin_ui() + if redir: + return redir + conn = db._get_conn() + banned = [dict(r) for r in conn.execute( + "SELECT * FROM profiles WHERE banned=1 ORDER BY id DESC" + ).fetchall()] + ban_log = db.get_ban_log(limit=100) + return render_template( + "admin/bans.html", + banned=banned, ban_log=ban_log, + account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, + ) + + +@bp.route("/admin/sessions") +def admin_sessions_page(): + account, scopes, redir = _require_admin_ui() + if redir: + return redir + active = session_mgr.all_public_sessions() + all_pids = [pid for s in active for pid in s.players] + profiles_map = db.get_profiles_batch(all_pids) + session_details = [] + for s in active: + players = [profiles_map[pid] for pid in s.players if pid in profiles_map] + session_details.append({"session": s, "players": players}) + return render_template( + "admin/sessions.html", + session_details=session_details, + online_count=len(ws_registry.connected_ids()), + account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, + ) + + +@bp.route("/admin/gifts") +def admin_gifts_page(): + account, scopes, redir = _require_admin_ui() + if redir: + return redir + conn = db._get_conn() + gifts = [dict(r) for r in conn.execute( + "SELECT g.*, p.username FROM gifts g LEFT JOIN profiles p ON p.id = g.profile_id ORDER BY g.id DESC LIMIT 500" + ).fetchall()] + pending = sum(1 for g in gifts if not g.get("consumed")) + return render_template( + "admin/gifts.html", + gifts=gifts, pending=pending, total=len(gifts), + account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, + ) + + +@bp.route("/admin/chat") +def admin_chat_page(): + account, scopes, redir = _require_admin_ui() + if redir: + return redir + threads = db.get_all_chat_threads(limit=200) + return render_template( + "admin/chat.html", + threads=threads, + account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, + ) + + +@bp.route("/admin/leaderboard") +def admin_leaderboard_page(): + account, scopes, redir = _require_admin_ui() + if redir: + return redir + entries = db.get_leaderboard_with_usernames(objective_type=1, limit=100) + return render_template( + "admin/leaderboard.html", + entries=entries, + account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, + ) + + +@bp.route("/admin/api/chat_threads") +@require_admin_api +def api_chat_threads(account, scopes): + threads = db.get_all_chat_threads(limit=200) + return jsonify(threads) + + +@bp.route("/admin/api/chat_thread/") +@require_admin_api +def api_chat_thread_messages(account, scopes, tid): + messages = db.get_chat_messages_admin(tid, limit=100) + players = db.get_chat_thread_players(tid) + return jsonify({"messages": messages, "player_ids": players}) + + +@bp.route("/admin/api/chat_message/", methods=["DELETE"]) +@require_scope(SCOPE_ADMIN) +def api_delete_chat_message(account, scopes, mid): + db.delete_chat_message(mid) + db.log_admin_action( + account.get("username", "admin"), "delete_chat_message", + f"Deleted chat message #{mid}", + request.headers.get("X-Forwarded-For", request.remote_addr or ""), + ) + return jsonify({"ok": True}) + + +@bp.route("/admin/api/sanitize_log") +@require_admin_api +def api_sanitize_log(account, scopes): + from routes.misc import get_sanitize_log + entries = get_sanitize_log() + pids = list({e["pid"] for e in entries if e.get("pid")}) + profiles = db.get_profiles_batch(pids) if pids else {} + for e in entries: + pid = e.get("pid") + p = profiles.get(pid) + e["username"] = p.get("Username", f"#{pid}") if p else (f"#{pid}" if pid else "?") + return jsonify(entries) + + +@bp.route("/admin/api/player_settings/", methods=["GET"]) +@require_admin_api +def api_player_settings_get(account, scopes, pid): + settings = db.get_settings(pid) + return jsonify(settings) + + +@bp.route("/admin/api/player_settings/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_player_settings_set(account, scopes, pid): + data = request.get_json(force=True, silent=True) or {} + action = data.get("action", "set") + key = str(data.get("key", "")).strip() + if not key: + return jsonify({"error": "key required"}), 400 + if action == "delete": + db.remove_setting(pid, key) + db.log_admin_action( + account.get("username", "admin"), "delete_setting", + f"Deleted setting {key!r} for player #{pid}", + request.headers.get("X-Forwarded-For", request.remote_addr or ""), + ) + else: + value = str(data.get("value", "")) + db.set_setting(pid, key, value) + if key == "Recroom.OOBE": + db.update_profile(pid, {"registration_status": 2}) + db.log_admin_action( + account.get("username", "admin"), "set_setting", + f"Set {key!r}={value!r} for player #{pid}", + request.headers.get("X-Forwarded-For", request.remote_addr or ""), + ) + return jsonify({"ok": True}) + + +@bp.route("/admin/api/force_oobe/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_force_oobe(account, scopes, pid): + db.set_setting(pid, "Recroom.OOBE", "100") + db.update_profile(pid, {"registration_status": 2}) + db.log_admin_action( + account.get("username", "admin"), "force_oobe", + f"Forced OOBE completion for player #{pid}", + request.headers.get("X-Forwarded-For", request.remote_addr or ""), + ) + return jsonify({"ok": True}) + + +@bp.route("/admin/api/force_screen_mode/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_force_screen_mode(account, scopes, pid): + data = request.get_json(force=True, silent=True) or {} + enabled = bool(data.get("enabled", True)) + db.set_setting(pid, "screen_mode_user", "1" if enabled else "0") + db.log_admin_action( + account.get("username", "admin"), "force_screen_mode", + f"Set screen_mode_user={'1' if enabled else '0'} for player #{pid}", + request.headers.get("X-Forwarded-For", request.remote_addr or ""), + ) + return jsonify({"ok": True, "screen_mode": enabled}) + + +@bp.route("/admin/api/bulk_action", methods=["POST"]) +@require_admin_api +def api_bulk_action(account, scopes, **kwargs): + data = request.get_json(force=True, silent=True) or {} + action = data.get("action", "") + pids = [int(x) for x in data.get("pids", []) if str(x).isdigit()] + if not pids or not action: + return jsonify({"error": "action and pids required"}), 400 + if action in ("ban", "unban", "gift") and SCOPE_ADMIN not in scopes: + return jsonify({"error": "Admin scope required"}), 403 + name = account.get("username", "admin") + ip = request.headers.get("X-Forwarded-For", request.remote_addr or "") + results = {"ok": 0, "fail": 0} + if action == "disconnect": + for pid in pids: + try: + ws_registry.disconnect(pid) + results["ok"] += 1 + except Exception: + results["fail"] += 1 + db.log_admin_action(name, "bulk_disconnect", f"Disconnected {results['ok']} players", ip) + elif action == "ban": + reason = str(data.get("reason", "Bulk ban"))[:256] + duration_h = int(data.get("duration_hours", 24)) + for pid in pids: + try: + db.ban_player(pid, reason, name, duration_h if duration_h > 0 else None) + results["ok"] += 1 + except Exception: + results["fail"] += 1 + db.log_admin_action(name, "bulk_ban", f"Banned {results['ok']} players: {reason}", ip) + elif action == "unban": + for pid in pids: + try: + db.unban_player(pid, name) + results["ok"] += 1 + except Exception: + results["fail"] += 1 + db.log_admin_action(name, "bulk_unban", f"Unbanned {results['ok']} players", ip) + elif action == "gift": + from core.ws_helpers import push_gift + xp = max(0, min(int(data.get("xp", 1000)), 99999)) + rarity = int(data.get("rarity", 0)) + message = str(data.get("message", ""))[:80] + for pid in pids: + try: + gift = db.add_gift(pid, xp=xp, gift_rarity=rarity, message=message, gift_context=5) + push_gift(pid, gift) + results["ok"] += 1 + except Exception: + results["fail"] += 1 + db.log_admin_action(name, "bulk_gift", f"Gifted {results['ok']} players ({xp} XP)", ip) + else: + return jsonify({"error": "unknown action"}), 400 + return jsonify({"ok": True, "results": results}) + + +@bp.route("/admin/api/leaderboard_data") +@require_admin_api +def api_leaderboard_data(account, scopes): + obj = int(request.args.get("objective", 1)) + entries = db.get_leaderboard_with_usernames(objective_type=obj, limit=100) + return jsonify(entries) + + +@bp.route("/admin/api/reset_leaderboard", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_reset_leaderboard(account, scopes): + data = request.get_json(force=True, silent=True) or {} + obj = data.get("objective") + db.reset_leaderboard_periodic(objective_type=obj) + name = account.get("username", "admin") + label = f"objective={obj}" if obj is not None else "all objectives" + db.log_admin_action( + name, "reset_leaderboard", f"Reset periodic leaderboard scores ({label})", + request.headers.get("X-Forwarded-For", request.remote_addr or ""), + ) + return jsonify({"ok": True}) + + +_BOT_ANALYTICS_PATH = "/home/kittyrecbots/KittyNet-DiscordBot/analytics.json" + + +@bp.route("/admin/live/discord") +def admin_discord_page(): + account, scopes, redir = _require_admin_ui() + if redir: + return redir + return render_template("admin/discord_view.html", account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN) + + +@bp.route("/admin/api/discord_analytics") +@require_admin_api +def api_discord_analytics(account, scopes): + import json as _json + from datetime import datetime, timezone, timedelta + from collections import defaultdict as _dd + + try: + with open(_BOT_ANALYTICS_PATH) as _f: + data = _json.load(_f) + except Exception as exc: + return jsonify({"error": str(exc)}), 500 + + now = datetime.now(timezone.utc) + snapshots = data.get("snapshots", []) + latest = snapshots[-1] if snapshots else {} + members = latest.get("member_count", 0) + + week_ago = now - timedelta(days=7) + recent = [s for s in snapshots if datetime.fromisoformat(s["timestamp"]) >= week_ago] + growth_7d = (recent[-1].get("member_count", 0) - recent[0].get("member_count", 0)) if len(recent) >= 2 else 0 + + hourly = data.get("hourly_messages", {}) + total_messages = sum(h.get("total", 0) for h in hourly.values()) + discord_links = data.get("discord_links", {}) + voice_sessions = data.get("voice_sessions", []) + active_voice = data.get("active_voice", {}) + + summary = { + "members": members, + "growth_7d": growth_7d, + "total_messages": total_messages, + "linked_accounts": len(discord_links), + "voice_sessions": len(voice_sessions), + "active_voice": len(active_voice), + } + + step = max(1, len(snapshots) // 150) + growth = [{"t": s["timestamp"], "c": s["member_count"]} for s in snapshots[::step]] + if snapshots and (not growth or growth[-1]["t"] != snapshots[-1]["timestamp"]): + growth.append({"t": snapshots[-1]["timestamp"], "c": snapshots[-1]["member_count"]}) + + cutoff_48h = now - timedelta(hours=48) + hourly_48h = [] + for k in sorted(hourly.keys()): + try: + ts = datetime.fromisoformat(k).replace(tzinfo=timezone.utc) + except Exception: + continue + if ts >= cutoff_48h: + hourly_48h.append({"h": k, "c": hourly[k].get("total", 0)}) + + channels = data.get("channels", {}) + top_channels = sorted( + [{"name": v.get("name", "?"), "total": v.get("total_messages", 0)} for v in channels.values()], + key=lambda x: -x["total"] + )[:10] + + users = data.get("user_stats", {}) + top_users = sorted( + [{"username": u.get("username", "?"), "total": u.get("total_messages", 0), "last": u.get("last_message", "")} + for u in users.values()], + key=lambda x: -x["total"] + )[:10] + + member_events = list(reversed(data.get("member_events", [])))[:25] + + links = [] + for discord_id, info in discord_links.items(): + if not isinstance(info, dict): + continue + pid = info.get("profile_id") + profile = db.get_profile(pid) if pid else None + links.append({ + "discord_id": discord_id, + "discord_username": info.get("username", "?"), + "linked_at": info.get("linked_at", ""), + "profile_id": pid, + "game_username": profile.get("Username", "?") if profile else "?", + "level": profile.get("Level", 0) if profile else 0, + }) + + ch_hours = _dd(float) + for s in voice_sessions: + ch_hours[s.get("channel_name", "?")] += s.get("duration_minutes", 0) / 60 + top_voice = sorted( + [{"name": k, "hours": round(v, 1)} for k, v in ch_hours.items()], + key=lambda x: -x["hours"] + )[:8] + + return jsonify({ + "summary": summary, + "growth": growth, + "hourly_48h": hourly_48h, + "top_channels": top_channels, + "top_users": top_users, + "member_events": member_events, + "discord_links": links, + "top_voice": top_voice, + }) + + +_VIDEOS_DIR = os.path.join(os.path.dirname(__file__), "..", "Videos") +_VIDEO_EXTS = {".mp4", ".webm", ".mov", ".avi", ".mkv", ".m4v"} +_MAX_VIDEO_BYTES = 512 * 1024 * 1024 + + +@bp.route("/admin/videos") +@require_admin_api +def admin_videos_page(account, scopes): + return render_template("admin/videos.html", scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN) + + +@bp.route("/admin/api/videos") +@require_admin_api +def api_videos_list(account, scopes): + vdir = os.path.normpath(_VIDEOS_DIR) + files = [] + if os.path.isdir(vdir): + for name in sorted(os.listdir(vdir)): + ext = os.path.splitext(name)[1].lower() + if ext in _VIDEO_EXTS: + path = os.path.join(vdir, name) + files.append({"name": name, "size": os.path.getsize(path), "url": "/Videos/" + name}) + return jsonify(files) + + +@bp.route("/admin/api/videos/replace", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_videos_replace(account, scopes): + vdir = os.path.normpath(_VIDEOS_DIR) + target = os.path.basename(request.form.get("target_name", "") or (request.get_json(force=True, silent=True) or {}).get("target_name", "")) + if not target: + return jsonify({"error": "No target filename"}), 400 + ext = os.path.splitext(target)[1].lower() + if ext not in _VIDEO_EXTS: + return jsonify({"error": "Invalid file type"}), 400 + dest = os.path.join(vdir, target) + if not os.path.isfile(dest): + return jsonify({"error": "Target does not exist — only replacement of existing videos allowed"}), 400 + url = request.form.get("url", "").strip() + f = request.files.get("file") + if url: + try: + with urllib.request.urlopen(url, timeout=60) as resp: + data = resp.read(_MAX_VIDEO_BYTES) + with open(dest, "wb") as out: + out.write(data) + except Exception as e: + return jsonify({"error": f"URL fetch failed: {e}"}), 400 + elif f and f.filename: + f.save(dest) + else: + return jsonify({"error": "Provide a file or URL"}), 400 + size = os.path.getsize(dest) + admin = account.get("username", "admin") + ip = request.headers.get("X-Forwarded-For", request.remote_addr or "") + db.log_admin_action(admin, "video_replace", f"Replaced video: {target} ({size} bytes)", ip) + return jsonify({"ok": True, "name": target, "size": size, "url": "/Videos/" + target}) + + +@bp.route("/admin/api/videos/delete", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def api_videos_delete(account, scopes): + data = request.get_json(force=True, silent=True) or {} + name = os.path.basename(data.get("name", "")) + if not name: + return jsonify({"error": "No filename"}), 400 + ext = os.path.splitext(name)[1].lower() + if ext not in _VIDEO_EXTS: + return jsonify({"error": "Invalid file type"}), 400 + vdir = os.path.normpath(_VIDEOS_DIR) + path = os.path.join(vdir, name) + if not os.path.isfile(path): + return jsonify({"error": "Not found"}), 404 + os.remove(path) + admin = account.get("username", "admin") + ip = request.headers.get("X-Forwarded-For", request.remote_addr or "") + db.log_admin_action(admin, "video_delete", f"Deleted video: {name}", ip) + return jsonify({"ok": True}) + + +@bp.route("/admin/logout") +def admin_logout(): + resp = redirect(make_login_redirect(f"{_base_url}/admin/")) + resp.set_cookie("Authorization", "", max_age=0, domain=_auth_cfg["cookie_domain"], path="/") + resp.set_cookie("Authorization", "", max_age=0, path="/") + session.pop("emergency_admin", None) + return resp + + +_EMERGENCY_HTML = """ +kittyrec-admin login +
+
+
+
kittyrec-admin — bash — 80x24
+
+
+
# KittyRec Administrative Shell v2.0
+
# Primary auth server unreachable — emergency mode active
+
+
root@kittyrec:~# sudo adminctl auth --emergency
+
[WARN] Auth server is unreachable
+
[WARN] Falling back to emergency credential store
+
+
Enter emergency passphrase to continue:
+
+
+ root@kittyrec:~# +
+ +
+
+ +
+ {error} +
+
+ +""" + + +@bp.route("/admin/emergency_login", methods=["GET", "POST"]) +@limiter.limit("5 per minute") +def emergency_login(): + import hmac + import time as _time + if not probe_auth_server(): + return redirect("/admin/") + if request.method == "POST": + if hmac.compare_digest(request.form.get("pw", ""), EMERGENCY_PASSWORD): + session["emergency_admin"] = {"expires": _time.time() + _EMERGENCY_SESSION_TTL} + print("[Admin] Emergency login granted") + return redirect("/admin/") + html = _EMERGENCY_HTML.replace("{error}", '
[ERR] Authentication failed: incorrect passphrase
') + return html, 200 + return _EMERGENCY_HTML.replace("{error}", ""), 200 + + +def register_console_ws(sock): + @sock.route("/admin/ws/console") + def console_ws(ws): + account, scopes = _get_admin_account() + if not account or not _has_any_admin_scope(scopes): + ws.close() + return + + pos = 0 + try: + with open(_LOG_PATH, "rb") as f: + f.seek(0, 2) + size = f.tell() + start = max(0, size - _LOG_INITIAL_BYTES) + f.seek(start) + chunk = f.read() + pos = size + if chunk: + ws.send(chunk.decode("utf-8", errors="replace")) + except FileNotFoundError: + pass + + while True: + try: + time.sleep(0.2) + with open(_LOG_PATH, "rb") as f: + f.seek(0, 2) + new_size = f.tell() + if new_size > pos: + with open(_LOG_PATH, "rb") as f: + f.seek(pos) + chunk = f.read(new_size - pos) + pos = new_size + if chunk: + ws.send(chunk.decode("utf-8", errors="replace")) + elif new_size < pos: + pos = new_size + except Exception: + break diff --git a/routes/presence.py b/routes/presence.py new file mode 100644 index 0000000..99c0767 --- /dev/null +++ b/routes/presence.py @@ -0,0 +1,90 @@ + +from flask import Blueprint, request, jsonify, Response + +from core.auth import check_auth, get_current_profile_id +from core.state import db, session_mgr, ws_registry, APP_VERSION +from core.builders import now_ticks +from core.constants import DORM_ROOM_GUID + +bp = Blueprint("presence", __name__) + +@bp.route("/api/presence/v2/setscreenmode", methods=["POST"]) +@check_auth +def set_screen_mode(): + pid = get_current_profile_id() + data = request.get_json(force=True, silent=True) or {} + in_screen = bool(data.get("InScreenMode", False)) + ws_registry.set_screen_mode(pid, in_screen) + if in_screen and pid: + db.set_setting(pid, "screen_mode_user", "1") + if db.get_setting(pid, "Recroom.OOBE") != "100": + db.set_setting(pid, "Recroom.OOBE", "100") + db.update_profile(pid, {"registration_status": 2}) + _send_oobe_skip_dm(pid) + print(f"[OOBE] Auto-set OOBE=100 for screen mode player {pid}") + return Response("OK", 200) + + +_KITTYREC_PID = 23 + +def _send_oobe_skip_dm(pid: int) -> None: + thread_id = db.get_or_create_chat([_KITTYREC_PID, pid]) + msg_text = ( + "your game is prob broken since your on screenmode and in the oobe. " + "dont worry the kittyrec anticheat is blessing your little heart by " + "letting you skip the oobe<3" + ) + msg_id = db.send_chat_message(thread_id, _KITTYREC_PID, msg_text) + msg = db.get_chat_message(msg_id) + ws_registry.send(pid, {"Id": 90, "Msg": msg}) + +@bp.route("/api/presence/v1/playerDisconnected", methods=["POST"]) +@check_auth +def player_disconnected(): + return Response("OK", 200) + +@bp.route("/api/presence/v3/heartbeat", methods=["POST"]) +@check_auth +def presence_heartbeat(): + from core.builders import activity_info + pid = get_current_profile_id() or 1 + session = session_mgr.get_player_session(pid) + if session is None: + name, key, sandbox = activity_info(DORM_ROOM_GUID) + session = session_mgr.join_room(pid, DORM_ROOM_GUID, name, key, sandbox=sandbox) + return jsonify({ + "Id": 4, + "Msg": { + "PlayerId": pid, + "IsOnline": True, + "InScreenMode": ws_registry.is_screen_mode(pid), + "GameSession": session.to_dict(), + }, + }) + +@bp.route("/api/presence/v1/setplayertype", methods=["POST"]) +@check_auth +def set_player_type(): + return jsonify([]) + +@bp.route("/api/presence/v2/list", methods=["POST"]) +@check_auth +def get_presence_list(): + ids = (request.get_json(force=True, silent=True) or [])[:200] + result = [] + for pid in ids: + session = session_mgr.get_player_session(pid) + is_online = ws_registry.is_connected(pid) + result.append({ + "PlayerId": pid, + "IsOnline": is_online, + "GameSessionId": session.photon_room_id if session else "", + "AppVersion": APP_VERSION, + "LastUpdateTime": now_ticks(), + "Activity": session.activity_key if session else "", + "Private": session.private if session else False, + "AvailableSpace": (max(0, session.max_capacity - len(session.players)) + if session else 0), + "GameInProgress": session.game_in_progress if session else False, + }) + return jsonify(result) diff --git a/routes/relationships.py b/routes/relationships.py new file mode 100644 index 0000000..9339e10 --- /dev/null +++ b/routes/relationships.py @@ -0,0 +1,408 @@ + +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 +from core.builders import now_iso, get_request_data +from core.ws_helpers import push_presence +from core.constants import ( + MSG_GAME_INVITE, MSG_FRIEND_INVITE, MSG_TEXT, MSG_FRIEND_REQUEST_ACCEPTED, + REL_NONE, REL_SENT, REL_RECEIVED, REL_FRIEND, +) +from core.config import base_url as _base_url + +bp = Blueprint("relationships", __name__) + +def _push_msg_ws(to_pid: int, msg_dict: dict) -> None: + ws_registry.send(to_pid, {"Id": 2, "Msg": msg_dict}) + +_MUTED_LOCAL = 1 +_MUTED_REMOTE = 2 +_IGNORED_LOCAL = 1 +_IGNORED_REMOTE = 2 + +def _rel_resp(target_id: int, rel_type: int, muted: int = 0, ignored: int = 0) -> dict: + return {"PlayerID": target_id, "RelationshipType": rel_type, "Muted": muted, "Ignored": ignored} + +def _fav_resp(target_id: int, rel_type: int, favorited: int) -> dict: + return {"PlayerID": target_id, "RelationshipType": rel_type, "Muted": 0, "Ignored": 0, "Favorited": favorited} + +def _msg_dict(msg_id: int, from_pid: int, msg_type: int, data: str, room_id, sent_time: str = None) -> dict: + return { + "Id": msg_id, "FromPlayerId": from_pid, "SentTime": sent_time or now_iso(), + "Type": msg_type, "Data": data, "RoomId": room_id, "PlayerEventId": None, + } + +def _rel_msg(about_pid: int, rel: dict) -> dict: + return { + "PlayerID": about_pid, + "RelationshipType": rel.get("RelationshipType", 0), + "Muted": rel.get("Muted", 0), + "Ignored": rel.get("Ignored", 0), + "Favorited": rel.get("Favorited", 0), + } + +def _push_relationship_ws(to_pid: int, about_pid: int, rel_type: int) -> None: + rel = db.get_relationship(to_pid, about_pid) + rel["RelationshipType"] = rel_type + ws_registry.send(to_pid, {"Id": 1, "Msg": _rel_msg(about_pid, rel)}) + +def _push_rel_both(pid: int, target_id: int) -> None: + my_rel = db.get_relationship(pid, target_id) + their_rel = db.get_relationship(target_id, pid) + ws_registry.send(pid, {"Id": 1, "Msg": _rel_msg(target_id, my_rel)}) + ws_registry.send(target_id, {"Id": 1, "Msg": _rel_msg(pid, their_rel)}) + + +@bp.route("/api/relationships/v2/get", methods=["GET"]) +@check_auth +def get_relationships(): + pid = get_current_profile_id() + if pid is None: + return jsonify([]) + return jsonify(db.get_relationships(pid)) + +@bp.route("/api/relationships/v2/sendfriendrequest", methods=["GET", "POST"]) +@check_auth +def send_friend_request(): + pid = get_current_profile_id() + try: + target_id = int(request.args.get("id", 0)) + except (ValueError, TypeError): + return jsonify(_rel_resp(0, REL_NONE)) + if not pid or not target_id or pid == target_id or not db.get_profile(target_id): + return jsonify(_rel_resp(target_id, REL_NONE)) + + existing = db.get_relationship(pid, target_id) + their_existing = db.get_relationship(target_id, pid) + + if existing["RelationshipType"] == REL_FRIEND: + return jsonify(_rel_resp(target_id, REL_FRIEND)) + + if their_existing["RelationshipType"] == REL_SENT or existing["RelationshipType"] == REL_RECEIVED: + db.set_relationship_type(pid, target_id, REL_FRIEND) + db.set_relationship_type(target_id, pid, REL_FRIEND) + db.delete_messages_of_type(pid, target_id, MSG_FRIEND_INVITE) + msg_id = db.send_message(pid, target_id, MSG_FRIEND_REQUEST_ACCEPTED, str(pid)) + _push_msg_ws(target_id, _msg_dict(msg_id, pid, MSG_FRIEND_REQUEST_ACCEPTED, str(pid), None)) + _push_relationship_ws(target_id, pid, REL_FRIEND) + _push_relationship_ws(pid, target_id, REL_FRIEND) + push_presence(pid, session_mgr.get_player_session(pid)) + push_presence(target_id, session_mgr.get_player_session(target_id)) + return jsonify(_rel_resp(target_id, REL_FRIEND)) + + db.set_relationship_type(pid, target_id, REL_SENT) + db.set_relationship_type(target_id, pid, REL_RECEIVED) + db.delete_messages_of_type(target_id, pid, MSG_FRIEND_INVITE) + msg_id = db.send_message(pid, target_id, MSG_FRIEND_INVITE, str(pid)) + _push_msg_ws(target_id, _msg_dict(msg_id, pid, MSG_FRIEND_INVITE, str(pid), None)) + _push_relationship_ws(target_id, pid, REL_RECEIVED) + _push_relationship_ws(pid, target_id, REL_SENT) + return jsonify(_rel_resp(target_id, REL_SENT)) + +@bp.route("/api/relationships/v2/acceptfriendrequest", methods=["GET", "POST"]) +@check_auth +def accept_friend_request(): + pid = get_current_profile_id() + try: + target_id = int(request.args.get("id", 0)) + except (ValueError, TypeError): + return jsonify(_rel_resp(0, REL_NONE)) + if not pid or not target_id or pid == target_id: + return jsonify(_rel_resp(target_id, REL_NONE)) + + my_rel = db.get_relationship(pid, target_id) + their_rel = db.get_relationship(target_id, pid) + if their_rel["RelationshipType"] != REL_SENT and my_rel["RelationshipType"] != REL_RECEIVED: + return jsonify(_rel_resp(target_id, my_rel["RelationshipType"])) + + db.set_relationship_type(pid, target_id, REL_FRIEND) + db.set_relationship_type(target_id, pid, REL_FRIEND) + db.delete_messages_of_type(pid, target_id, MSG_FRIEND_INVITE) + + msg_id = db.send_message(pid, target_id, MSG_FRIEND_REQUEST_ACCEPTED, str(pid)) + _push_msg_ws(target_id, _msg_dict(msg_id, pid, MSG_FRIEND_REQUEST_ACCEPTED, str(pid), None)) + _push_relationship_ws(target_id, pid, REL_FRIEND) + _push_relationship_ws(pid, target_id, REL_FRIEND) + push_presence(pid, session_mgr.get_player_session(pid)) + push_presence(target_id, session_mgr.get_player_session(target_id)) + + return jsonify(_rel_resp(target_id, REL_FRIEND)) + +@bp.route("/api/relationships/v2/addfriend", methods=["GET", "POST"]) +@check_auth +def add_friend(): + return send_friend_request() + +_KITTYREC_PID = 23 + +@bp.route("/api/relationships/v2/removefriend", methods=["GET", "POST"]) +@check_auth +def remove_friend(): + pid = get_current_profile_id() + try: + target_id = int(request.args.get("id", 0)) + except (ValueError, TypeError): + return jsonify(_rel_resp(0, REL_NONE)) + if target_id == _KITTYREC_PID: + return jsonify(_rel_resp(target_id, REL_FRIEND)) + if pid and target_id and pid != target_id: + db.remove_relationship(pid, target_id) + db.remove_relationship(target_id, pid) + db.delete_messages_of_type(pid, target_id, MSG_FRIEND_INVITE) + db.delete_messages_of_type(target_id, pid, MSG_FRIEND_INVITE) + _push_relationship_ws(target_id, pid, REL_NONE) + _push_relationship_ws(pid, target_id, REL_NONE) + return jsonify(_rel_resp(target_id, REL_NONE)) + +@bp.route("/api/relationships/v1/favorite", methods=["GET", "POST"]) +@check_auth +def favorite_player(): + pid = get_current_profile_id() + try: + target_id = int(request.args.get("id", 0)) + except (ValueError, TypeError): + return jsonify(_fav_resp(0, 0, 1)) + if pid and target_id and pid != target_id: + db.set_rel_field(pid, target_id, "favorited", 1) + rel = db.get_relationship(pid, target_id) if pid and target_id and pid != target_id else {} + return jsonify(_fav_resp(target_id, rel.get("RelationshipType", 0), 1)) + +@bp.route("/api/relationships/v1/unfavorite", methods=["GET", "POST"]) +@check_auth +def unfavorite_player(): + pid = get_current_profile_id() + try: + target_id = int(request.args.get("id", 0)) + except (ValueError, TypeError): + return jsonify(_fav_resp(0, 0, 0)) + if pid and target_id and pid != target_id: + db.set_rel_field(pid, target_id, "favorited", 0) + rel = db.get_relationship(pid, target_id) if pid and target_id and pid != target_id else {} + return jsonify(_fav_resp(target_id, rel.get("RelationshipType", 0), 0)) + +@bp.route("/api/relationships/v1/mute", methods=["POST"]) +@check_auth +def mute_player(): + pid = get_current_profile_id() + if pid is None: + return jsonify({"Success": False, "Message": "Not authenticated"}) + target_id = int(get_request_data().get("PlayerId", 0)) + if not target_id or target_id == pid: + return jsonify({"Success": False, "Message": "Invalid PlayerId"}) + if target_id == _KITTYREC_PID: + return jsonify({"Success": True, "Message": ""}) + db.set_rel_field(pid, target_id, "muted", _MUTED_LOCAL) + db.set_rel_field(target_id, pid, "muted", _MUTED_REMOTE) + _push_rel_both(pid, target_id) + return jsonify({"Success": True, "Message": ""}) + +@bp.route("/api/relationships/v1/unmute", methods=["POST"]) +@check_auth +def unmute_player(): + pid = get_current_profile_id() + if pid is None: + return jsonify({"Success": False, "Message": "Not authenticated"}) + target_id = int(get_request_data().get("PlayerId", 0)) + if not target_id or target_id == pid: + return jsonify({"Success": False, "Message": "Invalid PlayerId"}) + db.set_rel_field(pid, target_id, "muted", 0) + their_muted = db.get_relationship(target_id, pid).get("Muted", 0) + if their_muted == _MUTED_REMOTE: + db.set_rel_field(target_id, pid, "muted", 0) + _push_rel_both(pid, target_id) + return jsonify({"Success": True, "Message": ""}) + +@bp.route("/api/relationships/v1/ignore", methods=["POST"]) +@check_auth +def ignore_player(): + pid = get_current_profile_id() + if pid is None: + return jsonify({"Success": False, "Message": "Not authenticated"}) + target_id = int(get_request_data().get("PlayerId", 0)) + if not target_id or target_id == pid: + return jsonify({"Success": False, "Message": "Invalid PlayerId"}) + if target_id == _KITTYREC_PID: + return jsonify({"Success": True, "Message": ""}) + db.set_rel_field(pid, target_id, "ignored", _IGNORED_LOCAL) + db.set_rel_field(target_id, pid, "ignored", _IGNORED_REMOTE) + _push_rel_both(pid, target_id) + return jsonify({"Success": True, "Message": ""}) + +@bp.route("/api/relationships/v1/unignore", methods=["POST"]) +@check_auth +def unignore_player(): + pid = get_current_profile_id() + if pid is None: + return jsonify({"Success": False, "Message": "Not authenticated"}) + target_id = int(get_request_data().get("PlayerId", 0)) + if not target_id or target_id == pid: + return jsonify({"Success": False, "Message": "Invalid PlayerId"}) + db.set_rel_field(pid, target_id, "ignored", 0) + their_ignored = db.get_relationship(target_id, pid).get("Ignored", 0) + if their_ignored == _IGNORED_REMOTE: + db.set_rel_field(target_id, pid, "ignored", 0) + _push_rel_both(pid, target_id) + return jsonify({"Success": True, "Message": ""}) + +@bp.route("/api/relationships/v1/bulkignoreplatformusers", methods=["POST"]) +def bulk_ignore_platform(): + return jsonify({"Success": True, "Message": ""}) + +@bp.route("/api/messages/v2/get", methods=["GET"]) +@check_auth +def get_messages(): + pid = get_current_profile_id() + if pid is None: + return jsonify([]) + since_id = int(request.args.get("sinceId", 0)) + return jsonify(db.get_messages(pid, since_id)) + +@bp.route("/api/messages/v2/send", methods=["POST"]) +@limiter.limit("30 per minute") +@check_auth +def send_message_endpoint(): + pid = get_current_profile_id() + if pid is None: + return jsonify({"Success": False}) + data = get_request_data() + to_id = int(data.get("ToPlayerId", 0)) + msg_type = int(data.get("Type", MSG_TEXT)) + msg_data = str(data.get("Data", "")) + room_id = data.get("RoomId") + + if to_id == pid: + return jsonify({"Success": False}) + + from core.state import _KITTYREC_SYSTEM_PID + from core.system_messages import dispatch_reply + if to_id == _KITTYREC_SYSTEM_PID: + from tracking.password_tracking import has_real_password + if not has_real_password(pid): + return _handle_password_msg(pid, msg_data.strip()) + if dispatch_reply(pid, msg_data.strip()): + return jsonify({"Success": True}) + from datetime import datetime, timezone + sent = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + reply = "Invalid command." + msg_id = db.send_message(_KITTYREC_SYSTEM_PID, pid, 30, reply) + _push_msg_ws(pid, _msg_dict(msg_id, _KITTYREC_SYSTEM_PID, 30, reply, None, sent)) + return jsonify({"Success": True}) + + msg_id = db.send_message(pid, to_id, msg_type, msg_data, room_id) + _push_msg_ws(to_id, _msg_dict(msg_id, pid, msg_type, msg_data, room_id)) + return jsonify({"Success": True}) + + +def _handle_password_msg(pid, password): + from werkzeug.security import generate_password_hash + from core.state import _KITTYREC_SYSTEM_PID + from core.ws_helpers import push_profile_update + from datetime import datetime, timezone + + sent = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + if len(password) < 8 or len(password) > 128: + reply = "Password must be 8-128 characters. Try again!" + msg_id = db.send_message(_KITTYREC_SYSTEM_PID, pid, 30, reply) + _push_msg_ws(pid, _msg_dict(msg_id, _KITTYREC_SYSTEM_PID, 30, reply, None, sent)) + return jsonify({"Success": True}) + + conn = db._get_conn() + conn.execute( + "UPDATE profiles SET password=?, registration_status=2 WHERE id=?", + (generate_password_hash(password), pid), + ) + conn.commit() + from tracking.password_tracking import mark_password_set + mark_password_set(pid) + + profile = db.get_profile(pid) + uname = (profile or {}).get("Username", f"Player {pid}") + db.delete_messages_of_type(pid, _KITTYREC_SYSTEM_PID, 30) + reply = 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" + msg_id = db.send_message(_KITTYREC_SYSTEM_PID, pid, 30, reply) + _push_msg_ws(pid, _msg_dict(msg_id, _KITTYREC_SYSTEM_PID, 30, reply, None, sent)) + push_profile_update(pid) + print(f"[System] Player {pid} ({uname}) registered via message reply") + return jsonify({"Success": True}) + + +from core.system_messages import reply_handler + +@reply_handler("password_change") +def _password_change_handler(pid, text, ctx, reply): + from werkzeug.security import generate_password_hash + from core.ws_helpers import push_profile_update + from tracking.password_tracking import has_real_password, mark_password_set + + if has_real_password(pid): + reply("Invalid command.") + return + + if len(text) < 8 or len(text) > 128 or not text.isprintable(): + reply("Password must be 8-128 printable characters. Try again!", next_handler="password_change") + return + + conn = db._get_conn() + conn.execute( + "UPDATE profiles SET password=?, must_change_password=0 WHERE id=?", + (generate_password_hash(text), pid), + ) + conn.commit() + mark_password_set(pid) + + profile = db.get_profile(pid) + uname = (profile or {}).get("Username", f"Player {pid}") + from core.state import _KITTYREC_SYSTEM_PID as _SYS + db.delete_messages_of_type(pid, _SYS, 30) + reply(f"Password updated! You're all set, {uname}.") + push_profile_update(pid) + print(f"[System] Player {pid} ({uname}) updated password via message reply") + +@bp.route("/api/messages/v1/sendMultiple", methods=["POST"]) +@check_auth +@limiter.limit("5 per minute") +def send_message_multiple(): + pid = get_current_profile_id() + if pid is None: + return jsonify({"Success": False}) + data = get_request_data() + to_ids = [x for x in data.get("ToPlayerIds", []) if int(x) != pid][:10] + msg_type = int(data.get("Type", MSG_TEXT)) + msg_data = str(data.get("Data", ""))[:4096] + room_id = data.get("RoomId") + sent_time = now_iso() + for to_id in to_ids: + to_id = int(to_id) + msg_id = db.send_message(pid, to_id, msg_type, msg_data, room_id) + _push_msg_ws(to_id, _msg_dict(msg_id, pid, msg_type, msg_data, room_id, sent_time)) + return jsonify({"Success": True}) + +@bp.route("/api/messages/v2/delete", methods=["POST"]) +@check_auth +def delete_message_endpoint(): + pid = get_current_profile_id() + if pid is None: + return jsonify({"Success": False}) + msg_id = int(request.values.get("Id", 0)) + db.delete_message(msg_id, pid) + return jsonify({"Success": True}) + +@bp.route("/api/offlineinvite/v1/send", methods=["POST"]) +@limiter.limit("5 per minute") +@check_auth +def send_offline_invite(): + pid = get_current_profile_id() + if pid is None: + return jsonify({"Success": False}) + data = get_request_data() + to_id = int(data.get("ToPlayerId", 0)) + if not to_id or to_id == pid: + return jsonify({"Success": False}) + session = session_mgr.get_player_session(pid) + room_id = session.session_id if session else None + msg_id = db.send_message(pid, to_id, MSG_GAME_INVITE, "", room_id) + _push_msg_ws(to_id, _msg_dict(msg_id, pid, MSG_GAME_INVITE, "", room_id)) + return jsonify({"Success": True}) diff --git a/routes/rooms.py b/routes/rooms.py new file mode 100644 index 0000000..e0ccb5a --- /dev/null +++ b/routes/rooms.py @@ -0,0 +1,590 @@ + +import json +import os + +from flask import Blueprint, request, jsonify, Response + +from core.auth import check_auth, get_current_profile_id +from core.builders import now_iso +from core.state import session_mgr, db +from core.constants import DORM_ROOM_GUID + +def _load_room_config(): + cfg_path = os.path.join(os.path.dirname(__file__), "..", "data", "room_config.json") + with open(cfg_path, encoding="utf-8") as f: + return json.load(f) + +_room_cfg = _load_room_config() +_SOCIAL_GUIDS = set(_room_cfg["social_guids"]) +_BROWSE_EXCLUDE_GUIDS = _SOCIAL_GUIDS | set(_room_cfg["browse_exclude_extra_guids"]) +_MAX_ROOMS_PER_PLAYER = _room_cfg["max_rooms_per_player"] +_RESERVED_NAMES = set(_room_cfg["reserved_names"]) +_PAINTBALL_GUIDS = _room_cfg["paintball_guids"] +_PAINTBALL_SUPPRESS = set(_PAINTBALL_GUIDS[1:]) + +def _session_to_room(s) -> dict: + now = now_iso() + return { + "RoomId": s.session_id, + "Name": s.name, + "Description": "", + "CreatorPlayerId": s.creator_player_id or 23, + "ImageName": "", + "DataBlobName": "", + "ActivityLevelId": s.activity_level_id, + "State": 0, + "Accessibility": 0, + "IsSandbox": s.sandbox, + "Instanced": True, + "ScreenModeSupport": 0, + "MaxPlayers": s.max_capacity, + "VisitorCount": len(s.players), + "VisitCount": 0, + "CheerCount": 0, + "ReportCount": 0, + "StateModifiedAt": now, + "CreatedAt": now, + "ModifiedAt": now, + "LastVisitedAt": now, + "CoOwners": [], + "Hosts": [], + } + +def _all_browseable_rooms() -> list: + # Build live player counts for custom rooms (sessions tied to a DB room) + custom_player_counts: dict[int, int] = {} + for s in session_mgr.all_public_sessions(): + if s.rec_room_id: + existing = custom_player_counts.get(s.rec_room_id, 0) + custom_player_counts[s.rec_room_id] = max(existing, len(s.players)) + + # Always include every custom DB room; inject live player count if present + rooms = [] + for db_room in db.get_all_rooms(): + guid = db_room.get("ActivityLevelId", "") + if guid in _BROWSE_EXCLUDE_GUIDS: + continue + room_id = db_room.get("RoomId") + live = custom_player_counts.get(room_id, 0) + if live or db_room.get("VisitorCount", 0) != live: + db_room = dict(db_room) + db_room["VisitorCount"] = live + elif "VisitorCount" not in db_room: + db_room["VisitorCount"] = 0 + rooms.append(db_room) + + # Add preset sessions (no rec_room_id), deduplicated by GUID + seen_preset_guids: set[str] = set() + best_paintball: object = None + for s in session_mgr.all_public_sessions(): + if s.rec_room_id: + continue + if s.activity_level_id in _PAINTBALL_GUIDS: + if best_paintball is None or len(s.players) > len(best_paintball.players): + best_paintball = s + + for s in session_mgr.all_public_sessions(): + if s.rec_room_id: + continue + guid = s.activity_level_id + if guid in _BROWSE_EXCLUDE_GUIDS: + continue + if guid in _PAINTBALL_GUIDS: + if s is best_paintball and _PAINTBALL_GUIDS[0] not in seen_preset_guids: + rooms.append(_session_to_room(s)) + seen_preset_guids.update(_PAINTBALL_GUIDS) + elif guid not in seen_preset_guids: + rooms.append(_session_to_room(s)) + seen_preset_guids.add(guid) + + rooms.sort(key=lambda r: r.get("VisitorCount", 0), reverse=True) + return rooms + +bp = Blueprint("rooms", __name__) + +def _room_ok(room_dict): + return jsonify({"Result": 0, "Room": room_dict}) + +def _room_err(code=1): + return jsonify({"Result": code, "Room": None}) + +@bp.route("/api/rooms/v2/myrooms", methods=["GET"]) +@check_auth +def get_my_rooms(): + pid = get_current_profile_id() + if not pid: + return jsonify([]) + return jsonify(db.get_rooms_by_creator(pid)) + +@bp.route("/api/rooms/v2/mybookmarkedrooms", methods=["GET"]) +@check_auth +def get_bookmarked_rooms(): + pid = get_current_profile_id() + if not pid: + return jsonify([]) + return jsonify(db.get_bookmarked_rooms(pid)) + +@bp.route("/api/rooms/v2/hot", methods=["GET"]) +@bp.route("/api/rooms/v3/browse", methods=["GET"]) +@check_auth +def browse_rooms(): + skip = int(request.args.get("skip", 0)) + take = int(request.args.get("take", 75)) + rooms = _all_browseable_rooms() + return jsonify(rooms[skip:skip + take]) + +@bp.route("/api/rooms/v3/featured", methods=["GET"]) +@check_auth +def get_featured_rooms(): + return jsonify({ + "RoomId": 1, + "Name": "RecCenter", + "Description": "", + "CreatorPlayerId": 1, + "ImageName": "", + "ActivityLevelId": "cbad71af-0831-44d8-b8ef-69edafa841f6", + "State": 0, + "Accessibility": 0, + "IsSandbox": False, + "Instanced": True, + "ScreenModeSupport": 0, + }) + +@bp.route("/api/rooms/v1/featuredRoomGroup", methods=["GET"]) +@check_auth +def get_featured_room_group(): + return jsonify({"Name": "Featured", "FeaturedRooms": []}) + +def _fallback_room(): + now = now_iso() + return { + "RoomId": 1, + "Name": "RecCenter", + "Description": "", + "CreatorPlayerId": 1, + "ImageName": "", + "DataBlobName": "", + "ActivityLevelId": "cbad71af-0831-44d8-b8ef-69edafa841f6", + "State": 0, + "Accessibility": 0, + "IsSandbox": False, + "Instanced": True, + "ScreenModeSupport": 0, + "MaxPlayers": 20, + "VisitorCount": 0, + "VisitCount": 0, + "CheerCount": 0, + "ReportCount": 0, + "StateModifiedAt": now, + "CreatedAt": now, + "ModifiedAt": now, + "LastVisitedAt": now, + "CoOwners": [], + "Hosts": [], + } + +@bp.route("/api/rooms/v2/featured", methods=["GET"]) +@check_auth +def get_featured_rooms_v2(): + rooms = db.get_all_rooms() + return jsonify(rooms[0] if rooms else _fallback_room()) + +@bp.route("/api/rooms/v2/browse", methods=["POST"]) +@check_auth +def browse_rooms_v2(): + return jsonify(_all_browseable_rooms()) + +@bp.route("/api/rooms/v1/myrooms", methods=["GET"]) +@check_auth +def get_my_rooms_v1(): + pid = get_current_profile_id() + if not pid: + return jsonify([]) + return jsonify(db.get_rooms_by_creator(pid)) + +@bp.route("/api/rooms/v1/mybookmarkedrooms", methods=["GET"]) +@check_auth +def get_bookmarked_rooms_v1(): + pid = get_current_profile_id() + if not pid: + return jsonify([]) + return jsonify(db.get_bookmarked_rooms(pid)) + +@bp.route("/api/rooms/v1/myRecent", methods=["GET"]) +@bp.route("/api/rooms/v2/myRecent", methods=["GET"]) +@check_auth +def get_recent_rooms(): + pid = get_current_profile_id() + if not pid: + return jsonify([]) + skip = int(request.args.get("skip", 0)) + take = int(request.args.get("take", 10)) + rooms = db.get_recent_rooms(pid, limit=skip + take) + if not rooms: + rooms = _all_browseable_rooms() + return jsonify(rooms[skip:skip + take]) + +@bp.route("/api/rooms/v2/mySubscriptions", methods=["GET"]) +@check_auth +def get_room_subscriptions(): + return jsonify([]) + +@bp.route("/api/rooms/v1/search", methods=["POST"]) +@bp.route("/api/rooms/v2/search", methods=["GET"]) +@check_auth +def search_rooms(): + query = "" + if request.method == "POST": + data = request.get_json(force=True, silent=True) or {} + query = str(data.get("Name", "")).strip().lower() + else: + query = request.args.get("name", "").strip().lower() + if not query: + return jsonify(db.get_all_rooms()) + all_rooms = db.get_all_rooms() + return jsonify([r for r in all_rooms if query in r["Name"].lower()]) + +@bp.route("/api/rooms/v1/", methods=["GET"]) +@bp.route("/api/rooms/v2/", methods=["GET"]) +@check_auth +def get_room(room_id): + room = db.get_room(room_id) + if room: + return jsonify(room) + now = now_iso() + return jsonify({ + "RoomId": room_id, + "Name": "dormroom", + "Description": "", + "CreatorPlayerId": 1, + "ImageName": "", + "DataBlobName": "", + "ActivityLevelId": DORM_ROOM_GUID, + "State": 0, + "Accessibility": 0, + "IsSandbox": False, + "Instanced": True, + "ScreenModeSupport": 0, + "MaxPlayers": 20, + "VisitorCount": 0, + "VisitCount": 0, + "CheerCount": 0, + "ReportCount": 0, + "CreatedAt": now, + "ModifiedAt": now, + "StateModifiedAt": now, + "LastVisitedAt": now, + "CoOwners": [], + "Hosts": [], + }) + +@bp.route("/api/rooms/v3/details/", methods=["GET"]) +@check_auth +def get_room_details(room_id): + room = db.get_room(room_id) + if room: + return jsonify(room) + session = session_mgr.get_session(room_id) + creator_pid = session.creator_player_id if session else 1 + name = session.name if session else "DormRoom" + activity_id = session.activity_level_id if session else DORM_ROOM_GUID + is_sandbox = session.sandbox if session else False + now = now_iso() + return jsonify({ + "RoomId": room_id, + "Name": name, + "Description": "", + "CreatorPlayerId": creator_pid, + "ImageName": "", + "ActivityLevelId": activity_id, + "MaxPlayers": 20, + "State": 0, + "Accessibility": 0, + "IsSandbox": is_sandbox, + "Instanced": True, + "ScreenModeSupport": 0, + "DataBlobName": "", + "AccessibilityLocked": False, + "CreatedAt": now, + "ModifiedAt": now, + "StateModifiedAt": now, + "DataModifiedAt": None, + "LastVisitedAt": now, + "VisitorCount": len(session.players) if session else 0, + "VisitCount": 0, + "CheerCount": 0, + "ReportCount": 0, + "CoOwners": [], + "Hosts": [], + }) + +@bp.route("/api/rooms/v1/name/", methods=["GET"]) +@bp.route("/api/rooms/v2/name/", methods=["GET"]) +@check_auth +def get_room_by_name(room_name): + room = db.get_room_by_name(room_name) + if room: + return jsonify(room) + now = now_iso() + return jsonify({ + "RoomId": 0, + "Name": room_name, + "Description": "", + "CreatorPlayerId": 1, + "ImageName": "", + "DataBlobName": "", + "ActivityLevelId": "", + "State": 0, + "Accessibility": 0, + "IsSandbox": False, + "Instanced": True, + "ScreenModeSupport": 0, + "MaxPlayers": 20, + "VisitorCount": 0, + "VisitCount": 0, + "CheerCount": 0, + "ReportCount": 0, + "CreatedAt": now, + "ModifiedAt": now, + "StateModifiedAt": now, + "LastVisitedAt": now, + "CoOwners": [], + "Hosts": [], + }) + +@bp.route("/api/rooms/v2/personaldetails/", methods=["GET"]) +@check_auth +def get_personal_room_details(room_id): + pid = get_current_profile_id() + return jsonify({ + "IsCheering": db.is_room_cheered(pid, room_id) if pid else False, + "IsBookmarked": db.is_room_bookmarked(pid, room_id) if pid else False, + }) + +@bp.route("/api/rooms/v2/create", methods=["POST"]) +@check_auth +def create_room(): + + return jsonify({"Result": 1, "Room": None, "Message": "Room creation is temporarily disabled."}) + pid = get_current_profile_id() + data = request.get_json(force=True, silent=True) or {} + name = str(data.get("Name", "")).strip().replace(" ", "") + if not name: + return jsonify({"Result": 1, "Room": None, "Message": "Room name cannot be empty."}) + if name.lower() in _RESERVED_NAMES: + return jsonify({"Result": 11, "Room": None, "Message": "That room name is reserved."}) + existing = db.get_room_by_name(name) + if existing: + return jsonify({"Result": 10, "Room": None, "Message": "A room with that name already exists."}) + if db.count_rooms_by_creator(pid) >= _MAX_ROOMS_PER_PLAYER: + return jsonify({"Result": 20, "Room": None, "Message": f"You can only have {_MAX_ROOMS_PER_PLAYER} rooms."}) + activity_level_id = data.get("ActivityLevelId", "") + max_players = int(data.get("MaxPlayers", 20)) + if max_players < 1 or max_players > 40: + return jsonify({"Result": 30, "Room": None, "Message": "MaxPlayers must be between 1 and 40."}) + description = data.get("Description", "") + accessibility = int(data.get("Accessibility", 0)) + is_sandbox = bool(data.get("IsSandbox", False)) + instanced = bool(data.get("Instanced", True)) + screen_mode_support = int(data.get("ScreenModeSupport", 0)) + room = db.create_room( + creator_id=pid, + name=name, + description=description, + activity_level_id=activity_level_id, + accessibility=accessibility, + is_sandbox=is_sandbox, + instanced=instanced, + max_players=max_players, + screen_mode_support=screen_mode_support, + ) + game_session_id = int(data.get("GameSessionId", 0)) + if game_session_id: + session = session_mgr.get_session(game_session_id) + if session: + session.rec_room_id = room["RoomId"] + from core.ws_helpers import push_room_update, push_session_update + push_room_update(pid, room) + push_session_update(pid, session) + print(f"[Rooms] Player {pid} created room '{name}' " + f"(id={room['RoomId']}, session={game_session_id or 'none'})") + return _room_ok(room) + +@bp.route("/api/rooms/v1/clone", methods=["POST"]) +@check_auth +def clone_room(): + pid = get_current_profile_id() + data = request.get_json(force=True, silent=True) or {} + room_id = int(data.get("RoomId", 0)) + if not room_id: + return _room_err() + source = db.get_room(room_id) + if not source: + return _room_err() + if source.get("CreatorPlayerId") != pid and source.get("Accessibility", 1) != 0: + return _room_err() + if db.count_rooms_by_creator(pid) >= _MAX_ROOMS_PER_PLAYER: + return jsonify({"Result": 20, "Room": None, "Message": f"You can only have {_MAX_ROOMS_PER_PLAYER} rooms."}) + base_name = source["Name"] + " (Clone)" + clone_name = base_name + counter = 2 + while db.get_room_by_name(clone_name): + clone_name = f"{base_name} {counter}" + counter += 1 + room = db.create_room( + creator_id=pid, + name=clone_name, + description=source["Description"], + activity_level_id=source["ActivityLevelId"], + accessibility=source["Accessibility"], + is_sandbox=source["IsSandbox"], + instanced=source["Instanced"], + max_players=source["MaxPlayers"], + screen_mode_support=source["ScreenModeSupport"], + ) + source_data = db.get_room_data(room_id) + if source_data: + db.save_room_data(room["RoomId"], source_data) + print(f"[Rooms] Player {pid} cloned room '{source['Name']}' → '{clone_name}' (id={room['RoomId']})") + return _room_ok(room) + +@bp.route("/api/rooms/v1/cheer", methods=["POST"]) +@check_auth +def cheer_room(): + pid = get_current_profile_id() + data = request.get_json(force=True, silent=True) or {} + room_id = int(data.get("RoomId", 0)) + if not room_id: + return jsonify({"Success": True, "Message": ""}) + db.toggle_room_cheer(pid, room_id) + return jsonify({"Success": True, "Message": ""}) + +@bp.route("/api/rooms/v1/bookmark", methods=["POST"]) +@check_auth +def bookmark_room(): + pid = get_current_profile_id() + data = request.get_json(force=True, silent=True) or {} + room_id = int(data.get("RoomId", 0)) + if not room_id: + return jsonify({"Success": True, "Message": ""}) + db.toggle_room_bookmark(pid, room_id) + return jsonify({"Success": True, "Message": ""}) + +@bp.route("/api/rooms/v1/report", methods=["POST"]) +@check_auth +def report_room(): + return jsonify({"Success": True, "Message": ""}) + +_MODIFY_FIELD_MAP = { + "name": ("name", lambda d: d.get("Name", "")), + "description": ("description", lambda d: d.get("Description", "")), + "accessibility": ("accessibility", lambda d: int(d.get("Accessibility", 0))), + "instanced": ("instanced", lambda d: 1 if d.get("Instanced", True) else 0), + "screenmode": ("screen_mode_support", lambda d: int(d.get("ScreenModeSupport", 0))), + "maxplayers": ("max_players", lambda d: int(d.get("MaxPlayers", 20))), + "imagename": ("image_name", lambda d: d.get("ImageName", "")), +} + +@bp.route("/api/rooms/v1/modify/", methods=["POST"]) +@check_auth +def modify_room(prop): + pid = get_current_profile_id() + data = request.get_json(force=True, silent=True) or {} + room_id = int(data.get("RoomId", 0)) + if not room_id: + return _room_err() + if not db.is_room_owner_or_coowner(room_id, pid): + return _room_err() + if prop.lower() == "name": + new_name = str(data.get("Name", "")).strip().replace(" ", "") + if new_name.lower() in _RESERVED_NAMES: + return jsonify({"Result": 11, "Room": None}) + existing = db.get_room_by_name(new_name) + if existing and existing["RoomId"] != room_id: + return jsonify({"Result": 10, "Room": None}) + mapping = _MODIFY_FIELD_MAP.get(prop.lower()) + if mapping: + field, extractor = mapping + value = extractor(data) + room = db.update_room_field(room_id, field, value) + if room: + return _room_ok(room) + room = db.get_room(room_id) if room_id else None + if room: + return _room_ok(room) + return _room_err() + +@bp.route("/api/rooms/v1/modifyPermissions", methods=["POST"]) +@check_auth +def modify_room_permissions(): + pid = get_current_profile_id() + data = request.get_json(force=True, silent=True) or {} + room_id = int(data.get("RoomId", 0)) + target_pid = int(data.get("PlayerId", 0)) + if not room_id or not target_pid: + return jsonify({"Result": 0}) + if not db.is_room_owner_or_coowner(room_id, pid): + return Response("Forbidden", 403) + is_host = bool(data.get("IsHost", False)) + is_owner = bool(data.get("IsOwner", False)) + db.set_room_permission(room_id, target_pid, is_host, is_owner) + return jsonify({"Result": 0}) + +@bp.route("/api/rooms/v1/saveData/", methods=["POST", "GET"]) +@check_auth +def room_save_data(room_id): + pid = get_current_profile_id() + if request.method == "GET": + if not db.is_room_owner_or_coowner(room_id, pid): + return Response(b"", 200, {"Content-Type": "application/octet-stream"}) + blob = db.get_room_data(room_id) + if blob: + if isinstance(blob, str): + blob = blob.encode("utf-8") + return Response(blob, 200, {"Content-Type": "application/octet-stream"}) + return Response(b"", 200, {"Content-Type": "application/octet-stream"}) + if not db.is_room_owner_or_coowner(room_id, pid): + return Response("Forbidden", 403) + _MAX_ROOM_DATA = 10 * 1024 * 1024 + if request.content_type and "multipart/form-data" in request.content_type: + raw = request.files.get("data") + if raw: + blob = raw.read(_MAX_ROOM_DATA + 1) + if len(blob) > _MAX_ROOM_DATA: + return Response("Payload Too Large", 413) + db.save_room_data(room_id, blob) + img_list_raw = request.form.get("imgList") + if img_list_raw: + try: + img_data = json.loads(img_list_raw) + img_names = img_data.get("roomImageList", []) + if img_names: + db.update_room_field(room_id, "image_name", img_names[0] if img_names else "") + except (json.JSONDecodeError, AttributeError): + pass + else: + raw = request.get_data(cache=False) + if raw: + if len(raw) > _MAX_ROOM_DATA: + return Response("Payload Too Large", 413) + db.save_room_data(room_id, raw) + print(f"[Rooms] Room {room_id} data saved ({len(request.get_data())} bytes)") + room = db.get_room(room_id) + return jsonify(room) if room else jsonify({}) + +@bp.route("/api/rooms/v1/datahistory/", methods=["GET"]) +@check_auth +def room_data_history(room_id): + return jsonify([]) + +@bp.route("/api/rooms/v1/datahistory/restore", methods=["POST"]) +@check_auth +def restore_room_data(): + return jsonify({"Success": True, "Message": ""}) + +@bp.route("/api/rooms/v2/instancedetails/", methods=["GET"]) +@check_auth +def get_instance_details(room_id): + from core.state import session_mgr + sessions = [s for s in session_mgr.all_public_sessions() if s.rec_room_id == room_id] + return jsonify({"GameSessionCount": len(sessions), "PlayerCount": sum(len(s.players) for s in sessions)}) diff --git a/routes/sdk.py b/routes/sdk.py new file mode 100644 index 0000000..5f8c5bc --- /dev/null +++ b/routes/sdk.py @@ -0,0 +1,155 @@ +import json +import os +import random +import jwt +from functools import wraps +import uuid +from flask import Blueprint, request, jsonify, abort, send_from_directory +from werkzeug.utils import secure_filename + + +from core.config import sdk as _sdk_cfg, base_url as _base_url +from core.state import db + +jwtKey = _sdk_cfg.get("jwt_secret", "") + +bp = Blueprint("KittySDK", __name__) + +def getUset(f): + @wraps(f) + def decorated(*args, **kwargs): + auth = request.headers.get("Authorization") + + if not auth or not auth.startswith("Bearer "): + return abort(401) + + try: + token = auth.split(" ")[1] + + authr = jwt.decode(token, jwtKey, algorithms=["HS256"]) + + userd = db.get_profile(int(authr.get("sub"))) + + if userd is None: + return abort(401) + + return f(userd, *args, **kwargs) + + except Exception as e: + print(f"Auth Error: {e}") + return abort(401) + + return decorated + +@bp.route("/api/sdk/v1", methods=["POST"]) +def login(): + jsondata = request.get_json(silent=True) + + if not jsondata or not isinstance(jsondata, dict): + return abort(400) + + username = jsondata.get("username") + password = jsondata.get("password") + + if not username or not password: + return abort(400) + + profile = db.check_password(username, password) + + if profile is None: + + return jsonify({ + "Error": "Invalid username or password", + "Token": "" + }), 200 + + if not profile.get("Developer"): + return jsonify({ + "Error": "Access denied: not a developer", + "Token": "" + }) + + token = jwt.encode({ + "iss": f"{_base_url}/KittySDK", + "sub": str(profile.get("Id")) + }, jwtKey, algorithm="HS256") + + return jsonify({ + "Error": "", + "Token": token, + "User": profile, + }) + +@bp.route("/api/sdk/v1/myrooms", methods=["GET"]) +@getUset +def myrooms(user): + show_all = request.args.get("show_all", "false").lower() == "true" + if show_all: + if user.get("Developer"): + rooms = db.get_all_rooms() + else: + return abort(403) + else: + rooms = db.get_rooms_by_creator(user.get("Id")) + return jsonify(rooms) + +@bp.route("/assetbundles/", methods=["GET"]) +def aassetbundles(path): + try: + return send_from_directory(directory="assetbundles", path=path) + except FileNotFoundError: + return abort(404) + +@bp.route("/api/sdk/v1/upload", methods=["POST"]) +@getUset +def upload(user): + print(request.form) + print(request.files) + + Type = request.form.get("type") + if Type is None: + return abort(400) + if Type == "room": + roomId = request.form.get("roomId") + if roomId is None: + return abort(400) + if not isinstance(roomId, str): + return abort(400) + try: + roomId = int(roomId) + except ValueError: + return abort(400) + sceneName = request.form.get("sceneName") + if sceneName is None: + return abort(400) + if not isinstance(sceneName, str): + return abort(400) + + file = request.files.get("assetBundle") + if file is None: + return abort(400) + + rooms = db.get_all_rooms() if user.get("Developer") else db.get_rooms_by_creator(user.get("Id")) + + room = next((r for r in rooms if r.get("RoomId") == roomId), None) + if not room: + abort(404) + + randomFileName = secure_filename(f"sdk_room_{room.get("Name")}_{uuid.uuid4()}") + if randomFileName is None: + randomFileName = str(uuid.uuid4()) + saveDirectory = "assetbundles" + + os.makedirs(saveDirectory, exist_ok=True) + + file.save(os.path.join(saveDirectory, f"{randomFileName}.assetbundle")) + + db.update_room_field(roomId, "unity_asset_bundle_url", f"https://kittyrec.tabbycluster.net/assetbundles/{randomFileName}.assetbundle") + roomData = db.update_room_field(roomId, "unity_scene_name", sceneName) + + + return jsonify(roomData) + + + + return abort(404) \ No newline at end of file