Upload files to "routes"

This commit is contained in:
2026-07-24 15:35:00 +00:00
parent c145236ae0
commit b11c8aceed
5 changed files with 2043 additions and 0 deletions

77
routes/media.py Normal file
View File

@@ -0,0 +1,77 @@
import mimetypes
import os
from flask import Blueprint, Response, abort
bp = Blueprint("media", __name__)
_PUBLIC_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "public")
_VIDEOS_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "Videos")
_EXTRACTED_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "gamecode", "extracted")
_VIDEO_EXTS = {".mp4", ".webm", ".mov", ".avi", ".mkv", ".m4v"}
_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"}
_AUDIO_EXTS = {".ogg", ".wav", ".mp3", ".fsb"}
_FONT_EXTS = {".ttf", ".otf"}
_ALLOWED_EXTS = _VIDEO_EXTS | _IMAGE_EXTS | _AUDIO_EXTS | _FONT_EXTS | {".json", ".txt", ".svg", ".dll", ".shader", ".xml", ".bytes"}
def _serve_file(directory, filename):
path = os.path.realpath(os.path.join(directory, filename))
if not path.startswith(os.path.realpath(directory) + os.sep):
abort(403)
safe_name = os.path.basename(path)
if not os.path.isfile(path):
abort(404)
ext = os.path.splitext(safe_name)[1].lower()
if ext not in _ALLOWED_EXTS:
abort(403)
mime = mimetypes.guess_type(safe_name)[0] or "application/octet-stream"
size = os.path.getsize(path)
def stream():
with open(path, "rb") as f:
while True:
chunk = f.read(65536)
if not chunk:
break
yield chunk
return Response(
stream(),
200,
{
"Content-Type": mime,
"Content-Length": size,
"Accept-Ranges": "bytes",
"Cache-Control": "public, max-age=3600",
},
)
@bp.route("/public/<path:filename>", methods=["GET"])
def serve_public(filename):
return _serve_file(_PUBLIC_DIR, filename)
@bp.route("/Videos/<path:filename>", methods=["GET"])
def serve_video(filename):
resp = _serve_file(_VIDEOS_DIR, filename)
resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
resp.headers["CDN-Cache-Control"] = "no-store"
return resp
_VALID_ASSET_CATS = {"Texture2D", "Sprite", "AudioClip", "Font", "TextAsset", "Shader", "MonoBehaviour"}
@bp.route("/assets/<category>/<path:filename>", methods=["GET"])
def serve_extracted_asset(category, filename):
if category not in _VALID_ASSET_CATS:
abort(404)
asset_dir = os.path.join(_EXTRACTED_DIR, category)
return _serve_file(asset_dir, filename)

1008
routes/misc.py Normal file

File diff suppressed because it is too large Load Diff

111
routes/music.py Normal file
View File

@@ -0,0 +1,111 @@
import os
import subprocess
import uuid
from pathlib import Path
from flask import Blueprint, jsonify, send_file, abort
bp = Blueprint("music", __name__)
MUSIC_DIR = Path(__file__).parent.parent / "music"
_CONVERT_EXTS = {".mp3", ".ogg", ".flac", ".m4a", ".aac", ".opus", ".wma"}
def _ensure_dir():
MUSIC_DIR.mkdir(exist_ok=True)
def _needs_convert(src: Path, dst: Path) -> bool:
return not dst.exists() or dst.stat().st_mtime < src.stat().st_mtime
def _convert_to_wav(src: Path) -> Path:
dst = src.with_suffix(".wav")
if not _needs_convert(src, dst):
return dst
print(f"[Music] Converting: {src.name} → {dst.name}")
result = subprocess.run(
[
"ffmpeg", "-y",
"-i", str(src),
"-ar", "44100",
"-ac", "2",
"-acodec", "pcm_s16le",
str(dst),
],
capture_output=True,
text=True,
)
if result.returncode != 0:
print(f"[Music] ffmpeg error for {src.name}:\n{result.stderr[-500:]}")
raise RuntimeError(f"ffmpeg failed on {src.name}")
print(f"[Music] Done: {dst.name} ({dst.stat().st_size // 1024} KB)")
return dst
def _build_playlist() -> list[dict]:
_ensure_dir()
tracks = []
seen_stems = set()
for f in sorted(MUSIC_DIR.iterdir()):
if f.is_dir() or f.name.startswith("."):
continue
ext = f.suffix.lower()
if ext in _CONVERT_EXTS:
try:
wav = _convert_to_wav(f)
stem = wav.stem
if stem not in seen_stems:
seen_stems.add(stem)
tracks.append({
"Id": str(uuid.uuid5(uuid.NAMESPACE_URL, wav.name)),
"friendlyName": wav.stem,
"fileName": wav.name,
"fileType": 20,
})
except RuntimeError:
pass
elif ext == ".wav":
stem = f.stem
if stem not in seen_stems:
seen_stems.add(stem)
tracks.append({
"Id": str(uuid.uuid5(uuid.NAMESPACE_URL, f.name)),
"friendlyName": f.stem,
"fileName": f.name,
"fileType": 20,
})
return tracks
@bp.route("/api/music/v1/playlist", methods=["GET", "POST"])
def get_playlist():
tracks = _build_playlist()
print(f"[Music] Playlist → {len(tracks)} track(s)")
return jsonify(tracks)
@bp.route("/api/music/v1/file/<path:filename>", methods=["GET"])
def serve_track(filename):
_ensure_dir()
try:
target = (MUSIC_DIR / filename).resolve()
except Exception:
abort(400)
music_root = MUSIC_DIR.resolve()
if not str(target).startswith(str(music_root) + os.sep):
abort(403)
if not target.exists() or not target.is_file():
abort(404)
return send_file(
str(target),
mimetype="audio/wav",
conditional=True,
)

