mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 18:43:23 +01:00
cleanup
This commit is contained in:
@@ -20,11 +20,11 @@ from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.rom import RomFile, RomFileCategory
|
||||
from utils.router import APIRouter
|
||||
from utils.screenshots import (
|
||||
ALLOWED_SCREENSHOT_EXTENSIONS,
|
||||
is_allowed_screenshot_file,
|
||||
from utils.media_types import (
|
||||
ALLOWED_IMAGE_EXTENSIONS,
|
||||
is_inline_media_file,
|
||||
)
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -79,12 +79,12 @@ async def add_rom_screenshots(
|
||||
detail="Upload filename must be a plain file name, not a path",
|
||||
)
|
||||
|
||||
if not is_allowed_screenshot_file(safe_filename):
|
||||
if not is_inline_media_file(safe_filename):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=(
|
||||
f"Unsupported image file type. Allowed: "
|
||||
f"{', '.join(sorted(ALLOWED_SCREENSHOT_EXTENSIONS))}"
|
||||
f"{', '.join(sorted(ALLOWED_IMAGE_EXTENSIONS))}"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -17,11 +17,11 @@ from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from utils.filesystem import sanitize_filename
|
||||
from utils.router import APIRouter
|
||||
from utils.screenshots import (
|
||||
ALLOWED_SCREENSHOT_EXTENSIONS,
|
||||
is_allowed_screenshot_file,
|
||||
from utils.media_types import (
|
||||
ALLOWED_IMAGE_EXTENSIONS,
|
||||
is_inline_media_file,
|
||||
)
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/screenshots",
|
||||
@@ -69,12 +69,12 @@ async def add_screenshot(
|
||||
detail=f"Invalid screenshot filename: {str(exc)}",
|
||||
) from exc
|
||||
|
||||
if not is_allowed_screenshot_file(sanitized_screenshot_filename):
|
||||
if not is_inline_media_file(sanitized_screenshot_filename):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=(
|
||||
f"Unsupported image file type. Allowed: "
|
||||
f"{', '.join(sorted(ALLOWED_SCREENSHOT_EXTENSIONS))}"
|
||||
f"{', '.join(sorted(ALLOWED_IMAGE_EXTENSIONS))}"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import threading
|
||||
import zipfile
|
||||
from mimetypes import guess_type
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
import magic
|
||||
from fastapi import HTTPException, UploadFile, status
|
||||
@@ -13,18 +12,10 @@ from fastapi.responses import FileResponse
|
||||
from config import ASSETS_BASE_PATH
|
||||
from logger.logger import log
|
||||
from models.user import User
|
||||
from utils.media_types import IMAGE_EXT_BY_MIME_TYPE
|
||||
|
||||
from .base_handler import FSHandler
|
||||
|
||||
# Image MIME types we trust to (a) accept as avatar uploads and (b) serve
|
||||
# inline from the raw asset endpoint
|
||||
SAFE_IMAGE_MIME_TYPES: Final[dict[str, str]] = {
|
||||
"image/png": "png",
|
||||
"image/jpeg": "jpg",
|
||||
"image/webp": "webp",
|
||||
"image/gif": "gif",
|
||||
}
|
||||
|
||||
# libmagic loads its database on construction (~few MB read from disk), so we
|
||||
# share a single Magic instance across requests. The underlying magic_t handle
|
||||
# is not thread-safe, so guard from_buffer with a lock. Endpoints that call
|
||||
@@ -38,7 +29,7 @@ def validate_image_upload(upload: UploadFile, *, label: str = "Image") -> str:
|
||||
|
||||
Sniffs the leading bytes with libmagic and returns the trusted extension
|
||||
matching the detected MIME type. Raises HTTPException(400) if the file
|
||||
is not a recognized PNG/JPEG/WebP/GIF, or if MIME sniffing fails.
|
||||
is not a recognized image, or if MIME sniffing fails.
|
||||
Leaves the file cursor at 0.
|
||||
"""
|
||||
upload.file.seek(0)
|
||||
@@ -55,7 +46,7 @@ def validate_image_upload(upload: UploadFile, *, label: str = "Image") -> str:
|
||||
detail=f"Could not determine {label.lower()} file type",
|
||||
) from exc
|
||||
|
||||
safe_extension = SAFE_IMAGE_MIME_TYPES.get(detected_mime)
|
||||
safe_extension = IMAGE_EXT_BY_MIME_TYPE.get(detected_mime)
|
||||
if not safe_extension:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
@@ -76,7 +67,7 @@ def build_asset_file_response(
|
||||
avatar) can't execute as stored XSS."""
|
||||
download_name = filename or resolved_path.name
|
||||
guessed_type, _ = guess_type(download_name)
|
||||
if guessed_type in SAFE_IMAGE_MIME_TYPES:
|
||||
if guessed_type in IMAGE_EXT_BY_MIME_TYPE:
|
||||
return FileResponse(
|
||||
path=str(resolved_path),
|
||||
filename=download_name,
|
||||
|
||||
@@ -30,7 +30,17 @@ from .utils import (
|
||||
sanitize_filename,
|
||||
)
|
||||
|
||||
VIDEO_EXTS: tuple[str, ...] = (".mp4", ".webm", ".avi", ".mkv", ".mov", ".wmv")
|
||||
# Video container extensions recognized when probing for local LaunchBox media
|
||||
# and when validating a metadata video URL's suffix. A tuple because the probe
|
||||
# order is a preference order.
|
||||
RECOGNIZED_VIDEO_EXTENSIONS: tuple[str, ...] = (
|
||||
".mp4",
|
||||
".webm",
|
||||
".avi",
|
||||
".mkv",
|
||||
".mov",
|
||||
".wmv",
|
||||
)
|
||||
|
||||
|
||||
def local_media_req(
|
||||
@@ -356,7 +366,7 @@ def _get_video(req: MediaRequest) -> str | None:
|
||||
return None
|
||||
|
||||
for stem in ctx["stems"]:
|
||||
for ext in VIDEO_EXTS:
|
||||
for ext in RECOGNIZED_VIDEO_EXTENSIONS:
|
||||
candidate = ctx["base"] / f"{stem}{ext}"
|
||||
if candidate.is_file():
|
||||
return file_uri_for_local_path(candidate)
|
||||
@@ -553,7 +563,7 @@ def populate_rom_specific_paths(
|
||||
rom.platform_id, rom.id, MetadataMediaType.VIDEO
|
||||
)
|
||||
ext = Path(metadata["video_url"]).suffix.lower()
|
||||
if ext not in VIDEO_EXTS:
|
||||
if ext not in RECOGNIZED_VIDEO_EXTENSIONS:
|
||||
ext = ".mp4"
|
||||
metadata["video_path"] = f"{base}/video{ext}"
|
||||
return metadata
|
||||
|
||||
@@ -14,6 +14,7 @@ from config import (
|
||||
)
|
||||
from logger.logger import log
|
||||
from tasks.tasks import PeriodicTask, TaskType, update_job_meta
|
||||
from utils.media_types import ALLOWED_IMAGE_EXTENSIONS
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -30,9 +31,6 @@ class ConversionResult:
|
||||
class ImageConverter:
|
||||
"""Handles image format conversion to WebP."""
|
||||
|
||||
# Supported image formats
|
||||
SUPPORTED_EXTENSIONS = {".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".tif", ".gif"}
|
||||
|
||||
# Image mode conversion mapping
|
||||
MODE_CONVERSIONS = {
|
||||
"P": "RGBA", # Palette-based to RGBA (preserves transparency)
|
||||
@@ -147,7 +145,8 @@ class ConvertImagesToWebPTask(PeriodicTask):
|
||||
for p in self.resources_path.rglob("**/cover/*")
|
||||
if p.is_file()
|
||||
and not p.is_symlink()
|
||||
and p.suffix.lower() in ImageConverter.SUPPORTED_EXTENSIONS
|
||||
and p.suffix.lower() in ALLOWED_IMAGE_EXTENSIONS
|
||||
and p.suffix.lower() != ".webp"
|
||||
and not p.with_suffix(".webp").exists()
|
||||
]
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ from mutagen.oggopus import OggOpus
|
||||
from mutagen.oggvorbis import OggVorbis
|
||||
|
||||
from logger.logger import log
|
||||
from utils.media_types import IMAGE_EXT_BY_MIME_TYPE
|
||||
|
||||
ALLOWED_AUDIO_EXTENSIONS = frozenset(
|
||||
{".mp3", ".ogg", ".oga", ".opus", ".m4a", ".aac", ".wav", ".flac"}
|
||||
@@ -295,17 +296,8 @@ def _extract_picture_from_mp4(audio: MP4) -> tuple[bytes, str] | None:
|
||||
return bytes(cover), mime
|
||||
|
||||
|
||||
_COVER_EXT_BY_MIME = {
|
||||
"image/jpeg": "jpg",
|
||||
"image/jpg": "jpg",
|
||||
"image/png": "png",
|
||||
"image/webp": "webp",
|
||||
"image/gif": "gif",
|
||||
}
|
||||
|
||||
|
||||
def _ext_for_mime(mime: str) -> str:
|
||||
return _COVER_EXT_BY_MIME.get(mime.lower().split(";")[0].strip(), "bin")
|
||||
return IMAGE_EXT_BY_MIME_TYPE.get(mime.lower().split(";")[0].strip(), "bin")
|
||||
|
||||
|
||||
def soundtrack_cover_dir(platform_id: int, rom_id: int) -> str:
|
||||
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import mimetypes
|
||||
import os
|
||||
from typing import Final
|
||||
|
||||
# File extensions that are safe to serve inline (rendered/streamed by the
|
||||
# browser) from the ROM download endpoint. Images and videos never execute
|
||||
@@ -9,7 +10,7 @@ import os
|
||||
# avoids the content-sniffing/XSS risk that keeps arbitrary files served as
|
||||
# attachments.
|
||||
ALLOWED_IMAGE_EXTENSIONS = frozenset(
|
||||
{".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".avif"}
|
||||
{".png", ".jpg", ".jpeg", ".webp", ".gif", ".tiff", ".tif", ".bmp", ".avif"}
|
||||
)
|
||||
ALLOWED_VIDEO_EXTENSIONS = frozenset({".mp4", ".webm", ".ogv", ".mov", ".m4v"})
|
||||
|
||||
@@ -25,6 +26,17 @@ MEDIA_MIME_OVERRIDES = {
|
||||
".mov": "video/quicktime",
|
||||
}
|
||||
|
||||
# Image MIME types we trust to (a) accept as avatar uploads and (b) serve
|
||||
# inline from the raw asset endpoint. Maps each trusted MIME type to its
|
||||
# canonical file extension.
|
||||
IMAGE_EXT_BY_MIME_TYPE: Final[dict[str, str]] = {
|
||||
"image/png": "png",
|
||||
"image/jpeg": "jpg",
|
||||
"image/jpg": "jpg",
|
||||
"image/webp": "webp",
|
||||
"image/gif": "gif",
|
||||
}
|
||||
|
||||
|
||||
def is_inline_media_file(file_name: str) -> bool:
|
||||
"""Whether a library file is an image/video the browser can render inline."""
|
||||
|
||||
@@ -1,21 +1,7 @@
|
||||
import os
|
||||
|
||||
from config import FRONTEND_RESOURCES_PATH
|
||||
from models.assets import Save
|
||||
from models.rom import Rom
|
||||
|
||||
# Image formats every modern browser can decode. Shared by the per-ROM
|
||||
# (endpoints/roms/screenshot.py) and per-user (endpoints/screenshots.py)
|
||||
# screenshot upload endpoints.
|
||||
ALLOWED_SCREENSHOT_EXTENSIONS = frozenset(
|
||||
{".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".avif"}
|
||||
)
|
||||
|
||||
|
||||
def is_allowed_screenshot_file(file_name: str) -> bool:
|
||||
_, ext = os.path.splitext(file_name)
|
||||
return ext.lower() in ALLOWED_SCREENSHOT_EXTENSIONS
|
||||
|
||||
|
||||
def continue_playing_screenshot(rom: Rom, latest_save: Save | None) -> str | None:
|
||||
"""The "where you left off" image for a rom, in priority order: the latest
|
||||
|
||||
Reference in New Issue
Block a user