From 40f106fd512ff722b7997acc17ed4454bc924e92 Mon Sep 17 00:00:00 2001 From: admin Date: Fri, 24 Jul 2026 15:35:10 +0000 Subject: [PATCH] Upload files to "routes" --- routes/KittyLoader.py | 79 +++++++ routes/downloads.py | 500 ++++++++++++++++++++++++++++++++++++++++++ routes/health.py | 48 ++++ routes/images.py | 298 +++++++++++++++++++++++++ routes/inventory.py | 41 ++++ 5 files changed, 966 insertions(+) create mode 100644 routes/KittyLoader.py create mode 100644 routes/downloads.py create mode 100644 routes/health.py create mode 100644 routes/images.py create mode 100644 routes/inventory.py diff --git a/routes/KittyLoader.py b/routes/KittyLoader.py new file mode 100644 index 0000000..04f9508 --- /dev/null +++ b/routes/KittyLoader.py @@ -0,0 +1,79 @@ + +import json +import os +import random + +from functools import wraps + + +from flask import Blueprint, request, jsonify, Response, abort, send_file, send_from_directory +from core.config import server as _server_cfg +from core.state import db + +bp = Blueprint("KittyLoader", __name__) + +@bp.before_request +def _check_ua(): + if request.path == "/api/kittyloader/v1/KittyRec/getfile": + return + ua = request.headers.get("User-Agent", "") + if not ua.startswith("KittyLoader/"): + return abort(403) + +Branchs = { + "bff0c094-2d59-4f81-93dd-fc6f177ca584": "Prod", + "fb4ce906-59c1-4ffd-af5e-6696dfad1be2": "Dev", + "f94fa96b-7438-4323-825f-ff4dc4055db1": "BVT" +} + +proxyUrl = _server_cfg.get("kittyloader_proxy", "http://localhost:5242") + +def getBranch(f): + @wraps(f) + def decorated(*args, **kwargs): + Branch = request.headers.get("Branch") + if Branch is None: + return abort(403) + if Branch not in Branchs: + return abort(403) + return f(Branch, *args, **kwargs) + return decorated + +@bp.route("/api/kittyloader/v1/start", methods=["GET"]) +@getBranch +def start(Branch): + db.save_amplitude_event( + 0, "kittyloader_start", 0, + {"branch": Branchs.get(Branch, Branch), "ua": request.headers.get("User-Agent", "")}, + {}, "", "", + ) + return jsonify({"exit": False}) + +@bp.route("/api/kittyloader/v1/exit", methods=["GET"]) +@getBranch +def exit(Branch): + return Response("", 200) + +@bp.route("/api/kittyloader/v1/KittyRec/getfile", methods=["GET"]) +def kittyrec_getfile(): + FileName = request.args.get("filename") + if FileName is None: + return abort(400) + try: + + return send_from_directory(directory="kittyrec_dlls", path=FileName) + except FileNotFoundError: + return abort(404) + +@bp.route("/api/kittyloader/v1/KittyRec/get", methods=["GET"]) +@getBranch +def kittyrec(Branch): + with open(os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "KittyRecDlls.json")) as f: + jsonData: dict = json.load(f) + if jsonData.get(Branch) is None: + return abort(404) + data = jsonData.get(Branch) + return jsonify({ + "FileUrl": f"{proxyUrl}/api/kittyloader/v1/KittyRec/getfile?filename={data['file']}", + "SHA512": data["hash"] + }) diff --git a/routes/downloads.py b/routes/downloads.py new file mode 100644 index 0000000..158c2a5 --- /dev/null +++ b/routes/downloads.py @@ -0,0 +1,500 @@ +import hashlib +import json +import os +import secrets +import shutil +import time +import uuid +import zipfile +from datetime import datetime, timezone + +from flask import Blueprint, request, jsonify, render_template, Response, abort + +from routes.portal import require_admin_api, require_scope, SCOPE_ADMIN + +bp = Blueprint("downloads", __name__) + +_DL_DIR = os.path.join(os.path.dirname(__file__), "..", "data", "downloads") +_FILES_DIR = os.path.join(_DL_DIR, "files") +_TMP_DIR = os.path.join(_DL_DIR, "tmp") +_INDEX = os.path.join(_DL_DIR, "index.json") +_LAUNCHER_EXE = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "data", "launcher", "KittyRecLauncher.exe")) +_HTTPPROXY_EXE = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "HttpProxyReplacement", "HttpProxyReplacement.exe")) + +_CHUNK_MAX = 10 * 1024 * 1024 +_COMPILED_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "gamecode", "compiled")) +_COMPILED_PREV_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "gamecode", "compiled_prev")) + + +def _extract_to_compiled(zip_path, build_name): + try: + if not zipfile.is_zipfile(zip_path): + print(f"[Downloads] extract: {zip_path} is not a valid zip, skipping extract") + return False + if os.path.isdir(_COMPILED_PREV_DIR): + shutil.rmtree(_COMPILED_PREV_DIR, ignore_errors=True) + if os.path.isdir(_COMPILED_DIR): + os.rename(_COMPILED_DIR, _COMPILED_PREV_DIR) + os.makedirs(_COMPILED_DIR, exist_ok=True) + with zipfile.ZipFile(zip_path, "r") as zf: + zf.extractall(_COMPILED_DIR) + print(f"[Downloads] extracted '{build_name}' → {_COMPILED_DIR}") + return True + except Exception as e: + print(f"[Downloads] extract failed for '{build_name}': {e}") + if os.path.isdir(_COMPILED_PREV_DIR) and not os.path.isdir(_COMPILED_DIR): + os.rename(_COMPILED_PREV_DIR, _COMPILED_DIR) + return False + + +def _ensure_dirs(): + os.makedirs(_FILES_DIR, exist_ok=True) + os.makedirs(_TMP_DIR, exist_ok=True) + + +def _cleanup_stale_sessions(): + if not os.path.exists(_TMP_DIR): + return + cutoff = time.time() - 86400 + for name in os.listdir(_TMP_DIR): + path = os.path.join(_TMP_DIR, name) + try: + if os.path.isdir(path) and os.path.getmtime(path) < cutoff: + shutil.rmtree(path, ignore_errors=True) + except Exception: + pass + + +def _load_index(): + if not os.path.exists(_INDEX): + return [] + with open(_INDEX) as f: + return json.load(f) + + +def _save_index(builds): + _ensure_dirs() + with open(_INDEX, "w") as f: + json.dump(builds, f, indent=2) + + +def _find_build(builds, h1, h2, h3): + for b in builds: + if b["h1"] == h1 and b["h2"] == h2 and b["h3"] == h3: + return b + return None + + +def _normalize_filename(name: str) -> str: + import re + s = name.encode("ascii", "replace").decode("ascii") + s = re.sub(r'[^\w.\-]', '_', s) + s = re.sub(r'_+', '_', s).strip('_') + return s or "build" + + +def _content_disposition(build_name: str) -> str: + from urllib.parse import quote as _quote + safe = _normalize_filename(build_name) + ".zip" + encoded = _quote((build_name + ".zip").encode("utf-8"), safe="") + return f"attachment; filename=\"{safe}\"; filename*=UTF-8''{encoded}" + + +def _stream_file(path, filename): + size = os.path.getsize(path) + range_header = request.headers.get("Range") + + if range_header: + try: + byte_range = range_header.replace("bytes=", "").split("-") + start = int(byte_range[0]) + end = int(byte_range[1]) if byte_range[1] else size - 1 + except Exception: + start, end = 0, size - 1 + end = min(end, size - 1) + length = end - start + 1 + + def generate(): + with open(path, "rb") as f: + f.seek(start) + remaining = length + while remaining > 0: + chunk = f.read(min(65536, remaining)) + if not chunk: + break + remaining -= len(chunk) + yield chunk + + headers = { + "Content-Range": f"bytes {start}-{end}/{size}", + "Accept-Ranges": "bytes", + "Content-Length": str(length), + "Content-Disposition": _content_disposition(filename), + "Content-Type": "application/zip", + "Cache-Control": "no-store", + } + return Response(generate(), status=206, headers=headers) + + def generate_full(): + with open(path, "rb") as f: + while True: + chunk = f.read(65536) + if not chunk: + break + yield chunk + + headers = { + "Accept-Ranges": "bytes", + "Content-Length": str(size), + "Content-Disposition": _content_disposition(filename), + "Content-Type": "application/zip", + "Cache-Control": "no-store", + } + return Response(generate_full(), status=200, headers=headers) + + +@bp.route("/api/launcher/v1/manifest") +def launcher_manifest(): + from urllib.parse import quote as _quote + builds = _load_index() + meta = _load_meta_current() + current_id = meta.get("current_build_id") if meta else None + if not current_id: + return jsonify({"error": "No build available"}), 404 + build = next((b for b in builds if b["id"] == current_id and b.get("enabled")), None) + if not build: + return jsonify({"error": "No build available"}), 404 + dl_url = f"/download/{_quote(build['date'])}/{_quote(build['build_name'])}/{build['h1']}/{build['h2']}/{build['h3']}/get" + return jsonify({ + "build_id": build["id"], + "build_name": build["build_name"], + "sha256": build["sha256"], + "size": build["size"], + "download_url": dl_url, + "date": build["date"], + "download_count": build.get("download_count", 0), + }) + + +@bp.route("/download/launcher") +def download_launcher(): + if not os.path.exists(_LAUNCHER_EXE): + abort(404) + size = os.path.getsize(_LAUNCHER_EXE) + def generate(): + with open(_LAUNCHER_EXE, "rb") as f: + while True: + chunk = f.read(65536) + if not chunk: + break + yield chunk + return Response(generate(), status=200, headers={ + "Content-Type": "application/octet-stream", + "Content-Disposition": "attachment; filename=\"KittyRecLauncher.exe\"", + "Content-Length": str(size), + "Cache-Control": "no-store", + }) + + +@bp.route("/download/httpproxy") +def download_httpproxy(): + if not os.path.exists(_HTTPPROXY_EXE): + abort(404) + size = os.path.getsize(_HTTPPROXY_EXE) + def generate(): + with open(_HTTPPROXY_EXE, "rb") as f: + while True: + chunk = f.read(65536) + if not chunk: + break + yield chunk + return Response(generate(), status=200, headers={ + "Content-Type": "application/octet-stream", + "Content-Disposition": "attachment; filename=\"HttpProxyReplacement.exe\"", + "Content-Length": str(size), + "Cache-Control": "no-store", + }) + + +@bp.route("/download/current") +def download_current(): + from urllib.parse import quote as _quote + builds = _load_index() + meta = _load_meta_current() + current_id = meta.get("current_build_id") if meta else None + if not current_id: + return render_template("download_unavailable.html"), 404 + build = next((b for b in builds if b["id"] == current_id and b.get("enabled")), None) + if not build: + return render_template("download_unavailable.html"), 404 + dl_url = f"/download/{_quote(build['date'])}/{_quote(build['build_name'])}/{build['h1']}/{build['h2']}/{build['h3']}/get" + return render_template("download_page.html", build=build, dl_url=dl_url) + + +def _load_meta_current(): + path = os.path.join(_DL_DIR, "current.json") + if not os.path.exists(path): + return {} + with open(path) as f: + return json.load(f) + + +def _save_meta_current(data): + _ensure_dirs() + with open(os.path.join(_DL_DIR, "current.json"), "w") as f: + json.dump(data, f) + + +@bp.route("/admin/api/downloads/set_current/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def set_current_build(build_id, account, scopes): + builds = _load_index() + build = next((b for b in builds if b["id"] == build_id), None) + if not build: + return jsonify({"error": "Not found"}), 404 + _save_meta_current({"current_build_id": build_id}) + print(f"[Downloads] {account.get('username')} set current build to '{build['build_name']}'") + return jsonify({"ok": True}) + + +@bp.route("/download///

/

/

") +def download_page(date, build_name, h1, h2, h3): + from urllib.parse import quote as _quote + builds = _load_index() + build = _find_build(builds, h1, h2, h3) + if not build or not build.get("enabled"): + return render_template("download_unavailable.html"), 404 + dl_url = f"/download/{_quote(build['date'])}/{_quote(build['build_name'])}/{h1}/{h2}/{h3}/get" + return render_template("download_page.html", build=build, dl_url=dl_url) + + +@bp.route("/download///

/

/

/get") +def download_file(date, build_name, h1, h2, h3): + builds = _load_index() + build = _find_build(builds, h1, h2, h3) + if not build or not build.get("enabled"): + abort(404) + path = os.path.join(_FILES_DIR, build["id"] + ".zip") + if not os.path.exists(path): + abort(404) + for b in builds: + if b["id"] == build["id"]: + b["download_count"] = b.get("download_count", 0) + 1 + break + _save_index(builds) + print(f"[Downloads] Serving '{build['build_name']}' to {request.remote_addr}") + return _stream_file(path, build["build_name"]) + + +@bp.route("/admin/api/downloads/upload/start", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def upload_start(account, scopes): + _ensure_dirs() + _cleanup_stale_sessions() + data = request.get_json(force=True, silent=True) or {} + build_name = str(data.get("build_name", "")).strip()[:128] + if not build_name: + return jsonify({"error": "build_name required"}), 400 + session_id = str(uuid.uuid4()) + session_dir = os.path.join(_TMP_DIR, session_id) + os.makedirs(session_dir) + with open(os.path.join(session_dir, "meta.json"), "w") as f: + json.dump({"build_name": build_name, "uploaded_by": account.get("username", "admin"), "started_at": time.time()}, f) + return jsonify({"ok": True, "session_id": session_id}) + + +@bp.route("/admin/api/downloads/upload/chunk", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def upload_chunk(account, scopes): + session_id = request.form.get("session_id", "") + chunk_index = request.form.get("chunk_index", "") + if not session_id or chunk_index == "": + return jsonify({"error": "session_id and chunk_index required"}), 400 + session_dir = os.path.join(_TMP_DIR, session_id) + if not os.path.isdir(session_dir): + return jsonify({"error": "Unknown session"}), 404 + chunk_file = request.files.get("chunk") + if not chunk_file: + return jsonify({"error": "No chunk data"}), 400 + chunk_path = os.path.join(session_dir, f"chunk_{int(chunk_index):08d}") + chunk_file.save(chunk_path) + return jsonify({"ok": True, "received": int(chunk_index)}) + + +@bp.route("/admin/api/downloads/upload/finalize", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def upload_finalize(account, scopes): + data = request.get_json(force=True, silent=True) or {} + session_id = data.get("session_id", "") + total_chunks = int(data.get("total_chunks", 0)) + if not session_id or not total_chunks: + return jsonify({"error": "session_id and total_chunks required"}), 400 + session_dir = os.path.join(_TMP_DIR, session_id) + if not os.path.isdir(session_dir): + return jsonify({"error": "Unknown session"}), 404 + meta_path = os.path.join(session_dir, "meta.json") + with open(meta_path) as f: + meta = json.load(f) + build_id = str(uuid.uuid4()) + dest = os.path.join(_FILES_DIR, build_id + ".zip") + sha = hashlib.sha256() + size = 0 + with open(dest, "wb") as out: + for i in range(total_chunks): + chunk_path = os.path.join(session_dir, f"chunk_{i:08d}") + if not os.path.exists(chunk_path): + os.remove(dest) + shutil.rmtree(session_dir, ignore_errors=True) + return jsonify({"error": f"Missing chunk {i}"}), 400 + with open(chunk_path, "rb") as cf: + while True: + buf = cf.read(65536) + if not buf: + break + out.write(buf) + sha.update(buf) + size += len(buf) + shutil.rmtree(session_dir, ignore_errors=True) + if size == 0: + os.remove(dest) + return jsonify({"error": "Empty file after assembly"}), 400 + h1 = secrets.token_hex(8) + h2 = secrets.token_hex(8) + h3 = secrets.token_hex(8) + date_str = datetime.now(timezone.utc).strftime("%Y-%m-%d") + build = { + "id": build_id, + "date": date_str, + "build_name": meta["build_name"], + "h1": h1, "h2": h2, "h3": h3, + "size": size, + "sha256": sha.hexdigest(), + "enabled": True, + "uploaded_at": datetime.now(timezone.utc).isoformat(), + "uploaded_by": meta.get("uploaded_by", "admin"), + "download_count": 0, + } + builds = _load_index() + builds.append(build) + _save_index(builds) + url = f"/download/{date_str}/{meta['build_name']}/{h1}/{h2}/{h3}" + print(f"[Downloads] {meta.get('uploaded_by')} uploaded '{meta['build_name']}' ({size} bytes, {total_chunks} chunks) → {url}") + _extract_to_compiled(dest, meta["build_name"]) + return jsonify({"ok": True, "url": url, "build": build}) + + +@bp.route("/admin/api/downloads/upload", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def upload_build(account, scopes): + _ensure_dirs() + + build_name = request.form.get("build_name", "").strip()[:128] + if not build_name: + return jsonify({"error": "build_name required"}), 400 + + f = request.files.get("file") + if not f or not f.filename: + return jsonify({"error": "No file provided"}), 400 + if not f.filename.lower().endswith(".zip"): + return jsonify({"error": "Must be a .zip file"}), 400 + + build_id = str(uuid.uuid4()) + dest = os.path.join(_FILES_DIR, build_id + ".zip") + + f.save(dest) + + size = os.path.getsize(dest) + if size == 0: + os.remove(dest) + return jsonify({"error": "Empty file"}), 400 + + sha = hashlib.sha256() + with open(dest, "rb") as fh: + while True: + chunk = fh.read(65536) + if not chunk: + break + sha.update(chunk) + + h1 = secrets.token_hex(8) + h2 = secrets.token_hex(8) + h3 = secrets.token_hex(8) + date_str = datetime.now(timezone.utc).strftime("%Y-%m-%d") + + build = { + "id": build_id, + "date": date_str, + "build_name": build_name, + "h1": h1, + "h2": h2, + "h3": h3, + "size": size, + "sha256": sha.hexdigest(), + "enabled": True, + "uploaded_at": datetime.now(timezone.utc).isoformat(), + "uploaded_by": account.get("username", "admin"), + "download_count": 0, + } + + builds = _load_index() + builds.append(build) + _save_index(builds) + + url = f"/download/{date_str}/{build_name}/{h1}/{h2}/{h3}" + print(f"[Downloads] {account.get('username')} uploaded '{build_name}' ({size} bytes) → {url}") + _extract_to_compiled(dest, build_name) + return jsonify({"ok": True, "url": url, "build": build}) + + +@bp.route("/admin/api/downloads/list", methods=["GET"]) +@require_admin_api +def list_builds(account, scopes): + builds = _load_index() + current_id = _load_meta_current().get("current_build_id") + return jsonify({"builds": builds, "current_build_id": current_id}) + + +@bp.route("/admin/api/downloads/toggle/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def toggle_build(build_id, account, scopes): + builds = _load_index() + for b in builds: + if b["id"] == build_id: + b["enabled"] = not b.get("enabled", True) + _save_index(builds) + return jsonify({"ok": True, "enabled": b["enabled"]}) + return jsonify({"error": "Not found"}), 404 + + +@bp.route("/admin/api/downloads/rename/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def rename_build(build_id, account, scopes): + data = request.get_json(force=True, silent=True) or {} + new_name = str(data.get("build_name", "")).strip()[:128] + if not new_name: + return jsonify({"error": "build_name required"}), 400 + builds = _load_index() + for b in builds: + if b["id"] == build_id: + old_name = b["build_name"] + b["build_name"] = new_name + _save_index(builds) + print(f"[Downloads] {account.get('username')} renamed '{old_name}' → '{new_name}'") + return jsonify({"ok": True, "build_name": new_name}) + return jsonify({"error": "Not found"}), 404 + + +@bp.route("/admin/api/downloads/delete/", methods=["POST"]) +@require_scope(SCOPE_ADMIN) +def delete_build(build_id, account, scopes): + builds = _load_index() + build = next((b for b in builds if b["id"] == build_id), None) + if not build: + return jsonify({"error": "Not found"}), 404 + path = os.path.join(_FILES_DIR, build_id + ".zip") + if os.path.exists(path): + os.remove(path) + builds = [b for b in builds if b["id"] != build_id] + _save_index(builds) + print(f"[Downloads] {account.get('username')} deleted build '{build.get('build_name')}'") + return jsonify({"ok": True}) diff --git a/routes/health.py b/routes/health.py new file mode 100644 index 0000000..42cdee5 --- /dev/null +++ b/routes/health.py @@ -0,0 +1,48 @@ +import time + +from flask import Blueprint, jsonify + +from core.state import db, session_mgr, ws_registry +import core.state as _state +from core.config import server as _server_cfg + +bp = Blueprint("health", __name__) + +SERVER_BUILD = _server_cfg.get("build", "KittyRec") +_start_time = time.time() + + +def _check_db(): + t0 = time.monotonic() + try: + db.get_profile(23) + latency_ms = round((time.monotonic() - t0) * 1000, 2) + return "ok", latency_ms + except Exception as e: + latency_ms = round((time.monotonic() - t0) * 1000, 2) + return f"error: {e}", latency_ms + + +@bp.route("/health") +def health(): + db_status, db_latency_ms = _check_db() + online = len(ws_registry.connected_ids()) + sessions = len(session_mgr.all_public_sessions()) + + ok = db_status == "ok" + status = "ok" if ok else "degraded" + + return jsonify({ + "status": status, + "build": SERVER_BUILD, + "uptime_seconds": int(time.time() - _start_time), + "database": { + "status": db_status, + "latency_ms": db_latency_ms, + }, + "players": { + "online": online, + "active_sessions": sessions, + }, + "maintenance": _state.maintenance_mode, + }), 200 if ok else 503 diff --git a/routes/images.py b/routes/images.py new file mode 100644 index 0000000..22eefaa --- /dev/null +++ b/routes/images.py @@ -0,0 +1,298 @@ + +import io +import os +import time +from email.utils import formatdate + +from flask import Blueprint, request, jsonify, Response, send_file +from PIL import Image + +from core.auth import check_auth, get_current_profile_id +from core.limiter import limiter +from core.ws_helpers import push_profile_update +from core.state import db, session_mgr + +_IMG_BASE = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "uploads", "images")) +_DIR_PROFILE = os.path.join(_IMG_BASE, "profile") +_DIR_LQ = os.path.join(_IMG_BASE, "lq") +_DIR_HD = os.path.join(_IMG_BASE, "hd") + +for _d in (_DIR_PROFILE, _DIR_LQ, _DIR_HD): + os.makedirs(_d, exist_ok=True) + +def _save_pfp(filename: str, data: bytes) -> None: + try: + with open(os.path.join(_DIR_PROFILE, filename), "wb") as fh: + fh.write(data) + except Exception: + pass + +def _save_named(filename: str, data: bytes) -> None: + try: + img = Image.open(io.BytesIO(data)) + dest = _DIR_HD if max(img.width, img.height) > 720 else _DIR_LQ + with open(os.path.join(dest, filename), "wb") as fh: + fh.write(data) + except Exception: + pass + +bp = Blueprint("images", __name__) + +DEFAULT_1X1_PNG = ( + b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01" + b"\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00" + b"\x00\x00\x0cIDATx\x9cc\xf8\x0f\x00\x00\x01\x01\x00" + b"\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82" +) + +def _serve_image(player_id): + image_data = db.get_profile_image(player_id) + if image_data is None: + return Response(DEFAULT_1X1_PNG, 200, {"Content-Type": "image/png"}) + last_modified = formatdate(timeval=time.time(), usegmt=True) + return Response(image_data, 200, { + "Content-Type": "image/jpeg", + "Last-Modified": last_modified, + "Cache-Control": "no-cache, no-store, must-revalidate", + "Pragma": "no-cache", + }) + +def _parse_pid(name): + try: + return int(str(name).split("_")[0].split(".")[0]) + except (ValueError, TypeError): + return None + +@bp.route("/", methods=["GET"]) +@bp.route("/alt/", methods=["GET"]) +def serve_profile_image_root(player_id): + return _serve_image(player_id) + +_CDN_MIME = { + ".assetbundle": "application/octet-stream", + ".unity3d": "application/octet-stream", + ".bytes": "application/octet-stream", + ".json": "application/json", + ".png": "image/png", + ".gif": "image/gif", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", +} + +@bp.route("/", methods=["GET"]) +@bp.route("/alt/", methods=["GET"]) +def serve_profile_image_named(name): + if name.startswith("."): + return Response("Not Found", 404) + saved = db.get_named_image(name) + if saved is None and "." in name: + stem = name.rsplit(".", 1)[0] + if stem: + saved = db.get_named_image(stem) + if saved is not None: + ext = ("." + name.rsplit(".", 1)[1].lower()) if "." in name else "" + if name.startswith("cdn_") and ext and ext != ".jpg" and ext != ".jpeg": + mime = _CDN_MIME.get(ext, "application/octet-stream") + return send_file( + io.BytesIO(saved), + mimetype=mime, + as_attachment=False, + download_name=name, + ) + last_modified = formatdate(timeval=time.time(), usegmt=True) + return Response(saved, 200, { + "Content-Type": "image/jpeg", + "Last-Modified": last_modified, + "Cache-Control": "no-cache, no-store, must-revalidate", + "Pragma": "no-cache", + }) + player_id = _parse_pid(name) + if player_id is None: + return Response(DEFAULT_1X1_PNG, 200, {"Content-Type": "image/png"}) + return _serve_image(player_id) + +@bp.route("/api/images/v1/named", methods=["GET"]) +@bp.route("/api/images/v2/named", methods=["GET"]) +def get_named_images(): + return jsonify([]) + +_MAX_IMAGE_BYTES = 2 * 1024 * 1024 +_IMAGE_MAGIC = ( + b"\x89PNG", + b"\xff\xd8\xff", + b"GIF87a", + b"GIF89a", + b"RIFF", + b"\x00\x00\x00\x0cjP ", +) + +def _is_valid_image(data: bytes) -> bool: + return any(data[:len(m)] == m for m in _IMAGE_MAGIC) + +def _do_upload(pid): + profile = db.get_profile(pid) + if not profile: + print(f"[Images] Rejected upload from pid={pid}: no profile") + return False + f = request.files.get("image") or request.files.get("altimage") + image_data = f.read(_MAX_IMAGE_BYTES + 1) if f else request.get_data(cache=False, as_text=False) + if not image_data or len(image_data) > _MAX_IMAGE_BYTES: + return False + if not _is_valid_image(image_data): + print(f"[Images] Rejected upload from pid={pid}: invalid image format") + return False + old_image = db.get_profile_image(pid) + old_name = profile.get("ProfileImageName", "") + if old_image and old_name: + db.add_pfp_to_history(pid, old_name, old_image) + versioned_name = f"{pid}_{int(time.time())}" + _save_pfp(f"{versioned_name}.jpg", image_data) + db.update_profile(pid, {"profile_image_name": versioned_name}) + push_profile_update(pid) + print(f"[Images] Profile image uploaded for pid={pid} ({len(image_data)} bytes)") + return True + +@bp.route("/api/images/v2/profile", methods=["POST"]) +@limiter.limit("5 per minute") +@check_auth +def upload_profile_image_v2(): + pid = get_current_profile_id() + if pid: + _do_upload(pid) + return Response("OK", 200) + +@bp.route("/api/images/v3/profile", methods=["POST", "GET"]) +@limiter.limit("5 per minute") +@check_auth +def profile_image_v3(): + if request.method == "POST": + pid = get_current_profile_id() + if pid: + _do_upload(pid) + return Response("OK", 200) + return Response(DEFAULT_1X1_PNG, 200, {"Content-Type": "image/png"}) + +@bp.route("/api/images/v1/profile/", methods=["GET"]) +@check_auth +def get_profile_image(player_id): + image_data = db.get_profile_image(player_id) + if image_data is None: + return Response(DEFAULT_1X1_PNG, 200, {"Content-Type": "image/png"}) + + last_modified = formatdate(timeval=time.time(), usegmt=True) + return Response(image_data, 200, { + "Content-Type": "image/png", + "Last-Modified": last_modified, + "Cache-Control": "no-cache", + }) + +@bp.route("/api/images/v1/listsaved", methods=["GET"]) +@check_auth +def list_saved_images(): + pid = get_current_profile_id() + if not pid: + return jsonify([]) + names = db.get_saved_image_names(pid) + return jsonify([{"ImageName": n} for n in names]) + +@bp.route("/api/images/v1/modifyaccessibility", methods=["POST"]) +@check_auth +def modify_image_accessibility(): + return Response("OK", 200) + +@bp.route("/api/images/v2/deletetransient", methods=["POST"]) +@bp.route("/api/images/v3/deletetransient", methods=["POST"]) +@check_auth +def delete_transient_images(): + return Response("OK", 200) + +def _do_named_upload(pid: int): + f = request.files.get("image") or request.files.get("altimage") + image_data = f.read(_MAX_IMAGE_BYTES + 1) if f else request.get_data(cache=False, as_text=False) + if not image_data or len(image_data) > _MAX_IMAGE_BYTES: + return None, None, None + if not _is_valid_image(image_data): + return None, None, None + room_name = "" + try: + sid = int(request.args.get("gameSessionId", 0)) + if sid: + sess = session_mgr.get_session(sid) + if sess: + room_name = sess.name or "" + if not room_name: + sess = session_mgr.get_player_session(pid) + if sess: + room_name = sess.name or "" + except Exception: + pass + image_name = f"{pid}_{int(time.time())}.jpg" + try: + img = Image.open(io.BytesIO(image_data)) + max_dim = max(img.width, img.height) + except Exception: + max_dim = 0 + db.save_named_image(image_name, pid, image_data, room_name, max_dim=max_dim) + _save_named(image_name, image_data) + return image_name, len(image_data), room_name + +@bp.route("/api/images/v4/uploadtransient", methods=["POST"]) +@check_auth +def upload_transient_image(): + pid = get_current_profile_id() + if not pid: + return jsonify({"ImageName": ""}) + if not session_mgr.get_player_session(pid): + print(f"[Images] Rejected uploadtransient from pid={pid}: not in a session") + return jsonify({"ImageName": ""}) + image_name, size, _ = _do_named_upload(pid) + if not image_name: + print(f"[Images] Rejected uploadtransient from pid={pid}: invalid or empty image") + return jsonify({"ImageName": ""}) + print(f"[Images] Saved transient image '{image_name}' for pid={pid} ({size} bytes)") + return jsonify({"ImageName": image_name}) + +@bp.route("/api/images/v3/uploadsaved", methods=["POST"]) +@check_auth +def upload_saved_image(): + pid = get_current_profile_id() + if not pid: + return jsonify({"ImageName": ""}) + if not session_mgr.get_player_session(pid): + print(f"[Images] Rejected uploadsaved from pid={pid}: not in a session") + return jsonify({"ImageName": ""}) + image_name, size, room_name = _do_named_upload(pid) + if not image_name: + print(f"[Images] Rejected uploadsaved from pid={pid}: invalid or empty image") + return jsonify({"ImageName": ""}) + print(f"[Images] Saved image '{image_name}' for pid={pid} ({size} bytes) room={room_name!r}") + try: + from core.discord import send_public, _can_fire, _BASE_URL as _DU + if _can_fire(f"photo_{pid}", 300): + p = db.get_profile(pid) + uname = p["Username"] if p else str(pid) + room_str = f" in **{room_name}**" if room_name else "" + img_url = f"{_DU}/alt/{image_name}" + send_public( + title="Photo Taken!", + color=0x3498DB, + fields=[{"name": "Player", "value": uname, "inline": True}, + {"name": "Room", "value": room_name or "Unknown", "inline": True}], + description=f"**{uname}** snapped a photo{room_str}!", + thumbnail_url=img_url, + throttle_key="photo_global", + throttle_secs=8, + ) + except Exception: + pass + return jsonify({"ImageName": image_name}) + +@bp.route("/api/images/v1/sendlink", methods=["POST"]) +@check_auth +def send_image_link(): + return Response("OK", 200) + +@bp.route("/api/images/v1/deletesaved", methods=["POST"]) +@check_auth +def delete_saved_image(): + return Response("OK", 200) diff --git a/routes/inventory.py b/routes/inventory.py new file mode 100644 index 0000000..491a66e --- /dev/null +++ b/routes/inventory.py @@ -0,0 +1,41 @@ + +from flask import Blueprint, Response, jsonify + +from core.auth import check_auth + +bp = Blueprint("inventory", __name__) + +@bp.route("/api/equipment/v1/unlock", methods=["POST"]) +@check_auth +def unlock_equipment(): + return Response("OK", 200) + +@bp.route("/api/equipment/v1/gift", methods=["POST"]) +@check_auth +def gift_equipment(): + return Response("OK", 200) + +@bp.route("/api/consumables/v1/getUnlocked", methods=["GET"]) +@check_auth +def get_unlocked_consumables(): + return jsonify([]) + +@bp.route("/api/consumables/v1/consume", methods=["POST"]) +@check_auth +def consume_consumable(): + return Response("", 200) + +@bp.route("/api/consumables/v1/updateActive", methods=["POST"]) +@check_auth +def update_consumable_active(): + return Response("", 200) + +@bp.route("/api/consumables/v1/use", methods=["POST"]) +@check_auth +def use_consumable(): + return Response("OK", 200) + +@bp.route("/api/consumables/v1/gift", methods=["POST"]) +@check_auth +def gift_consumable(): + return Response("OK", 200)