551
routes/nameserver.py Normal file
View File

@@ -0,0 +1,551 @@
import os
import time
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, ws_registry, APP_VERSION
from core.config import base_url as _base_url, server as _server_cfg
bp = Blueprint("nameserver", __name__)
_web_presence: dict[int, float] = {}
_web_presence_lock = threading.Lock()
_WEB_PRESENCE_TTL = 150
def _web_heartbeat(pid: int) -> None:
cutoff = time.monotonic() - _WEB_PRESENCE_TTL
with _web_presence_lock:
_web_presence[pid] = time.monotonic()
expired = [k for k, v in _web_presence.items() if v < cutoff]
for k in expired:
del _web_presence[k]
def _web_online_ids() -> set[int]:
cutoff = time.monotonic() - _WEB_PRESENCE_TTL
with _web_presence_lock:
return {pid for pid, ts in _web_presence.items() if ts >= cutoff}
_SYSTEM_PIDS = {23}
def _all_online_ids() -> set[int]:
return (set(ws_registry.connected_ids()) | _web_online_ids()) - _SYSTEM_PIDS
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def _load_html(filename: str) -> str:
try:
with open(os.path.join(_BASE_DIR, filename), "r", encoding="utf-8") as f:
html = f.read()
except FileNotFoundError:
return f"<h1>Not Found</h1><p>{filename} missing.</p>"
return (html
.replace("{{BUILD_DATE_HUMAN}}", _server_cfg.get("build_date_human", ""))
.replace("{{APP_VERSION}}", _server_cfg.get("app_version", ""))
.replace("{{APP_VERSION_LONG}}", _server_cfg.get("app_version_long", "")))
@bp.route("/", methods=["GET"])
def nameserver():
proto = request.headers.get("X-Forwarded-Proto", "http").lower()
is_https = proto == "https"
http_base = f"{'https' if is_https else 'http'}://{request.host}/"
ws_base = f"{'wss' if is_https else 'ws'}://{request.host}/"
if request.args.get("v"):
return jsonify({
"Auth": http_base,
"API": http_base,
"WWW": http_base,
"Notifications": ws_base,
"Images": http_base,
})
return Response(_load_html("pages/web_portal.html"), 200, {"Content-Type": "text/html; charset=utf-8"})
@bp.route("/welcome", methods=["GET"])
def welcome():
return Response(_load_html("pages/welcome.html"), 200, {"Content-Type": "text/html; charset=utf-8"})
@bp.route("/dashboard", methods=["GET"])
def dashboard():
return Response(_load_html("pages/dashboard.html"), 200, {"Content-Type": "text/html; charset=utf-8"})
@bp.route("/recnet", methods=["GET"])
def recnet_page():
return Response(_load_html("pages/recnet.html"), 200, {"Content-Type": "text/html; charset=utf-8"})
@bp.route("/api-docs", methods=["GET"])
def api_docs_page():
return Response(_load_html("pages/api_page.html"), 200, {"Content-Type": "text/html; charset=utf-8"})
@bp.route("/web/status", methods=["GET"])
def web_status():
sessions = session_mgr.all_public_sessions()
return jsonify({
"online": len(_all_online_ids()),
"session_count": len(sessions),
"version": APP_VERSION,
"rooms": [
{
"name": s.name,
"activity": s.activity_key,
"players": len(s.players),
"max": s.max_capacity,
}
for s in sessions
],
})
@bp.route("/web/leaderboard", methods=["GET"])
@limiter.limit("30 per minute")
def web_leaderboard():
online_ids = _all_online_ids()
conn = db._get_conn()
rows = conn.execute(
"SELECT id, display_name, username, level, xp, profile_image_name "
"FROM profiles ORDER BY xp DESC"
).fetchall()
return jsonify([
{
"id": r["id"],
"display_name": r["display_name"],
"username": r["username"],
"level": r["level"],
"xp": r["xp"],
"online": r["id"] in online_ids,
"has_image": bool(r["profile_image_name"]),
}
for r in rows
])
@bp.route("/web/players", methods=["GET"])
@check_auth
def web_players():
pid = get_current_profile_id()
online_ids = _all_online_ids()
my_rels = {}
if pid:
for r in db.get_relationships(pid):
my_rels[r["PlayerID"]] = r["RelationshipType"]
conn = db._get_conn()
rows = conn.execute(
"SELECT id, username, display_name, level, xp, created_at, profile_image_name "
"FROM profiles ORDER BY id"
).fetchall()
return jsonify([
{
"id": r["id"],
"username": r["username"],
"display_name": r["display_name"],
"level": r["level"],
"xp": r["xp"],
"online": r["id"] in online_ids,
"created_at": r["created_at"],
"relationship": my_rels.get(r["id"], 0),
"has_image": bool(r["profile_image_name"]),
}
for r in rows
])
@bp.route("/web/friends", methods=["GET"])
def web_friends():
from core.constants import REL_FRIEND, REL_RECEIVED
pid = get_current_profile_id()
if pid is None:
return jsonify([])
online_ids = _all_online_ids()
rels = db.get_relationships(pid)
friends = []
for r in rels:
if r["RelationshipType"] == REL_FRIEND:
profile = db.get_profile(r["PlayerID"])
if profile:
friends.append({
"id": profile["Id"],
"username": profile["Username"],
"display_name": profile["DisplayName"],
"level": profile["Level"],
"online": profile["Id"] in online_ids,
"has_image": bool(profile.get("ProfileImageName", "")),
})
elif r["RelationshipType"] == REL_RECEIVED:
profile = db.get_profile(r["PlayerID"])
if profile:
friends.append({
"id": profile["Id"],
"username": profile["Username"],
"display_name": profile["DisplayName"],
"level": profile["Level"],
"online": profile["Id"] in online_ids,
"has_image": bool(profile.get("ProfileImageName", "")),
"pending_request": True,
})
return jsonify(friends)
@bp.route("/leaderboard", methods=["GET"])
def leaderboard_page():
return Response(_load_html("pages/leaderboard.html"), 200, {"Content-Type": "text/html; charset=utf-8"})
@bp.route("/account", methods=["GET"])
def account_page():
return Response(_load_html("pages/dashboard.html"), 200, {"Content-Type": "text/html; charset=utf-8"})
@bp.route("/web/change-password", methods=["POST"])
def web_change_password():
from werkzeug.security import generate_password_hash
from core.password_crypto import check_password as crypto_check_password
pid = get_current_profile_id()
if pid is None:
return jsonify({"error": "Not authenticated"}), 401
data = request.get_json(silent=True) or {}
current = data.get("current_password", "")
new_pw = data.get("new_password", "")
if not current or not new_pw:
return jsonify({"error": "Both fields are required"}), 400
if len(new_pw) < 8 or len(new_pw) > 128:
return jsonify({"error": "Password must be 8-128 characters"}), 400
conn = db._get_conn()
row = conn.execute("SELECT password FROM profiles WHERE id = ?", (pid,)).fetchone()
if not row:
return jsonify({"error": "Account not found"}), 404
stored = row["password"]
if stored:
if not crypto_check_password(stored, current):
return jsonify({"error": "Current password is incorrect"}), 403
conn.execute(
"UPDATE profiles SET password = ?, registration_status = 2 WHERE id = ?",
(generate_password_hash(new_pw), pid),
)
conn.commit()
from core.state import _KITTYREC_SYSTEM_PID
from datetime import datetime, timezone
profile = db.get_profile(pid)
uname = (profile or {}).get("Username", f"Player {pid}")
msg_text = 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, 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": 30, "Data": msg_text,
"RoomId": None, "PlayerEventId": None,
}})
from core.ws_helpers import push_profile_update
push_profile_update(pid)
return jsonify({"success": True})
_PFP_UPLOAD_COST = 9000
_MAX_PFP_BYTES = 2 * 1024 * 1024
_IMAGE_MAGIC = (b"\x89PNG", b"\xff\xd8\xff", b"GIF87a", b"GIF89a", b"RIFF")
@bp.route("/web/upload-pfp", methods=["POST"])
def web_upload_pfp():
import time as _time
from core.ws_helpers import push_profile_update
pid = get_current_profile_id()
if pid is None:
return jsonify({"error": "Not authenticated"}), 401
tokens = db.get_tokens(pid)
if tokens < _PFP_UPLOAD_COST:
return jsonify({"error": f"Not enough tokens. Need {_PFP_UPLOAD_COST}, have {tokens}"}), 402
f = request.files.get("image")
if not f:
return jsonify({"error": "No image provided"}), 400
image_data = f.read(_MAX_PFP_BYTES + 1)
if len(image_data) > _MAX_PFP_BYTES:
return jsonify({"error": "Image too large (max 2MB)"}), 400
if not any(image_data[:len(m)] == m for m in _IMAGE_MAGIC):
return jsonify({"error": "Invalid image format"}), 400
old_image = db.get_profile_image(pid)
old_profile = db.get_profile(pid)
old_name = (old_profile or {}).get("ProfileImageName", "") if old_profile else ""
if old_image and old_name:
db.add_pfp_to_history(pid, old_name, old_image)
db.update_tokens(pid, -_PFP_UPLOAD_COST)
image_name = f"{pid}_{int(_time.time())}"
db.set_profile_image(pid, image_data, image_name)
db.update_profile(pid, {"profile_image_name": image_name})
push_profile_update(pid)
new_tokens = db.get_tokens(pid)
return jsonify({"success": True, "image_name": image_name, "tokens": new_tokens})
@bp.route("/web/pfp-history", methods=["GET"])
def web_pfp_history():
pid = get_current_profile_id()
if pid is None:
return jsonify({"error": "Not authenticated"}), 401
history = db.get_pfp_history(pid)
return jsonify([{"id": h["id"], "created_at": h["created_at"]} for h in history])
@bp.route("/web/pfp-history/<int:history_id>", methods=["GET"])
def web_pfp_history_image(history_id):
from email.utils import formatdate
from core.auth import _jwt_decode
pid = get_current_profile_id()
if pid is None:
token = request.args.get("token", "")
if token:
try:
import core.auth as _auth
payload = _auth._jwt_decode(token, _auth.JWT_SECRET)
pid = payload.get("sub")
except Exception:
pid = None
if pid is None:
return Response(b"", 401)
image_data = db.get_pfp_history_image(history_id, pid)
if image_data is None:
return Response(b"", 404)
return Response(image_data, 200, {
"Content-Type": "image/jpeg",
"Cache-Control": "private, max-age=3600",
"Last-Modified": formatdate(usegmt=True),
})
@bp.route("/web/restore-pfp/<int:history_id>", methods=["POST"])
def web_restore_pfp(history_id):
import time as _time
from core.ws_helpers import push_profile_update
pid = get_current_profile_id()
if pid is None:
return jsonify({"error": "Not authenticated"}), 401
image_data = db.get_pfp_history_image(history_id, pid)
if image_data is None:
return jsonify({"error": "Not found"}), 404
old_image = db.get_profile_image(pid)
old_profile = db.get_profile(pid)
old_name = (old_profile or {}).get("ProfileImageName", "") if old_profile else ""
if old_image and old_name:
db.add_pfp_to_history(pid, old_name, old_image)
image_name = f"{pid}_{int(_time.time())}"
db.set_profile_image(pid, image_data, image_name)
db.update_profile(pid, {"profile_image_name": image_name})
push_profile_update(pid)
return jsonify({"success": True, "image_name": image_name})
@bp.route("/web/heartbeat", methods=["POST"])
@limiter.limit("60 per minute")
def web_heartbeat():
pid = get_current_profile_id()
if pid is None:
return jsonify({"error": "Not authenticated"}), 401
_web_heartbeat(pid)
return jsonify({"ok": True})
@bp.route("/web/token-balance", methods=["GET"])
def web_token_balance():
pid = get_current_profile_id()
if pid is None:
return jsonify({"error": "Not authenticated"}), 401
return jsonify({"tokens": db.get_tokens(pid)})
@bp.route("/web/my-photos", methods=["GET"])
def web_my_photos():
pid = get_current_profile_id()
if pid is None:
return jsonify({"error": "Not authenticated"}), 401
try:
offset = max(0, int(request.args.get("offset", 0)))
limit = min(48, max(1, int(request.args.get("limit", 24))))
except (ValueError, TypeError):
offset, limit = 0, 24
photos = db.get_photos_paginated(profile_id=pid, limit=limit, offset=offset)
total = db.get_photo_count(profile_id=pid)
return jsonify({
"photos": [{"name": p["name"], "room_name": p["room_name"], "created_at": p["created_at"]} for p in photos],
"total": total,
"offset": offset,
"limit": limit,
})
@bp.route("/web/notifications", methods=["GET"])
def web_notifications():
from core.constants import REL_RECEIVED, MSG_FRIEND_INVITE, MSG_FRIEND_REQUEST_ACCEPTED, MSG_GAME_INVITE, MSG_TEXT
pid = get_current_profile_id()
if pid is None:
return jsonify({"error": "Not authenticated"}), 401
online_ids = _all_online_ids()
result = []
rels = db.get_relationships(pid)
for r in rels:
if r["RelationshipType"] != REL_RECEIVED:
continue
p = db.get_profile(r["PlayerID"])
if not p:
continue
result.append({
"kind": "friend_request",
"id": r["PlayerID"],
"from_id": r["PlayerID"],
"from_name": p["DisplayName"] or p["Username"],
"from_username": p["Username"],
"has_image": bool(p.get("ProfileImageName", "")),
"sent_at": None,
})
msgs = db.get_messages(pid)
skip_types = {MSG_FRIEND_INVITE}
for m in reversed(msgs[-50:]):
t = m["Type"]
if t in skip_types:
continue
from_pid = m["FromPlayerId"]
p = db.get_profile(from_pid) if from_pid else None
from_name = (p["DisplayName"] or p["Username"]) if p else "KittyRec"
has_image = bool(p.get("ProfileImageName", "")) if p else False
if t == MSG_FRIEND_REQUEST_ACCEPTED:
label = f"{from_name} accepted your friend request"
elif t == MSG_GAME_INVITE:
label = f"{from_name} invited you to a room"
elif t == MSG_TEXT:
label = m["Data"][:120] if m.get("Data") else "New message"
else:
label = m.get("Data", "Notification")[:120]
result.append({
"kind": "notification",
"id": m["Id"],
"from_id": from_pid,
"from_name": from_name,
"has_image": has_image,
"label": label,
"type": t,
"sent_at": m["SentTime"],
"room_id": m.get("RoomId"),
})
return jsonify(result)
@bp.route("/web/notifications/dismiss/<int:msg_id>", methods=["POST"])
def web_dismiss_notification(msg_id):
pid = get_current_profile_id()
if pid is None:
return jsonify({"error": "Not authenticated"}), 401
db.delete_message(msg_id, pid)
return jsonify({"ok": True})
def _player_summary(pid: int, online_ids: set) -> dict:
p = db.get_profile(pid)
if not p:
return {"id": pid, "username": "Unknown", "display_name": "Unknown", "online": False, "has_image": False}
return {
"id": p["Id"],
"username": p["Username"],
"display_name": p["DisplayName"],
"online": p["Id"] in online_ids,
"has_image": bool(p.get("ProfileImageName", "")),
}
@bp.route("/web/chats", methods=["GET"])
@limiter.limit("60 per minute")
def web_chats():
pid = get_current_profile_id()
if pid is None:
return jsonify({"error": "Not authenticated"}), 401
online_ids = _all_online_ids()
threads = db.get_player_chats(pid)
result = []
for t in threads:
players = [_player_summary(p, online_ids) for p in t["PlayerIds"] if p != pid]
unread = 0
latest = t.get("LatestMessage")
if latest and t.get("LastReadMessageId", 0) < latest.get("ChatMessageId", 0):
conn = db._get_conn()
unread = conn.execute(
"SELECT COUNT(*) AS c FROM chat_messages WHERE thread_id = ? AND id > ?",
(t["ChatThreadId"], t.get("LastReadMessageId", 0)),
).fetchone()["c"]
result.append({
"thread_id": t["ChatThreadId"],
"players": players,
"latest_message": latest,
"unread": unread,
})
result.sort(key=lambda x: (x["latest_message"] or {}).get("ChatMessageId", 0), reverse=True)
return jsonify(result)
@bp.route("/web/chats/<int:thread_id>", methods=["GET"])
@limiter.limit("60 per minute")
def web_chat_thread(thread_id):
pid = get_current_profile_id()
if pid is None:
return jsonify({"error": "Not authenticated"}), 401
if pid not in db.get_chat_thread_players(thread_id):
return jsonify({"error": "Not found"}), 404
before_id = request.args.get("before_id", type=int)
messages = db.get_chat_messages(thread_id, count=50, before_id=before_id)
messages = list(reversed(messages))
online_ids = _all_online_ids()
players = [_player_summary(p, online_ids) for p in db.get_chat_thread_players(thread_id)]
if messages:
db.mark_chat_read(thread_id, pid, messages[-1]["ChatMessageId"])
return jsonify({"thread_id": thread_id, "players": players, "messages": messages})
@bp.route("/web/chats/<int:thread_id>/send", methods=["POST"])
@limiter.limit("30 per minute")
def web_chat_send(thread_id):
pid = get_current_profile_id()
if pid is None:
return jsonify({"error": "Not authenticated"}), 401
if db.is_banned(pid):
return jsonify({"error": "Forbidden"}), 403
if pid not in db.get_chat_thread_players(thread_id):
return jsonify({"error": "Not in thread"}), 403
data = request.get_json(silent=True) or {}
text = str(data.get("text", "")).strip()[:2000]
if not text:
return jsonify({"error": "Empty message"}), 400
msg_id = db.send_chat_message(thread_id, pid, text)
msg = db.get_chat_message(msg_id)
for member_pid in db.get_chat_thread_players(thread_id):
ws_registry.send(member_pid, {"Id": 90, "Msg": msg})
if member_pid != pid:
ws_registry.send(member_pid, {"Id": 2, "Msg": msg})
db.mark_chat_read(thread_id, pid, msg_id)
return jsonify(msg)
@bp.route("/web/chats/start", methods=["POST"])
@limiter.limit("10 per minute")
def web_chat_start():
pid = get_current_profile_id()
if pid is None:
return jsonify({"error": "Not authenticated"}), 401
data = request.get_json(silent=True) or {}
other_id = int(data.get("player_id", 0))
if not other_id or other_id == pid:
return jsonify({"error": "Invalid player"}), 400
if not db.get_profile(other_id):
return jsonify({"error": "Player not found"}), 404
thread_id = db.get_or_create_chat([pid, other_id])
return jsonify({"thread_id": thread_id})
@bp.route("/web/chats/<int:thread_id>/poll", methods=["GET"])
@limiter.limit("60 per minute")
def web_chat_poll(thread_id):
pid = get_current_profile_id()
if pid is None:
return jsonify({"error": "Not authenticated"}), 401
if pid not in db.get_chat_thread_players(thread_id):
return jsonify({"error": "Not found"}), 404
after_id = request.args.get("after_id", type=int, default=0)
conn = db._get_conn()
rows = conn.execute(
"SELECT * FROM chat_messages WHERE thread_id = ? AND id > ? ORDER BY id ASC LIMIT 50",
(thread_id, after_id),
).fetchall()
msgs = [db._chat_msg_row_to_dict(r) for r in rows]
if msgs:
db.mark_chat_read(thread_id, pid, msgs[-1]["ChatMessageId"])
return jsonify(msgs)

296
routes/players.py Normal file
View File

@@ -0,0 +1,296 @@
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/<int:player_id>", 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": ""})