Upload files to "routes"
This commit is contained in:
298
routes/images.py
Normal file
298
routes/images.py
Normal file
@@ -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("/<int:player_id>", methods=["GET"])
|
||||
@bp.route("/alt/<int:player_id>", 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("/<name>", methods=["GET"])
|
||||
@bp.route("/alt/<name>", 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/<int:player_id>", 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)
|
||||
Reference in New Issue
Block a user