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