Upload files to "routes"
This commit is contained in:
42
routes/admin_ws.py
Normal file
42
routes/admin_ws.py
Normal file
@@ -0,0 +1,42 @@
|
||||
import json
|
||||
|
||||
from core.state import db
|
||||
from routes.portal import _get_admin_account, _has_any_admin_scope
|
||||
|
||||
|
||||
def _send(ws, msg: dict) -> None:
|
||||
try:
|
||||
ws.send(json.dumps(msg))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def register_admin_ws(sock) -> None:
|
||||
|
||||
@sock.route("/admin/ws")
|
||||
def admin_ws_handler(ws):
|
||||
account, scopes = _get_admin_account()
|
||||
if not account or not _has_any_admin_scope(scopes):
|
||||
ws.close()
|
||||
return
|
||||
|
||||
import core.admin_ws as awr
|
||||
awr.register(ws)
|
||||
|
||||
try:
|
||||
from routes.misc import get_sanitize_log
|
||||
from core.anticheat import get_suspects
|
||||
suspects = get_suspects()
|
||||
_send(ws, {"type": "init", "sanitize_log": get_sanitize_log(), "suspects": suspects})
|
||||
except Exception as e:
|
||||
print(f"[AdminWS] init error: {e}")
|
||||
|
||||
try:
|
||||
while True:
|
||||
msg = ws.receive(timeout=30)
|
||||
if msg is None:
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
awr.unregister(ws)
|
||||
531
routes/auth.py
Normal file
531
routes/auth.py
Normal file
@@ -0,0 +1,531 @@
|
||||
|
||||
from flask import Blueprint, request, jsonify, Response
|
||||
|
||||
from core.auth import get_current_profile_id, make_token
|
||||
from core.limiter import limiter
|
||||
import core.state as _state
|
||||
from core.state import db
|
||||
from core.auth_state import current_jti, jti_lock
|
||||
from core.builders import make_profile_from_db, make_login_response, sanitize_username
|
||||
from core.profanity import is_clean
|
||||
|
||||
bp = Blueprint("auth", __name__)
|
||||
|
||||
|
||||
def _maintenance_block(profile: dict | None) -> dict | None:
|
||||
with _state.maintenance_lock:
|
||||
active = _state.maintenance_mode
|
||||
if not active:
|
||||
return None
|
||||
if profile and profile.get("Id") in _state.maintenance_exempt:
|
||||
return None
|
||||
return _error_response("KittyRec Is Down For Scheduled Maintenance")
|
||||
|
||||
|
||||
def _get_data() -> dict:
|
||||
json_data = request.get_json(force=True, silent=True)
|
||||
if json_data:
|
||||
return json_data
|
||||
return {k: v for k, v in request.values.items()}
|
||||
|
||||
|
||||
def _error_response(msg: str) -> dict:
|
||||
return {
|
||||
"Error": msg,
|
||||
"Player": None,
|
||||
"Token": "",
|
||||
"FirstLoginOfTheDay": False,
|
||||
"AnalyticsSessionId": 0,
|
||||
"CanUseScreenMode": True,
|
||||
}
|
||||
|
||||
|
||||
def _get_ip() -> str:
|
||||
return (request.headers.get("X-Forwarded-For", "") or request.remote_addr or "").split(",")[0].strip()
|
||||
|
||||
def _award_daily_login(pid: int) -> None:
|
||||
if pid and db.claim_daily_login_reward(pid, 500):
|
||||
from core.ws_helpers import push_gift
|
||||
gift = db.add_gift(pid, xp=100, gift_rarity=10, gift_context=0,
|
||||
currency_type=2, currency=500,
|
||||
message="Daily Login Bonus! +500 Tokens")
|
||||
push_gift(pid, gift)
|
||||
print(f"[Daily] Player {pid} claimed daily login reward: 500 tokens")
|
||||
|
||||
def _ip_is_banned(ip: str) -> bool:
|
||||
return db.is_ip_banned(ip)
|
||||
|
||||
def _compute_assoc_duration(banned_until) -> int:
|
||||
if not banned_until:
|
||||
return 0
|
||||
from datetime import datetime, timezone
|
||||
try:
|
||||
exp = datetime.fromisoformat(banned_until)
|
||||
if exp.tzinfo is None:
|
||||
exp = exp.replace(tzinfo=timezone.utc)
|
||||
delta = exp - datetime.now(timezone.utc)
|
||||
return max(1, int(delta.total_seconds() / 3600))
|
||||
except Exception:
|
||||
return 24
|
||||
|
||||
|
||||
def _cascade_ban_if_linked(profile_id: int) -> dict | None:
|
||||
from core.ban_service import kick_player
|
||||
from core.ban_tracker import record_ban_group
|
||||
assoc = db.get_associated_ban(profile_id)
|
||||
if assoc is None:
|
||||
return None
|
||||
source_name = assoc["_source_name"]
|
||||
source_id = assoc["_source_id"]
|
||||
duration_h = _compute_assoc_duration(assoc.get("banned_until"))
|
||||
reason = f"Banned by association with {source_name}"
|
||||
db.ban_player(profile_id, reason=reason, duration_hours=duration_h, admin_name="AntiCheat")
|
||||
kick_player(profile_id)
|
||||
print(f"[AntiCheat] Cascade ban: player {profile_id} ← association with {source_name} (id={source_id})")
|
||||
associated = db.get_associated_accounts_with_evidence(profile_id)
|
||||
for linked_id, evidence in associated.items():
|
||||
if db.is_banned(linked_id):
|
||||
continue
|
||||
db.ban_player(linked_id, reason=reason, duration_hours=duration_h, admin_name="AntiCheat")
|
||||
kick_player(linked_id)
|
||||
print(f"[AntiCheat] Cascade ban: player {linked_id} ← association with {source_name} (id={source_id}) via IPs={evidence['shared_ips']} platforms={evidence['shared_platform_ids']}")
|
||||
record_ban_group(source_id, source_name, {profile_id: {"shared_ips": [], "shared_platform_ids": []}, **associated}, reason)
|
||||
ban = db.get_ban_info(profile_id)
|
||||
if ban:
|
||||
return _error_response(db.format_ban_message(ban))
|
||||
return None
|
||||
|
||||
|
||||
def _notify_password_change_if_needed(profile_id: int) -> None:
|
||||
from tracking.password_tracking import has_real_password
|
||||
if has_real_password(profile_id):
|
||||
return
|
||||
from core.system_messages import send_and_await, has_pending
|
||||
if has_pending(profile_id):
|
||||
return
|
||||
send_and_await(profile_id,
|
||||
"You need to set a password before you can change your username! "
|
||||
"Reply to this message with a password (8+ chars) to get started.",
|
||||
"password_change", expires_in=0)
|
||||
|
||||
|
||||
def _issue_token(profile_id: int, ttl=None) -> str:
|
||||
ip = _get_ip()
|
||||
if ip:
|
||||
db.record_ip_login(profile_id, ip)
|
||||
db.update_last_login(profile_id)
|
||||
token = make_token(profile_id, ttl=ttl)
|
||||
from core.anticheat import on_token_issued
|
||||
from core.auth_state import current_jti
|
||||
on_token_issued(profile_id, current_jti.get(profile_id, ""))
|
||||
return token
|
||||
|
||||
|
||||
@bp.route("/api/platformlogin/v1/loginaccount", methods=["POST"])
|
||||
@limiter.limit("10 per minute")
|
||||
def login_account():
|
||||
data = _get_data()
|
||||
username = data.get("Username", "")
|
||||
password = data.get("Password", "")
|
||||
|
||||
profile = db.check_password(username, password)
|
||||
if profile is None:
|
||||
print(f"[SECURITY] Login fail: username={username!r} ip={_get_ip()}")
|
||||
return jsonify(_error_response("Invalid username or password"))
|
||||
|
||||
block = _maintenance_block(profile)
|
||||
if block:
|
||||
return jsonify(block)
|
||||
|
||||
ban = db.get_ban_info(profile["Id"])
|
||||
if ban:
|
||||
return jsonify(_error_response(db.format_ban_message(ban)))
|
||||
|
||||
ip = _get_ip()
|
||||
if ip and ip not in ("127.0.0.1", "::1") and db.is_ip_banned(ip):
|
||||
print(f"[SECURITY] IP-banned login attempt: ip={ip} username={username!r}")
|
||||
return jsonify(_error_response("This IP address is banned."))
|
||||
|
||||
cascade = _cascade_ban_if_linked(profile["Id"])
|
||||
if cascade:
|
||||
return jsonify(cascade)
|
||||
|
||||
platform = str(data.get("Platform", ""))
|
||||
platform_id = str(data.get("PlatformId", ""))
|
||||
if not platform_id.isdigit():
|
||||
platform_id = ""
|
||||
if platform and platform_id and platform_id != "0":
|
||||
already = db.get_profiles_by_platform(platform, platform_id)
|
||||
already_ids = [p["Id"] for p in already]
|
||||
if not already_ids or profile["Id"] in already_ids:
|
||||
db.update_profile_platform(profile["Id"], platform, platform_id)
|
||||
db.link_platform_to_profile(platform, platform_id, profile["Id"])
|
||||
|
||||
from datetime import timedelta
|
||||
remember_me = bool(data.get("RememberMe", False))
|
||||
ttl = timedelta(hours=8) if remember_me else None
|
||||
token = _issue_token(profile["Id"], ttl=ttl)
|
||||
db.add_cached_login(profile["Id"], current_jti[profile["Id"]])
|
||||
_award_daily_login(profile["Id"])
|
||||
_notify_password_change_if_needed(profile["Id"])
|
||||
try:
|
||||
from core.discord import notify_player_login
|
||||
notify_player_login(profile["Username"], profile["Id"])
|
||||
except Exception:
|
||||
pass
|
||||
return jsonify(make_login_response(make_profile_from_db(profile), token))
|
||||
|
||||
|
||||
@bp.route("/api/platformlogin/v1/logincached", methods=["POST"])
|
||||
@limiter.limit("10 per minute")
|
||||
def login_cached():
|
||||
data = _get_data()
|
||||
try:
|
||||
player_id = int(data.get("PlayerId", 0))
|
||||
except (TypeError, ValueError):
|
||||
player_id = 0
|
||||
if not player_id:
|
||||
return jsonify(_error_response("Account not found"))
|
||||
|
||||
platform = str(data.get("Platform", ""))
|
||||
platform_id = str(data.get("PlatformId", ""))
|
||||
if not platform_id.isdigit():
|
||||
platform_id = ""
|
||||
|
||||
if not (platform and platform_id and platform_id != "0"):
|
||||
return jsonify(_error_response("Authentication required"))
|
||||
|
||||
linked = db.get_profiles_by_platform(platform, platform_id)
|
||||
if not any(p["Id"] == player_id for p in linked):
|
||||
print(f"[SECURITY] logincached fail: pid={player_id} platform={platform}/{platform_id} ip={_get_ip()}")
|
||||
return jsonify(_error_response("Account not found"))
|
||||
|
||||
profile = db.get_profile(player_id)
|
||||
if profile is None:
|
||||
return jsonify(_error_response("Account not found"))
|
||||
|
||||
block = _maintenance_block(profile)
|
||||
if block:
|
||||
return jsonify(block)
|
||||
|
||||
ban = db.get_ban_info(profile["Id"])
|
||||
if ban:
|
||||
return jsonify(_error_response(db.format_ban_message(ban)))
|
||||
|
||||
ip = _get_ip()
|
||||
if ip and ip not in ("127.0.0.1", "::1") and db.is_ip_banned(ip):
|
||||
return jsonify(_error_response("This IP address is banned."))
|
||||
|
||||
cascade = _cascade_ban_if_linked(profile["Id"])
|
||||
if cascade:
|
||||
return jsonify(cascade)
|
||||
|
||||
db.update_profile_platform(profile["Id"], platform, platform_id)
|
||||
token = _issue_token(profile["Id"])
|
||||
db.add_cached_login(profile["Id"], current_jti[profile["Id"]])
|
||||
_award_daily_login(profile["Id"])
|
||||
_notify_password_change_if_needed(profile["Id"])
|
||||
try:
|
||||
from core.discord import notify_player_login
|
||||
notify_player_login(profile["Username"], profile["Id"])
|
||||
except Exception:
|
||||
pass
|
||||
return jsonify(make_login_response(make_profile_from_db(profile), token))
|
||||
|
||||
|
||||
_RESERVED_USERNAMES = {
|
||||
"admin", "administrator", "moderator", "mod", "staff", "owner",
|
||||
"system", "kittyrec", "kitty", "server", "support", "help",
|
||||
"player", "guest", "root", "superuser", "sudo",
|
||||
}
|
||||
|
||||
_BLOCKED_WARP_TAGS: set[str] = {}
|
||||
|
||||
_GLOBAL_CREATE_LIMIT = 0
|
||||
_GLOBAL_CREATE_LOCK = __import__("threading").Lock()
|
||||
_GLOBAL_CREATE_WINDOW: list = []
|
||||
|
||||
def _global_create_check() -> bool:
|
||||
import time
|
||||
now = time.time()
|
||||
with _GLOBAL_CREATE_LOCK:
|
||||
_GLOBAL_CREATE_WINDOW[:] = [t for t in _GLOBAL_CREATE_WINDOW if now - t < 60]
|
||||
if len(_GLOBAL_CREATE_WINDOW) >= 15:
|
||||
return False
|
||||
_GLOBAL_CREATE_WINDOW.append(now)
|
||||
return True
|
||||
|
||||
@bp.route("/api/platformlogin/v1/createaccount", methods=["POST"])
|
||||
@limiter.limit("2 per 5 minutes")
|
||||
def create_account():
|
||||
block = _maintenance_block(None)
|
||||
if block:
|
||||
return jsonify(block)
|
||||
warp_tag = request.headers.get("Cf-Warp-Tag-Id", "").strip()
|
||||
if warp_tag and warp_tag in _BLOCKED_WARP_TAGS:
|
||||
try:
|
||||
from core.discord import send_security
|
||||
send_security(
|
||||
title="Blocked Warp Tag Attempt",
|
||||
color=0xE74C3C,
|
||||
fields=[
|
||||
{"name": "Warp Tag", "value": warp_tag, "inline": True},
|
||||
{"name": "IP", "value": _get_ip(), "inline": True},
|
||||
],
|
||||
description="A blocked Cloudflare Warp client tried to create an account.",
|
||||
throttle_key=f"warp_{warp_tag}",
|
||||
throttle_secs=120,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if _ip_is_banned(_get_ip()):
|
||||
return jsonify(_error_response("Account creation is not allowed from this network.")), 403
|
||||
data = _get_data()
|
||||
username = sanitize_username(data.get("Username", ""))
|
||||
password = data.get("Password", "")
|
||||
display_name = sanitize_username(data.get("DisplayName", ""))
|
||||
platform = str(data.get("Platform", "0"))
|
||||
platform_id = str(data.get("PlatformId", ""))
|
||||
if not platform_id.isdigit():
|
||||
platform_id = ""
|
||||
|
||||
if username.lower() in _RESERVED_USERNAMES:
|
||||
return jsonify(_error_response("That username is not allowed."))
|
||||
if username and not is_clean(username):
|
||||
return jsonify(_error_response("That username is not allowed."))
|
||||
|
||||
if not username and platform_id and platform_id != "0":
|
||||
import random as _rnd
|
||||
auto_name = f"KittyRecPlayer{_rnd.randint(0, 999):03d}"
|
||||
profile = db.create_account(auto_name, "", auto_name, created_via="game")
|
||||
if profile is None:
|
||||
auto_name = f"KittyRecPlayer{_rnd.randint(0, 999):03d}"
|
||||
profile = db.create_account(auto_name, "", auto_name, created_via="game")
|
||||
if profile is None:
|
||||
return jsonify(_error_response("Could not create account, please try again"))
|
||||
db.link_platform_to_profile(platform, platform_id, profile["Id"])
|
||||
ban = db.get_ban_info(profile["Id"])
|
||||
if ban:
|
||||
return jsonify(_error_response(db.format_ban_message(ban)))
|
||||
cascade = _cascade_ban_if_linked(profile["Id"])
|
||||
if cascade:
|
||||
return jsonify(cascade)
|
||||
token = _issue_token(profile["Id"])
|
||||
db.add_cached_login(profile["Id"], current_jti[profile["Id"]])
|
||||
_award_daily_login(profile["Id"])
|
||||
print(f"[Auth] createaccount: new account platform={platform} id={platform_id} "
|
||||
f"→ pid={profile['Id']} ({profile['Username']})")
|
||||
try:
|
||||
from core.discord import send_public, record_signup, send_admin
|
||||
send_public(
|
||||
title="New Player Joined!",
|
||||
color=0x9B59B6,
|
||||
fields=[{"name": "Username", "value": profile["Username"], "inline": True},
|
||||
{"name": "Player ID", "value": str(profile["Id"]), "inline": True},
|
||||
{"name": "Created Via", "value": "In-Game", "inline": True}],
|
||||
description=f"**{profile['Username']}** just created an account on KittyRec!",
|
||||
throttle_key=f"newplayer_{profile['Id']}",
|
||||
throttle_secs=0,
|
||||
)
|
||||
if record_signup():
|
||||
send_admin(
|
||||
title="Registration Burst Detected",
|
||||
color=0xE67E22,
|
||||
fields=[{"name": "Threshold", "value": "5+ signups in 60s", "inline": True},
|
||||
{"name": "Latest", "value": profile["Username"], "inline": True}],
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return jsonify(make_login_response(make_profile_from_db(profile), token))
|
||||
|
||||
if not username:
|
||||
return jsonify(_error_response("Username is required"))
|
||||
|
||||
real_platform = platform if platform and platform != "0" else "Steam"
|
||||
real_platform_id = platform_id if platform_id and platform_id != "0" else None
|
||||
profile = db.create_account(username, password, display_name or username,
|
||||
platform=real_platform, platform_id=real_platform_id,
|
||||
created_via="game")
|
||||
if profile is None:
|
||||
return jsonify(_error_response("Username already taken"))
|
||||
if password:
|
||||
from tracking.password_tracking import mark_password_set
|
||||
mark_password_set(profile["Id"])
|
||||
|
||||
if platform and platform_id and platform_id != "0":
|
||||
db.link_platform_to_profile(platform, platform_id, profile["Id"])
|
||||
|
||||
ban = db.get_ban_info(profile["Id"])
|
||||
if ban:
|
||||
return jsonify(_error_response(db.format_ban_message(ban)))
|
||||
cascade = _cascade_ban_if_linked(profile["Id"])
|
||||
if cascade:
|
||||
return jsonify(cascade)
|
||||
|
||||
token = _issue_token(profile["Id"])
|
||||
db.add_cached_login(profile["Id"], current_jti[profile["Id"]])
|
||||
_award_daily_login(profile["Id"])
|
||||
try:
|
||||
from core.discord import send_public, record_signup, send_admin
|
||||
send_public(
|
||||
title="New Player Joined!",
|
||||
color=0x9B59B6,
|
||||
fields=[{"name": "Username", "value": profile["Username"], "inline": True},
|
||||
{"name": "Player ID", "value": str(profile["Id"]), "inline": True},
|
||||
{"name": "Created Via", "value": "In-Game", "inline": True}],
|
||||
description=f"**{profile['Username']}** just created an account on KittyRec!",
|
||||
throttle_key=f"newplayer_{profile['Id']}",
|
||||
throttle_secs=0,
|
||||
)
|
||||
if record_signup():
|
||||
send_admin(
|
||||
title="Registration Burst Detected",
|
||||
color=0xE67E22,
|
||||
fields=[{"name": "Threshold", "value": "5+ signups in 60s", "inline": True},
|
||||
{"name": "Latest", "value": profile["Username"], "inline": True}],
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return jsonify(make_login_response(make_profile_from_db(profile), token))
|
||||
|
||||
|
||||
@bp.route("/api/platformlogin/v1/registeraccount", methods=["POST"])
|
||||
@limiter.limit("10 per minute")
|
||||
def register_account():
|
||||
if _ip_is_banned(_get_ip()):
|
||||
return jsonify(_error_response("Account creation is not allowed from this network.")), 403
|
||||
data = _get_data()
|
||||
if "Email" in data and "Platform" not in data and "PlatformId" not in data:
|
||||
pid = get_current_profile_id()
|
||||
if pid:
|
||||
from werkzeug.security import generate_password_hash
|
||||
username = sanitize_username(data.get("Username", "")) or None
|
||||
password = data.get("Password", "")
|
||||
conn = db._get_conn()
|
||||
if username:
|
||||
if not is_clean(username):
|
||||
return jsonify(_error_response("That username is not allowed."))
|
||||
existing = conn.execute("SELECT id FROM profiles WHERE username = ? AND id != ?", (username, pid)).fetchone()
|
||||
if existing:
|
||||
return jsonify(_error_response("Username already taken"))
|
||||
conn.execute("UPDATE profiles SET username=?, display_name=? WHERE id=?", (username, username, pid))
|
||||
if password:
|
||||
conn.execute("UPDATE profiles SET password=? WHERE id=?", (generate_password_hash(password), pid))
|
||||
from tracking.password_tracking import mark_password_set
|
||||
mark_password_set(pid)
|
||||
conn.execute("UPDATE profiles SET registration_status=2 WHERE id=?", (pid,))
|
||||
conn.commit()
|
||||
from core.ws_helpers import push_profile_update
|
||||
push_profile_update(pid)
|
||||
print(f"[Auth] registeraccount email: pid={pid} username={username}")
|
||||
profile = db.get_profile(pid)
|
||||
token = _issue_token(pid)
|
||||
db.add_cached_login(pid, current_jti[pid])
|
||||
return jsonify(make_login_response(make_profile_from_db(profile), token))
|
||||
return jsonify({"Success": True, "Message": ""})
|
||||
platform = str(data.get("Platform", 0))
|
||||
platform_id = str(data.get("PlatformId", "0"))
|
||||
if not platform_id or platform_id == "0":
|
||||
return jsonify(_error_response("Platform authentication required"))
|
||||
existing = db.get_profiles_by_platform(platform, platform_id)
|
||||
if len(existing) > 3:
|
||||
return jsonify(_error_response("Too many accounts linked to this platform ID"))
|
||||
import random as _rnd
|
||||
username = f"KittyRecPlayer{_rnd.randint(0, 999):03d}"
|
||||
profile = db.get_or_create_profile(platform, platform_id, username)
|
||||
db.link_platform_to_profile(platform, platform_id, profile["Id"])
|
||||
ban = db.get_ban_info(profile["Id"])
|
||||
if ban:
|
||||
return jsonify(_error_response(db.format_ban_message(ban)))
|
||||
cascade = _cascade_ban_if_linked(profile["Id"])
|
||||
if cascade:
|
||||
return jsonify(cascade)
|
||||
block = _maintenance_block(profile)
|
||||
if block:
|
||||
return jsonify(block)
|
||||
token = _issue_token(profile["Id"])
|
||||
db.add_cached_login(profile["Id"], current_jti[profile["Id"]])
|
||||
_award_daily_login(profile["Id"])
|
||||
return jsonify(make_login_response(make_profile_from_db(profile), token))
|
||||
|
||||
|
||||
@bp.route("/api/platformlogin/v1/refreshlogin", methods=["GET", "POST"])
|
||||
@limiter.limit("20 per minute")
|
||||
def refresh_login():
|
||||
pid = get_current_profile_id(allow_expired=True)
|
||||
if pid:
|
||||
profile = db.get_profile(pid)
|
||||
if profile:
|
||||
ban = db.get_ban_info(profile["Id"])
|
||||
if ban:
|
||||
return jsonify(_error_response(db.format_ban_message(ban)))
|
||||
cascade = _cascade_ban_if_linked(profile["Id"])
|
||||
if cascade:
|
||||
return jsonify(cascade)
|
||||
block = _maintenance_block(profile)
|
||||
if block:
|
||||
return jsonify(block)
|
||||
token = _issue_token(profile["Id"])
|
||||
db.add_cached_login(profile["Id"], current_jti[profile["Id"]])
|
||||
return jsonify(make_login_response(make_profile_from_db(profile), token))
|
||||
return Response("Unauthorized", 401)
|
||||
|
||||
|
||||
@bp.route("/api/platformlogin/v1/logout", methods=["POST"])
|
||||
def logout():
|
||||
pid = get_current_profile_id(allow_expired=True)
|
||||
if pid:
|
||||
with jti_lock:
|
||||
current_jti.pop(pid, None)
|
||||
db.remove_cached_login(pid)
|
||||
try:
|
||||
profile = db.get_profile(pid)
|
||||
if profile:
|
||||
from core.discord import notify_player_logout
|
||||
notify_player_logout(profile["Username"], pid)
|
||||
except Exception:
|
||||
pass
|
||||
return Response("OK", 200)
|
||||
|
||||
|
||||
@bp.route("/api/platformlogin/v1/getcachedlogins", methods=["POST", "GET"])
|
||||
@limiter.limit("10 per minute")
|
||||
def get_cached_logins():
|
||||
data = _get_data()
|
||||
platform = str(data.get("Platform", ""))
|
||||
platform_id = str(data.get("PlatformId", ""))
|
||||
|
||||
if platform and platform_id and platform_id != "0":
|
||||
profiles = db.get_profiles_by_platform(platform, platform_id)
|
||||
if profiles:
|
||||
result = []
|
||||
for profile in profiles:
|
||||
if not db.get_ban_info(profile["Id"]):
|
||||
_cascade_ban_if_linked(profile["Id"])
|
||||
result.append(make_profile_from_db(profile))
|
||||
print(f"[Auth] getcachedlogins: platform={platform} id={platform_id} → pids={[p['Id'] for p in profiles]}")
|
||||
return jsonify(result)
|
||||
print(f"[Auth] getcachedlogins: no accounts for platform={platform} id={platform_id}")
|
||||
|
||||
return jsonify([])
|
||||
|
||||
|
||||
@bp.route("/api/platformlogin/v1/removecachedlogin", methods=["POST"])
|
||||
def remove_cached_login():
|
||||
data = _get_data()
|
||||
try:
|
||||
player_id = int(data.get("PlayerId", 0))
|
||||
except (TypeError, ValueError):
|
||||
player_id = 0
|
||||
if not player_id:
|
||||
return Response("OK", 200)
|
||||
pid = get_current_profile_id(allow_expired=True)
|
||||
if pid != player_id:
|
||||
return Response("OK", 200)
|
||||
db.remove_cached_login(player_id)
|
||||
return Response("OK", 200)
|
||||
|
||||
|
||||
@bp.route("/api/platformlogin/<path:action>", methods=["GET", "POST"])
|
||||
def platformlogin_catchall(action):
|
||||
return jsonify({"Error": "Not found", "Player": None, "Token": ""}), 404
|
||||
540
routes/avatar.py
Normal file
540
routes/avatar.py
Normal file
@@ -0,0 +1,540 @@
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import random
|
||||
|
||||
_GUID_RE = re.compile(
|
||||
r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
from flask import Blueprint, request, jsonify, Response
|
||||
|
||||
from core.auth import check_auth, get_current_profile_id
|
||||
from core.limiter import limiter
|
||||
from core.ws_helpers import push_profile_update, push_presence, push_consumable_added, push_consumable_removed, push_store_balance
|
||||
from core.state import db, session_mgr
|
||||
|
||||
bp = Blueprint("avatar", __name__)
|
||||
|
||||
import threading as _threading
|
||||
_gift_gen_locks: dict[int, _threading.Lock] = {}
|
||||
_gift_gen_locks_lock = _threading.Lock()
|
||||
|
||||
def _get_gift_gen_lock(pid: int) -> _threading.Lock:
|
||||
with _gift_gen_locks_lock:
|
||||
if pid not in _gift_gen_locks:
|
||||
_gift_gen_locks[pid] = _threading.Lock()
|
||||
return _gift_gen_locks[pid]
|
||||
|
||||
_raw_items_cache = None
|
||||
|
||||
def _get_raw_items():
|
||||
global _raw_items_cache
|
||||
if _raw_items_cache is None:
|
||||
_reload_items_cache()
|
||||
return _raw_items_cache
|
||||
|
||||
def _reload_items_cache():
|
||||
global _raw_items_cache, _level_map_cache, _activity_pool_cache, _rarity_map_cache, _custom_starter_guids, _always_ok_guids_cache
|
||||
_always_ok_guids_cache = None
|
||||
data_dir = os.path.join(os.path.dirname(__file__), "..", "data")
|
||||
try:
|
||||
with open(os.path.join(data_dir, "avataritems.json"), encoding="utf-8") as f:
|
||||
raw = json.load(f)
|
||||
except Exception as exc:
|
||||
print(f"[Avatar] Could not load avataritems.json: {exc}")
|
||||
raw = []
|
||||
try:
|
||||
with open(os.path.join(data_dir, "custom_swatches.json"), encoding="utf-8") as f:
|
||||
custom_swatches = json.load(f)
|
||||
except Exception:
|
||||
custom_swatches = []
|
||||
try:
|
||||
with open(os.path.join(data_dir, "custom_items.json"), encoding="utf-8") as f:
|
||||
custom_items = json.load(f)
|
||||
except Exception:
|
||||
custom_items = []
|
||||
_custom_starter_guids = {
|
||||
i["AvatarItemDesc"].split(",")[0]
|
||||
for i in custom_items
|
||||
if i.get("Starter") and i.get("AvatarItemDesc")
|
||||
}
|
||||
normalized = []
|
||||
for i in raw + custom_swatches:
|
||||
desc = i.get("AvatarItemDesc", "")
|
||||
if not desc or not _GUID_RE.match(desc.split(",")[0]):
|
||||
continue
|
||||
if "," not in desc:
|
||||
i = dict(i, AvatarItemDesc=desc + ",,,")
|
||||
normalized.append(i)
|
||||
for i in custom_items:
|
||||
desc = i.get("AvatarItemDesc", "")
|
||||
if not desc:
|
||||
continue
|
||||
if "," not in desc:
|
||||
i = dict(i, AvatarItemDesc=desc + ",,,")
|
||||
normalized.append(i)
|
||||
_raw_items_cache = normalized
|
||||
_level_map_cache = None
|
||||
_activity_pool_cache = {}
|
||||
_rarity_map_cache = None
|
||||
print(f"[Avatar] Loaded {len(raw)} base + {len(custom_swatches)} swatches + {len(custom_items)} custom items ({len(_custom_starter_guids)} custom starters)")
|
||||
|
||||
def _get_avatar_items():
|
||||
return _get_raw_items()
|
||||
|
||||
def _load_avatar_config():
|
||||
cfg_path = os.path.join(os.path.dirname(__file__), "..", "data", "avatar_config.json")
|
||||
with open(cfg_path, encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
_avatar_cfg = _load_avatar_config()
|
||||
|
||||
_STARTER_ITEM_GUIDS = set(_avatar_cfg["starter_item_guids"])
|
||||
|
||||
_custom_starter_guids = set()
|
||||
|
||||
def _all_starter_guids():
|
||||
return _STARTER_ITEM_GUIDS | _custom_starter_guids
|
||||
|
||||
_RARE_ITEM_GUIDS = set(_avatar_cfg["rare_item_guids"])
|
||||
_EPIC_BODY_GUIDS = set(_avatar_cfg["epic_body_guids"])
|
||||
_RARE_BODY_GUIDS = set(_avatar_cfg["rare_body_guids"])
|
||||
|
||||
def _item_rarity(item):
|
||||
guid = item.get("AvatarItemDesc", "").split(",")[0]
|
||||
if guid in _EPIC_BODY_GUIDS:
|
||||
return 3
|
||||
if guid in _RARE_BODY_GUIDS:
|
||||
return 2
|
||||
return random.Random(guid).choice([0, 0, 0, 1, 1])
|
||||
|
||||
_rarity_map_cache = None
|
||||
|
||||
def _get_rarity_buckets():
|
||||
global _rarity_map_cache
|
||||
if _rarity_map_cache is not None:
|
||||
return _rarity_map_cache
|
||||
buckets = {0: [], 1: [], 2: [], 3: []}
|
||||
for item in _get_raw_items():
|
||||
r = _item_rarity(item)
|
||||
buckets[r].append(item)
|
||||
_rarity_map_cache = buckets
|
||||
return buckets
|
||||
|
||||
_equipment_cache = None
|
||||
|
||||
def _get_equipment():
|
||||
global _equipment_cache
|
||||
if _equipment_cache is not None:
|
||||
return _equipment_cache
|
||||
data_dir = os.path.join(os.path.dirname(__file__), "..", "data")
|
||||
try:
|
||||
with open(os.path.join(data_dir, "equipment.json"), encoding="utf-8") as f:
|
||||
raw = json.load(f)
|
||||
except Exception:
|
||||
raw = []
|
||||
_equipment_cache = [e for e in raw if e.get("ModificationGuid")]
|
||||
return _equipment_cache
|
||||
|
||||
_EQUIPMENT_ACTIVITY_MAP = _avatar_cfg["equipment_activity_map"]
|
||||
|
||||
_level_map_cache = None
|
||||
|
||||
def _get_level_map():
|
||||
global _level_map_cache
|
||||
if _level_map_cache is not None:
|
||||
return _level_map_cache
|
||||
|
||||
all_items = _get_raw_items()
|
||||
|
||||
seen = set()
|
||||
non_starter = []
|
||||
for item in all_items:
|
||||
guid = item["AvatarItemDesc"].split(",")[0]
|
||||
if guid not in seen and guid not in _all_starter_guids():
|
||||
seen.add(guid)
|
||||
non_starter.append(guid)
|
||||
|
||||
non_starter.sort()
|
||||
total = len(non_starter)
|
||||
t1 = total // 4
|
||||
t2 = total // 2
|
||||
t3 = 3 * total // 4
|
||||
|
||||
guid_levels = {}
|
||||
for i, guid in enumerate(non_starter):
|
||||
if guid in _RARE_ITEM_GUIDS:
|
||||
guid_levels[guid] = 22
|
||||
elif i < t1:
|
||||
guid_levels[guid] = 3
|
||||
elif i < t2:
|
||||
guid_levels[guid] = 8
|
||||
elif i < t3:
|
||||
guid_levels[guid] = 15
|
||||
else:
|
||||
guid_levels[guid] = 22
|
||||
for guid in _all_starter_guids():
|
||||
guid_levels[guid] = 1
|
||||
|
||||
result = {}
|
||||
for item in all_items:
|
||||
desc = item["AvatarItemDesc"]
|
||||
guid = desc.split(",")[0]
|
||||
result[desc] = guid_levels.get(guid, 22)
|
||||
|
||||
_level_map_cache = result
|
||||
return result
|
||||
|
||||
_HAIR_KEYWORDS = {
|
||||
"hair", "ponytail", "braid", "bun", "afro", "dreadlock", "mohawk",
|
||||
"bangs", "pigtail", "bob", "curly", "wavy", "updo", "twintail",
|
||||
}
|
||||
|
||||
_QUEST_CONSUMABLES = _avatar_cfg["quest_consumables"]
|
||||
_FOOD_CONSUMABLES = _avatar_cfg["food_consumables"]
|
||||
|
||||
_ACTIVITY_POOLS = {
|
||||
"3d474b26-26f7-45e9-9a36-9b02847d5e6f": [
|
||||
"paintball", "boxer", "scout", "viking", "warrior",
|
||||
],
|
||||
"6d5eea4b-f069-4ed0-9916-0e2f07df0d03": [
|
||||
"soccer", "field hockey", "football", "tennis", "cheer",
|
||||
],
|
||||
"cbad71af-0831-44d8-b8ef-69edafa841f6": [
|
||||
"business", "tee", "t shirt", "sherlock", "marty", "aviator",
|
||||
],
|
||||
}
|
||||
|
||||
_activity_pool_cache = {}
|
||||
_always_ok_guids_cache = None
|
||||
|
||||
def _get_always_ok_guids():
|
||||
global _always_ok_guids_cache
|
||||
if _always_ok_guids_cache is not None:
|
||||
return _always_ok_guids_cache
|
||||
result = set(_all_starter_guids())
|
||||
for item in _get_raw_items():
|
||||
name = item.get("FriendlyName", "").lower()
|
||||
if any(kw in name for kw in _HAIR_KEYWORDS):
|
||||
result.add(item["AvatarItemDesc"].split(",")[0])
|
||||
_always_ok_guids_cache = result
|
||||
return result
|
||||
|
||||
def _filter_outfit_selections(outfit_str, owned):
|
||||
if not outfit_str:
|
||||
return outfit_str
|
||||
always_ok = _get_always_ok_guids()
|
||||
kept = []
|
||||
for entry in outfit_str.split(";"):
|
||||
if not entry:
|
||||
continue
|
||||
guid = entry.split(",")[0]
|
||||
if guid in always_ok or guid in owned:
|
||||
kept.append(entry)
|
||||
return ";".join(kept)
|
||||
|
||||
def _get_activity_item_pool(activity_guid):
|
||||
if activity_guid in _activity_pool_cache:
|
||||
return _activity_pool_cache[activity_guid]
|
||||
|
||||
all_items = _get_raw_items()
|
||||
keywords = _ACTIVITY_POOLS.get(activity_guid)
|
||||
if not keywords:
|
||||
_activity_pool_cache[activity_guid] = all_items
|
||||
return all_items
|
||||
|
||||
filtered = [
|
||||
i for i in all_items
|
||||
if any(kw in i.get("FriendlyName", "").lower() for kw in keywords)
|
||||
]
|
||||
pool = filtered if filtered else all_items
|
||||
_activity_pool_cache[activity_guid] = pool
|
||||
return pool
|
||||
|
||||
def _seed_starter_unlocks(profile_id, all_items):
|
||||
db.migrate_unlocks_from_gifts(profile_id)
|
||||
starter_descs = [
|
||||
i["AvatarItemDesc"] for i in all_items
|
||||
if i["AvatarItemDesc"].split(",")[0] in _all_starter_guids()
|
||||
]
|
||||
db.unlock_avatar_items(profile_id, starter_descs)
|
||||
|
||||
|
||||
_CURRENCY_REC_CENTER_TOKENS = 2
|
||||
|
||||
_RARITY_WIRE = {0: 0, 1: 10, 2: 20, 3: 30, 4: 50}
|
||||
|
||||
def _is_owned(desc, owned):
|
||||
return desc in owned or desc.split(",")[0] in owned
|
||||
|
||||
def _pick_equipment(activity_guid, profile_id):
|
||||
all_equip = _get_equipment()
|
||||
if not all_equip:
|
||||
return None
|
||||
prefab_keywords = _EQUIPMENT_ACTIVITY_MAP.get(activity_guid)
|
||||
if prefab_keywords:
|
||||
pool = [e for e in all_equip if any(kw in e["PrefabName"] for kw in prefab_keywords)]
|
||||
else:
|
||||
pool = all_equip
|
||||
owned_guids = set()
|
||||
if profile_id:
|
||||
conn = db._get_conn()
|
||||
rows = conn.execute(
|
||||
"SELECT equipment_modification_guid FROM gifts WHERE profile_id = ? AND equipment_modification_guid != ''",
|
||||
(profile_id,),
|
||||
).fetchall()
|
||||
owned_guids = {r["equipment_modification_guid"] for r in rows}
|
||||
unowned = [e for e in pool if e["ModificationGuid"] not in owned_guids]
|
||||
if not unowned:
|
||||
unowned = [e for e in all_equip if e["ModificationGuid"] not in owned_guids]
|
||||
return random.choice(unowned) if unowned else None
|
||||
|
||||
def _generate_gift_for_player(profile_id, activity_guid=None, xp=None, gift_context=2):
|
||||
with _get_gift_gen_lock(profile_id):
|
||||
return _generate_gift_for_player_locked(profile_id, activity_guid, xp, gift_context)
|
||||
|
||||
def _generate_gift_for_player_locked(profile_id, activity_guid=None, xp=None, gift_context=2):
|
||||
from core.constants import xp_to_level, get_activity_base_xp
|
||||
if xp is None:
|
||||
lo, hi = get_activity_base_xp(activity_guid)
|
||||
xp = random.randint(lo, hi) if hi > 0 else random.randint(50, 150)
|
||||
rarity = random.choices([0, 1, 2, 3, 4], weights=[54, 29, 12, 4, 1])[0]
|
||||
|
||||
profile = db.get_profile(profile_id) if profile_id else None
|
||||
current_xp = profile.get("XP", 0) if profile else 0
|
||||
projected_level = xp_to_level(current_xp + xp)
|
||||
|
||||
if random.random() < 0.25:
|
||||
token_amount = random.choice([50, 100, 150, 200, 250])
|
||||
gift = db.add_gift(
|
||||
profile_id,
|
||||
xp=xp,
|
||||
gift_rarity=_RARITY_WIRE[rarity],
|
||||
currency_type=_CURRENCY_REC_CENTER_TOKENS,
|
||||
currency=token_amount,
|
||||
gift_context=gift_context,
|
||||
level=projected_level,
|
||||
)
|
||||
return gift
|
||||
|
||||
if random.random() < 0.20 and activity_guid:
|
||||
equip = _pick_equipment(activity_guid, profile_id)
|
||||
if equip:
|
||||
gift = db.add_gift(
|
||||
profile_id,
|
||||
xp=xp,
|
||||
gift_rarity=_RARITY_WIRE[rarity],
|
||||
equipment_prefab_name=equip["PrefabName"],
|
||||
equipment_modification_guid=equip["ModificationGuid"],
|
||||
gift_context=gift_context,
|
||||
level=projected_level,
|
||||
)
|
||||
return gift
|
||||
|
||||
consumable = ""
|
||||
|
||||
owned = db.get_unlocked_items(profile_id) if profile_id else set()
|
||||
for pending in (db.get_pending_gifts(profile_id) if profile_id else []):
|
||||
desc = pending.get("AvatarItemDesc", "")
|
||||
if desc:
|
||||
owned.add(desc)
|
||||
owned.add(desc.split(",")[0])
|
||||
|
||||
buckets = _get_rarity_buckets()
|
||||
activity_pool = _get_activity_item_pool(activity_guid)
|
||||
|
||||
def _eligible(i):
|
||||
desc = i["AvatarItemDesc"]
|
||||
guid = desc.split(",")[0]
|
||||
return (not guid.startswith("sdk_")
|
||||
and guid not in _all_starter_guids()
|
||||
and not _is_owned(desc, owned))
|
||||
|
||||
pool = [i for i in activity_pool if _item_rarity(i) == rarity and _eligible(i)]
|
||||
if not pool:
|
||||
pool = [i for i in buckets.get(rarity, []) if _eligible(i)]
|
||||
if not pool:
|
||||
pool = [i for i in activity_pool if _eligible(i)]
|
||||
if not pool:
|
||||
all_items = _get_raw_items()
|
||||
pool = [i for i in all_items if _eligible(i)]
|
||||
|
||||
item = random.choice(pool) if pool else None
|
||||
|
||||
gift = db.add_gift(
|
||||
profile_id,
|
||||
xp=xp,
|
||||
gift_rarity=_RARITY_WIRE[rarity],
|
||||
avatar_item_desc=item["AvatarItemDesc"] if item else "",
|
||||
consumable_item_desc=consumable,
|
||||
gift_context=gift_context,
|
||||
level=projected_level,
|
||||
)
|
||||
return gift
|
||||
|
||||
@bp.route("/api/avatar/v2", methods=["GET"])
|
||||
@check_auth
|
||||
def get_avatar():
|
||||
pid = get_current_profile_id()
|
||||
avatar = db.get_avatar(pid)
|
||||
if pid and avatar.get("OutfitSelections"):
|
||||
owned = db.get_unlocked_items(pid)
|
||||
avatar["OutfitSelections"] = _filter_outfit_selections(avatar["OutfitSelections"], owned)
|
||||
return jsonify(avatar)
|
||||
|
||||
@bp.route("/api/avatar/v2/set", methods=["POST"])
|
||||
@check_auth
|
||||
def set_avatar():
|
||||
pid = get_current_profile_id()
|
||||
data = request.get_json(force=True, silent=True) or {}
|
||||
db.set_avatar(pid, data)
|
||||
push_profile_update(pid)
|
||||
push_presence(pid, session_mgr.get_player_session(pid))
|
||||
return jsonify(db.get_avatar(pid))
|
||||
|
||||
@bp.route("/api/avatar/v3/items", methods=["GET"])
|
||||
@check_auth
|
||||
def get_avatar_items():
|
||||
pid = get_current_profile_id()
|
||||
raw = _get_raw_items()
|
||||
|
||||
if not db.has_unlocked_items(pid):
|
||||
_seed_starter_unlocks(pid, raw)
|
||||
|
||||
unlocked = db.get_unlocked_items(pid)
|
||||
result = []
|
||||
for i in raw:
|
||||
desc = i["AvatarItemDesc"]
|
||||
name = i.get("FriendlyName", "").lower()
|
||||
is_hair = any(kw in name for kw in _HAIR_KEYWORDS)
|
||||
is_starter = desc.split(",")[0] in _all_starter_guids()
|
||||
if is_hair or is_starter or _is_owned(desc, unlocked):
|
||||
result.append({"AvatarItemDesc": desc, "UnlockedLevel": 1})
|
||||
return jsonify(result)
|
||||
|
||||
@bp.route("/api/avatar/v1/saved", methods=["GET"])
|
||||
@bp.route("/api/avatar/v2/saved", methods=["GET"])
|
||||
@bp.route("/api/avatar/v3/saved", methods=["GET"])
|
||||
@check_auth
|
||||
def get_saved_outfits():
|
||||
pid = get_current_profile_id()
|
||||
if not pid:
|
||||
return jsonify([])
|
||||
outfits = db.get_saved_outfits(pid)
|
||||
owned = db.get_unlocked_items(pid)
|
||||
for outfit in outfits:
|
||||
if outfit.get("OutfitSelections"):
|
||||
outfit["OutfitSelections"] = _filter_outfit_selections(outfit["OutfitSelections"], owned)
|
||||
return jsonify(outfits)
|
||||
|
||||
@bp.route("/api/avatar/v1/saved/set", methods=["POST"])
|
||||
@bp.route("/api/avatar/v2/saved/set", methods=["POST"])
|
||||
@bp.route("/api/avatar/v3/saved/set", methods=["POST"])
|
||||
@check_auth
|
||||
def set_saved_outfit():
|
||||
pid = get_current_profile_id()
|
||||
if not pid:
|
||||
return jsonify({})
|
||||
data = request.get_json(force=True, silent=True) or {}
|
||||
slot = int(data.get("Slot", 0))
|
||||
preview_image_name = str(data.get("PreviewImageName", ""))
|
||||
outfit_selections = str(data.get("OutfitSelections", ""))
|
||||
hair_color = str(data.get("HairColor", ""))
|
||||
skin_color = str(data.get("SkinColor", ""))
|
||||
face_features = str(data.get("FaceFeatures", ""))
|
||||
db.save_outfit(pid, slot, preview_image_name, outfit_selections, hair_color, skin_color, face_features)
|
||||
return jsonify({
|
||||
"Slot": slot,
|
||||
"PreviewImageName": preview_image_name,
|
||||
"OutfitSelections": outfit_selections,
|
||||
"HairColor": hair_color,
|
||||
"SkinColor": skin_color,
|
||||
"FaceFeatures": face_features,
|
||||
})
|
||||
|
||||
@bp.route("/api/avatar/v2/gifts", methods=["GET"])
|
||||
@check_auth
|
||||
def get_gifts():
|
||||
pid = get_current_profile_id()
|
||||
gifts = db.get_pending_gifts(pid) if pid else []
|
||||
return jsonify(gifts)
|
||||
|
||||
@bp.route("/api/avatar/v2/gifts/generate", methods=["POST"])
|
||||
@check_auth
|
||||
@limiter.limit("5 per 5 minutes")
|
||||
def generate_gift():
|
||||
pid = get_current_profile_id()
|
||||
if not pid:
|
||||
return jsonify({})
|
||||
|
||||
from core.gift_dispatch import dispatch_gift
|
||||
session = session_mgr.get_player_session(pid)
|
||||
if not session:
|
||||
print(f"[Gifts] Rejected generate for pid={pid}: not in a session")
|
||||
return jsonify({})
|
||||
activity_guid = getattr(session, "activity_level_id", None) if session else None
|
||||
gift_context = request.values.get("GiftContext", type=int, default=2)
|
||||
|
||||
gift = dispatch_gift(pid, activity_guid, gift_context=gift_context)
|
||||
if gift is None:
|
||||
return jsonify({})
|
||||
|
||||
db.mark_gift_pushed(gift["Id"])
|
||||
return jsonify(gift)
|
||||
|
||||
@bp.route("/api/avatar/v2/gifts/consume/", methods=["POST"])
|
||||
@bp.route("/api/avatar/v2/gifts/consume/<int:gift_id>", methods=["POST"])
|
||||
@check_auth
|
||||
def consume_gift(gift_id=None):
|
||||
pid = get_current_profile_id()
|
||||
if not pid:
|
||||
return Response("Unauthorized", 401)
|
||||
if not session_mgr.get_player_session(pid):
|
||||
print(f"[Gifts] Rejected consume for pid={pid}: not in a session")
|
||||
return Response("OK", 200)
|
||||
|
||||
if gift_id is None:
|
||||
try:
|
||||
_body = request.get_json(force=True, silent=True) or {}
|
||||
gift_id = int(_body.get("Id") or request.values.get("Id") or 0)
|
||||
except (ValueError, TypeError):
|
||||
gift_id = 0
|
||||
|
||||
if not gift_id:
|
||||
return Response("OK", 200)
|
||||
|
||||
owned = db.get_unlocked_items(pid)
|
||||
gift = db.consume_gift(gift_id, pid)
|
||||
if gift is None:
|
||||
return Response("OK", 200)
|
||||
|
||||
if gift.get("AvatarItemDesc"):
|
||||
if _is_owned(gift["AvatarItemDesc"], owned):
|
||||
pool = [i for i in _get_raw_items()
|
||||
if not _is_owned(i["AvatarItemDesc"], owned)
|
||||
and i["AvatarItemDesc"].split(",")[0] not in _all_starter_guids()]
|
||||
if pool:
|
||||
import random as _rnd
|
||||
replacement = _rnd.choice(pool)
|
||||
gift["AvatarItemDesc"] = replacement["AvatarItemDesc"]
|
||||
db.update_gift_item(gift_id, replacement["AvatarItemDesc"])
|
||||
db.unlock_avatar_item(pid, gift["AvatarItemDesc"])
|
||||
|
||||
print(f"[Gifts] Player {pid} consumed gift {gift_id} (xp={gift['Xp']}, "
|
||||
f"item={gift['AvatarItemDesc'][:30] if gift['AvatarItemDesc'] else 'none'}, "
|
||||
f"tokens={gift['Currency'] if gift['CurrencyType'] == 2 else 0})")
|
||||
if gift.get("ConsumableItemDesc"):
|
||||
db.add_consumable(pid, gift["ConsumableItemDesc"], 1)
|
||||
row = db.get_consumable_by_desc(pid, gift["ConsumableItemDesc"])
|
||||
if row:
|
||||
push_consumable_removed(pid, row)
|
||||
push_consumable_added(pid, row)
|
||||
if gift["CurrencyType"] == 2 and gift["Currency"] > 0:
|
||||
new_balance = db.get_tokens(pid)
|
||||
push_store_balance(pid, new_balance, 2, gift["Currency"])
|
||||
if gift["Xp"] > 0 or (gift["CurrencyType"] == 2 and gift["Currency"] > 0):
|
||||
push_profile_update(pid)
|
||||
return Response("OK", 200)
|
||||
257
routes/chat.py
Normal file
257
routes/chat.py
Normal file
@@ -0,0 +1,257 @@
|
||||
|
||||
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})
|
||||
47
routes/config.py
Normal file
47
routes/config.py
Normal file
@@ -0,0 +1,47 @@
|
||||
|
||||
from flask import Blueprint, request, jsonify
|
||||
|
||||
from core.auth import get_server_base
|
||||
from core.builders import now_ticks
|
||||
from core.constants import LEVEL_PROGRESSION_MAPS, DAILY_OBJECTIVE_SETS, get_todays_objectives
|
||||
|
||||
bp = Blueprint("config", __name__)
|
||||
|
||||
@bp.route("/api/versioncheck/v3", methods=["GET"])
|
||||
def version_check():
|
||||
return jsonify({"ValidVersion": True})
|
||||
|
||||
@bp.route("/api/config/v2", methods=["GET"])
|
||||
def get_config():
|
||||
base = get_server_base()
|
||||
return jsonify({
|
||||
"MessageOfTheDay": "Welcome to KittyRec indev!",
|
||||
"CdnBaseUri": base,
|
||||
"MatchmakingParams": {
|
||||
"PreferFullRoomsFrequency": 0.5,
|
||||
"PreferEmptyRoomsFrequency": 0.5,
|
||||
},
|
||||
"ServerMaintenance": {
|
||||
"StartsInMinutes": -1,
|
||||
},
|
||||
"LevelProgressionMaps": LEVEL_PROGRESSION_MAPS,
|
||||
"DailyObjectives": DAILY_OBJECTIVE_SETS,
|
||||
"ConfigTable": [
|
||||
{"Key": "ShareCamera.Enabled", "Value": "1"},
|
||||
{"Key": "CustomRooms.Enabled", "Value": "1"},
|
||||
{"Key": "ChallengesV2.Enabled", "Value": "1"},
|
||||
{"Key": "Consumables.Enabled", "Value": "1"},
|
||||
{"Key": "Rooms.MaxCustomRooms", "Value": "100"},
|
||||
{"Key": "Gift.DropChance", "Value": "1.0"},
|
||||
{"Key": "Gift.Falloff", "Value": "1.2"},
|
||||
{"Key": "Gift.MaxDaily", "Value": "10"},
|
||||
],
|
||||
"PhotonConfig": {
|
||||
"CrcCheckEnabled": False,
|
||||
"EnableServerTracingAfterDisconnect": False,
|
||||
},
|
||||
})
|
||||
|
||||
@bp.route("/api/config/v1/amplitude", methods=["GET"])
|
||||
def get_amplitude_config():
|
||||
return jsonify({"AmplitudeKey": "meowmeowmeow"})
|
||||
Reference in New Issue
Block a user