mirror of
https://github.com/rommapp/romm.git
synced 2026-12-06 15:54:45 +01:00
Merge remote-tracking branch 'origin/master' into chore/frontend-v2
This commit is contained in:
175 files changed
+5258
-2353
No files matched your search
@@ -51,6 +51,8 @@ lint:
|
||||
- frontend/src/__generated__/**
|
||||
- docker/Dockerfile
|
||||
- docker/nginx/js/**
|
||||
# Intentionally malformed YAML, used as a test fixture
|
||||
- backend/tests/config/fixtures/config/malformed_config.yml
|
||||
files:
|
||||
- name: vue
|
||||
extensions: [vue]
|
||||
|
||||
@@ -34,7 +34,7 @@ class _AnchorHrefParser(HTMLParser):
|
||||
# Skip sort/parent/query links exposed by Apache autoindex.
|
||||
if value.startswith(("?", "/", "#")) or ".." in value:
|
||||
return
|
||||
# Only keep image files — libretro stores PNGs.
|
||||
# Only keep image files, since libretro stores PNGs.
|
||||
decoded = unquote(value)
|
||||
if decoded.lower().endswith((".png", ".jpg", ".jpeg", ".webp")):
|
||||
self.filenames.append(decoded)
|
||||
|
||||
@@ -109,7 +109,7 @@ class RAHasherService:
|
||||
# Skip the subprocess entirely when the file is an archive and the
|
||||
# RA platform needs an on-disk disc image. RAHasher would just spawn,
|
||||
# fail with "Unsupported console for buffer hash: {id}", and return
|
||||
# nothing — paying process-spawn overhead per ROM for no result.
|
||||
# nothing, so we'd pay process-spawn overhead per ROM for no result.
|
||||
if file_path.lower().endswith(tuple(COMPRESSED_FILE_EXTENSIONS)):
|
||||
if platform["ra_id"] in RA_BUFFER_HASH_UNSUPPORTED_IDS:
|
||||
log.debug(
|
||||
|
||||
@@ -85,10 +85,34 @@ class ScreenScraperService:
|
||||
) from exc
|
||||
except aiohttp.ClientResponseError as err:
|
||||
if err.status == http.HTTPStatus.TOO_MANY_REQUESTS:
|
||||
# Retry after 2 seconds if rate limit hit
|
||||
log.warning("ScreenScraper: rate limit hit, retrying after 2s")
|
||||
await asyncio.sleep(2)
|
||||
elif err.status == 426:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="ScreenScraper has blacklisted this application version. Please update RomM.",
|
||||
) from err
|
||||
elif err.status == 430:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="ScreenScraper daily scrape quota exhausted. Try again tomorrow.",
|
||||
) from err
|
||||
elif err.status == 431:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="ScreenScraper daily unrecognized-ROM quota exhausted. Try again tomorrow.",
|
||||
) from err
|
||||
elif err.status == 423:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="ScreenScraper API is currently offline.",
|
||||
) from err
|
||||
elif err.status == http.HTTPStatus.UNAUTHORIZED:
|
||||
log.warning(
|
||||
"ScreenScraper API is temporarily unavailable (server CPU >60%)"
|
||||
)
|
||||
return {}
|
||||
else:
|
||||
# Log the error and return an empty dict if the request fails with a different code
|
||||
log.error(err)
|
||||
return {}
|
||||
except json.JSONDecodeError as exc:
|
||||
@@ -117,11 +141,32 @@ class ScreenScraperService:
|
||||
)
|
||||
return await res.json()
|
||||
except (aiohttp.ClientResponseError, aiohttp.ServerTimeoutError) as err:
|
||||
if (
|
||||
isinstance(err, aiohttp.ClientResponseError)
|
||||
and err.status == http.HTTPStatus.UNAUTHORIZED
|
||||
):
|
||||
return {}
|
||||
if isinstance(err, aiohttp.ClientResponseError):
|
||||
if err.status == http.HTTPStatus.UNAUTHORIZED:
|
||||
log.warning(
|
||||
"ScreenScraper API is temporarily unavailable (server CPU >60%)"
|
||||
)
|
||||
return {}
|
||||
elif err.status == 426:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="ScreenScraper has blacklisted this application version. Please update RomM.",
|
||||
) from err
|
||||
elif err.status == 430:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="ScreenScraper daily scrape quota exhausted. Try again tomorrow.",
|
||||
) from err
|
||||
elif err.status == 431:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="ScreenScraper daily unrecognized-ROM quota exhausted. Try again tomorrow.",
|
||||
) from err
|
||||
elif err.status == 423:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="ScreenScraper API is currently offline.",
|
||||
) from err
|
||||
|
||||
log.error(err)
|
||||
return {}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Add chd_sha1_hash to rom_files
|
||||
|
||||
Revision ID: 0080_add_chd_sha1_hash
|
||||
Revises: 0079_add_rom_files_rom_id_index
|
||||
Create Date: 2026-04-24 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0080_add_chd_sha1_hash"
|
||||
down_revision = "0079_add_rom_files_rom_id_index"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("rom_files", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column("chd_sha1_hash", sa.String(length=100), nullable=True),
|
||||
if_not_exists=True,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("rom_files", schema=None) as batch_op:
|
||||
batch_op.drop_column("chd_sha1_hash", if_exists=True)
|
||||
@@ -89,6 +89,7 @@ REFRESH_RETROACHIEVEMENTS_CACHE_DAYS: Final[int] = safe_int(
|
||||
)
|
||||
|
||||
# LAUNCHBOX
|
||||
LAUNCHBOX_BASE_PATH: Final[str] = f"{ROMM_BASE_PATH}/launchbox"
|
||||
LAUNCHBOX_API_ENABLED: Final[bool] = safe_str_to_bool(_get_env("LAUNCHBOX_API_ENABLED"))
|
||||
|
||||
# PLAYMATCH
|
||||
@@ -213,7 +214,7 @@ SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON: Final[str] = _get_env(
|
||||
)
|
||||
|
||||
# SYNC
|
||||
SYNC_BASE_PATH: Final[str] = _get_env("SYNC_BASE_PATH", f"{ROMM_BASE_PATH}/sync")
|
||||
SYNC_BASE_PATH: Final[str] = f"{ROMM_BASE_PATH}/sync"
|
||||
ENABLE_SYNC_FOLDER_WATCHER: Final[bool] = safe_str_to_bool(
|
||||
_get_env("ENABLE_SYNC_FOLDER_WATCHER")
|
||||
)
|
||||
@@ -226,10 +227,10 @@ SYNC_PUSH_PULL_CRON: Final[str] = _get_env(
|
||||
"*/30 * * * *", # Every 30 minutes
|
||||
)
|
||||
SYNC_SSH_KEYS_PATH: Final[str] = _get_env(
|
||||
"SYNC_SSH_KEYS_PATH", f"{ROMM_BASE_PATH}/sync/keys"
|
||||
"SYNC_SSH_KEYS_PATH", f"{SYNC_BASE_PATH}/keys"
|
||||
)
|
||||
SYNC_SSH_KNOWN_HOSTS_PATH: Final[str] = _get_env(
|
||||
"SYNC_SSH_KNOWN_HOSTS_PATH", f"{ROMM_BASE_PATH}/sync/known_hosts"
|
||||
"SYNC_SSH_KNOWN_HOSTS_PATH", f"{SYNC_BASE_PATH}/known_hosts"
|
||||
)
|
||||
|
||||
# EMULATION
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import enum
|
||||
import functools
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Final, NotRequired, TypedDict
|
||||
|
||||
import pydash
|
||||
@@ -49,6 +52,7 @@ DEFAULT_EXCLUDED_FILES: Final = [
|
||||
]
|
||||
DEFAULT_EXCLUDED_DIRS: Final = [
|
||||
"@eaDir",
|
||||
"assets",
|
||||
"__MACOSX",
|
||||
"$RECYCLE.BIN",
|
||||
".Trash-*",
|
||||
@@ -114,7 +118,6 @@ class Config:
|
||||
ROMS_FOLDER_NAME: str
|
||||
FIRMWARE_FOLDER_NAME: str
|
||||
SKIP_HASH_CALCULATION: bool
|
||||
HIGH_PRIO_STRUCTURE_PATH: str
|
||||
EJS_DEBUG: bool
|
||||
EJS_CACHE_LIMIT: int | None
|
||||
EJS_DISABLE_AUTO_UNLOAD: bool
|
||||
@@ -133,7 +136,16 @@ class Config:
|
||||
|
||||
def __init__(self, **entries):
|
||||
self.__dict__.update(entries)
|
||||
self.HIGH_PRIO_STRUCTURE_PATH = f"{LIBRARY_BASE_PATH}/{self.ROMS_FOLDER_NAME}"
|
||||
|
||||
@functools.cached_property
|
||||
def has_structure_path_b(self) -> bool:
|
||||
pattern = os.path.join(
|
||||
LIBRARY_BASE_PATH, "*", glob.escape(self.ROMS_FOLDER_NAME)
|
||||
)
|
||||
for match in glob.iglob(pattern):
|
||||
if os.path.isdir(match):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class ConfigManager:
|
||||
@@ -163,14 +175,12 @@ class ConfigManager:
|
||||
# Check if the config file is mounted
|
||||
with open(self.config_file, "r") as cf:
|
||||
self._config_file_mounted = True
|
||||
self._raw_config = yaml.load(cf, Loader=SafeLoader) or {}
|
||||
self._raw_config = self._safe_load_yaml(cf)
|
||||
|
||||
# Also check if the config file is writable
|
||||
self._config_file_writable = os.access(self.config_file, os.W_OK)
|
||||
except FileNotFoundError:
|
||||
log.critical(
|
||||
"Config file not found! Any changes made to the configuration will not persist after the application restarts."
|
||||
)
|
||||
self._create_missing_config_file()
|
||||
except PermissionError:
|
||||
log.warning(
|
||||
"Config file not writable! Any changes made to the configuration will not persist after the application restarts."
|
||||
@@ -180,6 +190,41 @@ class ConfigManager:
|
||||
self._parse_config()
|
||||
self._validate_config()
|
||||
|
||||
def _safe_load_yaml(self, cf) -> dict:
|
||||
"""Load YAML, falling back to an empty config on syntax errors so the
|
||||
app can still boot with defaults rather than crashing."""
|
||||
try:
|
||||
return yaml.load(cf, Loader=SafeLoader) or {}
|
||||
except yaml.YAMLError as exc:
|
||||
log.critical(
|
||||
f"Failed to parse {hl(self.config_file, BLUE)}: {exc}. "
|
||||
"Falling back to default configuration, fix the YAML "
|
||||
"syntax to apply your settings."
|
||||
)
|
||||
return {}
|
||||
|
||||
def _create_missing_config_file(self) -> None:
|
||||
log.warning(
|
||||
f"Config file not found, creating an empty config at {hl(self.config_file, BLUE)}"
|
||||
)
|
||||
|
||||
try:
|
||||
config_file = Path(self.config_file)
|
||||
config_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
config_file.touch(exist_ok=True)
|
||||
|
||||
# Reset any previously loaded singleton state so parsing reflects
|
||||
# the newly created empty config file.
|
||||
self._raw_config = {}
|
||||
self._config_file_mounted = True
|
||||
self._config_file_writable = os.access(self.config_file, os.W_OK)
|
||||
except PermissionError:
|
||||
self._config_file_mounted = False
|
||||
self._config_file_writable = False
|
||||
log.critical(
|
||||
"Config file not found and could not be created! Any changes made to the configuration will not persist after the application restarts."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def get_db_engine() -> URL:
|
||||
"""Builds the database connection string using environment variables
|
||||
@@ -602,12 +647,19 @@ class ConfigManager:
|
||||
log.critical("Invalid config.yml: scan.media must be a list")
|
||||
sys.exit(3)
|
||||
|
||||
for media in self.config.SCAN_MEDIA:
|
||||
if media not in MetadataMediaType:
|
||||
log.critical(
|
||||
f"Invalid config.yml: scan.media.{media} is not a valid media type"
|
||||
)
|
||||
sys.exit(3)
|
||||
# Drop unknown media types rather than exiting, since a newer release
|
||||
# may ship sample configs referencing media types this version doesn't know.
|
||||
unknown_media = [
|
||||
m for m in self.config.SCAN_MEDIA if m not in MetadataMediaType
|
||||
]
|
||||
if unknown_media:
|
||||
log.warning(
|
||||
f"Ignoring unknown values in scan.media: {unknown_media}. "
|
||||
"These may be from a newer RomM version; update to use them."
|
||||
)
|
||||
self.config.SCAN_MEDIA = [
|
||||
m for m in self.config.SCAN_MEDIA if m in MetadataMediaType
|
||||
]
|
||||
|
||||
valid_thumbnail_options = {
|
||||
MetadataMediaType.BOX2D,
|
||||
@@ -621,10 +673,12 @@ class ConfigManager:
|
||||
)
|
||||
sys.exit(3)
|
||||
if self.config.GAMELIST_MEDIA_THUMBNAIL not in valid_thumbnail_options:
|
||||
log.critical(
|
||||
f"Invalid config.yml: scan.gamelist.media.thumbnail must be one of {valid_thumbnail_options}"
|
||||
log.warning(
|
||||
f"Unknown scan.gamelist.media.thumbnail value "
|
||||
f"{self.config.GAMELIST_MEDIA_THUMBNAIL!r}; falling back to "
|
||||
f"{MetadataMediaType.BOX2D.value!r}. Valid options: {sorted(o.value for o in valid_thumbnail_options)}."
|
||||
)
|
||||
sys.exit(3)
|
||||
self.config.GAMELIST_MEDIA_THUMBNAIL = MetadataMediaType.BOX2D
|
||||
|
||||
valid_image_options = {
|
||||
MetadataMediaType.TITLE_SCREEN,
|
||||
@@ -640,15 +694,17 @@ class ConfigManager:
|
||||
sys.exit(3)
|
||||
|
||||
if self.config.GAMELIST_MEDIA_IMAGE not in valid_image_options:
|
||||
log.critical(
|
||||
f"Invalid config.yml: scan.gamelist.media.image must be one of {valid_image_options}"
|
||||
log.warning(
|
||||
f"Unknown scan.gamelist.media.image value "
|
||||
f"{self.config.GAMELIST_MEDIA_IMAGE!r}; falling back to "
|
||||
f"{MetadataMediaType.SCREENSHOT.value!r}. Valid options: {sorted(o.value for o in valid_image_options)}."
|
||||
)
|
||||
sys.exit(3)
|
||||
self.config.GAMELIST_MEDIA_IMAGE = MetadataMediaType.SCREENSHOT
|
||||
|
||||
def get_config(self) -> Config:
|
||||
try:
|
||||
with open(self.config_file, "r") as config_file:
|
||||
self._raw_config = yaml.load(config_file, Loader=SafeLoader) or {}
|
||||
self._raw_config = self._safe_load_yaml(config_file)
|
||||
except FileNotFoundError:
|
||||
log.debug("Config file not found!")
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ from exceptions.endpoint_exceptions import (
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_collection_handler
|
||||
from handler.filesystem import fs_resource_handler
|
||||
from handler.filesystem.assets_handler import validate_image_upload
|
||||
from handler.filesystem.base_handler import CoverSize
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
@@ -82,7 +83,7 @@ async def add_collection(
|
||||
|
||||
try:
|
||||
if artwork is not None and artwork.filename is not None:
|
||||
file_ext = artwork.filename.split(".")[-1]
|
||||
file_ext = validate_image_upload(artwork, label="Artwork")
|
||||
artwork_content = BytesIO(await artwork.read())
|
||||
(
|
||||
path_cover_l,
|
||||
@@ -427,7 +428,7 @@ async def update_collection(
|
||||
cleaned_data.update({"url_cover": ""})
|
||||
else:
|
||||
if artwork is not None and artwork.filename is not None:
|
||||
file_ext = artwork.filename.split(".")[-1]
|
||||
file_ext = validate_image_upload(artwork, label="Artwork")
|
||||
artwork_content = BytesIO(await artwork.read())
|
||||
(
|
||||
path_cover_l,
|
||||
|
||||
@@ -8,7 +8,7 @@ from decorators.auth import protected_route
|
||||
from endpoints.responses.device import DeviceCreateResponse, DeviceSchema
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_device_handler, db_device_save_sync_handler
|
||||
from handler.filesystem import fs_sync_handler
|
||||
from handler.filesystem import get_fs_sync_handler
|
||||
from logger.logger import log
|
||||
from models.device import Device, SyncMode
|
||||
from utils.router import APIRouter
|
||||
@@ -123,7 +123,7 @@ def register_device(
|
||||
# Auto-create sync folders for file_transfer devices
|
||||
if payload.sync_mode == SyncMode.FILE_TRANSFER:
|
||||
try:
|
||||
fs_sync_handler.ensure_device_directories(device_id)
|
||||
get_fs_sync_handler().ensure_device_directories(device_id)
|
||||
except Exception:
|
||||
log.warning(f"Failed to create sync directories for device {device_id}")
|
||||
|
||||
|
||||
@@ -159,6 +159,8 @@ async def metadata_heartbeat(source: str) -> bool:
|
||||
return await meta_launchbox_handler.heartbeat()
|
||||
case MetadataSource.HASHEOUS:
|
||||
return await meta_hasheous_handler.heartbeat()
|
||||
case MetadataSource.PLAYMATCH:
|
||||
return await meta_playmatch_handler.heartbeat()
|
||||
case MetadataSource.TGDB:
|
||||
return await meta_tgdb_handler.heartbeat()
|
||||
case MetadataSource.SGDB:
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
from mimetypes import guess_type
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from decorators.auth import protected_route
|
||||
from handler.auth.constants import Scope
|
||||
from handler.filesystem import fs_asset_handler
|
||||
from handler.filesystem.assets_handler import SAFE_IMAGE_MIME_TYPES
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter(
|
||||
@@ -12,6 +16,24 @@ router = APIRouter(
|
||||
)
|
||||
|
||||
|
||||
def _build_asset_response(resolved_path: Path) -> FileResponse:
|
||||
guessed_type, _ = guess_type(resolved_path.name)
|
||||
if guessed_type in SAFE_IMAGE_MIME_TYPES:
|
||||
return FileResponse(
|
||||
path=str(resolved_path),
|
||||
filename=resolved_path.name,
|
||||
media_type=guessed_type,
|
||||
content_disposition_type="inline",
|
||||
)
|
||||
|
||||
return FileResponse(
|
||||
path=str(resolved_path),
|
||||
filename=resolved_path.name,
|
||||
media_type="application/octet-stream",
|
||||
content_disposition_type="attachment",
|
||||
)
|
||||
|
||||
|
||||
@protected_route(router.head, "/assets/{path:path}", [Scope.ASSETS_READ])
|
||||
def head_raw_asset(request: Request, path: str):
|
||||
try:
|
||||
@@ -21,9 +43,9 @@ def head_raw_asset(request: Request, path: str):
|
||||
|
||||
# Check if file exists and is a file (not directory)
|
||||
if not resolved_path.exists() or not resolved_path.is_file():
|
||||
return HTTPException(status_code=404, detail="Asset not found")
|
||||
raise HTTPException(status_code=404, detail="Asset not found")
|
||||
|
||||
return FileResponse(path=str(resolved_path), filename=resolved_path.name)
|
||||
return _build_asset_response(resolved_path)
|
||||
|
||||
|
||||
@protected_route(router.get, "/assets/{path:path}", [Scope.ASSETS_READ])
|
||||
@@ -47,9 +69,6 @@ def get_raw_asset(request: Request, path: str):
|
||||
|
||||
# Check if file exists and is a file (not directory)
|
||||
if not resolved_path.exists() or not resolved_path.is_file():
|
||||
return HTTPException(status_code=404, detail="Asset not found")
|
||||
|
||||
if not resolved_path:
|
||||
raise HTTPException(status_code=404, detail="Asset not found")
|
||||
|
||||
return FileResponse(path=str(resolved_path), filename=resolved_path.name)
|
||||
return _build_asset_response(resolved_path)
|
||||
@@ -178,6 +178,7 @@ class RomFileSchema(BaseModel):
|
||||
md5_hash: str | None
|
||||
sha1_hash: str | None
|
||||
ra_hash: str | None
|
||||
chd_sha1_hash: str | None
|
||||
category: RomFileCategory | None
|
||||
audio_meta: RomFileAudioMetaSchema | None = None
|
||||
|
||||
@@ -315,7 +316,6 @@ class RomSchema(BaseModel):
|
||||
has_simple_single_file: bool
|
||||
has_nested_single_file: bool
|
||||
has_multiple_files: bool
|
||||
files: list[RomFileSchema]
|
||||
full_path: str
|
||||
created_at: UTCDatetime
|
||||
updated_at: UTCDatetime
|
||||
@@ -352,10 +352,6 @@ class RomSchema(BaseModel):
|
||||
def sort_alternative_names(cls, v: list[str]) -> list[str]:
|
||||
return sorted(v)
|
||||
|
||||
@field_validator("files")
|
||||
def sort_files(cls, v: list[RomFileSchema]) -> list[RomFileSchema]:
|
||||
return sorted(v, key=lambda x: x.file_name)
|
||||
|
||||
@field_validator("siblings")
|
||||
def sort_siblings(cls, v: list[SiblingRomSchema]) -> list[SiblingRomSchema]:
|
||||
return sorted(v, key=lambda x: x.sort_comparator)
|
||||
@@ -413,12 +409,17 @@ class UserCollectionSchema(BaseModel):
|
||||
|
||||
|
||||
class DetailedRomSchema(RomSchema):
|
||||
files: list[RomFileSchema]
|
||||
user_saves: list[SaveSchema]
|
||||
user_states: list[StateSchema]
|
||||
user_screenshots: list[ScreenshotSchema]
|
||||
user_collections: list[UserCollectionSchema]
|
||||
all_user_notes: list[UserNoteSchema]
|
||||
|
||||
@field_validator("files")
|
||||
def sort_files(cls, v: list[RomFileSchema]) -> list[RomFileSchema]:
|
||||
return sorted(v, key=lambda x: x.file_name)
|
||||
|
||||
@classmethod
|
||||
def from_orm_with_request(cls, db_rom: Rom, request: Request) -> DetailedRomSchema:
|
||||
user_id = request.user.id
|
||||
|
||||
@@ -49,6 +49,7 @@ from handler.auth.constants import Scope
|
||||
from handler.database import db_rom_handler
|
||||
from handler.database.base_handler import sync_session
|
||||
from handler.filesystem import fs_resource_handler, fs_rom_handler
|
||||
from handler.filesystem.assets_handler import validate_image_upload
|
||||
from handler.metadata import (
|
||||
meta_flashpoint_handler,
|
||||
meta_igdb_handler,
|
||||
@@ -58,7 +59,7 @@ from handler.metadata import (
|
||||
meta_ra_handler,
|
||||
meta_ss_handler,
|
||||
)
|
||||
from handler.metadata.ss_handler import get_preferred_media_types
|
||||
from handler.metadata.ss_handler import add_ss_auth_to_url, get_preferred_media_types
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
@@ -529,6 +530,7 @@ def get_roms(
|
||||
player_counts_logic=player_counts_logic,
|
||||
group_by_meta_id=group_by_meta_id,
|
||||
updated_after=updated_after,
|
||||
include_file_stats=True,
|
||||
)
|
||||
|
||||
# Get the char index for the roms
|
||||
@@ -1283,7 +1285,7 @@ async def update_rom(
|
||||
cleaned_data.update({"ss_id": None, "ss_metadata": {}})
|
||||
|
||||
if cleaned_data["igdb_id"] and int(cleaned_data["igdb_id"]) != rom.igdb_id:
|
||||
igdb_rom = await meta_igdb_handler.get_rom_by_id(cleaned_data["igdb_id"])
|
||||
igdb_rom = await meta_igdb_handler.get_rom_by_id(rom, cleaned_data["igdb_id"])
|
||||
if igdb_rom.get("igdb_id"):
|
||||
cleaned_data.update(igdb_rom)
|
||||
elif rom.igdb_id and not cleaned_data["igdb_id"]:
|
||||
@@ -1345,7 +1347,7 @@ async def update_rom(
|
||||
cleaned_data.update({"url_cover": ""})
|
||||
else:
|
||||
if artwork is not None and artwork.filename is not None:
|
||||
file_ext = artwork.filename.split(".")[-1]
|
||||
file_ext = validate_image_upload(artwork, label="Artwork")
|
||||
artwork_content = BytesIO(await artwork.read())
|
||||
(
|
||||
path_cover_l,
|
||||
@@ -1429,7 +1431,9 @@ async def update_rom(
|
||||
|
||||
if cleaned_data.get("ss_metadata", {}).get(f"{media_type.value}_path"):
|
||||
await fs_resource_handler.store_media_file(
|
||||
cleaned_data["ss_metadata"][f"{media_type.value}_url"],
|
||||
add_ss_auth_to_url(
|
||||
cleaned_data["ss_metadata"][f"{media_type.value}_url"]
|
||||
),
|
||||
cleaned_data["ss_metadata"][f"{media_type.value}_path"],
|
||||
)
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import json
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Annotated
|
||||
from uuid import UUID, uuid4
|
||||
@@ -9,6 +8,7 @@ from anyio import open_file
|
||||
from fastapi import Header, HTTPException, Request, status
|
||||
from starlette.responses import Response
|
||||
|
||||
from config import ROMM_BASE_PATH, ROMM_TMP_PATH
|
||||
from decorators.auth import protected_route
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_platform_handler
|
||||
@@ -22,7 +22,10 @@ router = APIRouter(
|
||||
tags=["upload"],
|
||||
)
|
||||
|
||||
ROM_UPLOAD_TMP_BASE = Path(tempfile.gettempdir()) / "romm" / "uploads"
|
||||
# Store upload chunks under ROMM_BASE_PATH (disk-backed) by default.
|
||||
# Users can override the tmp location with the ROMM_TMP_PATH env variable.
|
||||
_tmp_root = Path(ROMM_TMP_PATH) if ROMM_TMP_PATH else Path(ROMM_BASE_PATH)
|
||||
ROM_UPLOAD_TMP_BASE = _tmp_root / "tmp" / "uploads"
|
||||
ROM_UPLOAD_TTL = 86400 # 24 hours
|
||||
ROM_ASSEMBLY_CHUNK_SIZE = 8192 # 8KB read buffer during assembly
|
||||
ROM_UPLOAD_MAX_CHUNK_SIZE = 64 * 1024 * 1024 # 64MB hard cap per chunk
|
||||
|
||||
@@ -100,7 +100,7 @@ async def search_rom(
|
||||
if search_by.lower() == "id":
|
||||
try:
|
||||
igdb_rom, moby_rom, ss_rom, lb_rom = await asyncio.gather(
|
||||
meta_igdb_handler.get_matched_rom_by_id(int(search_term)),
|
||||
meta_igdb_handler.get_matched_rom_by_id(rom, int(search_term)),
|
||||
meta_moby_handler.get_matched_rom_by_id(int(search_term)),
|
||||
meta_ss_handler.get_matched_rom_by_id(rom, int(search_term)),
|
||||
meta_launchbox_handler.get_matched_rom_by_id(int(search_term)),
|
||||
@@ -125,7 +125,7 @@ async def search_rom(
|
||||
launchbox_matched_roms,
|
||||
) = await asyncio.gather(
|
||||
meta_igdb_handler.get_matched_roms_by_name(
|
||||
search_term, get_main_platform_igdb_id(rom.platform)
|
||||
rom, search_term, get_main_platform_igdb_id(rom.platform)
|
||||
),
|
||||
meta_moby_handler.get_matched_roms_by_name(
|
||||
search_term, rom.platform.moby_id
|
||||
|
||||
@@ -172,7 +172,7 @@ async def webrtc_signal(sid: str, data: WebRTCSignalData):
|
||||
)
|
||||
else:
|
||||
if not target:
|
||||
return # drop message—no recipient
|
||||
return # drop message, no recipient
|
||||
await netplay_socket_handler.socket_server.emit(
|
||||
"webrtc-signal",
|
||||
{
|
||||
|
||||
@@ -11,6 +11,7 @@ from rq import Worker
|
||||
from rq.job import Job
|
||||
|
||||
from config import DEV_MODE, REDIS_URL, SCAN_TIMEOUT, SCAN_WORKERS, TASK_RESULT_TTL
|
||||
from config.config_manager import MetadataMediaType
|
||||
from config.config_manager import config_manager as cm
|
||||
from endpoints.responses import TaskType
|
||||
from endpoints.responses.platform import PlatformSchema
|
||||
@@ -31,7 +32,7 @@ from handler.filesystem import (
|
||||
)
|
||||
from handler.filesystem.roms_handler import FSRom
|
||||
from handler.metadata import meta_gamelist_handler, meta_hltb_handler
|
||||
from handler.metadata.ss_handler import get_preferred_media_types
|
||||
from handler.metadata.ss_handler import add_ss_auth_to_url, get_preferred_media_types
|
||||
from handler.redis_handler import get_job_func_name, high_prio_queue, redis_client
|
||||
from handler.scan_handler import (
|
||||
MetadataSource,
|
||||
@@ -179,13 +180,17 @@ def _should_scan_rom(
|
||||
(
|
||||
scan_type == ScanType.UPDATE
|
||||
and rom.is_identified
|
||||
and any(getattr(rom, f"{source}_id") for source in metadata_sources)
|
||||
and any(
|
||||
getattr(rom, f"{source}_id", None)
|
||||
for source in metadata_sources
|
||||
)
|
||||
)
|
||||
# Unmatched scan should scan ROMs that are not identified by the selected metadata sources
|
||||
or (
|
||||
scan_type == ScanType.UNMATCHED
|
||||
and any(
|
||||
not getattr(rom, f"{source}_id") for source in metadata_sources
|
||||
not getattr(rom, f"{source}_id", None)
|
||||
for source in metadata_sources
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -297,6 +302,36 @@ async def _identify_rom(
|
||||
}
|
||||
)
|
||||
|
||||
# For a COMPLETE rescan, wipe all downloaded resources before re-fetching so
|
||||
# stale files (e.g. a cover from the wrong region) can't be reused. The
|
||||
# post-scan download steps below skip downloads when a file already exists or
|
||||
# when the source URL is unchanged, so the on-disk files must be removed here.
|
||||
if not newly_added and scan_type == ScanType.COMPLETE:
|
||||
try:
|
||||
await fs_resource_handler.remove_cover(rom)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
try:
|
||||
await fs_resource_handler.remove_manual(rom)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
try:
|
||||
await fs_resource_handler.remove_directory(
|
||||
f"{rom.fs_resources_path}/screenshots"
|
||||
)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
for media_type in MetadataMediaType:
|
||||
try:
|
||||
await fs_resource_handler.remove_media_resources_path(
|
||||
platform.id, rom.id, media_type
|
||||
)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
log.debug(f"Scanning {rom.fs_name}...")
|
||||
scanned_rom = await scan_rom(
|
||||
scan_type=scan_type,
|
||||
@@ -351,6 +386,7 @@ async def _identify_rom(
|
||||
md5_hash=file.md5_hash,
|
||||
sha1_hash=file.sha1_hash,
|
||||
ra_hash=file.ra_hash,
|
||||
chd_sha1_hash=file.chd_sha1_hash,
|
||||
)
|
||||
for file in fs_rom["files"]
|
||||
]
|
||||
@@ -422,7 +458,9 @@ async def _identify_rom(
|
||||
for media_type in preferred_media_types:
|
||||
if _added_rom.ss_metadata.get(f"{media_type.value}_path"):
|
||||
await fs_resource_handler.store_media_file(
|
||||
_added_rom.ss_metadata[f"{media_type.value}_url"],
|
||||
add_ss_auth_to_url(
|
||||
_added_rom.ss_metadata[f"{media_type.value}_url"]
|
||||
),
|
||||
_added_rom.ss_metadata[f"{media_type.value}_path"],
|
||||
)
|
||||
|
||||
@@ -436,6 +474,16 @@ async def _identify_rom(
|
||||
_added_rom.gamelist_metadata[f"{media_type.value}_path"],
|
||||
)
|
||||
|
||||
# Handle special media files from LaunchBox
|
||||
if _added_rom.launchbox_metadata and MetadataSource.LAUNCHBOX in metadata_sources:
|
||||
preferred_media_types = get_preferred_media_types()
|
||||
for media_type in preferred_media_types:
|
||||
if _added_rom.launchbox_metadata.get(f"{media_type.value}_path"):
|
||||
await fs_resource_handler.store_media_file(
|
||||
_added_rom.launchbox_metadata[f"{media_type.value}_url"],
|
||||
_added_rom.launchbox_metadata[f"{media_type.value}_path"],
|
||||
)
|
||||
|
||||
# Store normal and locked badges
|
||||
if _added_rom.ra_metadata and MetadataSource.RA in metadata_sources:
|
||||
for ach in _added_rom.ra_metadata.get("achievements", []):
|
||||
|
||||
@@ -147,7 +147,7 @@ def _build_task_status_response(
|
||||
|
||||
common_data = {
|
||||
"task_name": task_name,
|
||||
"task_id": job.get_id(),
|
||||
"task_id": job.id,
|
||||
"status": job.get_status(),
|
||||
"created_at": created_at,
|
||||
"enqueued_at": enqueued_at,
|
||||
@@ -386,7 +386,7 @@ async def run_single_task(
|
||||
|
||||
return {
|
||||
"task_name": task_instance.title,
|
||||
"task_id": job.get_id(),
|
||||
"task_id": job.id,
|
||||
"status": job.get_status() or JobStatus.QUEUED,
|
||||
"created_at": (
|
||||
job.created_at.isoformat()
|
||||
|
||||
@@ -12,6 +12,7 @@ from handler.auth import auth_handler
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_user_handler
|
||||
from handler.filesystem import fs_asset_handler
|
||||
from handler.filesystem.assets_handler import validate_image_upload
|
||||
from handler.metadata import meta_ra_handler
|
||||
from handler.metadata.ra_handler import RAUserProgression
|
||||
from logger.logger import log
|
||||
@@ -387,9 +388,10 @@ async def update_user(
|
||||
) from exc
|
||||
|
||||
if form_data.avatar is not None and form_data.avatar.filename is not None:
|
||||
safe_extension = validate_image_upload(form_data.avatar, label="Avatar")
|
||||
|
||||
user_avatar_path = fs_asset_handler.build_avatar_path(user=db_user)
|
||||
file_extension = form_data.avatar.filename.split(".")[-1]
|
||||
file_name = f"avatar.{file_extension}"
|
||||
file_name = f"avatar.{safe_extension}"
|
||||
|
||||
await fs_asset_handler.write_file(
|
||||
file=form_data.avatar.file, path=user_avatar_path, filename=file_name
|
||||
|
||||
@@ -90,18 +90,21 @@ class CSRFMiddleware:
|
||||
await self.app(scope, receive, send)
|
||||
|
||||
async def send(self, message: Message, send: Send, scope: Scope) -> None:
|
||||
if message["type"] != "http.response.start":
|
||||
await send(message)
|
||||
return
|
||||
|
||||
request = Request(scope)
|
||||
csrf_cookie = request.cookies.get(self.cookie_name)
|
||||
current_user_id = request.user.id if request.user.is_authenticated else None
|
||||
|
||||
if csrf_cookie is None:
|
||||
if not self._csrf_cookie_has_user(csrf_cookie, current_user_id):
|
||||
message.setdefault("headers", [])
|
||||
headers = MutableHeaders(scope=message)
|
||||
|
||||
cookie: http.cookies.BaseCookie = http.cookies.SimpleCookie()
|
||||
cookie_name = self.cookie_name
|
||||
cookie[cookie_name] = self._generate_csrf_token(
|
||||
request.user.id if request.user.is_authenticated else None
|
||||
)
|
||||
cookie[cookie_name] = self._generate_csrf_token(current_user_id)
|
||||
cookie[cookie_name]["path"] = self.cookie_path
|
||||
cookie[cookie_name]["secure"] = self.cookie_secure
|
||||
cookie[cookie_name]["httponly"] = self.cookie_httponly
|
||||
@@ -143,6 +146,19 @@ class CSRFMiddleware:
|
||||
obj = {"token": secrets.token_urlsafe(128), "user_id": user_id}
|
||||
return cast(str, self.serializer.dumps(obj))
|
||||
|
||||
def _csrf_cookie_has_user(
|
||||
self, csrf_cookie: str | None, user_id: int | None
|
||||
) -> bool:
|
||||
if csrf_cookie is None:
|
||||
return False
|
||||
|
||||
try:
|
||||
decoded_csrf_cookie = self.serializer.loads(csrf_cookie)
|
||||
except (TypeError, BadSignature):
|
||||
return False
|
||||
|
||||
return decoded_csrf_cookie.get("user_id") == user_id
|
||||
|
||||
def _csrf_tokens_match(
|
||||
self, document_cookie: str, header_cookie: str, user_id: int | None
|
||||
) -> bool:
|
||||
|
||||
@@ -25,10 +25,10 @@ from sqlalchemy.orm import (
|
||||
Query,
|
||||
QueryableAttribute,
|
||||
Session,
|
||||
joinedload,
|
||||
load_only,
|
||||
noload,
|
||||
selectinload,
|
||||
undefer,
|
||||
)
|
||||
from sqlalchemy.sql.elements import ColumnElement
|
||||
from sqlalchemy.sql.selectable import Select
|
||||
@@ -142,14 +142,14 @@ def with_details(func):
|
||||
),
|
||||
selectinload(Rom.rom_users).options(noload(RomUser.rom)),
|
||||
selectinload(Rom.metadatum).options(noload(RomMetadata.rom)),
|
||||
selectinload(Rom.files).options(
|
||||
joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name)
|
||||
),
|
||||
selectinload(Rom.files),
|
||||
selectinload(Rom.sibling_roms).options(
|
||||
noload(Rom.platform), noload(Rom.metadatum)
|
||||
),
|
||||
selectinload(Rom.collections),
|
||||
selectinload(Rom.notes),
|
||||
undefer(Rom.multi_file),
|
||||
undefer(Rom.top_level_file_count),
|
||||
)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
@@ -549,6 +549,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
player_counts_logic: str = "any",
|
||||
user_id: int | None = None,
|
||||
updated_after: datetime | None = None,
|
||||
include_file_stats: bool = False,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Query[Rom]:
|
||||
from handler.scan_handler import MetadataSource
|
||||
@@ -560,10 +561,6 @@ class DBRomsHandler(DBBaseHandler):
|
||||
selectinload(Rom.rom_users).options(noload(RomUser.rom)),
|
||||
# Sort table by metadata (first_release_date)
|
||||
selectinload(Rom.metadatum).options(noload(RomMetadata.rom)),
|
||||
# Required for multi-file ROM actions and 3DS QR code
|
||||
selectinload(Rom.files).options(
|
||||
joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name)
|
||||
),
|
||||
# Show sibling rom badges on cards
|
||||
selectinload(Rom.sibling_roms).options(
|
||||
noload(Rom.platform), noload(Rom.metadatum)
|
||||
@@ -572,6 +569,14 @@ class DBRomsHandler(DBBaseHandler):
|
||||
selectinload(Rom.notes),
|
||||
)
|
||||
|
||||
# Correlated subqueries and only undefer when the caller serializes the
|
||||
# gallery-card flags. Feeds and filter-value lookups don't need them.
|
||||
if include_file_stats:
|
||||
query = query.options(
|
||||
undefer(Rom.multi_file),
|
||||
undefer(Rom.top_level_file_count),
|
||||
)
|
||||
|
||||
# Handle platform filtering - platform filtering always uses OR logic since ROMs belong to only one platform
|
||||
if platform_ids:
|
||||
query = self._filter_by_platform_ids(query, platform_ids)
|
||||
@@ -941,8 +946,8 @@ class DBRomsHandler(DBBaseHandler):
|
||||
"""Retrieve a dictionary of roms by their filesystem names.
|
||||
|
||||
Eager-loads only `platform` (used downstream by the scan loop via
|
||||
`rom.platform_slug` / `rom.platform.fs_slug`) — deliberately
|
||||
avoiding `with_details`, whose full relationship eager-load is
|
||||
`rom.platform_slug` / `rom.platform.fs_slug`). This deliberately
|
||||
avoids `with_details`, whose full relationship eager-load is
|
||||
wasted work for the scan-skip decision on large platforms.
|
||||
"""
|
||||
roms = (
|
||||
@@ -950,9 +955,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
select(Rom)
|
||||
.options(
|
||||
selectinload(Rom.platform),
|
||||
selectinload(Rom.files).options(
|
||||
joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name)
|
||||
),
|
||||
selectinload(Rom.files),
|
||||
)
|
||||
.where(
|
||||
and_(
|
||||
|
||||
@@ -1,13 +1,30 @@
|
||||
from .assets_handler import FSAssetsHandler
|
||||
from .firmware_handler import FSFirmwareHandler
|
||||
from .launchbox_handler import FSLaunchboxHandler, get_fs_launchbox_handler
|
||||
from .platforms_handler import FSPlatformsHandler
|
||||
from .resources_handler import FSResourcesHandler
|
||||
from .roms_handler import FSRomsHandler
|
||||
from .sync_handler import FSSyncHandler
|
||||
from .sync_handler import FSSyncHandler, get_fs_sync_handler
|
||||
|
||||
fs_asset_handler = FSAssetsHandler()
|
||||
fs_firmware_handler = FSFirmwareHandler()
|
||||
fs_platform_handler = FSPlatformsHandler()
|
||||
fs_rom_handler = FSRomsHandler()
|
||||
fs_resource_handler = FSResourcesHandler()
|
||||
fs_sync_handler = FSSyncHandler()
|
||||
|
||||
__all__ = [
|
||||
"FSAssetsHandler",
|
||||
"FSFirmwareHandler",
|
||||
"FSLaunchboxHandler",
|
||||
"FSPlatformsHandler",
|
||||
"FSResourcesHandler",
|
||||
"FSRomsHandler",
|
||||
"FSSyncHandler",
|
||||
"fs_asset_handler",
|
||||
"fs_firmware_handler",
|
||||
"fs_platform_handler",
|
||||
"fs_resource_handler",
|
||||
"fs_rom_handler",
|
||||
"get_fs_launchbox_handler",
|
||||
"get_fs_sync_handler",
|
||||
]
|
||||
@@ -1,6 +1,11 @@
|
||||
import hashlib
|
||||
import os
|
||||
import threading
|
||||
import zipfile
|
||||
from typing import Final
|
||||
|
||||
import magic
|
||||
from fastapi import HTTPException, UploadFile, status
|
||||
|
||||
from config import ASSETS_BASE_PATH
|
||||
from logger.logger import log
|
||||
@@ -8,6 +13,57 @@ from models.user import User
|
||||
|
||||
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
|
||||
# this validator may execute in worker threads under sync routes.
|
||||
_MIME_DETECTOR = magic.Magic(mime=True)
|
||||
_MIME_DETECTOR_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def validate_image_upload(upload: UploadFile, *, label: str = "Image") -> str:
|
||||
"""Validate that an uploaded file is one of the safe image types.
|
||||
|
||||
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.
|
||||
Leaves the file cursor at 0.
|
||||
"""
|
||||
upload.file.seek(0)
|
||||
header = upload.file.read(4096)
|
||||
upload.file.seek(0)
|
||||
|
||||
try:
|
||||
with _MIME_DETECTOR_LOCK:
|
||||
detected_mime = _MIME_DETECTOR.from_buffer(header)
|
||||
except magic.MagicException as exc:
|
||||
log.error(f"libmagic failed to sniff uploaded {label.lower()}: {exc}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Could not determine {label.lower()} file type",
|
||||
) from exc
|
||||
|
||||
safe_extension = SAFE_IMAGE_MIME_TYPES.get(detected_mime)
|
||||
if not safe_extension:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=(
|
||||
f"{label} must be a PNG, JPEG, WebP, or GIF image "
|
||||
f"(detected {detected_mime or 'unknown type'})"
|
||||
),
|
||||
)
|
||||
|
||||
return safe_extension
|
||||
|
||||
|
||||
class FSAssetsHandler(FSHandler):
|
||||
def __init__(self) -> None:
|
||||
|
||||
@@ -17,7 +17,7 @@ from starlette.datastructures import UploadFile
|
||||
|
||||
from config.config_manager import config_manager as cm
|
||||
from models.base import FILE_NAME_MAX_LENGTH
|
||||
from utils.filesystem import iter_directories, iter_files
|
||||
from utils.filesystem import iter_directories, iter_files, link_or_copy_file
|
||||
|
||||
TAG_REGEX = re.compile(r"\(([^)]+)\)|\[([^]]+)\]")
|
||||
EXTENSION_REGEX = re.compile(r"\.(([a-z]+\.)*\w+)$")
|
||||
@@ -88,6 +88,50 @@ REGIONS = (
|
||||
REGIONS_BY_SHORTCODE = {region[0]: region[1] for region in REGIONS}
|
||||
REGIONS_NAME_KEYS = frozenset(region[1].lower() for region in REGIONS)
|
||||
|
||||
# Maps full REGIONS names to lowercase shortcodes used by metadata providers
|
||||
REGION_NAME_TO_PROVIDER_SHORTCODE: dict[str, str] = {
|
||||
"Australia": "au",
|
||||
"Asia": "asi",
|
||||
"Brazil": "br",
|
||||
"Canada": "ca",
|
||||
"China": "cn",
|
||||
"England": "uk",
|
||||
"Europe": "eu",
|
||||
"Finland": "fi",
|
||||
"France": "fr",
|
||||
"Germany": "de",
|
||||
"Greece": "gr",
|
||||
"Holland": "nl",
|
||||
"Hong Kong": "hk",
|
||||
"Italy": "it",
|
||||
"Japan": "jp",
|
||||
"Korea": "kr",
|
||||
"Netherlands": "nl",
|
||||
"Norway": "no",
|
||||
"Russia": "ru",
|
||||
"Spain": "sp",
|
||||
"Sweden": "se",
|
||||
"Taiwan": "tw",
|
||||
"USA": "us",
|
||||
"World": "wor",
|
||||
}
|
||||
|
||||
_REGION_NAME_TO_PROVIDER_SHORTCODE_CI = {
|
||||
k.lower(): v for k, v in REGION_NAME_TO_PROVIDER_SHORTCODE.items()
|
||||
}
|
||||
|
||||
|
||||
def region_name_to_provider_shortcode(region_name: str | None) -> str | None:
|
||||
"""Look up a provider shortcode for a region name (case-insensitive).
|
||||
|
||||
ROM filename parsing can leave region names in their raw casing
|
||||
(e.g. "europe", "EUROPE"), so callers must normalize before lookup.
|
||||
"""
|
||||
if not region_name:
|
||||
return None
|
||||
return _REGION_NAME_TO_PROVIDER_SHORTCODE_CI.get(region_name.lower())
|
||||
|
||||
|
||||
LANGUAGES_BY_SHORTCODE = {lang[0]: lang[1] for lang in LANGUAGES}
|
||||
LANGUAGES_NAME_KEYS = frozenset(lang[1].lower() for lang in LANGUAGES)
|
||||
|
||||
@@ -108,8 +152,6 @@ class FSHandler:
|
||||
self.base_path = Path(base_path).resolve()
|
||||
self._locks: dict[str, asyncio.Lock] = {}
|
||||
self._lock_mutex = asyncio.Lock()
|
||||
|
||||
# Create base directory synchronously during initialization
|
||||
self.base_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
async def _get_file_lock(self, file_path: str) -> asyncio.Lock:
|
||||
@@ -223,22 +265,24 @@ class FSHandler:
|
||||
return match.group(0) if match else ""
|
||||
|
||||
def exclude_single_files(self, files: list[str]) -> list[str]:
|
||||
excluded_extensions = cm.get_config().EXCLUDED_SINGLE_EXT
|
||||
excluded_names = cm.get_config().EXCLUDED_SINGLE_FILES
|
||||
cnfg = cm.get_config()
|
||||
excluded_extensions = cnfg.EXCLUDED_SINGLE_EXT
|
||||
excluded_names = cnfg.EXCLUDED_SINGLE_FILES
|
||||
excluded_files: list[str] = []
|
||||
|
||||
for file_name in files:
|
||||
# Split the file name to get the extension.
|
||||
ext = self.parse_file_extension(file_name)
|
||||
file_name_lower = file_name.lower()
|
||||
|
||||
# Exclude the file if it has no extension or the extension is in the excluded list.
|
||||
if ext and ext.lower() in excluded_extensions:
|
||||
# Check whether the filename ends with any excluded extension entry.
|
||||
if any(file_name_lower.endswith("." + ext) for ext in excluded_extensions):
|
||||
excluded_files.append(file_name)
|
||||
continue
|
||||
|
||||
# Additionally, check if the file name mathes a pattern in the excluded list.
|
||||
for name in excluded_names:
|
||||
if file_name == name or fnmatch.fnmatch(file_name, name):
|
||||
excluded_files.append(file_name)
|
||||
# Check if the file name matches a pattern in the excluded list.
|
||||
if file_name in excluded_names or any(
|
||||
fnmatch.fnmatch(file_name, name) for name in excluded_names
|
||||
):
|
||||
excluded_files.append(file_name)
|
||||
|
||||
# Return files that are not in the filtered list.
|
||||
return [f for f in files if f not in excluded_files]
|
||||
@@ -454,13 +498,21 @@ class FSHandler:
|
||||
|
||||
return await open_file(full_path, "rb")
|
||||
|
||||
async def copy_file(self, source_full_path: Path, dest_path: str) -> None:
|
||||
async def copy_file(
|
||||
self,
|
||||
source_full_path: Path,
|
||||
dest_path: str,
|
||||
allow_link: bool = False,
|
||||
) -> None:
|
||||
"""
|
||||
Copy a file from source to destination.
|
||||
|
||||
Args:
|
||||
source_full_path: Absolute path to the source file
|
||||
dest_path: Relative path to the destination file
|
||||
allow_link: Try a hardlink first and fall back to
|
||||
a copy when the link isn't possible (cross-device,
|
||||
unsupported filesystem, etc.)
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If source file does not exist
|
||||
@@ -485,7 +537,10 @@ class FSHandler:
|
||||
# Create destination directory if needed
|
||||
dest_parent_anyio_path = AnyioPath(str(dest_full_path.parent))
|
||||
await dest_parent_anyio_path.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(str(source_full_path), str(dest_full_path))
|
||||
if allow_link:
|
||||
link_or_copy_file(source_full_path, dest_full_path)
|
||||
else:
|
||||
shutil.copy2(str(source_full_path), str(dest_full_path))
|
||||
|
||||
async def move_file_or_folder(self, source_path: str, dest_path: str) -> None:
|
||||
"""
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import binascii
|
||||
import hashlib
|
||||
import os
|
||||
|
||||
from config import LIBRARY_BASE_PATH
|
||||
from config.config_manager import config_manager as cm
|
||||
@@ -17,9 +16,9 @@ class FSFirmwareHandler(FSHandler):
|
||||
def get_firmware_fs_structure(self, fs_slug: str) -> str:
|
||||
cnfg = cm.get_config()
|
||||
return (
|
||||
f"{cnfg.FIRMWARE_FOLDER_NAME}/{fs_slug}"
|
||||
if os.path.exists(cnfg.HIGH_PRIO_STRUCTURE_PATH)
|
||||
else f"{fs_slug}/{cnfg.FIRMWARE_FOLDER_NAME}"
|
||||
f"{fs_slug}/{cnfg.FIRMWARE_FOLDER_NAME}"
|
||||
if cnfg.has_structure_path_b
|
||||
else f"{cnfg.FIRMWARE_FOLDER_NAME}/{fs_slug}"
|
||||
)
|
||||
|
||||
async def get_firmware(self, platform_fs_slug: str):
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import functools
|
||||
|
||||
from config import LAUNCHBOX_BASE_PATH
|
||||
from handler.filesystem.base_handler import FSHandler
|
||||
|
||||
|
||||
class FSLaunchboxHandler(FSHandler):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(base_path=LAUNCHBOX_BASE_PATH)
|
||||
|
||||
|
||||
@functools.cache
|
||||
def get_fs_launchbox_handler() -> FSLaunchboxHandler:
|
||||
"""Lazily instantiate the LaunchBox handler on first use.
|
||||
|
||||
Deferred so that startup doesn't fail when the LaunchBox feature is
|
||||
unconfigured or its base path is not writable.
|
||||
"""
|
||||
return FSLaunchboxHandler()
|
||||
@@ -34,48 +34,37 @@ class FSPlatformsHandler(FSHandler):
|
||||
"""Detects the library structure type.
|
||||
|
||||
Returns:
|
||||
"LibraryStructure.A" for Structure A (roms/{platform})
|
||||
"LibraryStructure.B" for Structure B ({platform}/roms)
|
||||
None if no structure detected
|
||||
"LibraryStructure.B" for Structure B ({platform}/roms) when any
|
||||
platform has a roms subfolder.
|
||||
"LibraryStructure.A" for Structure A (roms/{platform}) when the
|
||||
top-level roms folder exists.
|
||||
None if no structure detected.
|
||||
"""
|
||||
cnfg = cm.get_config()
|
||||
|
||||
# Check if the roms folder exists (Structure A indicator)
|
||||
if cnfg.has_structure_path_b:
|
||||
return LibraryStructure.B
|
||||
|
||||
roms_path = os.path.join(LIBRARY_BASE_PATH, cnfg.ROMS_FOLDER_NAME)
|
||||
if os.path.exists(roms_path):
|
||||
return LibraryStructure.A
|
||||
|
||||
# Check if any platform folders with roms subfolders exist (Structure B)
|
||||
try:
|
||||
library_contents = os.listdir(LIBRARY_BASE_PATH)
|
||||
for item in library_contents:
|
||||
item_path = os.path.join(LIBRARY_BASE_PATH, item)
|
||||
roms_subfolder = os.path.join(item_path, cnfg.ROMS_FOLDER_NAME)
|
||||
if os.path.isdir(item_path) and os.path.exists(roms_subfolder):
|
||||
return LibraryStructure.B
|
||||
except (OSError, FileNotFoundError):
|
||||
pass
|
||||
|
||||
return None
|
||||
|
||||
def get_platforms_directory(self) -> str:
|
||||
cnfg = cm.get_config()
|
||||
|
||||
# Fallback to config hint when detection is inconclusive
|
||||
return (
|
||||
cnfg.ROMS_FOLDER_NAME
|
||||
if os.path.exists(cnfg.HIGH_PRIO_STRUCTURE_PATH)
|
||||
else ""
|
||||
)
|
||||
return "" if cnfg.has_structure_path_b else cnfg.ROMS_FOLDER_NAME
|
||||
|
||||
def get_platform_fs_structure(self, fs_slug: str) -> str:
|
||||
cnfg = cm.get_config()
|
||||
|
||||
# Fallback to config hint when detection is inconclusive
|
||||
return (
|
||||
f"{cnfg.ROMS_FOLDER_NAME}/{fs_slug}"
|
||||
if os.path.exists(cnfg.HIGH_PRIO_STRUCTURE_PATH)
|
||||
else f"{fs_slug}/{cnfg.ROMS_FOLDER_NAME}"
|
||||
f"{fs_slug}/{cnfg.ROMS_FOLDER_NAME}"
|
||||
if cnfg.has_structure_path_b
|
||||
else f"{cnfg.ROMS_FOLDER_NAME}/{fs_slug}"
|
||||
)
|
||||
|
||||
async def add_platform(self, fs_slug: str) -> None:
|
||||
|
||||
@@ -19,6 +19,34 @@ from utils.validation import validate_url_for_http_request
|
||||
|
||||
from .base_handler import CoverSize, FSHandler
|
||||
|
||||
LOCAL_FILE_SCHEMES = ("file://", "launchbox-file://")
|
||||
|
||||
|
||||
def _resolve_local_file_uri(uri: str) -> Path | None:
|
||||
"""Resolve a local-file URI to an absolute Path, or None if unsafe/unknown.
|
||||
|
||||
`file://` resolves under the ROM library root. `launchbox-file://` resolves
|
||||
under the LaunchBox data root, since LaunchBox metadata produces paths
|
||||
relative to `/romm/launchbox`, which is not the same as the library root.
|
||||
"""
|
||||
from handler.filesystem import fs_rom_handler, get_fs_launchbox_handler
|
||||
|
||||
if uri.startswith("launchbox-file://"):
|
||||
try:
|
||||
return get_fs_launchbox_handler().validate_path(
|
||||
uri[len("launchbox-file://") :]
|
||||
)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
if uri.startswith("file://"):
|
||||
try:
|
||||
return fs_rom_handler.validate_path(uri[len("file://") :])
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _content_type_essence(header_value: str) -> str:
|
||||
"""Return the MIME type token (before parameters), lowercased."""
|
||||
@@ -95,27 +123,23 @@ class FSResourcesHandler(FSHandler):
|
||||
cover_file = f"{entity.fs_resources_path}/cover"
|
||||
await self.make_directory(cover_file)
|
||||
|
||||
# Handle file:// URLs for gamelist.xml
|
||||
if url_cover.startswith("file://"):
|
||||
# Handle local-file URIs from metadata handlers (gamelist, LaunchBox)
|
||||
if url_cover.startswith(LOCAL_FILE_SCHEMES):
|
||||
try:
|
||||
from handler.filesystem import fs_rom_handler
|
||||
|
||||
validated = fs_rom_handler.validate_path(
|
||||
url_cover[7:] # Remove "file://" prefix
|
||||
)
|
||||
if await AnyioPath(validated).exists():
|
||||
# Copy the file to the resources directory
|
||||
dest_path = f"{cover_file}/{size.value}.png"
|
||||
await self.copy_file(validated, dest_path)
|
||||
|
||||
if ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP:
|
||||
self.image_converter.convert_to_webp(
|
||||
self.validate_path(f"{cover_file}/{size.value}.png"),
|
||||
force=True,
|
||||
)
|
||||
else:
|
||||
log.warning(f"Cover file not found: {str(validated)}")
|
||||
resolved = _resolve_local_file_uri(url_cover)
|
||||
if resolved is None or not await AnyioPath(resolved).exists():
|
||||
log.warning(f"Cover file not found: {url_cover}")
|
||||
return None
|
||||
dest_path = f"{cover_file}/{size.value}.png"
|
||||
# Small-size covers get resized in place, which would mutate
|
||||
# the user's source image if the destination were a hardlink.
|
||||
await self.copy_file(resolved, dest_path, allow_link=False)
|
||||
|
||||
if ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP:
|
||||
self.image_converter.convert_to_webp(
|
||||
self.validate_path(f"{cover_file}/{size.value}.png"),
|
||||
force=True,
|
||||
)
|
||||
except Exception as exc:
|
||||
log.error(f"Unable to copy cover file {url_cover}: {str(exc)}")
|
||||
return None
|
||||
@@ -275,20 +299,16 @@ class FSResourcesHandler(FSHandler):
|
||||
screenshot_path = f"{rom.fs_resources_path}/screenshots"
|
||||
await self.make_directory(screenshot_path)
|
||||
|
||||
# Handle file:// URLs for gamelist.xml
|
||||
if url_screenhot.startswith("file://"):
|
||||
# Handle local-file URIs from metadata handlers (gamelist, LaunchBox)
|
||||
if url_screenhot.startswith(LOCAL_FILE_SCHEMES):
|
||||
try:
|
||||
from handler.filesystem import fs_rom_handler
|
||||
|
||||
validated = fs_rom_handler.validate_path(
|
||||
url_screenhot[7:] # Remove "file://" prefix
|
||||
)
|
||||
if await AnyioPath(validated).exists():
|
||||
# Copy the file to the resources directory
|
||||
await self.copy_file(validated, f"{screenshot_path}/{idx}.jpg")
|
||||
else:
|
||||
log.warning(f"Screenshot file not found: {str(validated)}")
|
||||
resolved = _resolve_local_file_uri(url_screenhot)
|
||||
if resolved is None or not await AnyioPath(resolved).exists():
|
||||
log.warning(f"Screenshot file not found: {url_screenhot}")
|
||||
return None
|
||||
await self.copy_file(
|
||||
resolved, f"{screenshot_path}/{idx}.jpg", allow_link=True
|
||||
)
|
||||
except Exception as exc:
|
||||
log.error(f"Unable to copy screenshot file {url_screenhot}: {str(exc)}")
|
||||
return None
|
||||
@@ -395,20 +415,16 @@ class FSResourcesHandler(FSHandler):
|
||||
manual_path = f"{rom.fs_resources_path}/manual"
|
||||
await self.make_directory(manual_path)
|
||||
|
||||
# Handle file:// URLs for gamelist.xml
|
||||
if url_manual.startswith("file://"):
|
||||
# Handle local-file URIs from metadata handlers (gamelist, LaunchBox)
|
||||
if url_manual.startswith(LOCAL_FILE_SCHEMES):
|
||||
try:
|
||||
from handler.filesystem import fs_rom_handler
|
||||
|
||||
validated = fs_rom_handler.validate_path(
|
||||
url_manual[7:] # Remove "file://" prefix
|
||||
)
|
||||
if await AnyioPath(validated).exists():
|
||||
# Copy the file to the resources directory
|
||||
await self.copy_file(validated, f"{manual_path}/{rom.id}.pdf")
|
||||
else:
|
||||
log.warning(f"Manual file not found: {str(validated)}")
|
||||
resolved = _resolve_local_file_uri(url_manual)
|
||||
if resolved is None or not await AnyioPath(resolved).exists():
|
||||
log.warning(f"Manual file not found: {url_manual}")
|
||||
return None
|
||||
await self.copy_file(
|
||||
resolved, f"{manual_path}/{rom.id}.pdf", allow_link=True
|
||||
)
|
||||
except Exception as exc:
|
||||
log.error(f"Unable to copy manual file {url_manual}: {str(exc)}")
|
||||
return None
|
||||
@@ -542,17 +558,12 @@ class FSResourcesHandler(FSHandler):
|
||||
# Ensure destination directory exists
|
||||
await self.make_directory(directory)
|
||||
|
||||
# Handle file:// URLs for gamelist.xml
|
||||
if url_media.startswith("file://"):
|
||||
# Handle local-file URIs from metadata handlers (gamelist, LaunchBox)
|
||||
if url_media.startswith(LOCAL_FILE_SCHEMES):
|
||||
try:
|
||||
from handler.filesystem import fs_rom_handler
|
||||
|
||||
validated = fs_rom_handler.validate_path(
|
||||
url_media[7:] # Remove "file://" prefix
|
||||
)
|
||||
file_path = AnyioPath(validated)
|
||||
if await file_path.exists():
|
||||
await self.copy_file(Path(str(file_path)), dest_path)
|
||||
resolved = _resolve_local_file_uri(url_media)
|
||||
if resolved is not None and await AnyioPath(resolved).exists():
|
||||
await self.copy_file(resolved, dest_path, allow_link=True)
|
||||
except Exception as exc:
|
||||
log.error(f"Unable to copy media file {url_media}: {str(exc)}")
|
||||
return None
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
import binascii
|
||||
import bz2
|
||||
import fnmatch
|
||||
@@ -5,12 +6,13 @@ import hashlib
|
||||
import os
|
||||
import re
|
||||
import tarfile
|
||||
import threading
|
||||
import zipfile
|
||||
import zlib
|
||||
from collections.abc import Callable, Iterator
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import IO, Any, Final, Literal, TypedDict, cast
|
||||
from typing import IO, Any, Final, Literal, TypedDict
|
||||
|
||||
import magic
|
||||
import zipfile_inflate64 # trunk-ignore(ruff/F401): Patches zipfile to support Enhanced Deflate
|
||||
@@ -64,6 +66,7 @@ CHD_VERSION_LENGTH: Final = 4 # Version is a uint32
|
||||
CHD_V5_SHA1_OFFSET: Final = 84 # Combined raw+meta SHA1 offset in v5
|
||||
CHD_V5_SHA1_LENGTH: Final = 20 # SHA1 is 20 bytes
|
||||
CHD_V5_VERSION: Final = 5 # CHD v5 identifier
|
||||
CHD_MIME_TYPE: Final = "application/x-mame-chd"
|
||||
|
||||
NON_HASHABLE_PLATFORMS = frozenset(
|
||||
(
|
||||
@@ -97,6 +100,8 @@ NON_HASHABLE_PLATFORMS = frozenset(
|
||||
)
|
||||
|
||||
FILE_READ_CHUNK_SIZE = 1024 * 8
|
||||
_MIME_DETECTOR = magic.Magic(mime=True)
|
||||
_MIME_DETECTOR_LOCK = threading.Lock()
|
||||
|
||||
|
||||
class FSRom(TypedDict):
|
||||
@@ -114,11 +119,15 @@ class FileHash(TypedDict):
|
||||
crc_hash: str
|
||||
md5_hash: str
|
||||
sha1_hash: str
|
||||
chd_sha1_hash: str
|
||||
|
||||
|
||||
def is_compressed_file(file_path: str) -> bool:
|
||||
mime = magic.Magic(mime=True)
|
||||
file_type = mime.from_file(file_path)
|
||||
try:
|
||||
with _MIME_DETECTOR_LOCK:
|
||||
file_type = _MIME_DETECTOR.from_file(file_path)
|
||||
except magic.MagicException:
|
||||
file_type = ""
|
||||
|
||||
return file_type in COMPRESSED_MIME_TYPES or file_path.lower().endswith(
|
||||
tuple(COMPRESSED_FILE_EXTENSIONS)
|
||||
@@ -189,7 +198,19 @@ def read_bz2_file(file_path: Path) -> Iterator[bytes]:
|
||||
yield chunk
|
||||
|
||||
|
||||
def extract_chd_hash(file_path: Path) -> str | None:
|
||||
def is_chd_file(file_path: Path) -> bool:
|
||||
"""Return True if the file is a CHD by extension or libmagic-detected MIME type."""
|
||||
if file_path.suffix.lower() == ".chd":
|
||||
return True
|
||||
|
||||
try:
|
||||
with _MIME_DETECTOR_LOCK:
|
||||
return _MIME_DETECTOR.from_file(file_path) == CHD_MIME_TYPE
|
||||
except (OSError, magic.MagicException):
|
||||
return False
|
||||
|
||||
|
||||
def extract_chd_hash(file_path: Path) -> str:
|
||||
"""
|
||||
Extract the embedded SHA1 hash from a CHD (Compressed Hunks of Data) v5 file header.
|
||||
|
||||
@@ -215,7 +236,9 @@ def extract_chd_hash(file_path: Path) -> str | None:
|
||||
file_path: Path to the CHD file
|
||||
|
||||
Returns:
|
||||
SHA1 hash as hex string, or None if file is not a valid CHD v5 file or parsing fails
|
||||
The embedded SHA1 hash as a hex string for a valid CHD v5 file, or an
|
||||
empty string if the file is invalid, uses an unsupported CHD version,
|
||||
is truncated, or cannot be read due to an I/O error.
|
||||
"""
|
||||
try:
|
||||
with open(file_path, "rb") as f:
|
||||
@@ -227,7 +250,7 @@ def extract_chd_hash(file_path: Path) -> str | None:
|
||||
len(header) < CHD_MIN_HEADER_LENGTH
|
||||
or header[:CHD_SIGNATURE_LENGTH] != CHD_SIGNATURE
|
||||
):
|
||||
return None
|
||||
return ""
|
||||
|
||||
# Extract and verify version (big-endian uint32)
|
||||
version_end = CHD_VERSION_OFFSET + CHD_VERSION_LENGTH
|
||||
@@ -235,44 +258,16 @@ def extract_chd_hash(file_path: Path) -> str | None:
|
||||
|
||||
# Only support v5 CHD files
|
||||
if version != CHD_V5_VERSION:
|
||||
return None
|
||||
return ""
|
||||
|
||||
# Extract combined raw+meta SHA1 from v5 header
|
||||
sha1_end = CHD_V5_SHA1_OFFSET + CHD_V5_SHA1_LENGTH
|
||||
if len(header) < sha1_end:
|
||||
return None
|
||||
return ""
|
||||
sha1_bytes = header[CHD_V5_SHA1_OFFSET:sha1_end]
|
||||
return sha1_bytes.hex()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
class CHDHashWrapper:
|
||||
"""
|
||||
Wrapper class that mimics hashlib hash objects but returns a pre-computed hash.
|
||||
|
||||
This class provides a hashlib-compatible interface for pre-computed hashes
|
||||
extracted from CHD v5 file headers. It implements the same methods and attributes
|
||||
as hashlib hash objects (digest(), hexdigest(), update(), and name).
|
||||
"""
|
||||
|
||||
def __init__(self, hash_hex: str, name: str):
|
||||
self.hash_hex = hash_hex
|
||||
self.name = name
|
||||
# Store the digest as bytes
|
||||
self._digest = bytes.fromhex(hash_hex)
|
||||
|
||||
def hexdigest(self) -> str:
|
||||
"""Return the hash as a hexadecimal string."""
|
||||
return self.hash_hex
|
||||
|
||||
def digest(self) -> bytes:
|
||||
"""Return the hash as bytes."""
|
||||
return self._digest
|
||||
|
||||
def update(self, data: bytes | bytearray) -> None:
|
||||
"""No-op update method for compatibility with hashlib interface."""
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def category_matches(category: str, path_parts: list[str]):
|
||||
@@ -313,9 +308,9 @@ class FSRomsHandler(FSHandler):
|
||||
def get_roms_fs_structure(self, fs_slug: str) -> str:
|
||||
cnfg = cm.get_config()
|
||||
return (
|
||||
f"{cnfg.ROMS_FOLDER_NAME}/{fs_slug}"
|
||||
if os.path.exists(cnfg.HIGH_PRIO_STRUCTURE_PATH)
|
||||
else f"{fs_slug}/{cnfg.ROMS_FOLDER_NAME}"
|
||||
f"{fs_slug}/{cnfg.ROMS_FOLDER_NAME}"
|
||||
if cnfg.has_structure_path_b
|
||||
else f"{cnfg.ROMS_FOLDER_NAME}/{fs_slug}"
|
||||
)
|
||||
|
||||
def parse_tags(self, fs_name: str) -> ParsedTags:
|
||||
@@ -379,13 +374,25 @@ class FSRomsHandler(FSHandler):
|
||||
|
||||
def exclude_multi_roms(self, roms: list[str]) -> list[str]:
|
||||
excluded_names = cm.get_config().EXCLUDED_MULTI_FILES
|
||||
filtered_files: list = []
|
||||
normalized_patterns = [
|
||||
excluded_name.lower().strip() for excluded_name in excluded_names
|
||||
]
|
||||
|
||||
kept_roms: list[str] = []
|
||||
for rom in roms:
|
||||
if rom in excluded_names:
|
||||
filtered_files.append(rom)
|
||||
normalized_rom_name = rom.strip().lower()
|
||||
if normalized_rom_name in normalized_patterns:
|
||||
continue
|
||||
|
||||
return [f for f in roms if f not in filtered_files]
|
||||
if any(
|
||||
fnmatch.fnmatch(normalized_rom_name, pattern)
|
||||
for pattern in normalized_patterns
|
||||
):
|
||||
continue
|
||||
|
||||
kept_roms.append(rom)
|
||||
|
||||
return kept_roms
|
||||
|
||||
def _build_rom_file(
|
||||
self, rom: Rom, rom_path: Path, file_name: str, file_hash: FileHash
|
||||
@@ -422,6 +429,7 @@ class FSRomsHandler(FSHandler):
|
||||
crc_hash=file_hash["crc_hash"],
|
||||
md5_hash=file_hash["md5_hash"],
|
||||
sha1_hash=file_hash["sha1_hash"],
|
||||
chd_sha1_hash=file_hash["chd_sha1_hash"],
|
||||
)
|
||||
|
||||
async def get_rom_files(
|
||||
@@ -441,33 +449,56 @@ class FSRomsHandler(FSHandler):
|
||||
rom.platform_slug not in NON_HASHABLE_PLATFORMS and calculate_hashes
|
||||
)
|
||||
|
||||
excluded_file_names = cm.get_config().EXCLUDED_MULTI_PARTS_FILES
|
||||
excluded_file_exts = cm.get_config().EXCLUDED_MULTI_PARTS_EXT
|
||||
cnfg = cm.get_config()
|
||||
excluded_file_names = cnfg.EXCLUDED_MULTI_PARTS_FILES
|
||||
excluded_file_exts = cnfg.EXCLUDED_MULTI_PARTS_EXT
|
||||
|
||||
rom_crc_c = 0
|
||||
rom_md5_h = hashlib.md5(usedforsecurity=False) if calculate_hashes else None
|
||||
rom_sha1_h = hashlib.sha1(usedforsecurity=False) if calculate_hashes else None
|
||||
rom_ra_h = ""
|
||||
|
||||
rom_dir = Path(abs_fs_path, rom.fs_name)
|
||||
# Check if rom is a multi-part rom
|
||||
if await AnyioPath(f"{abs_fs_path}/{rom.fs_name}").is_dir():
|
||||
# Calculate the RA hash if the platform has a slug that matches a known RA slug
|
||||
if calculate_hashes:
|
||||
ra_platform = meta_ra_handler.get_platform(rom.platform_slug)
|
||||
if ra_platform and ra_platform["ra_id"]:
|
||||
# RAHasher can't process CHD files via the /* wildcard and instead expects
|
||||
# track files (bin/cue/etc.). For CHD-only folders, find the largest
|
||||
# CHD and pass it directly, matching single-file CHD behaviour.
|
||||
|
||||
def _largest_chd_file() -> Path | None:
|
||||
chds = [f for f in rom_dir.iterdir() if is_chd_file(f)]
|
||||
sorted_chds = sorted(
|
||||
chds, key=lambda f: f.stat().st_size, reverse=True
|
||||
)
|
||||
return sorted_chds[0] if sorted_chds else None
|
||||
|
||||
chd_file = await asyncio.to_thread(_largest_chd_file)
|
||||
ra_path = (
|
||||
str(chd_file)
|
||||
if chd_file and chd_file.is_file()
|
||||
else f"{abs_fs_path}/{rom.fs_name}/*"
|
||||
)
|
||||
rom_ra_h = await RAHasherService().calculate_hash(
|
||||
ra_platform,
|
||||
f"{abs_fs_path}/{rom.fs_name}/*",
|
||||
ra_path,
|
||||
)
|
||||
|
||||
for f_path, file_name in iter_files(
|
||||
f"{abs_fs_path}/{rom.fs_name}", recursive=True
|
||||
):
|
||||
# Check if file is excluded
|
||||
ext = self.parse_file_extension(file_name)
|
||||
if ext in excluded_file_exts:
|
||||
# Check if file is excluded by extension.
|
||||
f_rom_dir = Path(f_path, rom.fs_name)
|
||||
file_name_lower = file_name.lower()
|
||||
if any(
|
||||
file_name_lower.endswith("." + ext) for ext in excluded_file_exts
|
||||
):
|
||||
continue
|
||||
|
||||
# Check if the file name matches a pattern in the excluded list.
|
||||
if any(
|
||||
file_name == exc_name or fnmatch.fnmatch(file_name, exc_name)
|
||||
for exc_name in excluded_file_names
|
||||
@@ -482,7 +513,8 @@ class FSRomsHandler(FSHandler):
|
||||
if is_top_level:
|
||||
# Include this file in the main ROM hash calculation
|
||||
crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h = (
|
||||
self._calculate_rom_hashes(
|
||||
await asyncio.to_thread(
|
||||
self._calculate_rom_hashes,
|
||||
Path(f_path, file_name),
|
||||
rom_crc_c,
|
||||
rom_md5_h,
|
||||
@@ -491,7 +523,8 @@ class FSRomsHandler(FSHandler):
|
||||
)
|
||||
else:
|
||||
# Calculate individual file hash only
|
||||
crc_c, _, md5_h, _, sha1_h, _ = self._calculate_rom_hashes(
|
||||
crc_c, _, md5_h, _, sha1_h, _ = await asyncio.to_thread(
|
||||
self._calculate_rom_hashes,
|
||||
Path(f_path, file_name),
|
||||
0,
|
||||
hashlib.md5(usedforsecurity=False),
|
||||
@@ -514,12 +547,18 @@ class FSRomsHandler(FSHandler):
|
||||
if sha1_h.digest() != DEFAULT_SHA1_H_DIGEST
|
||||
else ""
|
||||
),
|
||||
chd_sha1_hash=(
|
||||
extract_chd_hash(f_rom_dir)
|
||||
if is_chd_file(f_rom_dir)
|
||||
else ""
|
||||
),
|
||||
)
|
||||
else:
|
||||
file_hash = FileHash(
|
||||
crc_hash="",
|
||||
md5_hash="",
|
||||
sha1_hash="",
|
||||
chd_sha1_hash="",
|
||||
)
|
||||
|
||||
rom_files.append(
|
||||
@@ -533,8 +572,12 @@ class FSRomsHandler(FSHandler):
|
||||
elif hashable_platform:
|
||||
try:
|
||||
crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h = (
|
||||
self._calculate_rom_hashes(
|
||||
Path(abs_fs_path, rom.fs_name), rom_crc_c, rom_md5_h, rom_sha1_h
|
||||
await asyncio.to_thread(
|
||||
self._calculate_rom_hashes,
|
||||
Path(abs_fs_path, rom.fs_name),
|
||||
rom_crc_c,
|
||||
rom_md5_h,
|
||||
rom_sha1_h,
|
||||
)
|
||||
)
|
||||
except zlib.error:
|
||||
@@ -561,6 +604,9 @@ class FSRomsHandler(FSHandler):
|
||||
if sha1_h.digest() != DEFAULT_SHA1_H_DIGEST
|
||||
else ""
|
||||
),
|
||||
chd_sha1_hash=(
|
||||
extract_chd_hash(rom_dir) if is_chd_file(rom_dir) else ""
|
||||
),
|
||||
)
|
||||
rom_files.append(
|
||||
self._build_rom_file(
|
||||
@@ -575,6 +621,7 @@ class FSRomsHandler(FSHandler):
|
||||
crc_hash="",
|
||||
md5_hash="",
|
||||
sha1_hash="",
|
||||
chd_sha1_hash="",
|
||||
)
|
||||
rom_files.append(
|
||||
self._build_rom_file(
|
||||
@@ -609,9 +656,12 @@ class FSRomsHandler(FSHandler):
|
||||
rom_sha1_h: Any,
|
||||
) -> tuple[int, int, Any, Any, Any, Any]:
|
||||
extension = Path(file_path).suffix.lower()
|
||||
mime = magic.Magic(mime=True)
|
||||
try:
|
||||
file_type = mime.from_file(file_path)
|
||||
try:
|
||||
with _MIME_DETECTOR_LOCK:
|
||||
file_type = _MIME_DETECTOR.from_file(file_path)
|
||||
except magic.MagicException:
|
||||
file_type = ""
|
||||
|
||||
crc_c = 0
|
||||
md5_h = hashlib.md5(usedforsecurity=False)
|
||||
@@ -651,17 +701,6 @@ class FSRomsHandler(FSHandler):
|
||||
for chunk in read_bz2_file(file_path):
|
||||
update_hashes(chunk)
|
||||
|
||||
elif extension == ".chd" or file_type == "application/x-mame-chd":
|
||||
chd_hash = extract_chd_hash(file_path)
|
||||
if chd_hash:
|
||||
sha1_h = cast(Any, CHDHashWrapper(chd_hash, name="sha1"))
|
||||
rom_sha1_h = cast(Any, CHDHashWrapper(chd_hash, name="sha1"))
|
||||
else:
|
||||
# Not a valid v5 CHD, treat as basic file
|
||||
# This ensures CRC32 and MD5 are still calculated for non-v5 CHDs
|
||||
for chunk in read_basic_file(file_path):
|
||||
update_hashes(chunk)
|
||||
|
||||
else:
|
||||
for chunk in read_basic_file(file_path):
|
||||
update_hashes(chunk)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import functools
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -110,3 +111,13 @@ class FSSyncHandler(FSHandler):
|
||||
f"Path {full_path} is outside the sync base directory"
|
||||
) from e
|
||||
path.unlink()
|
||||
|
||||
|
||||
@functools.cache
|
||||
def get_fs_sync_handler() -> FSSyncHandler:
|
||||
"""Lazily instantiate the sync folder handler on first use.
|
||||
|
||||
Deferred so that startup doesn't fail when sync is unconfigured or its
|
||||
base path is not writable.
|
||||
"""
|
||||
return FSSyncHandler()
|
||||
@@ -71,6 +71,10 @@ SENSITIVE_KEYS = {
|
||||
"devpassword",
|
||||
"y",
|
||||
}
|
||||
SENSITIVE_KEYS_REGEX = re.compile(
|
||||
rf"({'|'.join(re.escape(k) for k in SENSITIVE_KEYS)})=[^&\s\"]*",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
# This caches results to avoid repeated normalization of the same search term
|
||||
@@ -102,6 +106,7 @@ def _normalize_search_term(
|
||||
def strip_sensitive_query_params(
|
||||
url: str, sensitive_keys: set[str] = SENSITIVE_KEYS
|
||||
) -> str:
|
||||
"""Remove sensitive query parameters from a URL."""
|
||||
parsed = urlparse(url)
|
||||
qsl = parse_qsl(parsed.query, keep_blank_values=True)
|
||||
|
||||
@@ -112,6 +117,18 @@ def strip_sensitive_query_params(
|
||||
return urlunparse(parsed._replace(query=new_query))
|
||||
|
||||
|
||||
def restore_sensitive_query_params(url: str, params: dict[str, str]) -> str:
|
||||
"""Add back key/value pairs previously stripped by strip_sensitive_query_params."""
|
||||
parsed = urlparse(url)
|
||||
qsl = parse_qsl(parsed.query, keep_blank_values=True)
|
||||
|
||||
existing = {k.lower() for k in params}
|
||||
filtered = [(k, v) for k, v in qsl if k.lower() not in existing]
|
||||
|
||||
new_query = urlencode(filtered + list(params.items()))
|
||||
return urlunparse(parsed._replace(query=new_query))
|
||||
|
||||
|
||||
class MetadataHandler(abc.ABC):
|
||||
SEARCH_TERM_SPLIT_PATTERN = re.compile(r"[\:\-\/]")
|
||||
SEARCH_TERM_NORMALIZER = re.compile(r"\s*[:-]\s+")
|
||||
|
||||
@@ -1 +1 @@
|
||||
https://howlongtobeat.com/api/find
|
||||
https://howlongtobeat.com/api/bleed
|
||||
@@ -1,5 +1,6 @@
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Final, NotRequired, TypedDict
|
||||
@@ -19,6 +20,17 @@ from .base_handler import BaseRom, MetadataHandler
|
||||
|
||||
# https://github.com/Aloshi/EmulationStation/blob/master/GAMELISTS.md#reference
|
||||
|
||||
# ES-DE writes a top-level <alternativeEmulator> sibling to <gameList>, which produces
|
||||
# invalid multi-root XML. These patterns strip both self-closing and paired forms so the
|
||||
# remaining document can be parsed.
|
||||
ALTERNATIVE_EMULATOR_SELF_CLOSING_RE: Final = re.compile(
|
||||
r"<alternativeEmulator\b[^>]*/>"
|
||||
)
|
||||
ALTERNATIVE_EMULATOR_PAIRED_RE: Final = re.compile(
|
||||
r"<alternativeEmulator\b[^>]*>.*?</alternativeEmulator>",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
|
||||
def get_preferred_media_types() -> list[MetadataMediaType]:
|
||||
"""Get preferred media types from config"""
|
||||
@@ -104,6 +116,17 @@ def _make_file_uri(platform_dir: str, raw_text: str) -> str:
|
||||
return f"file://{joined_path.as_posix()}"
|
||||
|
||||
|
||||
def _split_comma_separated_values(value: str | None) -> list[str]:
|
||||
"""Split comma separated values into clean list"""
|
||||
|
||||
if not value:
|
||||
return []
|
||||
|
||||
split_values = value.split(",")
|
||||
|
||||
return pydash.compact([item.strip() for item in split_values])
|
||||
|
||||
|
||||
def extract_media_from_gamelist_rom(
|
||||
game: Element, platform: Platform
|
||||
) -> GamelistMetadataMedia:
|
||||
@@ -196,9 +219,18 @@ def extract_metadata_from_gamelist_rom(
|
||||
return GamelistMetadata(
|
||||
rating=rating,
|
||||
first_release_date=first_release_date,
|
||||
companies=pydash.compact([developer, publisher]),
|
||||
franchises=pydash.compact([family]),
|
||||
genres=pydash.compact([genre]),
|
||||
companies=list(
|
||||
dict.fromkeys(
|
||||
pydash.compact(
|
||||
[
|
||||
*_split_comma_separated_values(developer),
|
||||
*_split_comma_separated_values(publisher),
|
||||
]
|
||||
)
|
||||
)
|
||||
),
|
||||
franchises=_split_comma_separated_values(family),
|
||||
genres=_split_comma_separated_values(genre),
|
||||
player_count=players,
|
||||
md5_hash=md5,
|
||||
box3d_path=None,
|
||||
@@ -317,12 +349,25 @@ class GamelistHandler(MetadataHandler):
|
||||
roms_data: dict[str, GamelistRom] = {}
|
||||
|
||||
try:
|
||||
tree = ET.parse(gamelist_path)
|
||||
root = tree.getroot()
|
||||
if root is None:
|
||||
return roms_data
|
||||
xml_content = gamelist_path.read_text(encoding="utf-8", errors="replace")
|
||||
xml_content = ALTERNATIVE_EMULATOR_SELF_CLOSING_RE.sub("", xml_content)
|
||||
xml_content = ALTERNATIVE_EMULATOR_PAIRED_RE.sub("", xml_content)
|
||||
root: Element | None = ET.fromstring(xml_content)
|
||||
except ET.ParseError as e:
|
||||
log.warning(f"Failed to parse gamelist.xml at {gamelist_path}: {e}")
|
||||
root = None
|
||||
except Exception as e:
|
||||
log.error(f"Error reading gamelist.xml at {gamelist_path}: {e}")
|
||||
root = None
|
||||
|
||||
if root is None:
|
||||
return roms_data
|
||||
|
||||
try:
|
||||
for game in root:
|
||||
if game.tag not in ("game", "folder"):
|
||||
continue
|
||||
|
||||
for game in root.findall("game"):
|
||||
path_elem = game.find("path")
|
||||
if path_elem is None or path_elem.text is None:
|
||||
continue
|
||||
@@ -348,12 +393,14 @@ class GamelistHandler(MetadataHandler):
|
||||
desc_elem.text if desc_elem is not None and desc_elem.text else ""
|
||||
)
|
||||
regions = (
|
||||
pydash.compact([region_elem.text])
|
||||
_split_comma_separated_values(region_elem.text)
|
||||
if region_elem is not None
|
||||
else []
|
||||
)
|
||||
languages = (
|
||||
pydash.compact([lang_elem.text]) if lang_elem is not None else []
|
||||
_split_comma_separated_values(lang_elem.text)
|
||||
if lang_elem is not None
|
||||
else []
|
||||
)
|
||||
|
||||
# Build ROM data
|
||||
@@ -396,8 +443,6 @@ class GamelistHandler(MetadataHandler):
|
||||
|
||||
# Cache the parsed data for this platform
|
||||
self._gamelist_cache[cache_key] = roms_data
|
||||
except ET.ParseError as e:
|
||||
log.warning(f"Failed to parse gamelist.xml at {gamelist_path}: {e}")
|
||||
except Exception as e:
|
||||
log.error(f"Error reading gamelist.xml at {gamelist_path}: {e}")
|
||||
|
||||
|
||||
@@ -258,9 +258,16 @@ class HasheousHandler(MetadataHandler):
|
||||
if first_file is None:
|
||||
return fallback_rom
|
||||
|
||||
md5_hash = first_file.md5_hash
|
||||
sha1_hash = first_file.sha1_hash
|
||||
crc_hash = first_file.crc_hash
|
||||
if first_file.chd_sha1_hash:
|
||||
# For CHD files, Hasheous indexes by disc-data SHA1 only.
|
||||
# Raw file MD5/CRC are hashes of the container and won't match.
|
||||
md5_hash = None
|
||||
sha1_hash = first_file.chd_sha1_hash
|
||||
crc_hash = None
|
||||
else:
|
||||
md5_hash = first_file.md5_hash
|
||||
sha1_hash = first_file.sha1_hash
|
||||
crc_hash = first_file.crc_hash
|
||||
|
||||
if not (md5_hash or sha1_hash or crc_hash):
|
||||
log.warning(
|
||||
|
||||
@@ -14,8 +14,10 @@ from adapters.services.igdb_types import (
|
||||
)
|
||||
from config import IGDB_CLIENT_ID, IGDB_CLIENT_SECRET, IS_PYTEST_RUN
|
||||
from config.config_manager import config_manager as cm
|
||||
from handler.filesystem.base_handler import region_name_to_provider_shortcode
|
||||
from handler.redis_handler import async_cache
|
||||
from logger.logger import log
|
||||
from models.rom import Rom
|
||||
from utils.context import ctx_httpx_client
|
||||
|
||||
from .base_handler import (
|
||||
@@ -325,18 +327,22 @@ REGION_TO_IGDB_LOCALE: dict[str, str | None] = {
|
||||
}
|
||||
|
||||
|
||||
def get_igdb_preferred_locale() -> str | None:
|
||||
"""Get IGDB locale from scan.priority.region configuration.
|
||||
def get_igdb_preferred_locale(rom: Rom | None = None) -> str | None:
|
||||
"""Get IGDB locale, preferring the rom's own region tag when available.
|
||||
|
||||
Maps region priority codes to IGDB's game_localizations region identifiers.
|
||||
Returns the first matching region from the priority list, or None for default.
|
||||
Checks the rom's tagged regions first, then falls back to scan.priority.region.
|
||||
|
||||
Returns:
|
||||
IGDB region identifier (e.g., "ja-JP", "EU") or None for default
|
||||
"""
|
||||
config = cm.get_config()
|
||||
if rom is not None and isinstance(rom.regions, list):
|
||||
for region_name in rom.regions:
|
||||
code = region_name_to_provider_shortcode(region_name)
|
||||
if code and code in REGION_TO_IGDB_LOCALE:
|
||||
return REGION_TO_IGDB_LOCALE[code]
|
||||
|
||||
# Check each region in priority order and return first match
|
||||
config = cm.get_config()
|
||||
for region in config.SCAN_REGION_PRIORITY:
|
||||
if region.lower() in REGION_TO_IGDB_LOCALE:
|
||||
return REGION_TO_IGDB_LOCALE[region.lower()]
|
||||
@@ -456,6 +462,7 @@ class IGDBHandler(MetadataHandler):
|
||||
GameType.PORT,
|
||||
GameType.REMAKE,
|
||||
GameType.REMASTER,
|
||||
GameType.STANDALONE_EXPANSION,
|
||||
)
|
||||
game_type_filter = f"& game_type=({','.join(map(str, categories))})"
|
||||
else:
|
||||
@@ -503,14 +510,26 @@ class IGDBHandler(MetadataHandler):
|
||||
limit=self.pagination_limit,
|
||||
)
|
||||
|
||||
if roms_expanded:
|
||||
log.debug(
|
||||
"Searching expanded in games endpoint for expanded game %s",
|
||||
roms_expanded[0]["game"],
|
||||
# Collect all unique game IDs from the expanded search results,
|
||||
# skipping entries without a valid game id.
|
||||
unique_game_ids = list(
|
||||
dict.fromkeys(
|
||||
game_id
|
||||
for r in roms_expanded
|
||||
if (g := r.get("game")) and (game_id := g.get("id")) is not None
|
||||
)
|
||||
)
|
||||
|
||||
if unique_game_ids:
|
||||
log.debug(
|
||||
"Searching expanded in games endpoint for %d candidate game(s): %s",
|
||||
len(unique_game_ids),
|
||||
unique_game_ids,
|
||||
)
|
||||
id_filter = " | ".join(f"id={gid}" for gid in unique_game_ids)
|
||||
extra_roms = await self.igdb_service.list_games(
|
||||
fields=GAMES_FIELDS,
|
||||
where=f"id={roms_expanded[0]['game']['id']}",
|
||||
where=f"({id_filter})",
|
||||
limit=self.pagination_limit,
|
||||
)
|
||||
|
||||
@@ -587,7 +606,7 @@ class IGDBHandler(MetadataHandler):
|
||||
|
||||
return IGDBPlatform(igdb_id=None, slug=slug)
|
||||
|
||||
async def get_rom(self, fs_name: str, platform_igdb_id: int) -> IGDBRom:
|
||||
async def get_rom(self, rom: Rom, fs_name: str, platform_igdb_id: int) -> IGDBRom:
|
||||
from handler.filesystem import fs_rom_handler
|
||||
|
||||
if not self.is_enabled():
|
||||
@@ -600,7 +619,7 @@ class IGDBHandler(MetadataHandler):
|
||||
igdb_id_from_tag = self.extract_igdb_id_from_filename(fs_name)
|
||||
if igdb_id_from_tag:
|
||||
log.debug(f"Found IGDB ID tag in filename: {igdb_id_from_tag}")
|
||||
rom_by_id = await self.get_rom_by_id(igdb_id_from_tag)
|
||||
rom_by_id = await self.get_rom_by_id(rom, igdb_id_from_tag)
|
||||
if rom_by_id["igdb_id"]:
|
||||
log.debug(
|
||||
f"Successfully matched ROM by IGDB ID tag: {fs_name} -> {igdb_id_from_tag}"
|
||||
@@ -678,18 +697,20 @@ class IGDBHandler(MetadataHandler):
|
||||
search_term = self.normalize_search_term(search_term)
|
||||
|
||||
log.debug("Searching for %s on IGDB with game_type", search_term)
|
||||
rom = await self._search_rom(search_term, platform_igdb_id, with_game_type=True)
|
||||
if not rom:
|
||||
res = await self._search_rom(search_term, platform_igdb_id, with_game_type=True)
|
||||
if not res:
|
||||
log.debug("Searching for %s on IGDB without game_type", search_term)
|
||||
rom = await self._search_rom(search_term, platform_igdb_id)
|
||||
res = await self._search_rom(search_term, platform_igdb_id)
|
||||
|
||||
# IGDB search is fuzzy so no need to split the search term by special characters
|
||||
if not rom:
|
||||
if not res:
|
||||
return fallback_rom
|
||||
|
||||
return build_igdb_rom(self, rom, get_igdb_preferred_locale(), platform_igdb_id)
|
||||
return build_igdb_rom(
|
||||
self, res, get_igdb_preferred_locale(rom=rom), platform_igdb_id
|
||||
)
|
||||
|
||||
async def get_rom_by_id(self, igdb_id: int) -> IGDBRom:
|
||||
async def get_rom_by_id(self, rom: Rom, igdb_id: int) -> IGDBRom:
|
||||
if not self.is_enabled():
|
||||
return IGDBRom(igdb_id=None)
|
||||
|
||||
@@ -701,17 +722,17 @@ class IGDBHandler(MetadataHandler):
|
||||
if not roms:
|
||||
return IGDBRom(igdb_id=None)
|
||||
|
||||
return build_igdb_rom(self, roms[0], get_igdb_preferred_locale(), None)
|
||||
return build_igdb_rom(self, roms[0], get_igdb_preferred_locale(rom=rom), None)
|
||||
|
||||
async def get_matched_rom_by_id(self, igdb_id: int) -> IGDBRom | None:
|
||||
async def get_matched_rom_by_id(self, rom: Rom, igdb_id: int) -> IGDBRom | None:
|
||||
if not self.is_enabled():
|
||||
return None
|
||||
|
||||
rom = await self.get_rom_by_id(igdb_id)
|
||||
return rom if rom["igdb_id"] else None
|
||||
result = await self.get_rom_by_id(rom, igdb_id)
|
||||
return result if result["igdb_id"] else None
|
||||
|
||||
async def get_matched_roms_by_name(
|
||||
self, search_term: str, platform_igdb_id: int | None
|
||||
self, rom: Rom, search_term: str, platform_igdb_id: int | None
|
||||
) -> list[IGDBRom]:
|
||||
if not self.is_enabled():
|
||||
return []
|
||||
@@ -762,7 +783,7 @@ class IGDBHandler(MetadataHandler):
|
||||
if rom["id"] not in unique_ids
|
||||
]
|
||||
|
||||
preferred_locale = get_igdb_preferred_locale()
|
||||
preferred_locale = get_igdb_preferred_locale(rom=rom)
|
||||
return [
|
||||
build_igdb_rom(self, rom, preferred_locale, platform_igdb_id)
|
||||
for rom in matched_roms
|
||||
|
||||
@@ -128,6 +128,16 @@ class LaunchboxHandler(MetadataHandler):
|
||||
else:
|
||||
search_term = fs_name
|
||||
|
||||
# Resolve MAME arcade filename (e.g. wrlok_l3.zip) to its full title
|
||||
# via LaunchBox's Mame.xml before name-based lookup.
|
||||
if platform_slug == UPS.ARCADE:
|
||||
mame_entry = await self._remote.get_mame_entry(fs_name)
|
||||
if mame_entry:
|
||||
name = (mame_entry.get("Name") or "").strip()
|
||||
if name:
|
||||
search_term = name
|
||||
fallback_rom = LaunchboxRom(launchbox_id=None, name=name)
|
||||
|
||||
# We replace " - "/"- " with ": " to match Launchbox's naming convention
|
||||
search_term = re.sub(DASH_COLON_REGEX, ": ", search_term).lower()
|
||||
|
||||
@@ -152,6 +162,8 @@ class LaunchboxHandler(MetadataHandler):
|
||||
remote=index_entry,
|
||||
remote_images=remote_images,
|
||||
remote_enabled=remote_available,
|
||||
platform_name=get_platform(platform_slug).get("name"),
|
||||
fs_name=fs_name,
|
||||
)
|
||||
|
||||
return build_rom(
|
||||
@@ -162,7 +174,12 @@ class LaunchboxHandler(MetadataHandler):
|
||||
)
|
||||
|
||||
async def get_rom_by_id(
|
||||
self, database_id: int, *, remote_enabled: bool = True
|
||||
self,
|
||||
database_id: int,
|
||||
*,
|
||||
remote_enabled: bool = True,
|
||||
fs_name: str | None = None,
|
||||
platform_slug: str | None = None,
|
||||
) -> LaunchboxRom:
|
||||
if not self.is_enabled():
|
||||
return LaunchboxRom(launchbox_id=None)
|
||||
@@ -174,17 +191,42 @@ class LaunchboxHandler(MetadataHandler):
|
||||
if not remote:
|
||||
return LaunchboxRom(launchbox_id=None)
|
||||
|
||||
# Merge local-only fields when a local LaunchBox install has the same game
|
||||
local: dict[str, str] | None = None
|
||||
if fs_name and platform_slug:
|
||||
candidate = await self._local.get_rom(fs_name, platform_slug)
|
||||
if (
|
||||
candidate is not None
|
||||
and safe_int(candidate.get("DatabaseID")) == database_id
|
||||
):
|
||||
local = candidate
|
||||
|
||||
platform_name = (
|
||||
get_platform(platform_slug).get("name") if platform_slug else None
|
||||
)
|
||||
remote_images = await self._remote.fetch_images(
|
||||
remote=remote, remote_enabled=remote_enabled
|
||||
)
|
||||
media_req = remote_media_req(
|
||||
remote=remote,
|
||||
remote_images=remote_images,
|
||||
remote_enabled=remote_enabled,
|
||||
)
|
||||
if local is not None:
|
||||
media_req = local_media_req(
|
||||
platform_name=platform_name,
|
||||
fs_name=fs_name or "",
|
||||
local=local,
|
||||
remote=remote,
|
||||
remote_images=remote_images,
|
||||
remote_enabled=remote_enabled,
|
||||
)
|
||||
else:
|
||||
media_req = remote_media_req(
|
||||
remote=remote,
|
||||
remote_images=remote_images,
|
||||
remote_enabled=remote_enabled,
|
||||
platform_name=platform_name,
|
||||
fs_name=fs_name or "",
|
||||
)
|
||||
|
||||
return build_rom(
|
||||
local=None,
|
||||
local=local,
|
||||
remote=remote,
|
||||
launchbox_id=database_id,
|
||||
media_req=media_req,
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from config.config_manager import MetadataMediaType
|
||||
from handler.filesystem import fs_resource_handler
|
||||
from handler.metadata.ss_handler import get_preferred_media_types
|
||||
from utils.database import safe_str_to_bool
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from models.rom import Rom
|
||||
|
||||
from .types import (
|
||||
LAUNCHBOX_IMAGES_DIR,
|
||||
LAUNCHBOX_MANUALS_DIR,
|
||||
LAUNCHBOX_VIDEOS_DIR,
|
||||
LaunchboxImage,
|
||||
LaunchboxMetadata,
|
||||
LaunchboxRom,
|
||||
@@ -22,6 +30,8 @@ from .utils import (
|
||||
sanitize_filename,
|
||||
)
|
||||
|
||||
VIDEO_EXTS: tuple[str, ...] = (".mp4", ".webm", ".avi", ".mkv", ".mov", ".wmv")
|
||||
|
||||
|
||||
def local_media_req(
|
||||
*,
|
||||
@@ -49,11 +59,19 @@ def remote_media_req(
|
||||
remote: dict | None,
|
||||
remote_images: list[dict] | None,
|
||||
remote_enabled: bool,
|
||||
platform_name: str | None = None,
|
||||
fs_name: str = "",
|
||||
) -> MediaRequest:
|
||||
title = ((remote or {}).get("Name") or "").strip()
|
||||
# Without a platform_name, _build_local_media_context bails and local
|
||||
# Images/Manuals/Videos never get searched. Fall back to the platform
|
||||
# recorded on the remote entry so remote-matched ROMs can still surface
|
||||
# on-disk media.
|
||||
if not platform_name and remote:
|
||||
platform_name = (remote.get("Platform") or "").strip() or None
|
||||
return MediaRequest(
|
||||
None,
|
||||
"",
|
||||
platform_name,
|
||||
fs_name,
|
||||
title,
|
||||
None,
|
||||
remote_images,
|
||||
@@ -324,6 +342,28 @@ def _get_manuals(req: MediaRequest) -> str | None:
|
||||
return manual
|
||||
|
||||
|
||||
def _get_video(req: MediaRequest) -> str | None:
|
||||
"""Resolve a local LaunchBox video for the given ROM.
|
||||
|
||||
LaunchBox stores videos flat under `Videos/<Platform>/<GameStem>.<ext>`
|
||||
(no region or category subdirectories). Return a `launchbox-file://` URL
|
||||
to the first match, or None.
|
||||
"""
|
||||
ctx = _build_local_media_context(
|
||||
req, LAUNCHBOX_VIDEOS_DIR, include_region_hints=False
|
||||
)
|
||||
if ctx is None:
|
||||
return None
|
||||
|
||||
for stem in ctx["stems"]:
|
||||
for ext in VIDEO_EXTS:
|
||||
candidate = ctx["base"] / f"{stem}{ext}"
|
||||
if candidate.is_file():
|
||||
return file_uri_for_local_path(candidate)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _get_images(req: MediaRequest) -> list[LaunchboxImage]:
|
||||
images: list[LaunchboxImage] = []
|
||||
|
||||
@@ -495,6 +535,30 @@ def build_launchbox_metadata(
|
||||
)
|
||||
|
||||
|
||||
def populate_rom_specific_paths(
|
||||
metadata: LaunchboxMetadata, rom: "Rom"
|
||||
) -> LaunchboxMetadata:
|
||||
"""Populate rom-specific media paths on a LaunchBox metadata dict.
|
||||
|
||||
Called after the Rom is known (in the scan pipeline) to compute the
|
||||
destination path for local media that the handler surfaced a URL for.
|
||||
Currently just covers video.
|
||||
"""
|
||||
if (
|
||||
MetadataMediaType.VIDEO in get_preferred_media_types()
|
||||
and "video_url" in metadata
|
||||
and metadata.get("video_url")
|
||||
):
|
||||
base = fs_resource_handler.get_media_resources_path(
|
||||
rom.platform_id, rom.id, MetadataMediaType.VIDEO
|
||||
)
|
||||
ext = Path(metadata["video_url"]).suffix.lower()
|
||||
if ext not in VIDEO_EXTS:
|
||||
ext = ".mp4"
|
||||
metadata["video_path"] = f"{base}/video{ext}"
|
||||
return metadata
|
||||
|
||||
|
||||
def build_rom(
|
||||
*,
|
||||
local: dict[str, str] | None,
|
||||
@@ -509,10 +573,12 @@ def build_rom(
|
||||
url_cover: str | None = None
|
||||
url_screenshots: list[str] = []
|
||||
url_manual: str | None = None
|
||||
video_url: str | None = None
|
||||
if media_req is not None:
|
||||
url_cover = _get_cover(media_req)
|
||||
url_screenshots = _get_screenshots(media_req)
|
||||
url_manual = _get_manuals(media_req)
|
||||
video_url = _get_video(media_req)
|
||||
url_screenshots = url_screenshots or []
|
||||
|
||||
name = (
|
||||
@@ -532,6 +598,13 @@ def build_rom(
|
||||
).strip()
|
||||
|
||||
launchbox_id = int(launchbox_id) if launchbox_id is not None else None
|
||||
metadata = build_launchbox_metadata(
|
||||
local=local,
|
||||
remote=remote,
|
||||
images=images,
|
||||
)
|
||||
if video_url:
|
||||
metadata["video_url"] = video_url
|
||||
return LaunchboxRom(
|
||||
launchbox_id=launchbox_id,
|
||||
name=name,
|
||||
@@ -539,9 +612,5 @@ def build_rom(
|
||||
url_cover=url_cover or "",
|
||||
url_screenshots=url_screenshots,
|
||||
url_manual=url_manual or "",
|
||||
launchbox_metadata=build_launchbox_metadata(
|
||||
local=local,
|
||||
remote=remote,
|
||||
images=images,
|
||||
),
|
||||
launchbox_metadata=metadata,
|
||||
)
|
||||
@@ -5,6 +5,7 @@ from logger.logger import log
|
||||
|
||||
from .platforms import get_platform
|
||||
from .types import (
|
||||
LAUNCHBOX_MAME_KEY,
|
||||
LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY,
|
||||
LAUNCHBOX_METADATA_DATABASE_ID_KEY,
|
||||
LAUNCHBOX_METADATA_IMAGE_KEY,
|
||||
@@ -39,7 +40,7 @@ class RemoteSource:
|
||||
if not platform_name:
|
||||
return None
|
||||
|
||||
file_name_clean = (file_name or "").strip()
|
||||
file_name_clean = file_name.strip()
|
||||
if not file_name_clean:
|
||||
return None
|
||||
|
||||
@@ -74,6 +75,32 @@ class RemoteSource:
|
||||
|
||||
return None
|
||||
|
||||
async def get_mame_entry(self, file_name: str) -> dict | None:
|
||||
"""Resolve a MAME arcade filename to its LaunchBox MAME entry.
|
||||
|
||||
LaunchBox's Mame.xml indexes `<MameFile>` records by `<FileName>`, the
|
||||
MAME short name without an extension (e.g. `wrlok_l3` for `wrlok_l3.zip`).
|
||||
The entry carries `<Name>`, the full title to search for in Metadata.xml.
|
||||
"""
|
||||
file_name_clean = file_name.strip()
|
||||
if not file_name_clean:
|
||||
return None
|
||||
|
||||
# Try the raw filename first, then the stem (sans extension).
|
||||
candidates: list[str] = [file_name_clean]
|
||||
from pathlib import Path
|
||||
|
||||
stem = Path(file_name_clean).stem
|
||||
if stem and stem != file_name_clean:
|
||||
candidates.append(stem)
|
||||
|
||||
for candidate in candidates:
|
||||
entry = await async_cache.hget(LAUNCHBOX_MAME_KEY, candidate)
|
||||
if entry:
|
||||
return json.loads(entry)
|
||||
|
||||
return None
|
||||
|
||||
async def fetch_images(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -54,6 +54,8 @@ class LaunchboxMetadata(TypedDict):
|
||||
genres: NotRequired[list[str]]
|
||||
companies: NotRequired[list[str]]
|
||||
images: list[LaunchboxImage]
|
||||
video_url: NotRequired[str]
|
||||
video_path: NotRequired[str]
|
||||
|
||||
|
||||
class LaunchboxRom(BaseRom):
|
||||
|
||||
@@ -20,7 +20,7 @@ def file_uri_for_local_path(path: Path) -> str | None:
|
||||
relative = path.resolve().relative_to(LAUNCHBOX_LOCAL_DIR.resolve())
|
||||
except ValueError:
|
||||
return None
|
||||
return f"file://{relative.as_posix()}"
|
||||
return f"launchbox-file://{relative.as_posix()}"
|
||||
|
||||
|
||||
def coalesce(*values: object | None) -> str | None:
|
||||
|
||||
@@ -140,7 +140,7 @@ class LibretroHandler(MetadataHandler):
|
||||
matching MetadataMediaType (SCREENSHOT / TITLE_SCREEN / LOGO) is in
|
||||
SCAN_MEDIA, and appends any matches to `url_screenshots` so the
|
||||
scan_handler artwork loop picks them up. `name` is deliberately
|
||||
omitted — libretro artwork filenames aren't proper game names.
|
||||
omitted, since libretro artwork filenames aren't proper game names.
|
||||
"""
|
||||
platform = self.get_platform(platform_slug)
|
||||
if not platform or not platform["libretro_slug"]:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import json
|
||||
from enum import Enum
|
||||
from typing import NotRequired, TypedDict
|
||||
from typing import Final, NotRequired, TypedDict
|
||||
|
||||
import httpx
|
||||
import yarl
|
||||
@@ -16,22 +16,44 @@ from utils.context import ctx_httpx_client
|
||||
|
||||
class PlaymatchProvider(str, Enum):
|
||||
IGDB = "IGDB"
|
||||
STEAM_GRID_DB = "SteamGridDB"
|
||||
SCREEN_SCRAPER = "ScreenScraper"
|
||||
MOBY_GAMES = "MobyGames"
|
||||
LAUNCH_BOX = "LaunchBox"
|
||||
EMU_READY = "EmuReady"
|
||||
OPEN_VGDB = "OpenVGDB"
|
||||
|
||||
|
||||
# (rom attribute, provider tag). Playmatch drops unknown tags server-side.
|
||||
_PLAYMATCH_PROVIDER_TAGS: tuple[tuple[str, str], ...] = (
|
||||
("igdb_id", "IGDB"),
|
||||
("moby_id", "MOBY_GAMES"),
|
||||
("ss_id", "SCREENSCRAPER"),
|
||||
("ra_id", "RETRO_ACHIEVEMENTS"),
|
||||
("launchbox_id", "LAUNCHBOX"),
|
||||
("hasheous_id", "HASHEOUS"),
|
||||
("tgdb_id", "TGDB"),
|
||||
("flashpoint_id", "FLASHPOINT"),
|
||||
("hltb_id", "HOWLONGTOBEAT"),
|
||||
("libretro_id", "LIBRETRO"),
|
||||
("sgdb_id", "STEAMGRIDDB"),
|
||||
("gamelist_id", "GAMELIST"),
|
||||
# Tag is the uppercased Playmatch MetadataProvider name.
|
||||
# Playmatch parses it case-insensitively but spacing must match.
|
||||
# Tags Playmatch doesn't yet know are kept so older RomM clients keep
|
||||
# submitting the right tag once Playmatch adds support.
|
||||
PLAYMATCH_TAG_TO_ATTR: Final[dict[str, str]] = {
|
||||
"IGDB": "igdb_id",
|
||||
"MOBYGAMES": "moby_id",
|
||||
"SCREENSCRAPER": "ss_id",
|
||||
"RETRO_ACHIEVEMENTS": "ra_id",
|
||||
"LAUNCHBOX": "launchbox_id",
|
||||
"HASHEOUS": "hasheous_id",
|
||||
"TGDB": "tgdb_id",
|
||||
"FLASHPOINT": "flashpoint_id",
|
||||
"HOWLONGTOBEAT": "hltb_id",
|
||||
"LIBRETRO": "libretro_id",
|
||||
"STEAMGRIDDB": "sgdb_id",
|
||||
"GAMELIST": "gamelist_id",
|
||||
}
|
||||
|
||||
# Rom attrs the scan handler actually consumes from a Playmatch lookup.
|
||||
# Other tags exist only for outbound suggestions.
|
||||
PLAYMATCH_LOOKUP_ROM_ATTRS: frozenset[str] = frozenset(
|
||||
{"igdb_id", "moby_id", "ss_id", "launchbox_id", "sgdb_id"}
|
||||
)
|
||||
|
||||
# MetadataSource values (StrEnum) for which Playmatch can return ids. Typed as
|
||||
# strings so this module stays free of scan_handler imports. EmuReady and
|
||||
# OpenVGDB are in Playmatch's enum but have no RomM counterpart yet.
|
||||
PLAYMATCH_SUPPORTED_SOURCES: frozenset[str] = frozenset(
|
||||
{"igdb", "moby", "ss", "launchbox", "sgdb"}
|
||||
)
|
||||
|
||||
|
||||
@@ -39,8 +61,8 @@ class GameMatchType(str, Enum):
|
||||
SHA256 = "SHA256"
|
||||
SHA1 = "SHA1"
|
||||
MD5 = "MD5"
|
||||
FileNameAndSize = "FileNameAndSize"
|
||||
NoMatch = "NoMatch"
|
||||
FILE_NAME_AND_SIZE = "FileNameAndSize"
|
||||
NO_MATCH = "NoMatch"
|
||||
|
||||
|
||||
class PlaymatchExternalMetadata(TypedDict):
|
||||
@@ -55,6 +77,17 @@ class PlaymatchExternalMetadata(TypedDict):
|
||||
|
||||
class PlaymatchRomMatch(TypedDict):
|
||||
igdb_id: int | None
|
||||
moby_id: int | None
|
||||
ss_id: int | None
|
||||
launchbox_id: int | None
|
||||
sgdb_id: int | None
|
||||
ra_id: int | None
|
||||
hasheous_id: int | None
|
||||
tgdb_id: int | None
|
||||
flashpoint_id: str | None
|
||||
hltb_id: int | None
|
||||
gamelist_id: str | None
|
||||
libretro_id: str | None
|
||||
|
||||
|
||||
class PlaymatchHandler(MetadataHandler):
|
||||
@@ -124,7 +157,7 @@ class PlaymatchHandler(MetadataHandler):
|
||||
detail="Can't connect to Playmatch, check your internet connection",
|
||||
) from exc
|
||||
except json.JSONDecodeError as exc:
|
||||
log.error("Error decoding JSON response from ScreenScraper: %s", exc)
|
||||
log.error("Error decoding JSON response from Playmatch: %s", exc)
|
||||
return {}
|
||||
|
||||
async def lookup_rom(self, files: list[RomFile]) -> PlaymatchRomMatch:
|
||||
@@ -135,15 +168,30 @@ class PlaymatchHandler(MetadataHandler):
|
||||
:return: A PlaymatchRomMatch objects containing the matched ROM information.
|
||||
:raises HTTPException: If the request fails or the service is unavailable.
|
||||
"""
|
||||
fallback_rom = PlaymatchRomMatch(
|
||||
igdb_id=None,
|
||||
moby_id=None,
|
||||
ss_id=None,
|
||||
launchbox_id=None,
|
||||
sgdb_id=None,
|
||||
ra_id=None,
|
||||
hasheous_id=None,
|
||||
tgdb_id=None,
|
||||
flashpoint_id=None,
|
||||
hltb_id=None,
|
||||
gamelist_id=None,
|
||||
libretro_id=None,
|
||||
)
|
||||
|
||||
if not self.is_enabled():
|
||||
return PlaymatchRomMatch(igdb_id=None)
|
||||
return fallback_rom
|
||||
|
||||
first_file = next(
|
||||
(file for file in files if file.file_size_bytes > 0),
|
||||
None,
|
||||
)
|
||||
if first_file is None:
|
||||
return PlaymatchRomMatch(igdb_id=None)
|
||||
return fallback_rom
|
||||
|
||||
try:
|
||||
response = await self._request(
|
||||
@@ -157,45 +205,61 @@ class PlaymatchHandler(MetadataHandler):
|
||||
)
|
||||
except httpx.HTTPStatusError:
|
||||
# We silently fail if the service is unavailable as this should not block the rest of RomM.
|
||||
return PlaymatchRomMatch(igdb_id=None)
|
||||
return fallback_rom
|
||||
|
||||
game_match_type = response.get("gameMatchType", None)
|
||||
if game_match_type == GameMatchType.NoMatch:
|
||||
if game_match_type == GameMatchType.NO_MATCH:
|
||||
log.debug("No match found for the provided ROM file.")
|
||||
return PlaymatchRomMatch(igdb_id=None)
|
||||
return fallback_rom
|
||||
|
||||
externalMetadata = response.get("externalMetadata", [])
|
||||
if len(externalMetadata) == 0:
|
||||
log.debug("No external metadata found for the matched ROM file.")
|
||||
return PlaymatchRomMatch(igdb_id=None)
|
||||
|
||||
igdb_id = None
|
||||
return fallback_rom
|
||||
|
||||
result = fallback_rom
|
||||
for metadata in externalMetadata:
|
||||
provider_name = metadata.get("providerName", None)
|
||||
provider_game_id = metadata.get("providerId", None)
|
||||
if provider_name == PlaymatchProvider.IGDB and provider_game_id is not None:
|
||||
log.debug(
|
||||
"Playmatch found IGDB match with IGDB ID: %s", provider_game_id
|
||||
)
|
||||
igdb_id = int(provider_game_id)
|
||||
if not provider_name or provider_game_id is None:
|
||||
continue
|
||||
|
||||
return PlaymatchRomMatch(igdb_id=igdb_id)
|
||||
attr = PLAYMATCH_TAG_TO_ATTR.get(provider_name.upper())
|
||||
if not attr or attr not in PLAYMATCH_LOOKUP_ROM_ATTRS:
|
||||
continue
|
||||
|
||||
try:
|
||||
parsed_id = int(provider_game_id)
|
||||
except (TypeError, ValueError):
|
||||
log.debug(
|
||||
"Playmatch returned non-int ID for %s: %r",
|
||||
provider_name,
|
||||
provider_game_id,
|
||||
)
|
||||
continue
|
||||
|
||||
log.debug("Playmatch found %s match with id: %s", provider_name, parsed_id)
|
||||
result[attr] = parsed_id # trunk-ignore(mypy/literal-required)
|
||||
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def is_manual_match(form_fields_set: set[str]) -> bool:
|
||||
"""True if the submitted form contains any Playmatch-tracked provider id field."""
|
||||
return any(attr in form_fields_set for attr, _ in _PLAYMATCH_PROVIDER_TAGS)
|
||||
return any(attr in form_fields_set for attr in PLAYMATCH_TAG_TO_ATTR.values())
|
||||
|
||||
async def submit_manual_match_suggestion(self, rom: Rom) -> None:
|
||||
"""Fire-and-forget suggestion POST. No-ops if disabled or no provider IDs are set; never raises."""
|
||||
"""
|
||||
Fire-and-forget suggestion POST.
|
||||
No-ops if disabled or no provider IDs are set.
|
||||
"""
|
||||
try:
|
||||
if not self.is_enabled():
|
||||
return
|
||||
|
||||
mappings = [
|
||||
{"provider": tag, "providerId": str(getattr(rom, attr))}
|
||||
for attr, tag in _PLAYMATCH_PROVIDER_TAGS
|
||||
for tag, attr in PLAYMATCH_TAG_TO_ATTR.items()
|
||||
if getattr(rom, attr, None)
|
||||
]
|
||||
if not mappings:
|
||||
|
||||
@@ -11,7 +11,6 @@ from anyio import Path as AnyioPath
|
||||
from adapters.services.retroachievements import RetroAchievementsService
|
||||
from adapters.services.retroachievements_types import (
|
||||
RAGameExtendedDetails,
|
||||
RAGameListItem,
|
||||
)
|
||||
from config import (
|
||||
REFRESH_RETROACHIEVEMENTS_CACHE_DAYS,
|
||||
@@ -128,7 +127,7 @@ def extract_metadata_from_rom_details(
|
||||
class RAHandler(MetadataHandler):
|
||||
def __init__(self) -> None:
|
||||
self.ra_service = RetroAchievementsService()
|
||||
self.HASHES_FILE_NAME = "ra_hashes.json"
|
||||
self.HASHES_FILE_NAME = "ra_hashes_v2.json"
|
||||
|
||||
@classmethod
|
||||
def is_enabled(cls) -> bool:
|
||||
@@ -174,47 +173,44 @@ class RAHandler(MetadataHandler):
|
||||
file_stat = await AnyioPath(str(full_path)).stat()
|
||||
return int((time.time() - file_stat.st_mtime) / (24 * 3600))
|
||||
|
||||
async def _search_rom(self, rom: Rom, ra_hash: str) -> RAGameListItem | None:
|
||||
async def _search_rom(self, rom: Rom, ra_hash: str) -> int | None:
|
||||
if not rom.platform.ra_id:
|
||||
return None
|
||||
|
||||
# Fetch all hashes for specific platform
|
||||
roms: list[RAGameListItem]
|
||||
# hash_index maps lowercase hash -> game ID for O(1) lookups
|
||||
hash_index: dict[str, int]
|
||||
if (
|
||||
REFRESH_RETROACHIEVEMENTS_CACHE_DAYS
|
||||
<= await self._days_since_last_cache_file_update(rom.platform.id)
|
||||
or not await self._exists_cache_file(rom.platform.id)
|
||||
):
|
||||
# Write the roms result to a JSON file if older than REFRESH_RETROACHIEVEMENTS_CACHE_DAYS days
|
||||
# Fetch all games (including those without achievements) and build index
|
||||
roms = await self.ra_service.get_game_list(
|
||||
system_id=rom.platform.ra_id,
|
||||
only_games_with_achievements=True,
|
||||
only_games_with_achievements=False,
|
||||
include_hashes=True,
|
||||
)
|
||||
|
||||
hash_index = {h.lower(): r["ID"] for r in roms for h in r.get("Hashes", ())}
|
||||
|
||||
platform_resources_path = fs_resource_handler.get_platform_resources_path(
|
||||
rom.platform.id
|
||||
)
|
||||
|
||||
json_file = json.dumps(roms, indent=4)
|
||||
json_file = json.dumps(hash_index, indent=4)
|
||||
await fs_resource_handler.write_file(
|
||||
json_file.encode("utf-8"),
|
||||
platform_resources_path,
|
||||
self.HASHES_FILE_NAME,
|
||||
)
|
||||
else:
|
||||
# Read the roms result from the JSON file
|
||||
# Read the hash index from the JSON file
|
||||
json_file_bytes = await fs_resource_handler.read_file(
|
||||
self._get_hashes_file_path(rom.platform.id)
|
||||
)
|
||||
roms = json.loads(json_file_bytes.decode("utf-8"))
|
||||
hash_index = json.loads(json_file_bytes.decode("utf-8"))
|
||||
|
||||
ra_hash_lower = ra_hash.lower()
|
||||
for r in roms:
|
||||
if any(ra_hash_lower == h.lower() for h in r.get("Hashes", ())):
|
||||
return r
|
||||
|
||||
return None
|
||||
return hash_index.get(ra_hash.lower())
|
||||
|
||||
def get_platform(self, slug: str) -> RAGamesPlatform:
|
||||
if slug not in RA_PLATFORM_LIST:
|
||||
@@ -250,15 +246,13 @@ class RAHandler(MetadataHandler):
|
||||
if not ra_hash:
|
||||
return RAGameRom(ra_id=None)
|
||||
|
||||
ra_game_list_item = await self._search_rom(rom, ra_hash)
|
||||
ra_game_id = await self._search_rom(rom, ra_hash)
|
||||
|
||||
if not ra_game_list_item:
|
||||
if ra_game_id is None:
|
||||
return RAGameRom(ra_id=None)
|
||||
|
||||
try:
|
||||
rom_details = await self.ra_service.get_game_extended_details(
|
||||
ra_game_list_item["ID"]
|
||||
)
|
||||
rom_details = await self.ra_service.get_game_extended_details(ra_game_id)
|
||||
|
||||
return RAGameRom(
|
||||
ra_id=rom_details["ID"],
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import base64
|
||||
import html
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Final, NotRequired, TypedDict
|
||||
@@ -13,6 +13,7 @@ from config import SCREENSCRAPER_PASSWORD, SCREENSCRAPER_USER
|
||||
from config.config_manager import MetadataMediaType
|
||||
from config.config_manager import config_manager as cm
|
||||
from handler.filesystem import fs_resource_handler
|
||||
from handler.filesystem.base_handler import region_name_to_provider_shortcode
|
||||
from logger.logger import log
|
||||
from models.rom import Rom, RomFile
|
||||
|
||||
@@ -26,21 +27,51 @@ from .base_handler import (
|
||||
)
|
||||
from .base_handler import UniversalPlatformSlug as UPS
|
||||
from .base_handler import (
|
||||
restore_sensitive_query_params,
|
||||
strip_sensitive_query_params,
|
||||
)
|
||||
|
||||
SS_DEV_ID: Final = base64.b64decode("enVyZGkxNQ==").decode()
|
||||
SS_DEV_PASSWORD: Final = base64.b64decode("eFRKd29PRmpPUUc=").decode()
|
||||
SENSITIVE_KEYS = {"ssid", "sspassword"}
|
||||
|
||||
|
||||
def get_preferred_regions() -> list[str]:
|
||||
"""Get preferred regions from config"""
|
||||
def add_ss_auth_to_url(url: str) -> str:
|
||||
"""Re-add SS user credentials to a media URL at download time (never stored)."""
|
||||
if not SCREENSCRAPER_USER or not SCREENSCRAPER_PASSWORD:
|
||||
return url
|
||||
|
||||
return restore_sensitive_query_params(
|
||||
url,
|
||||
{
|
||||
"ssid": SCREENSCRAPER_USER,
|
||||
"sspassword": SCREENSCRAPER_PASSWORD,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def get_preferred_regions(rom: Rom | None = None) -> list[str]:
|
||||
"""Get preferred regions, prepending the rom's own region tags when available.
|
||||
|
||||
When a rom is tagged with multiple regions (e.g. "(Japan, USA)"), the rom's
|
||||
own tags are reordered according to the user's SCAN_REGION_PRIORITY so the
|
||||
user's preference wins among the regions the file is actually tagged as.
|
||||
Filename-tagged regions not present in the priority list keep their relative
|
||||
order and follow the prioritized ones.
|
||||
"""
|
||||
config = cm.get_config()
|
||||
return list(
|
||||
dict.fromkeys(
|
||||
config.SCAN_REGION_PRIORITY + ["us", "wor", "ss", "eu", "jp", "cus"]
|
||||
priority = config.SCAN_REGION_PRIORITY
|
||||
|
||||
rom_codes: list[str] = []
|
||||
if rom is not None and isinstance(rom.regions, list):
|
||||
for region_name in rom.regions:
|
||||
code = region_name_to_provider_shortcode(region_name)
|
||||
if code:
|
||||
rom_codes.append(code)
|
||||
rom_codes.sort(
|
||||
key=lambda code: priority.index(code) if code in priority else len(priority)
|
||||
)
|
||||
|
||||
return list(
|
||||
dict.fromkeys(rom_codes + priority + ["us", "wor", "ss", "eu", "jp", "cus"])
|
||||
) + ["unk"]
|
||||
|
||||
|
||||
@@ -72,6 +103,10 @@ ARCADES_SS_IDS: Final = [ARCADE_SS_ID, CPS1_SS_ID, CPS2_SS_ID, CPS3_SS_ID]
|
||||
# Regex to detect ScreenScraper ID tags in filenames like (ssfr-12345)
|
||||
SS_TAG_REGEX = re.compile(r"\(ssfr-(\d+)\)", re.IGNORECASE)
|
||||
|
||||
NOTGAME_NAME_PREFIX: Final = "ZZZ(NOTGAME)"
|
||||
|
||||
_ISO_EXTENSIONS: Final = frozenset({"iso", "cue", "chd", "gdi", "cdi", "bin"})
|
||||
|
||||
ACCEPTABLE_FILE_EXTENSIONS_BY_PLATFORM_SLUG = {
|
||||
UPS.DC: ["cue", "chd", "gdi", "cdi"],
|
||||
UPS.SEGACD: ["cue", "chd", "bin"],
|
||||
@@ -79,6 +114,15 @@ ACCEPTABLE_FILE_EXTENSIONS_BY_PLATFORM_SLUG = {
|
||||
}
|
||||
|
||||
|
||||
def _is_notgame(game: SSGame) -> bool:
|
||||
if game.get("notgame") == "true":
|
||||
return True
|
||||
return any(
|
||||
name.get("text", "").upper().startswith(NOTGAME_NAME_PREFIX)
|
||||
for name in game.get("noms", [])
|
||||
)
|
||||
|
||||
|
||||
class SSPlatform(TypedDict):
|
||||
slug: str
|
||||
ss_id: int | None
|
||||
@@ -140,6 +184,14 @@ class SSRom(BaseRom):
|
||||
ss_metadata: NotRequired[SSMetadata]
|
||||
|
||||
|
||||
def _get_rom_type(file: RomFile) -> str:
|
||||
if not file.is_top_level:
|
||||
return "dossier"
|
||||
if file.file_extension.lower() in _ISO_EXTENSIONS:
|
||||
return "iso"
|
||||
return "rom"
|
||||
|
||||
|
||||
def extract_media_from_ss_game(rom: Rom, game: SSGame) -> SSMetadataMedia:
|
||||
preferred_media_types = get_preferred_media_types()
|
||||
|
||||
@@ -174,7 +226,7 @@ def extract_media_from_ss_game(rom: Rom, game: SSGame) -> SSMetadataMedia:
|
||||
video_normalized_path=None,
|
||||
)
|
||||
|
||||
for region in get_preferred_regions():
|
||||
for region in get_preferred_regions(rom):
|
||||
for media in game.get("medias", []):
|
||||
if media.get("region", "unk") != region or media.get("parent") != "jeu":
|
||||
continue
|
||||
@@ -409,7 +461,7 @@ def build_ss_game(rom: Rom, game: SSGame) -> SSRom:
|
||||
preferred_media_types = get_preferred_media_types()
|
||||
|
||||
res_name = ""
|
||||
for region in get_preferred_regions():
|
||||
for region in get_preferred_regions(rom):
|
||||
res_name = next(
|
||||
(
|
||||
name["text"]
|
||||
@@ -472,8 +524,8 @@ def build_ss_game(rom: Rom, game: SSGame) -> SSRom:
|
||||
ss_id = int(game["id"]) if game.get("id") is not None else None
|
||||
game_rom: SSRom = {
|
||||
"ss_id": ss_id,
|
||||
"name": res_name.replace(" : ", ": "), # Normalize colons
|
||||
"summary": res_summary,
|
||||
"name": html.unescape(res_name.replace(" : ", ": ")), # Normalize colons
|
||||
"summary": html.unescape(res_summary),
|
||||
"url_cover": str(url_cover) if url_cover else "",
|
||||
"url_manual": str(url_manual) if url_manual else "",
|
||||
"url_screenshots": url_screenshots,
|
||||
@@ -524,6 +576,11 @@ class SSHandler(MetadataHandler):
|
||||
|
||||
games_by_name: dict[str, SSGame] = {}
|
||||
for rom in roms:
|
||||
if _is_notgame(rom):
|
||||
log.warning(
|
||||
"ScreenScraper: Received notgame entry in search results, ignoring"
|
||||
)
|
||||
continue
|
||||
for name in rom.get("noms", []):
|
||||
if name["text"] not in games_by_name or int(rom["id"]) < int(
|
||||
games_by_name[name["text"]]["id"]
|
||||
@@ -557,12 +614,12 @@ class SSHandler(MetadataHandler):
|
||||
|
||||
async def lookup_rom(
|
||||
self, rom: Rom, platform_ss_id: int, files: list[RomFile]
|
||||
) -> SSRom:
|
||||
) -> tuple[SSRom, bool]:
|
||||
if not self.is_enabled():
|
||||
return SSRom(ss_id=None)
|
||||
return SSRom(ss_id=None), False
|
||||
|
||||
if not platform_ss_id:
|
||||
return SSRom(ss_id=None)
|
||||
return SSRom(ss_id=None), False
|
||||
|
||||
filtered_files = [
|
||||
file
|
||||
@@ -582,7 +639,7 @@ class SSHandler(MetadataHandler):
|
||||
# expected to have the correct and complete hash values for external services.
|
||||
first_file = max(filtered_files, key=lambda f: f.file_size_bytes, default=None)
|
||||
if first_file is None:
|
||||
return SSRom(ss_id=None)
|
||||
return SSRom(ss_id=None), False
|
||||
|
||||
md5_hash = first_file.md5_hash
|
||||
sha1_hash = first_file.sha1_hash
|
||||
@@ -594,7 +651,7 @@ class SSHandler(MetadataHandler):
|
||||
"No hashes provided for ScreenScraper lookup. "
|
||||
"At least one of md5_hash, sha1_hash, or crc_hash is required."
|
||||
)
|
||||
return SSRom(ss_id=None)
|
||||
return SSRom(ss_id=None), False
|
||||
|
||||
res = await self.ss_service.get_game_info(
|
||||
system_id=platform_ss_id,
|
||||
@@ -602,11 +659,19 @@ class SSHandler(MetadataHandler):
|
||||
sha1=sha1_hash,
|
||||
crc=crc_hash,
|
||||
rom_size_bytes=fs_size_bytes,
|
||||
rom_name=first_file.file_name,
|
||||
rom_type=_get_rom_type(first_file),
|
||||
)
|
||||
if not res:
|
||||
return SSRom(ss_id=None)
|
||||
return SSRom(ss_id=None), False
|
||||
|
||||
return build_ss_game(rom, res)
|
||||
if _is_notgame(res):
|
||||
log.warning(
|
||||
"ScreenScraper: Received notgame entry from hash lookup, ignoring"
|
||||
)
|
||||
return SSRom(ss_id=None), True
|
||||
|
||||
return build_ss_game(rom, res), False
|
||||
|
||||
async def get_rom(self, rom: Rom, file_name: str, platform_ss_id: int) -> SSRom:
|
||||
from handler.filesystem import fs_rom_handler
|
||||
@@ -635,6 +700,9 @@ class SSHandler(MetadataHandler):
|
||||
search_term = fs_rom_handler.get_file_name_with_no_tags(file_name)
|
||||
fallback_rom = SSRom(ss_id=None)
|
||||
|
||||
if not search_term:
|
||||
return fallback_rom
|
||||
|
||||
# Support for PS2 OPL filename format
|
||||
match = PS2_OPL_REGEX.match(file_name)
|
||||
if platform_ss_id == PS2_SS_ID and match:
|
||||
@@ -756,7 +824,7 @@ class SSHandler(MetadataHandler):
|
||||
return [
|
||||
build_ss_game(rom, game)
|
||||
for game in matched_games
|
||||
if _is_ss_region(game) and game.get("id")
|
||||
if not _is_notgame(game) and _is_ss_region(game) and game.get("id")
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -116,7 +116,7 @@ TGDB_PLATFORM_LIST: dict[UPS, SlugToTGDBId] = {
|
||||
"media_medium": "Cassette tape, floppy disk (optional), ROM cartridge (optional)",
|
||||
"cpu": "MOS Technology 6502A with 2/1 MHz",
|
||||
"memory": "32 kB RAM, 32 kB ROM",
|
||||
"graphics": "160x256 (4 or 16 colours), 320x256 (2 or 4 colours), 640x256 (2 colours), 320x200 (2 colours — spaced display with two blank horizontal lines following every 8 pixel lines), 640x200 (2 colours — spaced display)",
|
||||
"graphics": "160x256 (4 or 16 colours), 320x256 (2 or 4 colours), 640x256 (2 colours), 320x200 (2 colours, spaced display with two blank horizontal lines following every 8 pixel lines), 640x200 (2 colours, spaced display)",
|
||||
"sound": "1 channel of sound, 7 octaves; built-in speaker",
|
||||
"display": "RF modulator, composite video, RGB monitor output",
|
||||
"max_controllers": "-",
|
||||
@@ -285,7 +285,7 @@ TGDB_PLATFORM_LIST: dict[UPS, SlugToTGDBId] = {
|
||||
"sound": "Television Interface Adaptor",
|
||||
"display": None,
|
||||
"max_controllers": "2",
|
||||
"summary": "The Atari 2600 is a video game console released in October 1977 by Atari, Inc. It is credited with popularizing the use of microprocessor-based hardware and cartridges containing game code, instead of having non-microprocessor dedicated hardware with all games built in. The first game console to use this format was the Fairchild Channel F; however, the Atari 2600 receives credit for making the plug-in concept popular among the game-playing public.The console was originally sold as the Atari VCS, for Video Computer System. Following the release of the Atari 5200, in 1982, the VCS was renamed 'Atari 2600', after the unit's Atari part number, CX2600. The 2600 was typically bundled with two joystick controllers, a conjoined pair of paddle controllers, and a cartridge game—initially Combat and later Pac-Man.The Atari 2600 was wildly successful, and during much of the 1980s, 'Atari' was a synonym for this model in mainstream media and, by extension, for video games in general.",
|
||||
"summary": "The Atari 2600 is a video game console released in October 1977 by Atari, Inc. It is credited with popularizing the use of microprocessor-based hardware and cartridges containing game code, instead of having non-microprocessor dedicated hardware with all games built in. The first game console to use this format was the Fairchild Channel F; however, the Atari 2600 receives credit for making the plug-in concept popular among the game-playing public.The console was originally sold as the Atari VCS, for Video Computer System. Following the release of the Atari 5200, in 1982, the VCS was renamed 'Atari 2600', after the unit's Atari part number, CX2600. The 2600 was typically bundled with two joystick controllers, a conjoined pair of paddle controllers, and a cartridge game, initially Combat and later Pac-Man.The Atari 2600 was wildly successful, and during much of the 1980s, 'Atari' was a synonym for this model in mainstream media and, by extension, for video games in general.",
|
||||
"url_logo": "https://cdn.thegamesdb.net/images/original/platform/boxart/22-1.jpg",
|
||||
},
|
||||
UPS.ATARI5200: {
|
||||
@@ -585,7 +585,7 @@ TGDB_PLATFORM_LIST: dict[UPS, SlugToTGDBId] = {
|
||||
"sound": "3 x square, 1 x noise, mono.",
|
||||
"display": None,
|
||||
"max_controllers": None,
|
||||
"summary": "The VIC-20 is an 8-bit home computer which was sold by Commodore Business Machines. The VIC-20 was announced in 1980, roughly three years after Commodore's first personal computer, the PET. The VIC-20 was the first computer of any description to sell one million units. As for commercial software offerings, an estimated 300 titles were available on cartridge, and another 500+ titles were available on tape. By comparison, the Atari 2600—the most popular of the video game consoles at the time—had a library of about 900 titles near the end of its production life (although many titles were extremely similar). Most cartridge games were ready to play as soon as the VIC-20 was turned on, as opposed to games on tape which required a time-consuming loading process. Titles on cartridge included Gorf, Cosmic Cruncher, Sargon II Chess, and many others. A handful of disk applications were released for the VIC-20.",
|
||||
"summary": "The VIC-20 is an 8-bit home computer which was sold by Commodore Business Machines. The VIC-20 was announced in 1980, roughly three years after Commodore's first personal computer, the PET. The VIC-20 was the first computer of any description to sell one million units. As for commercial software offerings, an estimated 300 titles were available on cartridge, and another 500+ titles were available on tape. By comparison, the Atari 2600, the most popular of the video game consoles at the time, had a library of about 900 titles near the end of its production life (although many titles were extremely similar). Most cartridge games were ready to play as soon as the VIC-20 was turned on, as opposed to games on tape which required a time-consuming loading process. Titles on cartridge included Gorf, Cosmic Cruncher, Sargon II Chess, and many others. A handful of disk applications were released for the VIC-20.",
|
||||
"url_logo": "https://cdn.thegamesdb.net/images/original/platform/boxart/4945-1.jpg",
|
||||
},
|
||||
UPS.DIDJ: {
|
||||
@@ -975,7 +975,7 @@ TGDB_PLATFORM_LIST: dict[UPS, SlugToTGDBId] = {
|
||||
"sound": None,
|
||||
"display": None,
|
||||
"max_controllers": "2",
|
||||
"summary": "The Magnavox Odyssey is the first commercial home video game console. It was developed by a small team led by Ralph H. Baer at Sanders Associates and released by Magnavox in the United States in September 1972 and overseas the following year. The Odyssey consists of a white, black, and brown box which connects to a television set and two rectangular controllers attached by wires. It is capable of displaying three square dots on the screen in monochrome black and white, with different behavior of the dots depending on the game played, and has no sound capabilities. Players place plastic overlays on the screen to create visuals, and the one or two players for each game control their dots with the three knobs and one button on the controller in accordance with the rules given for the game. The Odyssey console came packaged with dice, paper money, and other board game paraphernalia to go along with the games, and a peripheral controller—the first video game light gun—was sold separately.The idea for a video game console was thought up by Baer in August 1966, and over the next three years he, along with Bill Harrison and Bill Rusch, created seven successive prototype consoles. The seventh, known as the Brown Box, was shown to several manufacturers before Magnavox agreed to produce it in January 1971. After releasing the console in September 1972 through their dealerships, Magnavox sold between 69,000 and 100,000 units by the end of the year, and 350,000 by the time the console was discontinued in 1975. The console spawned the Magnavox Odyssey series of dedicated consoles, as well as the 1978 Magnavox Odyssey². One of the 28 games made for the system, a ping pong game, was an inspiration for Atari's successful Pong arcade game, in turn driving sales of the console. Baer's patents for the console and the games, including what was termed by a judge as 'the pioneering patent of the video game art', formed the basis of a series of lawsuits over 20 years, earning Sanders and Magnavox over US$100 million. The release of the Odyssey marked the end of the early history of video games, and the rise of the commercial video game industry along with the start of the first generation of video game consoles.",
|
||||
"summary": "The Magnavox Odyssey is the first commercial home video game console. It was developed by a small team led by Ralph H. Baer at Sanders Associates and released by Magnavox in the United States in September 1972 and overseas the following year. The Odyssey consists of a white, black, and brown box which connects to a television set and two rectangular controllers attached by wires. It is capable of displaying three square dots on the screen in monochrome black and white, with different behavior of the dots depending on the game played, and has no sound capabilities. Players place plastic overlays on the screen to create visuals, and the one or two players for each game control their dots with the three knobs and one button on the controller in accordance with the rules given for the game. The Odyssey console came packaged with dice, paper money, and other board game paraphernalia to go along with the games, and a peripheral controller, the first video game light gun, was sold separately.The idea for a video game console was thought up by Baer in August 1966, and over the next three years he, along with Bill Harrison and Bill Rusch, created seven successive prototype consoles. The seventh, known as the Brown Box, was shown to several manufacturers before Magnavox agreed to produce it in January 1971. After releasing the console in September 1972 through their dealerships, Magnavox sold between 69,000 and 100,000 units by the end of the year, and 350,000 by the time the console was discontinued in 1975. The console spawned the Magnavox Odyssey series of dedicated consoles, as well as the 1978 Magnavox Odyssey². One of the 28 games made for the system, a ping pong game, was an inspiration for Atari's successful Pong arcade game, in turn driving sales of the console. Baer's patents for the console and the games, including what was termed by a judge as 'the pioneering patent of the video game art', formed the basis of a series of lawsuits over 20 years, earning Sanders and Magnavox over US$100 million. The release of the Odyssey marked the end of the early history of video games, and the rise of the commercial video game industry along with the start of the first generation of video game consoles.",
|
||||
"url_logo": None,
|
||||
},
|
||||
UPS.ODYSSEY_2: {
|
||||
@@ -1275,7 +1275,7 @@ TGDB_PLATFORM_LIST: dict[UPS, SlugToTGDBId] = {
|
||||
"sound": "2 square wave generators, 1 PCM 4-bit wave sample channel",
|
||||
"display": "160 x 144",
|
||||
"max_controllers": "1",
|
||||
"summary": "The Game Boy, is an 8-bit handheld video game device developed and manufactured by Nintendo. It was released in Japan on April 21, 1989, in North America in August 1989, and in Europe on September 28, 1990. It is the first handheld console in the Game Boy line, and was created by Gunpei Yokoi and Nintendo Research & Development 1—the same staff who had designed the Game & Watch series as well as several popular games for the Nintendo Entertainment System.",
|
||||
"summary": "The Game Boy, is an 8-bit handheld video game device developed and manufactured by Nintendo. It was released in Japan on April 21, 1989, in North America in August 1989, and in Europe on September 28, 1990. It is the first handheld console in the Game Boy line, and was created by Gunpei Yokoi and Nintendo Research & Development 1, the same staff who had designed the Game & Watch series as well as several popular games for the Nintendo Entertainment System.",
|
||||
"url_logo": None,
|
||||
},
|
||||
UPS.GBA: {
|
||||
|
||||
+244
-73
@@ -29,11 +29,15 @@ from handler.metadata.gamelist_handler import GamelistRom
|
||||
from handler.metadata.hasheous_handler import HASHEOUS_PLATFORM_LIST, HasheousRom
|
||||
from handler.metadata.hltb_handler import HLTB_PLATFORM_LIST, HLTBRom
|
||||
from handler.metadata.igdb_handler import IGDB_PLATFORM_LIST, IGDBRom
|
||||
from handler.metadata.launchbox_handler.media import populate_rom_specific_paths
|
||||
from handler.metadata.launchbox_handler.platforms import LAUNCHBOX_PLATFORM_LIST
|
||||
from handler.metadata.launchbox_handler.types import LaunchboxRom
|
||||
from handler.metadata.libretro_handler import LIBRETRO_PLATFORM_LIST, LibretroRom
|
||||
from handler.metadata.moby_handler import MOBYGAMES_PLATFORM_LIST, MobyGamesRom
|
||||
from handler.metadata.playmatch_handler import PlaymatchRomMatch
|
||||
from handler.metadata.playmatch_handler import (
|
||||
PLAYMATCH_SUPPORTED_SOURCES,
|
||||
PlaymatchRomMatch,
|
||||
)
|
||||
from handler.metadata.ra_handler import RA_PLATFORM_LIST, RAGameRom
|
||||
from handler.metadata.sgdb_handler import SGDBRom
|
||||
from handler.metadata.ss_handler import SCREENSAVER_PLATFORM_LIST, SSRom
|
||||
@@ -74,6 +78,7 @@ class MetadataSource(enum.StrEnum):
|
||||
HLTB = "hltb" # HowLongToBeat
|
||||
GAMELIST = "gamelist" # ES-DE gamelist.xml
|
||||
LIBRETRO = "libretro" # Libretro thumbnails
|
||||
PLAYMATCH = "playmatch" # Playmatch
|
||||
|
||||
|
||||
def get_main_platform_igdb_id(platform: Platform):
|
||||
@@ -371,19 +376,32 @@ async def scan_rom(
|
||||
|
||||
async def fetch_playmatch_hash_match() -> PlaymatchRomMatch:
|
||||
if (
|
||||
playmatch_enabled
|
||||
and MetadataSource.IGDB in metadata_sources
|
||||
and platform.igdb_id
|
||||
meta_playmatch_handler.is_enabled()
|
||||
and MetadataSource.PLAYMATCH in metadata_sources
|
||||
and any(PLAYMATCH_SUPPORTED_SOURCES.intersection(metadata_sources))
|
||||
and (
|
||||
newly_added
|
||||
or scan_type == ScanType.COMPLETE
|
||||
or (scan_type == ScanType.UPDATE and rom.igdb_id)
|
||||
or (scan_type == ScanType.UNMATCHED and not rom.igdb_id)
|
||||
or scan_type == ScanType.UPDATE
|
||||
or scan_type == ScanType.UNMATCHED
|
||||
)
|
||||
):
|
||||
return await meta_playmatch_handler.lookup_rom(fs_rom["files"])
|
||||
return await meta_playmatch_handler.lookup_rom(fs_rom["files"] or rom.files)
|
||||
|
||||
return PlaymatchRomMatch(igdb_id=None)
|
||||
return PlaymatchRomMatch(
|
||||
igdb_id=None,
|
||||
moby_id=None,
|
||||
ss_id=None,
|
||||
launchbox_id=None,
|
||||
sgdb_id=None,
|
||||
ra_id=None,
|
||||
hasheous_id=None,
|
||||
tgdb_id=None,
|
||||
flashpoint_id=None,
|
||||
hltb_id=None,
|
||||
libretro_id=None,
|
||||
gamelist_id=None,
|
||||
)
|
||||
|
||||
async def fetch_hasheous_hash_match() -> HasheousRom:
|
||||
if (
|
||||
@@ -395,13 +413,13 @@ async def scan_rom(
|
||||
or (scan_type == ScanType.UPDATE and rom.hasheous_id)
|
||||
or (
|
||||
scan_type == ScanType.UNMATCHED
|
||||
and not rom.hasheous_id
|
||||
and (not rom.hasheous_id or not rom.hasheous_metadata)
|
||||
and rom.platform_slug in HASHEOUS_PLATFORM_LIST
|
||||
)
|
||||
)
|
||||
):
|
||||
return await meta_hasheous_handler.lookup_rom(
|
||||
platform.slug, fs_rom["files"]
|
||||
platform.slug, fs_rom["files"] or rom.files
|
||||
)
|
||||
|
||||
return HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None)
|
||||
@@ -446,7 +464,7 @@ async def scan_rom(
|
||||
or (scan_type == ScanType.UPDATE and rom.igdb_id)
|
||||
or (
|
||||
scan_type == ScanType.UNMATCHED
|
||||
and not rom.igdb_id
|
||||
and (not rom.igdb_id or not rom.igdb_metadata)
|
||||
and rom.platform_slug in IGDB_PLATFORM_LIST
|
||||
)
|
||||
)
|
||||
@@ -459,7 +477,7 @@ async def scan_rom(
|
||||
f"{hl(str(h_igdb_id), color=BLUE)} {emoji.EMOJI_ALIEN_MONSTER}",
|
||||
extra=LOGGER_MODULE_NAME,
|
||||
)
|
||||
return await meta_igdb_handler.get_rom_by_id(h_igdb_id)
|
||||
return await meta_igdb_handler.get_rom_by_id(rom, h_igdb_id)
|
||||
|
||||
# Use Playmatch matches to get the IGDB ID
|
||||
if playmatch_rom["igdb_id"] is not None:
|
||||
@@ -469,16 +487,20 @@ async def scan_rom(
|
||||
extra=LOGGER_MODULE_NAME,
|
||||
)
|
||||
|
||||
return await meta_igdb_handler.get_rom_by_id(playmatch_rom["igdb_id"])
|
||||
return await meta_igdb_handler.get_rom_by_id(
|
||||
rom, playmatch_rom["igdb_id"]
|
||||
)
|
||||
|
||||
main_platform_igdb_id = get_main_platform_igdb_id(platform)
|
||||
if scan_type == ScanType.UPDATE and rom.igdb_id:
|
||||
# Use the ID to refetch the metadata from IGDB
|
||||
return await meta_igdb_handler.get_rom_by_id(rom.igdb_id)
|
||||
return await meta_igdb_handler.get_rom_by_id(rom, rom.igdb_id)
|
||||
else:
|
||||
# If no matches found, use the file name to get the IGDB ID
|
||||
return await meta_igdb_handler.get_rom(
|
||||
rom_attrs["fs_name"], main_platform_igdb_id or platform.igdb_id
|
||||
rom,
|
||||
rom_attrs["fs_name"],
|
||||
main_platform_igdb_id or platform.igdb_id,
|
||||
)
|
||||
|
||||
return IGDBRom(igdb_id=None)
|
||||
@@ -488,7 +510,10 @@ async def scan_rom(
|
||||
newly_added
|
||||
or scan_type == ScanType.COMPLETE
|
||||
or (scan_type == ScanType.UPDATE and rom.gamelist_id)
|
||||
or (scan_type == ScanType.UNMATCHED and not rom.gamelist_id)
|
||||
or (
|
||||
scan_type == ScanType.UNMATCHED
|
||||
and (not rom.gamelist_id or not rom.gamelist_metadata)
|
||||
)
|
||||
):
|
||||
return await meta_gamelist_handler.get_rom(
|
||||
rom_attrs["fs_name"], platform, rom
|
||||
@@ -506,12 +531,16 @@ async def scan_rom(
|
||||
or (scan_type == ScanType.UPDATE and rom.flashpoint_id)
|
||||
or (
|
||||
scan_type == ScanType.UNMATCHED
|
||||
and not rom.flashpoint_id
|
||||
and (not rom.flashpoint_id or not rom.flashpoint_metadata)
|
||||
and platform.slug in FLASHPOINT_PLATFORM_LIST
|
||||
)
|
||||
)
|
||||
):
|
||||
if scan_type == ScanType.UPDATE and rom.flashpoint_id:
|
||||
if (scan_type == ScanType.UPDATE and rom.flashpoint_id) or (
|
||||
scan_type == ScanType.UNMATCHED
|
||||
and rom.flashpoint_id
|
||||
and not rom.flashpoint_metadata
|
||||
):
|
||||
return await meta_flashpoint_handler.get_rom_by_id(rom.flashpoint_id)
|
||||
else:
|
||||
return await meta_flashpoint_handler.get_rom(
|
||||
@@ -545,14 +574,17 @@ async def scan_rom(
|
||||
newly_added
|
||||
or scan_type == ScanType.COMPLETE
|
||||
or (scan_type == ScanType.UPDATE and rom.hltb_id)
|
||||
or (scan_type == ScanType.UNMATCHED and not rom.hltb_id)
|
||||
or (
|
||||
scan_type == ScanType.UNMATCHED
|
||||
and (not rom.hltb_id or not rom.hltb_metadata)
|
||||
)
|
||||
)
|
||||
):
|
||||
return await meta_hltb_handler.get_rom(rom_attrs["fs_name"], platform.slug)
|
||||
|
||||
return HLTBRom(hltb_id=None)
|
||||
|
||||
async def fetch_moby_rom() -> MobyGamesRom:
|
||||
async def fetch_moby_rom(playmatch_rom: PlaymatchRomMatch) -> MobyGamesRom:
|
||||
if (
|
||||
MetadataSource.MOBY in metadata_sources
|
||||
and platform.moby_id
|
||||
@@ -562,21 +594,29 @@ async def scan_rom(
|
||||
or (scan_type == ScanType.UPDATE and rom.moby_id)
|
||||
or (
|
||||
scan_type == ScanType.UNMATCHED
|
||||
and not rom.moby_id
|
||||
and (not rom.moby_id or not rom.moby_metadata)
|
||||
and rom.platform_slug in MOBYGAMES_PLATFORM_LIST
|
||||
)
|
||||
)
|
||||
):
|
||||
if scan_type == ScanType.UPDATE and rom.moby_id:
|
||||
return await meta_moby_handler.get_rom_by_id(rom.moby_id)
|
||||
else:
|
||||
return await meta_moby_handler.get_rom(
|
||||
rom_attrs["fs_name"], platform_moby_id=platform.moby_id
|
||||
|
||||
if playmatch_rom["moby_id"] is not None:
|
||||
log.debug(
|
||||
f"{hl(rom_attrs['fs_name'])} identified by Playmatch as MobyGames "
|
||||
f"{hl(str(playmatch_rom['moby_id']), color=BLUE)} {emoji.EMOJI_ALIEN_MONSTER}",
|
||||
extra=LOGGER_MODULE_NAME,
|
||||
)
|
||||
return await meta_moby_handler.get_rom_by_id(playmatch_rom["moby_id"])
|
||||
|
||||
return await meta_moby_handler.get_rom(
|
||||
rom_attrs["fs_name"], platform_moby_id=platform.moby_id
|
||||
)
|
||||
|
||||
return MobyGamesRom(moby_id=None)
|
||||
|
||||
async def fetch_ss_rom() -> SSRom:
|
||||
async def fetch_ss_rom(playmatch_rom: PlaymatchRomMatch) -> SSRom:
|
||||
if (
|
||||
MetadataSource.SS in metadata_sources
|
||||
and platform.ss_id
|
||||
@@ -586,7 +626,7 @@ async def scan_rom(
|
||||
or (scan_type == ScanType.UPDATE and rom.ss_id)
|
||||
or (
|
||||
scan_type == ScanType.UNMATCHED
|
||||
and not rom.ss_id
|
||||
and (not rom.ss_id or not rom.ss_metadata)
|
||||
and rom.platform_slug in SCREENSAVER_PLATFORM_LIST
|
||||
)
|
||||
)
|
||||
@@ -595,11 +635,20 @@ async def scan_rom(
|
||||
if scan_type == ScanType.UPDATE and rom.ss_id:
|
||||
return await meta_ss_handler.get_rom_by_id(rom, rom.ss_id)
|
||||
|
||||
# Use Playmatch's hash-based id when available
|
||||
if playmatch_rom["ss_id"] is not None:
|
||||
log.debug(
|
||||
f"{hl(rom_attrs['fs_name'])} identified by Playmatch as ScreenScraper "
|
||||
f"{hl(str(playmatch_rom['ss_id']), color=BLUE)} {emoji.EMOJI_ALIEN_MONSTER}",
|
||||
extra=LOGGER_MODULE_NAME,
|
||||
)
|
||||
return await meta_ss_handler.get_rom_by_id(rom, playmatch_rom["ss_id"])
|
||||
|
||||
# Use the file hashes for lookup
|
||||
game_by_hash = await meta_ss_handler.lookup_rom(
|
||||
rom, platform.ss_id, fs_rom["files"]
|
||||
game_by_hash, is_not_game = await meta_ss_handler.lookup_rom(
|
||||
rom, platform.ss_id, fs_rom["files"] or rom.files
|
||||
)
|
||||
if game_by_hash.get("ss_id"):
|
||||
if game_by_hash.get("ss_id") or is_not_game:
|
||||
return game_by_hash
|
||||
|
||||
# Fallback to the filename
|
||||
@@ -609,14 +658,16 @@ async def scan_rom(
|
||||
|
||||
return SSRom(ss_id=None)
|
||||
|
||||
async def fetch_launchbox_rom(platform_slug: str) -> LaunchboxRom:
|
||||
async def fetch_launchbox_rom(
|
||||
platform_slug: str, playmatch_rom: PlaymatchRomMatch
|
||||
) -> LaunchboxRom:
|
||||
if MetadataSource.LAUNCHBOX in metadata_sources and (
|
||||
newly_added
|
||||
or scan_type == ScanType.COMPLETE
|
||||
or (scan_type == ScanType.UPDATE and rom.launchbox_id)
|
||||
or (
|
||||
scan_type == ScanType.UNMATCHED
|
||||
and not rom.launchbox_id
|
||||
and (not rom.launchbox_id or not rom.launchbox_metadata)
|
||||
and rom.platform_slug in LAUNCHBOX_PLATFORM_LIST
|
||||
)
|
||||
):
|
||||
@@ -625,15 +676,49 @@ async def scan_rom(
|
||||
and rom.launchbox_id
|
||||
and launchbox_remote_enabled
|
||||
):
|
||||
return await meta_launchbox_handler.get_rom_by_id(
|
||||
rom.launchbox_id, remote_enabled=True
|
||||
launchbox_rom = await meta_launchbox_handler.get_rom_by_id(
|
||||
rom.launchbox_id,
|
||||
remote_enabled=True,
|
||||
fs_name=rom_attrs["fs_name"],
|
||||
platform_slug=platform_slug,
|
||||
)
|
||||
elif (
|
||||
scan_type == ScanType.UNMATCHED
|
||||
and rom.launchbox_id
|
||||
and not rom.launchbox_metadata
|
||||
and launchbox_remote_enabled
|
||||
):
|
||||
# ID was set manually but metadata was never fetched
|
||||
launchbox_rom = await meta_launchbox_handler.get_rom_by_id(
|
||||
rom.launchbox_id,
|
||||
remote_enabled=True,
|
||||
fs_name=rom_attrs["fs_name"],
|
||||
platform_slug=platform_slug,
|
||||
)
|
||||
elif playmatch_rom["launchbox_id"] is not None and launchbox_remote_enabled:
|
||||
log.debug(
|
||||
f"{hl(rom_attrs['fs_name'])} identified by Playmatch as LaunchBox "
|
||||
f"{hl(str(playmatch_rom['launchbox_id']), color=BLUE)} {emoji.EMOJI_ALIEN_MONSTER}",
|
||||
extra=LOGGER_MODULE_NAME,
|
||||
)
|
||||
launchbox_rom = await meta_launchbox_handler.get_rom_by_id(
|
||||
playmatch_rom["launchbox_id"],
|
||||
remote_enabled=True,
|
||||
fs_name=rom_attrs["fs_name"],
|
||||
platform_slug=platform_slug,
|
||||
)
|
||||
else:
|
||||
launchbox_rom = await meta_launchbox_handler.get_rom(
|
||||
rom_attrs["fs_name"],
|
||||
platform_slug,
|
||||
remote_enabled=launchbox_remote_enabled,
|
||||
)
|
||||
|
||||
return await meta_launchbox_handler.get_rom(
|
||||
rom_attrs["fs_name"],
|
||||
platform_slug,
|
||||
remote_enabled=launchbox_remote_enabled,
|
||||
)
|
||||
metadata = launchbox_rom.get("launchbox_metadata")
|
||||
if metadata:
|
||||
populate_rom_specific_paths(metadata, rom)
|
||||
|
||||
return launchbox_rom
|
||||
|
||||
return LaunchboxRom(launchbox_id=None)
|
||||
|
||||
@@ -648,7 +733,7 @@ async def scan_rom(
|
||||
or (scan_type == ScanType.UPDATE and rom.ra_id)
|
||||
or (
|
||||
scan_type == ScanType.UNMATCHED
|
||||
and not rom.ra_id
|
||||
and (not rom.ra_id or not rom.ra_metadata)
|
||||
and rom.platform_slug in RA_PLATFORM_LIST
|
||||
)
|
||||
)
|
||||
@@ -663,7 +748,9 @@ async def scan_rom(
|
||||
)
|
||||
return await meta_ra_handler.get_rom_by_id(rom=rom, ra_id=h_ra_id)
|
||||
|
||||
if scan_type == ScanType.UPDATE and rom.ra_id:
|
||||
if (scan_type == ScanType.UPDATE and rom.ra_id) or (
|
||||
scan_type == ScanType.UNMATCHED and rom.ra_id and not rom.ra_metadata
|
||||
):
|
||||
return await meta_ra_handler.get_rom_by_id(rom=rom, ra_id=rom.ra_id)
|
||||
else:
|
||||
return await meta_ra_handler.get_rom(
|
||||
@@ -682,7 +769,7 @@ async def scan_rom(
|
||||
or (scan_type == ScanType.UPDATE and rom.hasheous_id)
|
||||
or (
|
||||
scan_type == ScanType.UNMATCHED
|
||||
and not rom.hasheous_id
|
||||
and (not rom.hasheous_id or not rom.hasheous_metadata)
|
||||
and rom.platform_slug in HASHEOUS_PLATFORM_LIST
|
||||
)
|
||||
)
|
||||
@@ -719,10 +806,10 @@ async def scan_rom(
|
||||
libretro_handler_rom,
|
||||
) = await asyncio.gather(
|
||||
fetch_igdb_rom(playmatch_hash_match, hasheous_hash_match),
|
||||
fetch_moby_rom(),
|
||||
fetch_ss_rom(),
|
||||
fetch_moby_rom(playmatch_hash_match),
|
||||
fetch_ss_rom(playmatch_hash_match),
|
||||
fetch_ra_rom(hasheous_hash_match),
|
||||
fetch_launchbox_rom(platform.slug),
|
||||
fetch_launchbox_rom(platform.slug, playmatch_hash_match),
|
||||
fetch_hasheous_rom(hasheous_hash_match),
|
||||
fetch_flashpoint_rom(),
|
||||
fetch_hltb_rom(),
|
||||
@@ -730,22 +817,96 @@ async def scan_rom(
|
||||
fetch_libretro_rom(),
|
||||
)
|
||||
|
||||
metadata_handlers = {
|
||||
MetadataSource.IGDB: igdb_handler_rom,
|
||||
MetadataSource.MOBY: moby_handler_rom,
|
||||
MetadataSource.SS: ss_handler_rom,
|
||||
MetadataSource.RA: ra_handler_rom,
|
||||
MetadataSource.LAUNCHBOX: launchbox_handler_rom,
|
||||
MetadataSource.HASHEOUS: hasheous_handler_rom,
|
||||
MetadataSource.FLASHPOINT: flashpoint_handler_rom,
|
||||
MetadataSource.HLTB: hltb_handler_rom,
|
||||
MetadataSource.GAMELIST: gamelist_handler_rom,
|
||||
MetadataSource.LIBRETRO: libretro_handler_rom,
|
||||
metadata_handlers: dict[MetadataSource, dict] = {
|
||||
MetadataSource.IGDB: {
|
||||
"handler": igdb_handler_rom,
|
||||
"id_field": "igdb_id",
|
||||
"metadata_field": "igdb_metadata",
|
||||
},
|
||||
MetadataSource.MOBY: {
|
||||
"handler": moby_handler_rom,
|
||||
"id_field": "moby_id",
|
||||
"metadata_field": "moby_metadata",
|
||||
},
|
||||
MetadataSource.SS: {
|
||||
"handler": ss_handler_rom,
|
||||
"id_field": "ss_id",
|
||||
"metadata_field": "ss_metadata",
|
||||
},
|
||||
MetadataSource.RA: {
|
||||
"handler": ra_handler_rom,
|
||||
"id_field": "ra_id",
|
||||
"metadata_field": "ra_metadata",
|
||||
},
|
||||
MetadataSource.LAUNCHBOX: {
|
||||
"handler": launchbox_handler_rom,
|
||||
"id_field": "launchbox_id",
|
||||
"metadata_field": "launchbox_metadata",
|
||||
},
|
||||
MetadataSource.HASHEOUS: {
|
||||
"handler": hasheous_handler_rom,
|
||||
"id_field": "hasheous_id",
|
||||
"metadata_field": "hasheous_metadata",
|
||||
},
|
||||
MetadataSource.FLASHPOINT: {
|
||||
"handler": flashpoint_handler_rom,
|
||||
"id_field": "flashpoint_id",
|
||||
"metadata_field": "flashpoint_metadata",
|
||||
},
|
||||
MetadataSource.HLTB: {
|
||||
"handler": hltb_handler_rom,
|
||||
"id_field": "hltb_id",
|
||||
"metadata_field": "hltb_metadata",
|
||||
},
|
||||
MetadataSource.GAMELIST: {
|
||||
"handler": gamelist_handler_rom,
|
||||
"id_field": "gamelist_id",
|
||||
"metadata_field": "gamelist_metadata",
|
||||
},
|
||||
MetadataSource.LIBRETRO: {
|
||||
"handler": libretro_handler_rom,
|
||||
"id_field": "libretro_id",
|
||||
"metadata_field": None,
|
||||
},
|
||||
MetadataSource.SGDB: {
|
||||
"handler": {},
|
||||
"id_field": "sgdb_id",
|
||||
"metadata_field": None,
|
||||
},
|
||||
MetadataSource.TGDB: {
|
||||
"handler": {},
|
||||
"id_field": "tgdb_id",
|
||||
"metadata_field": None,
|
||||
},
|
||||
}
|
||||
|
||||
# For COMPLETE rescans, explicitly clear metadata IDs and metadata for unselected sources
|
||||
# This ensures that when a source is no longer selected, its data is removed from the ROM
|
||||
if not newly_added and scan_type == ScanType.COMPLETE:
|
||||
for source, fields in metadata_handlers.items():
|
||||
if source not in metadata_sources:
|
||||
rom_attrs[fields["id_field"]] = None
|
||||
if fields["metadata_field"]:
|
||||
rom_attrs[fields["metadata_field"]] = {}
|
||||
|
||||
# Reset artwork fields so stale values are cleared when no source supplies them
|
||||
rom_attrs.update(
|
||||
{
|
||||
"url_cover": "",
|
||||
"url_screenshots": [],
|
||||
"url_manual": "",
|
||||
"path_cover_s": "",
|
||||
"path_cover_l": "",
|
||||
"path_screenshots": [],
|
||||
"path_manual": "",
|
||||
}
|
||||
)
|
||||
|
||||
# Determine which metadata sources are available
|
||||
available_sources = [
|
||||
name for name, handler in metadata_handlers.items() if handler.get(f"{name}_id")
|
||||
name
|
||||
for name, fields in metadata_handlers.items()
|
||||
if fields["handler"].get(fields["id_field"])
|
||||
]
|
||||
|
||||
# Apply metadata priority order
|
||||
@@ -754,7 +915,7 @@ async def scan_rom(
|
||||
)
|
||||
# Reverse priority order to apply highest priority last
|
||||
for source_name in reversed(priority_ordered):
|
||||
handler_data = metadata_handlers[source_name]
|
||||
handler_data = metadata_handlers[source_name]["handler"]
|
||||
# Only update fields that have valid values
|
||||
for key, field_value in handler_data.items():
|
||||
if field_value:
|
||||
@@ -766,7 +927,7 @@ async def scan_rom(
|
||||
)
|
||||
# Reverse priority order to apply highest priority last
|
||||
for source_name in reversed(priority_ordered_artwork):
|
||||
handler_data = metadata_handlers[source_name]
|
||||
handler_data = metadata_handlers[source_name]["handler"]
|
||||
for field in ["url_cover", "url_screenshots", "url_manual"]:
|
||||
# Only update fields that have valid values
|
||||
field_value = handler_data.get(field)
|
||||
@@ -822,7 +983,7 @@ async def scan_rom(
|
||||
)
|
||||
return Rom(**rom_attrs)
|
||||
|
||||
async def fetch_sgdb_details() -> SGDBRom:
|
||||
async def fetch_sgdb_details(playmatch_rom: PlaymatchRomMatch) -> SGDBRom:
|
||||
"""Fetch SteamGridDB details for the ROM."""
|
||||
if MetadataSource.SGDB in metadata_sources and (
|
||||
newly_added
|
||||
@@ -832,22 +993,30 @@ async def scan_rom(
|
||||
):
|
||||
if scan_type == ScanType.UPDATE and rom.sgdb_id:
|
||||
return await meta_sgdb_handler.get_rom_by_id(rom.sgdb_id)
|
||||
else:
|
||||
game_names = [
|
||||
igdb_handler_rom.get("name", None),
|
||||
hasheous_handler_rom.get("name", None),
|
||||
ss_handler_rom.get("name", None),
|
||||
moby_handler_rom.get("name", None),
|
||||
launchbox_handler_rom.get("name", None),
|
||||
gamelist_handler_rom.get("name", None),
|
||||
rom_attrs["fs_name_no_tags"],
|
||||
]
|
||||
game_names = [name for name in game_names if name]
|
||||
return await meta_sgdb_handler.get_details_by_names(game_names)
|
||||
|
||||
if playmatch_rom["sgdb_id"] is not None:
|
||||
log.debug(
|
||||
f"{hl(rom_attrs['fs_name'])} identified by Playmatch as SteamGridDB "
|
||||
f"{hl(str(playmatch_rom['sgdb_id']), color=BLUE)} {emoji.EMOJI_ALIEN_MONSTER}",
|
||||
extra=LOGGER_MODULE_NAME,
|
||||
)
|
||||
return await meta_sgdb_handler.get_rom_by_id(playmatch_rom["sgdb_id"])
|
||||
|
||||
game_names = [
|
||||
igdb_handler_rom.get("name", None),
|
||||
hasheous_handler_rom.get("name", None),
|
||||
ss_handler_rom.get("name", None),
|
||||
moby_handler_rom.get("name", None),
|
||||
launchbox_handler_rom.get("name", None),
|
||||
gamelist_handler_rom.get("name", None),
|
||||
rom_attrs["fs_name_no_tags"],
|
||||
]
|
||||
game_names = [name for name in game_names if name]
|
||||
return await meta_sgdb_handler.get_details_by_names(game_names)
|
||||
|
||||
return SGDBRom(sgdb_id=None)
|
||||
|
||||
sgdb_hander_rom = await fetch_sgdb_details()
|
||||
sgdb_hander_rom = await fetch_sgdb_details(playmatch_hash_match)
|
||||
if sgdb_hander_rom.get("sgdb_id"):
|
||||
rom_attrs["sgdb_id"] = sgdb_hander_rom["sgdb_id"]
|
||||
|
||||
@@ -862,7 +1031,9 @@ async def scan_rom(
|
||||
)
|
||||
if sgdb_cover and not manual_cover_preserved:
|
||||
cover_sources = [
|
||||
name for name, h in metadata_handlers.items() if h.get("url_cover")
|
||||
name
|
||||
for name, fields in metadata_handlers.items()
|
||||
if fields["handler"].get("url_cover")
|
||||
]
|
||||
ranked = get_priority_ordered_metadata_sources(
|
||||
cover_sources + [MetadataSource.SGDB], "artwork"
|
||||
|
||||
@@ -11,6 +11,7 @@ device's sync_config.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import hashlib
|
||||
import os
|
||||
import tempfile
|
||||
@@ -49,7 +50,14 @@ class SSHSyncHandler:
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.keys_path = Path(SYNC_SSH_KEYS_PATH)
|
||||
self.keys_path.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
self.keys_path.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as e:
|
||||
raise RuntimeError(
|
||||
f"SSH keys directory {self.keys_path} is not writable ({e}). "
|
||||
"Mount a writable volume at this path, or set SYNC_SSH_KEYS_PATH "
|
||||
"to a writable location, to use push-pull sync."
|
||||
) from e
|
||||
|
||||
def _resolve_key_path(self, device_id: str, sync_config: dict) -> str | None:
|
||||
"""Resolve the SSH key path for a device.
|
||||
@@ -224,4 +232,12 @@ class SSHSyncHandler:
|
||||
log.info(f"Deleted remote file: {remote_path}")
|
||||
|
||||
|
||||
ssh_sync_handler = SSHSyncHandler()
|
||||
@functools.cache
|
||||
def get_ssh_sync_handler() -> SSHSyncHandler:
|
||||
"""Lazily instantiate the SSH sync handler on first use.
|
||||
|
||||
Deferred so that startup doesn't fail when push-pull sync is unconfigured
|
||||
or the keys directory is not writable. The handler raises a clear error
|
||||
at call time if the directory cannot be created.
|
||||
"""
|
||||
return SSHSyncHandler()
|
||||
@@ -1,4 +1,5 @@
|
||||
import logging
|
||||
import re
|
||||
from pprint import pformat
|
||||
|
||||
from colorama import Fore, Style, init
|
||||
@@ -116,7 +117,14 @@ class Formatter(logging.Formatter):
|
||||
}
|
||||
log_fmt = formats.get(record.levelno)
|
||||
formatter = logging.Formatter(fmt=log_fmt, datefmt="%Y-%m-%d %H:%M:%S")
|
||||
return formatter.format(record)
|
||||
output = formatter.format(record)
|
||||
|
||||
try:
|
||||
from handler.metadata.base_handler import SENSITIVE_KEYS_REGEX
|
||||
|
||||
return SENSITIVE_KEYS_REGEX.sub(r"\1=***", output)
|
||||
except ImportError:
|
||||
return output # skip redaction on the first few boot log lines
|
||||
|
||||
|
||||
def highlight(msg: str = "", color=YELLOW) -> str:
|
||||
|
||||
+56
-12
@@ -16,9 +16,12 @@ from sqlalchemy import (
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
and_,
|
||||
func,
|
||||
or_,
|
||||
select,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from sqlalchemy.orm import Mapped, column_property, mapped_column, relationship
|
||||
|
||||
from config import FRONTEND_RESOURCES_PATH
|
||||
from models.base import (
|
||||
@@ -77,6 +80,7 @@ class RomFile(BaseModel):
|
||||
md5_hash: Mapped[str | None] = mapped_column(String(100))
|
||||
sha1_hash: Mapped[str | None] = mapped_column(String(100))
|
||||
ra_hash: Mapped[str | None] = mapped_column(String(100))
|
||||
chd_sha1_hash: Mapped[str | None] = mapped_column(String(100))
|
||||
category: Mapped[RomFileCategory | None] = mapped_column(
|
||||
Enum(RomFileCategory), default=None
|
||||
)
|
||||
@@ -85,7 +89,7 @@ class RomFile(BaseModel):
|
||||
)
|
||||
missing_from_fs: Mapped[bool] = mapped_column(default=False, nullable=False)
|
||||
|
||||
rom: Mapped[Rom] = relationship(lazy="joined", back_populates="files")
|
||||
rom: Mapped[Rom] = relationship(back_populates="files")
|
||||
|
||||
@cached_property
|
||||
def full_path(self) -> str:
|
||||
@@ -327,21 +331,22 @@ class Rom(BaseModel):
|
||||
|
||||
return []
|
||||
|
||||
@cached_property
|
||||
if TYPE_CHECKING:
|
||||
# Defined out-of-line at module scope via column_property
|
||||
multi_file: Mapped[bool]
|
||||
top_level_file_count: Mapped[int]
|
||||
|
||||
@property
|
||||
def has_simple_single_file(self) -> bool:
|
||||
return len(self.files) == 1 and not self.files[0].is_nested
|
||||
return not self.multi_file and self.top_level_file_count == 1
|
||||
|
||||
@cached_property
|
||||
def _top_level_files(self) -> list[RomFile]:
|
||||
return [f for f in self.files if f.is_top_level]
|
||||
|
||||
@cached_property
|
||||
@property
|
||||
def has_nested_single_file(self) -> bool:
|
||||
return not self.has_simple_single_file and len(self._top_level_files) == 1
|
||||
return self.multi_file and self.top_level_file_count == 1
|
||||
|
||||
@cached_property
|
||||
@property
|
||||
def has_multiple_files(self) -> bool:
|
||||
return len(self._top_level_files) > 1
|
||||
return self.top_level_file_count > 1
|
||||
|
||||
@property
|
||||
def fs_resources_path(self) -> str:
|
||||
@@ -369,6 +374,7 @@ class Rom(BaseModel):
|
||||
(self.ss_metadata or {}).get("video_path")
|
||||
or (self.ss_metadata or {}).get("video_normalized_path")
|
||||
or (self.gamelist_metadata or {}).get("video_path")
|
||||
or (self.launchbox_metadata or {}).get("video_path")
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -383,6 +389,7 @@ class Rom(BaseModel):
|
||||
and not self.flashpoint_id
|
||||
and not self.hltb_id
|
||||
and not self.gamelist_id
|
||||
and not self.libretro_id
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -451,6 +458,43 @@ class Rom(BaseModel):
|
||||
return f"{self.fs_name} ({self.id})"
|
||||
|
||||
|
||||
# Correlated scalar subqueries against rom_files, deferred and opt-in via `undefer`
|
||||
# Revisit (real columns, JOIN/aggregate, or added indexes) if gallery latency regresses
|
||||
_rom_full_path = func.concat(Rom.fs_path, "/", Rom.fs_name)
|
||||
|
||||
Rom.multi_file = column_property(
|
||||
select(RomFile.id)
|
||||
.where(
|
||||
and_(
|
||||
RomFile.rom_id == Rom.id,
|
||||
RomFile.file_path != Rom.fs_path,
|
||||
)
|
||||
)
|
||||
.correlate_except(RomFile)
|
||||
.exists()
|
||||
.select()
|
||||
.scalar_subquery(),
|
||||
deferred=True,
|
||||
)
|
||||
|
||||
Rom.top_level_file_count = column_property(
|
||||
select(func.count(RomFile.id))
|
||||
.where(
|
||||
and_(
|
||||
RomFile.rom_id == Rom.id,
|
||||
or_(
|
||||
func.concat(RomFile.file_path, "/", RomFile.file_name)
|
||||
== _rom_full_path,
|
||||
RomFile.file_path == _rom_full_path,
|
||||
),
|
||||
)
|
||||
)
|
||||
.correlate_except(RomFile)
|
||||
.scalar_subquery(),
|
||||
deferred=True,
|
||||
)
|
||||
|
||||
|
||||
class RomUserStatus(enum.StrEnum):
|
||||
INCOMPLETE = "incomplete" # Started but not finished
|
||||
FINISHED = "finished" # Reached the end of the game
|
||||
|
||||
@@ -27,6 +27,7 @@ from handler.redis_handler import async_cache
|
||||
from logger.logger import log
|
||||
from models.firmware import FIRMWARE_FIXTURES_DIR, KNOWN_BIOS_KEY
|
||||
from tasks.scheduled.cleanup_netplay import cleanup_netplay_task
|
||||
from tasks.scheduled.cleanup_upload_tmp import cleanup_upload_tmp_task
|
||||
from tasks.scheduled.convert_images_to_webp import convert_images_to_webp_task
|
||||
from tasks.scheduled.scan_library import scan_library_task
|
||||
from tasks.scheduled.sync_retroachievements_progress import (
|
||||
@@ -51,6 +52,7 @@ async def main() -> None:
|
||||
|
||||
# Initialize scheduled tasks
|
||||
cleanup_netplay_task.init()
|
||||
cleanup_upload_tmp_task.init()
|
||||
|
||||
if ENABLE_SCHEDULED_RESCAN:
|
||||
log.info("Starting scheduled rescan")
|
||||
|
||||
@@ -27,7 +27,7 @@ from handler.database import (
|
||||
db_save_handler,
|
||||
db_sync_session_handler,
|
||||
)
|
||||
from handler.filesystem import fs_asset_handler, fs_sync_handler
|
||||
from handler.filesystem import fs_asset_handler, get_fs_sync_handler
|
||||
from handler.sync.comparison import compare_save_state
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
@@ -46,8 +46,9 @@ Change = tuple[str, str]
|
||||
def _extract_device_and_platform(path: str) -> tuple[str, str, str] | None:
|
||||
"""Extract device_id, platform_slug, and filename from a sync incoming path.
|
||||
|
||||
Expected path format: {SYNC_BASE_PATH}/{device_id}/incoming/{platform_slug}/filename.ext
|
||||
Expected path format: {ROMM_BASE_PATH}/sync/{device_id}/incoming/{platform_slug}/filename.ext
|
||||
"""
|
||||
fs_sync_handler = get_fs_sync_handler()
|
||||
try:
|
||||
rel_path = os.path.relpath(path, start=str(fs_sync_handler.base_path))
|
||||
parts = rel_path.split(os.sep)
|
||||
@@ -62,6 +63,7 @@ def _extract_device_and_platform(path: str) -> tuple[str, str, str] | None:
|
||||
|
||||
|
||||
def _ensure_conflicts_dir(device_id: str, platform_slug: str) -> str:
|
||||
fs_sync_handler = get_fs_sync_handler()
|
||||
conflicts_dir = str(
|
||||
fs_sync_handler.base_path
|
||||
/ fs_sync_handler.build_conflicts_path(device_id, platform_slug)
|
||||
@@ -207,6 +209,8 @@ def _process_incoming_file(
|
||||
"""Process a single incoming file from a device's sync folder."""
|
||||
from endpoints.sockets.sync import emit_sync_conflict
|
||||
|
||||
fs_sync_handler = get_fs_sync_handler()
|
||||
|
||||
# Look up platform
|
||||
platform = db_platform_handler.get_platform_by_fs_slug(platform_slug)
|
||||
if not platform:
|
||||
|
||||
@@ -87,7 +87,7 @@ class CleanupOrphanedResourcesTask(Task):
|
||||
platform_dirs: set[int] = {
|
||||
int(entry.name)
|
||||
async for entry in roms_resources_dir.iterdir()
|
||||
if await entry.is_dir()
|
||||
if entry.name.isdigit() and await entry.is_dir()
|
||||
}
|
||||
|
||||
rom_dirs_by_platform: dict[int, set[int]] = {}
|
||||
@@ -97,7 +97,7 @@ class CleanupOrphanedResourcesTask(Task):
|
||||
rom_dirs_by_platform[platform_dir] = {
|
||||
int(entry.name)
|
||||
async for entry in platform_dir_path.iterdir()
|
||||
if await entry.is_dir()
|
||||
if entry.name.isdigit() and await entry.is_dir()
|
||||
}
|
||||
|
||||
cleanup_stats.update(
|
||||
|
||||
@@ -9,7 +9,7 @@ from typing import Any
|
||||
|
||||
from config import ENABLE_SYNC_FOLDER_WATCHER
|
||||
from handler.database import db_device_handler
|
||||
from handler.filesystem import fs_sync_handler
|
||||
from handler.filesystem import get_fs_sync_handler
|
||||
from logger.logger import log
|
||||
from models.device import SyncMode
|
||||
from tasks.tasks import Task, TaskType
|
||||
@@ -38,6 +38,7 @@ class SyncFolderScanTask(Task):
|
||||
log.info("No file_transfer devices found")
|
||||
return {"status": "no_devices"}
|
||||
|
||||
fs_sync_handler = get_fs_sync_handler()
|
||||
total_files = 0
|
||||
for device in devices:
|
||||
if not device.sync_enabled:
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import shutil
|
||||
import time
|
||||
|
||||
from endpoints.roms.upload import ROM_UPLOAD_TMP_BASE, ROM_UPLOAD_TTL
|
||||
from logger.logger import log
|
||||
from tasks.tasks import PeriodicTask, TaskType
|
||||
|
||||
|
||||
class CleanupUploadTmpTask(PeriodicTask):
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
title="Scheduled upload tmp cleanup",
|
||||
description="Cleans up orphaned chunked-upload temp directories",
|
||||
task_type=TaskType.CLEANUP,
|
||||
enabled=True,
|
||||
manual_run=False,
|
||||
cron_string="0 * * * *", # Every hour
|
||||
func="tasks.scheduled.cleanup_upload_tmp.cleanup_upload_tmp_task.run",
|
||||
)
|
||||
|
||||
async def run(self) -> None:
|
||||
if not self.enabled:
|
||||
self.unschedule()
|
||||
return
|
||||
|
||||
if not ROM_UPLOAD_TMP_BASE.exists():
|
||||
return
|
||||
|
||||
cutoff = time.time() - ROM_UPLOAD_TTL
|
||||
removed = 0
|
||||
|
||||
for entry in ROM_UPLOAD_TMP_BASE.iterdir():
|
||||
if not entry.is_dir():
|
||||
continue
|
||||
try:
|
||||
if entry.stat().st_mtime < cutoff:
|
||||
shutil.rmtree(entry, ignore_errors=True)
|
||||
removed += 1
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
if removed:
|
||||
log.info(
|
||||
f"Cleaned up {removed} orphaned upload tmp director{'y' if removed == 1 else 'ies'}"
|
||||
)
|
||||
|
||||
|
||||
cleanup_upload_tmp_task = CleanupUploadTmpTask()
|
||||
@@ -11,6 +11,7 @@ from handler.metadata import (
|
||||
meta_launchbox_handler,
|
||||
meta_libretro_handler,
|
||||
meta_moby_handler,
|
||||
meta_playmatch_handler,
|
||||
meta_ra_handler,
|
||||
meta_sgdb_handler,
|
||||
meta_ss_handler,
|
||||
@@ -48,6 +49,7 @@ class ScanLibraryTask(PeriodicTask):
|
||||
MetadataSource.RA: meta_ra_handler.is_enabled(),
|
||||
MetadataSource.LAUNCHBOX: meta_launchbox_handler.is_enabled(),
|
||||
MetadataSource.HASHEOUS: meta_hasheous_handler.is_enabled(),
|
||||
MetadataSource.PLAYMATCH: meta_playmatch_handler.is_enabled(),
|
||||
MetadataSource.SGDB: meta_sgdb_handler.is_enabled(),
|
||||
MetadataSource.FLASHPOINT: meta_flashpoint_handler.is_enabled(),
|
||||
MetadataSource.HLTB: meta_hltb_handler.is_enabled(),
|
||||
|
||||
@@ -21,7 +21,7 @@ from handler.database import (
|
||||
)
|
||||
from handler.filesystem import fs_asset_handler
|
||||
from handler.sync.comparison import compare_save_state
|
||||
from handler.sync.ssh_handler import ssh_sync_handler
|
||||
from handler.sync.ssh_handler import get_ssh_sync_handler
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.device import Device, SyncMode
|
||||
@@ -102,6 +102,7 @@ async def _sync_device(device: Device, session_id: int | None = None) -> dict:
|
||||
)
|
||||
|
||||
try:
|
||||
ssh_sync_handler = get_ssh_sync_handler()
|
||||
conn = await ssh_sync_handler.connect(sync_config, device_id=device.id)
|
||||
except Exception as e:
|
||||
log.error(f"Push-pull: failed to connect to device {device.id}: {e}")
|
||||
@@ -227,6 +228,7 @@ async def _process_remote_save(
|
||||
remote_save,
|
||||
) -> str:
|
||||
"""Process a single remote save file. Returns action taken."""
|
||||
ssh_sync_handler = get_ssh_sync_handler()
|
||||
# Look up platform
|
||||
platform = db_platform_handler.get_platform_by_fs_slug(remote_save.platform_slug)
|
||||
if not platform:
|
||||
@@ -340,6 +342,7 @@ async def _push_missing_saves(
|
||||
save_directories: list[dict],
|
||||
) -> int:
|
||||
"""Push server saves that are missing from the device."""
|
||||
ssh_sync_handler = get_ssh_sync_handler()
|
||||
pushed = 0
|
||||
|
||||
# Build set of remote filenames per platform
|
||||
|
||||
@@ -300,6 +300,94 @@ class TestScreenScraperServiceUnit:
|
||||
|
||||
assert result == {}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_blacklisted_raises_403(self, service):
|
||||
"""Test that HTTP 426 (blacklisted version) raises HTTP 403."""
|
||||
mock_session = AsyncMock()
|
||||
mock_session.get.side_effect = aiohttp.ClientResponseError(
|
||||
request_info=MagicMock(), history=(), status=426
|
||||
)
|
||||
mock_context = MagicMock()
|
||||
mock_context.get.return_value = mock_session
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", mock_context):
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN
|
||||
assert "blacklisted" in exc_info.value.detail
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_daily_quota_exhausted_raises_429(self, service):
|
||||
"""Test that HTTP 430 (daily scrape quota) raises HTTP 429."""
|
||||
mock_session = AsyncMock()
|
||||
mock_session.get.side_effect = aiohttp.ClientResponseError(
|
||||
request_info=MagicMock(), history=(), status=430
|
||||
)
|
||||
mock_context = MagicMock()
|
||||
mock_context.get.return_value = mock_session
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", mock_context):
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_429_TOO_MANY_REQUESTS
|
||||
assert "daily scrape quota" in exc_info.value.detail
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_unrecognized_rom_quota_exhausted_raises_429(self, service):
|
||||
"""Test that HTTP 431 (unrecognized ROM quota) raises HTTP 429."""
|
||||
mock_session = AsyncMock()
|
||||
mock_session.get.side_effect = aiohttp.ClientResponseError(
|
||||
request_info=MagicMock(), history=(), status=431
|
||||
)
|
||||
mock_context = MagicMock()
|
||||
mock_context.get.return_value = mock_session
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", mock_context):
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_429_TOO_MANY_REQUESTS
|
||||
assert "unrecognized" in exc_info.value.detail
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_api_offline_raises_503(self, service):
|
||||
"""Test that HTTP 423 (API offline) raises HTTP 503."""
|
||||
mock_session = AsyncMock()
|
||||
mock_session.get.side_effect = aiohttp.ClientResponseError(
|
||||
request_info=MagicMock(), history=(), status=423
|
||||
)
|
||||
mock_context = MagicMock()
|
||||
mock_context.get.return_value = mock_session
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", mock_context):
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
|
||||
assert "offline" in exc_info.value.detail
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_cpu_throttle_returns_empty_dict(self, service):
|
||||
"""Test that HTTP 401 (server CPU throttle) returns empty dict without retrying."""
|
||||
mock_session = AsyncMock()
|
||||
mock_session.get.side_effect = aiohttp.ClientResponseError(
|
||||
request_info=MagicMock(),
|
||||
history=(),
|
||||
status=http.HTTPStatus.UNAUTHORIZED,
|
||||
)
|
||||
mock_context = MagicMock()
|
||||
mock_context.get.return_value = mock_session
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", mock_context):
|
||||
result = await service._request(
|
||||
"https://api.screenscraper.fr/api2/jeuInfos.php"
|
||||
)
|
||||
|
||||
assert result == {}
|
||||
assert mock_session.get.call_count == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_game_info_with_crc(self, service):
|
||||
"""Test get_game_info with CRC parameter."""
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# Config file containing values that a future RomM release might ship but
|
||||
# which this version doesn't yet know about. Used to verify the loader
|
||||
# tolerates unknown enum/option values instead of refusing to boot.
|
||||
|
||||
scan:
|
||||
media:
|
||||
- box2d
|
||||
- some_future_media_type
|
||||
- screenshot
|
||||
gamelist:
|
||||
media:
|
||||
thumbnail: "some_future_thumbnail"
|
||||
image: "some_future_image"
|
||||
|
||||
future_top_level_section:
|
||||
enabled: true
|
||||
setting: "value"
|
||||
@@ -0,0 +1,9 @@
|
||||
# Intentionally malformed YAML, used to verify the loader falls back to
|
||||
# defaults rather than crashing on a parse error.
|
||||
|
||||
scan:
|
||||
media:
|
||||
- box2d
|
||||
- screenshot # bad indentation, will fail to parse
|
||||
gamelist:
|
||||
export: true
|
||||
@@ -113,3 +113,50 @@ def test_empty_config_loader():
|
||||
assert loader.config.EJS_CONTROLS == {}
|
||||
assert loader.config.GAMELIST_MEDIA_THUMBNAIL == "box2d"
|
||||
assert loader.config.GAMELIST_MEDIA_IMAGE == "screenshot"
|
||||
|
||||
|
||||
def test_missing_config_file_is_created(tmp_path):
|
||||
config_file = tmp_path / "config" / "config.yml"
|
||||
|
||||
loader = ConfigManager(str(config_file))
|
||||
|
||||
assert config_file.parent.exists()
|
||||
assert config_file.exists()
|
||||
assert config_file.read_text() == ""
|
||||
assert loader.config.CONFIG_FILE_MOUNTED
|
||||
assert loader.config.CONFIG_FILE_WRITABLE
|
||||
|
||||
|
||||
def test_forward_compat_unknown_values_are_tolerated():
|
||||
"""A newer release may ship sample configs that reference media types
|
||||
this version doesn't yet recognize. The loader should drop unknowns and
|
||||
fall back to defaults rather than exiting."""
|
||||
loader = ConfigManager(
|
||||
os.path.join(
|
||||
Path(__file__).resolve().parent,
|
||||
"fixtures",
|
||||
"config/forward_compat_config.yml",
|
||||
)
|
||||
)
|
||||
|
||||
# Unknown entries in scan.media are filtered out; known ones survive.
|
||||
assert loader.config.SCAN_MEDIA == ["box2d", "screenshot"]
|
||||
# Unknown thumbnail/image values fall back to their defaults.
|
||||
assert loader.config.GAMELIST_MEDIA_THUMBNAIL == "box2d"
|
||||
assert loader.config.GAMELIST_MEDIA_IMAGE == "screenshot"
|
||||
|
||||
|
||||
def test_malformed_yaml_falls_back_to_defaults():
|
||||
"""A YAML parse error should log critically and leave the app on
|
||||
defaults, not crash."""
|
||||
loader = ConfigManager(
|
||||
os.path.join(
|
||||
Path(__file__).resolve().parent,
|
||||
"fixtures",
|
||||
"config/malformed_config.yml",
|
||||
)
|
||||
)
|
||||
|
||||
assert loader.config.ROMS_FOLDER_NAME == "roms"
|
||||
assert loader.config.FIRMWARE_FOLDER_NAME == "bios"
|
||||
assert loader.config.SCAN_MEDIA == ["box2d", "screenshot", "manual"]
|
||||
@@ -4,6 +4,7 @@ from unittest.mock import AsyncMock, patch
|
||||
from fastapi import status
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from handler.filesystem.resources_handler import FSResourcesHandler
|
||||
from handler.filesystem.roms_handler import FSRomsHandler
|
||||
from handler.metadata.flashpoint_handler import FlashpointHandler, FlashpointRom
|
||||
from handler.metadata.igdb_handler import IGDBHandler, IGDBRom
|
||||
@@ -127,6 +128,54 @@ def test_update_rom_reparses_tags_on_fs_name_change(
|
||||
assert body["tags"] == []
|
||||
|
||||
|
||||
# Minimal valid PNG (1x1 transparent pixel)
|
||||
_PNG_BYTES = (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
b"\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
|
||||
b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89"
|
||||
b"\x00\x00\x00\rIDATx\x9cc\xfc\xff\xff?\x00\x05\xfe\x02\xfe\xa75\x81\x84"
|
||||
b"\x00\x00\x00\x00IEND\xaeB`\x82"
|
||||
)
|
||||
|
||||
|
||||
def test_update_rom_rejects_non_image_artwork(
|
||||
client: TestClient, access_token: str, rom: Rom
|
||||
):
|
||||
response = client.put(
|
||||
f"/api/roms/{rom.id}",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
files={"artwork": ("cover.png", b"<script>alert(1)</script>", "image/png")},
|
||||
)
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "PNG, JPEG, WebP, or GIF" in response.json()["detail"]
|
||||
|
||||
|
||||
@patch.object(
|
||||
FSResourcesHandler,
|
||||
"store_artwork",
|
||||
new_callable=AsyncMock,
|
||||
return_value=("path/to/big.png", "path/to/small.png"),
|
||||
)
|
||||
def test_update_rom_artwork_uses_detected_extension(
|
||||
store_artwork_mock: AsyncMock,
|
||||
client: TestClient,
|
||||
access_token: str,
|
||||
rom: Rom,
|
||||
):
|
||||
response = client.put(
|
||||
f"/api/roms/{rom.id}",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
files={"artwork": ("payload.html", _PNG_BYTES, "image/png")},
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
# The handler is called with the trusted extension from libmagic, not the
|
||||
# extension parsed off the user-supplied filename.
|
||||
assert store_artwork_mock.called
|
||||
_, _, file_ext = store_artwork_mock.call_args.args
|
||||
assert file_ext == "png"
|
||||
|
||||
|
||||
def test_delete_roms(client: TestClient, access_token: str, rom: Rom):
|
||||
response = client.post(
|
||||
"/api/roms/delete",
|
||||
|
||||
@@ -180,7 +180,7 @@ class TestShouldScanRom:
|
||||
assert result is True
|
||||
|
||||
def test_no_scan_when_rom_id_not_in_list(self, rom: Rom):
|
||||
"""When roms_ids is non-empty, scan is scoped — roms outside the list are skipped for every scan type"""
|
||||
"""When roms_ids is non-empty, scan is scoped: roms outside the list are skipped for every scan type"""
|
||||
rom.id = 4
|
||||
rom.igdb_id = None
|
||||
rom.moby_id = None
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import status
|
||||
@@ -6,11 +7,21 @@ from fastapi import status
|
||||
from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS
|
||||
from handler.auth import oauth_handler
|
||||
from handler.database import db_collection_handler, db_rom_handler
|
||||
from handler.filesystem.resources_handler import FSResourcesHandler
|
||||
from models.collection import Collection
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom
|
||||
from models.user import User
|
||||
|
||||
# Minimal valid PNG (1x1 transparent pixel)
|
||||
_PNG_BYTES = (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
b"\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
|
||||
b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89"
|
||||
b"\x00\x00\x00\rIDATx\x9cc\xfc\xff\xff?\x00\x05\xfe\x02\xfe\xa75\x81\x84"
|
||||
b"\x00\x00\x00\x00IEND\xaeB`\x82"
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -59,7 +70,7 @@ def second_rom(admin_user: User, platform: Platform) -> Rom:
|
||||
|
||||
@pytest.fixture
|
||||
def other_user_token(editor_user: User) -> str:
|
||||
"""Access token for a second user — used to test ownership checks."""
|
||||
"""Access token for a second user, used to test ownership checks."""
|
||||
return oauth_handler.create_access_token(
|
||||
data={
|
||||
"sub": editor_user.username,
|
||||
@@ -227,7 +238,7 @@ class TestDeleteCollection:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# POST /collections/{id}/roms — atomic add
|
||||
# POST /collections/{id}/roms (atomic add)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -374,7 +385,7 @@ class TestAddRomsToCollection:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# DELETE /collections/{id}/roms — atomic remove
|
||||
# DELETE /collections/{id}/roms (atomic remove)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -513,7 +524,7 @@ class TestAtomicBehavior:
|
||||
):
|
||||
"""
|
||||
Simulates the corrected behavior: two separate add calls, each with a
|
||||
single ROM, should result in both ROMs being present — even if they
|
||||
single ROM, should result in both ROMs being present, even if they
|
||||
arrive close together. This would previously fail under the full-replace
|
||||
approach when requests arrived out of order.
|
||||
"""
|
||||
@@ -541,8 +552,8 @@ class TestAtomicBehavior:
|
||||
second_rom: Rom,
|
||||
):
|
||||
"""
|
||||
Add both ROMs, remove one, add it back — final state should reflect
|
||||
only the last operation per ROM.
|
||||
Add both ROMs, remove one, add it back. The final state should
|
||||
reflect only the last operation per ROM.
|
||||
"""
|
||||
client.post(
|
||||
f"/api/collections/{collection.id}/roms",
|
||||
@@ -564,3 +575,79 @@ class TestAtomicBehavior:
|
||||
refreshed = db_collection_handler.get_collection(collection.id)
|
||||
assert refreshed is not None
|
||||
assert set(refreshed.rom_ids) == {rom.id, second_rom.id}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Artwork upload validation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestArtworkUpload:
|
||||
def test_add_collection_rejects_non_image_artwork(self, client, access_token: str):
|
||||
response = client.post(
|
||||
"/api/collections",
|
||||
data={"name": "Bad Cover Collection"},
|
||||
files={"artwork": ("cover.png", b"<script>alert(1)</script>", "image/png")},
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "PNG, JPEG, WebP, or GIF" in response.json()["detail"]
|
||||
|
||||
@patch.object(
|
||||
FSResourcesHandler,
|
||||
"store_artwork",
|
||||
new_callable=AsyncMock,
|
||||
return_value=("path/to/big.png", "path/to/small.png"),
|
||||
)
|
||||
def test_add_collection_artwork_uses_detected_extension(
|
||||
self,
|
||||
store_artwork_mock: AsyncMock,
|
||||
client,
|
||||
access_token: str,
|
||||
):
|
||||
response = client.post(
|
||||
"/api/collections",
|
||||
data={"name": "Good Cover Collection"},
|
||||
files={"artwork": ("payload.html", _PNG_BYTES, "image/png")},
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert store_artwork_mock.called
|
||||
_, _, file_ext = store_artwork_mock.call_args.args
|
||||
assert file_ext == "png"
|
||||
|
||||
def test_update_collection_rejects_non_image_artwork(
|
||||
self, client, access_token: str, collection: Collection
|
||||
):
|
||||
response = client.put(
|
||||
f"/api/collections/{collection.id}",
|
||||
data={"rom_ids": "[]"},
|
||||
files={"artwork": ("cover.png", b"<script>alert(1)</script>", "image/png")},
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "PNG, JPEG, WebP, or GIF" in response.json()["detail"]
|
||||
|
||||
@patch.object(
|
||||
FSResourcesHandler,
|
||||
"store_artwork",
|
||||
new_callable=AsyncMock,
|
||||
return_value=("path/to/big.png", "path/to/small.png"),
|
||||
)
|
||||
def test_update_collection_artwork_uses_detected_extension(
|
||||
self,
|
||||
store_artwork_mock: AsyncMock,
|
||||
client,
|
||||
access_token: str,
|
||||
collection: Collection,
|
||||
):
|
||||
response = client.put(
|
||||
f"/api/collections/{collection.id}",
|
||||
data={"rom_ids": "[]"},
|
||||
files={"artwork": ("payload.html", _PNG_BYTES, "image/png")},
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert store_artwork_mock.called
|
||||
_, _, file_ext = store_artwork_mock.call_args.args
|
||||
assert file_ext == "png"
|
||||
@@ -151,6 +151,45 @@ def test_update_user(client, access_token: str, editor_user: User):
|
||||
assert user["role"] == "viewer"
|
||||
|
||||
|
||||
def test_update_user_rejects_non_image_avatar(
|
||||
client, access_token: str, editor_user: User
|
||||
):
|
||||
response = client.put(
|
||||
f"/api/users/{editor_user.id}",
|
||||
files={"avatar": ("avatar.png", b"<script>alert(1)</script>", "image/png")},
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "PNG, JPEG, WebP, or GIF" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_update_user_accepts_png_avatar(
|
||||
client, access_token: str, editor_user: User, tmp_path, monkeypatch
|
||||
):
|
||||
# Redirect ASSETS_BASE_PATH to a per-test tmp dir so the written avatar
|
||||
# doesn't leak into the repo's romm_test/ tree.
|
||||
from handler.filesystem import fs_asset_handler
|
||||
|
||||
monkeypatch.setattr(fs_asset_handler, "base_path", str(tmp_path))
|
||||
|
||||
# Minimal valid PNG (1x1 transparent pixel)
|
||||
png_bytes = (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
b"\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
|
||||
b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89"
|
||||
b"\x00\x00\x00\rIDATx\x9cc\xfc\xff\xff?\x00\x05\xfe\x02\xfe\xa75\x81\x84"
|
||||
b"\x00\x00\x00\x00IEND\xaeB`\x82"
|
||||
)
|
||||
response = client.put(
|
||||
f"/api/users/{editor_user.id}",
|
||||
files={"avatar": ("payload.html", png_bytes, "image/png")},
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
# Server picks the extension from the detected MIME, not the user-supplied filename.
|
||||
assert response.json()["avatar_path"].endswith("avatar.png")
|
||||
|
||||
|
||||
def test_delete_user(client, access_token: str, editor_user: User):
|
||||
response = client.delete(
|
||||
f"/api/users/{editor_user.id}",
|
||||
|
||||
@@ -13,4 +13,7 @@ def test_get_raw_asset(client, access_token):
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert "SUPER_MARIO_64_SAVE_FILE" in response.text
|
||||
assert response.headers["content-type"] == "text/plain; charset=utf-8"
|
||||
# Non-image assets must be served as an opaque download to prevent stored XSS
|
||||
# from any user-controlled file (e.g. an HTML uploaded as an avatar).
|
||||
assert response.headers["content-type"] == "application/octet-stream"
|
||||
assert response.headers["content-disposition"].startswith("attachment;")
|
||||
@@ -54,7 +54,7 @@ def create_mock_job(job_id="1", status="queued"):
|
||||
from datetime import datetime
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.get_id.return_value = job_id
|
||||
mock_job.id = job_id
|
||||
mock_job.get_status.return_value = status
|
||||
|
||||
# Create mock datetime objects with isoformat methods
|
||||
@@ -395,7 +395,7 @@ class TestGetTaskById:
|
||||
}
|
||||
mock_job.func_name = "test_task"
|
||||
mock_job.get_status.return_value = "finished"
|
||||
mock_job.get_id.return_value = "test-job-id-123"
|
||||
mock_job.id = "test-job-id-123"
|
||||
mock_job.result = {"status": "completed"}
|
||||
|
||||
mock_job_fetch.return_value = mock_job
|
||||
@@ -458,7 +458,7 @@ class TestGetTaskById:
|
||||
}
|
||||
mock_job.func_name = "test_task"
|
||||
mock_job.get_status.return_value = "failed"
|
||||
mock_job.get_id.return_value = "failed-job-id"
|
||||
mock_job.id = "failed-job-id"
|
||||
mock_job.result = {"error": "Task failed"}
|
||||
|
||||
mock_job_fetch.return_value = mock_job
|
||||
|
||||
@@ -242,8 +242,12 @@ class TestCSRFMiddleware:
|
||||
|
||||
def test_user_id_mismatch_fails(self) -> None:
|
||||
"""Tokens issued for one user must not validate for another."""
|
||||
|
||||
# We simulate two users by calling _generate_csrf_token with different IDs
|
||||
mw = CSRFMiddleware(app=lambda s, r, se: None, secret="test")
|
||||
async def noop_app(scope, receive, send):
|
||||
pass
|
||||
|
||||
mw = CSRFMiddleware(app=noop_app, secret="test")
|
||||
user1_token = mw._generate_csrf_token(user_id=1)
|
||||
|
||||
# user1_token should not validate for user_id=2
|
||||
@@ -270,8 +274,33 @@ class TestCSRFMiddleware:
|
||||
resp = client.post("/post", headers={"x-csrftoken": cookie2})
|
||||
assert resp.status_code == 403
|
||||
|
||||
def test_existing_cookie_is_rotated_when_authenticated_user_changes(self) -> None:
|
||||
"""GET should rotate CSRF cookie when cookie user_id doesn't match current user."""
|
||||
app = create_test_app()
|
||||
client = TestClient(app)
|
||||
serializer = URLSafeSerializer("test-secret", "csrftoken")
|
||||
|
||||
anonymous_cookie = serializer.dumps({"token": "old-token", "user_id": None})
|
||||
client.cookies.set(
|
||||
"csrftoken", anonymous_cookie, domain="testserver.local", path="/"
|
||||
)
|
||||
|
||||
resp = client.get("/get")
|
||||
assert resp.status_code == 200
|
||||
|
||||
rotated_cookie = client.cookies.get(
|
||||
"csrftoken", domain="testserver.local", path="/"
|
||||
)
|
||||
assert rotated_cookie is not None
|
||||
assert rotated_cookie != anonymous_cookie
|
||||
assert serializer.loads(rotated_cookie)["user_id"] == 1
|
||||
|
||||
def test_bad_signature_returns_false(self) -> None:
|
||||
"""_csrf_tokens_match should return False on BadSignature."""
|
||||
mw = CSRFMiddleware(app=lambda s, r, se: None, secret="test")
|
||||
|
||||
async def noop_app(scope, receive, send):
|
||||
pass
|
||||
|
||||
mw = CSRFMiddleware(app=noop_app, secret="test")
|
||||
ok = mw._csrf_tokens_match("bad-token", "bad-token", user_id=None)
|
||||
assert ok is False
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import errno
|
||||
import shutil
|
||||
import tempfile
|
||||
from io import BytesIO
|
||||
@@ -161,6 +162,43 @@ class TestFSHandler:
|
||||
assert "game.rom" in result
|
||||
assert "data.json" in result
|
||||
|
||||
def test_exclude_single_files_multi_dot(self, handler: FSHandler):
|
||||
"""Test that files with multiple dots are excluded by last or compound extension"""
|
||||
files = [
|
||||
"game.nds",
|
||||
"game.nds.hash.txt",
|
||||
"game.nds.enc.hash.txt",
|
||||
"readme.txt",
|
||||
"game.rom",
|
||||
]
|
||||
|
||||
with patch("handler.filesystem.base_handler.cm.get_config") as mock_config:
|
||||
# Exclude by last single extension
|
||||
mock_config.return_value.EXCLUDED_SINGLE_EXT = ["txt"]
|
||||
mock_config.return_value.EXCLUDED_SINGLE_FILES = []
|
||||
|
||||
result = handler.exclude_single_files(files)
|
||||
|
||||
assert "game.nds.hash.txt" not in result
|
||||
assert "game.nds.enc.hash.txt" not in result
|
||||
assert "readme.txt" not in result
|
||||
assert "game.nds" in result
|
||||
assert "game.rom" in result
|
||||
|
||||
with patch("handler.filesystem.base_handler.cm.get_config") as mock_config:
|
||||
# Exclude by compound sub-extension "hash.txt"
|
||||
mock_config.return_value.EXCLUDED_SINGLE_EXT = ["hash.txt"]
|
||||
mock_config.return_value.EXCLUDED_SINGLE_FILES = []
|
||||
|
||||
result = handler.exclude_single_files(files)
|
||||
|
||||
assert "game.nds.hash.txt" not in result
|
||||
assert "game.nds.enc.hash.txt" not in result
|
||||
# "readme.txt" does NOT end in "hash.txt", so it should remain
|
||||
assert "readme.txt" in result
|
||||
assert "game.nds" in result
|
||||
assert "game.rom" in result
|
||||
|
||||
async def test_make_directory(self, handler: FSHandler):
|
||||
"""Test directory creation"""
|
||||
await handler.make_directory("test_dir")
|
||||
@@ -478,3 +516,82 @@ class TestFSHandler:
|
||||
dirs = await handler.list_directories(".")
|
||||
for i in range(5):
|
||||
assert f"test_dir_{i}" not in dirs
|
||||
|
||||
async def test_copy_file_does_not_hardlink_by_default(
|
||||
self, handler: FSHandler, sample_file_content
|
||||
):
|
||||
"""copy_file defaults to allow_link=False: the destination is a real
|
||||
copy, so mutating it won't affect the source. Callers must opt in to
|
||||
hardlinking explicitly."""
|
||||
source_full = handler.base_path / "source.bin"
|
||||
source_full.write_bytes(sample_file_content)
|
||||
|
||||
await handler.copy_file(source_full, "dest.bin")
|
||||
|
||||
dest_full = handler.base_path / "dest.bin"
|
||||
assert dest_full.read_bytes() == sample_file_content
|
||||
assert source_full.stat().st_ino != dest_full.stat().st_ino
|
||||
|
||||
async def test_copy_file_allow_link_true_hardlinks(
|
||||
self, handler: FSHandler, sample_file_content
|
||||
):
|
||||
"""allow_link=True: when source and dest are on the same filesystem,
|
||||
the destination is a hardlink to the source (same inode)."""
|
||||
source_full = handler.base_path / "source.bin"
|
||||
source_full.write_bytes(sample_file_content)
|
||||
|
||||
await handler.copy_file(source_full, "dest.bin", allow_link=True)
|
||||
|
||||
dest_full = handler.base_path / "dest.bin"
|
||||
assert dest_full.read_bytes() == sample_file_content
|
||||
assert source_full.stat().st_ino == dest_full.stat().st_ino
|
||||
|
||||
async def test_copy_file_allow_link_false_does_real_copy(
|
||||
self, handler: FSHandler, sample_file_content
|
||||
):
|
||||
"""allow_link=False (explicit) produces a real copy — content matches
|
||||
but inodes differ. This matches the default but is exercised explicitly
|
||||
to lock in the contract."""
|
||||
source_full = handler.base_path / "source.bin"
|
||||
source_full.write_bytes(sample_file_content)
|
||||
|
||||
await handler.copy_file(source_full, "dest.bin", allow_link=False)
|
||||
|
||||
dest_full = handler.base_path / "dest.bin"
|
||||
assert dest_full.read_bytes() == sample_file_content
|
||||
assert source_full.stat().st_ino != dest_full.stat().st_ino
|
||||
|
||||
async def test_copy_file_allow_link_falls_back_to_copy_on_exdev(
|
||||
self, handler: FSHandler, sample_file_content
|
||||
):
|
||||
"""When allow_link=True and os.link raises EXDEV (cross-filesystem),
|
||||
copy_file transparently falls back to a real copy."""
|
||||
source_full = handler.base_path / "source.bin"
|
||||
source_full.write_bytes(sample_file_content)
|
||||
|
||||
with patch(
|
||||
"utils.filesystem.os.link",
|
||||
side_effect=OSError(errno.EXDEV, "Cross-device link"),
|
||||
):
|
||||
await handler.copy_file(source_full, "dest.bin", allow_link=True)
|
||||
|
||||
dest_full = handler.base_path / "dest.bin"
|
||||
assert dest_full.read_bytes() == sample_file_content
|
||||
assert source_full.stat().st_ino != dest_full.stat().st_ino
|
||||
|
||||
async def test_copy_file_nonexistent_source(self, handler: FSHandler):
|
||||
"""Missing source must raise FileNotFoundError regardless of link mode."""
|
||||
with pytest.raises(FileNotFoundError, match="Source file not found"):
|
||||
await handler.copy_file(handler.base_path / "missing.bin", "dest.bin")
|
||||
|
||||
|
||||
class TestFSHandlerInit:
|
||||
def test_raises_on_mkdir_failure(self):
|
||||
"""OSError from mkdir propagates, so misconfigured paths fail loudly
|
||||
at construction time. Optional features should defer construction
|
||||
(e.g. via a lazy factory) rather than swallow the error."""
|
||||
with patch.object(
|
||||
Path, "mkdir", side_effect=PermissionError(errno.EACCES, "denied")
|
||||
):
|
||||
with pytest.raises(PermissionError):
|
||||
FSHandler("/some/unwritable/path")
|
||||
@@ -138,14 +138,29 @@ class TestFSFirmwareHandler:
|
||||
assert hasattr(handler, "stream_file")
|
||||
assert hasattr(handler, "exclude_single_files")
|
||||
|
||||
def test_firmware_path_construction(self, handler: FSFirmwareHandler, config):
|
||||
"""Test that firmware paths are constructed correctly"""
|
||||
def test_firmware_path_construction_structure_a(
|
||||
self, handler: FSFirmwareHandler, config
|
||||
):
|
||||
"""Test that firmware paths are constructed correctly for Structure A"""
|
||||
platform_fs_slug = "n64"
|
||||
config.has_structure_path_b = False
|
||||
|
||||
with patch(
|
||||
"handler.filesystem.firmware_handler.cm.get_config", return_value=config
|
||||
):
|
||||
path = handler.get_firmware_fs_structure(platform_fs_slug)
|
||||
assert path == f"{config.FIRMWARE_FOLDER_NAME}/{platform_fs_slug}"
|
||||
|
||||
def test_firmware_path_construction_structure_b(
|
||||
self, handler: FSFirmwareHandler, config
|
||||
):
|
||||
"""Test that firmware paths are constructed correctly for Structure B"""
|
||||
platform_fs_slug = "n64"
|
||||
config.has_structure_path_b = True
|
||||
|
||||
with patch(
|
||||
"handler.filesystem.firmware_handler.cm.get_config", return_value=config
|
||||
):
|
||||
# Test normal path (high prio doesn't exist)
|
||||
path = handler.get_firmware_fs_structure(platform_fs_slug)
|
||||
assert path == f"{platform_fs_slug}/{config.FIRMWARE_FOLDER_NAME}"
|
||||
|
||||
|
||||
@@ -86,47 +86,46 @@ class TestFSPlatformsHandler:
|
||||
result = handler._exclude_platforms(platforms)
|
||||
assert result == platforms
|
||||
|
||||
def test_get_platforms_directory_high_priority_structure(
|
||||
def test_get_platforms_directory_structure_a(
|
||||
self, handler: FSPlatformsHandler, config
|
||||
):
|
||||
"""Test get_platforms_directory with high priority structure"""
|
||||
"""Test get_platforms_directory with Structure A (roms/{platform})"""
|
||||
config.has_structure_path_b = False
|
||||
with patch(
|
||||
"handler.filesystem.platforms_handler.cm.get_config", return_value=config
|
||||
):
|
||||
with patch("os.path.exists", return_value=True):
|
||||
result = handler.get_platforms_directory()
|
||||
assert result == config.ROMS_FOLDER_NAME
|
||||
result = handler.get_platforms_directory()
|
||||
assert result == config.ROMS_FOLDER_NAME
|
||||
|
||||
def test_get_platforms_directory_normal_structure(
|
||||
def test_get_platforms_directory_structure_b(
|
||||
self, handler: FSPlatformsHandler, config
|
||||
):
|
||||
"""Test get_platforms_directory with normal structure"""
|
||||
"""Test get_platforms_directory with Structure B ({platform}/roms)"""
|
||||
config.has_structure_path_b = True
|
||||
with patch(
|
||||
"handler.filesystem.platforms_handler.cm.get_config", return_value=config
|
||||
):
|
||||
with patch("os.path.exists", return_value=False):
|
||||
result = handler.get_platforms_directory()
|
||||
assert result == ""
|
||||
result = handler.get_platforms_directory()
|
||||
assert result == ""
|
||||
|
||||
def test_get_platform_fs_structure_high_priority(
|
||||
def test_get_platform_fs_structure_structure_a(
|
||||
self, handler: FSPlatformsHandler, config
|
||||
):
|
||||
"""Test get_platform_fs_structure with high priority structure"""
|
||||
"""Test get_platform_fs_structure with Structure A (roms/{platform})"""
|
||||
fs_slug = "n64"
|
||||
|
||||
config.has_structure_path_b = False
|
||||
with patch(
|
||||
"handler.filesystem.platforms_handler.cm.get_config", return_value=config
|
||||
):
|
||||
with patch("os.path.exists", return_value=True):
|
||||
result = handler.get_platform_fs_structure(fs_slug)
|
||||
assert result == f"{config.ROMS_FOLDER_NAME}/{fs_slug}"
|
||||
result = handler.get_platform_fs_structure(fs_slug)
|
||||
assert result == f"{config.ROMS_FOLDER_NAME}/{fs_slug}"
|
||||
|
||||
def test_get_platform_fs_structure_normal_structure(
|
||||
def test_get_platform_fs_structure_structure_b(
|
||||
self, handler: FSPlatformsHandler, config
|
||||
):
|
||||
"""Test get_platform_fs_structure with normal structure"""
|
||||
"""Test get_platform_fs_structure with Structure B ({platform}/roms)"""
|
||||
fs_slug = "n64"
|
||||
|
||||
config.has_structure_path_b = True
|
||||
with patch(
|
||||
"handler.filesystem.platforms_handler.cm.get_config", return_value=config
|
||||
):
|
||||
@@ -136,9 +135,9 @@ class TestFSPlatformsHandler:
|
||||
def test_get_platform_fs_structure_custom_folder_name(
|
||||
self, handler: FSPlatformsHandler, config_custom_folder
|
||||
):
|
||||
"""Test get_platform_fs_structure with custom folder name"""
|
||||
"""Test get_platform_fs_structure with custom folder name (Structure B)"""
|
||||
fs_slug = "psx"
|
||||
|
||||
config_custom_folder.has_structure_path_b = True
|
||||
with patch(
|
||||
"handler.filesystem.platforms_handler.cm.get_config",
|
||||
return_value=config_custom_folder,
|
||||
@@ -149,32 +148,32 @@ class TestFSPlatformsHandler:
|
||||
async def test_add_platform_creates_directory(
|
||||
self, handler: FSPlatformsHandler, config
|
||||
):
|
||||
"""Test that add_platform creates the correct directory"""
|
||||
"""Test that add_platform creates the correct directory (Structure A)"""
|
||||
fs_slug = "gba"
|
||||
expected_path = f"{config.ROMS_FOLDER_NAME}/{fs_slug}"
|
||||
config.has_structure_path_b = False
|
||||
|
||||
with patch(
|
||||
"handler.filesystem.platforms_handler.cm.get_config", return_value=config
|
||||
):
|
||||
with patch("os.path.exists", return_value=True):
|
||||
with patch.object(handler, "make_directory") as mock_make_directory:
|
||||
await handler.add_platform(fs_slug)
|
||||
mock_make_directory.assert_called_once_with(expected_path)
|
||||
with patch.object(handler, "make_directory") as mock_make_directory:
|
||||
await handler.add_platform(fs_slug)
|
||||
mock_make_directory.assert_called_once_with(expected_path)
|
||||
|
||||
async def test_add_platform_normal_structure(
|
||||
self, handler: FSPlatformsHandler, config
|
||||
):
|
||||
"""Test that add_platform creates directory with normal structure"""
|
||||
"""Test that add_platform creates directory with Structure B"""
|
||||
fs_slug = "gba"
|
||||
expected_path = f"{fs_slug}/{config.ROMS_FOLDER_NAME}"
|
||||
config.has_structure_path_b = True
|
||||
|
||||
with patch(
|
||||
"handler.filesystem.platforms_handler.cm.get_config", return_value=config
|
||||
):
|
||||
with patch("os.path.exists", return_value=False):
|
||||
with patch.object(handler, "make_directory") as mock_make_directory:
|
||||
await handler.add_platform(fs_slug)
|
||||
mock_make_directory.assert_called_once_with(expected_path)
|
||||
with patch.object(handler, "make_directory") as mock_make_directory:
|
||||
await handler.add_platform(fs_slug)
|
||||
mock_make_directory.assert_called_once_with(expected_path)
|
||||
|
||||
async def test_get_platforms_returns_existing_platforms(
|
||||
self, handler: FSPlatformsHandler, config
|
||||
@@ -204,15 +203,15 @@ class TestFSPlatformsHandler:
|
||||
self, handler: FSPlatformsHandler, config
|
||||
):
|
||||
"""Test that get_platforms calls list_directories with correct path"""
|
||||
config.has_structure_path_b = False
|
||||
with patch(
|
||||
"handler.filesystem.platforms_handler.cm.get_config", return_value=config
|
||||
):
|
||||
with patch("os.path.exists", return_value=True):
|
||||
with patch.object(
|
||||
handler, "list_directories", return_value=[]
|
||||
) as mock_list:
|
||||
await handler.get_platforms()
|
||||
mock_list.assert_called_once_with(path=config.ROMS_FOLDER_NAME)
|
||||
with patch.object(
|
||||
handler, "list_directories", return_value=[]
|
||||
) as mock_list:
|
||||
await handler.get_platforms()
|
||||
mock_list.assert_called_once_with(path=config.ROMS_FOLDER_NAME)
|
||||
|
||||
async def test_get_platforms_calls_list_directories_with_empty_path(
|
||||
self, handler: FSPlatformsHandler, config
|
||||
@@ -317,6 +316,7 @@ class TestFSPlatformsHandler:
|
||||
):
|
||||
"""Test detect_library_structure detects Structure A (roms/{platform})"""
|
||||
roms_path = f"{LIBRARY_BASE_PATH}/{config.ROMS_FOLDER_NAME}"
|
||||
config.has_structure_path_b = False
|
||||
|
||||
with patch(
|
||||
"handler.filesystem.platforms_handler.cm.get_config", return_value=config
|
||||
@@ -332,64 +332,47 @@ class TestFSPlatformsHandler:
|
||||
self, handler: FSPlatformsHandler, config
|
||||
):
|
||||
"""Test detect_library_structure detects Structure B ({platform}/roms)"""
|
||||
config.has_structure_path_b = True
|
||||
|
||||
with patch(
|
||||
"handler.filesystem.platforms_handler.cm.get_config", return_value=config
|
||||
):
|
||||
with patch("os.path.exists") as mock_exists:
|
||||
# ROMs folder doesn't exist at base level
|
||||
mock_exists.return_value = False
|
||||
result = handler.detect_library_structure()
|
||||
assert result == LibraryStructure.B
|
||||
|
||||
with patch("os.listdir") as mock_listdir:
|
||||
mock_listdir.return_value = ["n64", "psx", "other_folder"]
|
||||
def test_detect_library_structure_b_takes_priority_over_a(
|
||||
self, handler: FSPlatformsHandler, config
|
||||
):
|
||||
"""Structure B is reported even when the top-level roms folder exists."""
|
||||
config.has_structure_path_b = True
|
||||
|
||||
with patch("os.path.isdir") as mock_isdir:
|
||||
# n64 and psx are directories with roms subfolders
|
||||
def isdir_side_effect(path):
|
||||
return "n64" in path or "psx" in path
|
||||
|
||||
def exists_side_effect(path):
|
||||
# n64/roms and psx/roms exist
|
||||
return (
|
||||
f"n64/{config.ROMS_FOLDER_NAME}" in path
|
||||
or f"psx/{config.ROMS_FOLDER_NAME}" in path
|
||||
)
|
||||
|
||||
mock_isdir.side_effect = isdir_side_effect
|
||||
mock_exists.side_effect = exists_side_effect
|
||||
|
||||
result = handler.detect_library_structure()
|
||||
assert result == LibraryStructure.B
|
||||
with patch(
|
||||
"handler.filesystem.platforms_handler.cm.get_config", return_value=config
|
||||
):
|
||||
with patch("os.path.exists", return_value=True):
|
||||
result = handler.detect_library_structure()
|
||||
assert result == LibraryStructure.B
|
||||
|
||||
def test_detect_library_structure_none(self, handler: FSPlatformsHandler, config):
|
||||
"""Test detect_library_structure returns None when no structure detected"""
|
||||
with patch(
|
||||
"handler.filesystem.platforms_handler.cm.get_config", return_value=config
|
||||
):
|
||||
with patch("os.path.exists", return_value=False):
|
||||
with patch("os.listdir", return_value=[]):
|
||||
result = handler.detect_library_structure()
|
||||
assert result is None
|
||||
config.has_structure_path_b = False
|
||||
|
||||
def test_detect_library_structure_handles_os_errors(
|
||||
self, handler: FSPlatformsHandler, config
|
||||
):
|
||||
"""Test detect_library_structure handles OS errors gracefully"""
|
||||
with patch(
|
||||
"handler.filesystem.platforms_handler.cm.get_config", return_value=config
|
||||
):
|
||||
with patch("os.path.exists", return_value=False):
|
||||
with patch("os.listdir", side_effect=OSError("Permission denied")):
|
||||
result = handler.detect_library_structure()
|
||||
assert result is None
|
||||
result = handler.detect_library_structure()
|
||||
assert result is None
|
||||
|
||||
def test_detect_library_structure_empty_library(
|
||||
self, handler: FSPlatformsHandler, config
|
||||
):
|
||||
"""Test detect_library_structure with empty library directory"""
|
||||
config.has_structure_path_b = False
|
||||
|
||||
with patch(
|
||||
"handler.filesystem.platforms_handler.cm.get_config", return_value=config
|
||||
):
|
||||
with patch("os.path.exists", return_value=False):
|
||||
with patch("os.listdir", return_value=[]):
|
||||
result = handler.detect_library_structure()
|
||||
assert result is None
|
||||
result = handler.detect_library_structure()
|
||||
assert result is None
|
||||
@@ -7,7 +7,6 @@ import pytest
|
||||
|
||||
from config.config_manager import LIBRARY_BASE_PATH, Config
|
||||
from handler.filesystem.roms_handler import (
|
||||
CHDHashWrapper,
|
||||
FileHash,
|
||||
FSRomsHandler,
|
||||
extract_chd_hash,
|
||||
@@ -102,56 +101,48 @@ class TestFSRomsHandler:
|
||||
"""Test that FSRomsHandler initializes with LIBRARY_BASE_PATH"""
|
||||
assert handler.base_path == Path(LIBRARY_BASE_PATH).resolve()
|
||||
|
||||
def test_get_roms_fs_structure_normal_structure(self, handler: FSRomsHandler):
|
||||
"""Test get_roms_fs_structure with normal structure"""
|
||||
def test_get_roms_fs_structure_structure_b(self, handler: FSRomsHandler):
|
||||
"""Test get_roms_fs_structure with Structure B ({platform}/roms)"""
|
||||
fs_slug = "n64"
|
||||
cnfg = Config(
|
||||
EXCLUDED_PLATFORMS=[],
|
||||
EXCLUDED_SINGLE_EXT=[],
|
||||
EXCLUDED_SINGLE_FILES=[],
|
||||
EXCLUDED_MULTI_FILES=[],
|
||||
EXCLUDED_MULTI_PARTS_EXT=[],
|
||||
EXCLUDED_MULTI_PARTS_FILES=[],
|
||||
PLATFORMS_BINDING={},
|
||||
PLATFORMS_VERSIONS={},
|
||||
ROMS_FOLDER_NAME="roms",
|
||||
FIRMWARE_FOLDER_NAME="bios",
|
||||
)
|
||||
cnfg.has_structure_path_b = True
|
||||
|
||||
with pytest.MonkeyPatch.context() as m:
|
||||
m.setattr(
|
||||
"handler.filesystem.roms_handler.cm.get_config",
|
||||
lambda: Config(
|
||||
EXCLUDED_PLATFORMS=[],
|
||||
EXCLUDED_SINGLE_EXT=[],
|
||||
EXCLUDED_SINGLE_FILES=[],
|
||||
EXCLUDED_MULTI_FILES=[],
|
||||
EXCLUDED_MULTI_PARTS_EXT=[],
|
||||
EXCLUDED_MULTI_PARTS_FILES=[],
|
||||
PLATFORMS_BINDING={},
|
||||
PLATFORMS_VERSIONS={},
|
||||
ROMS_FOLDER_NAME="roms",
|
||||
FIRMWARE_FOLDER_NAME="bios",
|
||||
),
|
||||
)
|
||||
m.setattr("os.path.exists", lambda x: False) # Simulate normal structure
|
||||
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: cnfg)
|
||||
|
||||
result = handler.get_roms_fs_structure(fs_slug)
|
||||
assert result == f"{fs_slug}/roms"
|
||||
|
||||
def test_get_roms_fs_structure_high_priority_structure(
|
||||
self, handler: FSRomsHandler
|
||||
):
|
||||
"""Test get_roms_fs_structure with high priority structure"""
|
||||
def test_get_roms_fs_structure_structure_a(self, handler: FSRomsHandler):
|
||||
"""Test get_roms_fs_structure with Structure A (roms/{platform})"""
|
||||
fs_slug = "n64"
|
||||
cnfg = Config(
|
||||
EXCLUDED_PLATFORMS=[],
|
||||
EXCLUDED_SINGLE_EXT=[],
|
||||
EXCLUDED_SINGLE_FILES=[],
|
||||
EXCLUDED_MULTI_FILES=[],
|
||||
EXCLUDED_MULTI_PARTS_EXT=[],
|
||||
EXCLUDED_MULTI_PARTS_FILES=[],
|
||||
PLATFORMS_BINDING={},
|
||||
PLATFORMS_VERSIONS={},
|
||||
ROMS_FOLDER_NAME="roms",
|
||||
FIRMWARE_FOLDER_NAME="bios",
|
||||
)
|
||||
cnfg.has_structure_path_b = False
|
||||
|
||||
with pytest.MonkeyPatch.context() as m:
|
||||
m.setattr(
|
||||
"handler.filesystem.roms_handler.cm.get_config",
|
||||
lambda: Config(
|
||||
EXCLUDED_PLATFORMS=[],
|
||||
EXCLUDED_SINGLE_EXT=[],
|
||||
EXCLUDED_SINGLE_FILES=[],
|
||||
EXCLUDED_MULTI_FILES=[],
|
||||
EXCLUDED_MULTI_PARTS_EXT=[],
|
||||
EXCLUDED_MULTI_PARTS_FILES=[],
|
||||
PLATFORMS_BINDING={},
|
||||
PLATFORMS_VERSIONS={},
|
||||
ROMS_FOLDER_NAME="roms",
|
||||
FIRMWARE_FOLDER_NAME="bios",
|
||||
),
|
||||
)
|
||||
m.setattr(
|
||||
"os.path.exists", lambda x: True
|
||||
) # Simulate high priority structure
|
||||
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: cnfg)
|
||||
|
||||
result = handler.get_roms_fs_structure(fs_slug)
|
||||
assert result == f"roms/{fs_slug}"
|
||||
@@ -258,6 +249,41 @@ class TestFSRomsHandler:
|
||||
result = handler.exclude_multi_roms(roms)
|
||||
assert result == roms
|
||||
|
||||
def test_exclude_multi_roms_case_insensitive(self, handler: FSRomsHandler, config):
|
||||
"""Test exclude_multi_roms ignores case in excluded names"""
|
||||
roms = ["Game1", "Manuals", "Game2"]
|
||||
config.EXCLUDED_MULTI_FILES = ["manuals"]
|
||||
|
||||
with pytest.MonkeyPatch.context() as m:
|
||||
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
|
||||
|
||||
result = handler.exclude_multi_roms(roms)
|
||||
assert result == ["Game1", "Game2"]
|
||||
|
||||
def test_exclude_multi_roms_ignores_whitespace(
|
||||
self, handler: FSRomsHandler, config
|
||||
):
|
||||
"""Test exclude_multi_roms trims accidental surrounding whitespace"""
|
||||
roms = ["Game1", "covers", "Game2"]
|
||||
config.EXCLUDED_MULTI_FILES = [" covers "]
|
||||
|
||||
with pytest.MonkeyPatch.context() as m:
|
||||
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
|
||||
|
||||
result = handler.exclude_multi_roms(roms)
|
||||
assert result == ["Game1", "Game2"]
|
||||
|
||||
def test_exclude_multi_roms_wildcard_patterns(self, handler: FSRomsHandler, config):
|
||||
"""Test exclude_multi_roms keeps wildcard matching with normalized config"""
|
||||
roms = ["Game1", "Manuals", "manuals-fr", "Game2"]
|
||||
config.EXCLUDED_MULTI_FILES = [" manuals* "]
|
||||
|
||||
with pytest.MonkeyPatch.context() as m:
|
||||
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
|
||||
|
||||
result = handler.exclude_multi_roms(roms)
|
||||
assert result == ["Game1", "Game2"]
|
||||
|
||||
def test_build_rom_file_single_file(self, rom_single: Rom, handler: FSRomsHandler):
|
||||
"""Test _build_rom_file with actual single ROM file"""
|
||||
rom_path = Path(rom_single.fs_path)
|
||||
@@ -267,6 +293,7 @@ class TestFSRomsHandler:
|
||||
"crc_hash": "ABCD1234",
|
||||
"md5_hash": "def456",
|
||||
"sha1_hash": "789ghi",
|
||||
"chd_sha1_hash": "654321",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -292,6 +319,7 @@ class TestFSRomsHandler:
|
||||
"crc_hash": "12345678",
|
||||
"md5_hash": "abcdef",
|
||||
"sha1_hash": "123456",
|
||||
"chd_sha1_hash": "654321",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -386,6 +414,64 @@ class TestFSRomsHandler:
|
||||
assert rom_file.file_size_bytes > 0
|
||||
assert rom_file.last_modified is not None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_rom_files_multi_rom_multi_dot_exclusion(
|
||||
self, handler: FSRomsHandler, rom_multi
|
||||
):
|
||||
"""Multi-dot filenames in a multi-part dir are excluded by simple or compound ext rules."""
|
||||
multi_dot_file = (
|
||||
handler.base_path / "n64/roms/Super Mario 64 (J) (Rev A)/game.n64.hash.txt"
|
||||
)
|
||||
multi_dot_file.write_text("hash data")
|
||||
|
||||
try:
|
||||
# Exclude by the last single extension "txt"
|
||||
config_txt = Config(
|
||||
EXCLUDED_PLATFORMS=[],
|
||||
EXCLUDED_SINGLE_EXT=[],
|
||||
EXCLUDED_SINGLE_FILES=[],
|
||||
EXCLUDED_MULTI_FILES=[],
|
||||
EXCLUDED_MULTI_PARTS_EXT=["txt"],
|
||||
EXCLUDED_MULTI_PARTS_FILES=[],
|
||||
PLATFORMS_BINDING={},
|
||||
PLATFORMS_VERSIONS={},
|
||||
ROMS_FOLDER_NAME="roms",
|
||||
FIRMWARE_FOLDER_NAME="bios",
|
||||
)
|
||||
with pytest.MonkeyPatch.context() as m:
|
||||
m.setattr(
|
||||
"handler.filesystem.roms_handler.cm.get_config", lambda: config_txt
|
||||
)
|
||||
parsed = await handler.get_rom_files(rom_multi)
|
||||
file_names = [rf.file_name for rf in parsed.rom_files]
|
||||
assert "game.n64.hash.txt" not in file_names
|
||||
assert "Super Mario 64 (J) (Rev A) [Part 1].z64" in file_names
|
||||
|
||||
# Exclude by the compound extension "hash.txt"
|
||||
config_compound = Config(
|
||||
EXCLUDED_PLATFORMS=[],
|
||||
EXCLUDED_SINGLE_EXT=[],
|
||||
EXCLUDED_SINGLE_FILES=[],
|
||||
EXCLUDED_MULTI_FILES=[],
|
||||
EXCLUDED_MULTI_PARTS_EXT=["hash.txt"],
|
||||
EXCLUDED_MULTI_PARTS_FILES=[],
|
||||
PLATFORMS_BINDING={},
|
||||
PLATFORMS_VERSIONS={},
|
||||
ROMS_FOLDER_NAME="roms",
|
||||
FIRMWARE_FOLDER_NAME="bios",
|
||||
)
|
||||
with pytest.MonkeyPatch.context() as m:
|
||||
m.setattr(
|
||||
"handler.filesystem.roms_handler.cm.get_config",
|
||||
lambda: config_compound,
|
||||
)
|
||||
parsed = await handler.get_rom_files(rom_multi)
|
||||
file_names = [rf.file_name for rf in parsed.rom_files]
|
||||
assert "game.n64.hash.txt" not in file_names
|
||||
assert "Super Mario 64 (J) (Rev A) [Part 1].z64" in file_names
|
||||
finally:
|
||||
multi_dot_file.unlink(missing_ok=True)
|
||||
|
||||
async def test_rename_fs_rom_same_name(self, handler: FSRomsHandler):
|
||||
"""Test rename_fs_rom when old and new names are the same"""
|
||||
old_name = "test_rom.n64"
|
||||
@@ -510,7 +596,7 @@ class TestFSRomsHandler:
|
||||
assert parsed_tags.revision == "B"
|
||||
assert parsed_tags.version == ""
|
||||
|
||||
def test_platform_specific_behavior(self, handler: FSRomsHandler):
|
||||
def test_platform_specific_behavior(self, handler: FSRomsHandler, config):
|
||||
"""Test platform-specific behavior differences"""
|
||||
# Create mock platforms - one hashable, one non-hashable
|
||||
hashable_platform = Mock(spec=Platform)
|
||||
@@ -521,12 +607,15 @@ class TestFSRomsHandler:
|
||||
non_hashable_platform.fs_slug = "n64"
|
||||
non_hashable_platform.slug = "nintendo-64"
|
||||
|
||||
# Test ROM file structure paths
|
||||
hashable_path = handler.get_roms_fs_structure(hashable_platform.fs_slug)
|
||||
non_hashable_path = handler.get_roms_fs_structure(non_hashable_platform.fs_slug)
|
||||
config.has_structure_path_b = True
|
||||
|
||||
with pytest.MonkeyPatch.context() as m:
|
||||
m.setattr("os.path.exists", lambda x: False) # Normal structure
|
||||
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
|
||||
|
||||
hashable_path = handler.get_roms_fs_structure(hashable_platform.fs_slug)
|
||||
non_hashable_path = handler.get_roms_fs_structure(
|
||||
non_hashable_platform.fs_slug
|
||||
)
|
||||
|
||||
assert hashable_path == f"{hashable_platform.fs_slug}/roms"
|
||||
assert non_hashable_path == f"{non_hashable_platform.fs_slug}/roms"
|
||||
@@ -548,20 +637,20 @@ class TestFSRomsHandler:
|
||||
assert "Super Mario 64 (J) (Rev A)" in filtered_dirs
|
||||
assert "Test Multi Rom [USA]" in filtered_dirs
|
||||
|
||||
def test_rom_fs_structure_consistency(self, handler: FSRomsHandler):
|
||||
def test_rom_fs_structure_consistency(self, handler: FSRomsHandler, config):
|
||||
"""Test that ROM filesystem structure is consistent across methods"""
|
||||
fs_slug = "gba"
|
||||
|
||||
with pytest.MonkeyPatch.context() as m:
|
||||
# Test with normal structure
|
||||
m.setattr("os.path.exists", lambda x: False)
|
||||
m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config)
|
||||
|
||||
# Test with Structure B
|
||||
config.has_structure_path_b = True
|
||||
structure = handler.get_roms_fs_structure(fs_slug)
|
||||
assert structure == f"{fs_slug}/roms"
|
||||
|
||||
# Test with high priority structure
|
||||
m.setattr("os.path.exists", lambda x: True)
|
||||
|
||||
# Test with Structure A
|
||||
config.has_structure_path_b = False
|
||||
structure = handler.get_roms_fs_structure(fs_slug)
|
||||
assert structure == f"roms/{fs_slug}"
|
||||
|
||||
@@ -659,13 +748,11 @@ class TestFSRomsHandler:
|
||||
async def test_get_rom_files_with_chd_v5_uses_internal_hash(
|
||||
self, handler: FSRomsHandler, platform, tmp_path
|
||||
):
|
||||
"""Test that a CHD v5 file uses its internal hash and skips other hashing.
|
||||
"""Test that a CHD v5 file stores the header SHA1 in chd_sha1_hash.
|
||||
|
||||
This integration test verifies the complete CHD v5 hashing logic:
|
||||
1. For valid CHD v5 files, the embedded SHA1 hash from the file header is used
|
||||
2. CRC32 and MD5 hashes are NOT calculated from file contents
|
||||
3. The file is not double-processed by read_basic_file
|
||||
4. This prevents regressions in the if/elif archive type chain
|
||||
CHD files are hashed like any other file type (CRC32, MD5, SHA1 from
|
||||
raw bytes). The embedded disc-data SHA1 from the CHD v5 header is
|
||||
separately stored in chd_sha1_hash for metadata providers that need it.
|
||||
"""
|
||||
# Create a mock CHD v5 file in a temporary directory
|
||||
chd_file = tmp_path / "test.chd"
|
||||
@@ -698,22 +785,19 @@ class TestFSRomsHandler:
|
||||
# Run the hashing process
|
||||
parsed_rom_files = await test_handler.get_rom_files(rom)
|
||||
|
||||
# Assert that only SHA1 is populated, and it's from the header
|
||||
# All three raw-file hashes should be populated
|
||||
assert len(parsed_rom_files.rom_files) == 1
|
||||
assert parsed_rom_files.crc_hash != "", "CRC should be computed from raw bytes"
|
||||
assert parsed_rom_files.md5_hash != "", "MD5 should be computed from raw bytes"
|
||||
assert (
|
||||
parsed_rom_files.sha1_hash == internal_sha1
|
||||
), "SHA1 should be from CHD v5 header"
|
||||
assert parsed_rom_files.rom_files[0].sha1_hash == internal_sha1
|
||||
parsed_rom_files.sha1_hash != ""
|
||||
), "SHA1 should be computed from raw bytes"
|
||||
|
||||
# CRC32 and MD5 should be empty/zero (not calculated)
|
||||
assert (
|
||||
parsed_rom_files.crc_hash == ""
|
||||
), f"CRC hash should be empty, got: {parsed_rom_files.crc_hash}"
|
||||
assert (
|
||||
parsed_rom_files.md5_hash == ""
|
||||
), f"MD5 hash should be empty, got: {parsed_rom_files.md5_hash}"
|
||||
assert parsed_rom_files.rom_files[0].crc_hash == ""
|
||||
assert parsed_rom_files.rom_files[0].md5_hash == ""
|
||||
# Raw file SHA1 is NOT the header SHA1
|
||||
assert parsed_rom_files.sha1_hash != internal_sha1
|
||||
|
||||
# Header SHA1 stored separately in chd_sha1_hash
|
||||
assert parsed_rom_files.rom_files[0].chd_sha1_hash == internal_sha1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_rom_files_with_non_v5_chd_fallback_to_std_hashing(
|
||||
@@ -793,7 +877,7 @@ class TestExtractCHDHash:
|
||||
|
||||
result = extract_chd_hash(chd_file)
|
||||
|
||||
assert result is not None
|
||||
assert result
|
||||
assert isinstance(result, str)
|
||||
assert len(result) == 40 # SHA1 hex is 40 characters
|
||||
assert result == "0123456789abcdef0123456789abcdef01234567"
|
||||
@@ -810,7 +894,7 @@ class TestExtractCHDHash:
|
||||
|
||||
result = extract_chd_hash(chd_file)
|
||||
|
||||
assert result is None
|
||||
assert result == ""
|
||||
|
||||
def test_extract_chd_hash_v2_rejected(self, tmp_path):
|
||||
"""Test that CHD v2 files are rejected"""
|
||||
@@ -824,7 +908,7 @@ class TestExtractCHDHash:
|
||||
|
||||
result = extract_chd_hash(chd_file)
|
||||
|
||||
assert result is None
|
||||
assert result == ""
|
||||
|
||||
def test_extract_chd_hash_v3_rejected(self, tmp_path):
|
||||
"""Test that CHD v3 files are rejected"""
|
||||
@@ -838,7 +922,7 @@ class TestExtractCHDHash:
|
||||
|
||||
result = extract_chd_hash(chd_file)
|
||||
|
||||
assert result is None
|
||||
assert result == ""
|
||||
|
||||
def test_extract_chd_hash_v4_rejected(self, tmp_path):
|
||||
"""Test that CHD v4 files are rejected"""
|
||||
@@ -852,7 +936,7 @@ class TestExtractCHDHash:
|
||||
|
||||
result = extract_chd_hash(chd_file)
|
||||
|
||||
assert result is None
|
||||
assert result == ""
|
||||
|
||||
def test_extract_chd_hash_invalid_magic(self, tmp_path):
|
||||
"""Test that files without CHD magic signature are rejected"""
|
||||
@@ -866,7 +950,7 @@ class TestExtractCHDHash:
|
||||
|
||||
result = extract_chd_hash(chd_file)
|
||||
|
||||
assert result is None
|
||||
assert result == ""
|
||||
|
||||
def test_extract_chd_hash_truncated_header(self, tmp_path):
|
||||
"""Test that CHD v5 file with truncated header is rejected"""
|
||||
@@ -881,7 +965,7 @@ class TestExtractCHDHash:
|
||||
|
||||
result = extract_chd_hash(chd_file)
|
||||
|
||||
assert result is None
|
||||
assert result == ""
|
||||
|
||||
def test_extract_chd_hash_nonexistent_file(self, tmp_path):
|
||||
"""Test that non-existent files are handled gracefully"""
|
||||
@@ -889,7 +973,7 @@ class TestExtractCHDHash:
|
||||
|
||||
result = extract_chd_hash(nonexistent)
|
||||
|
||||
assert result is None
|
||||
assert result == ""
|
||||
|
||||
def test_extract_chd_hash_empty_file(self, tmp_path):
|
||||
"""Test that empty files are rejected"""
|
||||
@@ -898,7 +982,7 @@ class TestExtractCHDHash:
|
||||
|
||||
result = extract_chd_hash(chd_file)
|
||||
|
||||
assert result is None
|
||||
assert result == ""
|
||||
|
||||
def test_extract_chd_hash_sha1_format(self, tmp_path):
|
||||
"""Test that SHA1 hash is correctly formatted as hex"""
|
||||
@@ -922,28 +1006,6 @@ class TestExtractCHDHash:
|
||||
# Verify it's 40 characters (SHA1 is 20 bytes = 40 hex chars)
|
||||
assert len(result) == 40
|
||||
|
||||
def test_extract_chd_hash_with_wrapper(self, tmp_path):
|
||||
"""Test that extracted hash integrates properly with CHDHashWrapper"""
|
||||
chd_file = tmp_path / "test_wrapper.chd"
|
||||
|
||||
header = bytearray(124)
|
||||
header[0:8] = b"MComprHD"
|
||||
header[12:16] = int(5).to_bytes(4, "big")
|
||||
test_sha1 = bytes.fromhex("0123456789abcdef0123456789abcdef01234567")
|
||||
header[84:104] = test_sha1
|
||||
|
||||
chd_file.write_bytes(header)
|
||||
|
||||
extracted_hash = extract_chd_hash(chd_file)
|
||||
assert extracted_hash is not None
|
||||
|
||||
# Should be usable with CHDHashWrapper
|
||||
wrapper = CHDHashWrapper(extracted_hash, "sha1")
|
||||
assert wrapper.hexdigest() == extracted_hash
|
||||
assert len(wrapper.digest()) == 20
|
||||
# Verify digest bytes match the original
|
||||
assert wrapper.digest() == test_sha1
|
||||
|
||||
def test_extract_chd_hash_unknown_version(self, tmp_path):
|
||||
"""Test that unknown CHD versions are rejected"""
|
||||
chd_file = tmp_path / "test_unknown.chd"
|
||||
@@ -956,7 +1018,7 @@ class TestExtractCHDHash:
|
||||
|
||||
result = extract_chd_hash(chd_file)
|
||||
|
||||
assert result is None
|
||||
assert result == ""
|
||||
|
||||
def test_extract_chd_hash_multiple_different_hashes(self, tmp_path):
|
||||
"""Test that different SHA1 hashes are correctly extracted"""
|
||||
@@ -984,11 +1046,11 @@ class TestExtractCHDHash:
|
||||
def test_extract_chd_hash_version_boundary_cases(self, tmp_path):
|
||||
"""Test version checking at boundaries (0, 1, 4, 5, 6)"""
|
||||
test_versions = [
|
||||
(0, None), # Version 0 should return None
|
||||
(1, None), # Version 1 should return None
|
||||
(4, None), # Version 4 should return None
|
||||
(0, ""), # Version 0 should return ""
|
||||
(1, ""), # Version 1 should return ""
|
||||
(4, ""), # Version 4 should return ""
|
||||
(5, "0123456789abcdef0123456789abcdef01234567"), # Version 5 should work
|
||||
(6, None), # Version 6 should return None
|
||||
(6, ""), # Version 6 should return ""
|
||||
]
|
||||
|
||||
for version, expected in test_versions:
|
||||
@@ -1003,10 +1065,7 @@ class TestExtractCHDHash:
|
||||
|
||||
result = extract_chd_hash(chd_file)
|
||||
|
||||
if expected is None:
|
||||
assert result is None, f"Version {version} should return None"
|
||||
else:
|
||||
assert result == expected, f"Version {version} should return {expected}"
|
||||
assert result == expected, f"Version {version} should return {expected!r}"
|
||||
|
||||
def test_extract_chd_hash_file_too_short_for_magic(self, tmp_path):
|
||||
"""Test file that's too short to even contain magic + version"""
|
||||
@@ -1020,7 +1079,7 @@ class TestExtractCHDHash:
|
||||
|
||||
result = extract_chd_hash(chd_file)
|
||||
|
||||
assert result is None
|
||||
assert result == ""
|
||||
|
||||
def test_extract_chd_hash_permission_error(self, tmp_path):
|
||||
"""Test graceful handling of permission errors"""
|
||||
@@ -1037,7 +1096,7 @@ class TestExtractCHDHash:
|
||||
|
||||
try:
|
||||
result = extract_chd_hash(chd_file)
|
||||
assert result is None
|
||||
assert result == ""
|
||||
finally:
|
||||
# Restore permissions for cleanup
|
||||
chd_file.chmod(0o644)
|
||||
@@ -1082,7 +1141,7 @@ class TestExtractCHDHash:
|
||||
# Expected SHA1 from the header at bytes 84-103 (20 bytes, as per chd.h)
|
||||
expected_sha1 = "0167fc76f9e4312e6ab48fe980d2ce5b23f775c2"
|
||||
|
||||
assert result is not None
|
||||
assert result
|
||||
assert result == expected_sha1
|
||||
assert len(result) == 40
|
||||
# Verify it matches what's in the header
|
||||
@@ -1109,14 +1168,14 @@ class TestExtractCHDHash:
|
||||
|
||||
result = extract_chd_hash(chd_file)
|
||||
|
||||
assert result is not None
|
||||
assert result
|
||||
assert result == "0167fc76f9e4312e6ab48fe980d2ce5b23f775c2"
|
||||
assert bytes.fromhex(result) == test_sha1
|
||||
|
||||
def test_extract_chd_hash_off_by_one_header_sizes(self, tmp_path):
|
||||
"""Test boundary conditions around minimum required header size (104 bytes)"""
|
||||
test_cases = [
|
||||
(103, None), # 103 bytes - not enough for SHA1 region
|
||||
(103, ""), # 103 bytes - not enough for SHA1 region
|
||||
(
|
||||
104,
|
||||
"0167fc76f9e4312e6ab48fe980d2ce5b23f775c2",
|
||||
@@ -1158,8 +1217,8 @@ class TestExtractCHDHash:
|
||||
|
||||
result = extract_chd_hash(chd_file)
|
||||
|
||||
# Should return None because version is not 5
|
||||
assert result is None
|
||||
# Should return empty string because version is not 5
|
||||
assert result == ""
|
||||
|
||||
def test_extract_chd_hash_zero_sha1(self, tmp_path):
|
||||
"""Test handling of all-zero SHA1 hash (edge case but valid)"""
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
"""Tests for filesystem sync handler."""
|
||||
|
||||
import errno
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from handler.filesystem.sync_handler import FSSyncHandler
|
||||
from handler.filesystem.sync_handler import FSSyncHandler, get_fs_sync_handler
|
||||
|
||||
|
||||
class TestFSSyncHandler:
|
||||
@@ -133,3 +135,22 @@ class TestFSSyncHandler:
|
||||
def test_remove_incoming_file_nonexistent(self, handler: FSSyncHandler):
|
||||
# Should not raise for nonexistent files
|
||||
handler.remove_incoming_file("/nonexistent/path/file.sav")
|
||||
|
||||
|
||||
class TestFSSyncHandlerLazyFactory:
|
||||
"""Sync is an optional feature: if /romm/sync isn't writable (bad mount,
|
||||
wrong ownership), the app must still boot. The factory defers construction
|
||||
until first use so the error surfaces at the call site, not at startup."""
|
||||
|
||||
def test_factory_raises_at_call_time_when_unwritable(self):
|
||||
"""Regression for the PermissionError on /romm/sync at boot: the
|
||||
failure must surface from the factory call, not from module import."""
|
||||
get_fs_sync_handler.cache_clear()
|
||||
try:
|
||||
with patch.object(
|
||||
Path, "mkdir", side_effect=PermissionError(errno.EACCES, "denied")
|
||||
):
|
||||
with pytest.raises(PermissionError):
|
||||
get_fs_sync_handler()
|
||||
finally:
|
||||
get_fs_sync_handler.cache_clear()
|
||||
@@ -1,6 +1,7 @@
|
||||
import json
|
||||
import re
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from urllib.parse import parse_qsl, urlparse
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -21,6 +22,8 @@ from handler.metadata.base_handler import (
|
||||
MetadataHandler,
|
||||
UniversalPlatformSlug,
|
||||
_normalize_search_term,
|
||||
restore_sensitive_query_params,
|
||||
strip_sensitive_query_params,
|
||||
)
|
||||
from handler.redis_handler import async_cache
|
||||
|
||||
@@ -400,6 +403,152 @@ class TestMetadataHandlerMethods:
|
||||
assert result["api_key"] == "ab***ab" # Shows first 2 and last 2
|
||||
|
||||
|
||||
class TestStripSensitiveQueryParams:
|
||||
"""Test the strip_sensitive_query_params function."""
|
||||
|
||||
def test_removes_known_sensitive_keys(self):
|
||||
"""ssid and sspassword should be stripped from the query string."""
|
||||
url = "https://api.example.com/media?ssid=user&sspassword=secret&crc=abc"
|
||||
result = strip_sensitive_query_params(url)
|
||||
assert "ssid=" not in result
|
||||
assert "sspassword=" not in result
|
||||
assert "crc=abc" in result
|
||||
|
||||
def test_preserves_non_sensitive_params(self):
|
||||
"""Non-sensitive params should keep their values and ordering."""
|
||||
url = "https://api.example.com/media?systemeid=1&ssid=user&romnom=Game.zip"
|
||||
result = strip_sensitive_query_params(url)
|
||||
# parse rather than rely on a literal — urlencode may reorder identically-named keys
|
||||
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
||||
assert ("systemeid", "1") in parsed
|
||||
assert ("romnom", "Game.zip") in parsed
|
||||
assert all(k != "ssid" for k, _ in parsed)
|
||||
|
||||
def test_case_insensitive_key_matching(self):
|
||||
"""Keys should match regardless of case (SSID, SsId, etc.)."""
|
||||
url = "https://api.example.com/media?SSID=user&SSPassword=secret&crc=abc"
|
||||
result = strip_sensitive_query_params(url)
|
||||
assert "SSID=" not in result
|
||||
assert "SSPassword=" not in result
|
||||
assert "crc=abc" in result
|
||||
|
||||
def test_url_with_no_query(self):
|
||||
"""URLs without a query string should pass through unchanged in shape."""
|
||||
url = "https://api.example.com/media"
|
||||
result = strip_sensitive_query_params(url)
|
||||
assert result == "https://api.example.com/media"
|
||||
|
||||
def test_url_with_no_sensitive_params(self):
|
||||
"""URLs whose params are all non-sensitive should be preserved."""
|
||||
url = "https://api.example.com/media?systemeid=1&romnom=Game.zip"
|
||||
result = strip_sensitive_query_params(url)
|
||||
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
||||
assert ("systemeid", "1") in parsed
|
||||
assert ("romnom", "Game.zip") in parsed
|
||||
|
||||
def test_preserves_other_url_components(self):
|
||||
"""Scheme, host, path, and fragment should be preserved."""
|
||||
url = "https://api.example.com:8080/path/to/media?ssid=u&keep=1#frag"
|
||||
result = strip_sensitive_query_params(url)
|
||||
parsed = urlparse(result)
|
||||
assert parsed.scheme == "https"
|
||||
assert parsed.netloc == "api.example.com:8080"
|
||||
assert parsed.path == "/path/to/media"
|
||||
assert parsed.fragment == "frag"
|
||||
assert "ssid" not in parsed.query
|
||||
|
||||
def test_custom_sensitive_keys_override(self):
|
||||
"""A caller-supplied sensitive_keys set should override the default."""
|
||||
url = "https://api.example.com/m?ssid=user&token=tk&keep=1"
|
||||
result = strip_sensitive_query_params(url, sensitive_keys={"token"})
|
||||
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
||||
# ssid is not in the custom set so it stays; token is stripped
|
||||
assert ("ssid", "user") in parsed
|
||||
assert ("keep", "1") in parsed
|
||||
assert all(k != "token" for k, _ in parsed)
|
||||
|
||||
def test_blank_values_preserved(self):
|
||||
"""Blank values for non-sensitive keys should not be dropped."""
|
||||
url = "https://api.example.com/m?empty=&keep=1&ssid=user"
|
||||
result = strip_sensitive_query_params(url)
|
||||
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
||||
assert ("empty", "") in parsed
|
||||
assert ("keep", "1") in parsed
|
||||
|
||||
|
||||
class TestRestoreSensitiveQueryParams:
|
||||
"""Test the restore_sensitive_query_params function."""
|
||||
|
||||
def test_appends_to_url_with_no_query(self):
|
||||
"""Restoring onto a URL with no query should produce a valid query."""
|
||||
url = "https://api.example.com/media"
|
||||
result = restore_sensitive_query_params(
|
||||
url, {"ssid": "user", "sspassword": "secret"}
|
||||
)
|
||||
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
||||
assert ("ssid", "user") in parsed
|
||||
assert ("sspassword", "secret") in parsed
|
||||
|
||||
def test_preserves_existing_non_conflicting_params(self):
|
||||
"""Other params present on the URL must be kept alongside restored ones."""
|
||||
url = "https://api.example.com/m?systemeid=1&romnom=Game.zip"
|
||||
result = restore_sensitive_query_params(url, {"ssid": "user"})
|
||||
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
||||
assert ("systemeid", "1") in parsed
|
||||
assert ("romnom", "Game.zip") in parsed
|
||||
assert ("ssid", "user") in parsed
|
||||
|
||||
def test_overwrites_existing_same_key_no_duplicates(self):
|
||||
"""If the URL already has the key, it should be replaced, not duplicated."""
|
||||
url = "https://api.example.com/m?ssid=old&keep=1"
|
||||
result = restore_sensitive_query_params(url, {"ssid": "new"})
|
||||
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
||||
ssid_values = [v for k, v in parsed if k == "ssid"]
|
||||
assert ssid_values == ["new"]
|
||||
assert ("keep", "1") in parsed
|
||||
|
||||
def test_overwrite_is_case_insensitive(self):
|
||||
"""Existing keys differing only in case should still be replaced."""
|
||||
url = "https://api.example.com/m?SSID=old&keep=1"
|
||||
result = restore_sensitive_query_params(url, {"ssid": "new"})
|
||||
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
||||
# No leftover SSID=old entry under any casing
|
||||
ssid_values = [v for k, v in parsed if k.lower() == "ssid"]
|
||||
assert ssid_values == ["new"]
|
||||
|
||||
def test_encodes_special_characters_in_values(self):
|
||||
"""Values with reserved URL characters must be percent-encoded."""
|
||||
url = "https://api.example.com/m"
|
||||
result = restore_sensitive_query_params(url, {"sspassword": "p@ss w&rd=!"})
|
||||
# The raw value must not appear unencoded in the query
|
||||
assert "p@ss w&rd=!" not in result
|
||||
# But round-tripping through parse_qsl recovers the original value
|
||||
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
||||
assert ("sspassword", "p@ss w&rd=!") in parsed
|
||||
|
||||
def test_preserves_other_url_components(self):
|
||||
"""Scheme, host, path, and fragment should be preserved."""
|
||||
url = "https://api.example.com:8080/path?keep=1#frag"
|
||||
result = restore_sensitive_query_params(url, {"ssid": "u"})
|
||||
parsed = urlparse(result)
|
||||
assert parsed.scheme == "https"
|
||||
assert parsed.netloc == "api.example.com:8080"
|
||||
assert parsed.path == "/path"
|
||||
assert parsed.fragment == "frag"
|
||||
|
||||
def test_strip_then_restore_roundtrip(self):
|
||||
"""strip → restore should recover an equivalent URL for the credential keys."""
|
||||
original = "https://api.example.com/m?ssid=user&sspassword=secret&crc=abc"
|
||||
stripped = strip_sensitive_query_params(original)
|
||||
restored = restore_sensitive_query_params(
|
||||
stripped, {"ssid": "user", "sspassword": "secret"}
|
||||
)
|
||||
parsed = parse_qsl(urlparse(restored).query, keep_blank_values=True)
|
||||
assert ("ssid", "user") in parsed
|
||||
assert ("sspassword", "secret") in parsed
|
||||
assert ("crc", "abc") in parsed
|
||||
|
||||
|
||||
class TestRegexPatterns:
|
||||
"""Test regex patterns used in the metadata handler."""
|
||||
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import cast
|
||||
from unittest.mock import patch
|
||||
|
||||
from handler.metadata.gamelist_handler import GamelistHandler
|
||||
from models.platform import Platform
|
||||
|
||||
MOCK_METADATA = {
|
||||
"box2d_url": None,
|
||||
"image_url": None,
|
||||
"manual_url": None,
|
||||
"screenshot_url": None,
|
||||
"title_screen_url": None,
|
||||
}
|
||||
|
||||
|
||||
def test_parse_gamelist_xml_includes_folder_entries(tmp_path: Path, platform: Platform):
|
||||
gamelist_path = tmp_path / "gamelist.xml"
|
||||
gamelist_path.write_text(
|
||||
"""<?xml version="1.0"?>
|
||||
<gameList>
|
||||
<folder>
|
||||
<path>./Subfolder</path>
|
||||
<name>Folder Entry</name>
|
||||
<desc>Folder summary</desc>
|
||||
<lang>en, fr</lang>
|
||||
<region>us, eu</region>
|
||||
</folder>
|
||||
</gameList>""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
handler = GamelistHandler()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"handler.metadata.gamelist_handler.extract_metadata_from_gamelist_rom",
|
||||
return_value=MOCK_METADATA,
|
||||
),
|
||||
patch(
|
||||
"handler.metadata.gamelist_handler.get_preferred_media_types",
|
||||
return_value=[],
|
||||
),
|
||||
):
|
||||
roms_data = handler._parse_gamelist_xml(gamelist_path, platform)
|
||||
|
||||
assert "Subfolder" in roms_data
|
||||
folder_entry = roms_data["Subfolder"]
|
||||
assert folder_entry.get("name") == "Folder Entry"
|
||||
assert folder_entry.get("summary") == "Folder summary"
|
||||
assert folder_entry.get("languages") == ["en", "fr"]
|
||||
assert folder_entry.get("regions") == ["us", "eu"]
|
||||
|
||||
|
||||
def test_parse_gamelist_xml_keeps_game_entries(tmp_path: Path, platform: Platform):
|
||||
gamelist_path = tmp_path / "gamelist.xml"
|
||||
gamelist_path.write_text(
|
||||
"""<?xml version="1.0"?>
|
||||
<gameList>
|
||||
<game>
|
||||
<path>./test-rom.zip</path>
|
||||
<name>Game Entry</name>
|
||||
</game>
|
||||
</gameList>""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
handler = GamelistHandler()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"handler.metadata.gamelist_handler.extract_metadata_from_gamelist_rom",
|
||||
return_value=MOCK_METADATA,
|
||||
),
|
||||
patch(
|
||||
"handler.metadata.gamelist_handler.get_preferred_media_types",
|
||||
return_value=[],
|
||||
),
|
||||
):
|
||||
roms_data = handler._parse_gamelist_xml(gamelist_path, platform)
|
||||
|
||||
assert "test-rom.zip" in roms_data
|
||||
assert roms_data["test-rom.zip"].get("name") == "Game Entry"
|
||||
|
||||
|
||||
class TestGamelistHandler:
|
||||
def test_parse_gamelist_with_malformed_alternative_emulator_tag(self, tmp_path):
|
||||
gamelist_path = tmp_path / "gamelist.xml"
|
||||
gamelist_path.write_text(
|
||||
"""<?xml version="1.0" encoding="UTF-8"?>
|
||||
<gameList>
|
||||
<game>
|
||||
<path>./Test Game.zip</path>
|
||||
<name>Test Game</name>
|
||||
<desc>Test Summary</desc>
|
||||
<alternativeEmulator label="RetroArch & Standalone">duckstation</alternativeEmulator>
|
||||
</game>
|
||||
</gameList>
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
handler = GamelistHandler()
|
||||
platform = SimpleNamespace(id=1, fs_slug="psx")
|
||||
metadata = {
|
||||
"box2d_url": None,
|
||||
"image_url": None,
|
||||
"manual_url": None,
|
||||
"screenshot_url": None,
|
||||
"title_screen_url": None,
|
||||
}
|
||||
|
||||
with (
|
||||
patch(
|
||||
"handler.metadata.gamelist_handler.get_preferred_media_types",
|
||||
return_value=[],
|
||||
),
|
||||
patch(
|
||||
"handler.metadata.gamelist_handler.extract_metadata_from_gamelist_rom",
|
||||
return_value=metadata,
|
||||
),
|
||||
):
|
||||
roms_data = handler._parse_gamelist_xml(
|
||||
gamelist_path, cast(Platform, platform)
|
||||
)
|
||||
|
||||
assert "Test Game.zip" in roms_data
|
||||
assert roms_data["Test Game.zip"].get("name") == "Test Game"
|
||||
assert roms_data["Test Game.zip"].get("summary") == "Test Summary"
|
||||
|
||||
def test_parse_gamelist_with_es_de_alternative_emulator_sibling(self, tmp_path):
|
||||
gamelist_path = tmp_path / "gamelist.xml"
|
||||
gamelist_path.write_text(
|
||||
"""<?xml version="1.0"?>
|
||||
<alternativeEmulator>
|
||||
<label>Gambatte</label>
|
||||
</alternativeEmulator>
|
||||
<gameList>
|
||||
<game>
|
||||
<path>./Tetris.gb</path>
|
||||
<name>Tetris</name>
|
||||
<desc>Block stacking</desc>
|
||||
</game>
|
||||
</gameList>
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
handler = GamelistHandler()
|
||||
platform = SimpleNamespace(id=2, fs_slug="gb")
|
||||
metadata = {
|
||||
"box2d_url": None,
|
||||
"image_url": None,
|
||||
"manual_url": None,
|
||||
"screenshot_url": None,
|
||||
"title_screen_url": None,
|
||||
}
|
||||
|
||||
with (
|
||||
patch(
|
||||
"handler.metadata.gamelist_handler.get_preferred_media_types",
|
||||
return_value=[],
|
||||
),
|
||||
patch(
|
||||
"handler.metadata.gamelist_handler.extract_metadata_from_gamelist_rom",
|
||||
return_value=metadata,
|
||||
),
|
||||
):
|
||||
roms_data = handler._parse_gamelist_xml(
|
||||
gamelist_path, cast(Platform, platform)
|
||||
)
|
||||
|
||||
assert "Tetris.gb" in roms_data
|
||||
assert roms_data["Tetris.gb"].get("name") == "Tetris"
|
||||
assert roms_data["Tetris.gb"].get("summary") == "Block stacking"
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Tests for the IGDB metadata handler."""
|
||||
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from adapters.services.igdb_types import GameType
|
||||
from handler.metadata.igdb_handler import IGDBHandler
|
||||
|
||||
GENESIS_IGDB_ID = 29
|
||||
|
||||
|
||||
def _make_game(game_id: int, name: str) -> dict:
|
||||
"""Build a minimal IGDB Game dict for testing."""
|
||||
return {
|
||||
"id": game_id,
|
||||
"name": name,
|
||||
"slug": name.lower().replace(" ", "-"),
|
||||
"summary": "",
|
||||
"total_rating": 0.0,
|
||||
"aggregated_rating": 0.0,
|
||||
"first_release_date": None,
|
||||
"artworks": [],
|
||||
"cover": None,
|
||||
"screenshots": [],
|
||||
"platforms": [{"id": GENESIS_IGDB_ID, "name": "Sega Mega Drive/Genesis"}],
|
||||
"alternative_names": [],
|
||||
"genres": [],
|
||||
"franchise": None,
|
||||
"franchises": [],
|
||||
"collections": [],
|
||||
"game_modes": [],
|
||||
"involved_companies": [],
|
||||
"expansions": [],
|
||||
"dlcs": [],
|
||||
"remasters": [],
|
||||
"remakes": [],
|
||||
"expanded_games": [],
|
||||
"ports": [],
|
||||
"similar_games": [],
|
||||
"videos": [],
|
||||
"age_ratings": [],
|
||||
"multiplayer_modes": [],
|
||||
"game_localizations": [],
|
||||
}
|
||||
|
||||
|
||||
class TestSearchRomGameTypeFilter:
|
||||
"""Tests for _search_rom game_type filtering."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_standalone_expansion_included_in_game_type_filter(self):
|
||||
"""Searching with game_type filter must include STANDALONE_EXPANSION
|
||||
so that games like 'Ecco: The Tides of Time' are found on the first
|
||||
search pass and not confused with their parent game."""
|
||||
handler = IGDBHandler()
|
||||
|
||||
ecco_dolphin = _make_game(1799, "Ecco the Dolphin")
|
||||
ecco_tides = _make_game(5379, "Ecco: The Tides of Time")
|
||||
|
||||
async def mock_list_games(
|
||||
search_term=None, fields=None, where=None, limit=None
|
||||
):
|
||||
# First call (with game_type filter): return both games
|
||||
if where and "game_type" in where:
|
||||
# Verify STANDALONE_EXPANSION (4) is in the filter
|
||||
assert (
|
||||
str(int(GameType.STANDALONE_EXPANSION)) in where
|
||||
), f"STANDALONE_EXPANSION should be in game_type filter, got: {where}"
|
||||
# Simulate IGDB returning both games when the search includes
|
||||
# standalone expansions
|
||||
if search_term and "tides of time" in search_term.lower():
|
||||
return [ecco_dolphin, ecco_tides]
|
||||
return [ecco_dolphin]
|
||||
return []
|
||||
|
||||
with (
|
||||
patch(
|
||||
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
|
||||
return_value=True,
|
||||
),
|
||||
patch.object(
|
||||
handler.igdb_service,
|
||||
"list_games",
|
||||
side_effect=mock_list_games,
|
||||
),
|
||||
patch.object(
|
||||
handler.igdb_service,
|
||||
"search",
|
||||
new_callable=AsyncMock,
|
||||
return_value=[],
|
||||
),
|
||||
):
|
||||
result = await handler._search_rom(
|
||||
"ecco the tides of time", GENESIS_IGDB_ID, with_game_type=True
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
assert (
|
||||
result["id"] == 5379
|
||||
), f"Expected Ecco: The Tides of Time (id=5379), got {result.get('name')} (id={result.get('id')})"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_expanded_search_uses_all_results_not_just_first(self):
|
||||
"""When the primary search fails and the expanded IGDB search endpoint
|
||||
is used, all unique game IDs from the results must be fetched and
|
||||
the best match selected — not just the first result."""
|
||||
handler = IGDBHandler()
|
||||
|
||||
ecco_dolphin = _make_game(1799, "Ecco the Dolphin")
|
||||
ecco_tides = _make_game(5379, "Ecco: The Tides of Time")
|
||||
|
||||
# Primary search returns nothing useful
|
||||
async def mock_list_games(
|
||||
search_term=None, fields=None, where=None, limit=None
|
||||
):
|
||||
if where and "game_type" not in where and not where.startswith("("):
|
||||
# Primary search pass — return no results so we fall through to
|
||||
# the expanded search
|
||||
return []
|
||||
if where and where.startswith("("):
|
||||
# Expanded game details lookup — return both candidates
|
||||
return [ecco_dolphin, ecco_tides]
|
||||
return []
|
||||
|
||||
# Expanded search returns two results — wrong game FIRST, correct game second
|
||||
expanded_results = [
|
||||
{"game": {"id": 1799}, "name": "Ecco the Dolphin"},
|
||||
{"game": {"id": 5379}, "name": "Ecco: The Tides of Time"},
|
||||
]
|
||||
|
||||
with (
|
||||
patch(
|
||||
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
|
||||
return_value=True,
|
||||
),
|
||||
patch.object(
|
||||
handler.igdb_service,
|
||||
"list_games",
|
||||
side_effect=mock_list_games,
|
||||
),
|
||||
patch.object(
|
||||
handler.igdb_service,
|
||||
"search",
|
||||
new_callable=AsyncMock,
|
||||
return_value=expanded_results,
|
||||
),
|
||||
):
|
||||
result = await handler._search_rom(
|
||||
"ecco the tides of time", GENESIS_IGDB_ID, with_game_type=False
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
assert result["id"] == 5379, (
|
||||
f"Expected Ecco: The Tides of Time (id=5379), got {result.get('name')} (id={result.get('id')}). "
|
||||
"The expanded search must consider ALL results, not just the first."
|
||||
)
|
||||
@@ -2,11 +2,11 @@
|
||||
Tests for the LaunchBox metadata handler.
|
||||
|
||||
Covers:
|
||||
- utils.py — pure utility functions
|
||||
- platforms.py — platform slug resolution
|
||||
- local_source.py — LocalSource (local XML parsing + Redis index cache)
|
||||
- remote_source.py — RemoteSource (Redis metadata lookups)
|
||||
- handler.py — LaunchboxHandler orchestration
|
||||
- utils.py: pure utility functions
|
||||
- platforms.py: platform slug resolution
|
||||
- local_source.py: LocalSource (local XML parsing + Redis index cache)
|
||||
- remote_source.py: RemoteSource (Redis metadata lookups)
|
||||
- handler.py: LaunchboxHandler orchestration
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -19,15 +19,24 @@ from defusedxml import ElementTree as ET
|
||||
|
||||
from handler.metadata.launchbox_handler.handler import LaunchboxHandler
|
||||
from handler.metadata.launchbox_handler.local_source import LocalSource
|
||||
from handler.metadata.launchbox_handler.media import build_launchbox_metadata, build_rom
|
||||
from handler.metadata.launchbox_handler.media import (
|
||||
_get_video,
|
||||
build_launchbox_metadata,
|
||||
build_rom,
|
||||
populate_rom_specific_paths,
|
||||
remote_media_req,
|
||||
)
|
||||
from handler.metadata.launchbox_handler.platforms import get_platform
|
||||
from handler.metadata.launchbox_handler.remote_source import RemoteSource
|
||||
from handler.metadata.launchbox_handler.types import (
|
||||
LAUNCHBOX_MAME_KEY,
|
||||
LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY,
|
||||
LAUNCHBOX_METADATA_DATABASE_ID_KEY,
|
||||
LAUNCHBOX_METADATA_IMAGE_KEY,
|
||||
LAUNCHBOX_METADATA_NAME_KEY,
|
||||
LaunchboxImage,
|
||||
LaunchboxMetadata,
|
||||
MediaRequest,
|
||||
)
|
||||
from handler.metadata.launchbox_handler.utils import (
|
||||
coalesce,
|
||||
@@ -520,6 +529,67 @@ class TestRemoteSourceGetRom:
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestRemoteSourceGetMameEntry:
|
||||
@pytest.fixture
|
||||
def source(self) -> RemoteSource:
|
||||
return RemoteSource()
|
||||
|
||||
async def test_cache_miss_returns_none(self, source: RemoteSource):
|
||||
with patch.object(
|
||||
async_cache, "hget", new_callable=AsyncMock, return_value=None
|
||||
):
|
||||
result = await source.get_mame_entry("pacman.zip")
|
||||
assert result is None
|
||||
|
||||
async def test_cache_hit_returns_dict(self, source: RemoteSource):
|
||||
# Real LaunchBox Mame.xml indexes by stem (e.g. `wrlok_l3`, no ext)
|
||||
# and carries `<Name>` as the full title.
|
||||
mame_entry = {
|
||||
"FileName": "wrlok_l3",
|
||||
"Name": "Warlok",
|
||||
"Year": "1982",
|
||||
}
|
||||
with patch.object(
|
||||
async_cache,
|
||||
"hget",
|
||||
new_callable=AsyncMock,
|
||||
return_value=json.dumps(mame_entry),
|
||||
) as mock_hget:
|
||||
result = await source.get_mame_entry("wrlok_l3")
|
||||
mock_hget.assert_called_once_with(LAUNCHBOX_MAME_KEY, "wrlok_l3")
|
||||
assert result == mame_entry
|
||||
|
||||
async def test_falls_back_to_stem_when_given_filename_with_ext(
|
||||
self, source: RemoteSource
|
||||
):
|
||||
mame_entry = {"FileName": "wrlok_l3", "Name": "Warlok"}
|
||||
|
||||
async def fake_hget(_key, field):
|
||||
return json.dumps(mame_entry) if field == "wrlok_l3" else None
|
||||
|
||||
with patch.object(
|
||||
async_cache, "hget", new_callable=AsyncMock, side_effect=fake_hget
|
||||
) as mock_hget:
|
||||
result = await source.get_mame_entry("wrlok_l3.zip")
|
||||
# First lookup by raw filename (miss), then by stem (hit).
|
||||
assert mock_hget.call_count == 2
|
||||
assert mock_hget.call_args_list[0].args == (LAUNCHBOX_MAME_KEY, "wrlok_l3.zip")
|
||||
assert mock_hget.call_args_list[1].args == (LAUNCHBOX_MAME_KEY, "wrlok_l3")
|
||||
assert result == mame_entry
|
||||
|
||||
async def test_empty_input_returns_none(self, source: RemoteSource):
|
||||
result = await source.get_mame_entry("")
|
||||
assert result is None
|
||||
|
||||
async def test_whitespace_stripped(self, source: RemoteSource):
|
||||
with patch.object(
|
||||
async_cache, "hget", new_callable=AsyncMock, return_value=None
|
||||
) as mock_hget:
|
||||
await source.get_mame_entry(" wrlok_l3 ")
|
||||
# First call uses the trimmed filename.
|
||||
assert mock_hget.call_args_list[0].args == (LAUNCHBOX_MAME_KEY, "wrlok_l3")
|
||||
|
||||
|
||||
class TestRemoteSourceFetchImages:
|
||||
@pytest.fixture
|
||||
def source(self) -> RemoteSource:
|
||||
@@ -636,6 +706,255 @@ class TestBuildLaunchboxMetadata:
|
||||
assert meta.get("images", []) == images
|
||||
|
||||
|
||||
class TestGetVideo:
|
||||
@pytest.fixture
|
||||
def videos_dir(self, tmp_path: Path, monkeypatch) -> Path:
|
||||
videos_root = tmp_path / "Videos"
|
||||
videos_root.mkdir()
|
||||
monkeypatch.setattr(
|
||||
"handler.metadata.launchbox_handler.media.LAUNCHBOX_VIDEOS_DIR",
|
||||
videos_root,
|
||||
)
|
||||
# file_uri_for_local_path is rooted at LAUNCHBOX_LOCAL_DIR: patch so our
|
||||
# tmp videos sit under it and produce a well-formed URL.
|
||||
monkeypatch.setattr(
|
||||
"handler.metadata.launchbox_handler.utils.LAUNCHBOX_LOCAL_DIR",
|
||||
tmp_path,
|
||||
)
|
||||
return videos_root
|
||||
|
||||
def _req(
|
||||
self, fs_name: str, title: str = "", platform: str = "NES"
|
||||
) -> MediaRequest:
|
||||
return MediaRequest(
|
||||
platform_name=platform,
|
||||
fs_name=fs_name,
|
||||
title=title,
|
||||
region_hint=None,
|
||||
remote_images=None,
|
||||
remote_enabled=False,
|
||||
)
|
||||
|
||||
def test_no_platform_returns_none(self, videos_dir: Path):
|
||||
req = MediaRequest(
|
||||
platform_name=None,
|
||||
fs_name="game.nes",
|
||||
title="",
|
||||
region_hint=None,
|
||||
remote_images=None,
|
||||
remote_enabled=False,
|
||||
)
|
||||
assert _get_video(req) is None
|
||||
|
||||
def test_missing_platform_dir_returns_none(self, videos_dir: Path):
|
||||
# videos_dir has no "NES" subdirectory
|
||||
assert _get_video(self._req("mario.nes")) is None
|
||||
|
||||
def test_finds_mp4_by_fs_stem(self, videos_dir: Path):
|
||||
platform_dir = videos_dir / "NES"
|
||||
platform_dir.mkdir()
|
||||
(platform_dir / "Mario.mp4").write_bytes(b"")
|
||||
|
||||
url = _get_video(self._req("Mario.nes"))
|
||||
assert url == "launchbox-file://Videos/NES/Mario.mp4"
|
||||
|
||||
def test_falls_back_to_title_stem(self, videos_dir: Path):
|
||||
platform_dir = videos_dir / "NES"
|
||||
platform_dir.mkdir()
|
||||
(platform_dir / "Super Mario Bros.webm").write_bytes(b"")
|
||||
|
||||
url = _get_video(self._req("roms-mario-1.nes", title="Super Mario Bros"))
|
||||
assert url == "launchbox-file://Videos/NES/Super Mario Bros.webm"
|
||||
|
||||
def test_multiple_extensions_tried(self, videos_dir: Path):
|
||||
platform_dir = videos_dir / "NES"
|
||||
platform_dir.mkdir()
|
||||
(platform_dir / "Mario.mkv").write_bytes(b"")
|
||||
|
||||
url = _get_video(self._req("Mario.nes"))
|
||||
assert url is not None
|
||||
assert url.endswith(".mkv")
|
||||
|
||||
def test_no_match_returns_none(self, videos_dir: Path):
|
||||
platform_dir = videos_dir / "NES"
|
||||
platform_dir.mkdir()
|
||||
(platform_dir / "Zelda.mp4").write_bytes(b"")
|
||||
|
||||
assert _get_video(self._req("Mario.nes")) is None
|
||||
|
||||
|
||||
class TestPopulateRomSpecificPaths:
|
||||
def _rom(self) -> MagicMock:
|
||||
rom = MagicMock()
|
||||
rom.platform_id = 7
|
||||
rom.id = 42
|
||||
return rom
|
||||
|
||||
def test_no_video_url_is_noop(self):
|
||||
metadata: LaunchboxMetadata = {"first_release_date": None, "images": []}
|
||||
with patch(
|
||||
"handler.metadata.launchbox_handler.media.get_preferred_media_types"
|
||||
) as mock_preferred:
|
||||
from config.config_manager import MetadataMediaType
|
||||
|
||||
mock_preferred.return_value = [MetadataMediaType.VIDEO]
|
||||
populate_rom_specific_paths(metadata, self._rom())
|
||||
assert "video_path" not in metadata
|
||||
|
||||
def test_video_url_populates_path(self):
|
||||
metadata: LaunchboxMetadata = {
|
||||
"first_release_date": None,
|
||||
"images": [],
|
||||
"video_url": "launchbox-file://Videos/NES/Mario.mp4",
|
||||
}
|
||||
with patch(
|
||||
"handler.metadata.launchbox_handler.media.get_preferred_media_types"
|
||||
) as mock_preferred:
|
||||
from config.config_manager import MetadataMediaType
|
||||
|
||||
mock_preferred.return_value = [MetadataMediaType.VIDEO]
|
||||
populate_rom_specific_paths(metadata, self._rom())
|
||||
path = metadata.get("video_path", "")
|
||||
assert path.endswith("/video.mp4")
|
||||
assert "7" in path and "42" in path
|
||||
|
||||
def test_video_path_preserves_source_extension(self):
|
||||
from config.config_manager import MetadataMediaType
|
||||
|
||||
for src_ext, expected in (
|
||||
(".mkv", "/video.mkv"),
|
||||
(".webm", "/video.webm"),
|
||||
(".MOV", "/video.mov"),
|
||||
):
|
||||
metadata: LaunchboxMetadata = {
|
||||
"first_release_date": None,
|
||||
"images": [],
|
||||
"video_url": f"launchbox-file://Videos/NES/Mario{src_ext}",
|
||||
}
|
||||
with patch(
|
||||
"handler.metadata.launchbox_handler.media.get_preferred_media_types"
|
||||
) as mock_preferred:
|
||||
mock_preferred.return_value = [MetadataMediaType.VIDEO]
|
||||
populate_rom_specific_paths(metadata, self._rom())
|
||||
assert metadata.get("video_path", "").endswith(expected)
|
||||
|
||||
def test_video_not_in_preferred_media_skips(self):
|
||||
metadata: LaunchboxMetadata = {
|
||||
"first_release_date": None,
|
||||
"images": [],
|
||||
"video_url": "launchbox-file://Videos/NES/Mario.mp4",
|
||||
}
|
||||
with patch(
|
||||
"handler.metadata.launchbox_handler.media.get_preferred_media_types"
|
||||
) as mock_preferred:
|
||||
mock_preferred.return_value = []
|
||||
populate_rom_specific_paths(metadata, self._rom())
|
||||
assert "video_path" not in metadata
|
||||
|
||||
|
||||
class TestRemoteMediaReq:
|
||||
def test_explicit_platform_name_wins(self):
|
||||
req = remote_media_req(
|
||||
remote={"Name": "Super Mario Bros.", "Platform": "Wii"},
|
||||
remote_images=None,
|
||||
remote_enabled=True,
|
||||
platform_name="Nintendo Entertainment System",
|
||||
fs_name="mario.nes",
|
||||
)
|
||||
assert req.platform_name == "Nintendo Entertainment System"
|
||||
assert req.fs_name == "mario.nes"
|
||||
assert req.title == "Super Mario Bros."
|
||||
|
||||
def test_falls_back_to_remote_platform(self):
|
||||
req = remote_media_req(
|
||||
remote={"Name": "H.E.R.O.", "Platform": "Atari 2600"},
|
||||
remote_images=None,
|
||||
remote_enabled=True,
|
||||
)
|
||||
assert req.platform_name == "Atari 2600"
|
||||
assert req.fs_name == ""
|
||||
assert req.title == "H.E.R.O."
|
||||
|
||||
def test_no_platform_available_is_none(self):
|
||||
req = remote_media_req(
|
||||
remote={"Name": "Some Game"},
|
||||
remote_images=None,
|
||||
remote_enabled=True,
|
||||
)
|
||||
assert req.platform_name is None
|
||||
|
||||
|
||||
class TestRemoteMatchLocalImages:
|
||||
"""Regression test for bug where remote-matched roms skipped local image lookup.
|
||||
|
||||
When a ROM matches only via the remote Metadata.xml (no local XML entry),
|
||||
the handler previously passed platform_name=None to remote_media_req, which
|
||||
caused _build_local_media_context to bail and never search on-disk images.
|
||||
"""
|
||||
|
||||
async def test_remote_match_finds_local_images(
|
||||
self, tmp_path: Path, monkeypatch
|
||||
) -> None:
|
||||
# Arrange: images on disk, no local XML match, remote returns a hit.
|
||||
# Use "Clear Logo" + "Box - Front" to exercise both _get_images and
|
||||
# _get_cover through the same remote-match path.
|
||||
lb_root = tmp_path / "launchbox"
|
||||
images_root = lb_root / "Images"
|
||||
logo_dir = images_root / "Atari 2600" / "Clear Logo"
|
||||
box_dir = images_root / "Atari 2600" / "Box - Front"
|
||||
logo_dir.mkdir(parents=True)
|
||||
box_dir.mkdir(parents=True)
|
||||
(logo_dir / "H.E.R.O-01.png").write_bytes(b"")
|
||||
(box_dir / "H.E.R.O-01.png").write_bytes(b"")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"handler.metadata.launchbox_handler.media.LAUNCHBOX_IMAGES_DIR",
|
||||
images_root,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"handler.metadata.launchbox_handler.utils.LAUNCHBOX_LOCAL_DIR",
|
||||
lb_root,
|
||||
)
|
||||
|
||||
h = LaunchboxHandler()
|
||||
h._local = MagicMock(spec=LocalSource)
|
||||
h._remote = MagicMock(spec=RemoteSource)
|
||||
h._local.get_rom = AsyncMock(return_value=None) # type: ignore[method-assign]
|
||||
h._remote.get_mame_entry = AsyncMock(return_value=None) # type: ignore[method-assign]
|
||||
h._remote.get_rom = AsyncMock( # type: ignore[method-assign]
|
||||
return_value={
|
||||
"DatabaseID": "42",
|
||||
"Name": "H.E.R.O.",
|
||||
"Platform": "Atari 2600",
|
||||
}
|
||||
)
|
||||
h._remote.fetch_images = AsyncMock(return_value=None) # type: ignore[method-assign]
|
||||
monkeypatch.setattr(LaunchboxHandler, "is_enabled", lambda *_: True)
|
||||
monkeypatch.setattr(async_cache, "exists", AsyncMock(return_value=True))
|
||||
|
||||
with patch(
|
||||
"handler.metadata.launchbox_handler.handler.fs_rom_handler"
|
||||
) as mock_fs:
|
||||
mock_fs.get_file_name_with_no_tags.return_value = "hero"
|
||||
result = await h.get_rom("hero.a26", "atari2600")
|
||||
|
||||
# Assert: both the clear logo and box-front cover resolved to
|
||||
# launchbox-file:// URLs, even though the local XML never matched.
|
||||
assert "launchbox_metadata" in result
|
||||
images = result["launchbox_metadata"]["images"]
|
||||
assert len(images) == 1
|
||||
assert "type" in images[0]
|
||||
assert "url" in images[0]
|
||||
assert images[0]["type"] == "Clear Logo"
|
||||
assert images[0]["url"] == (
|
||||
"launchbox-file://Images/Atari 2600/Clear Logo/H.E.R.O-01.png"
|
||||
)
|
||||
assert "url_cover" in result
|
||||
assert result["url_cover"] == (
|
||||
"launchbox-file://Images/Atari 2600/Box - Front/H.E.R.O-01.png"
|
||||
)
|
||||
|
||||
|
||||
class TestBuildRom:
|
||||
def test_name_from_local_title(self):
|
||||
local = {"Title": "Super Mario Bros.", "Notes": "Classic platformer"}
|
||||
@@ -739,6 +1058,7 @@ class TestLaunchboxHandlerGetRom:
|
||||
h._local.get_rom = AsyncMock(return_value=None) # type: ignore[method-assign]
|
||||
h._remote.get_rom = AsyncMock(return_value=None) # type: ignore[method-assign]
|
||||
h._remote.get_by_id = AsyncMock(return_value=None) # type: ignore[method-assign]
|
||||
h._remote.get_mame_entry = AsyncMock(return_value=None) # type: ignore[method-assign]
|
||||
h._remote.fetch_images = AsyncMock(return_value=None) # type: ignore[method-assign]
|
||||
monkeypatch.setattr(LaunchboxHandler, "is_enabled", lambda *_: True)
|
||||
monkeypatch.setattr(async_cache, "exists", AsyncMock(return_value=True))
|
||||
@@ -868,6 +1188,92 @@ class TestLaunchboxHandlerGetRom:
|
||||
# fs_rom_handler.get_file_name_with_no_tags should NOT be called
|
||||
mock_fs.get_file_name_with_no_tags.assert_not_called()
|
||||
|
||||
async def test_arcade_mame_resolves_shortname_to_full_title(
|
||||
self, handler: LaunchboxHandler
|
||||
):
|
||||
mame_entry = {"FileName": "wrlok_l3", "Name": "Warlok"}
|
||||
remote_entry = {"DatabaseID": "999", "Name": "Warlok"}
|
||||
with (
|
||||
patch.object(
|
||||
handler._remote,
|
||||
"get_mame_entry",
|
||||
new=AsyncMock(return_value=mame_entry),
|
||||
) as mock_mame,
|
||||
patch.object(
|
||||
handler._remote,
|
||||
"get_rom",
|
||||
new=AsyncMock(return_value=remote_entry),
|
||||
) as mock_get_rom,
|
||||
patch(
|
||||
"handler.metadata.launchbox_handler.handler.fs_rom_handler"
|
||||
) as mock_fs,
|
||||
):
|
||||
mock_fs.get_file_name_with_no_tags.return_value = "wrlok_l3"
|
||||
result = await handler.get_rom("wrlok_l3.zip", "arcade")
|
||||
|
||||
mock_mame.assert_called_once_with("wrlok_l3.zip")
|
||||
# Search term should be the MAME Name, lowercased.
|
||||
assert mock_get_rom.call_args.args[0] == "warlok"
|
||||
assert result.get("name", None) == "Warlok"
|
||||
assert result.get("launchbox_id", None) == 999
|
||||
|
||||
async def test_arcade_mame_miss_falls_back_to_filename_search(
|
||||
self, handler: LaunchboxHandler
|
||||
):
|
||||
with (
|
||||
patch.object(
|
||||
handler._remote,
|
||||
"get_mame_entry",
|
||||
new=AsyncMock(return_value=None),
|
||||
) as mock_mame,
|
||||
patch(
|
||||
"handler.metadata.launchbox_handler.handler.fs_rom_handler"
|
||||
) as mock_fs,
|
||||
):
|
||||
mock_fs.get_file_name_with_no_tags.return_value = "wrlok_l3"
|
||||
result = await handler.get_rom("wrlok_l3.zip", "arcade")
|
||||
|
||||
mock_mame.assert_called_once_with("wrlok_l3.zip")
|
||||
assert result["launchbox_id"] is None
|
||||
|
||||
async def test_arcade_mame_only_match_sets_fallback_name(
|
||||
self, handler: LaunchboxHandler
|
||||
):
|
||||
# MAME entry exists but Metadata.xml has no matching game: still surface
|
||||
# the MAME name as the rom name.
|
||||
mame_entry = {"FileName": "wrlok_l3", "Name": "Warlok"}
|
||||
with (
|
||||
patch.object(
|
||||
handler._remote,
|
||||
"get_mame_entry",
|
||||
new=AsyncMock(return_value=mame_entry),
|
||||
),
|
||||
patch(
|
||||
"handler.metadata.launchbox_handler.handler.fs_rom_handler"
|
||||
) as mock_fs,
|
||||
):
|
||||
mock_fs.get_file_name_with_no_tags.return_value = "wrlok_l3"
|
||||
result = await handler.get_rom("wrlok_l3.zip", "arcade")
|
||||
|
||||
assert result["launchbox_id"] is None
|
||||
assert result.get("name", None) == "Warlok"
|
||||
|
||||
async def test_non_arcade_platform_skips_mame_lookup(
|
||||
self, handler: LaunchboxHandler
|
||||
):
|
||||
with (
|
||||
patch.object(
|
||||
handler._remote, "get_mame_entry", new=AsyncMock()
|
||||
) as mock_mame,
|
||||
patch(
|
||||
"handler.metadata.launchbox_handler.handler.fs_rom_handler"
|
||||
) as mock_fs,
|
||||
):
|
||||
mock_fs.get_file_name_with_no_tags.return_value = "wrlok_l3"
|
||||
await handler.get_rom("wrlok_l3.zip", "nes")
|
||||
|
||||
mock_mame.assert_not_called()
|
||||
|
||||
|
||||
class TestLaunchboxHandlerGetRomById:
|
||||
@pytest.fixture
|
||||
@@ -923,6 +1329,7 @@ class TestLaunchboxHandlerSearch:
|
||||
h._local.get_rom = AsyncMock(return_value=None) # type: ignore[method-assign]
|
||||
h._remote.get_rom = AsyncMock(return_value=None) # type: ignore[method-assign]
|
||||
h._remote.get_by_id = AsyncMock(return_value=None) # type: ignore[method-assign]
|
||||
h._remote.get_mame_entry = AsyncMock(return_value=None) # type: ignore[method-assign]
|
||||
h._remote.fetch_images = AsyncMock(return_value=None) # type: ignore[method-assign]
|
||||
monkeypatch.setattr(LaunchboxHandler, "is_enabled", lambda *_: True)
|
||||
monkeypatch.setattr(async_cache, "exists", AsyncMock(return_value=True))
|
||||
|
||||
@@ -77,8 +77,8 @@ def test_platform_list_uses_ups_keys():
|
||||
|
||||
|
||||
def test_find_matching_art_exact_case_insensitive(handler: LibretroHandler):
|
||||
# The match should prefer the exact case-insensitive filename — region tag
|
||||
# included — so a PAL ROM lands on the (Europe) artwork.
|
||||
# The match should prefer the exact case-insensitive filename (region tag
|
||||
# included), so a PAL ROM lands on the (Europe) artwork.
|
||||
result = handler._find_matching_art(
|
||||
"Castlevania - Symphony of the Night (Europe).iso", PSX_LISTING
|
||||
)
|
||||
@@ -101,7 +101,7 @@ def test_find_matching_art_ampersand_normalized(handler: LibretroHandler):
|
||||
|
||||
|
||||
def test_find_matching_art_fuzzy_fallback(handler: LibretroHandler):
|
||||
# No exact match — ROM has an extra `(Rev 1)` tag that libretro doesn't
|
||||
# No exact match, since the ROM has an extra `(Rev 1)` tag that libretro doesn't
|
||||
# index. Fuzzy fallback strips tags from both sides; the Europe variant
|
||||
# is the first tag-stripped candidate and wins.
|
||||
result = handler._find_matching_art(
|
||||
@@ -289,5 +289,5 @@ def test_art_type_values():
|
||||
|
||||
|
||||
def test_is_enabled_always_true():
|
||||
# No API key required — public server.
|
||||
# No API key required; this is a public server.
|
||||
assert LibretroHandler.is_enabled() is True
|
||||
@@ -2,10 +2,17 @@
|
||||
|
||||
from typing import cast
|
||||
from unittest.mock import MagicMock, patch
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import pytest
|
||||
|
||||
from adapters.services.screenscraper_types import SSGame
|
||||
from config.config_manager import Config, MetadataMediaType
|
||||
from handler.metadata.ss_handler import (
|
||||
SSHandler,
|
||||
_get_rom_type,
|
||||
_is_notgame,
|
||||
add_ss_auth_to_url,
|
||||
extract_media_from_ss_game,
|
||||
get_preferred_regions,
|
||||
)
|
||||
@@ -65,14 +72,49 @@ class TestGetPreferredRegions:
|
||||
|
||||
assert len(regions) == len(set(regions))
|
||||
|
||||
def test_multi_region_rom_respects_user_priority(self):
|
||||
"""For a multi-region ROM, the user's priority order wins among the
|
||||
regions the file is tagged as."""
|
||||
rom = MagicMock()
|
||||
rom.regions = ["Japan", "USA"]
|
||||
config = _make_config(region_priority=["us", "eu"])
|
||||
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
||||
regions = get_preferred_regions(rom)
|
||||
|
||||
assert regions.index("us") < regions.index("jp")
|
||||
|
||||
def test_multi_region_rom_untagged_priority_does_not_win(self):
|
||||
"""A region in SCAN_REGION_PRIORITY that the file is NOT tagged as
|
||||
should not outrank a region the file IS tagged as."""
|
||||
rom = MagicMock()
|
||||
rom.regions = ["Japan", "USA"]
|
||||
config = _make_config(region_priority=["eu", "us"])
|
||||
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
||||
regions = get_preferred_regions(rom)
|
||||
|
||||
assert regions.index("us") < regions.index("eu")
|
||||
assert regions.index("jp") < regions.index("eu")
|
||||
|
||||
def test_multi_region_rom_unprioritized_tags_preserve_order(self):
|
||||
"""Filename regions not in the priority list keep their filename order
|
||||
and follow the prioritized ones."""
|
||||
rom = MagicMock()
|
||||
rom.regions = ["Japan", "Brazil"]
|
||||
config = _make_config(region_priority=["us"])
|
||||
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
||||
regions = get_preferred_regions(rom)
|
||||
|
||||
assert regions.index("jp") < regions.index("br")
|
||||
|
||||
|
||||
class TestExtractMediaFromSsGame:
|
||||
"""Tests for extract_media_from_ss_game."""
|
||||
|
||||
def _make_rom(self) -> MagicMock:
|
||||
def _make_rom(self, regions: list[str] | None = None) -> MagicMock:
|
||||
rom = MagicMock()
|
||||
rom.platform_id = 1
|
||||
rom.id = 100
|
||||
rom.regions = regions
|
||||
return rom
|
||||
|
||||
def _make_game_with_cus_only(self) -> SSGame:
|
||||
@@ -159,3 +201,323 @@ class TestExtractMediaFromSsGame:
|
||||
|
||||
assert result["box2d_url"] is not None
|
||||
assert "box-2D(us)" in result["box2d_url"]
|
||||
|
||||
|
||||
class TestIsNotgame:
|
||||
def _game(self, notgame: str = "false", names: list[str] | None = None) -> SSGame:
|
||||
return cast(
|
||||
SSGame,
|
||||
{
|
||||
"notgame": notgame,
|
||||
"noms": [
|
||||
{"region": "ss", "text": n} for n in (names or ["Clean Game"])
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
def test_notgame_field_true(self):
|
||||
assert _is_notgame(self._game(notgame="true")) is True
|
||||
|
||||
def test_notgame_field_false_clean_name(self):
|
||||
assert _is_notgame(self._game(notgame="false")) is False
|
||||
|
||||
def test_zzz_notgame_lowercase_name(self):
|
||||
assert _is_notgame(self._game(names=["ZZZ(notgame)"])) is True
|
||||
|
||||
def test_zzz_notgame_long_form(self):
|
||||
assert (
|
||||
_is_notgame(self._game(names=["ZZZ(NOTGAME):Fichier Annexes - Non Jeux"]))
|
||||
is True
|
||||
)
|
||||
|
||||
def test_zzz_prefix_only_no_match(self):
|
||||
assert _is_notgame(self._game(names=["ZZZ Game Title"])) is False
|
||||
|
||||
def test_missing_notgame_field_clean_name(self):
|
||||
game = cast(SSGame, {"noms": [{"region": "ss", "text": "Normal Game"}]})
|
||||
assert _is_notgame(game) is False
|
||||
|
||||
|
||||
class TestExtractMediaSensitiveKeyStripping:
|
||||
def test_media_url_credentials_stripped(self):
|
||||
config = _make_config()
|
||||
rom = MagicMock()
|
||||
rom.platform_id = 1
|
||||
rom.id = 100
|
||||
full_url = "https://screenscraper.fr/img.png?ssid=user&sspassword=pass&devid=dev&devpassword=devpass&other=keep"
|
||||
game = cast(
|
||||
SSGame,
|
||||
{
|
||||
"medias": [
|
||||
{
|
||||
"type": "box-2D",
|
||||
"parent": "jeu",
|
||||
"region": "us",
|
||||
"url": full_url,
|
||||
"crc": "",
|
||||
"md5": "",
|
||||
"sha1": "",
|
||||
"size": "0",
|
||||
"format": "png",
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
with (
|
||||
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
||||
patch(
|
||||
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
||||
return_value="roms/1/100/box2d",
|
||||
),
|
||||
):
|
||||
result = extract_media_from_ss_game(rom, game)
|
||||
|
||||
# ssid/sspassword must be stripped before storage so user creds don't
|
||||
# end up in the DB. Dev creds and other params must be preserved so
|
||||
# subsequent media fetches still resolve.
|
||||
stored_url = result["box2d_url"]
|
||||
assert stored_url is not None
|
||||
query = parse_qs(urlparse(stored_url).query)
|
||||
assert "ssid" not in query
|
||||
assert "sspassword" not in query
|
||||
assert query.get("devid") == ["dev"]
|
||||
assert query.get("devpassword") == ["devpass"]
|
||||
assert query.get("other") == ["keep"]
|
||||
|
||||
def test_clean_url_unchanged(self):
|
||||
config = _make_config()
|
||||
rom = MagicMock()
|
||||
rom.platform_id = 1
|
||||
rom.id = 100
|
||||
clean_url = "https://screenscraper.fr/img.png?format=png"
|
||||
game = cast(
|
||||
SSGame,
|
||||
{
|
||||
"medias": [
|
||||
{
|
||||
"type": "box-2D",
|
||||
"parent": "jeu",
|
||||
"region": "us",
|
||||
"url": clean_url,
|
||||
"crc": "",
|
||||
"md5": "",
|
||||
"sha1": "",
|
||||
"size": "0",
|
||||
"format": "png",
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
with (
|
||||
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
||||
patch(
|
||||
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
||||
return_value="roms/1/100/box2d",
|
||||
),
|
||||
):
|
||||
result = extract_media_from_ss_game(rom, game)
|
||||
|
||||
assert result["box2d_url"] == clean_url
|
||||
|
||||
|
||||
class TestAddSsAuthToUrl:
|
||||
"""Tests for add_ss_auth_to_url — re-attaches user creds at download time."""
|
||||
|
||||
def test_appends_credentials_when_configured(self):
|
||||
"""With both user and password set, creds are appended to the URL."""
|
||||
url = "https://screenscraper.fr/img.png?systemeid=1&romnom=Game.zip"
|
||||
with (
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
||||
):
|
||||
result = add_ss_auth_to_url(url)
|
||||
|
||||
query = parse_qs(urlparse(result).query)
|
||||
assert query.get("ssid") == ["user1"]
|
||||
assert query.get("sspassword") == ["pw1"]
|
||||
# Other params are preserved
|
||||
assert query.get("systemeid") == ["1"]
|
||||
assert query.get("romnom") == ["Game.zip"]
|
||||
|
||||
def test_no_op_when_user_missing(self):
|
||||
"""If SCREENSCRAPER_USER is unset, the URL is returned unchanged."""
|
||||
url = "https://screenscraper.fr/img.png?systemeid=1"
|
||||
with (
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", ""),
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
||||
):
|
||||
result = add_ss_auth_to_url(url)
|
||||
|
||||
assert result == url
|
||||
|
||||
def test_no_op_when_password_missing(self):
|
||||
"""If SCREENSCRAPER_PASSWORD is unset, the URL is returned unchanged."""
|
||||
url = "https://screenscraper.fr/img.png?systemeid=1"
|
||||
with (
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", ""),
|
||||
):
|
||||
result = add_ss_auth_to_url(url)
|
||||
|
||||
assert result == url
|
||||
|
||||
def test_does_not_duplicate_existing_credentials(self):
|
||||
"""Pre-existing ssid/sspassword on the URL are replaced, not duplicated."""
|
||||
url = "https://screenscraper.fr/img.png?ssid=old&sspassword=oldpw&keep=1"
|
||||
with (
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "new"),
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "newpw"),
|
||||
):
|
||||
result = add_ss_auth_to_url(url)
|
||||
|
||||
query = parse_qs(urlparse(result).query)
|
||||
# Exactly one occurrence of each, with the new values
|
||||
assert query.get("ssid") == ["new"]
|
||||
assert query.get("sspassword") == ["newpw"]
|
||||
assert query.get("keep") == ["1"]
|
||||
|
||||
def test_handles_stripped_url_from_extract_media(self):
|
||||
"""A URL that's already had ssid/sspassword stripped (the storage form)
|
||||
gets credentials re-attached cleanly, with dev creds and other params
|
||||
left intact."""
|
||||
# Shape mirrors what extract_media_from_ss_game persists
|
||||
stripped_url = (
|
||||
"https://screenscraper.fr/img.png?devid=dev&devpassword=devpw&other=keep"
|
||||
)
|
||||
with (
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
||||
):
|
||||
result = add_ss_auth_to_url(stripped_url)
|
||||
|
||||
query = parse_qs(urlparse(result).query)
|
||||
assert query.get("ssid") == ["user1"]
|
||||
assert query.get("sspassword") == ["pw1"]
|
||||
assert query.get("devid") == ["dev"]
|
||||
assert query.get("devpassword") == ["devpw"]
|
||||
assert query.get("other") == ["keep"]
|
||||
|
||||
def test_strip_then_reauth_roundtrip(self):
|
||||
"""End-to-end: storing media strips user creds; download-time auth
|
||||
restores them without leaking creds into intermediate state."""
|
||||
config = _make_config()
|
||||
rom = MagicMock()
|
||||
rom.platform_id = 1
|
||||
rom.id = 100
|
||||
original_url = (
|
||||
"https://screenscraper.fr/img.png"
|
||||
"?ssid=scanner-user&sspassword=scanner-pw&systemeid=1"
|
||||
)
|
||||
game = cast(
|
||||
SSGame,
|
||||
{
|
||||
"medias": [
|
||||
{
|
||||
"type": "box-2D",
|
||||
"parent": "jeu",
|
||||
"region": "us",
|
||||
"url": original_url,
|
||||
"crc": "",
|
||||
"md5": "",
|
||||
"sha1": "",
|
||||
"size": "0",
|
||||
"format": "png",
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
with (
|
||||
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
||||
patch(
|
||||
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
||||
return_value="roms/1/100/box2d",
|
||||
),
|
||||
):
|
||||
extracted = extract_media_from_ss_game(rom, game)
|
||||
|
||||
stored_url = extracted["box2d_url"]
|
||||
assert stored_url is not None
|
||||
|
||||
# Stored URL must not carry user creds
|
||||
stored_query = parse_qs(urlparse(stored_url).query)
|
||||
assert "ssid" not in stored_query
|
||||
assert "sspassword" not in stored_query
|
||||
|
||||
# At download time, add_ss_auth_to_url re-attaches the *current* creds
|
||||
with (
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "download-user"),
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "download-pw"),
|
||||
):
|
||||
download_url = add_ss_auth_to_url(stored_url)
|
||||
|
||||
download_query = parse_qs(urlparse(download_url).query)
|
||||
assert download_query.get("ssid") == ["download-user"]
|
||||
assert download_query.get("sspassword") == ["download-pw"]
|
||||
assert download_query.get("systemeid") == ["1"]
|
||||
|
||||
|
||||
class TestGetRomType:
|
||||
def _file(self, ext: str, top_level: bool = True) -> MagicMock:
|
||||
f = MagicMock()
|
||||
f.file_extension = ext
|
||||
f.is_top_level = top_level
|
||||
return f
|
||||
|
||||
def test_iso_extension(self):
|
||||
assert _get_rom_type(self._file("iso")) == "iso"
|
||||
|
||||
def test_chd_extension(self):
|
||||
assert _get_rom_type(self._file("chd")) == "iso"
|
||||
|
||||
def test_rom_extension(self):
|
||||
assert _get_rom_type(self._file("nes")) == "rom"
|
||||
|
||||
def test_folder_based_rom(self):
|
||||
assert _get_rom_type(self._file("bin", top_level=False)) == "dossier"
|
||||
|
||||
|
||||
class TestLookupRom:
|
||||
def _make_mock_file(self) -> MagicMock:
|
||||
f = MagicMock()
|
||||
f.file_size_bytes = 1024
|
||||
f.is_top_level = True
|
||||
f.file_extension = "bin"
|
||||
f.md5_hash = "abc123"
|
||||
f.sha1_hash = "def456"
|
||||
f.crc_hash = "12345678"
|
||||
f.file_name = "bios.bin"
|
||||
return f
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_notgame_flag_on_notgame_field(self):
|
||||
notgame_response = {
|
||||
"id": "999",
|
||||
"notgame": "true",
|
||||
"noms": [{"region": "wor", "text": "SomeBios"}],
|
||||
}
|
||||
handler = SSHandler()
|
||||
with patch.object(
|
||||
handler.ss_service, "get_game_info", return_value=notgame_response
|
||||
):
|
||||
result, is_not_game = await handler.lookup_rom(
|
||||
MagicMock(platform_slug="snes"), 3, [self._make_mock_file()]
|
||||
)
|
||||
assert result["ss_id"] is None
|
||||
assert is_not_game is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_notgame_flag_on_zzz_prefix(self):
|
||||
notgame_response = {
|
||||
"id": "0",
|
||||
"notgame": "false",
|
||||
"noms": [{"region": "wor", "text": "ZZZ(NOTGAME)SomeBios"}],
|
||||
}
|
||||
handler = SSHandler()
|
||||
with patch.object(
|
||||
handler.ss_service, "get_game_info", return_value=notgame_response
|
||||
):
|
||||
result, is_not_game = await handler.lookup_rom(
|
||||
MagicMock(platform_slug="snes"), 3, [self._make_mock_file()]
|
||||
)
|
||||
assert result["ss_id"] is None
|
||||
assert is_not_game is True
|
||||
@@ -1,6 +1,15 @@
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from handler.database import db_platform_handler
|
||||
from handler.database import db_platform_handler, db_rom_handler
|
||||
from handler.metadata import (
|
||||
meta_hasheous_handler,
|
||||
meta_playmatch_handler,
|
||||
meta_ra_handler,
|
||||
)
|
||||
from handler.metadata.hasheous_handler import HasheousRom
|
||||
from handler.metadata.ra_handler import RAGameRom
|
||||
from handler.scan_handler import MetadataSource, ScanType, scan_platform, scan_rom
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom, RomFile
|
||||
@@ -93,3 +102,210 @@ async def test_scan_rom():
|
||||
# assert rom.hasheous_id == 4872
|
||||
# assert rom.fs_size_bytes == 23175094
|
||||
# assert rom.tags == []
|
||||
|
||||
|
||||
@patch.object(meta_playmatch_handler, "is_enabled", return_value=False)
|
||||
@patch.object(meta_hasheous_handler, "get_ra_game", new_callable=AsyncMock)
|
||||
@patch.object(meta_hasheous_handler, "get_igdb_game", new_callable=AsyncMock)
|
||||
@patch.object(meta_hasheous_handler, "lookup_rom", new_callable=AsyncMock)
|
||||
async def test_scan_rom_complete_clears_unselected_metadata(
|
||||
mock_lookup, mock_get_igdb, mock_get_ra, mock_playmatch_enabled
|
||||
):
|
||||
"""COMPLETE rescan with newly_added=False must clear id and *_metadata
|
||||
fields for sources that are no longer in metadata_sources."""
|
||||
hasheous_result = HasheousRom(
|
||||
hasheous_id=999,
|
||||
igdb_id=None,
|
||||
tgdb_id=None,
|
||||
ra_id=None,
|
||||
name="Mock Hasheous Game",
|
||||
)
|
||||
mock_lookup.return_value = hasheous_result
|
||||
mock_get_igdb.return_value = hasheous_result
|
||||
mock_get_ra.return_value = hasheous_result
|
||||
|
||||
platform = Platform(
|
||||
id=1,
|
||||
slug="n64",
|
||||
fs_slug="n64",
|
||||
name="Nintendo 64",
|
||||
igdb_id=4,
|
||||
ra_id=2,
|
||||
hasheous_id=64,
|
||||
)
|
||||
platform = db_platform_handler.add_platform(platform)
|
||||
|
||||
rom = Rom(
|
||||
platform_id=platform.id,
|
||||
fs_name="Paper Mario (USA).z64",
|
||||
fs_name_no_tags="Paper Mario",
|
||||
fs_name_no_ext="Paper Mario",
|
||||
fs_extension="z64",
|
||||
fs_path="n64/Paper Mario (USA)",
|
||||
name="Paper Mario",
|
||||
igdb_id=3340,
|
||||
igdb_metadata={"summary": "stale IGDB metadata"},
|
||||
ra_id=1234,
|
||||
ra_metadata={"name": "stale RA metadata"},
|
||||
hasheous_id=4872,
|
||||
fs_size_bytes=1024,
|
||||
tags=[],
|
||||
)
|
||||
rom = db_rom_handler.add_rom(rom)
|
||||
|
||||
async with initialize_context():
|
||||
result = await scan_rom(
|
||||
platform=platform,
|
||||
scan_type=ScanType.COMPLETE,
|
||||
rom=rom,
|
||||
fs_rom={
|
||||
"fs_name": "Paper Mario (USA).z64",
|
||||
"flat": True,
|
||||
"nested": False,
|
||||
"files": [],
|
||||
"crc_hash": "",
|
||||
"md5_hash": "",
|
||||
"sha1_hash": "",
|
||||
"ra_hash": "",
|
||||
},
|
||||
metadata_sources=[MetadataSource.HASHEOUS],
|
||||
newly_added=False,
|
||||
)
|
||||
|
||||
# IGDB and RA were unselected — their id and metadata must be cleared.
|
||||
assert result.igdb_id is None
|
||||
assert result.igdb_metadata == {}
|
||||
assert result.ra_id is None
|
||||
assert result.ra_metadata == {}
|
||||
# Hasheous is still selected and should remain populated.
|
||||
assert result.hasheous_id == 999
|
||||
|
||||
|
||||
@patch.object(meta_playmatch_handler, "is_enabled", return_value=False)
|
||||
@patch.object(meta_ra_handler, "get_rom_by_id", new_callable=AsyncMock)
|
||||
@patch.object(meta_ra_handler, "get_rom", new_callable=AsyncMock)
|
||||
async def test_scan_rom_unmatched_fetches_ra_when_id_set_but_no_metadata(
|
||||
mock_get_rom, mock_get_rom_by_id, mock_playmatch_enabled
|
||||
):
|
||||
"""UNMATCHED scan must fetch RA metadata when ra_id is set manually but
|
||||
ra_metadata is empty (the user manually set the ID)."""
|
||||
ra_result = RAGameRom(
|
||||
ra_id=2774,
|
||||
name="Jak and Daxter: The Precursor's Legacy",
|
||||
url_cover="https://media.retroachievements.org/Images/jpg",
|
||||
)
|
||||
mock_get_rom_by_id.return_value = ra_result
|
||||
mock_get_rom.return_value = RAGameRom(ra_id=None)
|
||||
|
||||
platform = Platform(
|
||||
id=1,
|
||||
slug="ps2",
|
||||
fs_slug="ps2",
|
||||
name="PlayStation 2",
|
||||
igdb_id=8,
|
||||
ra_id=21,
|
||||
)
|
||||
platform = db_platform_handler.add_platform(platform)
|
||||
|
||||
# ROM has ra_id set manually but no ra_metadata (never fetched before)
|
||||
rom = Rom(
|
||||
platform_id=platform.id,
|
||||
fs_name="Jak and Daxter.chd",
|
||||
fs_name_no_tags="Jak and Daxter",
|
||||
fs_name_no_ext="Jak and Daxter",
|
||||
fs_extension="chd",
|
||||
fs_path="ps2",
|
||||
name="Jak and Daxter",
|
||||
ra_id=2774,
|
||||
ra_metadata={}, # empty - never fetched
|
||||
fs_size_bytes=1024,
|
||||
tags=[],
|
||||
)
|
||||
rom = db_rom_handler.add_rom(rom)
|
||||
|
||||
async with initialize_context():
|
||||
result = await scan_rom(
|
||||
platform=platform,
|
||||
scan_type=ScanType.UNMATCHED,
|
||||
rom=rom,
|
||||
fs_rom={
|
||||
"fs_name": "Jak and Daxter.chd",
|
||||
"flat": True,
|
||||
"nested": False,
|
||||
"files": [],
|
||||
"crc_hash": "",
|
||||
"md5_hash": "",
|
||||
"sha1_hash": "",
|
||||
"ra_hash": "",
|
||||
},
|
||||
metadata_sources=[MetadataSource.RA],
|
||||
newly_added=False,
|
||||
)
|
||||
|
||||
# ra_id was set manually - get_rom_by_id should be called, not get_rom
|
||||
mock_get_rom_by_id.assert_called_once()
|
||||
mock_get_rom.assert_not_called()
|
||||
assert result.ra_id == 2774
|
||||
|
||||
|
||||
@patch.object(meta_playmatch_handler, "is_enabled", return_value=False)
|
||||
@patch.object(meta_ra_handler, "get_rom_by_id", new_callable=AsyncMock)
|
||||
@patch.object(meta_ra_handler, "get_rom", new_callable=AsyncMock)
|
||||
async def test_scan_rom_unmatched_skips_ra_when_id_and_metadata_exist(
|
||||
mock_get_rom, mock_get_rom_by_id, mock_playmatch_enabled
|
||||
):
|
||||
"""UNMATCHED scan must NOT re-fetch RA metadata when both ra_id and
|
||||
ra_metadata are already populated."""
|
||||
mock_get_rom_by_id.return_value = RAGameRom(ra_id=None)
|
||||
mock_get_rom.return_value = RAGameRom(ra_id=None)
|
||||
|
||||
platform = Platform(
|
||||
id=1,
|
||||
slug="ps2",
|
||||
fs_slug="ps2",
|
||||
name="PlayStation 2",
|
||||
igdb_id=8,
|
||||
ra_id=21,
|
||||
)
|
||||
platform = db_platform_handler.add_platform(platform)
|
||||
|
||||
# ROM has both ra_id and ra_metadata populated
|
||||
rom = Rom(
|
||||
platform_id=platform.id,
|
||||
fs_name="Jak and Daxter.chd",
|
||||
fs_name_no_tags="Jak and Daxter",
|
||||
fs_name_no_ext="Jak and Daxter",
|
||||
fs_extension="chd",
|
||||
fs_path="ps2",
|
||||
name="Jak and Daxter",
|
||||
ra_id=2774,
|
||||
ra_metadata={"achievements_count": 60}, # already populated
|
||||
fs_size_bytes=1024,
|
||||
tags=[],
|
||||
)
|
||||
rom = db_rom_handler.add_rom(rom)
|
||||
|
||||
async with initialize_context():
|
||||
result = await scan_rom(
|
||||
platform=platform,
|
||||
scan_type=ScanType.UNMATCHED,
|
||||
rom=rom,
|
||||
fs_rom={
|
||||
"fs_name": "Jak and Daxter.chd",
|
||||
"flat": True,
|
||||
"nested": False,
|
||||
"files": [],
|
||||
"crc_hash": "",
|
||||
"md5_hash": "",
|
||||
"sha1_hash": "",
|
||||
"ra_hash": "",
|
||||
},
|
||||
metadata_sources=[MetadataSource.RA],
|
||||
newly_added=False,
|
||||
)
|
||||
|
||||
# Both ID and metadata exist - should not re-fetch
|
||||
mock_get_rom_by_id.assert_not_called()
|
||||
mock_get_rom.assert_not_called()
|
||||
# Existing ra_id should be preserved
|
||||
assert result.ra_id == 2774
|
||||
@@ -4,3 +4,10 @@ from models.rom import Rom
|
||||
def test_rom(rom: Rom):
|
||||
assert rom.fs_path == "test_platform_slug/roms"
|
||||
assert rom.full_path == "test_platform_slug/roms/test_rom.zip"
|
||||
|
||||
|
||||
def test_rom_with_libretro_match_is_identified(rom: Rom):
|
||||
rom.libretro_id = "abc123"
|
||||
|
||||
assert rom.is_unidentified is False
|
||||
assert rom.is_identified is True
|
||||
@@ -0,0 +1,86 @@
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from tasks.scheduled.cleanup_upload_tmp import CleanupUploadTmpTask
|
||||
|
||||
|
||||
class TestCleanupUploadTmpTask:
|
||||
@pytest.fixture
|
||||
def task(self):
|
||||
return CleanupUploadTmpTask()
|
||||
|
||||
def test_init(self, task):
|
||||
"""Test task initialization"""
|
||||
assert (
|
||||
task.func
|
||||
== "tasks.scheduled.cleanup_upload_tmp.cleanup_upload_tmp_task.run"
|
||||
)
|
||||
assert task.enabled is True
|
||||
assert task.cron_string == "0 * * * *"
|
||||
|
||||
async def test_run_no_tmp_dir(self, task, monkeypatch, tmp_path):
|
||||
"""Task is a no-op when the uploads tmp directory does not exist."""
|
||||
import tasks.scheduled.cleanup_upload_tmp as mod
|
||||
|
||||
monkeypatch.setattr(mod, "ROM_UPLOAD_TMP_BASE", tmp_path / "nonexistent")
|
||||
# Should complete without error
|
||||
await task.run()
|
||||
|
||||
async def test_run_removes_expired_dirs(self, task, monkeypatch, tmp_path):
|
||||
"""Directories whose mtime is older than ROM_UPLOAD_TTL should be removed."""
|
||||
import tasks.scheduled.cleanup_upload_tmp as mod
|
||||
|
||||
uploads = tmp_path / "uploads"
|
||||
uploads.mkdir()
|
||||
monkeypatch.setattr(mod, "ROM_UPLOAD_TMP_BASE", uploads)
|
||||
monkeypatch.setattr(mod, "ROM_UPLOAD_TTL", 3600)
|
||||
|
||||
old_dir = uploads / "old-upload"
|
||||
old_dir.mkdir()
|
||||
# Backdate mtime to 2 hours ago
|
||||
old_ts = time.time() - 7200
|
||||
import os
|
||||
|
||||
os.utime(old_dir, (old_ts, old_ts))
|
||||
|
||||
await task.run()
|
||||
|
||||
assert not old_dir.exists()
|
||||
|
||||
async def test_run_keeps_recent_dirs(self, task, monkeypatch, tmp_path):
|
||||
"""Directories whose mtime is within ROM_UPLOAD_TTL should be kept."""
|
||||
import tasks.scheduled.cleanup_upload_tmp as mod
|
||||
|
||||
uploads = tmp_path / "uploads"
|
||||
uploads.mkdir()
|
||||
monkeypatch.setattr(mod, "ROM_UPLOAD_TMP_BASE", uploads)
|
||||
monkeypatch.setattr(mod, "ROM_UPLOAD_TTL", 3600)
|
||||
|
||||
recent_dir = uploads / "recent-upload"
|
||||
recent_dir.mkdir()
|
||||
# mtime is now (within TTL)
|
||||
|
||||
await task.run()
|
||||
|
||||
assert recent_dir.exists()
|
||||
|
||||
async def test_run_skips_files(self, task, monkeypatch, tmp_path):
|
||||
"""Files (not directories) in the uploads root are left untouched."""
|
||||
import tasks.scheduled.cleanup_upload_tmp as mod
|
||||
|
||||
uploads = tmp_path / "uploads"
|
||||
uploads.mkdir()
|
||||
monkeypatch.setattr(mod, "ROM_UPLOAD_TMP_BASE", uploads)
|
||||
monkeypatch.setattr(mod, "ROM_UPLOAD_TTL", 3600)
|
||||
|
||||
stale_file = uploads / "stale.tmp"
|
||||
stale_file.write_bytes(b"data")
|
||||
old_ts = time.time() - 7200
|
||||
import os
|
||||
|
||||
os.utime(stale_file, (old_ts, old_ts))
|
||||
|
||||
await task.run()
|
||||
|
||||
assert stale_file.exists()
|
||||
@@ -23,7 +23,7 @@ class TestExtractDeviceAndPlatform:
|
||||
@pytest.fixture(autouse=True)
|
||||
def patch_base_path(self, handler: FSSyncHandler, temp_dir):
|
||||
handler.base_path = Path(temp_dir)
|
||||
with patch("sync_watcher.fs_sync_handler", handler):
|
||||
with patch("sync_watcher.get_fs_sync_handler", return_value=handler):
|
||||
yield
|
||||
|
||||
def test_extract_valid_incoming_path(self, temp_dir):
|
||||
@@ -77,7 +77,7 @@ class TestEnsureConflictsDir:
|
||||
@pytest.fixture(autouse=True)
|
||||
def patch_base_path(self, handler: FSSyncHandler, temp_dir):
|
||||
handler.base_path = Path(temp_dir)
|
||||
with patch("sync_watcher.fs_sync_handler", handler):
|
||||
with patch("sync_watcher.get_fs_sync_handler", return_value=handler):
|
||||
yield
|
||||
|
||||
def test_creates_directory_and_returns_path(self, temp_dir):
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Tests for utils.filesystem helpers."""
|
||||
|
||||
import errno
|
||||
import os
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from utils.filesystem import link_or_copy_file
|
||||
|
||||
|
||||
class TestLinkOrCopyFile:
|
||||
"""Test the hardlink-with-copy-fallback helper used by importers and exporters."""
|
||||
|
||||
def test_same_filesystem_creates_hardlink(self, tmp_path):
|
||||
"""When source and dest are on the same filesystem, the helper creates a
|
||||
hardlink — source and dest share an inode and st_nlink reflects both."""
|
||||
source = tmp_path / "source.bin"
|
||||
source.write_bytes(b"payload")
|
||||
dest = tmp_path / "dest.bin"
|
||||
|
||||
link_or_copy_file(source, dest)
|
||||
|
||||
assert dest.read_bytes() == b"payload"
|
||||
# Hardlink: shared inode, link count >= 2
|
||||
assert source.stat().st_ino == dest.stat().st_ino
|
||||
assert source.stat().st_nlink >= 2
|
||||
|
||||
def test_falls_back_to_copy_on_exdev(self, tmp_path):
|
||||
"""When os.link raises EXDEV (cross-device), the helper falls back to
|
||||
shutil.copy2 — content matches but inodes differ."""
|
||||
source = tmp_path / "source.bin"
|
||||
source.write_bytes(b"payload")
|
||||
dest = tmp_path / "dest.bin"
|
||||
|
||||
exdev = OSError(errno.EXDEV, "Cross-device link")
|
||||
|
||||
with patch("utils.filesystem.os.link", side_effect=exdev):
|
||||
link_or_copy_file(source, dest)
|
||||
|
||||
assert dest.read_bytes() == b"payload"
|
||||
# Real copy: separate inodes
|
||||
assert source.stat().st_ino != dest.stat().st_ino
|
||||
|
||||
def test_falls_back_to_copy_on_eperm(self, tmp_path):
|
||||
"""EPERM (filesystem doesn't permit hardlinks, e.g. FAT32) must also
|
||||
trigger the copy fallback."""
|
||||
source = tmp_path / "source.bin"
|
||||
source.write_bytes(b"payload")
|
||||
dest = tmp_path / "dest.bin"
|
||||
|
||||
eperm = OSError(errno.EPERM, "Operation not permitted")
|
||||
|
||||
with patch("utils.filesystem.os.link", side_effect=eperm):
|
||||
link_or_copy_file(source, dest)
|
||||
|
||||
assert dest.read_bytes() == b"payload"
|
||||
assert source.stat().st_ino != dest.stat().st_ino
|
||||
|
||||
def test_reraises_non_fallback_oserror(self, tmp_path):
|
||||
"""An OSError that isn't in the fallback set (e.g. ENOSPC — disk full)
|
||||
must propagate; we don't want to mask real disk errors."""
|
||||
source = tmp_path / "source.bin"
|
||||
source.write_bytes(b"payload")
|
||||
dest = tmp_path / "dest.bin"
|
||||
|
||||
enospc = OSError(errno.ENOSPC, "No space left on device")
|
||||
|
||||
with patch("utils.filesystem.os.link", side_effect=enospc):
|
||||
with pytest.raises(OSError) as excinfo:
|
||||
link_or_copy_file(source, dest)
|
||||
|
||||
assert excinfo.value.errno == errno.ENOSPC
|
||||
assert not dest.exists()
|
||||
|
||||
def test_mutation_after_link_affects_source(self, tmp_path):
|
||||
"""Document hardlink semantics: writing through the dest path with
|
||||
O_TRUNC truncates the shared inode and therefore mutates the source.
|
||||
This is why callers that mutate dest in place (e.g. PIL resize) must
|
||||
not opt into hardlinking — copy_file defaults to allow_link=False to
|
||||
keep this hazard from being the easy path."""
|
||||
source = tmp_path / "source.bin"
|
||||
source.write_bytes(b"original")
|
||||
dest = tmp_path / "dest.bin"
|
||||
|
||||
link_or_copy_file(source, dest)
|
||||
|
||||
# Truncating-write through dest affects source (same inode).
|
||||
with open(dest, "wb") as f:
|
||||
f.write(b"mutated")
|
||||
|
||||
assert source.read_bytes() == b"mutated"
|
||||
|
||||
def test_mutation_after_copy_does_not_affect_source(self, tmp_path):
|
||||
"""When the helper falls back to copy, the inodes are independent —
|
||||
mutation through dest leaves the source untouched."""
|
||||
source = tmp_path / "source.bin"
|
||||
source.write_bytes(b"original")
|
||||
dest = tmp_path / "dest.bin"
|
||||
|
||||
with patch(
|
||||
"utils.filesystem.os.link",
|
||||
side_effect=OSError(errno.EXDEV, "Cross-device link"),
|
||||
):
|
||||
link_or_copy_file(source, dest)
|
||||
|
||||
with open(dest, "wb") as f:
|
||||
f.write(b"mutated")
|
||||
|
||||
assert source.read_bytes() == b"original"
|
||||
|
||||
def test_dest_already_exists_is_overwritten(self, tmp_path):
|
||||
"""When dest already exists, link_or_copy_file atomically replaces it.
|
||||
This mirrors shutil.copy2's overwrite-on-exists semantics so callers
|
||||
re-fetching a resource don't have to pre-unlink to avoid EEXIST."""
|
||||
source = tmp_path / "source.bin"
|
||||
source.write_bytes(b"new payload")
|
||||
dest = tmp_path / "dest.bin"
|
||||
dest.write_bytes(b"old payload")
|
||||
|
||||
link_or_copy_file(source, dest)
|
||||
|
||||
assert dest.read_bytes() == b"new payload"
|
||||
# Same-fs: dest is now a hardlink to source.
|
||||
assert source.stat().st_ino == dest.stat().st_ino
|
||||
|
||||
def test_dest_already_exists_is_overwritten_on_copy_fallback(self, tmp_path):
|
||||
"""Overwrite semantics also hold when the link fails and we fall back
|
||||
to copy — replace happens after the tempfile is populated either way."""
|
||||
source = tmp_path / "source.bin"
|
||||
source.write_bytes(b"new payload")
|
||||
dest = tmp_path / "dest.bin"
|
||||
dest.write_bytes(b"old payload")
|
||||
|
||||
with patch(
|
||||
"utils.filesystem.os.link",
|
||||
side_effect=OSError(errno.EXDEV, "Cross-device link"),
|
||||
):
|
||||
link_or_copy_file(source, dest)
|
||||
|
||||
assert dest.read_bytes() == b"new payload"
|
||||
# Fell back to copy: separate inodes.
|
||||
assert source.stat().st_ino != dest.stat().st_ino
|
||||
|
||||
def test_tempfile_cleaned_up_on_failure(self, tmp_path):
|
||||
"""If linking and the copy fallback both fail (e.g. ENOSPC), the helper
|
||||
must not leave a stray tempfile behind in dest's directory."""
|
||||
source = tmp_path / "source.bin"
|
||||
source.write_bytes(b"payload")
|
||||
dest = tmp_path / "dest.bin"
|
||||
|
||||
enospc = OSError(errno.ENOSPC, "No space left on device")
|
||||
|
||||
with patch("utils.filesystem.os.link", side_effect=enospc):
|
||||
with pytest.raises(OSError) as excinfo:
|
||||
link_or_copy_file(source, dest)
|
||||
|
||||
assert excinfo.value.errno == errno.ENOSPC
|
||||
assert not dest.exists()
|
||||
# No leftover .romm_link_tmp_* file in the directory.
|
||||
leftovers = [
|
||||
p for p in tmp_path.iterdir() if p.name.startswith(".romm_link_tmp_")
|
||||
]
|
||||
assert leftovers == []
|
||||
|
||||
def test_helper_uses_os_link_first(self, tmp_path):
|
||||
"""Sanity-check that the helper calls os.link before any copy logic —
|
||||
guards against a future refactor regressing to copy-only. The second
|
||||
arg is a tempfile in dest's parent (not dest itself), since we
|
||||
link-then-replace for atomic overwrite."""
|
||||
source = tmp_path / "source.bin"
|
||||
source.write_bytes(b"payload")
|
||||
dest = tmp_path / "dest.bin"
|
||||
|
||||
with patch("utils.filesystem.os.link", wraps=os.link) as link_spy:
|
||||
link_or_copy_file(source, dest)
|
||||
|
||||
link_spy.assert_called_once()
|
||||
args = link_spy.call_args.args
|
||||
assert args[0] == source
|
||||
assert args[1].parent == dest.parent
|
||||
assert args[1].name.startswith(".romm_link_tmp_")
|
||||
@@ -1,8 +1,11 @@
|
||||
from os.path import isabs
|
||||
from xml.etree.ElementTree import fromstring
|
||||
|
||||
import pytest
|
||||
|
||||
from config import FRONTEND_RESOURCES_PATH
|
||||
from handler.database import db_platform_handler, db_rom_handler
|
||||
from handler.filesystem import fs_platform_handler, fs_resource_handler
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom
|
||||
from models.user import User
|
||||
@@ -40,7 +43,14 @@ def platform_with_roms(admin_user: User):
|
||||
"companies": ["Nintendo", "Nintendo EAD"],
|
||||
"first_release_date": 709257600, # 1992-06-23 UTC in seconds; view *1000
|
||||
"total_rating": 92.0, # view uses this directly as a 0-100 igdb_rating
|
||||
}
|
||||
},
|
||||
"path_cover_l": "snes/covers/super-mario-world.jpg",
|
||||
"path_manual": "snes/manuals/super-mario-world.pdf",
|
||||
"path_screenshots": ["snes/screenshots/super-mario-world-1.jpg"],
|
||||
"gamelist_metadata": {
|
||||
"player_count": "2",
|
||||
"video_path": "snes/videos/super-mario-world.mp4", # feeds rom.path_video property
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
@@ -211,3 +221,193 @@ def test_export_gamelist_xml_scrap_element(platform_with_roms):
|
||||
scrap = game.find("scrap")
|
||||
assert scrap is not None
|
||||
assert scrap.get("name") == "RomM"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tag", ["thumbnail", "image", "video", "screenshot", "manual"])
|
||||
def test_export_gamelist_xml_local_media_relative_path(platform_with_roms, tag):
|
||||
platform, _ = platform_with_roms
|
||||
exporter = GamelistExporter(local_export=True)
|
||||
xml_str = exporter.export_platform_to_xml(platform.id, request=None)
|
||||
root = fromstring(xml_str)
|
||||
game = root.findall("game")[0]
|
||||
|
||||
elem = game.find(tag)
|
||||
assert elem is not None
|
||||
assert elem.text is not None
|
||||
assert not isabs(elem.text)
|
||||
|
||||
|
||||
def test_export_gamelist_xml_local_ss_metadata_media_relative(platform_with_roms):
|
||||
platform, roms = platform_with_roms
|
||||
|
||||
db_rom_handler.update_rom(
|
||||
roms[0].id,
|
||||
{
|
||||
"ss_metadata": {
|
||||
"box3d_path": "snes-ss/box3d/test.png",
|
||||
"box2d_back_path": "snes-ss/boxback/test.png",
|
||||
"fanart_path": "snes-ss/fanart/test.png",
|
||||
"logo_path": "snes-ss/logo/test.png",
|
||||
"miximage_path": "snes-ss/miximage/test.png",
|
||||
"physical_path": "snes-ss/physical/test.png",
|
||||
"title_screen_path": "snes-ss/titlescreen/test.png",
|
||||
"bezel_path": "snes-ss/bezel/test.png",
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
exporter = GamelistExporter(local_export=True)
|
||||
xml_str = exporter.export_platform_to_xml(platform.id, request=None)
|
||||
root = fromstring(xml_str)
|
||||
game = root.findall("game")[0]
|
||||
|
||||
media_tags = [
|
||||
"box3d",
|
||||
"boxback",
|
||||
"fanart",
|
||||
"marquee",
|
||||
"miximage",
|
||||
"physicalmedia",
|
||||
"title_screen",
|
||||
"bezel",
|
||||
]
|
||||
for tag in media_tags:
|
||||
elem = game.find(tag)
|
||||
assert elem is not None and elem.text is not None
|
||||
|
||||
assert not isabs(elem.text)
|
||||
|
||||
|
||||
def test_export_gamelist_xml_local_no_absolute_paths_anywhere(platform_with_roms):
|
||||
"""Catch-all: when local_export=True, no element text should contain
|
||||
the FRONTEND_RESOURCES_PATH absolute prefix."""
|
||||
platform, _ = platform_with_roms
|
||||
|
||||
exporter = GamelistExporter(local_export=True)
|
||||
xml_str = exporter.export_platform_to_xml(platform.id, request=None)
|
||||
root = fromstring(xml_str)
|
||||
|
||||
for elem in root.iter():
|
||||
if elem.text and FRONTEND_RESOURCES_PATH in elem.text:
|
||||
pytest.fail(
|
||||
f"<{elem.tag}> contains absolute FRONTEND_RESOURCES_PATH: {elem.text}"
|
||||
)
|
||||
|
||||
|
||||
def test_export_gamelist_xml_rejects_path_traversal(platform_with_roms):
|
||||
"""Paths with traversal segments must not escape the resources directory."""
|
||||
platform, roms = platform_with_roms
|
||||
|
||||
db_rom_handler.update_rom(roms[0].id, {"path_cover_l": "../../etc/passwd"})
|
||||
|
||||
exporter = GamelistExporter(local_export=True)
|
||||
with pytest.raises(ValueError, match="invalid parent directory references"):
|
||||
exporter.export_platform_to_xml(platform.id, request=None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def isolated_filesystem(tmp_path, monkeypatch):
|
||||
"""Redirect resource and library base paths to a temp directory so that
|
||||
export_platform_to_file() can copy real assets and write gamelist.xml
|
||||
without touching the host filesystem."""
|
||||
resources_base = tmp_path / "resources"
|
||||
library_base = tmp_path / "library"
|
||||
monkeypatch.setattr(fs_resource_handler, "base_path", resources_base)
|
||||
monkeypatch.setattr(fs_platform_handler, "base_path", library_base)
|
||||
return resources_base, library_base
|
||||
|
||||
|
||||
async def test_export_platform_to_file_copies_assets(
|
||||
platform_with_roms, isolated_filesystem
|
||||
):
|
||||
"""export_platform_to_file copies each media file into <platform>/assets/<subdir>/
|
||||
and writes gamelist.xml referencing those relative paths."""
|
||||
resources_base, library_base = isolated_filesystem
|
||||
platform, _ = platform_with_roms
|
||||
|
||||
sources = {
|
||||
"snes/covers/super-mario-world.jpg": b"cover-bytes",
|
||||
"snes/screenshots/super-mario-world-1.jpg": b"shot-bytes",
|
||||
"snes/manuals/super-mario-world.pdf": b"manual-bytes",
|
||||
"snes/videos/super-mario-world.mp4": b"video-bytes",
|
||||
}
|
||||
for rel, content in sources.items():
|
||||
src = resources_base / rel
|
||||
src.parent.mkdir(parents=True, exist_ok=True)
|
||||
src.write_bytes(content)
|
||||
|
||||
exporter = GamelistExporter(local_export=True)
|
||||
assert await exporter.export_platform_to_file(platform.id, request=None) is True
|
||||
|
||||
platform_dir = library_base / fs_platform_handler.get_platform_fs_structure(
|
||||
platform.fs_slug
|
||||
)
|
||||
|
||||
expected_assets = {
|
||||
"assets/covers/Super Mario World (USA).jpg": b"cover-bytes",
|
||||
"assets/screenshots/Super Mario World (USA).jpg": b"shot-bytes",
|
||||
"assets/manuals/Super Mario World (USA).pdf": b"manual-bytes",
|
||||
"assets/videos/Super Mario World (USA).mp4": b"video-bytes",
|
||||
}
|
||||
for rel, content in expected_assets.items():
|
||||
dest = platform_dir / rel
|
||||
assert dest.is_file(), f"missing asset {dest}"
|
||||
assert dest.read_bytes() == content
|
||||
|
||||
gamelist = platform_dir / "gamelist.xml"
|
||||
assert gamelist.is_file()
|
||||
game = fromstring(gamelist.read_text()).findall("game")[0]
|
||||
|
||||
expected_refs = {
|
||||
"thumbnail": "./assets/covers/Super Mario World (USA).jpg",
|
||||
"screenshot": "./assets/screenshots/Super Mario World (USA).jpg",
|
||||
"video": "./assets/videos/Super Mario World (USA).mp4",
|
||||
"manual": "./assets/manuals/Super Mario World (USA).pdf",
|
||||
}
|
||||
for tag, expected in expected_refs.items():
|
||||
elem = game.find(tag)
|
||||
assert elem is not None and elem.text == expected
|
||||
|
||||
|
||||
async def test_export_platform_to_file_omits_tags_when_copy_fails(
|
||||
platform_with_roms, isolated_filesystem
|
||||
):
|
||||
"""When a source resource is missing, _copy_asset returns False; the
|
||||
corresponding tag must be omitted from gamelist.xml and no asset file
|
||||
must be written for it. Other assets still export normally."""
|
||||
resources_base, library_base = isolated_filesystem
|
||||
platform, _ = platform_with_roms
|
||||
|
||||
# Provide cover and screenshot, deliberately omit manual + video sources.
|
||||
for rel in (
|
||||
"snes/covers/super-mario-world.jpg",
|
||||
"snes/screenshots/super-mario-world-1.jpg",
|
||||
):
|
||||
src = resources_base / rel
|
||||
src.parent.mkdir(parents=True, exist_ok=True)
|
||||
src.write_bytes(b"X")
|
||||
|
||||
exporter = GamelistExporter(local_export=True)
|
||||
assert await exporter.export_platform_to_file(platform.id, request=None) is True
|
||||
|
||||
platform_dir = library_base / fs_platform_handler.get_platform_fs_structure(
|
||||
platform.fs_slug
|
||||
)
|
||||
|
||||
# Successful copies present
|
||||
assert (platform_dir / "assets/covers/Super Mario World (USA).jpg").is_file()
|
||||
assert (platform_dir / "assets/screenshots/Super Mario World (USA).jpg").is_file()
|
||||
# Failed copies don't produce destination files (an empty subdir may be
|
||||
# left behind because _copy_asset mkdirs before opening the source).
|
||||
assert not (platform_dir / "assets/manuals/Super Mario World (USA).pdf").exists()
|
||||
assert not (platform_dir / "assets/videos/Super Mario World (USA).mp4").exists()
|
||||
|
||||
game = fromstring((platform_dir / "gamelist.xml").read_text()).findall("game")[0]
|
||||
assert game.find("manual") is None
|
||||
assert game.find("video") is None
|
||||
thumbnail = game.find("thumbnail")
|
||||
assert thumbnail is not None
|
||||
assert thumbnail.text == "./assets/covers/Super Mario World (USA).jpg"
|
||||
screenshot = game.find("screenshot")
|
||||
assert screenshot is not None
|
||||
assert screenshot.text == "./assets/screenshots/Super Mario World (USA).jpg"
|
||||
@@ -1,5 +1,7 @@
|
||||
import errno
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
@@ -37,6 +39,54 @@ def iter_directories(path: str, recursive: bool = False) -> Iterator[tuple[Path,
|
||||
break
|
||||
|
||||
|
||||
# errno values that mean "hardlink not possible here, fall back to copy".
|
||||
# EXDEV: cross-device link. EPERM: filesystem doesn't permit/support hardlinks
|
||||
# (e.g. FAT32, exFAT, some network mounts). EOPNOTSUPP/ENOTSUP: same, on BSD/macOS.
|
||||
# EMLINK: source already has the maximum number of hardlinks for the filesystem.
|
||||
_LINK_FALLBACK_ERRNOS: frozenset[int] = frozenset(
|
||||
e
|
||||
for e in (
|
||||
getattr(errno, "EXDEV", None),
|
||||
getattr(errno, "EPERM", None),
|
||||
getattr(errno, "EOPNOTSUPP", None),
|
||||
getattr(errno, "ENOTSUP", None),
|
||||
getattr(errno, "EMLINK", None),
|
||||
getattr(errno, "EACCES", None),
|
||||
)
|
||||
if e is not None
|
||||
)
|
||||
|
||||
|
||||
def link_or_copy_file(source: Path, dest: Path) -> None:
|
||||
"""Place ``source`` at ``dest`` via hardlink (preferred) or copy (fallback),
|
||||
atomically replacing ``dest`` if it already exists. Caller is responsible
|
||||
for creating ``dest.parent``.
|
||||
|
||||
Hardlinking is preferred because it's instantaneous and uses no extra disk
|
||||
space, but only works within a single filesystem. If linking isn't possible,
|
||||
we transparently fall back to ``shutil.copy2`` (preserving metadata).
|
||||
|
||||
Overwriting is atomic: we link/copy to a tempfile in dest's directory, then
|
||||
rename it onto dest, which mirrors shutil.copy2's overwrite-on-exists
|
||||
behavior.
|
||||
"""
|
||||
tmp_path = dest.parent / f".romm_link_tmp_{os.urandom(8).hex()}"
|
||||
try:
|
||||
try:
|
||||
os.link(source, tmp_path)
|
||||
except OSError as exc:
|
||||
if exc.errno not in _LINK_FALLBACK_ERRNOS:
|
||||
raise
|
||||
shutil.copy2(source, tmp_path)
|
||||
os.replace(tmp_path, dest)
|
||||
except BaseException:
|
||||
try:
|
||||
os.unlink(tmp_path)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
INVALID_CHARS_HYPHENS = re.compile(r"[\\/:|]")
|
||||
INVALID_CHARS_EMPTY = re.compile(r'[*?"<>+]')
|
||||
|
||||
|
||||
+206
-164
@@ -1,4 +1,5 @@
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from xml.etree.ElementTree import ( # trunk-ignore(bandit/B405)
|
||||
Element,
|
||||
SubElement,
|
||||
@@ -7,13 +8,31 @@ from xml.etree.ElementTree import ( # trunk-ignore(bandit/B405)
|
||||
)
|
||||
|
||||
from fastapi import Request
|
||||
from starlette.datastructures import URLPath
|
||||
|
||||
from config import FRONTEND_RESOURCES_PATH, YOUTUBE_BASE_URL
|
||||
from config.config_manager import config_manager as cm
|
||||
from handler.database import db_platform_handler, db_rom_handler
|
||||
from handler.filesystem import fs_platform_handler
|
||||
from handler.filesystem import fs_platform_handler, fs_resource_handler
|
||||
from logger.logger import log
|
||||
from models.rom import Rom
|
||||
from utils.filesystem import link_or_copy_file
|
||||
|
||||
# Map gamelist asset keys to subdirectory names inside assets/
|
||||
ASSET_DIRS: dict[str, str] = {
|
||||
"box2d": "covers",
|
||||
"box3d": "boxes",
|
||||
"box2d_back": "backcovers",
|
||||
"fanart": "fanart",
|
||||
"marquee": "marquees",
|
||||
"miximage": "miximages",
|
||||
"physical": "physical",
|
||||
"screenshot": "screenshots",
|
||||
"title_screen": "titlescreens",
|
||||
"bezel": "bezels",
|
||||
"video": "videos",
|
||||
"manual": "manuals",
|
||||
}
|
||||
|
||||
|
||||
def get_media_options_for_export() -> tuple[str, str]:
|
||||
@@ -35,8 +54,123 @@ class GamelistExporter:
|
||||
"%Y%m%dT%H%M%S"
|
||||
)
|
||||
|
||||
def _collect_assets(self, rom: Rom) -> dict[str, Path]:
|
||||
"""Collect available media assets for a ROM.
|
||||
|
||||
Returns a dict mapping gamelist asset key to the absolute source file path.
|
||||
"""
|
||||
assets: dict[str, Path] = {}
|
||||
|
||||
if rom.path_cover_l:
|
||||
assets["box2d"] = fs_resource_handler.validate_path(rom.path_cover_l)
|
||||
|
||||
if rom.path_screenshots:
|
||||
assets["screenshot"] = fs_resource_handler.validate_path(
|
||||
rom.path_screenshots[0]
|
||||
)
|
||||
|
||||
if rom.path_video:
|
||||
assets["video"] = fs_resource_handler.validate_path(rom.path_video)
|
||||
|
||||
if rom.path_manual:
|
||||
assets["manual"] = fs_resource_handler.validate_path(rom.path_manual)
|
||||
|
||||
ss = rom.ss_metadata or {}
|
||||
gl = rom.gamelist_metadata or {}
|
||||
|
||||
# Each gamelist asset key may be sourced from screenscraper or gamelist
|
||||
# metadata; preference order is screenscraper first, gamelist second.
|
||||
extended: dict[str, list[str]] = {
|
||||
"box3d": [ss.get("box3d_path", ""), gl.get("box3d_path", "")],
|
||||
"box2d_back": [
|
||||
ss.get("box2d_back_path", ""),
|
||||
gl.get("box2d_back_path", ""),
|
||||
],
|
||||
"fanart": [ss.get("fanart_path", ""), gl.get("fanart_path", "")],
|
||||
"marquee": [ss.get("logo_path", ""), gl.get("marquee_path", "")],
|
||||
"miximage": [ss.get("miximage_path", ""), gl.get("miximage_path", "")],
|
||||
"physical": [ss.get("physical_path", ""), gl.get("physical_path", "")],
|
||||
"title_screen": [
|
||||
ss.get("title_screen_path", ""),
|
||||
gl.get("title_screen_path", ""),
|
||||
],
|
||||
"bezel": [ss.get("bezel_path", "")],
|
||||
}
|
||||
|
||||
for asset_key, candidates in extended.items():
|
||||
for candidate in candidates:
|
||||
if candidate:
|
||||
assets[asset_key] = fs_resource_handler.validate_path(candidate)
|
||||
break
|
||||
|
||||
return assets
|
||||
|
||||
def _build_asset_refs(
|
||||
self,
|
||||
rom: Rom,
|
||||
request: Request | None,
|
||||
assets: dict[str, Path],
|
||||
platform_dir: Path | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""Build the asset references that will appear in gamelist.xml.
|
||||
|
||||
For local exports, returns relative paths like ``assets/covers/<rom>.jpg``
|
||||
and, if ``platform_dir`` is provided, copies the source files into place.
|
||||
|
||||
For non-local exports, returns absolute URLs built from ``request.base_url``.
|
||||
"""
|
||||
refs: dict[str, str] = {}
|
||||
|
||||
if self.local_export:
|
||||
for asset_key, source_path in assets.items():
|
||||
subdir = ASSET_DIRS.get(asset_key, asset_key)
|
||||
dest_name = f"{rom.fs_name_no_ext}{source_path.suffix}"
|
||||
rel_path = f"./assets/{subdir}/{dest_name}"
|
||||
|
||||
if platform_dir is not None:
|
||||
dest_path = platform_dir / rel_path
|
||||
if not self._copy_asset(source_path, dest_path):
|
||||
continue
|
||||
|
||||
refs[asset_key] = rel_path
|
||||
return refs
|
||||
|
||||
if request is None:
|
||||
raise ValueError("Request object must be provided for non-local exports")
|
||||
|
||||
for asset_key, source_path in assets.items():
|
||||
resource_part = source_path.relative_to(
|
||||
Path(fs_resource_handler.base_path).resolve()
|
||||
)
|
||||
refs[asset_key] = str(
|
||||
URLPath(
|
||||
f"{FRONTEND_RESOURCES_PATH}/{resource_part.as_posix()}"
|
||||
).make_absolute_url(request.base_url)
|
||||
)
|
||||
|
||||
return refs
|
||||
|
||||
def _copy_asset(self, source: Path, dest: Path) -> bool:
|
||||
"""Place ``source`` at ``dest`` via hardlink (same filesystem) or copy
|
||||
(otherwise). Returns True on success."""
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
if dest.exists():
|
||||
return True
|
||||
|
||||
try:
|
||||
link_or_copy_file(source, dest)
|
||||
return True
|
||||
except OSError as e:
|
||||
log.warning(f"Failed to copy {source} -> {dest}: {e}")
|
||||
return False
|
||||
|
||||
def _create_game_element(
|
||||
self, rom: Rom, request: Request | None, media_image: str, media_thumbnail: str
|
||||
self,
|
||||
rom: Rom,
|
||||
request: Request | None,
|
||||
asset_refs: dict[str, str],
|
||||
media_image: str,
|
||||
media_thumbnail: str,
|
||||
) -> Element:
|
||||
"""Create a <game> element for a ROM"""
|
||||
game = Element("game")
|
||||
@@ -62,85 +196,28 @@ class GamelistExporter:
|
||||
if rom.summary:
|
||||
SubElement(game, "desc").text = rom.summary
|
||||
|
||||
# Media files
|
||||
thumbnail_path: str | None = None
|
||||
match media_thumbnail:
|
||||
case "box3d":
|
||||
if rom.ss_metadata and rom.ss_metadata.get("box3d_path"):
|
||||
thumbnail_path = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.ss_metadata['box3d_path']}"
|
||||
)
|
||||
elif rom.gamelist_metadata and rom.gamelist_metadata.get("box3d_path"):
|
||||
thumbnail_path = f"{FRONTEND_RESOURCES_PATH}/{rom.gamelist_metadata['box3d_path']}"
|
||||
case "miximage":
|
||||
if rom.ss_metadata and rom.ss_metadata.get("miximage_path"):
|
||||
thumbnail_path = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.ss_metadata['miximage_path']}"
|
||||
)
|
||||
elif rom.gamelist_metadata and rom.gamelist_metadata.get(
|
||||
"miximage_path"
|
||||
):
|
||||
thumbnail_path = f"{FRONTEND_RESOURCES_PATH}/{rom.gamelist_metadata['miximage_path']}"
|
||||
case "physical":
|
||||
if rom.ss_metadata and rom.ss_metadata.get("physical_path"):
|
||||
thumbnail_path = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.ss_metadata['physical_path']}"
|
||||
)
|
||||
elif rom.gamelist_metadata and rom.gamelist_metadata.get(
|
||||
"physical_path"
|
||||
):
|
||||
thumbnail_path = f"{FRONTEND_RESOURCES_PATH}/{rom.gamelist_metadata['physical_path']}"
|
||||
# Thumbnail: prefer media_thumbnail option, fall back to box2d (cover)
|
||||
thumbnail = asset_refs.get(media_thumbnail) or asset_refs.get("box2d")
|
||||
if thumbnail:
|
||||
SubElement(game, "thumbnail").text = thumbnail
|
||||
|
||||
# "cover" and "box2d" both map to path_cover_l
|
||||
if thumbnail_path is None and rom.path_cover_l:
|
||||
thumbnail_path = f"{FRONTEND_RESOURCES_PATH}/{rom.path_cover_l}"
|
||||
if thumbnail_path:
|
||||
SubElement(game, "thumbnail").text = thumbnail_path
|
||||
|
||||
if path_video := rom.path_video:
|
||||
SubElement(game, "video").text = f"{FRONTEND_RESOURCES_PATH}/{path_video}"
|
||||
if "video" in asset_refs:
|
||||
SubElement(game, "video").text = asset_refs["video"]
|
||||
elif rom.youtube_video_id:
|
||||
SubElement(game, "video").text = (
|
||||
f"{YOUTUBE_BASE_URL}/embed/{rom.youtube_video_id}"
|
||||
)
|
||||
|
||||
if rom.path_screenshots:
|
||||
SubElement(game, "screenshot").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.path_screenshots[0]}"
|
||||
)
|
||||
if "screenshot" in asset_refs:
|
||||
SubElement(game, "screenshot").text = asset_refs["screenshot"]
|
||||
|
||||
image_path: str | None = None
|
||||
match media_image:
|
||||
case "title_screen":
|
||||
if rom.ss_metadata and rom.ss_metadata.get("title_screen_path"):
|
||||
image_path = f"{FRONTEND_RESOURCES_PATH}/{rom.ss_metadata['title_screen_path']}"
|
||||
elif rom.gamelist_metadata and rom.gamelist_metadata.get(
|
||||
"title_screen_path"
|
||||
):
|
||||
image_path = f"{FRONTEND_RESOURCES_PATH}/{rom.gamelist_metadata['title_screen_path']}"
|
||||
case "miximage":
|
||||
if rom.ss_metadata and rom.ss_metadata.get("miximage_path"):
|
||||
image_path = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.ss_metadata['miximage_path']}"
|
||||
)
|
||||
elif rom.gamelist_metadata and rom.gamelist_metadata.get(
|
||||
"miximage_path"
|
||||
):
|
||||
image_path = f"{FRONTEND_RESOURCES_PATH}/{rom.gamelist_metadata['miximage_path']}"
|
||||
case "box2d":
|
||||
if rom.path_cover_l:
|
||||
image_path = f"{FRONTEND_RESOURCES_PATH}/{rom.path_cover_l}"
|
||||
# Image: prefer media_image option, fall back to screenshot
|
||||
image = asset_refs.get(media_image) or asset_refs.get("screenshot")
|
||||
if image:
|
||||
SubElement(game, "image").text = image
|
||||
|
||||
# "screenshot" (default) and anything else falls through to path_screenshots
|
||||
if image_path is None and rom.path_screenshots:
|
||||
image_path = f"{FRONTEND_RESOURCES_PATH}/{rom.path_screenshots[0]}"
|
||||
if image_path:
|
||||
SubElement(game, "image").text = image_path
|
||||
|
||||
if rom.path_manual:
|
||||
SubElement(game, "manual").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.path_manual}"
|
||||
)
|
||||
if "manual" in asset_refs:
|
||||
SubElement(game, "manual").text = asset_refs["manual"]
|
||||
|
||||
# Additional metadata
|
||||
if rom.metadatum.companies and len(rom.metadatum.companies) > 0:
|
||||
@@ -178,70 +255,20 @@ class GamelistExporter:
|
||||
if rom.gamelist_id:
|
||||
SubElement(game, "id").text = str(rom.gamelist_id)
|
||||
|
||||
# Provider specific metadata
|
||||
if rom.ss_metadata:
|
||||
if rom.ss_metadata.get("box3d_path"):
|
||||
SubElement(game, "box3d").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.ss_metadata['box3d_path']}"
|
||||
)
|
||||
if rom.ss_metadata.get("box2d_back_path"):
|
||||
SubElement(game, "boxback").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.ss_metadata['box2d_back_path']}"
|
||||
)
|
||||
if rom.ss_metadata.get("fanart_path"):
|
||||
SubElement(game, "fanart").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.ss_metadata['fanart_path']}"
|
||||
)
|
||||
if rom.ss_metadata.get("logo_path"):
|
||||
SubElement(game, "marquee").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.ss_metadata['logo_path']}"
|
||||
)
|
||||
if rom.ss_metadata.get("miximage_path"):
|
||||
SubElement(game, "miximage").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.ss_metadata['miximage_path']}"
|
||||
)
|
||||
if rom.ss_metadata.get("physical_path"):
|
||||
SubElement(game, "physicalmedia").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.ss_metadata['physical_path']}"
|
||||
)
|
||||
if rom.ss_metadata.get("title_screen_path"):
|
||||
SubElement(game, "title_screen").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.ss_metadata['title_screen_path']}"
|
||||
)
|
||||
if rom.ss_metadata.get("bezel_path"):
|
||||
SubElement(game, "bezel").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.ss_metadata['bezel_path']}"
|
||||
)
|
||||
|
||||
if rom.gamelist_metadata:
|
||||
if rom.gamelist_metadata.get("box3d_path"):
|
||||
SubElement(game, "box3d").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.gamelist_metadata['box3d_path']}"
|
||||
)
|
||||
if rom.gamelist_metadata.get("box2d_back_path"):
|
||||
SubElement(game, "boxback").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.gamelist_metadata['box2d_back_path']}"
|
||||
)
|
||||
if rom.gamelist_metadata.get("fanart_path"):
|
||||
SubElement(game, "fanart").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.gamelist_metadata['fanart_path']}"
|
||||
)
|
||||
if rom.gamelist_metadata.get("marquee_path"):
|
||||
SubElement(game, "marquee").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.gamelist_metadata['marquee_path']}"
|
||||
)
|
||||
if rom.gamelist_metadata.get("miximage_path"):
|
||||
SubElement(game, "miximage").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.gamelist_metadata['miximage_path']}"
|
||||
)
|
||||
if rom.gamelist_metadata.get("physical_path"):
|
||||
SubElement(game, "physicalmedia").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.gamelist_metadata['physical_path']}"
|
||||
)
|
||||
if rom.gamelist_metadata.get("title_screen_path"):
|
||||
SubElement(game, "title_screen").text = (
|
||||
f"{FRONTEND_RESOURCES_PATH}/{rom.gamelist_metadata['title_screen_path']}"
|
||||
)
|
||||
# Dedicated asset elements
|
||||
element_names: dict[str, str] = {
|
||||
"box3d": "box3d",
|
||||
"box2d_back": "boxback",
|
||||
"fanart": "fanart",
|
||||
"marquee": "marquee",
|
||||
"miximage": "miximage",
|
||||
"physical": "physicalmedia",
|
||||
"title_screen": "title_screen",
|
||||
"bezel": "bezel",
|
||||
}
|
||||
for asset_key, tag in element_names.items():
|
||||
if asset_key in asset_refs:
|
||||
SubElement(game, tag).text = asset_refs[asset_key]
|
||||
|
||||
# Add scraping info
|
||||
scrap = SubElement(game, "scrap")
|
||||
@@ -250,41 +277,52 @@ class GamelistExporter:
|
||||
|
||||
return game
|
||||
|
||||
def export_platform_to_xml(self, platform_id: int, request: Request | None) -> str:
|
||||
"""Export a platform's ROMs to gamelist.xml format
|
||||
|
||||
Args:
|
||||
platform_id: Platform ID to export
|
||||
|
||||
Returns:
|
||||
XML string in gamelist.xml format
|
||||
"""
|
||||
def _build_gamelist_xml(
|
||||
self,
|
||||
platform_id: int,
|
||||
request: Request | None,
|
||||
platform_dir: Path | None,
|
||||
) -> tuple[str, int]:
|
||||
"""Build gamelist XML, optionally copying assets into ``platform_dir/assets/``."""
|
||||
platform = db_platform_handler.get_platform(platform_id)
|
||||
if not platform:
|
||||
raise ValueError(f"Platform with ID {platform_id} not found")
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(platform_ids=[platform_id])
|
||||
|
||||
# Create root element
|
||||
root = Element("gameList")
|
||||
|
||||
media_image, media_thumbnail = get_media_options_for_export()
|
||||
|
||||
count = 0
|
||||
for rom in roms:
|
||||
if rom and not rom.missing_from_fs and rom.fs_name != "gamelist.xml":
|
||||
game_element = self._create_game_element(
|
||||
rom,
|
||||
request=request,
|
||||
media_image=media_image,
|
||||
media_thumbnail=media_thumbnail,
|
||||
)
|
||||
root.append(game_element)
|
||||
if not rom or rom.missing_from_fs or rom.fs_name == "gamelist.xml":
|
||||
continue
|
||||
|
||||
assets = self._collect_assets(rom)
|
||||
asset_refs = self._build_asset_refs(
|
||||
rom, request=request, assets=assets, platform_dir=platform_dir
|
||||
)
|
||||
|
||||
game_element = self._create_game_element(
|
||||
rom,
|
||||
request=request,
|
||||
asset_refs=asset_refs,
|
||||
media_image=media_image,
|
||||
media_thumbnail=media_thumbnail,
|
||||
)
|
||||
root.append(game_element)
|
||||
count += 1
|
||||
|
||||
# Convert to XML string
|
||||
indent(root, space=" ", level=0)
|
||||
xml_str = tostring(root, encoding="unicode", xml_declaration=True)
|
||||
log.info(f"Exported {count} ROMs for platform {platform.name}")
|
||||
return xml_str, count
|
||||
|
||||
log.info(f"Exported {len(roms)} ROMs for platform {platform.name}")
|
||||
def export_platform_to_xml(self, platform_id: int, request: Request | None) -> str:
|
||||
"""Export a platform's ROMs to gamelist.xml format (no asset files copied)."""
|
||||
xml_str, _ = self._build_gamelist_xml(
|
||||
platform_id, request=request, platform_dir=None
|
||||
)
|
||||
return xml_str
|
||||
|
||||
async def export_platform_to_file(
|
||||
@@ -292,11 +330,8 @@ class GamelistExporter:
|
||||
platform_id: int,
|
||||
request: Request | None,
|
||||
) -> bool:
|
||||
"""Export platform ROMs to gamelist.xml file in the platform's directory
|
||||
|
||||
Args:
|
||||
platform_id: Platform ID to export
|
||||
request: FastAPI request object for URL generation
|
||||
"""Export platform ROMs to gamelist.xml in the platform's directory,
|
||||
copying media assets into a local assets/ folder when local_export=True.
|
||||
|
||||
Returns:
|
||||
True if successful, False otherwise
|
||||
@@ -310,8 +345,15 @@ class GamelistExporter:
|
||||
platform_fs_structure = fs_platform_handler.get_platform_fs_structure(
|
||||
platform.fs_slug
|
||||
)
|
||||
platform_dir = (
|
||||
fs_platform_handler.base_path / platform_fs_structure
|
||||
if self.local_export
|
||||
else None
|
||||
)
|
||||
|
||||
xml_content = self.export_platform_to_xml(platform_id, request=request)
|
||||
xml_content, _ = self._build_gamelist_xml(
|
||||
platform_id, request=request, platform_dir=platform_dir
|
||||
)
|
||||
await fs_platform_handler.write_file(
|
||||
xml_content.encode("utf-8"), platform_fs_structure, "gamelist.xml"
|
||||
)
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import shutil
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
@@ -8,6 +7,7 @@ from handler.database import db_platform_handler, db_rom_handler
|
||||
from handler.filesystem import fs_platform_handler, fs_resource_handler
|
||||
from logger.logger import log
|
||||
from models.rom import Rom
|
||||
from utils.filesystem import link_or_copy_file
|
||||
|
||||
# Map Pegasus asset keys to subdirectory names inside assets/
|
||||
ASSET_DIRS: dict[str, str] = {
|
||||
@@ -177,14 +177,14 @@ class PegasusExporter:
|
||||
return "\n".join(lines)
|
||||
|
||||
def _copy_asset(self, source: Path, dest: Path) -> bool:
|
||||
"""Copy a file from source to dest using raw read/write. Returns True on success."""
|
||||
"""Place ``source`` at ``dest`` via hardlink (same filesystem) or copy
|
||||
(otherwise). Returns True on success."""
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
if dest.exists():
|
||||
return True
|
||||
|
||||
try:
|
||||
with open(source, "rb") as src, open(dest, "wb") as dst:
|
||||
shutil.copyfileobj(src, dst)
|
||||
link_or_copy_file(source, dest)
|
||||
return True
|
||||
except OSError as e:
|
||||
log.warning(f"Failed to copy {source} -> {dest}: {e}")
|
||||
|
||||
+7
-6
@@ -30,6 +30,7 @@ from handler.metadata import (
|
||||
meta_launchbox_handler,
|
||||
meta_libretro_handler,
|
||||
meta_moby_handler,
|
||||
meta_playmatch_handler,
|
||||
meta_ra_handler,
|
||||
meta_sgdb_handler,
|
||||
meta_ss_handler,
|
||||
@@ -49,8 +50,6 @@ sentry_sdk.init(
|
||||
)
|
||||
tracer = trace.get_tracer(__name__)
|
||||
|
||||
structure_level = 2 if os.path.exists(cm.get_config().HIGH_PRIO_STRUCTURE_PATH) else 1
|
||||
|
||||
|
||||
@enum.unique
|
||||
class EventType(enum.StrEnum):
|
||||
@@ -122,11 +121,12 @@ def process_changes(changes: Sequence[Change]) -> None:
|
||||
# Filter for valid events, applying the same exclusion rules as the scanner:
|
||||
# exact-match and fnmatch patterns for files, plus excluded directory names
|
||||
# checked against every path component so events inside excluded dirs are ignored.
|
||||
config = cm.get_config()
|
||||
cnfg = cm.get_config()
|
||||
structure_level = 1 if cnfg.has_structure_path_b else 2
|
||||
excluded_patterns = (
|
||||
config.EXCLUDED_SINGLE_FILES
|
||||
+ config.EXCLUDED_MULTI_FILES
|
||||
+ config.EXCLUDED_MULTI_PARTS_FILES
|
||||
cnfg.EXCLUDED_SINGLE_FILES
|
||||
+ cnfg.EXCLUDED_MULTI_FILES
|
||||
+ cnfg.EXCLUDED_MULTI_PARTS_FILES
|
||||
)
|
||||
|
||||
def _is_excluded(path: str) -> bool:
|
||||
@@ -182,6 +182,7 @@ def process_changes(changes: Sequence[Change]) -> None:
|
||||
MetadataSource.RA: meta_ra_handler.is_enabled(),
|
||||
MetadataSource.LAUNCHBOX: meta_launchbox_handler.is_enabled(),
|
||||
MetadataSource.HASHEOUS: meta_hasheous_handler.is_enabled(),
|
||||
MetadataSource.PLAYMATCH: meta_playmatch_handler.is_enabled(),
|
||||
MetadataSource.SGDB: meta_sgdb_handler.is_enabled(),
|
||||
MetadataSource.FLASHPOINT: meta_flashpoint_handler.is_enabled(),
|
||||
MetadataSource.HLTB: meta_hltb_handler.is_enabled(),
|
||||
|
||||
+1
-1
@@ -219,7 +219,7 @@ ENV PYTHONUNBUFFERED=1
|
||||
ENV PYTHONPATH=/backend
|
||||
|
||||
# Declare the supported volumes
|
||||
VOLUME ["/romm/resources", "/romm/library", "/romm/assets", "/romm/config", "/redis-data"]
|
||||
VOLUME ["/romm/resources", "/romm/library", "/romm/assets", "/romm/config", "/romm/sync", "/redis-data"]
|
||||
|
||||
# Expose non-privileged ports
|
||||
EXPOSE 8080 6379/tcp
|
||||
|
||||
+44
-36
@@ -62,11 +62,26 @@ error_log() {
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Populate a caller-provided array with the opentelemetry-instrument wrapper
|
||||
# argv tokens for service "$2", or leave it empty if OTEL is disabled or the
|
||||
# wrapper binary is missing. Use "${arr[@]}" to exec directly, or
|
||||
# "${arr[*]@Q}" to embed as a shell-quoted prefix string.
|
||||
otel_prefix() {
|
||||
local -n out_arr="$1"
|
||||
if [[ ${OTEL_SDK_DISABLED:-false} == "true" ]]; then return 0; fi
|
||||
if ! command -v opentelemetry-instrument >/dev/null 2>&1; then
|
||||
warn_log "opentelemetry-instrument not found, starting $2 without OpenTelemetry instrumentation"
|
||||
return 0
|
||||
fi
|
||||
# shellcheck disable=SC2034 # nameref binds out_arr to caller variable
|
||||
out_arr=(opentelemetry-instrument --service_name "${OTEL_SERVICE_NAME_PREFIX-}$2")
|
||||
}
|
||||
|
||||
# Commands to run initial startup tasks
|
||||
run_startup() {
|
||||
if ! PYTHONPATH="/backend:${PYTHONPATH-}" opentelemetry-instrument \
|
||||
--service_name "${OTEL_SERVICE_NAME_PREFIX-}startup" \
|
||||
python3 /backend/startup.py; then
|
||||
local -a wrap=()
|
||||
otel_prefix wrap startup
|
||||
if ! PYTHONPATH="/backend:${PYTHONPATH-}" "${wrap[@]}" python3 /backend/startup.py; then
|
||||
error_log "Startup script failed, exiting"
|
||||
fi
|
||||
}
|
||||
@@ -88,14 +103,18 @@ wait_for_gunicorn_socket() {
|
||||
fi
|
||||
}
|
||||
|
||||
# function that runs or main process and creates a corresponding PID file,
|
||||
# Runs our main process and creates a corresponding PID file
|
||||
start_bin_gunicorn() {
|
||||
# cleanup potentially leftover socket
|
||||
rm /tmp/gunicorn.sock -f
|
||||
|
||||
# Wire LOGLEVEL into Gunicorn's logging config so it respects the env var
|
||||
# Wire LOGLEVEL into Gunicorn's logging config so it respects the env var.
|
||||
local gunicorn_level="${LOGLEVEL^^}"
|
||||
sed -i '/\[logger_gunicorn\]/,/^\[/ s/^level=.*/level='"${gunicorn_level}"'/' /etc/gunicorn/logging.conf
|
||||
local gunicorn_log_config="/tmp/gunicorn/logging.conf"
|
||||
# Copy the config to a writable runtime path so this works on read-only root filesystems.
|
||||
mkdir -p /tmp/gunicorn
|
||||
cp /etc/gunicorn/logging.conf "${gunicorn_log_config}"
|
||||
sed -i '/\[logger_gunicorn\]/,/^\[/ s/^level=.*/level='"${gunicorn_level}"'/' "${gunicorn_log_config}"
|
||||
|
||||
# commands to start our main application and store its PID to check for crashes
|
||||
info_log "Starting backend"
|
||||
@@ -103,9 +122,9 @@ start_bin_gunicorn() {
|
||||
export PYTHONUNBUFFERED=1
|
||||
export PYTHONDONTWRITEBYTECODE=1
|
||||
|
||||
opentelemetry-instrument \
|
||||
--service_name "${OTEL_SERVICE_NAME_PREFIX-}api" \
|
||||
gunicorn \
|
||||
local -a wrap=()
|
||||
otel_prefix wrap api
|
||||
"${wrap[@]}" gunicorn \
|
||||
--bind=0.0.0.0:"${DEV_PORT:-5000}" \
|
||||
--bind=unix:/tmp/gunicorn.sock \
|
||||
--pid=/tmp/gunicorn.pid \
|
||||
@@ -118,7 +137,7 @@ start_bin_gunicorn() {
|
||||
--max-requests-jitter "${WEB_SERVER_MAX_REQUESTS_JITTER:-100}" \
|
||||
--worker-connections "${WEB_SERVER_WORKER_CONNECTIONS:-1000}" \
|
||||
--error-logfile - \
|
||||
--log-config /etc/gunicorn/logging.conf \
|
||||
--log-config "${gunicorn_log_config}" \
|
||||
main:app &
|
||||
}
|
||||
|
||||
@@ -196,8 +215,7 @@ start_bin_rq_scheduler() {
|
||||
RQ_REDIS_SSL=${REDIS_SSL:-0} \
|
||||
rqscheduler \
|
||||
--path /backend \
|
||||
--pid /tmp/rq_scheduler.pid \
|
||||
--logging_level "${LOGLEVEL}" &
|
||||
--pid /tmp/rq_scheduler.pid &
|
||||
}
|
||||
|
||||
# Commands to start RQ worker
|
||||
@@ -226,36 +244,26 @@ start_bin_rq_worker() {
|
||||
|
||||
start_bin_watcher() {
|
||||
info_log "Starting watcher"
|
||||
if [[ ${OTEL_SDK_DISABLED:-false} == "true" ]]; then
|
||||
# Skip opentelemetry-instrument when OTEL is disabled to ensure
|
||||
# WATCHFILES_CHANGES env var is properly passed to watcher.py
|
||||
watchfiles \
|
||||
--target-type command \
|
||||
"python3 watcher.py" \
|
||||
/romm/library &
|
||||
else
|
||||
watchfiles \
|
||||
--target-type command \
|
||||
"opentelemetry-instrument --service_name '${OTEL_SERVICE_NAME_PREFIX-}watcher' python3 watcher.py" \
|
||||
/romm/library &
|
||||
fi
|
||||
local -a wrap=()
|
||||
otel_prefix wrap watcher
|
||||
watchfiles \
|
||||
--target-type command \
|
||||
"${wrap[*]@Q} python3 watcher.py" \
|
||||
/romm/library &
|
||||
WATCHER_PID=$!
|
||||
echo "${WATCHER_PID}" >/tmp/watcher.pid
|
||||
}
|
||||
|
||||
start_bin_sync_watcher() {
|
||||
info_log "Starting sync folder watcher"
|
||||
if [[ ${OTEL_SDK_DISABLED:-false} == "true" ]]; then
|
||||
watchfiles \
|
||||
--target-type command \
|
||||
"python3 sync_watcher.py" \
|
||||
/romm/sync &
|
||||
else
|
||||
watchfiles \
|
||||
--target-type command \
|
||||
"opentelemetry-instrument --service_name '${OTEL_SERVICE_NAME_PREFIX-}sync_watcher' python3 sync_watcher.py" \
|
||||
/romm/sync &
|
||||
fi
|
||||
sync_base_path="${ROMM_BASE_PATH:-/romm}/sync"
|
||||
mkdir -p "${sync_base_path}"
|
||||
local -a wrap=()
|
||||
otel_prefix wrap sync_watcher
|
||||
watchfiles \
|
||||
--target-type command \
|
||||
"${wrap[*]@Q} python3 sync_watcher.py" \
|
||||
"${sync_base_path}" &
|
||||
SYNC_WATCHER_PID=$!
|
||||
echo "${SYNC_WATCHER_PID}" >/tmp/sync_watcher.pid
|
||||
}
|
||||
|
||||
@@ -43,13 +43,13 @@ Comprehensive documentation of the RomM backend: a FastAPI-based server powering
|
||||
|
||||
RomM's backend is responsible for:
|
||||
|
||||
- **Library scanning** — detecting platforms and ROMs from the filesystem
|
||||
- **Metadata enrichment** — pulling game info from 10+ external providers
|
||||
- **User management** — roles, authentication, per-user game tracking
|
||||
- **Asset management** — saves, save states, screenshots, firmware/BIOS
|
||||
- **Device sync** — cross-device save synchronization
|
||||
- **Netplay** — real-time multiplayer room coordination
|
||||
- **Feed generation** — Tinfoil, WebRcade, PKGi, and other custom formats
|
||||
- **Library scanning**: detecting platforms and ROMs from the filesystem
|
||||
- **Metadata enrichment**: pulling game info from 10+ external providers
|
||||
- **User management**: roles, authentication, per-user game tracking
|
||||
- **Asset management**: saves, save states, screenshots, firmware/BIOS
|
||||
- **Device sync**: cross-device save synchronization
|
||||
- **Netplay**: real-time multiplayer room coordination
|
||||
- **Feed generation**: Tinfoil, WebRcade, PKGi, and other custom formats
|
||||
|
||||
---
|
||||
|
||||
@@ -378,13 +378,13 @@ Request → CORS → CSRF → Authentication → Session (Redis) → Context Va
|
||||
Response ← CORS ← CSRF ← Authentication ← Session (Redis) ← Context Vars ← Endpoint
|
||||
```
|
||||
|
||||
| Layer | Middleware | Purpose |
|
||||
| ----- | -------------------------- | -------------------------------------------------- |
|
||||
| 1 | `CORSMiddleware` | Allow cross-origin requests (all origins) |
|
||||
| 2 | `CSRFMiddleware` | Token-based CSRF protection (cookie + header) |
|
||||
| 3 | `AuthenticationMiddleware` | `HybridAuthBackend` — Basic, Bearer, Session, OIDC |
|
||||
| 4 | `RedisSessionMiddleware` | Cookie-based sessions stored in Redis |
|
||||
| 5 | `set_context_middleware` | Inject aiohttp/httpx clients into context vars |
|
||||
| Layer | Middleware | Purpose |
|
||||
| ----- | -------------------------- | ------------------------------------------------- |
|
||||
| 1 | `CORSMiddleware` | Allow cross-origin requests (all origins) |
|
||||
| 2 | `CSRFMiddleware` | Token-based CSRF protection (cookie + header) |
|
||||
| 3 | `AuthenticationMiddleware` | `HybridAuthBackend`: Basic, Bearer, Session, OIDC |
|
||||
| 4 | `RedisSessionMiddleware` | Cookie-based sessions stored in Redis |
|
||||
| 5 | `set_context_middleware` | Inject aiohttp/httpx clients into context vars |
|
||||
|
||||
### Request Flow
|
||||
|
||||
@@ -547,7 +547,7 @@ Constants: `FILE_NAME_MAX_LENGTH=450`, `FILE_PATH_MAX_LENGTH=1000`, `FILE_EXTENS
|
||||
|
||||
#### ROMs
|
||||
|
||||
**Table:** `roms` — the central entity
|
||||
**Table:** `roms` (the central entity)
|
||||
|
||||
| Column Group | Columns | Notes |
|
||||
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
|
||||
@@ -585,7 +585,7 @@ Tracks individual files within a ROM (archives can contain multiple files).
|
||||
|
||||
#### ROM Metadata (Aggregated)
|
||||
|
||||
**Table:** `roms_metadata` — aggregated metadata from all providers
|
||||
**Table:** `roms_metadata` (aggregated metadata from all providers)
|
||||
|
||||
| Column | Type |
|
||||
| -------------------- | --------------------------- |
|
||||
@@ -604,7 +604,7 @@ Tracks individual files within a ROM (archives can contain multiple files).
|
||||
|
||||
#### ROM User Data
|
||||
|
||||
**Table:** `rom_user` — per-user, per-ROM tracking
|
||||
**Table:** `rom_user` (per-user, per-ROM tracking)
|
||||
|
||||
| Column | Type | Notes |
|
||||
| -------------------- | ------------ | --------------------------------------------------------------------- |
|
||||
@@ -638,7 +638,7 @@ Tracks individual files within a ROM (archives can contain multiple files).
|
||||
|
||||
#### Collections
|
||||
|
||||
**Table:** `collections` — manually curated ROM lists
|
||||
**Table:** `collections` (manually curated ROM lists)
|
||||
|
||||
| Column | Type | Notes |
|
||||
| ----------------------------- | ----------- | --------- |
|
||||
@@ -652,7 +652,7 @@ Tracks individual files within a ROM (archives can contain multiple files).
|
||||
|
||||
Linked to ROMs via `collections_roms` join table (M:M).
|
||||
|
||||
**Table:** `smart_collections` — dynamic, filter-based
|
||||
**Table:** `smart_collections` (dynamic, filter-based)
|
||||
|
||||
| Column | Type | Notes |
|
||||
| ----------------- | ------- | ----------------------- |
|
||||
@@ -660,7 +660,7 @@ Linked to ROMs via `collections_roms` join table (M:M).
|
||||
| `rom_ids` | JSON | Cached matching ROM IDs |
|
||||
| `rom_count` | Integer | Cached count |
|
||||
|
||||
**View:** `virtual_collections` — database view, read-only, excluded from migrations.
|
||||
**View:** `virtual_collections` (database view, read-only, excluded from migrations).
|
||||
|
||||
---
|
||||
|
||||
@@ -672,7 +672,7 @@ All three share a similar structure:
|
||||
| ------------- | ---------------------------------- | ------------------- |
|
||||
| `saves` | `emulator`, `slot`, `content_hash` | Device sync support |
|
||||
| `states` | `emulator` | Save states |
|
||||
| `screenshots` | — | In-game captures |
|
||||
| `screenshots` | | In-game captures |
|
||||
|
||||
Common columns: `id`, `rom_id` (FK), `user_id` (FK), `file_name`, `file_path`, `file_size_bytes`, `missing_from_fs`
|
||||
|
||||
@@ -693,7 +693,7 @@ Saves additionally link to `device_save_sync` for cross-device tracking.
|
||||
| `sync_enabled` | Boolean | |
|
||||
| `last_seen` | Timestamp | |
|
||||
|
||||
**Table:** `device_save_sync` — tracks per-device, per-save sync state
|
||||
**Table:** `device_save_sync` (tracks per-device, per-save sync state)
|
||||
|
||||
| Column | Type |
|
||||
| ----------------------- | ------------ |
|
||||
@@ -705,7 +705,7 @@ Saves additionally link to `device_save_sync` for cross-device tracking.
|
||||
|
||||
#### Client Tokens
|
||||
|
||||
**Table:** `client_tokens` — long-lived API tokens
|
||||
**Table:** `client_tokens` (long-lived API tokens)
|
||||
|
||||
| Column | Type | Notes |
|
||||
| -------------- | ------------ | ---------------------------- |
|
||||
@@ -1025,15 +1025,15 @@ The codebase exposes roughly **175 HTTP routes** and **11 WebSocket handlers** a
|
||||
### Scope Definitions
|
||||
|
||||
```text
|
||||
me.read / me.write — Own profile
|
||||
roms.read / roms.write — ROM data
|
||||
platforms.read / platforms.write — Platform data
|
||||
assets.read / assets.write — Saves, states, screenshots
|
||||
devices.read / devices.write — Device management
|
||||
firmware.read / firmware.write — BIOS files
|
||||
collections.read / collections.write — Collections
|
||||
users.read / users.write — User management (admin)
|
||||
tasks.run — Task execution
|
||||
me.read / me.write : Own profile
|
||||
roms.read / roms.write : ROM data
|
||||
platforms.read / platforms.write : Platform data
|
||||
assets.read / assets.write : Saves, states, screenshots
|
||||
devices.read / devices.write : Device management
|
||||
firmware.read / firmware.write : BIOS files
|
||||
collections.read / collections.write : Collections
|
||||
users.read / users.write : User management (admin)
|
||||
tasks.run : Task execution
|
||||
```
|
||||
|
||||
### CSRF Protection
|
||||
@@ -1056,7 +1056,7 @@ tasks.run — Task execution
|
||||
|
||||
### 8.1 Scan Handler (`handler/scan_handler.py`)
|
||||
|
||||
The core of RomM — orchestrates library scanning and metadata enrichment.
|
||||
The core of RomM. Orchestrates library scanning and metadata enrichment.
|
||||
|
||||
**Scan Types:**
|
||||
|
||||
@@ -1185,7 +1185,7 @@ Tracks per-user playtime events ingested from clients (web player, console mode,
|
||||
|
||||
### 8.7 Device Sync Sessions
|
||||
|
||||
Coordinates save/state synchronization between devices using three sync modes (`API`, `FILE_TRANSFER`, `PUSH_PULL`). `SyncSession` tracks the lifecycle of a push/pull operation (including optional SSH-based file transfer — see `SYNC_SSH_*` env vars). Endpoints live in `endpoints/sync.py`; state is stored in the `sync_sessions` table.
|
||||
Coordinates save/state synchronization between devices using three sync modes (`API`, `FILE_TRANSFER`, `PUSH_PULL`). `SyncSession` tracks the lifecycle of a push/pull operation (including optional SSH-based file transfer; see `SYNC_SSH_*` env vars). Endpoints live in `endpoints/sync.py`; state is stored in the `sync_sessions` table.
|
||||
|
||||
### 8.8 Socket Handler (`handler/socket_handler.py`)
|
||||
|
||||
@@ -1302,7 +1302,7 @@ Client ←──Socket.IO──→ FastAPI (python-socketio) ←──Redis P
|
||||
| ------------------- | ------------------ | --------------------------- |
|
||||
| `scan:update_stats` | `ScanStats` object | Each ROM/platform processed |
|
||||
| `scan:log` | Log message | Scan log entries |
|
||||
| `scan:stop` | — | Scan completed or cancelled |
|
||||
| `scan:stop` | | Scan completed or cancelled |
|
||||
|
||||
### Netplay (`/netplay`)
|
||||
|
||||
@@ -1476,10 +1476,10 @@ Falls back to `FakeRedis` in test mode.
|
||||
| Variable | Default | Description |
|
||||
| ---------------- | --------- | ----------------------------------- |
|
||||
| `ROMM_DB_DRIVER` | `mariadb` | `mariadb`, `mysql`, or `postgresql` |
|
||||
| `DB_HOST` | — | Database host |
|
||||
| `DB_HOST` | | Database host |
|
||||
| `DB_PORT` | `3306` | Database port |
|
||||
| `DB_USER` | — | Database user |
|
||||
| `DB_PASSWD` | — | Database password |
|
||||
| `DB_USER` | | Database user |
|
||||
| `DB_PASSWD` | | Database password |
|
||||
| `DB_NAME` | `romm` | Database name |
|
||||
|
||||
#### Redis
|
||||
@@ -1488,8 +1488,8 @@ Falls back to `FakeRedis` in test mode.
|
||||
| ---------------- | ----------- | --------------------- |
|
||||
| `REDIS_HOST` | `127.0.0.1` | Redis host |
|
||||
| `REDIS_PORT` | `6379` | Redis port |
|
||||
| `REDIS_USERNAME` | — | Redis username (ACL) |
|
||||
| `REDIS_PASSWORD` | — | Redis password |
|
||||
| `REDIS_USERNAME` | | Redis username (ACL) |
|
||||
| `REDIS_PASSWORD` | | Redis password |
|
||||
| `REDIS_DB` | `0` | Redis database number |
|
||||
| `REDIS_SSL` | `false` | Enable SSL |
|
||||
|
||||
@@ -1497,7 +1497,7 @@ Falls back to `FakeRedis` in test mode.
|
||||
|
||||
| Variable | Default | Description |
|
||||
| ------------------------------------ | --------- | ------------------------------------- |
|
||||
| `ROMM_AUTH_SECRET_KEY` | — | **Required.** JWT/session signing key |
|
||||
| `ROMM_AUTH_SECRET_KEY` | | **Required.** JWT/session signing key |
|
||||
| `OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS` | `1800` | 30 minutes |
|
||||
| `OAUTH_REFRESH_TOKEN_EXPIRE_SECONDS` | `604800` | 7 days |
|
||||
| `SESSION_MAX_AGE_SECONDS` | `1209600` | 14 days |
|
||||
@@ -1511,16 +1511,16 @@ Falls back to `FakeRedis` in test mode.
|
||||
| Variable | Default | Description |
|
||||
| ------------------------------- | -------------------- | ------------------------------- |
|
||||
| `OIDC_ENABLED` | `false` | Enable OpenID Connect |
|
||||
| `OIDC_PROVIDER` | — | Provider URL |
|
||||
| `OIDC_CLIENT_ID` | — | Client ID |
|
||||
| `OIDC_CLIENT_SECRET` | — | Client secret |
|
||||
| `OIDC_REDIRECT_URI` | — | Redirect URI |
|
||||
| `OIDC_PROVIDER` | | Provider URL |
|
||||
| `OIDC_CLIENT_ID` | | Client ID |
|
||||
| `OIDC_CLIENT_SECRET` | | Client secret |
|
||||
| `OIDC_REDIRECT_URI` | | Redirect URI |
|
||||
| `OIDC_USERNAME_ATTRIBUTE` | `preferred_username` | Username claim |
|
||||
| `OIDC_CLAIM_ROLES` | — | Roles claim name |
|
||||
| `OIDC_ROLE_VIEWER/EDITOR/ADMIN` | — | Role mappings |
|
||||
| `OIDC_TLS_CACERTFILE` | — | Custom CA bundle for OIDC calls |
|
||||
| `OIDC_CLAIM_ROLES` | | Roles claim name |
|
||||
| `OIDC_ROLE_VIEWER/EDITOR/ADMIN` | | Role mappings |
|
||||
| `OIDC_TLS_CACERTFILE` | | Custom CA bundle for OIDC calls |
|
||||
| `OIDC_RP_INITIATED_LOGOUT` | `false` | Send logout to OIDC provider |
|
||||
| `OIDC_END_SESSION_ENDPOINT` | — | End-session URL override |
|
||||
| `OIDC_END_SESSION_ENDPOINT` | | End-session URL override |
|
||||
|
||||
#### API Keys
|
||||
|
||||
@@ -1551,26 +1551,25 @@ Falls back to `FakeRedis` in test mode.
|
||||
| -------------------------------------- | ----------- | ------------------------------- |
|
||||
| `SCAN_TIMEOUT` | `14400` | 4-hour scan timeout |
|
||||
| `SCAN_WORKERS` | `1` | Concurrent scan workers |
|
||||
| `TASK_TIMEOUT` | — | RQ job timeout for manual tasks |
|
||||
| `TASK_RESULT_TTL` | — | How long to keep job results |
|
||||
| `TASK_TIMEOUT` | | RQ job timeout for manual tasks |
|
||||
| `TASK_RESULT_TTL` | | How long to keep job results |
|
||||
| `ENABLE_SCHEDULED_RESCAN` | `false` | Auto library rescan |
|
||||
| `SCHEDULED_RESCAN_CRON` | `0 3 * * *` | Rescan schedule |
|
||||
| `ENABLE_RESCAN_ON_FILESYSTEM_CHANGE` | `false` | Watch for file changes |
|
||||
| `RESCAN_ON_FILESYSTEM_CHANGE_DELAY` | `5` | Debounce delay (minutes) |
|
||||
| `SEVEN_ZIP_TIMEOUT` | — | Timeout for 7-Zip extraction |
|
||||
| `REFRESH_RETROACHIEVEMENTS_CACHE_DAYS` | — | RA cache TTL (days) |
|
||||
| `SEVEN_ZIP_TIMEOUT` | | Timeout for 7-Zip extraction |
|
||||
| `REFRESH_RETROACHIEVEMENTS_CACHE_DAYS` | | RA cache TTL (days) |
|
||||
|
||||
#### Device Sync
|
||||
|
||||
| Variable | Default | Description |
|
||||
| --------------------------------- | ------- | --------------------------------- |
|
||||
| `ENABLE_SYNC_FOLDER_WATCHER` | `false` | Watch sync folder for new saves |
|
||||
| `SYNC_FOLDER_SCAN_DELAY` | — | Debounce for sync folder scans |
|
||||
| `ENABLE_SYNC_PUSH_PULL` | `false` | Enable scheduled push/pull sync |
|
||||
| `SYNC_PUSH_PULL_CRON` | — | Cron schedule for push/pull |
|
||||
| `SYNC_SSH_HOST` / `SYNC_SSH_PORT` | — | SSH target for FILE_TRANSFER sync |
|
||||
| `SYNC_SSH_USERNAME` | — | SSH user |
|
||||
| `SYNC_SSH_PRIVATE_KEY_PATH` | — | SSH private key path |
|
||||
| Variable | Default | Description |
|
||||
| ---------------------------- | ------- | ------------------------------- |
|
||||
| `ENABLE_SYNC_FOLDER_WATCHER` | `false` | Watch sync folder for new saves |
|
||||
| `SYNC_FOLDER_SCAN_DELAY` | | Debounce for sync folder scans |
|
||||
| `ENABLE_SYNC_PUSH_PULL` | `false` | Enable scheduled push/pull sync |
|
||||
| `SYNC_PUSH_PULL_CRON` | | Cron schedule for push/pull |
|
||||
| `SYNC_SSH_KEYS_PATH` | | SSH keys path |
|
||||
| `SYNC_SSH_KNOWN_HOSTS_PATH` | | SSH known hosts path |
|
||||
|
||||
### YAML Configuration (`config.yml`)
|
||||
|
||||
@@ -1628,12 +1627,12 @@ Managed by `ConfigManager` (singleton pattern) which reads, validates, and write
|
||||
|
||||
```text
|
||||
Exception
|
||||
├── AuthCredentialsException # 401 — Incorrect credentials
|
||||
├── AuthenticationSchemeException # 401 — Invalid auth scheme
|
||||
├── UserDisabledException # 401 — Account disabled
|
||||
├── OAuthCredentialsException # 401 — Invalid OAuth token
|
||||
├── OIDCDisabledException # 500 — OIDC not configured
|
||||
├── OIDCNotConfiguredException # 500 — OIDC feature disabled
|
||||
├── AuthCredentialsException # 401: Incorrect credentials
|
||||
├── AuthenticationSchemeException # 401: Invalid auth scheme
|
||||
├── UserDisabledException # 401: Account disabled
|
||||
├── OAuthCredentialsException # 401: Invalid OAuth token
|
||||
├── OIDCDisabledException # 500: OIDC not configured
|
||||
├── OIDCNotConfiguredException # 500: OIDC feature disabled
|
||||
│
|
||||
├── PlatformNotFoundInDatabaseException # 404
|
||||
├── RomNotFoundInDatabaseException # 404
|
||||
|
||||
@@ -323,12 +323,12 @@ index.html
|
||||
### Plugin Registration Order
|
||||
|
||||
```text
|
||||
1. Vuetify — Material Design components, themes, icons
|
||||
2. Pinia — State management (with router injection)
|
||||
3. vue-i18n — Internationalization (17 locales)
|
||||
4. Mitt — Event emitter (provided as 'emitter')
|
||||
5. MD Editor — Markdown editor with XSS plugin
|
||||
6. Vue Router — Navigation with guards
|
||||
1. Vuetify : Material Design components, themes, icons
|
||||
2. Pinia : State management (with router injection)
|
||||
3. vue-i18n : Internationalization (17 locales)
|
||||
4. Mitt : Event emitter (provided as 'emitter')
|
||||
5. MD Editor : Markdown editor with XSS plugin
|
||||
6. Vue Router : Navigation with guards
|
||||
```
|
||||
|
||||
### Request Lifecycle
|
||||
@@ -864,10 +864,10 @@ All synthesized with sine/noise blend, exponential envelopes, low-pass filter, a
|
||||
|
||||
`utils/index.ts` provides:
|
||||
|
||||
- `getSupportedEJSCores(platform)` — maps platforms to EmulatorJS cores
|
||||
- `isEJSEmulationSupported(rom)` — checks WebGL + server config
|
||||
- `isRuffleEmulationSupported(rom)` — checks Flash platform
|
||||
- `isCDBasedSystem(platform)` — 31 CD-based platforms for animation logic
|
||||
- `getSupportedEJSCores(platform)`: maps platforms to EmulatorJS cores
|
||||
- `isEJSEmulationSupported(rom)`: checks WebGL + server config
|
||||
- `isRuffleEmulationSupported(rom)`: checks Flash platform
|
||||
- `isCDBasedSystem(platform)`: 31 CD-based platforms for animation logic
|
||||
|
||||
---
|
||||
|
||||
@@ -921,7 +921,7 @@ Vuetify handles theme switching. Additional shared brand colors: `romm-red`, `ro
|
||||
|
||||
| Code | Language |
|
||||
| ------- | --------------------------- |
|
||||
| `en_US` | English (US) — default |
|
||||
| `en_US` | English (US, default) |
|
||||
| `en_GB` | English (UK) |
|
||||
| `fr_FR` | French |
|
||||
| `de_DE` | German |
|
||||
@@ -964,9 +964,9 @@ io({
|
||||
|
||||
**Events consumed:**
|
||||
|
||||
- `scan:update_stats` — live scan progress (platform/ROM counts)
|
||||
- `scan:log` — scan log messages
|
||||
- `scan:stop` — scan completion
|
||||
- `scan:update_stats`: live scan progress (platform/ROM counts)
|
||||
- `scan:log`: scan log messages
|
||||
- `scan:stop`: scan completion
|
||||
|
||||
**Dev proxy:** Vite proxies `/ws` to backend with WebSocket upgrade support.
|
||||
|
||||
@@ -1016,34 +1016,34 @@ Request Flow with Cache:
|
||||
|
||||
**Display:**
|
||||
|
||||
- `formatBytes()` — human-readable sizes (B through PB)
|
||||
- `formatTimestamp()` — locale-aware dates
|
||||
- `formatRelativeDate()` — relative time strings
|
||||
- `formatBytes()`: human-readable sizes (B through PB)
|
||||
- `formatTimestamp()`: locale-aware dates
|
||||
- `formatRelativeDate()`: relative time strings
|
||||
|
||||
**Emojis & Localization:**
|
||||
|
||||
- `regionToEmoji()` — 50+ region codes → country flags
|
||||
- `languageToEmoji()` — 40+ language codes → country flags
|
||||
- `regionToEmoji()`: 50+ region codes → country flags
|
||||
- `languageToEmoji()`: 40+ language codes → country flags
|
||||
|
||||
**Emulation Support:**
|
||||
|
||||
- `getSupportedEJSCores()` — platform → EmulatorJS core mapping
|
||||
- `isEJSEmulationSupported()` — WebGL + config check
|
||||
- `isCDBasedSystem()` — 31 CD-based platforms
|
||||
- `getSupportedEJSCores()`: platform → EmulatorJS core mapping
|
||||
- `isEJSEmulationSupported()`: WebGL + config check
|
||||
- `isCDBasedSystem()`: 31 CD-based platforms
|
||||
|
||||
**Game Status:**
|
||||
|
||||
- `romStatusMap` — 8 statuses with emoji, text, i18n keys
|
||||
- `romStatusMap`: 8 statuses with emoji, text, i18n keys
|
||||
- Status enum: `unplayed`, `now_playing`, `backlogged`, `paused`, `completed`, `100%`, `retired`, `never_playing`
|
||||
|
||||
**Layout:**
|
||||
|
||||
- `views` — 3 view modes with responsive grid configurations
|
||||
- `calculateMainLayoutWidth()` — dynamic width based on drawer state
|
||||
- `views`: 3 view modes with responsive grid configurations
|
||||
- `calculateMainLayoutWidth()`: dynamic width based on drawer state
|
||||
|
||||
**Task Display:**
|
||||
|
||||
- `convertCronExpression()` — human-readable cron (via cronstrue)
|
||||
- `convertCronExpression()`: human-readable cron (via cronstrue)
|
||||
- Task status/type maps with colors and icons
|
||||
|
||||
### Cover Generation (`utils/covers.ts`)
|
||||
@@ -1075,8 +1075,8 @@ Procedural SVG generation for:
|
||||
1. Tailwind CSS (`@tailwindcss/vite`)
|
||||
2. Vue 3 (`@vitejs/plugin-vue`)
|
||||
3. Vuetify auto-import (`vite-plugin-vuetify`, 57 pre-optimized components)
|
||||
4. PWA (`vite-plugin-pwa` — service worker, installable)
|
||||
5. HTTPS (`vite-plugin-mkcert` — optional dev HTTPS)
|
||||
4. PWA (`vite-plugin-pwa`, service worker, installable)
|
||||
5. HTTPS (`vite-plugin-mkcert`, optional dev HTTPS)
|
||||
6. Static copy (ROM patcher JS assets)
|
||||
|
||||
### Scripts
|
||||
|
||||
+4
-3
@@ -52,8 +52,7 @@ RQ_REDIS_HOST=${REDIS_HOST:-127.0.0.1} \
|
||||
RQ_REDIS_SSL=${REDIS_SSL:-0} \
|
||||
rqscheduler \
|
||||
--path /app/backend \
|
||||
--pid /tmp/rq_scheduler.pid \
|
||||
--logging_level "${LOGLEVEL:-INFO}" &
|
||||
--pid /tmp/rq_scheduler.pid &
|
||||
|
||||
echo "Starting RQ worker..."
|
||||
# Build Redis URL properly
|
||||
@@ -81,10 +80,12 @@ watchfiles \
|
||||
|
||||
if [[ ${ENABLE_SYNC_FOLDER_WATCHER:-false} == "true" ]]; then
|
||||
echo "Starting sync folder watcher..."
|
||||
sync_base_path="${ROMM_BASE_PATH:-/romm}/sync"
|
||||
mkdir -p "${sync_base_path}"
|
||||
watchfiles \
|
||||
--target-type command \
|
||||
'uv run python sync_watcher.py' \
|
||||
/app/romm/sync &
|
||||
"${sync_base_path}" &
|
||||
fi
|
||||
|
||||
# Start the frontend dev server
|
||||
|
||||
+1
-2
@@ -1,7 +1,7 @@
|
||||
# Core Application
|
||||
ROMM_BASE_PATH=/romm # Base folder path for library, resources and assets
|
||||
ROMM_TMP_PATH= # Custom temporary directory path
|
||||
ROMM_BASE_URL=http://0.0.0.0 # Base URL used when rendering container log links
|
||||
ROMM_BASE_URL=http://0.0.0.0 # Public URL of this instance
|
||||
ROMM_PORT=8080 # Port on which the application listens
|
||||
KIOSK_MODE=false # Read-only mode for public displays or kiosks
|
||||
|
||||
@@ -88,7 +88,6 @@ ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC=false # Enable scheduled Retro
|
||||
SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON=0 4 * * * # Cron expression for scheduled RetroAchievements sync
|
||||
|
||||
# Sync
|
||||
SYNC_BASE_PATH= # Base folder for sync state (defaults to $ROMM_BASE_PATH/sync)
|
||||
ENABLE_SYNC_FOLDER_WATCHER=false # Watch the sync folder and trigger scans on change
|
||||
SYNC_FOLDER_SCAN_DELAY=2 # Delay in minutes before scanning after a sync folder change
|
||||
ENABLE_SYNC_PUSH_PULL=false # Enable scheduled sync push/pull
|
||||
|
||||
@@ -5,12 +5,14 @@ exclude:
|
||||
platforms: []
|
||||
roms:
|
||||
multi_file:
|
||||
names: []
|
||||
names: ["images", "videos"]
|
||||
parts:
|
||||
extensions: []
|
||||
names: []
|
||||
single_file:
|
||||
extensions: []
|
||||
extensions:
|
||||
- xml
|
||||
- txt
|
||||
names: []
|
||||
filesystem: {}
|
||||
system:
|
||||
@@ -88,6 +90,7 @@ system:
|
||||
macintosh: mac
|
||||
mame: arcade
|
||||
mastersystem: sms
|
||||
megacd: segacd
|
||||
megadrive: genesis
|
||||
megadrive-msu: genesis
|
||||
megaduck: mega-duck-slash-cougar-boy
|
||||
|
||||
Generated
+215
-693
File diff suppressed because it is too large.
Load diff
@@ -42,10 +42,11 @@
|
||||
"@floating-ui/vue": "^1.1.11",
|
||||
"@mdi/font": "7.4.47",
|
||||
"@vueuse/core": "^13.7.0",
|
||||
"axios": "^1.15.0",
|
||||
"axios": "^1.16.0",
|
||||
"bowser": "^2.14.1",
|
||||
"cronstrue": "^2.57.0",
|
||||
"date-fns": "^4.1.0",
|
||||
"js-cookie": "^3.0.5",
|
||||
"js-cookie": "^3.0.7",
|
||||
"lodash": "^4.18.1",
|
||||
"md-editor-v3": "^5.8.4",
|
||||
"mitt": "^3.0.1",
|
||||
|
||||
+1
-1
@@ -84,7 +84,6 @@ export type DetailedRomSchema = {
|
||||
has_simple_single_file: boolean;
|
||||
has_nested_single_file: boolean;
|
||||
has_multiple_files: boolean;
|
||||
files: Array<RomFileSchema>;
|
||||
full_path: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
@@ -94,6 +93,7 @@ export type DetailedRomSchema = {
|
||||
rom_user: RomUserSchema;
|
||||
merged_screenshots: Array<string>;
|
||||
merged_ra_metadata: (RomRAMetadata | null);
|
||||
files: Array<RomFileSchema>;
|
||||
user_saves: Array<SaveSchema>;
|
||||
user_states: Array<StateSchema>;
|
||||
user_screenshots: Array<ScreenshotSchema>;
|
||||
|
||||
@@ -18,6 +18,7 @@ export type RomFileSchema = {
|
||||
md5_hash: (string | null);
|
||||
sha1_hash: (string | null);
|
||||
ra_hash: (string | null);
|
||||
chd_sha1_hash: (string | null);
|
||||
category: (RomFileCategory | null);
|
||||
audio_meta?: (RomFileAudioMetaSchema | null);
|
||||
};
|
||||
|
||||
@@ -16,5 +16,7 @@ export type RomLaunchboxMetadata = {
|
||||
genres?: Array<string>;
|
||||
companies?: Array<string>;
|
||||
images?: Array<LaunchboxImage>;
|
||||
video_url?: string;
|
||||
video_path?: string;
|
||||
};
|
||||
|
||||
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user