import re 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, ws_registry, session_mgr from core.builders import make_profile_from_db, sanitize_username, get_request_data from core.profanity import is_clean from core.ws_helpers import push_profile_update bp = Blueprint("players", __name__) @bp.route("/api/players/v1/", methods=["GET"]) @check_auth def get_player(player_id): profile = db.get_profile(player_id) if profile is None: return Response("Not Found", 404) return jsonify(make_profile_from_db(profile)) @bp.route("/api/players/v1/list", methods=["POST"]) @check_auth def get_players_list(): ids = (request.get_json(force=True, silent=True) or [])[:200] profiles_map = db.get_profiles_batch(ids) return jsonify([make_profile_from_db(profiles_map[pid]) for pid in ids if pid in profiles_map]) @bp.route("/api/players/v1/createProfile", methods=["POST"]) @check_auth def create_player_profile(): pid = get_current_profile_id() profile = db.get_profile(pid) if pid else None if profile is None: data = get_request_data() profile = { "Id": 1, "Username": data.get("Username", "Player"), "DisplayName": data.get("DisplayName", "Player"), "XP": 999999, "Level": 30, "Developer": False, "Bio": "", "Birthday": "", "RegistrationStatus": 2, } return jsonify(make_profile_from_db(profile)) @bp.route("/api/players/v1/GetGeneratedNameOptions", methods=["GET"]) @check_auth def get_generated_names(): return jsonify(["CosmicPlayer", "StarryGamer", "NeonDancer", "PixelHero", "VRExplorer"]) @bp.route("/api/players/v2/displayname", methods=["POST"]) @check_auth def set_display_name(): pid = get_current_profile_id() from tracking.password_tracking import has_real_password if pid and not has_real_password(pid): import string, random, threading from core.state import _KITTYREC_SYSTEM_PID from datetime import datetime, timezone def _resend_temp(p=pid): import time time.sleep(2) if not ws_registry.is_connected(p): return if has_real_password(p): 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, p), ) _c.commit() profile = db.get_profile(p) uname = (profile or {}).get("Username", f"Player {p}") 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!" ) db.delete_messages_of_type(p, _KITTYREC_SYSTEM_PID, 30) msg_id = db.send_message(_KITTYREC_SYSTEM_PID, p, 30, msg_text) sent = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") ws_registry.send(p, {"Id": 2, "Msg": { "Id": msg_id, "FromPlayerId": _KITTYREC_SYSTEM_PID, "SentTime": sent, "Type": 30, "Data": msg_text, "RoomId": None, "PlayerEventId": None, }}) threading.Thread(target=_resend_temp, daemon=True).start() return jsonify({"Success": False, "Message": "Register first! Check your messages."}) new_name = sanitize_username(request.form.get("Name") or request.form.get("DisplayName") or "") if not new_name: data = get_request_data() new_name = sanitize_username(data.get("Name", data.get("DisplayName", ""))) if pid and new_name: if not is_clean(new_name): return jsonify({"Success": False, "Message": "That name is not allowed.", "Username": "", "DisplayName": ""}) existing = db.get_profile_by_username(new_name) if existing and existing.get("Id") != pid: return jsonify({"Success": False, "Message": "Name already taken.", "Username": "", "DisplayName": ""}) db.update_profile(pid, {"display_name": new_name, "username": new_name}) push_profile_update(pid) return jsonify({"Success": True, "Message": "", "Username": new_name, "DisplayName": new_name}) @bp.route("/api/players/v1/bio", methods=["POST"]) @check_auth def set_bio(): pid = get_current_profile_id() data = get_request_data() bio = re.sub(r"<[^>]+>", "", str(data.get("Bio", "")))[:500] if pid: db.update_profile(pid, {"bio": bio}) push_profile_update(pid) profile = db.get_profile(pid) if pid else None return jsonify({"Success": True, "Message": "", "Bio": profile.get("Bio", bio) if profile else bio}) @bp.route("/api/players/v1/birthday", methods=["POST"]) @check_auth def set_birthday(): pid = get_current_profile_id() data = get_request_data() birthday = str(data.get("BirthdayDateString", data.get("Birthday", "")))[:32] if pid and birthday: db.update_profile(pid, {"birthday": birthday}) return jsonify({ "Success": True, "Message": "", "MustRestart": False, "IsJunior": False, }) @bp.route("/api/players/v2/search", methods=["GET"]) @check_auth def search_players(): query = request.args.get("name", "").strip()[:100] if query.lower() == "all": profiles = db.search_profiles("", limit=200) return jsonify([make_profile_from_db(p) for p in profiles]) if not query or len(query) < 2: online_ids = ws_registry.connected_ids() profiles_map = db.get_profiles_batch(online_ids) return jsonify([make_profile_from_db(p) for p in profiles_map.values()]) profiles = db.search_profiles(query) print(f"[Search] name={query!r} → {len(profiles)} result(s)") return jsonify([make_profile_from_db(p) for p in profiles]) @bp.route("/api/players/v1/getByUsername", methods=["GET"]) @check_auth def get_by_username(): name = request.args.get("name", "Player") profile = db.get_profile_by_username(name) if profile: return jsonify(make_profile_from_db(profile)) return jsonify(make_profile_from_db({ "Id": 0, "Username": name, "DisplayName": name, "XP": 0, "Level": 1, "Developer": False, "Bio": "", "Birthday": "", "RegistrationStatus": 2, })) @bp.route("/api/players/v2/phone", methods=["POST"]) @check_auth def set_phone(): return jsonify({"Success": True, "Message": ""}) @bp.route("/api/players/v2/phone/verify", methods=["POST"]) @check_auth def verify_phone(): return jsonify({"Success": True, "Message": ""}) @bp.route("/api/players/v2/updateReputation", methods=["POST"]) @check_auth def update_reputation(): return Response("OK", 200) def _make_objective_complete(pid): from core.constants import xp_for_client, xp_to_next_level profile = db.get_profile(pid) xp = profile.get("XP", 0) if profile else 0 level = profile.get("Level", 1) if profile else 1 return { "deltaXp": 0, "currentLevel": level, "currentXp": xp_for_client(xp, level), "xpRequiredToLevelUp": xp_to_next_level(xp, level), } @bp.route("/api/players/v1/objectives", methods=["GET", "POST"]) @limiter.limit("20 per minute") @check_auth def get_player_objectives(): if request.method == "POST": from datetime import datetime, timezone pid = get_current_profile_id() if not pid: return jsonify([]) if not session_mgr.get_player_session(pid): print(f"[Objectives v1] Rejected pid={pid}: not in a session") return jsonify([]) objectives = (request.get_json(force=True, silent=True) or [])[:20] if not isinstance(objectives, list): objectives = [objectives] total_xp = 0 today = datetime.now(timezone.utc).strftime("%Y-%m-%d") seen_lb_types: set = set() for obj in objectives: if not isinstance(obj, dict): continue additional_xp = max(0, min(int(obj.get("additionalXp", 0)), 200)) obj_type = int(obj.get("objectiveType", -1)) if obj_type >= 1 and obj_type not in seen_lb_types: db.increment_leaderboard(pid, obj_type) seen_lb_types.add(obj_type) if additional_xp > 0: slot = obj_type - 10 if 10 <= obj_type <= 12 else None if slot is not None: inserted = db.try_mark_daily_complete(pid, today, slot) if not inserted: print(f"[Objectives v1] Player {pid} already completed daily slot {slot} today — skipping") continue total_xp += additional_xp if total_xp > 0: db.award_xp(pid, total_xp) push_profile_update(pid) print(f"[Objectives v1] Player {pid} awarded {total_xp} XP from {len(objectives)} objective(s)") return jsonify([]) _MAX_DAILY_SLOT_XP = 1000 @bp.route("/api/players/v2/objective", methods=["POST"]) @limiter.limit("20 per minute") @check_auth def complete_objective_v2(): from datetime import datetime, timezone pid = get_current_profile_id() if not pid: return jsonify({"deltaXp": 0, "currentLevel": 1, "currentXp": 0, "xpRequiredToLevelUp": 300}) if not session_mgr.get_player_session(pid): print(f"[Objectives v2] Rejected pid={pid}: not in a session") return jsonify(_make_objective_complete(pid)) _raw_xp = int(request.values.get("additionalXp", 0)) additional_xp = max(0, min(_raw_xp, _MAX_DAILY_SLOT_XP)) if _raw_xp > _MAX_DAILY_SLOT_XP: print(f"[SECURITY] XP cap violation: pid={pid} sent additionalXp={_raw_xp} capped={additional_xp}") obj_type = int(request.values.get("objectiveType", -1)) if obj_type >= 1: db.increment_leaderboard(pid, obj_type) if additional_xp > 0: today = datetime.now(timezone.utc).strftime("%Y-%m-%d") slot = obj_type - 10 if 10 <= obj_type <= 12 else None if slot is not None: inserted = db.try_mark_daily_complete(pid, today, slot) if not inserted: print(f"[Objectives] Player {pid} already completed daily slot {slot} today — skipping") return jsonify(_make_objective_complete(pid)) new_xp, new_level = db.award_xp(pid, additional_xp) push_profile_update(pid) print(f"[Objectives] Player {pid} daily slot={slot} type={obj_type}, +{additional_xp} XP → level {new_level}") from core.constants import xp_for_client, xp_to_next_level return jsonify({ "deltaXp": additional_xp, "currentLevel": new_level, "currentXp": xp_for_client(new_xp, new_level), "xpRequiredToLevelUp": xp_to_next_level(new_xp, new_level), }) return jsonify(_make_objective_complete(pid)) @bp.route("/api/players/v2/listByPlatformId", methods=["POST"]) @check_auth def list_by_platform(): data = get_request_data() _PLATFORM_NAMES = {0: "Steam", 1: "Oculus", 2: "PlayStation"} platform_name = _PLATFORM_NAMES.get(int(data.get("Platform", 0)), "Steam") platform_ids = data.get("PlatformIds", []) result = [] for pid_str in platform_ids: profile = db.get_profile_by_platform(platform_name, str(pid_str)) if profile: result.append(make_profile_from_db(profile)) return jsonify(result) @bp.route("/api/players/v1/avoidJuniors", methods=["POST"]) @check_auth def avoid_juniors(): return Response("OK", 200) @bp.route("/api/players/v1/deleteProfile", methods=["POST"]) @check_auth def delete_profile(): return jsonify({"Success": True, "Message": ""}) @bp.route("/api/players/v1/phonelastfour", methods=["GET"]) @check_auth def phone_last_four(): return jsonify({"PhoneNumber": ""})