Files
2026-07-24 15:35:19 +00:00

258 lines
9.6 KiB
Python

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, _KITTYREC_SYSTEM_PID
from core.constants import REL_FRIEND
from core.config import base_url as _base_url
bp = Blueprint("chat", __name__)
def _require_pid():
pid = get_current_profile_id()
if pid is None:
return None, (jsonify({"error": "Unauthorized"}), 401)
return pid, None
@bp.route("/api/chat/v2/myChats", methods=["GET"])
def my_chats():
pid, err = _require_pid()
if err:
return err
return jsonify(db.get_player_chats(pid))
@bp.route("/api/chat/v2/getById", methods=["GET"])
def get_chat_by_id():
pid, err = _require_pid()
if err:
return err
thread_id = int(request.args.get("ChatId", 0))
count = int(request.args.get("MessageCount", 50))
detail = db.get_chat_thread_detail(thread_id, pid, count)
if detail is None:
return jsonify({"Success": False})
return jsonify(detail)
@bp.route("/api/chat/v2/getByPlayers", methods=["GET"])
def get_chat_by_players():
pid, err = _require_pid()
if err:
return err
raw_ids = request.args.getlist("PlayerIds")
count = int(request.args.get("MessageCount", 50))
try:
player_ids = [int(x) for x in raw_ids if x.strip()]
except ValueError:
player_ids = []
if pid not in player_ids:
player_ids.append(pid)
thread_id = db.find_chat(player_ids)
if thread_id is None:
return jsonify({"error": "not found"}), 404
detail = db.get_chat_thread_detail(thread_id, pid, count)
if detail is None:
return jsonify({"error": "not found"}), 404
return jsonify(detail)
@bp.route("/api/chat/v2/messages", methods=["GET"])
def get_chat_messages():
pid, err = _require_pid()
if err:
return err
thread_id = int(request.args.get("ChatId", 0))
if thread_id and pid not in db.get_chat_thread_players(thread_id):
return jsonify([])
count = int(request.args.get("MessageCount", 50))
ref_id_str = request.args.get("ReferenceMessageId")
before_id = int(ref_id_str) if ref_id_str else None
return jsonify(db.get_chat_messages(thread_id, count, before_id))
@bp.route("/api/chat/v1/create", methods=["POST"])
@limiter.limit("10 per minute")
def create_chat():
pid, err = _require_pid()
if err:
return err
data = request.get_json(force=True, silent=True) or {}
player_ids = [int(x) for x in data.get("PlayerIds", [])]
initial_msg = str(data.get("MessageContents", ""))[:4096]
if pid not in player_ids:
player_ids.append(pid)
if all(p == pid for p in player_ids):
return jsonify({"ChatResult": 1, "ChatThread": None})
thread_id = db.get_or_create_chat(player_ids)
if initial_msg:
db.send_chat_message(thread_id, pid, initial_msg)
detail = db.get_chat_thread_detail(thread_id, pid)
return jsonify({"ChatResult": 0, "ChatThread": detail})
@bp.route("/api/chat/v1/sendMessage", methods=["POST"])
@bp.route("/api/chat/v2/sendMessage", methods=["POST"])
@limiter.limit("15 per minute")
def send_chat_message():
pid, err = _require_pid()
if err:
return err
data = request.get_json(force=True, silent=True) or {}
thread_id = int(data.get("ChatId", 0))
members = db.get_chat_thread_players(thread_id)
if pid not in members:
return jsonify({"ChatResult": 1})
text = str(data.get("MessageContents", data.get("Contents", "")))[:4096]
if _KITTYREC_SYSTEM_PID in members:
from tracking.password_tracking import has_real_password
if not has_real_password(pid):
return _handle_password_chat(pid, thread_id, text.strip())
msg = _send_system_chat(pid, thread_id, "Invalid command.")
return jsonify({"ChatResult": 0, "ChatMessage": msg})
msg_id = db.send_chat_message(thread_id, pid, text)
msg = db.get_chat_message(msg_id)
for member_pid in members:
ws_registry.send(member_pid, {"Id": 90, "Msg": msg})
return jsonify({"ChatResult": 0, "ChatMessage": msg})
def _send_system_chat(pid, thread_id, text):
reply_id = db.send_chat_message(thread_id, _KITTYREC_SYSTEM_PID, text)
reply_msg = db.get_chat_message(reply_id)
ws_registry.send(pid, {"Id": 90, "Msg": reply_msg})
return reply_msg
def _handle_password_chat(pid, thread_id, password):
from werkzeug.security import generate_password_hash, check_password_hash
from core.ws_helpers import push_profile_update
from datetime import datetime, timezone
if len(password) < 8 or len(password) > 128:
msg = _send_system_chat(pid, thread_id, "Password must be 8-128 characters. Try again!")
return jsonify({"ChatResult": 0, "ChatMessage": msg})
if not password.isprintable():
msg = _send_system_chat(pid, thread_id, "Password contains invalid characters. Use letters, numbers, and symbols only. Try again!")
return jsonify({"ChatResult": 0, "ChatMessage": msg})
try:
hashed = generate_password_hash(password)
conn = db._get_conn()
conn.execute(
"UPDATE profiles SET password = ?, registration_status = 2 WHERE id = ?",
(hashed, pid),
)
conn.commit()
from tracking.password_tracking import mark_password_set
mark_password_set(pid)
stored_row = conn.execute("SELECT password FROM profiles WHERE id = ?", (pid,)).fetchone()
if not stored_row or not check_password_hash(stored_row["password"], password):
print(f"[System] CRITICAL: Password DB write verification failed for player {pid}")
msg = _send_system_chat(pid, thread_id, "Something went wrong saving your password. Please try again!")
return jsonify({"ChatResult": 0, "ChatMessage": msg})
except Exception as e:
print(f"[System] CRITICAL: Password registration failed for player {pid}: {e}")
msg = _send_system_chat(pid, thread_id, "Something went wrong. Please try again!")
return jsonify({"ChatResult": 0, "ChatMessage": msg})
profile = db.get_profile(pid)
uname = (profile or {}).get("Username", f"Player {pid}")
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"
db.delete_messages_of_type(pid, _KITTYREC_SYSTEM_PID, 30)
msg_id = db.send_message(_KITTYREC_SYSTEM_PID, pid, 30, reply)
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": 30, "Data": reply,
"RoomId": None, "PlayerEventId": None,
}})
_send_system_chat(pid, thread_id, reply)
push_profile_update(pid)
print(f"[System] Player {pid} ({uname}) registered via chat reply — password verified OK")
return jsonify({"ChatResult": 0, "ChatMessage": {"ChatMessageId": msg_id}})
def _handle_password_change(pid, thread_id, password):
from werkzeug.security import generate_password_hash
from tracking.password_tracking import mark_password_set
if len(password) < 8 or len(password) > 128:
msg = _send_system_chat(pid, thread_id, "Password must be 8-128 characters. Try again!")
return jsonify({"ChatResult": 0, "ChatMessage": msg})
if not password.isprintable():
msg = _send_system_chat(pid, thread_id, "Password contains invalid characters. Try again!")
return jsonify({"ChatResult": 0, "ChatMessage": msg})
try:
hashed = generate_password_hash(password)
conn = db._get_conn()
conn.execute("UPDATE profiles SET password=?, must_change_password=0 WHERE id=?", (hashed, pid))
conn.commit()
mark_password_set(pid)
except Exception as e:
print(f"[System] Password change failed for player {pid}: {e}")
msg = _send_system_chat(pid, thread_id, "Something went wrong. Please try again!")
return jsonify({"ChatResult": 0, "ChatMessage": msg})
profile = db.get_profile(pid)
uname = (profile or {}).get("Username", f"Player {pid}")
msg = _send_system_chat(pid, thread_id, f"Password updated! You're all set, {uname}.")
print(f"[System] Player {pid} ({uname}) set new password via chat reply")
return jsonify({"ChatResult": 0, "ChatMessage": msg})
@bp.route("/api/chat/v1/readMessage", methods=["POST"])
def read_chat_message():
pid, err = _require_pid()
if err:
return err
data = request.get_json(force=True, silent=True) or {}
thread_id = int(data.get("ChatId", 0))
msg_id = int(data.get("MessageId", 0))
db.mark_chat_read(thread_id, pid, msg_id)
return jsonify({"ChatResult": 0})
@bp.route("/api/chat/v1/addToChat", methods=["POST"])
def add_to_chat():
pid, err = _require_pid()
if err:
return err
data = request.get_json(force=True, silent=True) or {}
thread_id = int(data.get("ChatId", 0))
if pid not in db.get_chat_thread_players(thread_id):
return jsonify({"ChatResult": 1})
new_pid = int(data.get("PlayerToAddId", 0))
if not new_pid:
return jsonify({"ChatResult": 1})
rel = db.get_relationship(pid, new_pid)
if rel["RelationshipType"] != REL_FRIEND:
return jsonify({"ChatResult": 1})
db.add_to_chat_thread(thread_id, new_pid)
return jsonify({"ChatResult": 0})
@bp.route("/api/chat/v1/leaveChat", methods=["POST"])
def leave_chat():
pid, err = _require_pid()
if err:
return err
data = request.get_json(force=True, silent=True) or {}
thread_id = int(data.get("ChatId", 0))
db.leave_chat_thread(thread_id, pid)
return jsonify({"ChatResult": 0})