Upload files to "routes"

This commit is contained in:
2026-07-24 15:34:40 +00:00
parent 2ca832a741
commit 1b073dcfa3
5 changed files with 1651 additions and 0 deletions

486
routes/sessions.py Normal file
View File

@@ -0,0 +1,486 @@
import threading
from flask import Blueprint, request, jsonify, Response
from core.auth import check_auth, get_current_profile_id
from core.limiter import limiter
from core.state import db, session_mgr
from core.builders import activity_info, get_request_data
from core.ws_helpers import push_presence
from core.constants import DORM_ROOM_GUID, MSG_GAME_INVITE, MSG_PARTY_ACTIVITY_SWITCH
from core.state import ws_registry
from core.builders import now_iso
from routes.avatar import _get_activity_item_pool
_KITTYREC_PID = 23
def _send_party_invites(from_pid: int, session, party_ids: list) -> None:
if not party_ids or not session:
return
for to_id in party_ids:
if to_id == from_pid:
continue
try:
msg_id = db.send_message(from_pid, to_id, MSG_PARTY_ACTIVITY_SWITCH, "", session.session_id)
ws_registry.send(to_id, {"Id": 2, "Msg": {
"Id": msg_id, "FromPlayerId": from_pid, "SentTime": now_iso(),
"Type": MSG_PARTY_ACTIVITY_SWITCH, "Data": "",
}})
except Exception:
pass
print(f"[Party] Player {from_pid} → party invites sent to {party_ids}")
_welcomed: set[int] = set()
def _notify_room_join(pid: int, session) -> None:
try:
from core.discord import send_public
p = db.get_profile(pid)
uname = p["Username"] if p else str(pid)
dname = (p or {}).get("DisplayName", uname)
img = (p or {}).get("ProfileImageName", "")
from core.config import base_url as _base_url
player_count = len(session.players)
send_public(
title="Room Join",
color=0x9B59B6,
fields=[
{"name": "Player", "value": dname, "inline": True},
{"name": "Room", "value": session.name or "Unknown", "inline": True},
{"name": "Players in Room", "value": str(player_count), "inline": True},
],
thumbnail_url=f"{_base_url}/alt/{img}" if img else None,
throttle_key=f"roomjoin_{pid}",
throttle_secs=60,
)
except Exception:
pass
_welcomed_lock = threading.Lock()
def session_gift_count(pid: int, activity_guid: str) -> int:
return db.get_session_gift_count(pid, activity_guid)
def session_gift_increment(pid: int, activity_guid: str) -> None:
db.increment_session_gift_count(pid, activity_guid)
def session_gift_reset(pid: int) -> None:
db.reset_session_gift_counts(pid)
from core.anticheat import check_banned_room_join
bp = Blueprint("sessions", __name__)
def _send_welcome_dm(pid: int) -> None:
import time
import secrets
import string
time.sleep(10)
from tracking.password_tracking import has_real_password
if has_real_password(pid):
return
profile = db.get_profile(pid)
if not profile:
return
from werkzeug.security import generate_password_hash
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=? WHERE id=?",
(generate_password_hash(temp_pass), pid))
conn.commit()
username = profile.get("Username", f"Player{pid}")
thread_id = db.get_or_create_chat([_KITTYREC_PID, pid])
msg_text = (
f"Welcome to KittyRec!\n"
f"Username: {username}\n"
f"Temp password: {temp_pass}\n"
f"STOP SHARING YOUR SCREEN!\n"
f"Reply to this message with a new password (8+ chars) to register!"
)
msg_id = db.send_chat_message(thread_id, _KITTYREC_PID, msg_text)
msg = db.get_chat_message(msg_id)
ws_registry.send(pid, {"Id": 90, "Msg": msg})
print(f"[Welcome] Sent temp password to pid={pid} ({username})")
def _maybe_welcome(pid: int, activity_guid: str) -> None:
if activity_guid == DORM_ROOM_GUID:
return
with _welcomed_lock:
if pid in _welcomed:
return
_welcomed.add(pid)
from tracking.password_tracking import has_real_password
if has_real_password(pid):
return
profile = db.get_profile(pid)
if not profile:
return
t = threading.Thread(target=_send_welcome_dm, args=(pid,), daemon=True)
t.start()
def make_game_session_response(data: dict | None = None, force_pid: int | None = None) -> dict:
pid = force_pid or get_current_profile_id() or 1
activity_guid = DORM_ROOM_GUID
private = False
sandbox = False
rec_room_id = None
expected_ids: list[int] = []
if data:
raw_eids = data.get("ExpectedPlayerIds") or []
if isinstance(raw_eids, list):
expected_ids = [int(x) for x in raw_eids if str(x).lstrip('-').isdigit()]
level_ids = data.get("ActivityLevelIds", [])
if level_ids:
activity_guid = str(level_ids[0])
elif data.get("ActivityLevelId"):
activity_guid = str(data["ActivityLevelId"])
elif data.get("RecRoomId") or data.get("RoomId"):
rec_room_id = int(data.get("RecRoomId") or data.get("RoomId") or 0)
if rec_room_id:
if db.is_room_disabled(rec_room_id):
return {"Result": 7}
live = session_mgr.get_session(rec_room_id)
if live:
if check_banned_room_join(pid, live.activity_level_id):
return {"Result": 12}
session_gift_reset(pid)
joined = session_mgr.join_session_by_id(pid, rec_room_id)
if joined:
push_presence(pid, joined)
_maybe_welcome(pid, joined.activity_level_id)
if joined.activity_level_id != DORM_ROOM_GUID:
db.record_room_visit(pid, joined.activity_level_id, rec_room_id)
threading.Thread(target=_notify_room_join, args=(pid, joined), daemon=True).start()
print(f"[Session] Player {pid} → '{joined.name}' "
f"(sid={joined.session_id}, photon={joined.photon_room_id}, "
f"{len(joined.players)} players)")
_send_party_invites(pid, joined, expected_ids)
return {"Result": 0, "GameSession": joined.to_dict()}
else:
room = db.get_room(rec_room_id)
if room and room.get("ActivityLevelId"):
activity_guid = room["ActivityLevelId"]
private = bool(data.get("Private", False))
sandbox = bool(data.get("Sandbox", False))
if not rec_room_id and db.is_activity_disabled(activity_guid):
return {"Result": 7}
if check_banned_room_join(pid, activity_guid):
return {"Result": 12}
name, key, default_sandbox = activity_info(activity_guid)
creator_pid = pid
if rec_room_id:
room = db.get_room(rec_room_id)
if room:
name = room.get("Name") or name
sandbox = bool(room.get("IsSandbox", False))
creator_pid = room.get("CreatorPlayerId") or pid
else:
sandbox = True
else:
sandbox = sandbox or (default_sandbox and activity_guid != DORM_ROOM_GUID)
session_gift_reset(pid)
session = session_mgr.join_room(pid, activity_guid, name, key,
private=private, sandbox=sandbox,
rec_room_id=rec_room_id,
creator_pid=creator_pid)
push_presence(pid, session)
_maybe_welcome(pid, activity_guid)
if activity_guid != DORM_ROOM_GUID:
db.record_room_visit(pid, activity_guid, rec_room_id)
threading.Thread(target=_notify_room_join, args=(pid, session), daemon=True).start()
print(f"[Session] Player {pid} → '{session.name}' "
f"(sid={session.session_id}, photon={session.photon_room_id}, "
f"{len(session.players)} players)")
_send_party_invites(pid, session, expected_ids)
return {"Result": 0, "GameSession": session.to_dict()}
@bp.route("/api/gamesessions/v1/", methods=["GET"])
@check_auth
def list_game_sessions():
sessions = session_mgr.all_public_sessions()
return jsonify([s.to_v1_dict() for s in sessions])
@bp.route("/api/gamesessions/v2/create", methods=["GET", "POST"])
@check_auth
def create_game_session():
data = request.get_json(force=True, silent=True) or {}
data["Private"] = True
return jsonify(make_game_session_response(data))
@bp.route("/api/gamesessions/v2/modify", methods=["POST"])
@check_auth
def modify_game_session():
pid = get_current_profile_id()
data = request.get_json(force=True, silent=True) or {}
game_session_id = int(data.get("GameSessionId", 0))
if game_session_id:
session = session_mgr.get_session(game_session_id)
if session:
is_creator = (pid == session.creator_player_id)
is_member = (pid in session.players)
if is_creator:
if "Private" in data:
session_mgr.modify_session(game_session_id, private=bool(data["Private"]))
if "MaxCapacity" in data:
session_mgr.modify_session(game_session_id, max_capacity=int(data["MaxCapacity"]))
if (is_creator or is_member) and "InProgress" in data:
session_mgr.modify_session(game_session_id, game_in_progress=bool(data["InProgress"]))
return Response("OK", 200)
@bp.route("/api/gamesessions/v2/joinplayer", methods=["POST"])
@check_auth
def join_player_session():
pid = get_current_profile_id() or 1
data = request.get_json(force=True, silent=True) or {}
target_pid = int(data.get("PlayerId", 0))
expected_ids = data.get("ExpectedPlayerIds") or []
party_size = len(expected_ids) if isinstance(expected_ids, list) else 1
if target_pid:
session_gift_reset(pid)
session = session_mgr.join_session_of(pid, target_pid, party_size=party_size)
if session:
push_presence(pid, session)
party_ids = [int(x) for x in expected_ids if str(x).lstrip('-').isdigit()] if isinstance(expected_ids, list) else []
_send_party_invites(pid, session, party_ids)
print(f"[Session] Player {pid} joined player {target_pid}'s session "
f"(sid={session.session_id}, photon={session.photon_room_id}, party={party_size})")
return jsonify({"Result": 0, "GameSession": session.to_dict()})
return jsonify(make_game_session_response(data))
@bp.route("/api/gamesessions/v2/joinroom", methods=["POST"])
@bp.route("/api/gamesessions/v2/joinrandom", methods=["POST"])
@bp.route("/api/gamesessions/v3/joinRandom", methods=["POST"])
@bp.route("/api/gamesessions/v2/join", methods=["POST"])
@bp.route("/api/gamesessions/v2/joinevent", methods=["POST"])
@check_auth
def join_game_session():
data = request.get_json(force=True, silent=True) or {}
return jsonify(make_game_session_response(data))
@bp.route("/api/gamesessions/v3/joinroom", methods=["POST"])
@check_auth
def join_room_v3():
data = request.get_json(force=True, silent=True) or {}
return jsonify(make_game_session_response(data))
@bp.route("/api/gamesessions/v2/reportjoinresult", methods=["POST"])
@check_auth
def report_join_result():
pid = get_current_profile_id()
if pid:
data = get_request_data()
result_names = {0: "Success", 1: "FailedToConnectToRegion", 2: "FailedToConnectToRoom", 3: "FailedToSpawnPlayer"}
result_code = int(data.get("Result", 0))
props = {
"result": result_names.get(result_code, str(result_code)),
"result_code": result_code,
"region": data.get("RegionId", ""),
"room_id": data.get("RoomId", ""),
"game_session_id": data.get("GameSessionId"),
"master_player_id": data.get("MasterPlayerId"),
"rec_room_id": data.get("RecRoomId"),
}
db.save_amplitude_event(pid, "room_joinRequest", 0, props, {}, "", "")
if result_code != 0:
print(f"[JoinResult] Player {pid} failed to join room: {props['result']} (region={props['region']}, room={props['room_id']})")
return Response("OK", 200)
@bp.route("/api/gamesessions/v2/reportgamejoinresult", methods=["POST"])
@check_auth
def report_game_join_result():
pid = get_current_profile_id()
if pid:
if not session_mgr.get_player_session(pid):
print(f"[JoinResult] Rejected challenge check for pid={pid}: not in a session")
return Response("OK", 200)
data = get_request_data()
result_code = int(data.get("Result", 0))
if result_code != 0:
return Response("OK", 200)
_SOCIAL_GUIDS = {
DORM_ROOM_GUID,
"cbad71af-0831-44d8-b8ef-69edafa841f6",
"a067557f-ca32-43e6-b6e5-daaec60b4f5a",
"0a864c86-5a71-4e18-8041-8124e4dc9d98",
}
activity_guid = str(data.get("ActivityLevelId", ""))
if not activity_guid:
ids = data.get("ActivityLevelIds", [])
if ids:
activity_guid = str(ids[0])
if not activity_guid:
game_session_id = data.get("GameSessionId")
if game_session_id is not None:
gs = session_mgr.get_session(int(game_session_id))
if gs:
activity_guid = gs.activity_level_id
if not activity_guid:
rec_room_id = data.get("RecRoomId")
if rec_room_id:
room = db.get_room(int(rec_room_id))
if room:
activity_guid = room.get("ActivityLevelId", "")
if not activity_guid:
cur = session_mgr.get_player_session(pid)
if cur:
activity_guid = cur.activity_level_id
if activity_guid and activity_guid not in _SOCIAL_GUIDS:
from core.constants import get_current_weekly_challenge
from core.ws_helpers import push_gift as _push_gift
ch = get_current_weekly_challenge()
if activity_guid == ch["activity_guid"]:
db_key = ch["week"]
prog = db.get_challenge_progress(pid, db_key)
if not prog["completed"]:
new_score = db.increment_challenge_progress(pid, db_key)
print(f"[Challenge] Player {pid} progress on '{ch['title']}': {new_score}/{ch['target']}")
if new_score >= ch["target"]:
if db.try_mark_challenge_completed(pid, db_key):
import random as _rnd
from routes.avatar import _QUEST_CONSUMABLES
_pool = _get_activity_item_pool(ch["activity_guid"])
_item = _rnd.choice(_pool) if _pool else None
_consumable = _QUEST_CONSUMABLES.get(ch["activity_guid"], "")
reward = db.add_gift(pid, xp=ch["reward_xp"], gift_rarity=ch["reward_rarity"],
avatar_item_desc=_item["AvatarItemDesc"] if _item else "",
consumable_item_desc=_consumable,
message=f"Weekly Challenge: {ch['title']}!", gift_context=6)
_push_gift(pid, reward)
print(f"[Challenge] Player {pid} completed '{ch['title']}' — reward granted")
return Response("OK", 200)
@bp.route("/api/gamesessions/v2/joingamesession", methods=["POST"])
@check_auth
def join_game_session_by_id():
pid = get_current_profile_id() or 1
data = request.get_json(force=True, silent=True) or {}
game_session_id = int(data.get("GameSessionId", 0))
if game_session_id:
target_session = session_mgr.get_session(game_session_id)
if target_session and target_session.private:
return jsonify({"Result": 9})
session = session_mgr.join_session_by_id(pid, game_session_id)
if session:
push_presence(pid, session)
print(f"[Session] Player {pid} joined session {game_session_id} "
f"(photon={session.photon_room_id})")
return jsonify({"Result": 0, "GameSession": session.to_dict()})
return jsonify(make_game_session_response(data))
@bp.route("/api/gamesessions/v2/changeactivity", methods=["POST", "PUT"])
@check_auth
def change_session_activity():
pid = get_current_profile_id()
data = request.get_json(force=True, silent=True) or {}
game_session_id = int(data.get("GameSessionId", 0))
activity_id = data.get("ActivityLevelId", "")
if game_session_id and activity_id:
session = session_mgr.get_session(game_session_id)
if session and pid == session.creator_player_id:
session_mgr.modify_session(game_session_id, activity_level_id=activity_id)
push_presence(pid, session)
return Response("OK", 200)
@bp.route("/api/gamesessions/v2/changename", methods=["POST", "PUT"])
@check_auth
def change_session_name():
pid = get_current_profile_id()
data = request.get_json(force=True, silent=True) or {}
game_session_id = int(data.get("GameSessionId", 0))
name = data.get("Name", "")
if game_session_id and name:
session = session_mgr.get_session(game_session_id)
if session and pid == session.creator_player_id:
session_mgr.modify_session(game_session_id, name=name)
return Response("OK", 200)
@bp.route("/api/gamesessions/v2/changemaxcapacity", methods=["POST", "PUT"])
@check_auth
def change_session_max_capacity():
pid = get_current_profile_id()
data = request.get_json(force=True, silent=True) or {}
game_session_id = int(data.get("GameSessionId", 0))
max_cap = int(data.get("MaxCapacity", 20))
if game_session_id:
session = session_mgr.get_session(game_session_id)
if session and pid == session.creator_player_id:
session_mgr.modify_session(game_session_id, max_capacity=max_cap)
return Response("OK", 200)
@bp.route("/api/gamesessions/v2/setinprogress", methods=["POST", "PUT"])
@check_auth
def set_session_in_progress():
pid = get_current_profile_id()
data = request.get_json(force=True, silent=True) or {}
game_session_id = int(data.get("GameSessionId", 0))
in_progress = bool(data.get("InProgress", False))
if game_session_id:
session = session_mgr.get_session(game_session_id)
if session and (pid == session.creator_player_id or pid in session.players):
session_mgr.modify_session(game_session_id, game_in_progress=in_progress)
return Response("OK", 200)
@bp.route("/api/gamesessions/v2/setprivate", methods=["POST", "PUT"])
@check_auth
def set_session_private():
pid = get_current_profile_id()
data = request.get_json(force=True, silent=True) or {}
game_session_id = int(data.get("GameSessionId", 0))
private = bool(data.get("Private", False))
if game_session_id:
session = session_mgr.get_session(game_session_id)
if session and pid == session.creator_player_id:
session_mgr.modify_session(game_session_id, private=private)
return Response("OK", 200)
@bp.route("/api/gamesessions/v2/block", methods=["POST"])
@check_auth
def block_game_session():
return Response("OK", 200)
@bp.route("/api/objectives/v1/myprogress", methods=["GET"])
@check_auth
def get_objectives_progress():
return jsonify({"Objectives": [], "ObjectiveGroups": []})
@bp.route("/api/objectives/v1/cleargroup", methods=["POST"])
@check_auth
def clear_objective_group():
from datetime import datetime, timezone
data = request.get_json(force=True, silent=True) or {}
group = data.get("Group", 0)
cleared_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.0000000Z")
return jsonify({"Group": group, "IsCompleted": True, "ClearedAt": cleared_at})
@bp.route("/api/objectives/v1/updateobjective", methods=["POST"])
@check_auth
def update_objective():
return Response("OK", 200)
@bp.route("/api/objectives/v1/completegroup", methods=["POST"])
@check_auth
def complete_objective_group():
from datetime import datetime, timezone
data = request.get_json(force=True, silent=True) or {}
group = int(data.get("Group", 0))
cleared_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.0000000Z")
return jsonify({"Group": group, "IsCompleted": True, "ClearedAt": cleared_at})

