import time from flask import redirect, request, flash, url_for from flask_admin import Admin, AdminIndexView, BaseView, expose from flask_admin.contrib.sqla import ModelView from flask_admin.actions import action import json from markupsafe import Markup from core.admin_auth import ( get_admin_account, has_any_admin_scope, SCOPE_ADMIN, SCOPE_MOD, make_login_redirect, probe_auth_server, EMERGENCY_LOGIN_URL, ) from core.state import db as game_db, ws_registry, session_mgr from core.ban_service import kick_player, cascade_ban, cascade_unban from core.models import sql_db, Profile, Gift, BanLog, Room, AdminTodo, AdminIssue class _AuthMixin: def is_accessible(self): account, scopes = get_admin_account() return account is not None and has_any_admin_scope(scopes) def inaccessible_callback(self, name, **kwargs): if probe_auth_server(): return redirect(EMERGENCY_LOGIN_URL) return redirect(make_login_redirect()) def _get_account(self): return get_admin_account() class HomeView(_AuthMixin, AdminIndexView): @expose("/") def index(self): account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) game_db.log_admin_action( account["username"], "login", f"Admin panel login", request.headers.get("X-Forwarded-For", request.remote_addr or ""), ) try: from core.discord import send_admin send_admin( title="Admin Login", color=0x3498DB, fields=[{"name": "Admin", "value": account["username"], "inline": True}, {"name": "IP", "value": request.headers.get("X-Forwarded-For", request.remote_addr or "?"), "inline": True}], ) except Exception: pass import datetime as _dt today = _dt.datetime.utcnow() today_start = today.strftime("%Y-%m-%d 00:00:00") today_end = today.strftime("%Y-%m-%d 23:59:59") conn = game_db._get_conn() pending_gifts = conn.execute("SELECT COUNT(*) AS c FROM gifts WHERE consumed=0").fetchone()["c"] banned_count = conn.execute("SELECT COUNT(*) AS c FROM profiles WHERE banned=1").fetchone()["c"] total_players = conn.execute("SELECT COUNT(*) AS c FROM profiles").fetchone()["c"] admin_logins_today = conn.execute( "SELECT COUNT(*) AS c FROM admin_action_log WHERE action='login' AND created_at BETWEEN ? AND ?", (today_start, today_end), ).fetchone()["c"] recent_actions = game_db.get_admin_action_log(limit=25) online_ids = ws_registry.connected_ids() profiles_map = game_db.get_profiles_batch(online_ids) online_players = [] for pid in online_ids: p = profiles_map.get(pid) if p: s = session_mgr.get_player_session(pid) online_players.append({ "id": p["Id"], "username": p["Username"], "display_name": p["DisplayName"], "level": p["Level"], "room": s.name if s else "Lobby", "developer": p.get("Developer", False), "screen_mode": ws_registry.is_screen_mode(pid), }) active_sessions = session_mgr.all_public_sessions() return self.render( "admin/index.html", online_count=len(ws_registry.connected_ids()), session_count=len(active_sessions), total_players=total_players, pending_gifts=pending_gifts, banned_count=banned_count, admin_logins_today=admin_logins_today, online_players=online_players, recent_actions=recent_actions, active_sessions=active_sessions, account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, ) _RARITY_LABELS = {0: "Common", 1: "Uncommon", 2: "Rare", 3: "Epic", 4: "Legendary", 5: "Mythic"} _CONTEXT_LABELS = {0: "Admin", 1: "Activity", 2: "Store", 3: "LevelUp"} class ProfileView(_AuthMixin, ModelView): column_list = ["id", "username", "display_name", "level", "xp", "tokens", "developer", "banned", "ban_reason", "created_at"] column_searchable_list = ["username", "display_name", "platform_id"] column_filters = ["banned", "developer", "level", "platform"] column_sortable_list = ["id", "username", "level", "xp", "tokens", "banned", "developer", "created_at"] column_default_sort = ("id", False) column_editable_list = ["tokens", "xp", "level", "developer", "banned"] can_delete = False can_create = False page_size = 50 form_excluded_columns = ["password", "gifts", "ban_logs", "created_at"] column_labels = { "display_name": "Display Name", "ban_reason": "Ban Reason", "banned_until": "Banned Until", "banned_by": "Banned By", "created_at": "Joined", "platform_id": "Platform ID", } column_formatters = { "developer": lambda v, c, m, p: Markup('★ Dev') if m.developer else "", "banned": lambda v, c, m, p: Markup('⛔ Banned') if m.banned else Markup('✓ OK'), "username": lambda v, c, m, p: Markup( f'{m.username}
' f'{m.display_name}
' f'🎁 Gift Item' ), } column_extra_row_actions = [] def after_model_change(self, form, model, is_created): if is_created: return account, _ = get_admin_account() name = account.get("username", "admin") if account else "admin" changed_fields = [f for f in form.data if f not in ("csrf_token",) and getattr(model, f, None) is not None] game_db.log_admin_action(name, "edit_profile", f"Edited profile {model.username} (id={model.id}): fields={', '.join(changed_fields)}", request.headers.get("X-Forwarded-For", request.remote_addr or "")) if getattr(model, "banned", False): reason = model.ban_reason or "Admin ban (inline)" cascade_ban(model.id, reason, 0, name) else: cascade_unban(model.id, name) def _ip(self): return request.headers.get("X-Forwarded-For", request.remote_addr or "") @action("ban_1h", "Ban (1 hour)") def action_ban_1h(self, ids): account, _ = self._get_account() name = account.get("username", "admin") if account else "admin" reason = (request.form.get("ban_reason") or "Admin ban")[:256] for id in ids: p = game_db.get_profile(int(id)) game_db.ban_player(int(id), reason=reason, duration_hours=1, admin_name=name) cascade_ban(int(id), reason, 1, name) game_db.log_admin_action(name, "ban_1h", f"Banned {p['Username'] if p else id}: {reason}", self._ip()) try: from core.discord import send_admin names = ", ".join(game_db.get_profile(int(i))["Username"] for i in ids if game_db.get_profile(int(i))) send_admin(title="Players Banned (1h)", color=0xE74C3C, fields=[{"name": "Players", "value": names or str(ids), "inline": False}, {"name": "Reason", "value": reason, "inline": False}, {"name": "By", "value": name, "inline": True}]) except Exception: pass flash(f"Banned {len(ids)} player(s) for 1 hour.", "success") @action("ban_day", "Ban (1 day)") def action_ban_day(self, ids): account, _ = self._get_account() name = account.get("username", "admin") if account else "admin" reason = (request.form.get("ban_reason") or "Admin ban")[:256] for id in ids: p = game_db.get_profile(int(id)) game_db.ban_player(int(id), reason=reason, duration_hours=24, admin_name=name) cascade_ban(int(id), reason, 24, name) game_db.log_admin_action(name, "ban_1d", f"Banned {p['Username'] if p else id}: {reason}", self._ip()) try: from core.discord import send_admin names = ", ".join(game_db.get_profile(int(i))["Username"] for i in ids if game_db.get_profile(int(i))) send_admin(title="Players Banned (24h)", color=0xE74C3C, fields=[{"name": "Players", "value": names or str(ids), "inline": False}, {"name": "Reason", "value": reason, "inline": False}, {"name": "By", "value": name, "inline": True}]) except Exception: pass flash(f"Banned {len(ids)} player(s) for 24 hours.", "success") @action("ban_week", "Ban (1 week)") def action_ban_week(self, ids): account, _ = self._get_account() name = account.get("username", "admin") if account else "admin" reason = (request.form.get("ban_reason") or "Admin ban")[:256] for id in ids: p = game_db.get_profile(int(id)) game_db.ban_player(int(id), reason=reason, duration_hours=168, admin_name=name) cascade_ban(int(id), reason, 168, name) game_db.log_admin_action(name, "ban_1w", f"Banned {p['Username'] if p else id}: {reason}", self._ip()) try: from core.discord import send_admin names = ", ".join(game_db.get_profile(int(i))["Username"] for i in ids if game_db.get_profile(int(i))) send_admin(title="Players Banned (1 week)", color=0xE74C3C, fields=[{"name": "Players", "value": names or str(ids), "inline": False}, {"name": "Reason", "value": reason, "inline": False}, {"name": "By", "value": name, "inline": True}]) except Exception: pass flash(f"Banned {len(ids)} player(s) for 1 week.", "success") @action("permaban", "Permanent Ban") def action_permaban(self, ids): account, scopes = self._get_account() if SCOPE_ADMIN not in scopes: flash("Requires kittyrec.admin scope.", "error") return name = account.get("username", "admin") if account else "admin" reason = (request.form.get("ban_reason") or "Permanent ban")[:256] for id in ids: p = game_db.get_profile(int(id)) game_db.ban_player(int(id), reason=reason, duration_hours=0, admin_name=name) cascade_ban(int(id), reason, 0, name) game_db.log_admin_action(name, "permaban", f"Permabanned {p['Username'] if p else id}: {reason}", self._ip()) try: from core.discord import send_admin names = ", ".join(game_db.get_profile(int(i))["Username"] for i in ids if game_db.get_profile(int(i))) send_admin(title="Players Permabanned", color=0x7F0000, fields=[{"name": "Players", "value": names or str(ids), "inline": False}, {"name": "Reason", "value": reason, "inline": False}, {"name": "By", "value": name, "inline": True}]) except Exception: pass flash(f"Permanently banned {len(ids)} player(s).", "success") @action("unban", "Unban", "Unban selected players?") def action_unban(self, ids): account, scopes = self._get_account() if SCOPE_ADMIN not in scopes: flash("Requires kittyrec.admin scope.", "error") return name = account.get("username", "admin") if account else "admin" from core.anticheat import reset_offenses for id in ids: p = game_db.get_profile(int(id)) cascade_unban(int(id), name) reset_offenses(int(id)) game_db.log_admin_action(name, "unban", f"Unbanned {p['Username'] if p else id}", self._ip()) try: from core.discord import send_admin names = ", ".join(game_db.get_profile(int(i))["Username"] for i in ids if game_db.get_profile(int(i))) send_admin(title="Players Unbanned", color=0x2ECC71, fields=[{"name": "Players", "value": names or str(ids), "inline": False}, {"name": "By", "value": name, "inline": True}]) except Exception: pass flash(f"Unbanned {len(ids)} player(s).", "success") @action("toggle_dev", "Toggle Developer", "Toggle developer flag?") def action_toggle_dev(self, ids): account, scopes = self._get_account() if SCOPE_ADMIN not in scopes: flash("Requires kittyrec.admin scope.", "error") return name = account.get("username", "admin") if account else "admin" for id in ids: p = game_db.get_profile(int(id)) if p: game_db.set_developer(int(id), not p.get("Developer")) game_db.log_admin_action(name, "toggle_dev", f"Toggled dev for {p['Username']}", self._ip()) flash(f"Toggled developer for {len(ids)} player(s).", "success") @action("disconnect", "Disconnect (WebSocket)", "Disconnect WebSocket for selected players?") def action_disconnect(self, ids): account, _ = self._get_account() name = account.get("username", "admin") if account else "admin" for id in ids: p = game_db.get_profile(int(id)) kick_player(int(id)) game_db.log_admin_action(name, "disconnect", f"Disconnected {p['Username'] if p else id}", self._ip()) flash(f"Disconnected {len(ids)} player(s).", "success") @action("gift_xp", "Gift 1000 XP", "Send 1000 XP gift to selected players?") def action_gift_xp(self, ids): account, scopes = self._get_account() if SCOPE_ADMIN not in scopes: flash("Requires kittyrec.admin scope.", "error") return name = account.get("username", "admin") if account else "admin" from core.ws_helpers import push_gift for id in ids: p = game_db.get_profile(int(id)) gift = game_db.add_gift(int(id), xp=1000, gift_rarity=10, message="Gift from KittyRec admin", gift_context=0) push_gift(int(id), gift) game_db.log_admin_action(name, "gift_xp", f"Gifted 1000 XP to {p['Username'] if p else id}", self._ip()) flash(f"Sent 1000 XP gift to {len(ids)} player(s).", "success") @action("gift_tokens", "Gift 100 Tokens", "Send 100 RecCenterTokens to selected players?") def action_gift_tokens(self, ids): account, scopes = self._get_account() if SCOPE_ADMIN not in scopes: flash("Requires kittyrec.admin scope.", "error") return name = account.get("username", "admin") if account else "admin" from core.ws_helpers import push_gift for id in ids: p = game_db.get_profile(int(id)) gift = game_db.add_gift(int(id), gift_rarity=10, currency_type=2, currency=100, message="Tokens from KittyRec admin", gift_context=0) push_gift(int(id), gift) game_db.log_admin_action(name, "gift_tokens", f"Gifted 100 tokens to {p['Username'] if p else id}", self._ip()) flash(f"Sent 100 tokens to {len(ids)} player(s).", "success") @action("reset_password", "Reset Password", "Generate a new temp password and DM it to selected players?") def action_reset_password(self, ids): account, scopes = self._get_account() if SCOPE_ADMIN not in scopes: flash("Requires kittyrec.admin scope.", "error") return name = account.get("username", "admin") if account else "admin" import secrets, string from werkzeug.security import generate_password_hash _KITTYREC_PID = 23 alphabet = string.ascii_letters + string.digits for id in ids: pid = int(id) p = game_db.get_profile(pid) if not p: continue temp_pass = "".join(secrets.choice(alphabet) for _ in range(8)) conn = game_db._get_conn() conn.execute("UPDATE profiles SET password=? WHERE id=?", (generate_password_hash(temp_pass), pid)) conn.commit() username = p.get("Username", f"Player{pid}") thread_id = game_db.get_or_create_chat([_KITTYREC_PID, pid]) msg_text = ( 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 set it!" ) msg_id = game_db.send_chat_message(thread_id, _KITTYREC_PID, msg_text) msg = game_db.get_chat_message(msg_id) ws_registry.send(pid, {"Id": 90, "Msg": msg}) game_db.log_admin_action(name, "reset_password", f"Reset password for {username} (id={pid})", self._ip()) print(f"[Admin] {name} reset password for pid={pid} ({username})") flash(f"Reset password for {len(ids)} player(s) and sent DM.", "success") @action("temp_password", "Get Temp Password", "Generate a temp password and show it here (for offline players)?") def action_temp_password(self, ids): account, scopes = self._get_account() if SCOPE_ADMIN not in scopes: flash("Requires kittyrec.admin scope.", "error") return name = account.get("username", "admin") if account else "admin" import secrets, string from werkzeug.security import generate_password_hash alphabet = string.ascii_letters + string.digits results = [] for id in ids: pid = int(id) p = game_db.get_profile(pid) if not p: continue temp_pass = "".join(secrets.choice(alphabet) for _ in range(10)) conn = game_db._get_conn() conn.execute("UPDATE profiles SET password=? WHERE id=?", (generate_password_hash(temp_pass), pid)) conn.commit() username = p.get("Username", f"Player{pid}") results.append(f"{username}: {temp_pass}") game_db.log_admin_action(name, "temp_password", f"Generated temp password for {username} (id={pid})", self._ip()) print(f"[Admin] {name} generated temp password for pid={pid} ({username})") if results: creds = " | ".join(results) flash(Markup(f'Temp passwords generated — {creds}'), "success") else: flash("No valid players selected.", "warning") @action("send_notification", "Send Notification", "Send an in-game notification to selected players?") def action_send_notification(self, ids): account, scopes = self._get_account() if not has_any_admin_scope(scopes): flash("Requires admin or mod scope.", "error") return name = account.get("username", "admin") if account else "admin" message = request.form.get("notification_message", "").strip() if not message: message = "Hello from KittyRec admin!" from routes.portal import _send_system_message sent = 0 for id in ids: pid = int(id) p = game_db.get_profile(pid) if not p: continue _send_system_message(pid, message) sent += 1 game_db.log_admin_action(name, "send_notification", f"Sent notification to {sent} player(s): {message[:80]}", self._ip()) flash(f"Sent notification to {sent} player(s).", "success") @action("delete_accounts", "Delete Accounts", "PERMANENTLY delete selected accounts? This cannot be undone.") def action_delete_accounts(self, ids): account, scopes = self._get_account() if SCOPE_ADMIN not in scopes: flash("Requires kittyrec.admin scope.", "error") return name = account.get("username", "admin") if account else "admin" deleted = [] for id in ids: pid = int(id) p = game_db.get_profile(pid) username = p["Username"] if p else str(pid) kick_player(pid) game_db.delete_profile(pid) game_db.log_admin_action(name, "delete_account", f"Deleted account {username} (id={pid})", self._ip()) deleted.append(username) try: from core.discord import send_admin send_admin(title="Accounts Deleted", color=0xE74C3C, fields=[{"name": "Accounts", "value": ", ".join(deleted) or "none", "inline": False}, {"name": "By", "value": name, "inline": True}]) except Exception: pass flash(f"Deleted {len(deleted)} account(s): {', '.join(deleted)}", "success") class GiftView(_AuthMixin, ModelView): can_create = False can_edit = False can_delete = False column_list = ["id", "profile_id", "xp", "gift_rarity", "avatar_item_desc", "consumable_item_desc", "equipment_prefab_name", "message", "gift_context", "consumed", "created_at"] column_searchable_list = ["avatar_item_desc", "consumable_item_desc", "equipment_prefab_name", "message"] column_filters = ["consumed", "gift_rarity", "gift_context", "profile_id"] column_default_sort = ("id", True) page_size = 50 column_labels = { "profile_id": "Player", "gift_rarity": "Rarity", "avatar_item_desc": "Avatar Item", "consumable_item_desc": "Consumable", "equipment_prefab_name": "Equipment", "gift_context": "Context", } column_formatters = { "gift_rarity": lambda v, c, m, p: _RARITY_LABELS.get(m.gift_rarity, str(m.gift_rarity)), "gift_context": lambda v, c, m, p: _CONTEXT_LABELS.get(m.gift_context, str(m.gift_context)), "consumed": lambda v, c, m, p: Markup('Opened') if m.consumed else Markup('Pending'), } def _ip(self): return request.headers.get("X-Forwarded-For", request.remote_addr or "") @expose("/gift-item/", methods=["GET", "POST"]) def gift_item_view(self): import json, os account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) if SCOPE_ADMIN not in scopes: flash("Requires kittyrec.admin scope.", "error") return redirect(self.get_url(".index_view")) player_id = int(request.args.get("player_id", 0) or request.form.get("player_id", 0)) player = game_db.get_profile(player_id) if player_id else None data_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data") with open(os.path.join(data_dir, "avataritems.json")) as f: all_items = json.load(f) custom_items_only = [] try: with open(os.path.join(data_dir, "custom_items.json")) as f: _raw_custom = json.load(f) custom_items_only = [ dict(i, AvatarItemDesc=i["AvatarItemDesc"] if "," in i["AvatarItemDesc"] else i["AvatarItemDesc"] + ",,,") for i in _raw_custom if i.get("AvatarItemDesc") ] all_items = all_items + custom_items_only except Exception: pass try: with open(os.path.join(data_dir, "custom_swatches.json")) as f: all_items = all_items + json.load(f) except Exception: pass try: with open(os.path.join(data_dir, "consumables.json")) as f: all_consumables = json.load(f) except Exception: all_consumables = [] try: with open(os.path.join(data_dir, "equipment.json")) as f: all_equipment = json.load(f) except Exception: all_equipment = [] error = None success = None if request.method == "POST": gift_type = request.form.get("gift_type", "item") rarity = int(request.form.get("rarity", 1) or 1) message = request.form.get("message", "Gift from KittyRec admin").strip() or "Gift from KittyRec admin" xp = int(request.form.get("xp", 0) or 0) level = int(request.form.get("level", 0) or 0) name = account.get("username", "admin") if not player: error = "Player not found." elif gift_type == "tokens": tokens = int(request.form.get("tokens", 0) or 0) if tokens <= 0: error = "Token amount must be > 0." else: from core.ws_helpers import push_gift gift = game_db.add_gift( player_id, gift_rarity=rarity, currency_type=2, currency=tokens, xp=xp, level=level, message=message, gift_context=0, ) push_gift(player_id, gift) game_db.log_admin_action(name, "gift_tokens", f"Gifted {tokens} tokens to {player['Username'] if player else player_id}", self._ip()) success = f"Sent {tokens} tokens to {player['Username']}!" elif gift_type == "consumable": consumable_desc = request.form.get("consumable_desc", "").strip() if not consumable_desc: error = "Must select a consumable." else: from core.ws_helpers import push_gift gift = game_db.add_gift( player_id, xp=xp, level=level, gift_rarity=rarity, consumable_item_desc=consumable_desc, message=message, gift_context=0, ) push_gift(player_id, gift) game_db.log_admin_action(name, "gift_consumable", f"Gifted consumable '{consumable_desc}' to {player['Username'] if player else player_id}", self._ip()) success = f"Consumable sent to {player['Username']}!" elif gift_type == "equipment": equip_prefab = request.form.get("equip_prefab", "").strip() equip_guid = request.form.get("equip_guid", "").strip() if not equip_prefab or not equip_guid: error = "Must select an equipment item." else: from core.ws_helpers import push_gift gift = game_db.add_gift( player_id, xp=xp, level=level, gift_rarity=rarity, equipment_prefab_name=equip_prefab, equipment_modification_guid=equip_guid, message=message, gift_context=0, ) push_gift(player_id, gift) game_db.log_admin_action(name, "gift_equipment", f"Gifted equipment '{equip_prefab}' to {player['Username'] if player else player_id}", self._ip()) success = f"Equipment sent to {player['Username']}!" else: item_desc = request.form.get("item_desc", "").strip() if not item_desc and xp <= 0 and level <= 0: error = "Must provide an item, XP > 0, or level > 0." else: from core.ws_helpers import push_gift gift = game_db.add_gift( player_id, xp=xp, level=level, gift_rarity=rarity, avatar_item_desc=item_desc, message=message, gift_context=0, ) push_gift(player_id, gift) game_db.log_admin_action(name, "gift_item", f"Gifted item '{item_desc or 'xp/level only'}' ({xp} XP, {level} levels, rarity {rarity}) to {player['Username'] if player else player_id}", self._ip()) success = f"Gift sent to {player['Username']}!" return self.render( "admin/gift_item.html", player=player, player_id=player_id, all_items=all_items, custom_items_only=custom_items_only, all_consumables=all_consumables, all_equipment=all_equipment, error=error, success=success, account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, ) class BanLogView(_AuthMixin, ModelView): can_create = False can_edit = False can_delete = False column_list = ["id", "profile_id", "action", "reason", "duration_hours", "banned_until", "admin_name", "created_at"] column_filters = ["action", "admin_name", "profile_id"] column_default_sort = ("id", True) page_size = 50 column_labels = { "profile_id": "Player", "admin_name": "By Admin", "duration_hours": "Duration (h)", } column_formatters = { "action": lambda v, c, m, p: Markup( f'BAN' if m.action == "ban" else f'UNBAN' ), "duration_hours": lambda v, c, m, p: "Permanent" if m.duration_hours == 0 and m.action == "ban" else (f"{m.duration_hours}h" if m.duration_hours else "—"), } class RoomView(_AuthMixin, ModelView): can_create = False can_edit = True can_delete = True column_list = ["id", "name", "creator_id", "activity_level_id", "is_sandbox", "max_players", "special_gamemode", "accessibility", "created_at"] column_searchable_list = ["name", "description", "activity_level_id"] column_filters = ["is_sandbox", "accessibility", "special_gamemode"] column_default_sort = ("modified_at", True) column_labels = {"special_gamemode": "Gamemode Flags"} form_columns = ["name", "creator_id", "description", "activity_level_id", "max_players", "accessibility", "is_sandbox", "instanced", "special_gamemode", "state"] page_size = 50 class RoomsManageView(_AuthMixin, BaseView): @expose("/", methods=["GET", "POST"]) def index(self): account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) from core.constants import KNOWN_ACTIVITIES, specialGameMode error = None success = None if request.method == "POST" and SCOPE_ADMIN in scopes: action_type = request.form.get("action_type", "create") if action_type == "create": name = request.form.get("name", "").strip()[:128] activity_level_id = request.form.get("activity_level_id", "").strip() max_players = max(1, min(40, int(request.form.get("max_players", 10) or 10))) is_sandbox = request.form.get("is_sandbox") == "1" if not name: error = "Room name is required." elif not activity_level_id: error = "Activity Level ID is required." elif game_db.get_room_by_name(name): error = f"A room named '{name}' already exists." else: room = game_db.create_room( creator_id=1, name=name, activity_level_id=activity_level_id, max_players=max_players, is_sandbox=is_sandbox, ) admin_name = account.get("username", "admin") game_db.log_admin_action(admin_name, "create_room", f"Created room '{name}' (id={room['RoomId']}, activity={activity_level_id})", request.headers.get("X-Forwarded-For", request.remote_addr or "")) success = f"Room '{name}' created (id={room['RoomId']})." elif action_type == "delete": room_id = int(request.form.get("room_id", 0) or 0) if room_id: room = game_db.get_room(room_id) if room: game_db.delete_room(room_id) admin_name = account.get("username", "admin") game_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 "")) success = f"Room deleted." all_rooms = game_db.get_all_rooms() activities = {guid: info[0] for guid, info in KNOWN_ACTIVITIES.items()} for r in all_rooms: alid = r.get("ActivityLevelId", "") if alid and alid not in activities: activities[alid] = r.get("Name", alid[:12]) gamemode_defaults = game_db.get_all_gamemode_defaults() gamemode_flags = [{"name": m.name.replace("_", " "), "value": m.value} for m in specialGameMode if m.value > 0] disabled_activities = set(game_db.get_all_disabled_activities()) return self.render( "admin/rooms_manage.html", all_rooms=all_rooms, activities=activities, gamemode_defaults=gamemode_defaults, gamemode_flags=gamemode_flags, disabled_activities=disabled_activities, error=error, success=success, account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, ) class CdnView(_AuthMixin, BaseView): @expose("/", methods=["GET"]) def index(self): account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) return self.render( "admin/cdn_view.html", account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, ) class DownloadsView(_AuthMixin, BaseView): @expose("/", methods=["GET"]) def index(self): account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) return self.render( "admin/downloads_view.html", account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, ) class DllArchiveView(_AuthMixin, BaseView): @expose("/", methods=["GET"]) def index(self): account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) return self.render( "admin/dll_archive.html", account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, ) class SessionsView(_AuthMixin, BaseView): @expose("/") def index(self): account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) active = session_mgr.all_public_sessions() all_pids = [pid for s in active for pid in s.players] profiles_map = game_db.get_profiles_batch(all_pids) details = [] for s in active: players = [profiles_map[pid] for pid in s.players if pid in profiles_map] details.append({"session": s, "players": players}) return self.render( "admin/sessions_view.html", details=details, online_count=len(ws_registry.connected_ids()), account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, ) class StoreView(_AuthMixin, BaseView): @expose("/", methods=["GET", "POST"]) def index(self): account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) from routes.storefronts import ( reroll_store, _current_store_items, _RARITY_PRICE, _ROTATION_WINDOW_SECS, _store_seed_offset, _store_item_map, ) if request.method == "POST" and SCOPE_ADMIN in scopes: action_type = request.form.get("action_type", "reroll") _ip = request.headers.get("X-Forwarded-For", request.remote_addr or "") if action_type == "reroll": offset = reroll_store() game_db.log_admin_action(account.get("username", "admin"), "reroll_store", f"Rerolled store (offset={offset})", _ip) flash(f"Store rerolled! (seed offset: {offset})", "success") elif action_type == "pin": gift_drop_id = int(request.form.get("gift_drop_id", 0) or 0) slot = int(request.form.get("slot", 0) or 0) if gift_drop_id and 0 <= slot <= 7: item = _store_item_map().get(gift_drop_id) if item: game_db.set_store_featured(slot, gift_drop_id) game_db.log_admin_action(account.get("username", "admin"), "store_pin", f"Pinned '{item['FriendlyName']}' (id={gift_drop_id}) to slot {slot}", _ip) flash(f"Pinned '{item['FriendlyName']}' to slot {slot}.", "success") else: flash("Item not found.", "error") else: flash("Invalid gift_drop_id or slot (0-7).", "error") elif action_type == "unpin": slot = request.form.get("slot") if slot == "all": game_db.clear_store_featured() game_db.log_admin_action(account.get("username", "admin"), "store_unpin", "Cleared all pinned store slots", _ip) flash("Cleared all pinned items.", "success") elif slot is not None: game_db.clear_store_featured(int(slot)) game_db.log_admin_action(account.get("username", "admin"), "store_unpin", f"Unpinned store slot {slot}", _ip) flash(f"Unpinned slot {slot}.", "success") current = _current_store_items() secs_left = _ROTATION_WINDOW_SECS - (int(time.time()) % _ROTATION_WINDOW_SECS) featured = game_db.get_store_featured() all_items = sorted(_store_item_map().values(), key=lambda x: x["FriendlyName"]) return self.render( "admin/store_view.html", current=current, rarity_prices=_RARITY_PRICE, secs_left=secs_left, seed_offset=_store_seed_offset, featured=featured, all_items=all_items, account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, ) class TexturesView(_AuthMixin, BaseView): _ASSET_CATEGORIES = { "Texture2D": {"exts": (".png",), "label": "Textures"}, "Sprite": {"exts": (".png",), "label": "Sprites"}, "AudioClip": {"exts": (".ogg", ".wav", ".mp3", ".fsb", "."), "label": "Audio"}, "Font": {"exts": (".ttf", ".otf"), "label": "Fonts"}, "TextAsset": {"exts": (".txt", ".json", ".xml", ".bytes", "."), "label": "Text Assets"}, "Shader": {"exts": (".shader",), "label": "Shaders"}, "MonoBehaviour": {"exts": (".json",), "label": "MonoBehaviours"}, } @expose("/") def index(self): import os account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) extracted_base = os.path.join(os.path.dirname(os.path.dirname(__file__)), "gamecode", "extracted") category = request.args.get("cat", "Texture2D") if category not in self._ASSET_CATEGORIES: category = "Texture2D" asset_dir = os.path.join(extracted_base, category) search = request.args.get("q", "").strip().lower() page = max(1, int(request.args.get("page", 1))) per_page = 60 try: all_files = sorted(os.listdir(asset_dir)) except FileNotFoundError: all_files = [] if search: all_files = [f for f in all_files if search in f.lower()] total = len(all_files) pages = max(1, (total + per_page - 1) // per_page) page = min(page, pages) files = all_files[(page - 1) * per_page: page * per_page] cat_counts = {} for cat_name in self._ASSET_CATEGORIES: cat_dir = os.path.join(extracted_base, cat_name) try: cat_counts[cat_name] = len(os.listdir(cat_dir)) except FileNotFoundError: cat_counts[cat_name] = 0 return self.render( "admin/textures_view.html", files=files, search=search, page=page, pages=pages, total=total, category=category, categories=self._ASSET_CATEGORIES, cat_counts=cat_counts, account=account, scopes=scopes, ) class ConsoleView(_AuthMixin, BaseView): @expose("/") def index(self): import os log_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "server.log") initial = "" try: with open(log_path, "rb") as f: f.seek(0, 2) size = f.tell() start = max(0, size - 128 * 1024) f.seek(start) initial = f.read().decode("utf-8", errors="replace") except Exception: pass return self.render("admin/console_view.html", initial_log=initial, initial_pos=size if initial else 0) class EventsView(_AuthMixin, BaseView): @expose("/") def index(self): account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) from core.constants import KNOWN_ACTIVITIES activities = {guid: info[0] for guid, info in KNOWN_ACTIVITIES.items()} return self.render( "admin/events_view.html", account=account, scopes=scopes, activities=activities, SCOPE_ADMIN=SCOPE_ADMIN, ) class SwatchesView(_AuthMixin, BaseView): @expose("/", methods=["GET", "POST"]) def index(self): import json as _json, os as _os account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) data_dir = _os.path.join(_os.path.dirname(_os.path.dirname(__file__)), "data") swatches_path = _os.path.join(data_dir, "custom_swatches.json") items_path = _os.path.join(data_dir, "avataritems.json") error = None success = None if request.method == "POST" and SCOPE_ADMIN in scopes: action_type = request.form.get("action_type", "add") try: with open(swatches_path) as f: swatches = _json.load(f) except Exception: swatches = [] if action_type == "add": base_guid = request.form.get("base_guid", "").strip() swatch_guid = request.form.get("swatch_guid", "").strip() friendly_name = request.form.get("friendly_name", "").strip() if not base_guid or not swatch_guid or not friendly_name: error = "All fields required." else: desc = f"{base_guid},{swatch_guid},," if any(s["AvatarItemDesc"] == desc for s in swatches): error = "Swatch already exists." else: swatches.append({"AvatarItemDesc": desc, "FriendlyName": friendly_name}) with open(swatches_path, "w") as f: _json.dump(swatches, f, indent=2) from routes.avatar import _reload_items_cache _reload_items_cache() success = f"Added swatch '{friendly_name}'." elif action_type == "delete": desc = request.form.get("desc", "") swatches = [s for s in swatches if s["AvatarItemDesc"] != desc] with open(swatches_path, "w") as f: _json.dump(swatches, f, indent=2) from routes.avatar import _reload_items_cache _reload_items_cache() success = "Swatch deleted." try: with open(swatches_path) as f: swatches = _json.load(f) except Exception: swatches = [] try: with open(items_path) as f: base_items = _json.load(f) except Exception: base_items = [] return self.render( "admin/swatches_view.html", swatches=swatches, base_items=base_items, error=error, success=success, account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, ) class AvatarItemsView(_AuthMixin, BaseView): @expose("/", methods=["GET", "POST"]) def index(self): import json as _json, os as _os account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) data_dir = _os.path.join(_os.path.dirname(_os.path.dirname(__file__)), "data") custom_items_path = _os.path.join(data_dir, "custom_items.json") base_items_path = _os.path.join(data_dir, "avataritems.json") swatches_path = _os.path.join(data_dir, "custom_swatches.json") error = None success = None def _load_custom(): try: with open(custom_items_path) as f: return _json.load(f) except Exception: return [] def _save_custom(items): with open(custom_items_path, "w") as f: _json.dump(items, f, indent=2) from routes.avatar import _reload_items_cache _reload_items_cache() if request.method == "POST" and SCOPE_ADMIN in scopes: action_type = request.form.get("action_type", "add") custom = _load_custom() if action_type == "add": item_id = request.form.get("item_id", "").strip() friendly_name = request.form.get("friendly_name", "").strip()[:128] starter = request.form.get("starter") == "1" if not item_id or not friendly_name: error = "Item ID and Friendly Name are required." else: try: with open(base_items_path) as f: base_items = _json.load(f) except Exception: base_items = [] try: with open(swatches_path) as f: swatches = _json.load(f) except Exception: swatches = [] all_existing_guids = { i.get("AvatarItemDesc", "").split(",")[0] for i in base_items + swatches + custom } if item_id in all_existing_guids: error = f"Item ID '{item_id}' already exists." else: custom.append({ "AvatarItemDesc": item_id, "FriendlyName": friendly_name, "Starter": starter, }) _save_custom(custom) admin_name = account.get("username", "admin") game_db.log_admin_action(admin_name, "add_avatar_item", f"Added avatar item '{friendly_name}' (id={item_id}, starter={starter})", request.headers.get("X-Forwarded-For", request.remote_addr or "")) success = f"Added '{friendly_name}'." elif action_type == "toggle_starter": item_id = request.form.get("item_id", "") for item in custom: if item.get("AvatarItemDesc", "").split(",")[0] == item_id: item["Starter"] = not item.get("Starter", False) admin_name = account.get("username", "admin") game_db.log_admin_action(admin_name, "toggle_starter_item", f"Toggled starter for avatar item '{item.get('FriendlyName', item_id)}' (starter={item['Starter']})", request.headers.get("X-Forwarded-For", request.remote_addr or "")) success = f"Starter toggled for '{item.get('FriendlyName', item_id)}'." break else: error = "Item not found." if not error: _save_custom(custom) elif action_type == "delete": item_id = request.form.get("item_id", "") before = len(custom) custom = [i for i in custom if i.get("AvatarItemDesc", "").split(",")[0] != item_id] if len(custom) < before: _save_custom(custom) admin_name = account.get("username", "admin") game_db.log_admin_action(admin_name, "delete_avatar_item", f"Deleted avatar item id={item_id}", request.headers.get("X-Forwarded-For", request.remote_addr or "")) success = "Item deleted." else: error = "Item not found." custom = _load_custom() return self.render( "admin/avatar_items_view.html", custom_items=custom, error=error, success=success, account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, ) class kittyrecModView(_AuthMixin, BaseView): _DLLS_PATH = None def _dlls_path(self): import os as _os return _os.path.join(_os.path.dirname(_os.path.dirname(__file__)), "data", "KittyRecDlls.json") def _dlls_dir(self): import os as _os return _os.path.join(_os.path.dirname(_os.path.dirname(__file__)), "kittyrec_dlls") @expose("/", methods=["GET", "POST"]) def index(self): import os as _os, hashlib as _hashlib, uuid as _uuid account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) from core.constants import BRANCHS error = None success = None dlls_path = self._dlls_path() dlls_dir = self._dlls_dir() try: with open(dlls_path) as f: dll_data = json.load(f) except Exception: dll_data = {k: None for k in BRANCHS} if request.method == "POST" and SCOPE_ADMIN in scopes: branch_id = request.form.get("branch_id", "").strip() action_type = request.form.get("action_type", "upload") if branch_id not in BRANCHS: error = "Invalid branch." elif action_type == "clear": dll_data[branch_id] = None with open(dlls_path, "w") as f: json.dump(dll_data, f, indent=4) success = f"Cleared {BRANCHS[branch_id]}." elif action_type == "upload": f = request.files.get("dll_file") if not f or not f.filename: error = "No file selected." else: data = f.read() sha512 = _hashlib.sha512(data).hexdigest() new_filename = str(_uuid.uuid4()) + ".dll" dest = _os.path.join(dlls_dir, new_filename) with open(dest, "wb") as out: out.write(data) old = dll_data.get(branch_id) dll_data[branch_id] = {"file": new_filename, "hash": sha512} with open(dlls_path, "w") as out: json.dump(dll_data, out, indent=4) if old and old.get("file"): old_path = _os.path.join(dlls_dir, old["file"]) try: _os.remove(old_path) except Exception: pass name = account.get("username", "admin") game_db.log_admin_action(name, "dll_upload", f"Uploaded DLL for branch {BRANCHS[branch_id]}: {new_filename}", request.headers.get("X-Forwarded-For", request.remote_addr or "")) try: from core.discord import send_admin send_admin(title="DLL Uploaded", color=0xE67E22, fields=[{"name": "Branch", "value": BRANCHS[branch_id], "inline": True}, {"name": "By", "value": name, "inline": True}, {"name": "Size", "value": f"{len(data):,} bytes", "inline": True}, {"name": "SHA512", "value": f"`{sha512[:32]}...`", "inline": False}]) except Exception: pass success = f"Uploaded to {BRANCHS[branch_id]} ({len(data):,} bytes)." return self.render( "admin/kittyrecMod.html", account=account, scopes=scopes, branchs=BRANCHS, dll_data=dll_data, error=error, success=success, SCOPE_ADMIN=SCOPE_ADMIN, ) _PRIORITY_LABELS = {0: "Low", 1: "Medium", 2: "High", 3: "Critical"} _PRIORITY_COLORS = {0: "secondary", 1: "info", 2: "warning", 3: "danger"} _STATUS_COLORS = {"open": "primary", "in_progress": "warning", "done": "success", "closed": "secondary", "reported": "primary", "confirmed": "info", "investigating": "warning", "resolved": "success", "wontfix": "secondary"} _SEVERITY_COLORS = {"low": "secondary", "medium": "info", "high": "warning", "critical": "danger"} class TodoView(_AuthMixin, ModelView): can_create = True can_edit = True can_delete = True column_list = ["id", "title", "priority", "status", "assigned_to", "created_by", "created_at", "completed_at"] column_searchable_list = ["title", "description", "assigned_to", "created_by"] column_filters = ["status", "priority", "assigned_to"] column_default_sort = [("status", False), ("priority", True)] column_editable_list = ["assigned_to"] page_size = 50 form_excluded_columns = ["created_at", "completed_at"] column_labels = { "assigned_to": "Assigned To", "created_by": "Created By", "created_at": "Created", "completed_at": "Completed", } form_choices = { "status": [("open", "Open"), ("in_progress", "In Progress"), ("done", "Done"), ("closed", "Closed")], "priority": [(0, "Low"), (1, "Medium"), (2, "High"), (3, "Critical")], } column_formatters = { "priority": lambda v, c, m, p: Markup(f'{_PRIORITY_LABELS.get(m.priority, "?")}'), "status": lambda v, c, m, p: Markup(f'{m.status.replace("_", " ").title()}'), "title": lambda v, c, m, p: Markup(f'{m.title}' + (f'
{m.description[:80]}...' if m.description and len(m.description) > 80 else (f'
{m.description}' if m.description else ''))), } def on_model_change(self, form, model, is_created): if is_created: import datetime account, _ = get_admin_account() model.created_at = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") model.created_by = account.get("username", "admin") if account else "admin" if model.status == "done" and not model.completed_at: import datetime model.completed_at = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") elif model.status != "done": model.completed_at = None @action("mark_done", "Mark Done", "Mark selected todos as done?") def action_mark_done(self, ids): import datetime now = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") for id in ids: todo = sql_db.session.query(AdminTodo).get(int(id)) if todo: todo.status = "done" todo.completed_at = now sql_db.session.commit() flash(f"Marked {len(ids)} todo(s) as done.", "success") @action("mark_open", "Reopen", "Reopen selected todos?") def action_mark_open(self, ids): for id in ids: todo = sql_db.session.query(AdminTodo).get(int(id)) if todo: todo.status = "open" todo.completed_at = None sql_db.session.commit() flash(f"Reopened {len(ids)} todo(s).", "success") class IssueView(_AuthMixin, ModelView): can_create = True can_edit = True can_delete = True column_list = ["id", "title", "category", "severity", "status", "reported_by", "assigned_to", "created_at", "resolved_at"] column_searchable_list = ["title", "description", "reported_by", "assigned_to"] column_filters = ["status", "category", "severity", "assigned_to"] column_default_sort = [("status", False), ("severity", True)] column_editable_list = ["assigned_to"] page_size = 50 form_excluded_columns = ["created_at", "resolved_at"] column_labels = { "reported_by": "Reported By", "assigned_to": "Assigned To", "created_at": "Created", "resolved_at": "Resolved", } form_choices = { "status": [("open", "Open"), ("confirmed", "Confirmed"), ("investigating", "Investigating"), ("resolved", "Resolved"), ("wontfix", "Won't Fix"), ("closed", "Closed")], "category": [("bug", "Bug"), ("crash", "Crash"), ("exploit", "Exploit"), ("performance", "Performance"), ("feature", "Feature Request"), ("other", "Other")], "severity": [("low", "Low"), ("medium", "Medium"), ("high", "High"), ("critical", "Critical")], } column_formatters = { "severity": lambda v, c, m, p: Markup(f'{m.severity.title()}'), "status": lambda v, c, m, p: Markup(f'{m.status.replace("_", " ").title()}'), "category": lambda v, c, m, p: Markup(f'{m.category.title()}'), "title": lambda v, c, m, p: Markup(f'{m.title}' + (f'
{m.description[:80]}...' if m.description and len(m.description) > 80 else (f'
{m.description}' if m.description else ''))), } def on_model_change(self, form, model, is_created): if is_created: import datetime account, _ = get_admin_account() model.created_at = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") model.reported_by = model.reported_by or (account.get("username", "admin") if account else "admin") if model.status in ("resolved", "closed", "wontfix") and not model.resolved_at: import datetime model.resolved_at = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") elif model.status not in ("resolved", "closed", "wontfix"): model.resolved_at = None @action("resolve", "Resolve", "Resolve selected issues?") def action_resolve(self, ids): import datetime now = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") for id in ids: issue = sql_db.session.query(AdminIssue).get(int(id)) if issue: issue.status = "resolved" issue.resolved_at = now sql_db.session.commit() flash(f"Resolved {len(ids)} issue(s).", "success") @action("mark_critical", "Mark Critical") def action_mark_critical(self, ids): for id in ids: issue = sql_db.session.query(AdminIssue).get(int(id)) if issue: issue.severity = "critical" sql_db.session.commit() flash(f"Marked {len(ids)} issue(s) as critical.", "success") class AnalyticsView(_AuthMixin, BaseView): @expose("/") def index(self): import json as _json account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) stats = game_db.get_amplitude_stats() recent_events = game_db.get_amplitude_events(limit=200) count_history = game_db.get_player_count_history(hours=72) growth = game_db.get_growth_stats() def _to_dict(rows): return {r["d"]: r["c"] for r in rows} def _all_dates(*dicts): from datetime import date, timedelta all_d = set() for d in dicts: all_d.update(d.keys()) if not all_d: return [] lo = min(all_d) hi = max(all_d) try: cur = date.fromisoformat(lo) end = date.fromisoformat(hi) out = [] while cur <= end: out.append(str(cur)) cur += timedelta(days=1) return out except Exception: return sorted(all_d) def _polyline(data_dict, dates, W, H, cumulative=False): if not dates: return "" if cumulative: vals = [] run = 0 for d in dates: run += data_dict.get(d, 0) vals.append(run) else: vals = [data_dict.get(d, 0) for d in dates] max_v = max(vals) if vals else 1 if max_v == 0: max_v = 1 n = len(dates) pts = [] for i, v in enumerate(vals): x = round(i / max(n - 1, 1) * W, 1) y = round(H - v / max_v * H, 1) pts.append(f"{x},{y}") return " ".join(pts) SVG_W, SVG_H = 800, 80 reg_dict = _to_dict(growth["reg_by_day"]) login_dict = _to_dict(growth["daily_logins"]) visit_dict = _to_dict(growth["room_visits_by_day"]) chat_dict = _to_dict(growth["chat_by_day"]) photo_dict = _to_dict(growth["photos_by_day"]) gift_dict = _to_dict(growth["gifts_by_day"]) unlock_dict= _to_dict(growth["unlocked_by_day"]) admin_dict = _to_dict(growth["admin_by_day"]) all_activity_dates = _all_dates(login_dict, visit_dict, chat_dict, photo_dict) all_dates = _all_dates(reg_dict, login_dict, visit_dict, chat_dict, photo_dict, gift_dict) growth_charts = { "cum_reg": _polyline(reg_dict, all_dates, SVG_W, SVG_H, cumulative=True), "daily_reg": _polyline(reg_dict, all_dates, SVG_W, SVG_H), "logins": _polyline(login_dict, all_activity_dates, SVG_W, SVG_H), "visits": _polyline(visit_dict, all_activity_dates, SVG_W, SVG_H), "chat": _polyline(chat_dict, all_activity_dates, SVG_W, SVG_H), "photos": _polyline(photo_dict, all_activity_dates, SVG_W, SVG_H), "gifts": _polyline(gift_dict, all_dates, SVG_W, SVG_H), "unlocked": _polyline(unlock_dict,all_dates, SVG_W, SVG_H), "admin": _polyline(admin_dict, _all_dates(admin_dict), SVG_W, SVG_H), } ban_by_day_bans = {} ban_by_day_unbans = {} for row in growth["bans_by_day"]: d = row["d"] if row["action"] == "ban": ban_by_day_bans[d] = row["c"] else: ban_by_day_unbans[d] = row["c"] ban_dates = _all_dates(ban_by_day_bans, ban_by_day_unbans) growth_charts["bans"] = _polyline(ban_by_day_bans, ban_dates, SVG_W, SVG_H) growth_charts["unbans"] = _polyline(ban_by_day_unbans, ban_dates, SVG_W, SVG_H) activity_series_maxes = { "Logins": max(login_dict.values()) if login_dict else 0, "Visits": max(visit_dict.values()) if visit_dict else 0, "Chat": max(chat_dict.values()) if chat_dict else 0, "Photos": max(photo_dict.values()) if photo_dict else 0, } date_labels = { "all_first": all_dates[0] if all_dates else "", "all_last": all_dates[-1] if all_dates else "", "act_first": all_activity_dates[0] if all_activity_dates else "", "act_last": all_activity_dates[-1] if all_activity_dates else "", "ban_first": ban_dates[0] if ban_dates else "", "ban_last": ban_dates[-1] if ban_dates else "", } def parse_props(row, key="event_props"): try: v = row.get(key) if isinstance(row, dict) else row[key] return _json.loads(v) if isinstance(v, str) else (v or {}) except Exception: return {} def _safe_uid(v): try: return int(v) if v and str(v).lstrip('-').isdigit() else None except (ValueError, TypeError): return None all_user_ids = set() for u in stats["by_user"]: uid = _safe_uid(u["user_id"]) if uid: all_user_ids.add(uid) for row in stats["all_activity"] + stats["purchase_rows"] + stats["crash_rows"] + stats["social_rows"] + stats["network_rows"] + stats["objective_rows"] + stats["load_rows"] + stats["levelup_rows"] + stats["photon_rows"]: uid = _safe_uid(row.get("user_id")) if uid: all_user_ids.add(uid) for ev in recent_events: uid = _safe_uid(ev.get("user_id")) if uid: all_user_ids.add(uid) profiles_map = game_db.get_profiles_batch(list(all_user_ids)) if all_user_ids else {} user_names = {uid: (p["Username"] if p else f"#{uid}") for uid, p in profiles_map.items()} activity_rows = [] act_buckets = {} for row in stats["all_activity"]: p = parse_props(row) name = p.get("activityName", "unknown") entry = { "user_id": row["user_id"], "activity": name, "total_time": float(p.get("total_time") or 0), "avg_fps": float(p.get("avg_fps") or 0), "min_fps": float(p.get("min_fps") or 0), "max_fps": float(p.get("max_fps") or 0), "stdev_fps": float(p.get("stdev_fps") or 0), "avg_ping": float(p.get("avg_ping") or 0), "min_ping": float(p.get("min_ping") or 0), "max_ping": float(p.get("max_ping") or 0), "stdev_ping": float(p.get("stdev_ping") or 0), "dropped_frames_perc": float(p.get("dropped_frames_perc") or 0), "rw_dropped_perc": float(p.get("rw_dropped_frames_perc") or 0), "rw_dropped_1to2p_perc": float(p.get("rw_dropped_frames_1to2p_perc") or 0), "avg_sl": float(p.get("avg_sl") or 0), "load_time": float(p.get("loadTime") or 0), "load_source": p.get("load_source", ""), "is_sandbox": bool(p.get("is_sandbox", False)), "tt_public": float(p.get("tt_Public") or 0), "tt_private": float(p.get("tt_Private") or 0), "tt_dorm": float(p.get("tt_Dorm") or 0), "c_received_gift": int(p.get("c_received_gift") or 0), "created_at": row["created_at"], } activity_rows.append(entry) if name not in act_buckets: act_buckets[name] = {"sessions": 0, "total_time": 0, "fps": [], "ping": [], "stdev_fps": [], "stdev_ping": [], "rw_drop": [], "sl": [], "load_times": [], "gifts": 0} b = act_buckets[name] b["sessions"] += 1 b["total_time"] += entry["total_time"] if entry["avg_fps"]: b["fps"].append(entry["avg_fps"]) if entry["avg_ping"]: b["ping"].append(entry["avg_ping"]) if entry["stdev_fps"]: b["stdev_fps"].append(entry["stdev_fps"]) if entry["stdev_ping"]: b["stdev_ping"].append(entry["stdev_ping"]) if entry["rw_dropped_perc"] is not None: b["rw_drop"].append(entry["rw_dropped_perc"]) if entry["avg_sl"]: b["sl"].append(entry["avg_sl"]) if entry["load_time"]: b["load_times"].append(entry["load_time"]) b["gifts"] += entry["c_received_gift"] def avg(lst): return round(sum(lst) / len(lst), 2) if lst else 0 activity_summary = {} for name, b in act_buckets.items(): activity_summary[name] = { "sessions": b["sessions"], "total_time": b["total_time"], "avg_fps": avg(b["fps"]), "avg_ping": avg(b["ping"]), "avg_stdev_fps": avg(b["stdev_fps"]), "avg_stdev_ping": avg(b["stdev_ping"]), "avg_rw_drop": avg(b["rw_drop"]), "avg_sl": avg(b["sl"]), "avg_load_time": avg(b["load_times"]), "total_gifts": b["gifts"], } PHOTON_REGIONS = ["eu", "us", "usw", "cae", "asia", "jp", "au", "sa", "in", "ru", "rue", "kr"] region_buckets = {r: [] for r in PHOTON_REGIONS} for row in stats["photon_rows"]: p = parse_props(row) for r in PHOTON_REGIONS: v = p.get(r) if v is not None: try: region_buckets[r].append(int(v)) except (ValueError, TypeError): pass photon_summary = {} for r in PHOTON_REGIONS: vals = region_buckets[r] if vals: svals = sorted(vals) p95_idx = max(0, int(len(svals) * 0.95) - 1) photon_summary[r] = { "avg": avg(vals), "min": min(vals), "max": max(vals), "p95": svals[p95_idx], "count": len(vals), } purchases = [] item_buckets = {} daily_spend = {} type_spend = {} storefront_counts = {} for row in stats["purchase_rows"]: p = parse_props(row) name = p.get("item_name", "Unknown") cost = int(p.get("item_cost") or 0) itype = p.get("item_type", "Unknown") sf = p.get("storefront", "Unknown") day = (row.get("created_at") or "")[:10] purchases.append({"user_id": row["user_id"], "item_name": name, "cost": cost, "item_type": itype, "storefront": sf, "initial_bal": p.get("initial_bal", 0), "new_bal": p.get("new_bal", 0), "created_at": row.get("created_at", "")}) if name not in item_buckets: item_buckets[name] = {"count": 0, "total_cost": 0, "item_type": itype} item_buckets[name]["count"] += 1 item_buckets[name]["total_cost"] += cost daily_spend[day] = daily_spend.get(day, 0) + cost type_spend[itype] = type_spend.get(itype, 0) + 1 storefront_counts[sf] = storefront_counts.get(sf, 0) + 1 top_items = sorted(item_buckets.items(), key=lambda x: x[1]["count"], reverse=True) total_tokens_spent = sum(p["cost"] for p in purchases) crashes = [] crash_patterns = {} for row in stats["crash_rows"]: p = parse_props(row) err = p.get("error", "Unknown")[:120] stack = p.get("stackTrace", "") crashes.append({"user_id": row["user_id"], "error": err, "stack": stack, "created_at": row.get("created_at", "")}) crash_patterns[err] = crash_patterns.get(err, 0) + 1 social_counts = {} invite_funnel = {"sent": 0, "received": 0, "accepted": 0} for row in stats["social_rows"]: et = row["event_type"] social_counts[et] = social_counts.get(et, 0) + 1 if et == "sent_game_invite": invite_funnel["sent"] += 1 elif et == "received_GameInvite": invite_funnel["received"] += 1 elif et == "accepted_game_invite": invite_funnel["accepted"] += 1 network_events = [] conn_failures = {} master_switches = [] for row in stats["network_rows"]: p = parse_props(row) et = row["event_type"] network_events.append({"event_type": et, "user_id": row["user_id"], "props": p, "created_at": row.get("created_at", "")}) if et == "connection_failure": cause = p.get("cause", "Unknown") conn_failures[cause] = conn_failures.get(cause, 0) + 1 elif et == "network_masterSwitched": master_switches.append({"user_id": row["user_id"], "activity": p.get("activityName", ""), "new_ping": p.get("newPing"), "old_ping": p.get("oldPing"), "created_at": row.get("created_at", "")}) load_scene_stats = {} for row in stats["load_rows"]: p = parse_props(row) scene = row["event_type"].replace("_load", "").replace("_additive_load", "") if scene not in load_scene_stats: load_scene_stats[scene] = {"count": 0, "players": set(), "sources": {}} load_scene_stats[scene]["count"] += 1 uid = row.get("user_id") if uid: load_scene_stats[scene]["players"].add(uid) src = p.get("source", p.get("prev", "")) if src: load_scene_stats[scene]["sources"][src] = load_scene_stats[scene]["sources"].get(src, 0) + 1 for k in load_scene_stats: load_scene_stats[k]["players"] = len(load_scene_stats[k]["players"]) levelup_data = [] for row in stats["levelup_rows"]: p = parse_props(row) levelup_data.append({ "user_id": row["user_id"], "activity": p.get("activityName", "—"), "created_at": row.get("created_at", ""), }) objective_data = [] for row in stats["objective_rows"]: p = parse_props(row) objective_data.append({ "user_id": row["user_id"], "type": p.get("type", "—"), "score": p.get("requiredScore", "—"), "level": p.get("Level", "—"), "created_at": row.get("created_at", ""), }) gift_open_total = sum(g["c"] for g in stats["gift_stats"]) gift_open_consumed = next((g["c"] for g in stats["gift_stats"] if g["consumed"]), 0) gift_open_rate = round(gift_open_consumed / gift_open_total * 100, 1) if gift_open_total else 0 events_by_day = {r["d"]: r["c"] for r in stats["events_by_day"]} events_by_hour = {r["h"]: r["c"] for r in stats["events_by_hour"]} sessions_by_day = {r["d"]: r["c"] for r in stats["sessions_by_day"]} total_playtime_secs = sum(a["total_time"] for a in activity_rows) for ev in recent_events: ev["_props"] = parse_props(ev) return self.render( "admin/analytics_view.html", stats=stats, recent_events=recent_events, activity_rows=activity_rows, activity_summary=activity_summary, photon_summary=photon_summary, purchases=purchases, top_items=top_items, total_tokens_spent=total_tokens_spent, daily_spend=daily_spend, type_spend=type_spend, storefront_counts=storefront_counts, crashes=crashes, crash_patterns=crash_patterns, social_counts=social_counts, invite_funnel=invite_funnel, network_events=network_events, conn_failures=conn_failures, master_switches=master_switches, load_scene_stats=load_scene_stats, gift_open_rate=gift_open_rate, gift_open_consumed=gift_open_consumed, gift_open_total=gift_open_total, events_by_day=events_by_day, events_by_hour=events_by_hour, sessions_by_day=sessions_by_day, total_playtime_secs=total_playtime_secs, levelup_data=levelup_data, objective_data=objective_data, growth=growth, growth_charts=growth_charts, activity_series_maxes=activity_series_maxes, date_labels=date_labels, count_history=count_history, user_names=user_names, account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, ) class UGCItemsView(_AuthMixin, BaseView): _DATA_PATH = None def _items_path(self): import os as _os return _os.path.join(_os.path.dirname(_os.path.dirname(__file__)), "data", "ugc_outfit_items.json") def _load(self): import json as _json try: with open(self._items_path()) as f: return _json.load(f) except Exception: return [] def _save(self, items): import json as _json with open(self._items_path(), "w") as f: _json.dump(items, f, indent=2) @expose("/", methods=["GET", "POST"]) def index(self): import os as _os, uuid as _uuid account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) _MAX_BYTES = 10 * 1024 * 1024 error = None success = None if request.method == "POST" and SCOPE_ADMIN in scopes: action_type = request.form.get("action_type", "add") items = self._load() if action_type == "add": friendly_name = request.form.get("friendly_name", "").strip()[:128] use_cdn = request.form.get("use_cdn") == "1" version = max(0, int(request.form.get("version", 0) or 0)) if not friendly_name: error = "Friendly name is required." elif use_cdn: f_bundle = request.files.get("assetbundle_file") f_manifest = request.files.get("manifest_file") if not f_bundle or not f_manifest: error = "Both files are required for CDN upload." else: bundle_data = f_bundle.read(_MAX_BYTES + 1) manifest_data = f_manifest.read(_MAX_BYTES + 1) if len(bundle_data) > _MAX_BYTES or len(manifest_data) > _MAX_BYTES: error = "Files too large (max 10MB each)." else: random_stem = _uuid.uuid4().hex bundle_cdn_name = f"cdn_ugc_{random_stem}.assetbundle" manifest_cdn_name = f"cdn_ugc_{random_stem}.manifest" game_db.save_named_image(bundle_cdn_name, -1, bundle_data, room_name=friendly_name) game_db.save_named_image(manifest_cdn_name, -1, manifest_data, room_name=friendly_name) item_id = str(_uuid.uuid4()) items.append({ "id": item_id, "friendly_name": friendly_name, "assetbundle_name": bundle_cdn_name, "manifest_name": manifest_cdn_name, "version": version, }) self._save(items) admin_name = account.get("username", "admin") game_db.log_admin_action(admin_name, "add_ugc_outfit_item", f"Added UGC outfit item '{friendly_name}' (bundle={bundle_cdn_name})", request.headers.get("X-Forwarded-For", request.remote_addr or "")) success = f"Added '{friendly_name}' (CDN)." else: bundle_path = request.form.get("bundle_url", "").strip() manifest_path = request.form.get("manifest_url", "").strip() if not bundle_path or not manifest_path: error = "Both AssetbundleName and ManifestName paths are required." else: item_id = str(_uuid.uuid4()) items.append({ "id": item_id, "friendly_name": friendly_name, "assetbundle_name": bundle_path, "manifest_name": manifest_path, "version": version, }) self._save(items) admin_name = account.get("username", "admin") game_db.log_admin_action(admin_name, "add_ugc_outfit_item", f"Added UGC outfit item '{friendly_name}' (direct, bundle={bundle_path})", request.headers.get("X-Forwarded-For", request.remote_addr or "")) success = f"Added '{friendly_name}' (direct URL)." elif action_type == "edit": item_id = request.form.get("item_id", "") friendly_name = request.form.get("friendly_name", "").strip()[:128] bundle_path = request.form.get("bundle_url", "").strip() manifest_path = request.form.get("manifest_url", "").strip() version = max(0, int(request.form.get("version", 0) or 0)) target = next((i for i in items if i.get("id") == item_id), None) if not target: error = "Item not found." elif not friendly_name or not bundle_path or not manifest_path: error = "All fields required." else: target["friendly_name"] = friendly_name target["assetbundle_name"] = bundle_path target["manifest_name"] = manifest_path target["version"] = version self._save(items) admin_name = account.get("username", "admin") game_db.log_admin_action(admin_name, "edit_ugc_outfit_item", f"Edited UGC outfit item '{friendly_name}' (id={item_id})", request.headers.get("X-Forwarded-For", request.remote_addr or "")) success = f"Saved '{friendly_name}'." elif action_type == "delete": item_id = request.form.get("item_id", "") before = len(items) items = [i for i in items if i.get("id") != item_id] if len(items) < before: self._save(items) admin_name = account.get("username", "admin") game_db.log_admin_action(admin_name, "delete_ugc_outfit_item", f"Deleted UGC outfit item id={item_id}", request.headers.get("X-Forwarded-For", request.remote_addr or "")) success = "Item deleted." else: error = "Item not found." items = self._load() return self.render( "admin/ugc_items_view.html", items=items, error=error, success=success, account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, ) class MusicView(_AuthMixin, BaseView): _MAX_BYTES = 100 * 1024 * 1024 @expose("/", methods=["GET", "POST"]) def index(self): import os as _os, re as _re account, scopes = get_admin_account() if not account or not has_any_admin_scope(scopes): return redirect(make_login_redirect()) from routes.music import MUSIC_DIR, _CONVERT_EXTS MUSIC_DIR.mkdir(exist_ok=True) error = None success = None _ALLOWED_EXTS = _CONVERT_EXTS | {".wav"} if request.method == "POST" and SCOPE_ADMIN in scopes: action_type = request.form.get("action_type", "upload") _ip = request.headers.get("X-Forwarded-For", request.remote_addr or "") admin_name = account.get("username", "admin") if action_type == "upload": f = request.files.get("music_file") if not f or not f.filename: error = "No file selected." else: ext = _os.path.splitext(f.filename)[1].lower() if ext not in _ALLOWED_EXTS: error = f"Unsupported format. Allowed: {', '.join(sorted(_ALLOWED_EXTS))}" else: data = f.read(self._MAX_BYTES + 1) if len(data) > self._MAX_BYTES: error = "File too large (max 100 MB)." else: safe_name = _re.sub(r"[^\w\s\-.]", "", f.filename).strip() if not safe_name: safe_name = "track" + ext dest = MUSIC_DIR / safe_name with open(dest, "wb") as out: out.write(data) game_db.log_admin_action(admin_name, "music_upload", f"Uploaded track '{safe_name}' ({len(data):,} bytes)", _ip) success = f"Uploaded '{safe_name}' ({len(data) // 1024:,} KB)." elif action_type == "delete": filename = request.form.get("filename", "").strip() if filename: target = (MUSIC_DIR / filename).resolve() music_root = str(MUSIC_DIR.resolve()) if not str(target).startswith(music_root + _os.sep): error = "Invalid filename." elif not target.exists() or not target.is_file(): error = "File not found." else: target.unlink() wav_sibling = target.with_suffix(".wav") if target.suffix.lower() != ".wav" and wav_sibling.exists(): wav_sibling.unlink() game_db.log_admin_action(admin_name, "music_delete", f"Deleted track '{filename}'", _ip) success = f"Deleted '{filename}'." elif action_type == "rename": old_name = request.form.get("old_name", "").strip() new_name = request.form.get("new_name", "").strip() if old_name and new_name: safe_new = _re.sub(r"[^\w\s\-.]", "", new_name).strip() src = (MUSIC_DIR / old_name).resolve() dst = (MUSIC_DIR / safe_new).resolve() music_root = str(MUSIC_DIR.resolve()) if not str(src).startswith(music_root + _os.sep) or not str(dst).startswith(music_root + _os.sep): error = "Invalid filename." elif not src.exists(): error = "Source file not found." elif dst.exists(): error = f"'{safe_new}' already exists." else: src.rename(dst) game_db.log_admin_action(admin_name, "music_rename", f"Renamed track '{old_name}' → '{safe_new}'", _ip) success = f"Renamed to '{safe_new}'." tracks = [] for f in sorted(MUSIC_DIR.iterdir()): if f.is_file() and not f.name.startswith("."): tracks.append({ "name": f.name, "ext": f.suffix.lower(), "size_kb": f.stat().st_size // 1024, }) return self.render( "admin/music_view.html", tracks=tracks, error=error, success=success, account=account, scopes=scopes, SCOPE_ADMIN=SCOPE_ADMIN, ) def create_admin(app): from flask_admin.theme import Bootstrap4Theme admin = Admin( app, name="KittyRec Admin", index_view=HomeView(name="Dashboard", url="/admin", endpoint="admin"), theme=Bootstrap4Theme(base_template="admin/custom_base.html"), ) admin.add_view(ProfileView(Profile, sql_db.session, name="Players", endpoint="admin_players", category="Players")) admin.add_view(GiftView(Gift, sql_db.session, name="Gifts", endpoint="admin_gifts", category="Players")) admin.add_view(BanLogView(BanLog, sql_db.session, name="Ban Log", endpoint="admin_bans", category="Players")) admin.add_view(RoomsManageView(name="Rooms", endpoint="admin_rooms_manage", url="/admin/live/rooms", category="Game")) admin.add_view(SessionsView(name="Live Sessions", endpoint="admin_sessions", url="/admin/live/sessions", category="Game")) admin.add_view(StoreView(name="Store", endpoint="admin_store", url="/admin/live/store", category="Game")) admin.add_view(EventsView(name="Events", endpoint="admin_events", url="/admin/live/events", category="Game")) admin.add_view(TexturesView(name="Game Assets", endpoint="admin_textures", url="/admin/live/textures", category="Content")) admin.add_view(SwatchesView(name="Swatches", endpoint="admin_swatches", url="/admin/live/swatches", category="Content")) admin.add_view(AvatarItemsView(name="Avatar Items", endpoint="admin_avatar_items", url="/admin/live/avatar_items", category="Content")) admin.add_view(UGCItemsView(name="UGC Avatar", endpoint="admin_ugc_items", url="/admin/live/ugc_items", category="Content")) admin.add_view(MusicView(name="Music", endpoint="admin_music", url="/admin/live/music", category="Content")) admin.add_view(CdnView(name="CDN", endpoint="admin_cdn", url="/admin/live/cdn", category="Content")) admin.add_view(DownloadsView(name="Downloads", endpoint="admin_downloads", url="/admin/live/downloads", category="Content")) admin.add_view(DllArchiveView(name="DLL Archive", endpoint="admin_dll_archive", url="/admin/live/dll_archive", category="Content")) admin.add_view(kittyrecModView(name="KittyRec Mod", endpoint="admin_kittyrec_mod", url="/admin/kittyrec/mod", category="Content")) admin.add_view(TodoView(AdminTodo, sql_db.session, name="Todos", endpoint="admin_todos", category="Tracking")) admin.add_view(IssueView(AdminIssue, sql_db.session, name="Issues", endpoint="admin_issues", category="Tracking")) admin.add_view(AnalyticsView(name="Analytics", endpoint="admin_analytics", url="/admin/analytics", category="System")) admin.add_view(ConsoleView(name="Console", endpoint="admin_console", url="/admin/live/console", category="System")) return admin