1009 lines
35 KiB
Python
1009 lines
35 KiB
Python
|
|
import json
|
|
import os
|
|
import re
|
|
import threading
|
|
import time
|
|
import uuid
|
|
from collections import deque
|
|
from datetime import datetime, timezone, timedelta
|
|
from flask import Blueprint, request, jsonify, Response
|
|
from urllib.parse import unquote_plus
|
|
|
|
from core.auth import check_auth, get_current_profile_id
|
|
from core.limiter import limiter
|
|
from core.state import db, session_mgr
|
|
from core.config import base_url as _base_url
|
|
from core.profanity import is_hate_speech as _is_hate_speech
|
|
|
|
_groups: dict = {}
|
|
_groups_lock = threading.Lock()
|
|
_groups_counter: list = [0]
|
|
|
|
_ROYALE_TIERS = [
|
|
(0, "Rookie", 0, 500),
|
|
(500, "Bronze", 500, 1500),
|
|
(1500, "Silver", 1500, 3500),
|
|
(3500, "Gold", 3500, 7000),
|
|
(7000, "Platinum", 7000, 12000),
|
|
(12000, "Diamond", 12000, 20000),
|
|
(20000, "Champion", 20000, 20000),
|
|
]
|
|
|
|
def _royale_stats(xp: int) -> dict:
|
|
tier = _ROYALE_TIERS[0]
|
|
for i, t in enumerate(_ROYALE_TIERS):
|
|
if xp >= t[0]:
|
|
tier = t
|
|
else:
|
|
break
|
|
idx = _ROYALE_TIERS.index(tier)
|
|
return {
|
|
"TotalXP": xp,
|
|
"Level": idx + 1,
|
|
"RankIdx": idx,
|
|
"RankName": tier[1],
|
|
"CurrentLevelXPThreshold": tier[2],
|
|
"NextLevelXPThreshold": tier[3],
|
|
"NextLevelAcornReward": idx * 25,
|
|
}
|
|
|
|
def _get_royale_xp(pid: int) -> int:
|
|
settings = db.get_settings(pid)
|
|
for s in settings:
|
|
if s["Key"] == "royale_xp":
|
|
try:
|
|
return int(s["Value"])
|
|
except (ValueError, TypeError):
|
|
return 0
|
|
return 0
|
|
|
|
def _build_group_dict(g: dict) -> dict:
|
|
gid = g["GroupId"]
|
|
member_pids = g.get("_member_pids", [])
|
|
return {
|
|
"GroupId": gid,
|
|
"Name": g.get("Name", ""),
|
|
"Description": g.get("Description", ""),
|
|
"CreatedAt": g.get("CreatedAt", datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")),
|
|
"ImageName": g.get("ImageName", ""),
|
|
"BanStatus": 0,
|
|
"CreatorId": g.get("CreatorId", 0),
|
|
"NumMembers": len(member_pids),
|
|
"Members": [{"GroupId": gid, "PlayerId": p, "Permissions": 0} for p in member_pids],
|
|
}
|
|
|
|
_MEMORY_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "uploads", "memories")
|
|
os.makedirs(_MEMORY_DIR, exist_ok=True)
|
|
|
|
def _build_slur_re():
|
|
_PATTERNS = [
|
|
r"n[i1!|][gq9][gq9][e3]r",
|
|
r"n[i1!|][gq9][gq9][ae3]",
|
|
r"n[i1!|][gq9][gq9][ae3][sz]",
|
|
r"f[a4][gq9][gq9][o0]t",
|
|
r"f[a4][gq9][gq9][o0]t[sz]",
|
|
r"f[a4][gq9]",
|
|
r"ch[i1][nk][gq][sz]?",
|
|
r"g[o0][o0]k[sz]?",
|
|
r"sp[i1][cks][sz]?",
|
|
r"w[e3]tb[a4][cks][gq][sz]?",
|
|
r"k[i1][ck][e3][sz]?",
|
|
r"j[e3]w[sz]?\b",
|
|
r"h[e3][e3]b[sz]?",
|
|
r"cr[a4][cks][gq][e3]r[sz]?",
|
|
r"j[i1][gq][a4]b[o0][o0]",
|
|
r"t[o0]w[e3]lh[e3][a4]d",
|
|
r"r[e3]t[a4]rd",
|
|
r"tr[a4]nn[yi1][e3]?[sz]?",
|
|
r"[sz]h[e3]m[a4][l1][e3]",
|
|
]
|
|
combined = "|".join(r"(?<!\w)(?:" + p + r")(?!\w)" for p in _PATTERNS)
|
|
return re.compile(combined, re.IGNORECASE)
|
|
|
|
_SLUR_RE = _build_slur_re()
|
|
_sanitize_log: deque = deque(maxlen=500)
|
|
|
|
_SANITIZE_LOG_FILE = os.path.join(os.path.dirname(__file__), "..", "tracking", "sanitize_log.json")
|
|
|
|
def _load_sanitize_log() -> None:
|
|
try:
|
|
if os.path.exists(_SANITIZE_LOG_FILE):
|
|
with open(_SANITIZE_LOG_FILE) as f:
|
|
entries = json.load(f)
|
|
for e in reversed(entries[:500]):
|
|
_sanitize_log.appendleft(e)
|
|
except Exception as e:
|
|
print(f"[Sanitize] Failed to load log: {e}")
|
|
|
|
def _save_sanitize_log() -> None:
|
|
try:
|
|
with open(_SANITIZE_LOG_FILE, "w") as f:
|
|
json.dump(list(_sanitize_log), f)
|
|
except Exception as e:
|
|
print(f"[Sanitize] Failed to save log: {e}")
|
|
|
|
def _is_pure(text: str) -> bool:
|
|
return _SLUR_RE.search(text) is None
|
|
|
|
def get_sanitize_log():
|
|
return list(_sanitize_log)
|
|
|
|
_load_sanitize_log()
|
|
|
|
bp = Blueprint("misc", __name__)
|
|
|
|
@bp.route("/discord", methods=["GET"])
|
|
def discord_redirect():
|
|
from flask import redirect
|
|
return redirect("https://discord.gg/n43M7dCBQX", 302)
|
|
|
|
@bp.route("/api/playerevents/v1/all", methods=["GET"])
|
|
@check_auth
|
|
def get_all_player_events():
|
|
events = db.get_active_events()
|
|
created = []
|
|
for e in events:
|
|
created.append({
|
|
"EventId": e["id"],
|
|
"Name": e["name"],
|
|
"Description": e["description"],
|
|
"StartTime": e["start_time"],
|
|
"EndTime": e["end_time"],
|
|
"PosterImageName": e["poster_image"],
|
|
"CreatorPlayerId": e["creator_player_id"],
|
|
})
|
|
return jsonify({"Created": created, "Responses": []})
|
|
|
|
@bp.route("/api/playerevents/v1/<int:event_id>", methods=["GET"])
|
|
@check_auth
|
|
def get_player_event(event_id):
|
|
e = db.get_event(event_id)
|
|
if not e:
|
|
return Response("Not Found", 404)
|
|
return jsonify({
|
|
"EventId": e["id"],
|
|
"Name": e["name"],
|
|
"Description": e["description"],
|
|
"StartTime": e["start_time"],
|
|
"EndTime": e["end_time"],
|
|
"PosterImageName": e["poster_image"],
|
|
"CreatorPlayerId": e["creator_player_id"],
|
|
})
|
|
|
|
@bp.route("/api/playerevents/v1/respond", methods=["POST"])
|
|
@check_auth
|
|
def respond_to_event():
|
|
return Response("OK", 200)
|
|
|
|
def _sub_challenge_config(ch: dict, sub_index: int, current_score: int) -> str:
|
|
cc = min(max(current_score - sub_index, 0), 1)
|
|
config = {
|
|
"ct": 1,
|
|
"t": 1,
|
|
"cc": cc,
|
|
"ctc": [
|
|
{
|
|
"ct": 7,
|
|
"vs": [{"a": ch["activity_int"], "l": 0}],
|
|
}
|
|
],
|
|
}
|
|
return json.dumps(config, separators=(",", ":"))
|
|
|
|
|
|
def _build_challenge_message(ch: dict, prog: dict) -> str:
|
|
from datetime import datetime, timezone
|
|
from core.constants import KNOWN_ACTIVITIES
|
|
current = prog["current_score"]
|
|
now_utc = datetime.now(timezone.utc)
|
|
start_dt = datetime.fromtimestamp(ch["start_time"], tz=timezone.utc)
|
|
end_dt = datetime.fromtimestamp(ch["end_time"], tz=timezone.utc)
|
|
fmt = "%Y-%m-%dT%H:%M:%SZ"
|
|
target = ch["target"]
|
|
activity_name = KNOWN_ACTIVITIES.get(ch["activity_guid"], (ch["title"],))[0]
|
|
challenges = []
|
|
for i in range(target):
|
|
challenges.append({
|
|
"ChallengeId": ch["id"] * 10 + (i + 1),
|
|
"Name": ch["title"],
|
|
"Description": f"Play a game of {activity_name}.",
|
|
"Tooltip": "",
|
|
"Complete": current > i,
|
|
"Config": _sub_challenge_config(ch, i, current),
|
|
})
|
|
hammikjfffb = {
|
|
"ChallengeMapId": ch["id"],
|
|
"StartAt": start_dt.strftime(fmt),
|
|
"EndAt": end_dt.strftime(fmt),
|
|
"ServerTime": now_utc.strftime(fmt),
|
|
"Challenges": challenges,
|
|
"Gifts": [],
|
|
}
|
|
return json.dumps(hammikjfffb, separators=(",", ":"))
|
|
|
|
|
|
@bp.route("/api/challenge/v1/getCurrent", methods=["GET"])
|
|
@check_auth
|
|
def get_current_challenge():
|
|
return jsonify({"Success": False, "Message": ""})
|
|
from core.constants import get_current_weekly_challenge
|
|
pid = get_current_profile_id()
|
|
ch = get_current_weekly_challenge()
|
|
prog = db.get_challenge_progress(pid, ch["week"]) if pid else {"current_score": 0, "completed": False, "reward_claimed": False}
|
|
return jsonify({
|
|
"Success": True,
|
|
"Message": _build_challenge_message(ch, prog),
|
|
})
|
|
|
|
|
|
@bp.route("/api/challenge/v2/updateProgress", methods=["POST"])
|
|
@check_auth
|
|
def update_challenge_progress():
|
|
return Response("OK", 200)
|
|
from core.constants import get_current_weekly_challenge
|
|
from core.ws_helpers import push_gift
|
|
pid = get_current_profile_id()
|
|
if not pid:
|
|
return Response("OK", 200)
|
|
data = request.get_json(force=True, silent=True) or {}
|
|
print(f"[Challenge] updateProgress pid={pid}: {data}")
|
|
ch = get_current_weekly_challenge()
|
|
db_key = ch["week"]
|
|
incoming_map_id = int(data.get("ChallengeMapId") or 0)
|
|
if incoming_map_id and incoming_map_id != ch["id"]:
|
|
print(f"[Challenge] updateProgress: ignoring stale ChallengeMapId={incoming_map_id} (current={ch['id']})")
|
|
return Response("OK", 200)
|
|
prog = db.get_challenge_progress(pid, db_key)
|
|
if prog["completed"]:
|
|
return Response("OK", 200)
|
|
config_str = data.get("Config", "")
|
|
if config_str:
|
|
try:
|
|
cfg = json.loads(config_str)
|
|
client_score = int(cfg.get("cc", 0))
|
|
if client_score > prog["current_score"]:
|
|
db.set_challenge_progress(pid, db_key, client_score)
|
|
prog = db.get_challenge_progress(pid, db_key)
|
|
print(f"[Challenge] Player {pid} progress on '{ch['title']}': {client_score}/{ch['target']}")
|
|
except Exception:
|
|
pass
|
|
complete_flag = str(data.get("Complete", "")).lower() == "true"
|
|
if complete_flag and not prog["completed"]:
|
|
from routes.avatar import _get_activity_item_pool, _QUEST_CONSUMABLES
|
|
import random as _rnd
|
|
db.mark_challenge_completed(pid, db_key)
|
|
_pool = _get_activity_item_pool(ch["activity_guid"])
|
|
_item = _rnd.choice(_pool) if _pool else None
|
|
_consumable = _QUEST_CONSUMABLES.get(ch["activity_guid"], "")
|
|
gift = db.add_gift(pid, xp=ch["reward_xp"], gift_rarity=ch["reward_rarity"],
|
|
avatar_item_desc=_item["AvatarItemDesc"] if _item else "",
|
|
consumable_item_desc=_consumable,
|
|
message=f"Weekly Challenge: {ch['title']}!", gift_context=6)
|
|
push_gift(pid, gift)
|
|
print(f"[Challenge] Player {pid} completed '{ch['title']}' via updateProgress — reward sent")
|
|
return Response("OK", 200)
|
|
|
|
@bp.route("/api/PlayerReporting/v3/create", methods=["POST"])
|
|
@limiter.limit("5 per minute")
|
|
@check_auth
|
|
def create_report():
|
|
return jsonify({"Success": True, "Message": ""})
|
|
|
|
@bp.route("/api/PlayerReporting/v1/moderationBlockDetails", methods=["GET"])
|
|
def moderation_block_details():
|
|
pid = get_current_profile_id()
|
|
if pid:
|
|
ban = db.get_ban_info(pid)
|
|
if ban:
|
|
duration_h = 0
|
|
if ban.get("banned_until"):
|
|
try:
|
|
exp = datetime.fromisoformat(ban["banned_until"])
|
|
if exp.tzinfo is None:
|
|
exp = exp.replace(tzinfo=timezone.utc)
|
|
secs_left = max(0, int((exp - datetime.now(timezone.utc)).total_seconds()))
|
|
duration_h = max(1, secs_left // 3600)
|
|
except Exception:
|
|
pass
|
|
return jsonify({
|
|
"ReportCategory": -1,
|
|
"Duration": duration_h,
|
|
"GameSessionId": 0,
|
|
"Message": db.format_ban_message(ban),
|
|
})
|
|
return jsonify({
|
|
"ReportCategory": 0,
|
|
"Duration": 0,
|
|
"GameSessionId": 0,
|
|
"Message": "",
|
|
})
|
|
|
|
@bp.route("/api/PlayerReporting/v2/voteToKick", methods=["POST"])
|
|
@check_auth
|
|
def vote_to_kick():
|
|
return jsonify({"Success": True, "Message": ""})
|
|
|
|
@bp.route("/api/PlayerReporting/v1/kickFromEvent", methods=["POST"])
|
|
@check_auth
|
|
def kick_from_event():
|
|
return jsonify({"Success": True, "Message": ""})
|
|
|
|
@bp.route("/api/playerReputation/v1/heal", methods=["POST"])
|
|
@check_auth
|
|
def heal_reputation():
|
|
return Response("OK", 200)
|
|
|
|
@bp.route("/api/PlayersBanned/v2/ban", methods=["POST", "GET"])
|
|
@check_auth
|
|
def player_ban():
|
|
return jsonify({"IsBanned": False, "BannedUntil": 0})
|
|
|
|
@bp.route("/api/playersubscriptions/v1/my", methods=["GET"])
|
|
@check_auth
|
|
def get_my_subscriptions():
|
|
pid = get_current_profile_id()
|
|
subs = db.get_subscriptions(pid) if pid else []
|
|
return jsonify([{"PlayerId": s["PlayerId"]} for s in subs])
|
|
|
|
@bp.route("/api/playersubscriptions/v1/subscribe/<int:player_id>", methods=["GET", "POST"])
|
|
@check_auth
|
|
def subscribe_player(player_id):
|
|
return jsonify({"Response": 1})
|
|
|
|
@bp.route("/api/playersubscriptions/v1/unsubscribe/<int:player_id>", methods=["GET", "POST"])
|
|
@check_auth
|
|
def unsubscribe_player(player_id):
|
|
return jsonify({"Response": 1})
|
|
|
|
@bp.route("/api/playersubscriptions/v1/status/<int:player_id>", methods=["GET"])
|
|
@check_auth
|
|
def subscription_status(player_id):
|
|
pid = get_current_profile_id()
|
|
subscribed = db.is_subscribed(pid, player_id) if pid else False
|
|
count = db.get_subscriber_count(player_id)
|
|
return jsonify({"Status": 1 if subscribed else 0, "SubscriberCount": count})
|
|
|
|
@bp.route("/api/groups/v1", methods=["GET", "POST"])
|
|
@check_auth
|
|
def groups_root():
|
|
pid = get_current_profile_id()
|
|
if request.method == "POST":
|
|
data = request.get_json(force=True, silent=True) or {}
|
|
with _groups_lock:
|
|
_groups_counter[0] += 1
|
|
gid = _groups_counter[0]
|
|
_groups[gid] = {
|
|
"GroupId": gid,
|
|
"Name": data.get("Name", ""),
|
|
"Description": data.get("Description", ""),
|
|
"CreatedAt": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
"ImageName": data.get("ImageName", ""),
|
|
"CreatorId": pid or 0,
|
|
"_member_pids": [pid] if pid else [],
|
|
}
|
|
group_dict = _build_group_dict(_groups[gid])
|
|
return jsonify({"Status": 0, "Group": group_dict})
|
|
with _groups_lock:
|
|
my = [_build_group_dict(g) for g in _groups.values() if pid in g.get("_member_pids", [])]
|
|
return jsonify(my)
|
|
|
|
@bp.route("/api/groups/v1/<path:group_id>", methods=["GET"])
|
|
@check_auth
|
|
def get_group(group_id):
|
|
pid = get_current_profile_id()
|
|
try:
|
|
gid = int(group_id)
|
|
except (ValueError, TypeError):
|
|
gid = group_id
|
|
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
with _groups_lock:
|
|
g = _groups.get(gid)
|
|
if g is None:
|
|
return jsonify({"GroupId": gid, "Name": "", "Description": "", "CreatedAt": now, "ImageName": "", "BanStatus": 0, "CreatorId": 0, "NumMembers": 0, "Members": []})
|
|
if pid and pid not in g.get("_member_pids", []):
|
|
g.setdefault("_member_pids", []).append(pid)
|
|
return jsonify(_build_group_dict(g))
|
|
|
|
@bp.route("/api/groups/v1/delete/<path:group_id>", methods=["POST"])
|
|
@check_auth
|
|
def delete_group(group_id):
|
|
try:
|
|
gid = int(group_id)
|
|
except (ValueError, TypeError):
|
|
gid = group_id
|
|
pid = get_current_profile_id()
|
|
with _groups_lock:
|
|
g = _groups.get(gid)
|
|
if g is not None and g.get("CreatorId") == pid:
|
|
_groups.pop(gid, None)
|
|
return jsonify({"Status": 0})
|
|
|
|
@bp.route("/api/groups/v1/name/<path:name>", methods=["GET"])
|
|
@check_auth
|
|
def get_group_by_name(name):
|
|
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
with _groups_lock:
|
|
for g in _groups.values():
|
|
if g.get("Name") == name:
|
|
return jsonify(_build_group_dict(g))
|
|
return jsonify({"GroupId": 0, "Name": name, "Description": "", "CreatedAt": now, "ImageName": "", "BanStatus": 0, "CreatorId": 0, "NumMembers": 0, "Members": []})
|
|
|
|
@bp.route("/api/events/v1/status/<int:event_id>", methods=["GET"])
|
|
@check_auth
|
|
def get_event_status(event_id):
|
|
return jsonify({"EventId": event_id, "Status": 0})
|
|
|
|
@bp.route("/api/events/v3/list", methods=["GET"])
|
|
@check_auth
|
|
def list_events():
|
|
return jsonify([])
|
|
|
|
@bp.route("/api/royale/v1/current", methods=["GET"])
|
|
@check_auth
|
|
def get_current_royale():
|
|
pid = get_current_profile_id()
|
|
xp = _get_royale_xp(pid) if pid else 0
|
|
return jsonify(_royale_stats(xp))
|
|
|
|
@bp.route("/api/royale/v1/matchcomplete", methods=["POST"])
|
|
@limiter.limit("10 per hour")
|
|
@check_auth
|
|
def royale_match_complete():
|
|
pid = get_current_profile_id()
|
|
if pid:
|
|
if not session_mgr.get_player_session(pid):
|
|
print(f"[Royale] Rejected matchcomplete for pid={pid}: not in a session")
|
|
return jsonify(_royale_stats(_get_royale_xp(pid)))
|
|
data = request.get_json(force=True, silent=True) or {}
|
|
earned = max(0, min(int(data.get("XpEarned", data.get("xp_earned", data.get("Xp", 200)))), 200))
|
|
current = _get_royale_xp(pid)
|
|
new_xp = current + earned
|
|
db.set_setting(pid, "royale_xp", str(new_xp))
|
|
result = _royale_stats(new_xp)
|
|
result["TotalXPAwarded"] = earned
|
|
return jsonify(result)
|
|
return jsonify(_royale_stats(0))
|
|
|
|
@bp.route("/api/PlayerCheer/v1/create", methods=["GET", "POST"])
|
|
@check_auth
|
|
def create_cheer():
|
|
from core.ws_helpers import push_profile_update
|
|
pid = get_current_profile_id()
|
|
data = request.get_json(force=True, silent=True) or request.values.to_dict()
|
|
to_pid = int(data.get("ToPlayerId", 0) or request.args.get("ToPlayerId", 0))
|
|
if pid and to_pid and pid != to_pid:
|
|
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
|
if not db.has_cheered_today(pid, to_pid, today):
|
|
db.record_cheer(pid, to_pid, today)
|
|
db.update_profile(to_pid, {"reputation": (db.get_profile(to_pid) or {}).get("Reputation", 0) + 1})
|
|
push_profile_update(to_pid)
|
|
print(f"[Cheer] Player {pid} cheered player {to_pid}")
|
|
return jsonify({"Success": True})
|
|
|
|
@bp.route("/api/PlayerCheer/v1/SetSelectedCheer", methods=["GET", "POST"])
|
|
@check_auth
|
|
def set_selected_cheer():
|
|
pid = get_current_profile_id()
|
|
data = request.get_json(force=True, silent=True) or request.values.to_dict()
|
|
cheer_idx = int(data.get("SelectedCheer", 0) or request.args.get("SelectedCheer", 0))
|
|
db.update_profile(pid, {"selected_cheer": cheer_idx})
|
|
return jsonify({"Success": True})
|
|
|
|
@bp.route("/api/Leaderboard/v1", methods=["GET", "POST"])
|
|
@check_auth
|
|
def leaderboard():
|
|
from core.constants import REL_FRIEND
|
|
obj_type = int(request.values.get("ObjectiveType", 1))
|
|
limit = max(1, min(int(request.values.get("Limit", 100)), 500))
|
|
|
|
pid = get_current_profile_id()
|
|
friend_ids = []
|
|
if pid:
|
|
friend_ids = [r["PlayerID"] for r in db.get_relationships(pid) if r["RelationshipType"] == REL_FRIEND]
|
|
if pid not in friend_ids:
|
|
friend_ids.append(pid)
|
|
|
|
now = datetime.now(timezone.utc)
|
|
days_until_sunday = (6 - now.weekday()) % 7 or 7
|
|
next_reset = (now + timedelta(days=days_until_sunday)).replace(
|
|
hour=0, minute=0, second=0, microsecond=0
|
|
).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
return jsonify({
|
|
"GlobalOverall": db.get_leaderboard(obj_type, limit),
|
|
"GlobalPeriodic": db.get_leaderboard(obj_type, limit, sort_periodic=True),
|
|
"FriendsOverall": db.get_leaderboard(obj_type, limit, friend_ids=friend_ids),
|
|
"FriendsPeriodic": db.get_leaderboard(obj_type, limit, friend_ids=friend_ids, sort_periodic=True),
|
|
"NextResetUTC": next_reset,
|
|
})
|
|
|
|
@bp.route("/api/PlayerElo/<path:action>", methods=["GET", "POST"])
|
|
@check_auth
|
|
def player_elo(action):
|
|
return jsonify({})
|
|
|
|
@bp.route("/api/sanitize/<path:action>", methods=["POST"])
|
|
@check_auth
|
|
def sanitize(action):
|
|
data = request.get_json(force=True, silent=True) or {}
|
|
text = str(data.get("Text", data.get("Value", "")))
|
|
pure = not _is_hate_speech(text)
|
|
pid = get_current_profile_id()
|
|
if not pure:
|
|
print(f"[Sanitize] REJECTED pid={pid}: {text!r}")
|
|
entry = {
|
|
"text": text,
|
|
"pid": pid,
|
|
"flagged": not pure,
|
|
"ts": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
}
|
|
_sanitize_log.appendleft(entry)
|
|
_save_sanitize_log()
|
|
try:
|
|
profile = db.get_profile(pid) if pid else None
|
|
enriched = dict(entry)
|
|
enriched["username"] = profile.get("Username", f"#{pid}") if profile else (f"#{pid}" if pid else "?")
|
|
import core.admin_ws as awr
|
|
awr.push({"type": "sanitize_entry", "entry": enriched})
|
|
except Exception:
|
|
pass
|
|
return jsonify({"IsPure": pure})
|
|
|
|
@bp.route("/api/datablob/v1/deletetransient", methods=["POST"])
|
|
@check_auth
|
|
def delete_transient_blob():
|
|
return Response("OK", 200)
|
|
|
|
@bp.route("/api/datablob/v1/deletesaved", methods=["POST"])
|
|
@check_auth
|
|
def delete_saved_blob():
|
|
return Response("OK", 200)
|
|
|
|
@bp.route("/api/datablob/<path:action>", methods=["GET", "POST"])
|
|
@check_auth
|
|
def datablob_catchall(action):
|
|
return jsonify({})
|
|
|
|
@bp.route("/api/activities/charades/v1/words", methods=["GET"])
|
|
@check_auth
|
|
def charades_words():
|
|
import os
|
|
words_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "charades_words.txt")
|
|
try:
|
|
with open(words_path) as f:
|
|
lines = [line.strip() for line in f if line.strip()]
|
|
except FileNotFoundError:
|
|
lines = []
|
|
result = []
|
|
for line in lines:
|
|
if "|" in line:
|
|
parts = line.split("|", 1)
|
|
try:
|
|
difficulty = int(parts[1].strip())
|
|
except ValueError:
|
|
difficulty = 0
|
|
result.append({"EN_US": parts[0].strip(), "Difficulty": difficulty})
|
|
else:
|
|
result.append({"EN_US": line, "Difficulty": 0})
|
|
return jsonify(result)
|
|
|
|
@bp.route("/api/bulletinboard/v1/featuredrooms", methods=["GET"])
|
|
def featured_rooms():
|
|
print(f"[BulletinBoard] featuredrooms requested from {request.headers.get('X-Forwarded-For', request.remote_addr)}")
|
|
resp = [{"displayName": "KittyRec", "roomId": 0, "roomImage": "public/featured_room.jpg"}]
|
|
print(f"[BulletinBoard] returning {len(resp)} room(s): {resp}")
|
|
return jsonify(resp)
|
|
|
|
|
|
_MEMORY_MAX_BYTES = 2 * 1024 * 1024
|
|
|
|
_MAGIC = [
|
|
(b"\x89PNG\r\n\x1a\n", "png"),
|
|
(b"\xff\xd8\xff", "jpg"),
|
|
(b"GIF87a", "gif"),
|
|
(b"GIF89a", "gif"),
|
|
(b"RIFF", "webp"),
|
|
(b"\x00\x00\x00\x18ftyp", "mp4"),
|
|
(b"\x00\x00\x00\x1cftyp", "mp4"),
|
|
(b"\x00\x00\x00 ftyp", "mp4"),
|
|
(b"\x1aE\xdf\xa3", "webm"),
|
|
(b"OggS", "ogg"),
|
|
(b"fLaC", "flac"),
|
|
(b"\xff\xfb", "mp3"),
|
|
(b"ID3", "mp3"),
|
|
]
|
|
|
|
def _detect_ext(data: bytes) -> str:
|
|
for magic, ext in _MAGIC:
|
|
if data[:len(magic)] == magic:
|
|
if ext == "webp" and len(data) >= 12 and data[8:12] == b"WEBP":
|
|
return "webp"
|
|
elif ext != "webp":
|
|
return ext
|
|
return "bin"
|
|
|
|
@bp.route("/api/MemoryStream/v1/upload", methods=["POST"])
|
|
@check_auth
|
|
def memory_upload():
|
|
pid = get_current_profile_id()
|
|
if not pid or not session_mgr.get_player_session(pid):
|
|
print(f"[MemoryStream] Rejected upload for pid={pid}: not in a session")
|
|
return jsonify({"fileName": "not provided"})
|
|
game_session_id = request.args.get("gameSessionId", "")
|
|
room_name = ""
|
|
if game_session_id:
|
|
try:
|
|
sid = int(game_session_id)
|
|
sess = session_mgr.get_session(sid)
|
|
if sess:
|
|
room_name = sess.name or ""
|
|
except Exception:
|
|
pass
|
|
|
|
print(f"[MemoryStream] pid={pid} upload request — content-type={request.content_type!r} content-length={request.content_length} gameSessionId={game_session_id!r} room={room_name!r}")
|
|
print(f"[MemoryStream] files keys={list(request.files.keys())} form keys={list(request.form.keys())}")
|
|
|
|
data_bytes = b""
|
|
file_obj = request.files.get("data")
|
|
if file_obj is not None:
|
|
data_bytes = file_obj.read(_MEMORY_MAX_BYTES + 1)
|
|
print(f"[MemoryStream] pid={pid} — source=files filename={file_obj.filename!r} content_type={file_obj.content_type!r} raw_size={len(data_bytes)}")
|
|
else:
|
|
form_val = request.form.get("data")
|
|
if form_val is not None:
|
|
data_bytes = form_val.encode("latin-1") if isinstance(form_val, str) else form_val
|
|
print(f"[MemoryStream] pid={pid} — source=form size={len(data_bytes)}")
|
|
else:
|
|
data_bytes = request.get_data(cache=False)
|
|
print(f"[MemoryStream] pid={pid} — source=raw_body size={len(data_bytes)}")
|
|
|
|
if not data_bytes:
|
|
print(f"[MemoryStream] pid={pid} — REJECTED: no data")
|
|
return jsonify({"fileName": "not provided"})
|
|
if len(data_bytes) > _MEMORY_MAX_BYTES:
|
|
print(f"[MemoryStream] pid={pid} — REJECTED: {len(data_bytes)} bytes exceeds 20MB limit")
|
|
return jsonify({"fileName": "not provided"})
|
|
|
|
zero_bytes = sum(1 for b in data_bytes[:256] if b == 0)
|
|
print(f"[MemoryStream] pid={pid} — first 64 bytes: {data_bytes[:64].hex()}")
|
|
print(f"[MemoryStream] pid={pid} — zero ratio in first 256 bytes: {zero_bytes}/256")
|
|
|
|
ext = _detect_ext(data_bytes)
|
|
if ext == "bin":
|
|
print(f"[MemoryStream] pid={pid} — REJECTED: unrecognized file type")
|
|
return jsonify({"fileName": "not provided"})
|
|
filename = f"{uuid.uuid4()}.{ext}"
|
|
filepath = os.path.join(_MEMORY_DIR, filename)
|
|
with open(filepath, "wb") as f:
|
|
f.write(data_bytes)
|
|
db.save_memory_upload(pid, game_session_id, room_name, filename, len(data_bytes))
|
|
print(f"[MemoryStream] pid={pid} — SAVED '{filename}' ({len(data_bytes)} bytes, type={ext}) room='{room_name}'")
|
|
return jsonify({"fileName": filename})
|
|
|
|
|
|
@bp.route("/api/analytics/<path:action>", methods=["GET", "POST"])
|
|
def analytics_catchall(action):
|
|
return Response("OK", 200)
|
|
|
|
|
|
@bp.route("/amplitude/<path:action>", methods=["GET", "POST"])
|
|
def amplitude_catchall(action):
|
|
try:
|
|
pairs = {}
|
|
ct = request.content_type or ""
|
|
if "form" in ct:
|
|
for k, v in request.form.items():
|
|
try:
|
|
pairs[k] = json.loads(v)
|
|
except (json.JSONDecodeError, TypeError):
|
|
pairs[k] = v
|
|
else:
|
|
raw = request.get_data(as_text=True)
|
|
if raw:
|
|
try:
|
|
body = json.loads(raw)
|
|
if isinstance(body, dict):
|
|
pairs = body
|
|
except json.JSONDecodeError:
|
|
for part in raw.split("&"):
|
|
if "=" in part:
|
|
k, v = part.split("=", 1)
|
|
v = unquote_plus(v)
|
|
try:
|
|
pairs[k] = json.loads(v)
|
|
except (json.JSONDecodeError, TypeError):
|
|
pairs[k] = v
|
|
|
|
events = pairs.get("event") or pairs.get("events", [])
|
|
if isinstance(events, dict):
|
|
events = [events]
|
|
if not isinstance(events, list):
|
|
events = []
|
|
|
|
identifications = pairs.get("identification", [])
|
|
if isinstance(identifications, str):
|
|
try:
|
|
identifications = json.loads(identifications)
|
|
except Exception:
|
|
identifications = []
|
|
if not isinstance(identifications, list):
|
|
identifications = [identifications] if identifications else []
|
|
|
|
stored = 0
|
|
if events:
|
|
db.save_amplitude_events_batch(events)
|
|
stored += len(events)
|
|
if identifications:
|
|
identify_events = [{
|
|
"user_id": i.get("user_id", 0),
|
|
"event_type": "$identify",
|
|
"event_time": 0,
|
|
"event_properties": {},
|
|
"user_properties": i.get("user_properties", {}),
|
|
"app_version": i.get("app_version", ""),
|
|
"insert_id": "",
|
|
} for i in identifications if isinstance(i, dict)]
|
|
if identify_events:
|
|
db.save_amplitude_events_batch(identify_events)
|
|
stored += len(identify_events)
|
|
|
|
if stored:
|
|
print(f"[Amplitude] /{action}: stored {stored} event(s)")
|
|
else:
|
|
print(f"[Amplitude] /{action}: no events in payload")
|
|
|
|
_process_analytics_gifts(events)
|
|
|
|
except Exception as e:
|
|
print(f"[Amplitude] /{action}: parse error: {e}")
|
|
return Response("OK", 200)
|
|
|
|
_MIN_PLAY_SECONDS = 90
|
|
|
|
def _process_analytics_gifts(events):
|
|
pass
|
|
|
|
|
|
_CLIENT_LOG_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "uploads", "clientlogs")
|
|
os.makedirs(_CLIENT_LOG_DIR, exist_ok=True)
|
|
|
|
_BAT_TEMPLATE = rf"""@echo off
|
|
setlocal enabledelayedexpansion
|
|
set "LOGDIR=%APPDATA%\..\LocalLow\Against Gravity\Rec Room"
|
|
set "SERVER={_base_url}"
|
|
set "LOGFILE=%LOGDIR%\output_log.txt"
|
|
set "CLEANED=%TEMP%\kittyrec_log_cleaned.txt"
|
|
|
|
echo KittyRec Live Log Streamer
|
|
echo ==========================
|
|
echo.
|
|
|
|
if not exist "%LOGFILE%" (
|
|
echo output_log.txt not found at: %LOGDIR%
|
|
echo Make sure Rec Room has been run at least once.
|
|
pause
|
|
exit /b 1
|
|
)
|
|
|
|
echo Streaming logs to server every 5 seconds...
|
|
echo Press Ctrl+C to stop.
|
|
echo.
|
|
|
|
:loop
|
|
findstr /v /c:"Not allowed to access triangles/indices on mesh" /c:"(Filename: C:\buildslave\unity\build" /c:"(isReadable is false" /c:"DivideByZeroException: Division by zero" /c:"RecRoom.Radio" /c:"FlyVRMovementController" /c:"PlayerGameRoleManager" /c:"NullReferenceException: Object reference not set" /c:"VRPlayerController.ECOJHEDOHIG" /c:"XR: OpenVR" /c:"Thread -> id:" /c:"[Physics.PhysX]" /c:"Unloading unused" /c:"GarbageCollect" "%LOGFILE%" > "%CLEANED%"
|
|
curl -s -X POST "%SERVER%/api/clientlogs/stream" -F "log=@\"%CLEANED%\"" -o nul
|
|
echo [%TIME%] Pushed log (%~z1 bytes)
|
|
timeout /t 5 /nobreak >nul
|
|
goto loop
|
|
"""
|
|
|
|
|
|
@bp.route("/api/clientlogs/getuploader", methods=["GET"])
|
|
def download_log_uploader():
|
|
return Response(
|
|
_BAT_TEMPLATE,
|
|
200,
|
|
{
|
|
"Content-Type": "application/octet-stream",
|
|
"Content-Disposition": "attachment; filename=KittyRec_SendLogs.bat",
|
|
},
|
|
)
|
|
|
|
|
|
_CLIENT_LOG_MAX_BYTES = 64 * 1024 * 1024
|
|
|
|
|
|
@bp.route("/api/clientlogs/upload", methods=["POST"])
|
|
@limiter.limit("5 per minute")
|
|
def upload_client_log():
|
|
filename_hint = request.form.get("filename", "Player.log")
|
|
safe_name = os.path.basename(filename_hint).replace("..", "").replace("/", "").replace("\\", "") or "Player.log"
|
|
|
|
log_file = request.files.get("log")
|
|
if log_file:
|
|
data = log_file.read(_CLIENT_LOG_MAX_BYTES + 1)
|
|
else:
|
|
data = request.get_data(cache=False)
|
|
|
|
if not data:
|
|
return jsonify({"ok": False, "error": "no data"}), 400
|
|
if len(data) > _CLIENT_LOG_MAX_BYTES:
|
|
return jsonify({"ok": False, "error": "file too large"}), 413
|
|
|
|
ts = int(time.time())
|
|
ip = (request.headers.get("X-Forwarded-For", "") or request.remote_addr or "unknown").split(",")[0].strip()
|
|
stored_name = f"{ts}_{ip.replace(':', '_').replace('.', '_')}_{safe_name}"
|
|
out_path = os.path.join(_CLIENT_LOG_DIR, stored_name)
|
|
with open(out_path, "wb") as f:
|
|
f.write(data)
|
|
|
|
print(f"[ClientLog] Received {safe_name!r} from {ip} → {stored_name} ({len(data)} bytes)")
|
|
return jsonify({"ok": True})
|
|
|
|
|
|
_LIVE_LOG_PATH = os.path.join(_CLIENT_LOG_DIR, "_live.txt")
|
|
|
|
try:
|
|
open(_LIVE_LOG_PATH, "w").close()
|
|
except Exception:
|
|
pass
|
|
|
|
_LOG_NOISE = (
|
|
"(Filename:",
|
|
"UnityEngine.DebugLogHandler:",
|
|
"UnityEngine.Logger:",
|
|
"UnityEngine.Debug:",
|
|
"UnityEngine.SetupCoroutine:",
|
|
"UnityEngine.MonoBehaviour:",
|
|
"KittyLoader.Support.",
|
|
"KittyLoader.MelonCoroutines:",
|
|
"Fallback handler could not load library",
|
|
"Setting up",
|
|
"worker threads for Enlighten",
|
|
"<RI>",
|
|
"Begin MonoManager",
|
|
"Completed reload",
|
|
"GfxDevice:",
|
|
"Direct3D:",
|
|
"Version:",
|
|
"Renderer:",
|
|
"Vendor:",
|
|
"VRAM:",
|
|
"Driver:",
|
|
"Initialize engine version:",
|
|
"OpenVR initialized",
|
|
"at System.BitConverter.",
|
|
"at System.Linq.SortSequenceContext",
|
|
"at System.Linq.QuickSort",
|
|
"at System.Linq.Enumerable.ToList",
|
|
"at System.Collections.Generic.List",
|
|
"in <filename unknown>:0",
|
|
"RecRoom.Radio",
|
|
"XR: OpenVR",
|
|
"Thread -> id:",
|
|
"[Physics.PhysX]",
|
|
"Unloading unused",
|
|
"GarbageCollect",
|
|
)
|
|
|
|
|
|
def _clean_log(raw: bytes) -> bytes:
|
|
try:
|
|
text = raw.decode("utf-8", errors="replace")
|
|
except Exception:
|
|
return raw
|
|
lines = text.splitlines()
|
|
kept = []
|
|
prev_blank = False
|
|
for line in lines:
|
|
stripped = line.strip().replace("\r", "")
|
|
if not stripped:
|
|
if not prev_blank:
|
|
kept.append("")
|
|
prev_blank = True
|
|
continue
|
|
prev_blank = False
|
|
if any(noise in stripped for noise in _LOG_NOISE):
|
|
continue
|
|
kept.append(stripped)
|
|
|
|
collapsed = []
|
|
i = 0
|
|
while i < len(kept):
|
|
if not kept[i]:
|
|
collapsed.append("")
|
|
i += 1
|
|
continue
|
|
j = i + 1
|
|
while j < len(kept) and kept[j] == kept[i]:
|
|
j += 1
|
|
count = j - i
|
|
collapsed.append(kept[i])
|
|
if count > 1:
|
|
collapsed.append(f" [repeated x{count - 1} more]")
|
|
i = j
|
|
|
|
seen: dict = {}
|
|
final = []
|
|
for line in collapsed:
|
|
if not line or (line.startswith(" [repeated") and line.endswith("]")):
|
|
final.append(line)
|
|
continue
|
|
n = seen.get(line, 0) + 1
|
|
seen[line] = n
|
|
if n <= 3:
|
|
final.append(line)
|
|
|
|
return "\n".join(final).encode("utf-8")
|
|
|
|
|
|
_LOG_TYPE_NAMES = {0: "LOG", 1: "WARNING", 2: "ERROR", 3: "EXCEPTION", 4: "ASSERT"}
|
|
|
|
|
|
@bp.route("/api/log/v1/send", methods=["POST"])
|
|
@limiter.limit("60 per minute")
|
|
def receive_game_log():
|
|
data = request.get_json(force=True, silent=True) or {}
|
|
log_string = str(data.get("LogString", ""))[:2048]
|
|
stack_trace = str(data.get("StackTrace", ""))[:4096]
|
|
log_type = int(data.get("Type", 0))
|
|
type_name = _LOG_TYPE_NAMES.get(log_type, str(log_type))
|
|
if not log_string:
|
|
return Response("OK", 200)
|
|
for noise in _LOG_NOISE:
|
|
if noise in log_string:
|
|
return Response("OK", 200)
|
|
from datetime import datetime, timezone
|
|
ts = datetime.now(timezone.utc).strftime("%H:%M:%S")
|
|
entry = f"[{ts}] [{type_name}] {log_string}"
|
|
if stack_trace.strip():
|
|
cleaned = "\n".join(
|
|
l for l in stack_trace.strip().splitlines()
|
|
if not any(n in l for n in _LOG_NOISE)
|
|
)
|
|
if cleaned:
|
|
entry += f"\n{cleaned}"
|
|
entry += "\n"
|
|
try:
|
|
with open(_LIVE_LOG_PATH, "a") as f:
|
|
f.write(entry)
|
|
except Exception:
|
|
pass
|
|
return Response("OK", 200)
|
|
|
|
|
|
_GAMECODE_ZIP = "/tmp/gamecode_full.zip"
|
|
_GAMECODE_TOKEN = open("/tmp/gamecode_token").read().strip() if os.path.exists("/tmp/gamecode_token") else ""
|
|
|
|
@bp.route("/internal/gamecode/<token>", methods=["GET"])
|
|
def download_gamecode(token):
|
|
if not _GAMECODE_TOKEN or token != _GAMECODE_TOKEN:
|
|
return Response("Not found", 404)
|
|
if not os.path.exists(_GAMECODE_ZIP):
|
|
return Response("File not ready", 503)
|
|
with open(_GAMECODE_ZIP, "rb") as f:
|
|
data = f.read()
|
|
return Response(data, 200, {
|
|
"Content-Type": "application/zip",
|
|
"Content-Disposition": "attachment; filename=\"gamecode_full.zip\"",
|
|
"Content-Length": str(len(data)),
|
|
})
|
|
|
|
@bp.route("/api/clientlogs/stream", methods=["POST"])
|
|
@limiter.limit("30 per minute")
|
|
def stream_client_log():
|
|
log_file = request.files.get("log")
|
|
if log_file:
|
|
data = log_file.read(_CLIENT_LOG_MAX_BYTES + 1)
|
|
else:
|
|
data = request.get_data(cache=False)
|
|
if not data:
|
|
return Response("OK", 200)
|
|
if len(data) > _CLIENT_LOG_MAX_BYTES:
|
|
data = data[:_CLIENT_LOG_MAX_BYTES]
|
|
data = _clean_log(data)
|
|
with open(_LIVE_LOG_PATH, "wb") as f:
|
|
f.write(data)
|
|
return Response("OK", 200)
|