151
routes/settings.py Normal file
View File

@@ -0,0 +1,151 @@
from datetime import date as _date
from flask import Blueprint, request, jsonify, Response
from core.auth import check_auth, get_current_profile_id
from core.builders import get_request_data
from core.state import db
bp = Blueprint("settings", __name__)
_SERVER_MANAGED_KEYS = {"royale_xp", "screen_mode_user"}
@bp.route("/api/settings/v2/", methods=["GET"])
@check_auth
def get_settings():
pid = get_current_profile_id()
if pid is None:
return jsonify([])
settings = db.get_settings(pid)
today_count = db.get_daily_gift_count(pid, _date.today().isoformat())
for s in settings:
if s["Key"] == "GIFT_COUNT":
s["Value"] = str(today_count)
break
else:
if today_count > 0:
settings.append({"Key": "GIFT_COUNT", "Value": str(today_count)})
is_screen_user = any(s["Key"] == "screen_mode_user" and s["Value"] == "1" for s in settings)
if is_screen_user:
has_oobe = False
for s in settings:
if s["Key"] == "Recroom.OOBE":
if s["Value"] != "100":
s["Value"] = "100"
db.set_setting(pid, "Recroom.OOBE", "100")
db.update_profile(pid, {"registration_status": 2})
has_oobe = True
break
if not has_oobe:
db.set_setting(pid, "Recroom.OOBE", "100")
db.update_profile(pid, {"registration_status": 2})
settings.append({"Key": "Recroom.OOBE", "Value": "100"})
return jsonify(settings)
@bp.route("/api/settings/v2/set", methods=["POST"])
@check_auth
def set_setting():
pid = get_current_profile_id()
data = get_request_data()
if pid is None:
print(f"[Settings] Dropping unauthenticated set: {data.get('Key', '')!r}")
return Response("OK", 200)
key = str(data.get("Key", ""))[:128]
if key in _SERVER_MANAGED_KEYS:
return Response("OK", 200)
value = str(data.get("Value", ""))[:4096]
db.set_setting(pid, key, value)
if key == "Recroom.OOBE":
db.update_profile(pid, {"registration_status": 2})
return Response("OK", 200)
@bp.route("/api/settings/v2/remove", methods=["POST"])
@check_auth
def remove_setting():
pid = get_current_profile_id()
if pid is None:
return Response("OK", 200)
data = get_request_data()
db.remove_setting(pid, data.get("Key", ""))
return Response("OK", 200)
@bp.route("/api/settings/v2/<path:key>", methods=["GET"])
@check_auth
def get_setting_by_key(key):
pid = get_current_profile_id()
if pid is None:
return jsonify({"Key": key, "Value": ""})
value = db.get_setting(pid, key)
return jsonify({"Key": key, "Value": value if value is not None else ""})
@bp.route("/api/equipment/v1/getUnlocked", methods=["GET"])
@check_auth
def get_unlocked_equipment():
pid = get_current_profile_id()
if not pid:
return jsonify([])
return jsonify(db.get_unlocked_equipment(pid))
@bp.route("/api/equipment/v1/update", methods=["POST"])
@check_auth
def update_equipment():
pid = get_current_profile_id()
if not pid:
return Response("OK", 200)
items = (request.get_json(force=True, silent=True) or [])[:200]
if isinstance(items, list) and items:
db.set_equipment_favorites(pid, items)
return jsonify([])
@bp.route("/api/consumables/v1/getUnlocked", methods=["GET"])
@check_auth
def get_unlocked_consumables():
pid = get_current_profile_id()
if not pid:
return jsonify([])
rows = db.get_consumable_inventory(pid)
from datetime import datetime, timezone
result = []
for r in rows:
raw_ts = r.get("created_at") or ""
if raw_ts and "T" not in raw_ts:
raw_ts = raw_ts.replace(" ", "T") + "Z"
if not raw_ts:
raw_ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
result.append({
"Id": r["id"],
"ConsumableItemDesc": r["consumable_item_desc"],
"CreatedAt": raw_ts,
"Count": r["count"],
"UnlockedLevel": r.get("unlocked_level", 0),
"IsActive": bool(r.get("is_active", 0)),
})
return jsonify(result)
@bp.route("/api/consumables/v1/consume", methods=["POST"])
@check_auth
def consume_consumable():
pid = get_current_profile_id()
data = get_request_data()
try:
consumable_id = int(data.get("Id", 0))
except (TypeError, ValueError):
consumable_id = 0
delta = int(data.get("DeltaCount", 1))
if pid and consumable_id:
db.use_consumable(pid, consumable_id, abs(delta))
return Response("OK", 200)
@bp.route("/api/consumables/v1/updateActive", methods=["POST"])
@check_auth
def update_active_consumable():
pid = get_current_profile_id()
data = get_request_data()
try:
consumable_id = int(data.get("Id", 0))
except (TypeError, ValueError):
consumable_id = 0
is_active = data.get("IsActive", False)
if pid and consumable_id:
db.set_consumable_active(pid, consumable_id, is_active)
return Response("OK", 200)

