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, ws_registry from core.builders import now_iso, get_request_data from core.ws_helpers import push_presence from core.constants import ( MSG_GAME_INVITE, MSG_FRIEND_INVITE, MSG_TEXT, MSG_FRIEND_REQUEST_ACCEPTED, REL_NONE, REL_SENT, REL_RECEIVED, REL_FRIEND, ) from core.config import base_url as _base_url bp = Blueprint("relationships", __name__) def _push_msg_ws(to_pid: int, msg_dict: dict) -> None: ws_registry.send(to_pid, {"Id": 2, "Msg": msg_dict}) _MUTED_LOCAL = 1 _MUTED_REMOTE = 2 _IGNORED_LOCAL = 1 _IGNORED_REMOTE = 2 def _rel_resp(target_id: int, rel_type: int, muted: int = 0, ignored: int = 0) -> dict: return {"PlayerID": target_id, "RelationshipType": rel_type, "Muted": muted, "Ignored": ignored} def _fav_resp(target_id: int, rel_type: int, favorited: int) -> dict: return {"PlayerID": target_id, "RelationshipType": rel_type, "Muted": 0, "Ignored": 0, "Favorited": favorited} def _msg_dict(msg_id: int, from_pid: int, msg_type: int, data: str, room_id, sent_time: str = None) -> dict: return { "Id": msg_id, "FromPlayerId": from_pid, "SentTime": sent_time or now_iso(), "Type": msg_type, "Data": data, "RoomId": room_id, "PlayerEventId": None, } def _rel_msg(about_pid: int, rel: dict) -> dict: return { "PlayerID": about_pid, "RelationshipType": rel.get("RelationshipType", 0), "Muted": rel.get("Muted", 0), "Ignored": rel.get("Ignored", 0), "Favorited": rel.get("Favorited", 0), } def _push_relationship_ws(to_pid: int, about_pid: int, rel_type: int) -> None: rel = db.get_relationship(to_pid, about_pid) rel["RelationshipType"] = rel_type ws_registry.send(to_pid, {"Id": 1, "Msg": _rel_msg(about_pid, rel)}) def _push_rel_both(pid: int, target_id: int) -> None: my_rel = db.get_relationship(pid, target_id) their_rel = db.get_relationship(target_id, pid) ws_registry.send(pid, {"Id": 1, "Msg": _rel_msg(target_id, my_rel)}) ws_registry.send(target_id, {"Id": 1, "Msg": _rel_msg(pid, their_rel)}) @bp.route("/api/relationships/v2/get", methods=["GET"]) @check_auth def get_relationships(): pid = get_current_profile_id() if pid is None: return jsonify([]) return jsonify(db.get_relationships(pid)) @bp.route("/api/relationships/v2/sendfriendrequest", methods=["GET", "POST"]) @check_auth def send_friend_request(): pid = get_current_profile_id() try: target_id = int(request.args.get("id", 0)) except (ValueError, TypeError): return jsonify(_rel_resp(0, REL_NONE)) if not pid or not target_id or pid == target_id or not db.get_profile(target_id): return jsonify(_rel_resp(target_id, REL_NONE)) existing = db.get_relationship(pid, target_id) their_existing = db.get_relationship(target_id, pid) if existing["RelationshipType"] == REL_FRIEND: return jsonify(_rel_resp(target_id, REL_FRIEND)) if their_existing["RelationshipType"] == REL_SENT or existing["RelationshipType"] == REL_RECEIVED: db.set_relationship_type(pid, target_id, REL_FRIEND) db.set_relationship_type(target_id, pid, REL_FRIEND) db.delete_messages_of_type(pid, target_id, MSG_FRIEND_INVITE) msg_id = db.send_message(pid, target_id, MSG_FRIEND_REQUEST_ACCEPTED, str(pid)) _push_msg_ws(target_id, _msg_dict(msg_id, pid, MSG_FRIEND_REQUEST_ACCEPTED, str(pid), None)) _push_relationship_ws(target_id, pid, REL_FRIEND) _push_relationship_ws(pid, target_id, REL_FRIEND) push_presence(pid, session_mgr.get_player_session(pid)) push_presence(target_id, session_mgr.get_player_session(target_id)) return jsonify(_rel_resp(target_id, REL_FRIEND)) db.set_relationship_type(pid, target_id, REL_SENT) db.set_relationship_type(target_id, pid, REL_RECEIVED) db.delete_messages_of_type(target_id, pid, MSG_FRIEND_INVITE) msg_id = db.send_message(pid, target_id, MSG_FRIEND_INVITE, str(pid)) _push_msg_ws(target_id, _msg_dict(msg_id, pid, MSG_FRIEND_INVITE, str(pid), None)) _push_relationship_ws(target_id, pid, REL_RECEIVED) _push_relationship_ws(pid, target_id, REL_SENT) return jsonify(_rel_resp(target_id, REL_SENT)) @bp.route("/api/relationships/v2/acceptfriendrequest", methods=["GET", "POST"]) @check_auth def accept_friend_request(): pid = get_current_profile_id() try: target_id = int(request.args.get("id", 0)) except (ValueError, TypeError): return jsonify(_rel_resp(0, REL_NONE)) if not pid or not target_id or pid == target_id: return jsonify(_rel_resp(target_id, REL_NONE)) my_rel = db.get_relationship(pid, target_id) their_rel = db.get_relationship(target_id, pid) if their_rel["RelationshipType"] != REL_SENT and my_rel["RelationshipType"] != REL_RECEIVED: return jsonify(_rel_resp(target_id, my_rel["RelationshipType"])) db.set_relationship_type(pid, target_id, REL_FRIEND) db.set_relationship_type(target_id, pid, REL_FRIEND) db.delete_messages_of_type(pid, target_id, MSG_FRIEND_INVITE) msg_id = db.send_message(pid, target_id, MSG_FRIEND_REQUEST_ACCEPTED, str(pid)) _push_msg_ws(target_id, _msg_dict(msg_id, pid, MSG_FRIEND_REQUEST_ACCEPTED, str(pid), None)) _push_relationship_ws(target_id, pid, REL_FRIEND) _push_relationship_ws(pid, target_id, REL_FRIEND) push_presence(pid, session_mgr.get_player_session(pid)) push_presence(target_id, session_mgr.get_player_session(target_id)) return jsonify(_rel_resp(target_id, REL_FRIEND)) @bp.route("/api/relationships/v2/addfriend", methods=["GET", "POST"]) @check_auth def add_friend(): return send_friend_request() _KITTYREC_PID = 23 @bp.route("/api/relationships/v2/removefriend", methods=["GET", "POST"]) @check_auth def remove_friend(): pid = get_current_profile_id() try: target_id = int(request.args.get("id", 0)) except (ValueError, TypeError): return jsonify(_rel_resp(0, REL_NONE)) if target_id == _KITTYREC_PID: return jsonify(_rel_resp(target_id, REL_FRIEND)) if pid and target_id and pid != target_id: db.remove_relationship(pid, target_id) db.remove_relationship(target_id, pid) db.delete_messages_of_type(pid, target_id, MSG_FRIEND_INVITE) db.delete_messages_of_type(target_id, pid, MSG_FRIEND_INVITE) _push_relationship_ws(target_id, pid, REL_NONE) _push_relationship_ws(pid, target_id, REL_NONE) return jsonify(_rel_resp(target_id, REL_NONE)) @bp.route("/api/relationships/v1/favorite", methods=["GET", "POST"]) @check_auth def favorite_player(): pid = get_current_profile_id() try: target_id = int(request.args.get("id", 0)) except (ValueError, TypeError): return jsonify(_fav_resp(0, 0, 1)) if pid and target_id and pid != target_id: db.set_rel_field(pid, target_id, "favorited", 1) rel = db.get_relationship(pid, target_id) if pid and target_id and pid != target_id else {} return jsonify(_fav_resp(target_id, rel.get("RelationshipType", 0), 1)) @bp.route("/api/relationships/v1/unfavorite", methods=["GET", "POST"]) @check_auth def unfavorite_player(): pid = get_current_profile_id() try: target_id = int(request.args.get("id", 0)) except (ValueError, TypeError): return jsonify(_fav_resp(0, 0, 0)) if pid and target_id and pid != target_id: db.set_rel_field(pid, target_id, "favorited", 0) rel = db.get_relationship(pid, target_id) if pid and target_id and pid != target_id else {} return jsonify(_fav_resp(target_id, rel.get("RelationshipType", 0), 0)) @bp.route("/api/relationships/v1/mute", methods=["POST"]) @check_auth def mute_player(): pid = get_current_profile_id() if pid is None: return jsonify({"Success": False, "Message": "Not authenticated"}) target_id = int(get_request_data().get("PlayerId", 0)) if not target_id or target_id == pid: return jsonify({"Success": False, "Message": "Invalid PlayerId"}) if target_id == _KITTYREC_PID: return jsonify({"Success": True, "Message": ""}) db.set_rel_field(pid, target_id, "muted", _MUTED_LOCAL) db.set_rel_field(target_id, pid, "muted", _MUTED_REMOTE) _push_rel_both(pid, target_id) return jsonify({"Success": True, "Message": ""}) @bp.route("/api/relationships/v1/unmute", methods=["POST"]) @check_auth def unmute_player(): pid = get_current_profile_id() if pid is None: return jsonify({"Success": False, "Message": "Not authenticated"}) target_id = int(get_request_data().get("PlayerId", 0)) if not target_id or target_id == pid: return jsonify({"Success": False, "Message": "Invalid PlayerId"}) db.set_rel_field(pid, target_id, "muted", 0) their_muted = db.get_relationship(target_id, pid).get("Muted", 0) if their_muted == _MUTED_REMOTE: db.set_rel_field(target_id, pid, "muted", 0) _push_rel_both(pid, target_id) return jsonify({"Success": True, "Message": ""}) @bp.route("/api/relationships/v1/ignore", methods=["POST"]) @check_auth def ignore_player(): pid = get_current_profile_id() if pid is None: return jsonify({"Success": False, "Message": "Not authenticated"}) target_id = int(get_request_data().get("PlayerId", 0)) if not target_id or target_id == pid: return jsonify({"Success": False, "Message": "Invalid PlayerId"}) if target_id == _KITTYREC_PID: return jsonify({"Success": True, "Message": ""}) db.set_rel_field(pid, target_id, "ignored", _IGNORED_LOCAL) db.set_rel_field(target_id, pid, "ignored", _IGNORED_REMOTE) _push_rel_both(pid, target_id) return jsonify({"Success": True, "Message": ""}) @bp.route("/api/relationships/v1/unignore", methods=["POST"]) @check_auth def unignore_player(): pid = get_current_profile_id() if pid is None: return jsonify({"Success": False, "Message": "Not authenticated"}) target_id = int(get_request_data().get("PlayerId", 0)) if not target_id or target_id == pid: return jsonify({"Success": False, "Message": "Invalid PlayerId"}) db.set_rel_field(pid, target_id, "ignored", 0) their_ignored = db.get_relationship(target_id, pid).get("Ignored", 0) if their_ignored == _IGNORED_REMOTE: db.set_rel_field(target_id, pid, "ignored", 0) _push_rel_both(pid, target_id) return jsonify({"Success": True, "Message": ""}) @bp.route("/api/relationships/v1/bulkignoreplatformusers", methods=["POST"]) def bulk_ignore_platform(): return jsonify({"Success": True, "Message": ""}) @bp.route("/api/messages/v2/get", methods=["GET"]) @check_auth def get_messages(): pid = get_current_profile_id() if pid is None: return jsonify([]) since_id = int(request.args.get("sinceId", 0)) return jsonify(db.get_messages(pid, since_id)) @bp.route("/api/messages/v2/send", methods=["POST"]) @limiter.limit("30 per minute") @check_auth def send_message_endpoint(): pid = get_current_profile_id() if pid is None: return jsonify({"Success": False}) data = get_request_data() to_id = int(data.get("ToPlayerId", 0)) msg_type = int(data.get("Type", MSG_TEXT)) msg_data = str(data.get("Data", "")) room_id = data.get("RoomId") if to_id == pid: return jsonify({"Success": False}) from core.state import _KITTYREC_SYSTEM_PID from core.system_messages import dispatch_reply if to_id == _KITTYREC_SYSTEM_PID: from tracking.password_tracking import has_real_password if not has_real_password(pid): return _handle_password_msg(pid, msg_data.strip()) if dispatch_reply(pid, msg_data.strip()): return jsonify({"Success": True}) from datetime import datetime, timezone sent = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") reply = "Invalid command." msg_id = db.send_message(_KITTYREC_SYSTEM_PID, pid, 30, reply) _push_msg_ws(pid, _msg_dict(msg_id, _KITTYREC_SYSTEM_PID, 30, reply, None, sent)) return jsonify({"Success": True}) msg_id = db.send_message(pid, to_id, msg_type, msg_data, room_id) _push_msg_ws(to_id, _msg_dict(msg_id, pid, msg_type, msg_data, room_id)) return jsonify({"Success": True}) def _handle_password_msg(pid, password): from werkzeug.security import generate_password_hash from core.state import _KITTYREC_SYSTEM_PID from core.ws_helpers import push_profile_update from datetime import datetime, timezone sent = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") if len(password) < 8 or len(password) > 128: reply = "Password must be 8-128 characters. Try again!" msg_id = db.send_message(_KITTYREC_SYSTEM_PID, pid, 30, reply) _push_msg_ws(pid, _msg_dict(msg_id, _KITTYREC_SYSTEM_PID, 30, reply, None, sent)) return jsonify({"Success": True}) conn = db._get_conn() conn.execute( "UPDATE profiles SET password=?, registration_status=2 WHERE id=?", (generate_password_hash(password), pid), ) conn.commit() from tracking.password_tracking import mark_password_set mark_password_set(pid) profile = db.get_profile(pid) uname = (profile or {}).get("Username", f"Player {pid}") db.delete_messages_of_type(pid, _KITTYREC_SYSTEM_PID, 30) reply = f"Your account has been verified, {uname}! You can now change your name in-game. Login to your account at {_base_url}/ Thanks for playing :D" msg_id = db.send_message(_KITTYREC_SYSTEM_PID, pid, 30, reply) _push_msg_ws(pid, _msg_dict(msg_id, _KITTYREC_SYSTEM_PID, 30, reply, None, sent)) push_profile_update(pid) print(f"[System] Player {pid} ({uname}) registered via message reply") return jsonify({"Success": True}) from core.system_messages import reply_handler @reply_handler("password_change") def _password_change_handler(pid, text, ctx, reply): from werkzeug.security import generate_password_hash from core.ws_helpers import push_profile_update from tracking.password_tracking import has_real_password, mark_password_set if has_real_password(pid): reply("Invalid command.") return if len(text) < 8 or len(text) > 128 or not text.isprintable(): reply("Password must be 8-128 printable characters. Try again!", next_handler="password_change") return conn = db._get_conn() conn.execute( "UPDATE profiles SET password=?, must_change_password=0 WHERE id=?", (generate_password_hash(text), pid), ) conn.commit() mark_password_set(pid) profile = db.get_profile(pid) uname = (profile or {}).get("Username", f"Player {pid}") from core.state import _KITTYREC_SYSTEM_PID as _SYS db.delete_messages_of_type(pid, _SYS, 30) reply(f"Password updated! You're all set, {uname}.") push_profile_update(pid) print(f"[System] Player {pid} ({uname}) updated password via message reply") @bp.route("/api/messages/v1/sendMultiple", methods=["POST"]) @check_auth @limiter.limit("5 per minute") def send_message_multiple(): pid = get_current_profile_id() if pid is None: return jsonify({"Success": False}) data = get_request_data() to_ids = [x for x in data.get("ToPlayerIds", []) if int(x) != pid][:10] msg_type = int(data.get("Type", MSG_TEXT)) msg_data = str(data.get("Data", ""))[:4096] room_id = data.get("RoomId") sent_time = now_iso() for to_id in to_ids: to_id = int(to_id) msg_id = db.send_message(pid, to_id, msg_type, msg_data, room_id) _push_msg_ws(to_id, _msg_dict(msg_id, pid, msg_type, msg_data, room_id, sent_time)) return jsonify({"Success": True}) @bp.route("/api/messages/v2/delete", methods=["POST"]) @check_auth def delete_message_endpoint(): pid = get_current_profile_id() if pid is None: return jsonify({"Success": False}) msg_id = int(request.values.get("Id", 0)) db.delete_message(msg_id, pid) return jsonify({"Success": True}) @bp.route("/api/offlineinvite/v1/send", methods=["POST"]) @limiter.limit("5 per minute") @check_auth def send_offline_invite(): pid = get_current_profile_id() if pid is None: return jsonify({"Success": False}) data = get_request_data() to_id = int(data.get("ToPlayerId", 0)) if not to_id or to_id == pid: return jsonify({"Success": False}) session = session_mgr.get_player_session(pid) room_id = session.session_id if session else None msg_id = db.send_message(pid, to_id, MSG_GAME_INVITE, "", room_id) _push_msg_ws(to_id, _msg_dict(msg_id, pid, MSG_GAME_INVITE, "", room_id)) return jsonify({"Success": True})