import json import os from flask import Blueprint, request, jsonify, Response from core.auth import check_auth, get_current_profile_id from core.builders import now_iso from core.state import session_mgr, db from core.constants import DORM_ROOM_GUID def _load_room_config(): cfg_path = os.path.join(os.path.dirname(__file__), "..", "data", "room_config.json") with open(cfg_path, encoding="utf-8") as f: return json.load(f) _room_cfg = _load_room_config() _SOCIAL_GUIDS = set(_room_cfg["social_guids"]) _BROWSE_EXCLUDE_GUIDS = _SOCIAL_GUIDS | set(_room_cfg["browse_exclude_extra_guids"]) _MAX_ROOMS_PER_PLAYER = _room_cfg["max_rooms_per_player"] _RESERVED_NAMES = set(_room_cfg["reserved_names"]) _PAINTBALL_GUIDS = _room_cfg["paintball_guids"] _PAINTBALL_SUPPRESS = set(_PAINTBALL_GUIDS[1:]) def _session_to_room(s) -> dict: now = now_iso() return { "RoomId": s.session_id, "Name": s.name, "Description": "", "CreatorPlayerId": s.creator_player_id or 23, "ImageName": "", "DataBlobName": "", "ActivityLevelId": s.activity_level_id, "State": 0, "Accessibility": 0, "IsSandbox": s.sandbox, "Instanced": True, "ScreenModeSupport": 0, "MaxPlayers": s.max_capacity, "VisitorCount": len(s.players), "VisitCount": 0, "CheerCount": 0, "ReportCount": 0, "StateModifiedAt": now, "CreatedAt": now, "ModifiedAt": now, "LastVisitedAt": now, "CoOwners": [], "Hosts": [], } def _all_browseable_rooms() -> list: # Build live player counts for custom rooms (sessions tied to a DB room) custom_player_counts: dict[int, int] = {} for s in session_mgr.all_public_sessions(): if s.rec_room_id: existing = custom_player_counts.get(s.rec_room_id, 0) custom_player_counts[s.rec_room_id] = max(existing, len(s.players)) # Always include every custom DB room; inject live player count if present rooms = [] for db_room in db.get_all_rooms(): guid = db_room.get("ActivityLevelId", "") if guid in _BROWSE_EXCLUDE_GUIDS: continue room_id = db_room.get("RoomId") live = custom_player_counts.get(room_id, 0) if live or db_room.get("VisitorCount", 0) != live: db_room = dict(db_room) db_room["VisitorCount"] = live elif "VisitorCount" not in db_room: db_room["VisitorCount"] = 0 rooms.append(db_room) # Add preset sessions (no rec_room_id), deduplicated by GUID seen_preset_guids: set[str] = set() best_paintball: object = None for s in session_mgr.all_public_sessions(): if s.rec_room_id: continue if s.activity_level_id in _PAINTBALL_GUIDS: if best_paintball is None or len(s.players) > len(best_paintball.players): best_paintball = s for s in session_mgr.all_public_sessions(): if s.rec_room_id: continue guid = s.activity_level_id if guid in _BROWSE_EXCLUDE_GUIDS: continue if guid in _PAINTBALL_GUIDS: if s is best_paintball and _PAINTBALL_GUIDS[0] not in seen_preset_guids: rooms.append(_session_to_room(s)) seen_preset_guids.update(_PAINTBALL_GUIDS) elif guid not in seen_preset_guids: rooms.append(_session_to_room(s)) seen_preset_guids.add(guid) rooms.sort(key=lambda r: r.get("VisitorCount", 0), reverse=True) return rooms bp = Blueprint("rooms", __name__) def _room_ok(room_dict): return jsonify({"Result": 0, "Room": room_dict}) def _room_err(code=1): return jsonify({"Result": code, "Room": None}) @bp.route("/api/rooms/v2/myrooms", methods=["GET"]) @check_auth def get_my_rooms(): pid = get_current_profile_id() if not pid: return jsonify([]) return jsonify(db.get_rooms_by_creator(pid)) @bp.route("/api/rooms/v2/mybookmarkedrooms", methods=["GET"]) @check_auth def get_bookmarked_rooms(): pid = get_current_profile_id() if not pid: return jsonify([]) return jsonify(db.get_bookmarked_rooms(pid)) @bp.route("/api/rooms/v2/hot", methods=["GET"]) @bp.route("/api/rooms/v3/browse", methods=["GET"]) @check_auth def browse_rooms(): skip = int(request.args.get("skip", 0)) take = int(request.args.get("take", 75)) rooms = _all_browseable_rooms() return jsonify(rooms[skip:skip + take]) @bp.route("/api/rooms/v3/featured", methods=["GET"]) @check_auth def get_featured_rooms(): return jsonify({ "RoomId": 1, "Name": "RecCenter", "Description": "", "CreatorPlayerId": 1, "ImageName": "", "ActivityLevelId": "cbad71af-0831-44d8-b8ef-69edafa841f6", "State": 0, "Accessibility": 0, "IsSandbox": False, "Instanced": True, "ScreenModeSupport": 0, }) @bp.route("/api/rooms/v1/featuredRoomGroup", methods=["GET"]) @check_auth def get_featured_room_group(): return jsonify({"Name": "Featured", "FeaturedRooms": []}) def _fallback_room(): now = now_iso() return { "RoomId": 1, "Name": "RecCenter", "Description": "", "CreatorPlayerId": 1, "ImageName": "", "DataBlobName": "", "ActivityLevelId": "cbad71af-0831-44d8-b8ef-69edafa841f6", "State": 0, "Accessibility": 0, "IsSandbox": False, "Instanced": True, "ScreenModeSupport": 0, "MaxPlayers": 20, "VisitorCount": 0, "VisitCount": 0, "CheerCount": 0, "ReportCount": 0, "StateModifiedAt": now, "CreatedAt": now, "ModifiedAt": now, "LastVisitedAt": now, "CoOwners": [], "Hosts": [], } @bp.route("/api/rooms/v2/featured", methods=["GET"]) @check_auth def get_featured_rooms_v2(): rooms = db.get_all_rooms() return jsonify(rooms[0] if rooms else _fallback_room()) @bp.route("/api/rooms/v2/browse", methods=["POST"]) @check_auth def browse_rooms_v2(): return jsonify(_all_browseable_rooms()) @bp.route("/api/rooms/v1/myrooms", methods=["GET"]) @check_auth def get_my_rooms_v1(): pid = get_current_profile_id() if not pid: return jsonify([]) return jsonify(db.get_rooms_by_creator(pid)) @bp.route("/api/rooms/v1/mybookmarkedrooms", methods=["GET"]) @check_auth def get_bookmarked_rooms_v1(): pid = get_current_profile_id() if not pid: return jsonify([]) return jsonify(db.get_bookmarked_rooms(pid)) @bp.route("/api/rooms/v1/myRecent", methods=["GET"]) @bp.route("/api/rooms/v2/myRecent", methods=["GET"]) @check_auth def get_recent_rooms(): pid = get_current_profile_id() if not pid: return jsonify([]) skip = int(request.args.get("skip", 0)) take = int(request.args.get("take", 10)) rooms = db.get_recent_rooms(pid, limit=skip + take) if not rooms: rooms = _all_browseable_rooms() return jsonify(rooms[skip:skip + take]) @bp.route("/api/rooms/v2/mySubscriptions", methods=["GET"]) @check_auth def get_room_subscriptions(): return jsonify([]) @bp.route("/api/rooms/v1/search", methods=["POST"]) @bp.route("/api/rooms/v2/search", methods=["GET"]) @check_auth def search_rooms(): query = "" if request.method == "POST": data = request.get_json(force=True, silent=True) or {} query = str(data.get("Name", "")).strip().lower() else: query = request.args.get("name", "").strip().lower() if not query: return jsonify(db.get_all_rooms()) all_rooms = db.get_all_rooms() return jsonify([r for r in all_rooms if query in r["Name"].lower()]) @bp.route("/api/rooms/v1/", methods=["GET"]) @bp.route("/api/rooms/v2/", methods=["GET"]) @check_auth def get_room(room_id): room = db.get_room(room_id) if room: return jsonify(room) now = now_iso() return jsonify({ "RoomId": room_id, "Name": "dormroom", "Description": "", "CreatorPlayerId": 1, "ImageName": "", "DataBlobName": "", "ActivityLevelId": DORM_ROOM_GUID, "State": 0, "Accessibility": 0, "IsSandbox": False, "Instanced": True, "ScreenModeSupport": 0, "MaxPlayers": 20, "VisitorCount": 0, "VisitCount": 0, "CheerCount": 0, "ReportCount": 0, "CreatedAt": now, "ModifiedAt": now, "StateModifiedAt": now, "LastVisitedAt": now, "CoOwners": [], "Hosts": [], }) @bp.route("/api/rooms/v3/details/", methods=["GET"]) @check_auth def get_room_details(room_id): room = db.get_room(room_id) if room: return jsonify(room) session = session_mgr.get_session(room_id) creator_pid = session.creator_player_id if session else 1 name = session.name if session else "DormRoom" activity_id = session.activity_level_id if session else DORM_ROOM_GUID is_sandbox = session.sandbox if session else False now = now_iso() return jsonify({ "RoomId": room_id, "Name": name, "Description": "", "CreatorPlayerId": creator_pid, "ImageName": "", "ActivityLevelId": activity_id, "MaxPlayers": 20, "State": 0, "Accessibility": 0, "IsSandbox": is_sandbox, "Instanced": True, "ScreenModeSupport": 0, "DataBlobName": "", "AccessibilityLocked": False, "CreatedAt": now, "ModifiedAt": now, "StateModifiedAt": now, "DataModifiedAt": None, "LastVisitedAt": now, "VisitorCount": len(session.players) if session else 0, "VisitCount": 0, "CheerCount": 0, "ReportCount": 0, "CoOwners": [], "Hosts": [], }) @bp.route("/api/rooms/v1/name/", methods=["GET"]) @bp.route("/api/rooms/v2/name/", methods=["GET"]) @check_auth def get_room_by_name(room_name): room = db.get_room_by_name(room_name) if room: return jsonify(room) now = now_iso() return jsonify({ "RoomId": 0, "Name": room_name, "Description": "", "CreatorPlayerId": 1, "ImageName": "", "DataBlobName": "", "ActivityLevelId": "", "State": 0, "Accessibility": 0, "IsSandbox": False, "Instanced": True, "ScreenModeSupport": 0, "MaxPlayers": 20, "VisitorCount": 0, "VisitCount": 0, "CheerCount": 0, "ReportCount": 0, "CreatedAt": now, "ModifiedAt": now, "StateModifiedAt": now, "LastVisitedAt": now, "CoOwners": [], "Hosts": [], }) @bp.route("/api/rooms/v2/personaldetails/", methods=["GET"]) @check_auth def get_personal_room_details(room_id): pid = get_current_profile_id() return jsonify({ "IsCheering": db.is_room_cheered(pid, room_id) if pid else False, "IsBookmarked": db.is_room_bookmarked(pid, room_id) if pid else False, }) @bp.route("/api/rooms/v2/create", methods=["POST"]) @check_auth def create_room(): return jsonify({"Result": 1, "Room": None, "Message": "Room creation is temporarily disabled."}) pid = get_current_profile_id() data = request.get_json(force=True, silent=True) or {} name = str(data.get("Name", "")).strip().replace(" ", "") if not name: return jsonify({"Result": 1, "Room": None, "Message": "Room name cannot be empty."}) if name.lower() in _RESERVED_NAMES: return jsonify({"Result": 11, "Room": None, "Message": "That room name is reserved."}) existing = db.get_room_by_name(name) if existing: return jsonify({"Result": 10, "Room": None, "Message": "A room with that name already exists."}) if db.count_rooms_by_creator(pid) >= _MAX_ROOMS_PER_PLAYER: return jsonify({"Result": 20, "Room": None, "Message": f"You can only have {_MAX_ROOMS_PER_PLAYER} rooms."}) activity_level_id = data.get("ActivityLevelId", "") max_players = int(data.get("MaxPlayers", 20)) if max_players < 1 or max_players > 40: return jsonify({"Result": 30, "Room": None, "Message": "MaxPlayers must be between 1 and 40."}) description = data.get("Description", "") accessibility = int(data.get("Accessibility", 0)) is_sandbox = bool(data.get("IsSandbox", False)) instanced = bool(data.get("Instanced", True)) screen_mode_support = int(data.get("ScreenModeSupport", 0)) room = db.create_room( creator_id=pid, name=name, description=description, activity_level_id=activity_level_id, accessibility=accessibility, is_sandbox=is_sandbox, instanced=instanced, max_players=max_players, screen_mode_support=screen_mode_support, ) game_session_id = int(data.get("GameSessionId", 0)) if game_session_id: session = session_mgr.get_session(game_session_id) if session: session.rec_room_id = room["RoomId"] from core.ws_helpers import push_room_update, push_session_update push_room_update(pid, room) push_session_update(pid, session) print(f"[Rooms] Player {pid} created room '{name}' " f"(id={room['RoomId']}, session={game_session_id or 'none'})") return _room_ok(room) @bp.route("/api/rooms/v1/clone", methods=["POST"]) @check_auth def clone_room(): pid = get_current_profile_id() data = request.get_json(force=True, silent=True) or {} room_id = int(data.get("RoomId", 0)) if not room_id: return _room_err() source = db.get_room(room_id) if not source: return _room_err() if source.get("CreatorPlayerId") != pid and source.get("Accessibility", 1) != 0: return _room_err() if db.count_rooms_by_creator(pid) >= _MAX_ROOMS_PER_PLAYER: return jsonify({"Result": 20, "Room": None, "Message": f"You can only have {_MAX_ROOMS_PER_PLAYER} rooms."}) base_name = source["Name"] + " (Clone)" clone_name = base_name counter = 2 while db.get_room_by_name(clone_name): clone_name = f"{base_name} {counter}" counter += 1 room = db.create_room( creator_id=pid, name=clone_name, description=source["Description"], activity_level_id=source["ActivityLevelId"], accessibility=source["Accessibility"], is_sandbox=source["IsSandbox"], instanced=source["Instanced"], max_players=source["MaxPlayers"], screen_mode_support=source["ScreenModeSupport"], ) source_data = db.get_room_data(room_id) if source_data: db.save_room_data(room["RoomId"], source_data) print(f"[Rooms] Player {pid} cloned room '{source['Name']}' → '{clone_name}' (id={room['RoomId']})") return _room_ok(room) @bp.route("/api/rooms/v1/cheer", methods=["POST"]) @check_auth def cheer_room(): pid = get_current_profile_id() data = request.get_json(force=True, silent=True) or {} room_id = int(data.get("RoomId", 0)) if not room_id: return jsonify({"Success": True, "Message": ""}) db.toggle_room_cheer(pid, room_id) return jsonify({"Success": True, "Message": ""}) @bp.route("/api/rooms/v1/bookmark", methods=["POST"]) @check_auth def bookmark_room(): pid = get_current_profile_id() data = request.get_json(force=True, silent=True) or {} room_id = int(data.get("RoomId", 0)) if not room_id: return jsonify({"Success": True, "Message": ""}) db.toggle_room_bookmark(pid, room_id) return jsonify({"Success": True, "Message": ""}) @bp.route("/api/rooms/v1/report", methods=["POST"]) @check_auth def report_room(): return jsonify({"Success": True, "Message": ""}) _MODIFY_FIELD_MAP = { "name": ("name", lambda d: d.get("Name", "")), "description": ("description", lambda d: d.get("Description", "")), "accessibility": ("accessibility", lambda d: int(d.get("Accessibility", 0))), "instanced": ("instanced", lambda d: 1 if d.get("Instanced", True) else 0), "screenmode": ("screen_mode_support", lambda d: int(d.get("ScreenModeSupport", 0))), "maxplayers": ("max_players", lambda d: int(d.get("MaxPlayers", 20))), "imagename": ("image_name", lambda d: d.get("ImageName", "")), } @bp.route("/api/rooms/v1/modify/", methods=["POST"]) @check_auth def modify_room(prop): pid = get_current_profile_id() data = request.get_json(force=True, silent=True) or {} room_id = int(data.get("RoomId", 0)) if not room_id: return _room_err() if not db.is_room_owner_or_coowner(room_id, pid): return _room_err() if prop.lower() == "name": new_name = str(data.get("Name", "")).strip().replace(" ", "") if new_name.lower() in _RESERVED_NAMES: return jsonify({"Result": 11, "Room": None}) existing = db.get_room_by_name(new_name) if existing and existing["RoomId"] != room_id: return jsonify({"Result": 10, "Room": None}) mapping = _MODIFY_FIELD_MAP.get(prop.lower()) if mapping: field, extractor = mapping value = extractor(data) room = db.update_room_field(room_id, field, value) if room: return _room_ok(room) room = db.get_room(room_id) if room_id else None if room: return _room_ok(room) return _room_err() @bp.route("/api/rooms/v1/modifyPermissions", methods=["POST"]) @check_auth def modify_room_permissions(): pid = get_current_profile_id() data = request.get_json(force=True, silent=True) or {} room_id = int(data.get("RoomId", 0)) target_pid = int(data.get("PlayerId", 0)) if not room_id or not target_pid: return jsonify({"Result": 0}) if not db.is_room_owner_or_coowner(room_id, pid): return Response("Forbidden", 403) is_host = bool(data.get("IsHost", False)) is_owner = bool(data.get("IsOwner", False)) db.set_room_permission(room_id, target_pid, is_host, is_owner) return jsonify({"Result": 0}) @bp.route("/api/rooms/v1/saveData/", methods=["POST", "GET"]) @check_auth def room_save_data(room_id): pid = get_current_profile_id() if request.method == "GET": if not db.is_room_owner_or_coowner(room_id, pid): return Response(b"", 200, {"Content-Type": "application/octet-stream"}) blob = db.get_room_data(room_id) if blob: if isinstance(blob, str): blob = blob.encode("utf-8") return Response(blob, 200, {"Content-Type": "application/octet-stream"}) return Response(b"", 200, {"Content-Type": "application/octet-stream"}) if not db.is_room_owner_or_coowner(room_id, pid): return Response("Forbidden", 403) _MAX_ROOM_DATA = 10 * 1024 * 1024 if request.content_type and "multipart/form-data" in request.content_type: raw = request.files.get("data") if raw: blob = raw.read(_MAX_ROOM_DATA + 1) if len(blob) > _MAX_ROOM_DATA: return Response("Payload Too Large", 413) db.save_room_data(room_id, blob) img_list_raw = request.form.get("imgList") if img_list_raw: try: img_data = json.loads(img_list_raw) img_names = img_data.get("roomImageList", []) if img_names: db.update_room_field(room_id, "image_name", img_names[0] if img_names else "") except (json.JSONDecodeError, AttributeError): pass else: raw = request.get_data(cache=False) if raw: if len(raw) > _MAX_ROOM_DATA: return Response("Payload Too Large", 413) db.save_room_data(room_id, raw) print(f"[Rooms] Room {room_id} data saved ({len(request.get_data())} bytes)") room = db.get_room(room_id) return jsonify(room) if room else jsonify({}) @bp.route("/api/rooms/v1/datahistory/", methods=["GET"]) @check_auth def room_data_history(room_id): return jsonify([]) @bp.route("/api/rooms/v1/datahistory/restore", methods=["POST"]) @check_auth def restore_room_data(): return jsonify({"Success": True, "Message": ""}) @bp.route("/api/rooms/v2/instancedetails/", methods=["GET"]) @check_auth def get_instance_details(room_id): from core.state import session_mgr sessions = [s for s in session_mgr.all_public_sessions() if s.rec_room_id == room_id] return jsonify({"GameSessionCount": len(sessions), "PlayerCount": sum(len(s.players) for s in sessions)})