720
routes/storefronts.py Normal file
View File

@@ -0,0 +1,720 @@
import json
import os
import random
import time
from flask import Blueprint, request, jsonify, Response
from core.auth import check_auth, get_current_profile_id
from core.builders import now_ticks
from core.ws_helpers import push_profile_update
from core.limiter import limiter
from core.state import db, session_mgr
from routes.avatar import _generate_gift_for_player
bp = Blueprint("storefronts", __name__)
_ITEM_RARITY_MAP = {
"21caa68e-c3fa-474c-af5e-af1e742b7a60": 30,
"fb907eb2-91c8-45ff-84a5-462bb86ea7de": 30,
"ec5255d5-edaf-4888-9fe1-e89ac0e0d300": 50,
"102c625b-b988-4bf8-a2aa-a31ad7029cdc": 50,
"fe34adaf-47d3-435b-b2fd-b2fee05fceae": 20,
"b6610b7b-3978-46fd-9af6-41b4568c9b4d": 20,
"74b91f2b-d4d3-4e41-8946-b1296ab7a773": 20,
"657efe89-620a-46a2-8b58-cafd855c7cd5": 10,
"967187b8-df20-4f4f-b48f-10b9ea75cedf": 20,
"1041d745-c5e9-4218-a3e1-198f5c9c418c": 20,
"c0e59f27-a13d-4bd9-b3b8-a38a360f649b": 30,
"42aa7888-f0b9-4584-9cc1-966585c6b36e": 20,
"ff15e25d-d467-47a8-9ecc-e415d5acb90c": 50,
"35f60d27-22cf-4e17-8f39-c9e3a9fa2291": 30,
"a986ff33-9e16-4219-8ebb-2e7b4c772ca7": 20,
"34d45669-b319-4c7d-bd05-078961d70d0b": 20,
"f218e2de-46fd-45b9-9e0e-670b6bb905e7": 50,
"d0a9262f-5504-46a7-bb10-7507503db58e": 50,
"3757149b-f478-4975-81e5-d808a1bed8d5": 50,
"d6b0a1e7-e918-43e5-8191-3a8d9d01df7c": 20,
"a302741d-313b-4682-82e5-ac76764e662c": 30,
"e15b13a7-9e9a-4b32-ba2c-0cb31ed55a8c": 30,
"24c4404a-839f-46bd-98b6-6848d747a98b": 50,
"71fd5353-b439-4a23-b471-bfb99b8154d7": 50,
"7a7d8a06-7982-4bcb-b7bd-4d03b48889b4": 30,
"348ac48b-986e-4d42-a0f7-1aea16b88271": 20,
"4308da04-af84-40bb-845a-7a9e1a2726ec": 30,
"c87239ca-a255-4b13-bbc5-1b38236fb4cc": 50,
"3a790be3-2937-44d4-be01-b5d65353bd3d": 30,
"7c4d447c-6594-4bd8-9510-12ad683ab116": 0,
"e042433a-40a2-4758-8074-3b9d407835ec": 30,
"47629ed1-5378-427c-ad61-4b44d2fe90cc": 20,
"34144f4c-f6ef-49e5-a286-1781e82e6782": 20,
"6427bd57-fcb2-420f-8b3e-d1da43470b84": 20,
"7db6b49f-3e2a-4da8-bdfa-e9ad9ebc5ba6": 50,
"b89be768-a169-4b24-8022-751e7b817865": 50,
"c6c08eb5-381a-4193-9722-80da95d62abe": 10,
"f527ffaf-da03-4519-82ed-46a9cb981dc3": 50,
"08d56627-4500-4724-8692-a23c96ddb3ec": 10,
"d8f408f0-78f5-4e8a-b42a-e7b09632d1fd": 20,
"1a028850-64ee-40ab-b547-ebbcfa1b04b3": 50,
"ce250e13-8137-4f62-9e52-2b1cebe7d0ad": 30,
"c161dc73-6ce3-49c4-8d15-45e6911f84e4": 10,
"7553d851-1986-4325-870d-e425dfb7d007": 20,
"cca7ab3d-5609-4700-92fd-3280fcea9b77": 20,
"6b337a35-95d9-4b3a-9891-d9fbb06262aa": 10,
"3e139dd9-4757-43a8-8546-8da70dc17f0a": 10,
"d3d69bee-60bc-44a3-ad7c-65b3b69d1e59": 20,
"d766c8d3-76e8-4021-b0a4-24b78fb7eaba": 10,
"f76b709c-b173-426e-81f2-279a67d2fde1": 20,
"5f492f8f-ab61-484a-9587-747132b54309": 20,
"24d94673-f394-42e6-a3c8-276f8b8aa722": 20,
"843e3364-a743-4dfc-a990-0436e47b8c10": 20,
"da55bfc3-47b7-46f6-b548-7fb2c2a5e0bf": 30,
"739fd42a-8a8c-44a5-afa3-e0974802c6ae": 10,
"27e742bf-3081-4274-ba70-301f0edeb4f1": 10,
"e60fccda-8711-463d-b8a3-7cd5e76903b2": 30,
"1b37d6cd-0a89-4604-a046-e5cff55b0cf6": 30,
"9073d6a0-3bc1-4c82-aeb3-d4ee195538b4": 10,
"38b38e24-d636-41c6-b80e-a285ae3106dc": 0,
"60067e91-18b8-43ab-ae20-a8ea74c757bf": 0,
"3af4c506-d49c-4126-9437-1d3bb1658863": 0,
"5d1c42a0-7e36-431a-8e78-a8b74046d153": 10,
"2e5afc40-7e25-418c-8b1b-316b8ef479a7": 10,
"67117b3d-0669-4cf3-8a4f-066cabd4d8b1": 50,
"8d97303c-5138-4da1-a74d-378da19d11cb": 30,
"11e508a7-fe7d-470e-b270-2dba33e2f7a1": 20,
"02a5b48c-abba-4385-967b-ba900424829e": 50,
"e1a13235-e3b3-4b39-8e6f-e6449d4321b7": 30,
"587ca2bb-dd42-42bf-833f-4e2a97349866": 20,
"abc25091-ed5f-4c72-9364-fffeef1bc239": 50,
"473c672d-2b79-48a2-a49d-fd68160c5bde": 10,
"64ad8789-1645-45f7-819a-a413ff7c9622": 10,
"3bb50a88-09ae-48c7-a42c-df5879680eff": 20,
"7a6fe0e6-f930-4fb8-9b2f-4c857a273dd9": 10,
"8fc7aaef-adec-4534-8f91-445e4e7095d5": 10,
"b1c3ccc8-91d7-434e-b9cc-bd632fffc01b": 30,
"74e6878f-94e0-41f2-93ea-de6412238385": 20,
"94eb7ef3-528f-4f59-92a0-48b0ec287527": 20,
"88739d79-aeb9-471a-b25b-776f46bba9f6": 50,
"b904304b-cce0-466f-8569-c621eeadd4f7": 50,
"9d68e9f4-6ea0-4717-bb78-f2783a14a6b6": 20,
"5800d2b5-75b8-442f-8b10-63bd3d73a1b8": 10,
"b537c30c-faef-4649-9a1f-be3985936f93": 20,
"7c1552a6-bc36-46e6-884c-1de6b8111a92": 30,
"f277af6a-0807-4716-8948-1bee236ffb74": 30,
"f60e093f-33be-4527-b827-060adc77b1f4": 20,
"7134c60b-0640-463a-8d97-caa9184bef93": 20,
"293e7ad3-01c9-43af-96e3-06c34145ff12": 20,
"703f1987-2b31-4b6f-bab7-1939b1105ac0": 30,
"cea5c141-32d8-4dae-80d9-6fb74834a79c": 20,
"8c51fc1a-b1ad-4002-a13c-4313abd92c7f": 20,
"4fcb5b84-13a9-43e6-9680-72b17874ae53": 50,
"3044adce-90c0-4f66-81f5-39c4fca86fdf": 20,
"eada710d-ea0c-473f-b9c6-23e210607b24": 20,
"bb54e0e9-5d90-41f3-94c0-8e82f1791af1": 30,
"18feb3c2-049f-4f91-9f4e-6b5fcb4ab70c": 20,
"a16d59da-caa5-4388-af67-315bfcb16f64": 10,
"5ac25e5a-8c8e-445c-82a4-7272baec1eb5": 10,
"07205057-0804-41de-abe4-bd4027fee1df": 20,
"ef84cb35-5e25-4aa6-82c9-17f01a5040c7": 10,
"8263a9ca-8c57-4e81-b3e3-24f2ca19a70a": 20,
"418ed21e-766f-4c69-9d57-6f866dcc7feb": 30,
"03f8c394-28fa-4087-978b-8d108f0bd969": 20,
"9cdb4965-6f00-4304-afed-e301e73a2b3a": 10,
"b861e5f3-fc6d-43b3-9861-c1b45cb493a8": 50,
"f17a2f9e-1eab-44e8-b10a-1f53c5d0778c": 20,
"49397e16-1027-4286-9bc4-b59eae565ff0": 10,
"61ba3c90-c81e-4deb-bc79-50c0f1fe3e83": 20,
"2b7f4dae-51da-4af0-b009-12d6005c85c6": 10,
"27cdecd2-88f1-40a8-80a9-87abd827c3c5": 10,
"b9e0f03b-2609-4911-82e9-1e324dbbe8be": 0,
"664485e9-a159-4fcb-b32c-2b114b4a1218": 0,
"eceb7d49-be41-4228-86a9-2973d62e7135": 0,
"3b00c71f-79c2-4a04-9fc0-a23b4c85562f": 0,
"3df394de-9c3e-4141-aba4-12eac4742102": 0,
"274cb9b2-2f59-47ea-9a8d-a5b656d148c6": 50,
"b02053b3-013f-42b0-8881-85f5be2b8cda": 30,
"62ce4109-8dee-4895-bf1b-bfa143db4c7e": 0,
"9c8fc7f0-8f99-4aad-a34f-8d979f6ae352": 0,
"896c2491-2f96-4986-9cbd-b3b31ef5d8c5": 0,
"f41653f9-ae02-443c-aaf4-1c6f4e49035d": 30,
"77c37481-a185-47ff-af55-65f9fdfcf9e5": 30,
"6d815b35-6f68-4ed4-817d-70f141e1a571": 30,
"84cd594c-1cd8-4b4d-8409-85c8fd5fb02a": 30,
"745c5110-104e-4b37-aabf-7c690fd54811": 10,
"f51a7ed5-52ea-485f-a430-303697f6fec9": 30,
"515dfc36-7f7b-47bc-abee-380d68f41be6": 30,
"2296ed0d-df56-4d46-b33a-aae9230a47fc": 30,
"06306723-ca20-4aa6-b7b3-917113f41ac3": 0,
"c70005d5-6276-4a98-acb3-6a77bc19379a": 0,
"1d27b674-f9e2-4ffc-9d8c-a58a1be06457": 0,
"0088603e-ec3b-4478-8694-e6fb1989b3f2": 0,
"880a3cc0-7407-4b61-b759-f9dd890fe9e5": 0,
"e36bcd98-7e85-43fa-89f8-57e4ec33823a": 0,
"fcfcaf63-deb4-45f7-b711-c051c9ea45cb": 0,
"da4e7b34-2095-4a9e-801e-4f409039e0dd": 0,
"b148cb1e-df81-442f-aea6-ab1727aad00e": 0,
"eb9611c6-bb50-41a2-93e9-7f959815a846": 0,
"193a3bf9-abc0-4d78-8d63-92046908b1c5": 0,
"e286863c-2967-4d00-b837-b49487b9484a": 0,
"09177621-9ecd-4f6a-b6a5-64490139141d": 0,
"0753d7a4-8247-4fca-a6fc-359c26086140": 0,
"d84c0ff9-8fbe-4ed8-abf3-7996e81888ab": 0,
"95ab7a7c-c35d-4da5-9955-0921064470b6": 0,
"241506f6-bf88-4b46-b5fe-513a225421f4": 0,
"ffea7a65-613f-4835-921e-6dd15f357b7e": 0,
"21599b51-c50f-43d8-ac5f-62c30cd02ca5": 0,
"24a240f4-1574-420b-b898-a7e91f170759": 0,
"c45ed7b8-99bd-4a4b-a9ff-e16edf5d7a18": 0,
"9d9fadb6-97eb-480e-a224-4e0179082071": 0,
"e49d5d78-157e-4bc8-b878-ff7c4963fdc4": 10,
"92302d9d-c527-418c-ac5d-1fa869727505": 0,
"79b90274-6eec-4664-acfb-4a123334661e": 0,
"1fd69ef8-0b74-4962-af5a-67f0bf0358f2": 0,
"8b9f1413-e786-4a30-946c-9292f207875a": 0,
"2cb4f372-3372-4583-8b57-c4e3988e3c28": 0,
"d8280c0c-d803-4513-be10-a0ba96d8821e": 0,
"1a71064b-794f-40fa-9109-8ad36602b6e1": 0,
"77d3c585-4928-4471-a425-89036efe7299": 0,
"a12f724f-4a73-4ab8-aad4-6bfc662b4dd6": 0,
"f9dd08f8-16d3-4c39-af4f-89f7bb6e80d3": 0,
"e5b83dfc-b2e1-4dcb-a4ab-9d3a4c8a34ae": 0,
"7dd6f7b0-7ba0-429f-a04f-e32d3a79ee61": 0,
"529015c7-3b4a-4a73-b2c3-33103339b6e3": 10,
"d2d3264b-fbf6-40b5-9f10-c85ec737d112": 30,
"17aed0a0-70ed-49da-ad09-5bc4746f7718": 20,
"dcf9012d-f9e9-4f15-872e-f130af3b2efa": 20,
"14ef6b00-debf-4a85-9755-b4d37df496d3": 0,
"71014872-d879-4858-9d68-58da3c673d8b": 20,
"1e504fee-b593-4037-bd8f-b88025147991": 20,
"b99a89c7-38c5-4196-9862-4e1bf9cb0ce1": 50,
"3d5184e1-0201-4476-bf4b-4eb28190de62": 50,
"ad0bdec5-f767-42e7-99e0-221473464a85": 50,
"34654303-9760-447f-8614-1c26506db994": 20,
"a628d62c-fa30-4405-bcbc-3e646e3a3434": 20,
"ec836d2a-b1b8-4566-b8eb-123ae2845956": 30,
"5e3929d3-d291-4e91-a0ba-2ef203e407d3": 10,
"2b2eb9e5-d52e-4004-bdb2-0bcf6910992d": 30,
"5a38f864-7d1c-4989-8558-40b9668f78ef": 20,
"2faa26b6-f7c3-4b0d-8f70-1f9454e64a54": 20,
"40528de7-38a3-4a7c-8f93-6d3bfa5573f2": 0,
"a61e86cd-f7e7-4ac7-a6e8-df269bc5cb01": 30,
"8d703940-224a-4b0c-a04d-f365550071e1": 10,
"e614df5d-3cfe-4bca-b9c2-30c267b9c94e": 10,
"123de433-a005-4994-8a11-d2d84ad66b11": 20,
"1596c113-aa3a-4f5c-b398-e5c3575548e7": 30,
"76369aef-aeda-46d2-996a-cd00594d0543": 20,
"8d17031a-c0a5-4145-92b7-1f0c2d8f0ce6": 0,
"f5c9743f-e77c-42f2-ba63-9843342cbf8e": 30,
"59d9560d-e5af-4205-b860-3afea1cc31a9": 10,
"6d36091e-7083-4e3d-8729-94612602c8cb": 50,
"01689baf-405e-4b38-9f09-b624e03865b8": 10,
"8d10cc78-6b00-45f3-affb-205e9cc5b03f": 0,
"cc96f8a5-bc5b-4f89-83b7-ecd53905ada7": 0,
"9bf5d259-7774-4cbe-a90f-7f188cc0dce7": 0,
"45f5e714-8a5f-4385-a97f-675066167011": 0,
"5b6535f0-86cd-417a-bcce-a1ace9a5f260": 30,
"83be5ba4-525a-4781-a5f6-839c22e4d1d3": 20,
"5accb7dc-90a3-46ee-bad2-8fd1861d50f1": 10,
"bf13fa1c-f991-4aaa-9402-aac109be9562": 50,
"6b9e022c-0b68-48fd-8eca-da8573c18900": 0,
"5cd08cfb-c729-4c30-96d9-6a99bb934d91": 0,
"f47f81e7-fcdd-4687-9b99-013147bef30f": 20,
"bf9dc196-5727-4752-8126-7ad5fcd96d55": 10,
"2f8518fc-c989-40de-98b4-c6f09b304166": 20,
"de0ac50d-2adb-4114-bd2e-68953b13d706": 0,
"2e59d8d0-91a0-4449-bfdc-a5d663fd9343": 10,
"ba84b23e-01ee-4668-a7ef-2e3e0eca2f23": 50,
"4d507dfa-4a99-4ac0-8537-229e9dc0eb4a": 0,
"8aa79563-ace1-4ba7-ad0c-f3210a78142f": 0,
"9c34c2c1-07d7-4180-94a2-be8c9caaae84": 20,
"2c679f89-c76e-4cfb-94e9-448c8fd44d55": 50,
"6930ce13-4be4-4ab9-9817-667bd261ffc3": 50,
"0bc6bd1b-8b7e-4945-a1d6-c26b9c043318": 20,
"b1bfe0b4-1ff6-420f-acfc-2331d34246dc": 20,
"02077915-57d3-4e26-b4fe-8e0399cbb293": 20,
"18cd3470-2dd9-4a0a-98bd-eae2d5f5d522": 30,
"e9913b06-58cb-4b90-bd08-981a3f19f352": 20,
"c3745cee-d87e-4a23-b6e2-64ebf05c8b11": 50,
"a6f1825e-1647-4d06-85d7-ac2d139612c0": 50,
"3dc003c5-428b-47d6-80fb-6520b63119e8": 20,
"ff7e6d41-5c27-4516-930c-ad0e9a23cce2": 20,
"5f600892-aa67-484a-afc7-14c219d89c52": 30,
"7b857a8c-92ad-4028-a2c2-b3c20cdab5f2": 0,
"39278302-b52a-48a8-a566-ed756a5fa1a9": 10,
"350c5c1e-318b-4233-a7e5-1f49909d8e65": 20,
"e4ba395e-f291-4e7b-8193-45f4422f41ce": 20,
"a96e168c-0c4d-4c70-9f8a-c8f07164ce99": 10,
"25d4c652-1730-4925-925e-31a290a2272a": 10,
"4ce7a70f-15a0-4cad-98ee-5cbb40827338": 10,
"418db0e0-c7af-40c2-9cac-d461ce41e210": 50,
"97eae086-cfea-45ff-9b77-1d184256d493": 10,
"5b01eaa3-0cac-40c0-b72a-b3f6a868ae0c": 30,
"125a3a62-1005-47dc-9fd8-ee09ea803e9f": 10,
"ce81210f-8eb8-4cd2-95d5-046d4da229c8": 10,
"9eb7f505-5afd-4b28-9886-7996d38c59c6": 20,
"4d533b3a-b5fa-446a-842d-92798ad5b493": 20,
"9bf9d502-8a3c-4b24-9565-0a2c2d9864fd": 10,
"28374ebc-4050-4ea0-b3b6-41ebe75cedf7": 10,
"74365234-cb72-409d-8cf5-9a7209f707e1": 10,
"50c9c6f8-2963-4ef3-95d5-e999a898269f": 50,
"3dec4865-cf23-4c19-a460-dd2db80ee851": 10,
"4763436c-2dcc-482a-bf37-a6b16d7aae6e": 10,
"1974dd48-aa44-434f-879a-eaff0c7c06e6": 50,
"22ef1089-d073-4fe8-b038-6f34adf0b85f": 10,
"ecc1dbe6-ca06-4564-b2a6-30956194d1e9": 0,
"71921831-ba6f-408b-a00e-2fd97663636f": 0,
}
_store_items_cache = None
_store_seed_offset = 0
def _load_store_items():
global _store_items_cache
if _store_items_cache is not None:
return _store_items_cache
data_path = os.path.join(os.path.dirname(__file__), "..", "data", "avataritems.json")
try:
with open(data_path, encoding="utf-8") as f:
raw = json.load(f)
except Exception as exc:
print(f"[Store] Could not load avataritems.json: {exc}")
raw = []
seen_descs = set()
items = []
for i, entry in enumerate(raw):
desc = entry.get("AvatarItemDesc", "")
body = desc.split(",")[0]
if not body or desc in seen_descs:
continue
seen_descs.add(desc)
rarity = _ITEM_RARITY_MAP.get(body, 10)
name = entry.get("FriendlyName", "Unknown Item")
full_desc = desc if "," in desc else f"{body},,,"
items.append({
"GiftDropId": i + 1,
"FriendlyName": name,
"Tooltip": f"Wear the {name} in Rec Room!",
"AvatarItemDesc": full_desc,
"ConsumableItemDesc": "",
"EquipmentPrefabName": "",
"EquipmentModificationGuid": "",
"Rarity": rarity,
"IsQuery": False,
"Unique": False,
"Level": 1,
"Context": 0,
})
_store_items_cache = items
print(f"[Store] Loaded {len(items)} store items from avataritems.json")
return items
def _store_item_map():
all_items = _load_store_items() + _LEGENDARY_ITEMS
return {item["GiftDropId"]: item for item in all_items}
_RARITY_PRICE = {0: 120, 10: 320, 20: 800, 30: 2000, 50: 4800}
_RARITY_TICKET_PRICE = {0: 80, 10: 210, 20: 530, 30: 1330, 50: 3200}
_RARITY_SKULL_PRICE = {0: 40, 10: 105, 20: 265, 30: 660, 50: 1600}
_ROTATION_WINDOW_SECS = 86400
_ROTATION_SIZE = 8
_FOOD_ITEMS = [
{"GiftDropId": 9001, "FriendlyName": "Cheese Pizza", "Tooltip": "A delicious slice.", "AvatarItemDesc": "", "ConsumableItemDesc": "5hIAZ9wg5EyG1cILf4FS2A", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 0, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9002, "FriendlyName": "Pepperoni Pizza", "Tooltip": "Extra pepperoni!", "AvatarItemDesc": "", "ConsumableItemDesc": "mq23W-RSP0G8iGNLdrcpUw", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 0, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9003, "FriendlyName": "Supreme Pizza", "Tooltip": "Everything on it.", "AvatarItemDesc": "", "ConsumableItemDesc": "wUCIKdJSvEmiQHYMyx4X4w", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 10, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9004, "FriendlyName": "Root Beer", "Tooltip": "Frosty and refreshing.", "AvatarItemDesc": "", "ConsumableItemDesc": "JfnVXFmilU6ysv-VbTAe3A", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 0, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9005, "FriendlyName": "Cola", "Tooltip": "The classic Rec Room drink.", "AvatarItemDesc": "", "ConsumableItemDesc": "wx--2TPTdEuGAqLCjs9Qag", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 0, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9006, "FriendlyName": "Bear Claw", "Tooltip": "A sweet pastry.", "AvatarItemDesc": "", "ConsumableItemDesc": "ZtZnYBpKkECJlhHmkj4MiA", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 0, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9007, "FriendlyName": "Ego Potion", "Tooltip": "Makes your head grow!", "AvatarItemDesc": "", "ConsumableItemDesc": "Tpxqe_lycUelySRHM8B0Vw", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 20, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9008, "FriendlyName": "High Five O'Spells", "Tooltip": "Magical high fives!", "AvatarItemDesc": "", "ConsumableItemDesc": "VQSgL2pTLkWx4B3kwYG7UA", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 20, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9009, "FriendlyName": "High Five O'Gold", "Tooltip": "Golden high fives!", "AvatarItemDesc": "", "ConsumableItemDesc": "-hy0qD-iUk-v4NHxNzanmg", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 20, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9010, "FriendlyName": "High Five O'Lasers", "Tooltip": "Laser high fives!", "AvatarItemDesc": "", "ConsumableItemDesc": "xHOwjwpXd0GDkvBz2VqieA", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 20, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9011, "FriendlyName": "Goblin King Film", "Tooltip": "Quest camera filter.", "AvatarItemDesc": "", "ConsumableItemDesc": "6SyCoJCgo0Wd6qlPlnMOtg", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 10, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9012, "FriendlyName": "Sepia Camera Film", "Tooltip": "Classic sepia filter.", "AvatarItemDesc": "", "ConsumableItemDesc": "A5M-yf9tgUihq1uab3v58g", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 10, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9013, "FriendlyName": "B&W Camera Film", "Tooltip": "Black & white filter.", "AvatarItemDesc": "", "ConsumableItemDesc": "frOMH6WxDEG1fBqC4_83vg", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 10, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9014, "FriendlyName": "Dawn Camera Film", "Tooltip": "Beautiful dawn filter.", "AvatarItemDesc": "", "ConsumableItemDesc": "m0bVLwWGj0GuIBSb6wCk6Q", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 10, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9015, "FriendlyName": "Ghost Beard Film", "Tooltip": "Spooky pirate filter.", "AvatarItemDesc": "", "ConsumableItemDesc": "1c0Djlp090uBDczEobYNQw", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 10, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9016, "FriendlyName": "Witch Film", "Tooltip": "Mystical witch filter.", "AvatarItemDesc": "", "ConsumableItemDesc": "mL3zCEuy2UWZxAV4V-OsMA", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 10, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 9017, "FriendlyName": "Jumbotron Film", "Tooltip": "Sci-fi camera filter.", "AvatarItemDesc": "", "ConsumableItemDesc": "Il4VmrnjDkqjmjzddqoIEw", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 10, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
]
_LEGENDARY_ITEMS = [
{"GiftDropId": 8001, "FriendlyName": "Saija Helmet", "Tooltip": "Legendary Saija warrior helmet.", "AvatarItemDesc": "274cb9b2-2f59-47ea-9a8d-a5b656d148c6,,,", "ConsumableItemDesc": "", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 50, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 8004, "FriendlyName": "Astronaut Helmet", "Tooltip": "Space-worthy helmet.", "AvatarItemDesc": "f218e2de-46fd-45b9-9e0e-670b6bb905e7,,,", "ConsumableItemDesc": "", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 50, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 8005, "FriendlyName": "Top Hat", "Tooltip": "A dapper top hat.", "AvatarItemDesc": "102c625b-b988-4bf8-a2aa-a31ad7029cdc,,,", "ConsumableItemDesc": "", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 50, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
{"GiftDropId": 8006, "FriendlyName": "Bunny Ears", "Tooltip": "Fluffy bunny ears.", "AvatarItemDesc": "71fd5353-b439-4a23-b471-bfb99b8154d7,,,", "ConsumableItemDesc": "", "EquipmentPrefabName": "", "EquipmentModificationGuid": "", "Rarity": 50, "IsQuery": False, "Unique": False, "Level": 1, "Context": 0},
]
def reroll_store():
global _store_seed_offset
_store_seed_offset += 1
return _store_seed_offset
def _current_store_items():
window = int(time.time()) // _ROTATION_WINDOW_SECS + _store_seed_offset
rng = random.Random(window)
all_items = _store_item_map()
featured_slots = []
try:
from core.state import db
for entry in db.get_store_featured():
item = all_items.get(entry["gift_drop_id"])
if item:
featured_slots.append(item)
except Exception:
pass
featured_ids = {i["GiftDropId"] for i in featured_slots}
legend_pool = [i for i in _LEGENDARY_ITEMS if i["GiftDropId"] not in featured_ids]
rng.shuffle(legend_pool)
legend_picks = legend_pool[:max(0, 2 - sum(1 for i in featured_slots if i["GiftDropId"] >= 8000))]
food_picks = []
legendary_guids = {i["AvatarItemDesc"].split(",")[0] for i in _LEGENDARY_ITEMS if i["AvatarItemDesc"]}
try:
from routes.avatar import _avatar_cfg
_excluded_guids = set(_avatar_cfg.get("starter_item_guids", [])) | set(_avatar_cfg.get("hair_item_guids", []))
except Exception:
_excluded_guids = set()
avatar_pool = [i for i in _load_store_items()
if i["GiftDropId"] < 8000
and i["GiftDropId"] not in featured_ids
and i["AvatarItemDesc"].split(",")[0] not in legendary_guids
and i["AvatarItemDesc"].split(",")[0] not in _excluded_guids]
rng.shuffle(avatar_pool)
remaining_slots = max(0, _ROTATION_SIZE * 2 + 2 - len(featured_slots) - len(legend_picks) - len(food_picks))
avatar_picks = avatar_pool[:remaining_slots]
return featured_slots + legend_picks + food_picks + avatar_picks
def _secs_until_next_rotation():
now = int(time.time())
return _ROTATION_WINDOW_SECS - (now % _ROTATION_WINDOW_SECS)
_BALANCE_ADD_CONFIG = {
100: {"base": 500, "bonus_max": 0},
200: {"base": 100, "bonus_max": 0},
1000: {"base": 250, "bonus_max": 100},
1001: {"base": 75, "bonus_max": 25},
1100: {"base": 250, "bonus_max": 0},
1200: {"base": 500, "bonus_max": 0},
}
def _wrap_store_items(items):
return [
{
"PurchasableItemId": item["GiftDropId"],
"Type": 0,
"IsFeatured": False,
"Prices": [
{"CurrencyType": 1, "Price": _RARITY_TICKET_PRICE.get(item["Rarity"], 100)},
{"CurrencyType": 2, "Price": _RARITY_PRICE.get(item["Rarity"], 150)},
{"CurrencyType": 100, "Price": _RARITY_SKULL_PRICE.get(item["Rarity"], 50)},
],
"GiftDrops": [item],
}
for item in items
]
@bp.route("/api/storefronts/v3/giftdropstore/<int:store_id>", methods=["GET"])
@check_auth
def get_gift_drop_store(store_id):
next_update_ticks = now_ticks() + _secs_until_next_rotation() * 10_000_000
items = _current_store_items()
legendary_ids = {i["GiftDropId"] for i in _LEGENDARY_ITEMS}
if store_id == 3:
store_items = [
{
"PurchasableItemId": item["GiftDropId"],
"Type": 0,
"IsFeatured": item["GiftDropId"] in legendary_ids,
"Prices": [
{"CurrencyType": 1, "Price": _RARITY_TICKET_PRICE.get(item["Rarity"], 100)},
{"CurrencyType": 2, "Price": _RARITY_PRICE.get(item["Rarity"], 150)},
{"CurrencyType": 100, "Price": _RARITY_SKULL_PRICE.get(item["Rarity"], 50)},
],
"GiftDrops": [item],
}
for item in items
]
else:
store_items = _wrap_store_items(items)
return jsonify({
"StorefrontType": store_id,
"NextUpdate": next_update_ticks,
"StoreItems": store_items,
})
@bp.route("/api/storefronts/v3/balance/<int:currency_id>", methods=["GET"])
@check_auth
def get_balance(currency_id):
pid = get_current_profile_id()
balance = db.get_tokens(pid) if (pid and currency_id == 2) else 0
return jsonify({"CurrencyType": currency_id, "Balance": balance})
@bp.route("/api/storefronts/v2/balance", methods=["GET", "POST"])
@bp.route("/api/storefronts/v3/balance", methods=["GET", "POST"])
@limiter.limit("10 per minute")
@check_auth
def balance_v2():
pid = get_current_profile_id()
if request.method == "GET":
tokens = db.get_tokens(pid) if pid else 0
return jsonify([
{"CurrencyType": 1, "Balance": 0},
{"CurrencyType": 2, "Balance": tokens},
{"CurrencyType": 100, "Balance": 0},
])
if not session_mgr.get_player_session(pid):
print(f"[Tokens] Rejected balance POST for pid={pid}: not in a session")
tokens = db.get_tokens(pid) if pid else 0
return jsonify({"Balance": tokens, "CurrencyType": 2, "BalanceUpdates": []})
data = request.get_json(force=True, silent=True) or {}
currency_type = int(data.get("CurrencyType", 2))
balance_adds = (data.get("BalanceAdds", []) or [])[:5]
updates = []
total_awarded = 0
seen_types = set()
for add in balance_adds:
add_type = int(add.get("BalanceAddType", 0))
if add_type in seen_types:
continue
seen_types.add(add_type)
multiplier = min(float(add.get("Multiplier", 1.0)), 1.0)
config = _BALANCE_ADD_CONFIG.get(add_type, {"base": 0, "bonus_max": 0})
base_award = int(config["base"] * multiplier)
bonus_award = random.randint(0, config["bonus_max"]) if config["bonus_max"] > 0 else 0
total = base_award + bonus_award
total_awarded += total
updates.append({
"UpdateResponse": 0,
"Data": {
"BalanceAddType": add_type,
"BaseAward": base_award,
"BonusAward": bonus_award,
"RateLimit": 0,
"CurrentCount": 1,
"Total": total,
"BalanceInGiftBox": False,
},
})
new_balance = db.update_tokens(pid, total_awarded) if pid else 0
if total_awarded > 0:
types = [a.get("BalanceAddType") for a in balance_adds]
print(f"[Tokens] Player {pid} earned {total_awarded} tokens "
f"(balance: {new_balance}, types: {types})")
return jsonify({
"Balance": new_balance,
"CurrencyType": currency_type,
"BalanceUpdates": updates,
})
@bp.route("/api/storefronts/v1/objectives", methods=["GET", "POST"])
@check_auth
def get_storefront_objectives():
return jsonify([])
@bp.route("/api/storefronts/v1/season/<int:store_id>", methods=["GET"])
@check_auth
def get_season(store_id):
from core.builders import now_iso
now = now_iso()
return jsonify({
"StorefrontType": store_id,
"NextUpdate": now,
"Season": 1,
"Name": "Season 1",
"StartAt": now,
"EndAt": now,
"CurrencyType": store_id,
"Tiers": [],
"PersonalDetails": {
"HasEliteUpgrade": False,
"CurrentSeasonTier": 0,
"ModifiedAt": now,
},
})
@bp.route("/api/storefronts/v1/buyElite", methods=["POST"])
@bp.route("/api/storefronts/v1/buyTier", methods=["POST"])
@check_auth
def storefront_purchase_elite():
return jsonify({})
def _do_buy(pid: int, gift_drop_id: int) -> dict:
current_ids = {i["GiftDropId"] for i in _current_store_items()}
store_item = _store_item_map().get(gift_drop_id) if gift_drop_id in current_ids else None
if not pid or not store_item:
balance = db.get_tokens(pid) if pid else 0
return {"Balance": balance, "CurrencyType": 2, "BalanceUpdates": [{"UpdateResponse": 4}]}
price = _RARITY_PRICE.get(store_item["Rarity"], 300)
new_balance = db.deduct_tokens_if_enough(pid, price)
if new_balance is None:
current_balance = db.get_tokens(pid)
print(f"[Store] Player {pid} cannot afford {store_item['FriendlyName']} "
f"(price={price}, balance={current_balance})")
return {"Balance": current_balance, "CurrencyType": 2, "BalanceUpdates": [{"UpdateResponse": 2}]}
gift = db.add_gift(
pid, xp=0, gift_rarity=store_item["Rarity"],
equipment_prefab_name=store_item["EquipmentPrefabName"],
equipment_modification_guid=store_item["EquipmentModificationGuid"],
avatar_item_desc=store_item["AvatarItemDesc"],
consumable_item_desc=store_item["ConsumableItemDesc"],
gift_context=0,
)
if store_item["AvatarItemDesc"]:
db.unlock_avatar_item(pid, store_item["AvatarItemDesc"])
if store_item["ConsumableItemDesc"]:
desc = store_item["ConsumableItemDesc"]
count = 60 if desc.startswith("Consumable_") else 1
db.add_consumable(pid, desc, count)
push_profile_update(pid)
print(f"[Store] Player {pid} bought {store_item['FriendlyName']} "
f"for {price} tokens (new balance: {new_balance})")
return {
"Balance": new_balance,
"CurrencyType": 2,
"BalanceUpdates": [{
"UpdateResponse": 0,
"Data": [gift],
}],
}
@bp.route("/api/storefronts/v1/buyItem", methods=["POST"])
@check_auth
def storefront_buy_item():
pid = get_current_profile_id()
data = request.get_json(force=True, silent=True) or {}
gift_drop_id = int(
data.get("PurchasableItemId") or data.get("GiftDropId") or
request.values.get("PurchasableItemId", 0)
)
return jsonify(_do_buy(pid, gift_drop_id))
@bp.route("/api/storefronts/v2/buy", methods=["POST"])
@check_auth
def storefront_buy_v2():
pid = get_current_profile_id()
data = request.get_json(force=True, silent=True) or {}
gift_drop_id = int(data.get("GiftDropId", 0))
return jsonify(_do_buy(pid, gift_drop_id))
@bp.route("/api/storefronts/v1/allGiftDrops/<int:store_id>", methods=["GET"])
@check_auth
def all_gift_drops(store_id):
items = [dict(item, Cost=_RARITY_PRICE.get(item["Rarity"], 150)) for item in _current_store_items()]
return jsonify(items)
@bp.route("/api/storefronts/v2/<int:store_id>", methods=["GET"])
@check_auth
def get_storefront_v2(store_id):
items = [dict(item, Cost=_RARITY_PRICE.get(item["Rarity"], 150)) for item in _current_store_items()]
secs = _secs_until_next_rotation()
end_ts = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + secs))
return jsonify({
"StoreItems": items,
"StartAt": "2018-01-01T00:00:00Z",
"EndAt": end_ts,
})
@bp.route("/api/storefronts/v1/balance/<int:currency_id>", methods=["GET"])
@check_auth
def balance_v1(currency_id):
pid = get_current_profile_id()
balance = db.get_tokens(pid) if (pid and currency_id == 2) else 0
return jsonify({"Balance": balance, "StorefrontType": currency_id})
@bp.route("/api/storefronts/v1/balanceAddType/<int:currency>/<int:add_type>", methods=["GET"])
@check_auth
def balance_add_type(currency, add_type):
return jsonify({"CurrencyType": currency, "BalanceAddType": add_type, "RateLimitType": 0})
@bp.route("/api/checklist/v1/current", methods=["GET"])
@check_auth
def get_checklist():
return jsonify([])
@bp.route("/api/checklist/v1/complete", methods=["POST"])
@check_auth
def complete_checklist():
return Response("OK", 200)
_last_rotation_window = None
def _get_rotation_window():
return int(time.time()) // _ROTATION_WINDOW_SECS + _store_seed_offset
def _broadcast_store_refresh():
from core.state import ws_registry, _KITTYREC_SYSTEM_PID
from core.builders import now_iso
ws_registry.broadcast({
"Id": 2,
"Msg": {
"Id": 0,
"FromPlayerId": _KITTYREC_SYSTEM_PID,
"SentTime": now_iso(),
"Type": 30,
"Data": "The store has refreshed! Check out the new items.",
"RoomId": None,
"PlayerEventId": None,
},
})
print("[Store] Broadcast store refresh notification to connected players")
def _store_rotation_watcher():
global _last_rotation_window
_last_rotation_window = _get_rotation_window()
while True:
time.sleep(10)
current = _get_rotation_window()
if current != _last_rotation_window:
_last_rotation_window = current
_broadcast_store_refresh()
def start_store_watcher():
import threading
t = threading.Thread(target=_store_rotation_watcher, daemon=True)
t.start()
print("[Store] Rotation watcher started (interval: 1h)")

22
routes/ugc.py Normal file
View File

@@ -0,0 +1,22 @@
import json
import os
from flask import Blueprint, jsonify, abort
bp = Blueprint("ugc", __name__)
_DATA_PATH = os.path.join(os.path.dirname(__file__), "..", "data", "ugc_outfit_items.json")
def _load_items():
try:
with open(_DATA_PATH, encoding="utf-8") as f:
return json.load(f)
except Exception:
return []
@bp.route("/api/ugc/v1/outfititem/get", methods=["GET"])
def get_outfit_items():
return abort(410)

272
routes/ws.py Normal file
View File

@@ -0,0 +1,272 @@
import json
import threading
from core.state import db, session_mgr, ws_registry
from core.ws_helpers import push_presence, push_gift
from core.builders import activity_info
from core.ban_service import cascade_kick_linked, kick_player
from core.constants import DORM_ROOM_GUID
from core.config import server as _server_cfg, base_url as _base_url
SERVER_BUILD = _server_cfg.get("build", "")
_next_session_id = 1
_session_lock = threading.Lock()
def _is_ip_banned(ip: str) -> bool:
return db.is_ip_banned(ip)
def register_ws(sock) -> None:
@sock.route("/api/notification/v2")
def notification_ws(ws):
global _next_session_id
from core.auth import get_current_profile_id
from flask import request as ws_req
pid = get_current_profile_id()
if pid is None:
print("[WS] Rejected unauthenticated WebSocket connection")
ws.close()
return
ip = (ws_req.headers.get("X-Forwarded-For", "") or ws_req.remote_addr or "").split(",")[0].strip()
if ip and ip not in ("127.0.0.1", "::1"):
db.record_ip_login(pid, ip)
if db.is_banned(pid):
print(f"[WS] Banned player {pid} tried to connect — closing")
cascade_kick_linked(pid)
try:
ws.send(json.dumps({"Id": 20, "Msg": {}}))
except Exception:
pass
ws.close()
return
import core.state as _st
with _st.maintenance_lock:
maint = _st.maintenance_mode
if maint:
if pid not in _st.maintenance_exempt:
print(f"[WS] Player {pid} rejected during maintenance")
ws.close()
return
if _is_ip_banned(ip):
print(f"[WS] IP-banned address {ip} tried to connect (pid={pid}) — closing")
if not db.is_banned(pid):
db.ban_player(pid, reason="Banned by IP association", duration_hours=0, admin_name="AntiCheat")
print(f"[AntiCheat] IP cascade ban: player {pid} at banned IP {ip}")
cascade_kick_linked(pid)
try:
ws.send(json.dumps({"Id": 20, "Msg": {}}))
except Exception:
pass
ws.close()
return
try:
handshake_raw = ws.receive()
if handshake_raw is None:
print(f"[WS] Player {pid}: connection closed before handshake")
return
handshake = json.loads(handshake_raw)
print(f"[WS] Player {pid} connected (keys: {list(handshake.keys())})")
except Exception as e:
print(f"[WS] Bad handshake from player {pid}: {e}")
return
with _session_lock:
ws_session_id = _next_session_id
_next_session_id += 1
ws.send(json.dumps({"SessionId": ws_session_id}))
ws_registry.register(pid, ws)
from core.daemons import record_session_start
record_session_start(pid)
for pending in db.get_pending_gifts(pid):
try:
push_gift(pid, pending)
except Exception:
pass
from core.daemons import record_heartbeat
record_heartbeat(pid)
settings = db.get_settings(pid)
if any(s["Key"] == "screen_mode_user" and s["Value"] == "1" for s in settings):
ws_registry.set_screen_mode(pid, True)
try:
from core.discord import mark_first_login, send_public
if mark_first_login(pid):
p = db.get_profile(pid)
uname = p["Username"] if p else str(pid)
dname = (p or {}).get("DisplayName", uname)
img = (p or {}).get("ProfileImageName", "")
send_public(
title="First Login!",
color=0x3498DB,
fields=[{"name": "Player", "value": uname, "inline": True},
{"name": "ID", "value": str(pid), "inline": True}],
description=f"**{dname}** just logged in for the very first time!",
thumbnail_url=f"{_base_url}/alt/{img}" if img else None,
throttle_key=f"firstlogin_{pid}",
throttle_secs=0,
)
except Exception:
pass
session = session_mgr.get_player_session(pid)
if session is None:
name, key, sandbox = activity_info(DORM_ROOM_GUID)
session = session_mgr.join_room(pid, DORM_ROOM_GUID, name, key,
private=True, sandbox=sandbox)
push_presence(pid, session)
for other_pid in ws_registry.connected_ids():
if other_pid == pid:
continue
other_session = session_mgr.get_player_session(other_pid)
try:
ws.send(json.dumps({
"Id": 12,
"Msg": {
"PlayerId": other_pid,
"IsOnline": True,
"InScreenMode": ws_registry.is_screen_mode(other_pid),
"GameSession": other_session.to_dict() if other_session else None,
},
}))
except Exception:
pass
from core.state import _KITTYREC_SYSTEM_PID
try:
ws.send(json.dumps({
"Id": 12,
"Msg": {
"PlayerId": _KITTYREC_SYSTEM_PID,
"IsOnline": True,
"InScreenMode": True,
"GameSession": None,
},
}))
except Exception:
pass
print(f"[WS] Player {pid} → '{session.name}' "
f"(sid={session.session_id}, {len(session.players)} in room, "
f"{ws_registry.player_count()} online)")
from tracking.password_tracking import has_real_password
if not has_real_password(pid):
def _send_pw_msg(_pid=pid):
import time, string, random
from core.state import _KITTYREC_SYSTEM_PID
from datetime import datetime, timezone
time.sleep(10)
if not ws_registry.is_connected(_pid):
return
if has_real_password(_pid):
return
temp_pw = "".join(random.choices(string.ascii_letters + string.digits, k=8))
_c = db._get_conn()
_c.execute(
"UPDATE profiles SET password = ? WHERE id = ? AND registration_status != 2",
(temp_pw, _pid),
)
_c.commit()
profile = db.get_profile(_pid)
uname = profile["Username"] if profile else f"Player {_pid}"
msg_text = (
f"Welcome to KittyRec!\n"
f"Username: {uname}\n"
f"Temp password: {temp_pw}\n"
f"STOP SHARING YOUR SCREEN!\n"
f"Reply to this message with a new password (8+ chars) to register!"
)
msg_type = 30
db.delete_messages_of_type(_pid, _KITTYREC_SYSTEM_PID, msg_type)
msg_id = db.send_message(_KITTYREC_SYSTEM_PID, _pid, msg_type, msg_text)
sent = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
ws_registry.send(_pid, {"Id": 2, "Msg": {
"Id": msg_id, "FromPlayerId": _KITTYREC_SYSTEM_PID,
"SentTime": sent, "Type": msg_type, "Data": msg_text,
"RoomId": None, "PlayerEventId": None,
}})
print(f"[System] Sent temp password to pid={_pid} user={uname}")
threading.Thread(target=_send_pw_msg, daemon=True, name=f"temp-pw-{pid}").start()
try:
while True:
msg = ws.receive()
if msg is None:
break
try:
data = json.loads(msg)
api = data.get("api", "")
if api == "heartbeat2":
record_heartbeat(pid)
cur = session_mgr.get_player_session(pid) or session
param = data.get("param") or {}
client_gm = param.get("SpecialGamemode")
if client_gm is not None and cur:
try:
session_mgr.modify_session(cur.session_id, special_gamemode=int(client_gm))
except Exception:
pass
ws.send(json.dumps({
"Id": 4,
"Msg": {
"PlayerId": pid,
"IsOnline": True,
"InScreenMode": ws_registry.is_screen_mode(pid),
"GameSession": cur.to_dict(),
},
}))
elif api == "playerSubscriptions/v1/update":
param = data.get("param", {}) or {}
sub_ids = param.get("PlayerIds", param.get("playerIds", []))[:200]
for sub_pid in sub_ids:
sub_session = session_mgr.get_player_session(sub_pid)
ws.send(json.dumps({
"Id": 12,
"Msg": {
"PlayerId": sub_pid,
"IsOnline": ws_registry.is_connected(sub_pid),
"InScreenMode": ws_registry.is_screen_mode(sub_pid),
"GameSession": sub_session.to_dict() if sub_session else None,
},
}))
else:
print(f"[WS] Player {pid}: unhandled api={api!r} data={data}")
except json.JSONDecodeError:
pass
except Exception as e:
print(f"[WS] Player {pid} error: {e}")
finally:
removed = ws_registry.unregister(pid, ws)
if removed:
from core.daemons import flush_session_time
flush_session_time(pid)
session_mgr.leave_session(pid)
push_presence(pid, None, online=False)
from routes.sessions import session_gift_reset
session_gift_reset(pid)
print(f"[WS] Player {pid} disconnected – "
f"{ws_registry.player_count()} remaining")
else:
print(f"[WS] Player {pid} old socket closed "
f"(new connection already registered – ignoring cleanup)")