From 40689d7e39e9514c13256e29d5f54e48e46f22eb Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Fri, 17 Apr 2026 22:59:00 -0400 Subject: [PATCH 001/186] Fix LaunchBox local-media file:// paths resolving under library root LaunchBox produced file:// URIs relative to /romm/launchbox, but the resources handler resolved them under /romm/library via fs_rom_handler, so local images/manuals/screenshots were never found. Switch LaunchBox to a distinct launchbox-file:// scheme and add FSLaunchboxHandler + _resolve_local_file_uri to route each scheme to the correct root. Co-Authored-By: Claude Opus 4.7 (1M context) --- backend/handler/filesystem/__init__.py | 2 + .../handler/filesystem/launchbox_handler.py | 9 ++ .../handler/filesystem/resources_handler.py | 109 +++++++++--------- .../metadata/launchbox_handler/utils.py | 2 +- 4 files changed, 68 insertions(+), 54 deletions(-) create mode 100644 backend/handler/filesystem/launchbox_handler.py diff --git a/backend/handler/filesystem/__init__.py b/backend/handler/filesystem/__init__.py index d11d2df22..7430823aa 100644 --- a/backend/handler/filesystem/__init__.py +++ b/backend/handler/filesystem/__init__.py @@ -1,5 +1,6 @@ from .assets_handler import FSAssetsHandler from .firmware_handler import FSFirmwareHandler +from .launchbox_handler import FSLaunchboxHandler from .platforms_handler import FSPlatformsHandler from .resources_handler import FSResourcesHandler from .roms_handler import FSRomsHandler @@ -11,3 +12,4 @@ fs_platform_handler = FSPlatformsHandler() fs_rom_handler = FSRomsHandler() fs_resource_handler = FSResourcesHandler() fs_sync_handler = FSSyncHandler() +fs_launchbox_handler = FSLaunchboxHandler() diff --git a/backend/handler/filesystem/launchbox_handler.py b/backend/handler/filesystem/launchbox_handler.py new file mode 100644 index 000000000..9c34f065b --- /dev/null +++ b/backend/handler/filesystem/launchbox_handler.py @@ -0,0 +1,9 @@ +from pathlib import Path + +from config import ROMM_BASE_PATH +from handler.filesystem.base_handler import FSHandler + + +class FSLaunchboxHandler(FSHandler): + def __init__(self) -> None: + super().__init__(base_path=str(Path(ROMM_BASE_PATH) / "launchbox")) diff --git a/backend/handler/filesystem/resources_handler.py b/backend/handler/filesystem/resources_handler.py index d92f2b003..680b6c279 100644 --- a/backend/handler/filesystem/resources_handler.py +++ b/backend/handler/filesystem/resources_handler.py @@ -19,6 +19,32 @@ 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 — LaunchBox metadata produces paths relative + to `/romm/launchbox`, which is not the same as the library root. + """ + from handler.filesystem import fs_launchbox_handler, fs_rom_handler + + if uri.startswith("launchbox-file://"): + try: + return 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 +121,21 @@ 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" + await self.copy_file(resolved, 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, + ) except Exception as exc: log.error(f"Unable to copy cover file {url_cover}: {str(exc)}") return None @@ -275,20 +295,14 @@ 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") except Exception as exc: log.error(f"Unable to copy screenshot file {url_screenhot}: {str(exc)}") return None @@ -395,20 +409,14 @@ 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") except Exception as exc: log.error(f"Unable to copy manual file {url_manual}: {str(exc)}") return None @@ -542,17 +550,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) except Exception as exc: log.error(f"Unable to copy media file {url_media}: {str(exc)}") return None diff --git a/backend/handler/metadata/launchbox_handler/utils.py b/backend/handler/metadata/launchbox_handler/utils.py index 8c73d0892..23bc8af53 100644 --- a/backend/handler/metadata/launchbox_handler/utils.py +++ b/backend/handler/metadata/launchbox_handler/utils.py @@ -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: From a83f3bdca7bd363c4128f76a0d16dd9078b33f34 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 18 Apr 2026 12:00:26 -0400 Subject: [PATCH 002/186] Wire up LaunchBox MAME arcade lookups The scheduled task populated LAUNCHBOX_MAME_KEY from Mame.xml but no handler code ever read it, so arcade ROMs like pacman.zip never matched against Metadata.xml (which keys on full titles like "Pac-Man"). Add RemoteSource.get_mame_entry() and an ARCADE branch in get_rom() that resolves the MAME filename to its Description before name lookup. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../metadata/launchbox_handler/handler.py | 10 ++ .../launchbox_handler/remote_source.py | 16 ++ .../metadata/test_launchbox_handler.py | 137 ++++++++++++++++++ 3 files changed, 163 insertions(+) diff --git a/backend/handler/metadata/launchbox_handler/handler.py b/backend/handler/metadata/launchbox_handler/handler.py index 0cd9d5f6c..414b185e5 100644 --- a/backend/handler/metadata/launchbox_handler/handler.py +++ b/backend/handler/metadata/launchbox_handler/handler.py @@ -128,6 +128,16 @@ class LaunchboxHandler(MetadataHandler): else: search_term = fs_name + # Resolve MAME arcade filename (e.g. pacman.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: + description = (mame_entry.get("Description") or "").strip() + if description: + search_term = description + fallback_rom = LaunchboxRom(launchbox_id=None, name=description) + # We replace " - "/"- " with ": " to match Launchbox's naming convention search_term = re.sub(DASH_COLON_REGEX, ": ", search_term).lower() diff --git a/backend/handler/metadata/launchbox_handler/remote_source.py b/backend/handler/metadata/launchbox_handler/remote_source.py index c2b9e66d6..121c2c126 100644 --- a/backend/handler/metadata/launchbox_handler/remote_source.py +++ b/backend/handler/metadata/launchbox_handler/remote_source.py @@ -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, @@ -74,6 +75,21 @@ 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 `` records by `` (e.g. + `pacman.zip`). The entry carries `Description` — the full title to + search for in Metadata.xml. + """ + file_name_clean = (file_name or "").strip() + if not file_name_clean: + return None + entry = await async_cache.hget(LAUNCHBOX_MAME_KEY, file_name_clean) + if not entry: + return None + return json.loads(entry) + async def fetch_images( self, *, diff --git a/backend/tests/handler/metadata/test_launchbox_handler.py b/backend/tests/handler/metadata/test_launchbox_handler.py index cb97207b0..fb1fe4ce3 100644 --- a/backend/tests/handler/metadata/test_launchbox_handler.py +++ b/backend/tests/handler/metadata/test_launchbox_handler.py @@ -23,6 +23,7 @@ from handler.metadata.launchbox_handler.media import build_launchbox_metadata, b 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, @@ -520,6 +521,46 @@ 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): + mame_entry = { + "FileName": "pacman.zip", + "GameName": "pacman", + "Description": "Pac-Man", + } + with patch.object( + async_cache, + "hget", + new_callable=AsyncMock, + return_value=json.dumps(mame_entry), + ) as mock_hget: + result = await source.get_mame_entry("pacman.zip") + mock_hget.assert_called_once_with(LAUNCHBOX_MAME_KEY, "pacman.zip") + 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(" pacman.zip ") + mock_hget.assert_called_once_with(LAUNCHBOX_MAME_KEY, "pacman.zip") + + class TestRemoteSourceFetchImages: @pytest.fixture def source(self) -> RemoteSource: @@ -739,6 +780,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 +910,100 @@ 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": "pacman.zip", + "GameName": "pacman", + "Description": "Pac-Man", + } + remote_entry = {"DatabaseID": "999", "Name": "Pac-Man"} + 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 = "pacman" + result = await handler.get_rom("pacman.zip", "arcade") + + mock_mame.assert_called_once_with("pacman.zip") + # search term should be the MAME Description, lowercased + assert mock_get_rom.call_args.args[0] == "pac-man" + assert result.get("name", None) == "Pac-Man" + 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 = "pacman" + result = await handler.get_rom("pacman.zip", "arcade") + + mock_mame.assert_called_once_with("pacman.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 description as the rom name. + mame_entry = { + "FileName": "pacman.zip", + "GameName": "pacman", + "Description": "Pac-Man", + } + 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 = "pacman" + result = await handler.get_rom("pacman.zip", "arcade") + + assert result["launchbox_id"] is None + assert result.get("name", None) == "Pac-Man" + + 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 = "pacman" + await handler.get_rom("pacman.zip", "nes") + + mock_mame.assert_not_called() + class TestLaunchboxHandlerGetRomById: @pytest.fixture @@ -923,6 +1059,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)) From 8fc426b35c925d396dd066597270907188971b6c Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 18 Apr 2026 12:13:42 -0400 Subject: [PATCH 003/186] Import local LaunchBox videos LaunchBox stores videos under /romm/launchbox/Videos//. but the handler only extracted YouTube IDs; LAUNCHBOX_VIDEOS_DIR was defined and unused. Add _get_video() to surface local videos as launchbox-file:// URLs, thread a populate_rom_specific_paths() through the scan pipeline to set video_path once the rom is known, and mirror the SS/gamelist branch in the scan socket so store_media_file actually copies the video into the rom's resource directory. Rom.path_video now also reads from launchbox_metadata. Co-Authored-By: Claude Opus 4.7 (1M context) --- backend/endpoints/sockets/scan.py | 10 ++ .../metadata/launchbox_handler/media.py | 82 ++++++++++- .../metadata/launchbox_handler/types.py | 2 + backend/handler/scan_handler.py | 22 ++- backend/models/rom.py | 1 + .../metadata/test_launchbox_handler.py | 135 +++++++++++++++++- 6 files changed, 240 insertions(+), 12 deletions(-) diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index bc3374981..2f5f52b89 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -412,6 +412,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", []): diff --git a/backend/handler/metadata/launchbox_handler/media.py b/backend/handler/metadata/launchbox_handler/media.py index 889690b8f..475545d45 100644 --- a/backend/handler/metadata/launchbox_handler/media.py +++ b/backend/handler/metadata/launchbox_handler/media.py @@ -1,10 +1,15 @@ from pathlib import Path +from typing import TYPE_CHECKING 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, @@ -324,6 +329,45 @@ 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//.` + (no region or category subdirectories). Return a `launchbox-file://` URL + to the first match, or None. + """ + if not req.platform_name: + return None + + base = (LAUNCHBOX_VIDEOS_DIR / req.platform_name).resolve() + if not base.is_dir(): + return None + + stems: list[str] = [] + if req.fs_name: + stems.append(Path(req.fs_name).stem) + if req.title: + stems.append(req.title) + + stems_clean: list[str] = [] + for s in stems: + clean = sanitize_filename(s) + if clean and clean not in stems_clean: + stems_clean.append(clean) + + if not stems_clean: + return None + + video_exts = (".mp4", ".webm", ".avi", ".mkv", ".mov", ".wmv") + for stem in stems_clean: + for ext in video_exts: + candidate = 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 +539,29 @@ 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. + """ + from config.config_manager import MetadataMediaType + from handler.filesystem import fs_resource_handler + from handler.metadata.ss_handler import get_preferred_media_types + + if MetadataMediaType.VIDEO in get_preferred_media_types() and metadata.get( + "video_url" + ): + base = fs_resource_handler.get_media_resources_path( + rom.platform_id, rom.id, MetadataMediaType.VIDEO + ) + metadata["video_path"] = f"{base}/video.mp4" + return metadata + + def build_rom( *, local: dict[str, str] | None, @@ -509,10 +576,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 +601,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 +615,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, ) diff --git a/backend/handler/metadata/launchbox_handler/types.py b/backend/handler/metadata/launchbox_handler/types.py index bb3033400..864b6e39a 100644 --- a/backend/handler/metadata/launchbox_handler/types.py +++ b/backend/handler/metadata/launchbox_handler/types.py @@ -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): diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 03ab3d2dd..e1565275e 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -623,15 +623,25 @@ async def scan_rom( and rom.launchbox_id and launchbox_remote_enabled ): - return await meta_launchbox_handler.get_rom_by_id( + launchbox_rom = await meta_launchbox_handler.get_rom_by_id( rom.launchbox_id, remote_enabled=True ) + 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: + from handler.metadata.launchbox_handler.media import ( + populate_rom_specific_paths, + ) + + populate_rom_specific_paths(metadata, rom) + + return launchbox_rom return LaunchboxRom(launchbox_id=None) diff --git a/backend/models/rom.py b/backend/models/rom.py index 88fd257d8..9b5035e4b 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -357,6 +357,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 diff --git a/backend/tests/handler/metadata/test_launchbox_handler.py b/backend/tests/handler/metadata/test_launchbox_handler.py index fb1fe4ce3..a630f2363 100644 --- a/backend/tests/handler/metadata/test_launchbox_handler.py +++ b/backend/tests/handler/metadata/test_launchbox_handler.py @@ -19,7 +19,12 @@ 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, +) 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 ( @@ -29,6 +34,8 @@ from handler.metadata.launchbox_handler.types import ( LAUNCHBOX_METADATA_IMAGE_KEY, LAUNCHBOX_METADATA_NAME_KEY, LaunchboxImage, + LaunchboxMetadata, + MediaRequest, ) from handler.metadata.launchbox_handler.utils import ( coalesce, @@ -677,6 +684,132 @@ 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.ss_handler.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.ss_handler.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_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.ss_handler.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 TestBuildRom: def test_name_from_local_title(self): local = {"Title": "Super Mario Bros.", "Notes": "Classic platformer"} From f33844be409cc31e185054d95ee6542f5eb32d73 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 18 Apr 2026 12:32:54 -0400 Subject: [PATCH 004/186] Find local LaunchBox media for remote-only rom matches remote_media_req built a MediaRequest with platform_name=None, which made _build_local_media_context bail and never search on-disk Images/Manuals/Videos. Any rom that matched only via Metadata.xml (no local XML entry) ended up with images: [] even though LaunchBox art was sitting on disk. Thread platform_name and fs_name into remote_media_req, falling back to the remote entry's Platform field when no slug is available (e.g. lookups by database id). Co-Authored-By: Claude Opus 4.7 (1M context) --- .../metadata/launchbox_handler/handler.py | 2 + .../metadata/launchbox_handler/media.py | 12 ++- .../metadata/test_launchbox_handler.py | 100 ++++++++++++++++++ 3 files changed, 112 insertions(+), 2 deletions(-) diff --git a/backend/handler/metadata/launchbox_handler/handler.py b/backend/handler/metadata/launchbox_handler/handler.py index 414b185e5..850f667ae 100644 --- a/backend/handler/metadata/launchbox_handler/handler.py +++ b/backend/handler/metadata/launchbox_handler/handler.py @@ -162,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( diff --git a/backend/handler/metadata/launchbox_handler/media.py b/backend/handler/metadata/launchbox_handler/media.py index 475545d45..118e2abb8 100644 --- a/backend/handler/metadata/launchbox_handler/media.py +++ b/backend/handler/metadata/launchbox_handler/media.py @@ -54,11 +54,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, diff --git a/backend/tests/handler/metadata/test_launchbox_handler.py b/backend/tests/handler/metadata/test_launchbox_handler.py index a630f2363..cdd27e808 100644 --- a/backend/tests/handler/metadata/test_launchbox_handler.py +++ b/backend/tests/handler/metadata/test_launchbox_handler.py @@ -24,6 +24,7 @@ from handler.metadata.launchbox_handler.media import ( 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 @@ -810,6 +811,105 @@ class TestPopulateRomSpecificPaths: 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. + images = result["launchbox_metadata"]["images"] + assert len(images) == 1 + assert images[0]["type"] == "Clear Logo" + assert images[0]["url"] == ( + "launchbox-file://Images/Atari 2600/Clear Logo/H.E.R.O-01.png" + ) + 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"} From fad2e5c77d7de5679eac26b5a1b5c3743620ada4 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 18 Apr 2026 14:31:16 -0400 Subject: [PATCH 005/186] Use correct LaunchBox MameFile schema The sample_metadata.zip test fixture used invented tag names (, FileName ending in .zip). Real LaunchBox Mame.xml (see backend/tasks/fixtures/launchbox/mame.xml) uses as the full title and keys MameFile entries by the stem (e.g. wrlok_l3), no extension. Read Name instead of Description, and fall back to the stem when the raw fs_name lookup misses. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../metadata/launchbox_handler/handler.py | 10 +-- .../metadata/launchbox_handler/media.py | 35 ++------ .../launchbox_handler/remote_source.py | 25 ++++-- backend/handler/scan_handler.py | 5 +- .../metadata/test_launchbox_handler.py | 85 +++++++++++-------- 5 files changed, 82 insertions(+), 78 deletions(-) diff --git a/backend/handler/metadata/launchbox_handler/handler.py b/backend/handler/metadata/launchbox_handler/handler.py index 850f667ae..3a68988ea 100644 --- a/backend/handler/metadata/launchbox_handler/handler.py +++ b/backend/handler/metadata/launchbox_handler/handler.py @@ -128,15 +128,15 @@ class LaunchboxHandler(MetadataHandler): else: search_term = fs_name - # Resolve MAME arcade filename (e.g. pacman.zip) to its full title + # 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: - description = (mame_entry.get("Description") or "").strip() - if description: - search_term = description - fallback_rom = LaunchboxRom(launchbox_id=None, name=description) + 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() diff --git a/backend/handler/metadata/launchbox_handler/media.py b/backend/handler/metadata/launchbox_handler/media.py index 118e2abb8..eadcb8472 100644 --- a/backend/handler/metadata/launchbox_handler/media.py +++ b/backend/handler/metadata/launchbox_handler/media.py @@ -1,6 +1,9 @@ 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: @@ -344,32 +347,16 @@ def _get_video(req: MediaRequest) -> str | None: (no region or category subdirectories). Return a `launchbox-file://` URL to the first match, or None. """ - if not req.platform_name: - return None - - base = (LAUNCHBOX_VIDEOS_DIR / req.platform_name).resolve() - if not base.is_dir(): - return None - - stems: list[str] = [] - if req.fs_name: - stems.append(Path(req.fs_name).stem) - if req.title: - stems.append(req.title) - - stems_clean: list[str] = [] - for s in stems: - clean = sanitize_filename(s) - if clean and clean not in stems_clean: - stems_clean.append(clean) - - if not stems_clean: + ctx = _build_local_media_context( + req, LAUNCHBOX_VIDEOS_DIR, include_region_hints=False + ) + if ctx is None: return None video_exts = (".mp4", ".webm", ".avi", ".mkv", ".mov", ".wmv") - for stem in stems_clean: + for stem in ctx["stems"]: for ext in video_exts: - candidate = base / f"{stem}{ext}" + candidate = ctx["base"] / f"{stem}{ext}" if candidate.is_file(): return file_uri_for_local_path(candidate) @@ -556,10 +543,6 @@ def populate_rom_specific_paths( destination path for local media that the handler surfaced a URL for. Currently just covers video. """ - from config.config_manager import MetadataMediaType - from handler.filesystem import fs_resource_handler - from handler.metadata.ss_handler import get_preferred_media_types - if MetadataMediaType.VIDEO in get_preferred_media_types() and metadata.get( "video_url" ): diff --git a/backend/handler/metadata/launchbox_handler/remote_source.py b/backend/handler/metadata/launchbox_handler/remote_source.py index 121c2c126..3952cdca9 100644 --- a/backend/handler/metadata/launchbox_handler/remote_source.py +++ b/backend/handler/metadata/launchbox_handler/remote_source.py @@ -78,17 +78,28 @@ class RemoteSource: 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 `` records by `` (e.g. - `pacman.zip`). The entry carries `Description` — the full title to - search for in Metadata.xml. + LaunchBox's Mame.xml indexes `` records by `` — the + MAME short name without an extension (e.g. `wrlok_l3` for `wrlok_l3.zip`). + The entry carries `` — the full title to search for in Metadata.xml. """ file_name_clean = (file_name or "").strip() if not file_name_clean: return None - entry = await async_cache.hget(LAUNCHBOX_MAME_KEY, file_name_clean) - if not entry: - return None - return json.loads(entry) + + # 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, diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index e1565275e..3e475bf4b 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -29,6 +29,7 @@ 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 @@ -635,10 +636,6 @@ async def scan_rom( metadata = launchbox_rom.get("launchbox_metadata") if metadata: - from handler.metadata.launchbox_handler.media import ( - populate_rom_specific_paths, - ) - populate_rom_specific_paths(metadata, rom) return launchbox_rom diff --git a/backend/tests/handler/metadata/test_launchbox_handler.py b/backend/tests/handler/metadata/test_launchbox_handler.py index cdd27e808..fdb972935 100644 --- a/backend/tests/handler/metadata/test_launchbox_handler.py +++ b/backend/tests/handler/metadata/test_launchbox_handler.py @@ -542,10 +542,12 @@ class TestRemoteSourceGetMameEntry: 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 `` as the full title. mame_entry = { - "FileName": "pacman.zip", - "GameName": "pacman", - "Description": "Pac-Man", + "FileName": "wrlok_l3", + "Name": "Warlok", + "Year": "1982", } with patch.object( async_cache, @@ -553,8 +555,26 @@ class TestRemoteSourceGetMameEntry: new_callable=AsyncMock, return_value=json.dumps(mame_entry), ) as mock_hget: - result = await source.get_mame_entry("pacman.zip") - mock_hget.assert_called_once_with(LAUNCHBOX_MAME_KEY, "pacman.zip") + 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): @@ -565,8 +585,9 @@ class TestRemoteSourceGetMameEntry: with patch.object( async_cache, "hget", new_callable=AsyncMock, return_value=None ) as mock_hget: - await source.get_mame_entry(" pacman.zip ") - mock_hget.assert_called_once_with(LAUNCHBOX_MAME_KEY, "pacman.zip") + 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: @@ -772,7 +793,7 @@ class TestPopulateRomSpecificPaths: def test_no_video_url_is_noop(self): metadata: LaunchboxMetadata = {"first_release_date": None, "images": []} with patch( - "handler.metadata.ss_handler.get_preferred_media_types" + "handler.metadata.launchbox_handler.media.get_preferred_media_types" ) as mock_preferred: from config.config_manager import MetadataMediaType @@ -787,7 +808,7 @@ class TestPopulateRomSpecificPaths: "video_url": "launchbox-file://Videos/NES/Mario.mp4", } with patch( - "handler.metadata.ss_handler.get_preferred_media_types" + "handler.metadata.launchbox_handler.media.get_preferred_media_types" ) as mock_preferred: from config.config_manager import MetadataMediaType @@ -804,7 +825,7 @@ class TestPopulateRomSpecificPaths: "video_url": "launchbox-file://Videos/NES/Mario.mp4", } with patch( - "handler.metadata.ss_handler.get_preferred_media_types" + "handler.metadata.launchbox_handler.media.get_preferred_media_types" ) as mock_preferred: mock_preferred.return_value = [] populate_rom_specific_paths(metadata, self._rom()) @@ -1146,12 +1167,8 @@ class TestLaunchboxHandlerGetRom: async def test_arcade_mame_resolves_shortname_to_full_title( self, handler: LaunchboxHandler ): - mame_entry = { - "FileName": "pacman.zip", - "GameName": "pacman", - "Description": "Pac-Man", - } - remote_entry = {"DatabaseID": "999", "Name": "Pac-Man"} + mame_entry = {"FileName": "wrlok_l3", "Name": "Warlok"} + remote_entry = {"DatabaseID": "999", "Name": "Warlok"} with ( patch.object( handler._remote, @@ -1167,13 +1184,13 @@ class TestLaunchboxHandlerGetRom: "handler.metadata.launchbox_handler.handler.fs_rom_handler" ) as mock_fs, ): - mock_fs.get_file_name_with_no_tags.return_value = "pacman" - result = await handler.get_rom("pacman.zip", "arcade") + 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("pacman.zip") - # search term should be the MAME Description, lowercased - assert mock_get_rom.call_args.args[0] == "pac-man" - assert result.get("name", None) == "Pac-Man" + 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( @@ -1189,22 +1206,18 @@ class TestLaunchboxHandlerGetRom: "handler.metadata.launchbox_handler.handler.fs_rom_handler" ) as mock_fs, ): - mock_fs.get_file_name_with_no_tags.return_value = "pacman" - result = await handler.get_rom("pacman.zip", "arcade") + 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("pacman.zip") + 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 description as the rom name. - mame_entry = { - "FileName": "pacman.zip", - "GameName": "pacman", - "Description": "Pac-Man", - } + # the MAME name as the rom name. + mame_entry = {"FileName": "wrlok_l3", "Name": "Warlok"} with ( patch.object( handler._remote, @@ -1215,11 +1228,11 @@ class TestLaunchboxHandlerGetRom: "handler.metadata.launchbox_handler.handler.fs_rom_handler" ) as mock_fs, ): - mock_fs.get_file_name_with_no_tags.return_value = "pacman" - result = await handler.get_rom("pacman.zip", "arcade") + 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) == "Pac-Man" + assert result.get("name", None) == "Warlok" async def test_non_arcade_platform_skips_mame_lookup( self, handler: LaunchboxHandler @@ -1232,8 +1245,8 @@ class TestLaunchboxHandlerGetRom: "handler.metadata.launchbox_handler.handler.fs_rom_handler" ) as mock_fs, ): - mock_fs.get_file_name_with_no_tags.return_value = "pacman" - await handler.get_rom("pacman.zip", "nes") + 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() From 91d69282813201fc8e38a00cce353c8007861529 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 18 Apr 2026 14:40:36 -0400 Subject: [PATCH 006/186] Lift LaunchBox video extensions to module constant Co-Authored-By: Claude Opus 4.7 (1M context) --- backend/handler/metadata/launchbox_handler/media.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/backend/handler/metadata/launchbox_handler/media.py b/backend/handler/metadata/launchbox_handler/media.py index eadcb8472..1760d5e98 100644 --- a/backend/handler/metadata/launchbox_handler/media.py +++ b/backend/handler/metadata/launchbox_handler/media.py @@ -30,6 +30,8 @@ from .utils import ( sanitize_filename, ) +VIDEO_EXTS: tuple[str, ...] = (".mp4", ".webm", ".avi", ".mkv", ".mov", ".wmv") + def local_media_req( *, @@ -353,9 +355,8 @@ def _get_video(req: MediaRequest) -> str | None: if ctx is None: return None - video_exts = (".mp4", ".webm", ".avi", ".mkv", ".mov", ".wmv") for stem in ctx["stems"]: - for ext in video_exts: + for ext in VIDEO_EXTS: candidate = ctx["base"] / f"{stem}{ext}" if candidate.is_file(): return file_uri_for_local_path(candidate) From 2498ecf729c4914dfacf2ff881c720e12c09f0da Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 29 Apr 2026 12:39:47 +0000 Subject: [PATCH 008/186] fix: store chunk uploads under ROMM_BASE_PATH and show upload speed in UI Agent-Logs-Url: https://github.com/rommapp/romm/sessions/2f626cb9-e564-4764-b9e9-3de396e3e7ca Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com> --- backend/endpoints/roms/upload.py | 7 +++++-- frontend/src/services/api/rom.ts | 7 ++++++- frontend/src/stores/upload.ts | 2 ++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/backend/endpoints/roms/upload.py b/backend/endpoints/roms/upload.py index c28232927..883dadb63 100644 --- a/backend/endpoints/roms/upload.py +++ b/backend/endpoints/roms/upload.py @@ -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 diff --git a/frontend/src/services/api/rom.ts b/frontend/src/services/api/rom.ts index f218b545b..8a983fe4e 100644 --- a/frontend/src/services/api/rom.ts +++ b/frontend/src/services/api/rom.ts @@ -67,7 +67,12 @@ async function uploadRomChunked({ onUploadProgress: (progressEvent: AxiosProgressEvent) => { const chunkFraction = progressEvent.progress ?? 0; const overall = ((i + chunkFraction) / totalChunks) * 100; - uploadStore.updateChunkProgress(file.name, overall, file.size); + uploadStore.updateChunkProgress( + file.name, + overall, + file.size, + progressEvent.rate, + ); }, }); lastError = null; diff --git a/frontend/src/stores/upload.ts b/frontend/src/stores/upload.ts index 974f1346f..1b885e2b1 100644 --- a/frontend/src/stores/upload.ts +++ b/frontend/src/stores/upload.ts @@ -47,6 +47,7 @@ export default defineStore("upload", { filename: string, overallPercent: number, totalBytes: number, + rate?: number, ) { const file = this.files.find((f) => f.filename === filename); if (!file) return; @@ -54,6 +55,7 @@ export default defineStore("upload", { file.progress = overallPercent; file.total = totalBytes; file.loaded = (overallPercent / 100) * totalBytes; + file.rate = rate ?? file.rate; file.finished = overallPercent >= 100; }, fail(filename: string, reason: string) { From eb842bd9523d98513f9cc358c2c2f59e9e26e033 Mon Sep 17 00:00:00 2001 From: Julien Loir <6706489+Namaneo@users.noreply.github.com> Date: Wed, 29 Apr 2026 15:08:30 +0200 Subject: [PATCH 009/186] Fix: UI settings not woking after switching pages back and forth --- frontend/src/composables/useUISettings.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/composables/useUISettings.ts b/frontend/src/composables/useUISettings.ts index e8150b6cb..c901e0d32 100644 --- a/frontend/src/composables/useUISettings.ts +++ b/frontend/src/composables/useUISettings.ts @@ -1,7 +1,7 @@ import { useLocalStorage } from "@vueuse/core"; import type { RemovableRef } from "@vueuse/core"; import { storeToRefs } from "pinia"; -import { watch, ref } from "vue"; +import { effectScope, watch, ref } from "vue"; import type { UserSchema } from "@/__generated__"; import userApi from "@/services/api/user"; import storeAuth from "@/stores/auth"; @@ -173,7 +173,7 @@ function createUISettings() { export function useUISettings() { // Return singleton instance if (!uiSettingsInstance) { - uiSettingsInstance = createUISettings(); + uiSettingsInstance = effectScope(true).run(createUISettings)!; } return uiSettingsInstance; } From 80b5fdf21f5d7fcc4de4640791fd903485daee6f Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 29 Apr 2026 16:42:12 +0000 Subject: [PATCH 010/186] fix: add periodic janitor to clean up orphaned upload tmp directories Agent-Logs-Url: https://github.com/rommapp/romm/sessions/2e55dd7f-d99d-48a2-ae15-0b8c4817cc6e Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com> --- backend/startup.py | 2 + backend/tasks/scheduled/cleanup_upload_tmp.py | 46 ++++++++++ .../tests/tasks/test_cleanup_upload_tmp.py | 87 +++++++++++++++++++ 3 files changed, 135 insertions(+) create mode 100644 backend/tasks/scheduled/cleanup_upload_tmp.py create mode 100644 backend/tests/tasks/test_cleanup_upload_tmp.py diff --git a/backend/startup.py b/backend/startup.py index 9181960ad..c009f4264 100644 --- a/backend/startup.py +++ b/backend/startup.py @@ -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") diff --git a/backend/tasks/scheduled/cleanup_upload_tmp.py b/backend/tasks/scheduled/cleanup_upload_tmp.py new file mode 100644 index 000000000..e4fea374a --- /dev/null +++ b/backend/tasks/scheduled/cleanup_upload_tmp.py @@ -0,0 +1,46 @@ +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() diff --git a/backend/tests/tasks/test_cleanup_upload_tmp.py b/backend/tests/tasks/test_cleanup_upload_tmp.py new file mode 100644 index 000000000..95c6b7746 --- /dev/null +++ b/backend/tests/tasks/test_cleanup_upload_tmp.py @@ -0,0 +1,87 @@ +import time +from pathlib import Path + +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() From 832447bbb19be9d644c26ddc942dcdddd8d61b8d Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 29 Apr 2026 14:30:48 -0400 Subject: [PATCH 011/186] rnu fmt --- backend/tasks/scheduled/cleanup_upload_tmp.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/tasks/scheduled/cleanup_upload_tmp.py b/backend/tasks/scheduled/cleanup_upload_tmp.py index e4fea374a..f55c90669 100644 --- a/backend/tasks/scheduled/cleanup_upload_tmp.py +++ b/backend/tasks/scheduled/cleanup_upload_tmp.py @@ -40,7 +40,9 @@ class CleanupUploadTmpTask(PeriodicTask): pass if removed: - log.info(f"Cleaned up {removed} orphaned upload tmp director{'y' if removed == 1 else 'ies'}") + log.info( + f"Cleaned up {removed} orphaned upload tmp director{'y' if removed == 1 else 'ies'}" + ) cleanup_upload_tmp_task = CleanupUploadTmpTask() From aee17e51d541fb2d283ed5485e04c038dd2d03fc Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 29 Apr 2026 14:43:37 -0400 Subject: [PATCH 012/186] fix --- backend/tests/tasks/test_cleanup_upload_tmp.py | 1 - 1 file changed, 1 deletion(-) diff --git a/backend/tests/tasks/test_cleanup_upload_tmp.py b/backend/tests/tasks/test_cleanup_upload_tmp.py index 95c6b7746..2a833fd31 100644 --- a/backend/tests/tasks/test_cleanup_upload_tmp.py +++ b/backend/tests/tasks/test_cleanup_upload_tmp.py @@ -1,5 +1,4 @@ import time -from pathlib import Path import pytest From af870e0278b0b358116da057a539d192ba7281a1 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 29 Apr 2026 19:31:13 +0000 Subject: [PATCH 014/186] fix: replace deprecated job.get_id() with job.id for rq >= 2.7.0 compatibility Agent-Logs-Url: https://github.com/rommapp/romm/sessions/4326c200-57f5-4a27-96e8-570df82968e5 Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com> --- backend/endpoints/tasks.py | 4 ++-- pyproject.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/endpoints/tasks.py b/backend/endpoints/tasks.py index e1c1303f4..40b6ba432 100644 --- a/backend/endpoints/tasks.py +++ b/backend/endpoints/tasks.py @@ -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() diff --git a/pyproject.toml b/pyproject.toml index 62958e0bf..36dc4f3d9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,7 +43,7 @@ dependencies = [ "python-magic ~= 0.4", "python-socketio ~= 5.11", "redis ~= 6.2", - "rq ~= 2.1", + "rq >= 2.1", # TODO: Move back to upstream `rq-scheduler`, when support for username and SSL settings is added. # Related PR: https://github.com/rq/rq-scheduler/pull/325 "rq-scheduler @ git+https://github.com/adamantike/rq-scheduler.git@feat/script-options-username-ssl", From bffde45f2b1d1c611922c1607ba6de7af136771c Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 29 Apr 2026 19:38:26 +0000 Subject: [PATCH 015/186] fix: bump rq minimum version to 2.7 in pyproject.toml Agent-Logs-Url: https://github.com/rommapp/romm/sessions/efd0c66d-f72c-4e62-a976-4f2c3deb3608 Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com> --- pyproject.toml | 2 +- uv.lock | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 36dc4f3d9..2935cdf51 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,7 +43,7 @@ dependencies = [ "python-magic ~= 0.4", "python-socketio ~= 5.11", "redis ~= 6.2", - "rq >= 2.1", + "rq ~= 2.7", # TODO: Move back to upstream `rq-scheduler`, when support for username and SSL settings is added. # Related PR: https://github.com/rq/rq-scheduler/pull/325 "rq-scheduler @ git+https://github.com/adamantike/rq-scheduler.git@feat/script-options-username-ssl", diff --git a/uv.lock b/uv.lock index fe2570660..b300511cf 100644 --- a/uv.lock +++ b/uv.lock @@ -7,7 +7,7 @@ resolution-markers = [ ] [options] -exclude-newer = "2026-04-15T23:26:03.241937662Z" +exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values. exclude-newer-span = "P7D" [[package]] @@ -2238,7 +2238,7 @@ requires-dist = [ { name = "python-socketio", specifier = "~=5.11" }, { name = "pyyaml", specifier = "~=6.0" }, { name = "redis", specifier = "~=6.2" }, - { name = "rq", specifier = "~=2.1" }, + { name = "rq", specifier = ">=2.1" }, { name = "rq-scheduler", git = "https://github.com/adamantike/rq-scheduler.git?rev=feat%2Fscript-options-username-ssl" }, { name = "sentry-sdk", specifier = "~=2.32" }, { name = "sqlalchemy", extras = ["mariadb-connector", "mysql-connector", "postgresql-psycopg"], specifier = "~=2.0" }, From 98b6d17e4fea45cd5b23cc9be92409dc84d12ea7 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 29 Apr 2026 15:41:39 -0400 Subject: [PATCH 016/186] fix lock --- uv.lock | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/uv.lock b/uv.lock index b300511cf..e84a4a0a4 100644 --- a/uv.lock +++ b/uv.lock @@ -7,7 +7,7 @@ resolution-markers = [ ] [options] -exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values. +exclude-newer = "2026-04-22T19:41:29.076564Z" exclude-newer-span = "P7D" [[package]] @@ -441,6 +441,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/3c/38/bbe2e63902847cf79036ecc75550d0698af31c91c7575352eb25190d0fb3/coverage-7.9.2-py3-none-any.whl", hash = "sha256:e425cd5b00f6fc0ed7cdbd766c70be8baab4b7839e4d4fe5fac48581dd968ea4", size = 204005, upload-time = "2025-07-03T10:54:13.491Z" }, ] +[[package]] +name = "croniter" +version = "6.2.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/de/5832661ed55107b8a09af3f0a2e71e0957226a59eb1dcf0a445cce6daf20/croniter-6.2.2.tar.gz", hash = "sha256:ba60832a5ec8e12e51b8691c3309a113d1cf6526bdf1a48150ce8ec7a532d0ab", size = 113762, upload-time = "2026-03-15T08:43:48.112Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d0/39/783980e78cb92c2d7bdb1fc7dbc86e94ccc6d58224d76a7f1f51b6c51e30/croniter-6.2.2-py3-none-any.whl", hash = "sha256:a5d17b1060974d36251ea4faf388233eca8acf0d09cbd92d35f4c4ac8f279960", size = 45422, upload-time = "2026-03-15T08:43:46.626Z" }, +] + [[package]] name = "crontab" version = "1.0.4" @@ -2238,7 +2250,7 @@ requires-dist = [ { name = "python-socketio", specifier = "~=5.11" }, { name = "pyyaml", specifier = "~=6.0" }, { name = "redis", specifier = "~=6.2" }, - { name = "rq", specifier = ">=2.1" }, + { name = "rq", specifier = "~=2.7" }, { name = "rq-scheduler", git = "https://github.com/adamantike/rq-scheduler.git?rev=feat%2Fscript-options-username-ssl" }, { name = "sentry-sdk", specifier = "~=2.32" }, { name = "sqlalchemy", extras = ["mariadb-connector", "mysql-connector", "postgresql-psycopg"], specifier = "~=2.0" }, @@ -2261,15 +2273,16 @@ provides-extras = ["dev", "test"] [[package]] name = "rq" -version = "2.4.0" +version = "2.8.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "click" }, + { name = "croniter" }, { name = "redis" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/83/f2/af00f6c89131ccd8dfe408e75ea631fd0c572785d7d69701b0a656171da0/rq-2.4.0.tar.gz", hash = "sha256:750bab5dbb7cf1ec8a0aa2ebe8949472fa58fc121afd446c7bf5f7797f5e0655", size = 661530, upload-time = "2025-06-14T03:57:49.795Z" } +sdist = { url = "https://files.pythonhosted.org/packages/39/91/cdb1517255b28fdaa44d0377caa810524e6a38d24373e5ef3911b04e4228/rq-2.8.0.tar.gz", hash = "sha256:dd75b5a19016efd235143058e82fdc5658a0c1e9a76664cc7d02f721c7308a4a", size = 743395, upload-time = "2026-04-17T00:21:13.734Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/34/ef/4239a17f056ad7a864d53fec920886e017cf50c1494ee8ab05d44cc46799/rq-2.4.0-py3-none-any.whl", hash = "sha256:4b854d27ad0d9687b9e6f686e001a3043807694ace5340a3f9697b42c6a9c65a", size = 106353, upload-time = "2025-06-14T03:57:47.926Z" }, + { url = "https://files.pythonhosted.org/packages/3c/07/9a8c6ac2440f8e532260adaa3fe4a8f7edfcac4f038f3428e71cb32e13e2/rq-2.8.0-py3-none-any.whl", hash = "sha256:49d87c8d0068b890e83052050ffd18be328339ae00c9c6d5dbf2702eb06107d2", size = 119484, upload-time = "2026-04-17T00:21:11.513Z" }, ] [[package]] From ee1faf363c6f6f013bd78be8e4921d04d8986880 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 29 Apr 2026 19:57:57 +0000 Subject: [PATCH 017/186] fix: update test mocks to use job.id attribute instead of get_id() Agent-Logs-Url: https://github.com/rommapp/romm/sessions/f053983a-ae39-44b3-a59d-083d65f2055d Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com> --- backend/tests/endpoints/test_tasks.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/tests/endpoints/test_tasks.py b/backend/tests/endpoints/test_tasks.py index cc53ce1c6..d9b3eeaae 100644 --- a/backend/tests/endpoints/test_tasks.py +++ b/backend/tests/endpoints/test_tasks.py @@ -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 From 5063ce5e5746a7da8e59170bb646af7445383f5a Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 29 Apr 2026 16:23:48 -0400 Subject: [PATCH 018/186] fix backend arch --- docs/BACKEND_ARCHITECTURE.md | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index 86d37943a..cc3c43ffb 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -1562,15 +1562,14 @@ Falls back to `FakeRedis` in test mode. #### 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`) From 339c0083752c18e8e737f89802c15283e7292c86 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 29 Apr 2026 20:25:31 +0000 Subject: [PATCH 019/186] chore(deps): bump postcss from 8.5.8 to 8.5.12 in /frontend Bumps [postcss](https://github.com/postcss/postcss) from 8.5.8 to 8.5.12. - [Release notes](https://github.com/postcss/postcss/releases) - [Changelog](https://github.com/postcss/postcss/blob/main/CHANGELOG.md) - [Commits](https://github.com/postcss/postcss/compare/8.5.8...8.5.12) --- updated-dependencies: - dependency-name: postcss dependency-version: 8.5.12 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- frontend/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/frontend/package-lock.json b/frontend/package-lock.json index f1e721217..f63272b52 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -7920,9 +7920,9 @@ } }, "node_modules/postcss": { - "version": "8.5.8", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", - "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", + "version": "8.5.12", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.12.tgz", + "integrity": "sha512-W62t/Se6rA0Az3DfCL0AqJwXuKwBeYg6nOaIgzP+xZ7N5BFCI7DYi1qs6ygUYT6rvfi6t9k65UMLJC+PHZpDAA==", "funding": [ { "type": "opencollective", From 96c3634b8002fa75cd2ab5be8ac8212240eed25d Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 30 Apr 2026 12:52:22 -0400 Subject: [PATCH 020/186] refactor: split HIGH_PRIO_STRUCTURE_PATH into STRUCTURE_PATH_A/B Replace the single HIGH_PRIO_STRUCTURE_PATH config attribute with two glob patterns (STRUCTURE_PATH_A = roms/*, STRUCTURE_PATH_B = */roms) and update all call sites to detect Structure B via glob.glob, defaulting to Structure A when no match is found. Co-Authored-By: Claude Opus 4.7 (1M context) --- backend/config/config_manager.py | 6 ++++-- backend/handler/filesystem/firmware_handler.py | 7 ++++--- backend/handler/filesystem/platforms_handler.py | 13 +++++-------- backend/handler/filesystem/roms_handler.py | 7 ++++--- backend/watcher.py | 4 +++- 5 files changed, 20 insertions(+), 17 deletions(-) diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index da7be7e7b..37dea145d 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -114,7 +114,8 @@ class Config: ROMS_FOLDER_NAME: str FIRMWARE_FOLDER_NAME: str SKIP_HASH_CALCULATION: bool - HIGH_PRIO_STRUCTURE_PATH: str + STRUCTURE_PATH_A: str + STRUCTURE_PATH_B: str EJS_DEBUG: bool EJS_CACHE_LIMIT: int | None EJS_DISABLE_AUTO_UNLOAD: bool @@ -133,7 +134,8 @@ class Config: def __init__(self, **entries): self.__dict__.update(entries) - self.HIGH_PRIO_STRUCTURE_PATH = f"{LIBRARY_BASE_PATH}/{self.ROMS_FOLDER_NAME}" + self.STRUCTURE_PATH_A = f"{LIBRARY_BASE_PATH}/{self.ROMS_FOLDER_NAME}/*" + self.STRUCTURE_PATH_B = f"{LIBRARY_BASE_PATH}/*/{self.ROMS_FOLDER_NAME}" class ConfigManager: diff --git a/backend/handler/filesystem/firmware_handler.py b/backend/handler/filesystem/firmware_handler.py index 1d52a61a9..ef6d8e6da 100644 --- a/backend/handler/filesystem/firmware_handler.py +++ b/backend/handler/filesystem/firmware_handler.py @@ -1,4 +1,5 @@ import binascii +import glob import hashlib import os @@ -17,9 +18,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 glob.glob(cnfg.STRUCTURE_PATH_B) + else f"{cnfg.FIRMWARE_FOLDER_NAME}/{fs_slug}" ) async def get_firmware(self, platform_fs_slug: str): diff --git a/backend/handler/filesystem/platforms_handler.py b/backend/handler/filesystem/platforms_handler.py index 8f981ef6c..ea1019f67 100644 --- a/backend/handler/filesystem/platforms_handler.py +++ b/backend/handler/filesystem/platforms_handler.py @@ -1,3 +1,4 @@ +import glob import os from anyio import Path as AnyioPath @@ -62,20 +63,16 @@ class FSPlatformsHandler(FSHandler): 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 glob.glob(cnfg.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 glob.glob(cnfg.STRUCTURE_PATH_B) + else f"{cnfg.ROMS_FOLDER_NAME}/{fs_slug}" ) async def add_platform(self, fs_slug: str) -> None: diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 0e2832099..ef6561462 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -1,6 +1,7 @@ import binascii import bz2 import fnmatch +import glob import hashlib import os import re @@ -313,9 +314,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 glob.glob(cnfg.STRUCTURE_PATH_B) + else f"{cnfg.ROMS_FOLDER_NAME}/{fs_slug}" ) def parse_tags(self, fs_name: str) -> ParsedTags: diff --git a/backend/watcher.py b/backend/watcher.py index 4c72d22ee..80675c20b 100644 --- a/backend/watcher.py +++ b/backend/watcher.py @@ -1,5 +1,6 @@ import enum import fnmatch +import glob import json import os from collections.abc import Sequence @@ -49,7 +50,8 @@ sentry_sdk.init( ) tracer = trace.get_tracer(__name__) -structure_level = 2 if os.path.exists(cm.get_config().HIGH_PRIO_STRUCTURE_PATH) else 1 +_cfg = cm.get_config() +structure_level = 1 if glob.glob(_cfg.STRUCTURE_PATH_B) else 2 @enum.unique From 0e7359132bbc61a2bf33b89d37f91df129615274 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 30 Apr 2026 14:00:53 -0400 Subject: [PATCH 021/186] test: update fs handler tests for STRUCTURE_PATH_A/B refactor Switch the get_platform_fs_structure, get_firmware_fs_structure, get_platforms_directory and get_roms_fs_structure tests from mocking os.path.exists to mocking glob.glob, matching the new STRUCTURE_PATH_B detection logic. Rename the existing high_priority/normal_structure variants to structure_a/structure_b for clarity, and fix test_platform_specific_behavior so its monkeypatch wraps the calls instead of being applied after them. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../filesystem/test_firmware_handler.py | 32 +++++++-- .../filesystem/test_platforms_handler.py | 70 +++++++++++++------ .../handler/filesystem/test_roms_handler.py | 44 +++++++----- 3 files changed, 101 insertions(+), 45 deletions(-) diff --git a/backend/tests/handler/filesystem/test_firmware_handler.py b/backend/tests/handler/filesystem/test_firmware_handler.py index ab6981840..23143be1b 100644 --- a/backend/tests/handler/filesystem/test_firmware_handler.py +++ b/backend/tests/handler/filesystem/test_firmware_handler.py @@ -138,16 +138,38 @@ 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" 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}" + with patch( + "handler.filesystem.firmware_handler.glob.glob", return_value=[] + ): + 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" + + with patch( + "handler.filesystem.firmware_handler.cm.get_config", return_value=config + ): + with patch( + "handler.filesystem.firmware_handler.glob.glob", + return_value=[ + f"{LIBRARY_BASE_PATH}/{platform_fs_slug}/{config.ROMS_FOLDER_NAME}" + ], + ): + path = handler.get_firmware_fs_structure(platform_fs_slug) + assert path == f"{platform_fs_slug}/{config.FIRMWARE_FOLDER_NAME}" async def test_multiple_platform_handling(self, handler: FSFirmwareHandler, config): """Test handling of different platform slugs""" diff --git a/backend/tests/handler/filesystem/test_platforms_handler.py b/backend/tests/handler/filesystem/test_platforms_handler.py index 091305a06..a302cabc3 100644 --- a/backend/tests/handler/filesystem/test_platforms_handler.py +++ b/backend/tests/handler/filesystem/test_platforms_handler.py @@ -86,77 +86,98 @@ 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})""" with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): - with patch("os.path.exists", return_value=True): + with patch( + "handler.filesystem.platforms_handler.glob.glob", return_value=[] + ): 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)""" with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): - with patch("os.path.exists", return_value=False): + with patch( + "handler.filesystem.platforms_handler.glob.glob", + return_value=[f"{LIBRARY_BASE_PATH}/n64/{config.ROMS_FOLDER_NAME}"], + ): 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" with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): - with patch("os.path.exists", return_value=True): + with patch( + "handler.filesystem.platforms_handler.glob.glob", return_value=[] + ): 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" with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): - result = handler.get_platform_fs_structure(fs_slug) - assert result == f"{fs_slug}/{config.ROMS_FOLDER_NAME}" + with patch( + "handler.filesystem.platforms_handler.glob.glob", + return_value=[ + f"{LIBRARY_BASE_PATH}/{fs_slug}/{config.ROMS_FOLDER_NAME}" + ], + ): + result = handler.get_platform_fs_structure(fs_slug) + assert result == f"{fs_slug}/{config.ROMS_FOLDER_NAME}" 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" with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config_custom_folder, ): - result = handler.get_platform_fs_structure(fs_slug) - assert result == f"{fs_slug}/{config_custom_folder.ROMS_FOLDER_NAME}" + with patch( + "handler.filesystem.platforms_handler.glob.glob", + return_value=[ + f"{LIBRARY_BASE_PATH}/{fs_slug}/{config_custom_folder.ROMS_FOLDER_NAME}" + ], + ): + result = handler.get_platform_fs_structure(fs_slug) + assert result == f"{fs_slug}/{config_custom_folder.ROMS_FOLDER_NAME}" 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}" with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): - with patch("os.path.exists", return_value=True): + with patch( + "handler.filesystem.platforms_handler.glob.glob", return_value=[] + ): 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) @@ -164,14 +185,19 @@ class TestFSPlatformsHandler: 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}" with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): - with patch("os.path.exists", return_value=False): + with patch( + "handler.filesystem.platforms_handler.glob.glob", + return_value=[ + f"{LIBRARY_BASE_PATH}/{fs_slug}/{config.ROMS_FOLDER_NAME}" + ], + ): 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) @@ -207,7 +233,9 @@ class TestFSPlatformsHandler: with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): - with patch("os.path.exists", return_value=True): + with patch( + "handler.filesystem.platforms_handler.glob.glob", return_value=[] + ): with patch.object( handler, "list_directories", return_value=[] ) as mock_list: diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index f393006b5..a882827a0 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -102,8 +102,8 @@ 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" with pytest.MonkeyPatch.context() as m: @@ -122,15 +122,16 @@ class TestFSRomsHandler: FIRMWARE_FOLDER_NAME="bios", ), ) - m.setattr("os.path.exists", lambda x: False) # Simulate normal structure + m.setattr( + "handler.filesystem.roms_handler.glob.glob", + lambda _: [f"{LIBRARY_BASE_PATH}/{fs_slug}/roms"], + ) 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" with pytest.MonkeyPatch.context() as m: @@ -149,9 +150,7 @@ class TestFSRomsHandler: FIRMWARE_FOLDER_NAME="bios", ), ) - m.setattr( - "os.path.exists", lambda x: True - ) # Simulate high priority structure + m.setattr("handler.filesystem.roms_handler.glob.glob", lambda _: []) result = handler.get_roms_fs_structure(fs_slug) assert result == f"roms/{fs_slug}" @@ -521,12 +520,16 @@ 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) - with pytest.MonkeyPatch.context() as m: - m.setattr("os.path.exists", lambda x: False) # Normal structure + m.setattr( + "handler.filesystem.roms_handler.glob.glob", + lambda _: [f"{LIBRARY_BASE_PATH}/n64/roms"], + ) # Structure B + + 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" @@ -553,14 +556,17 @@ class TestFSRomsHandler: fs_slug = "gba" with pytest.MonkeyPatch.context() as m: - # Test with normal structure - m.setattr("os.path.exists", lambda x: False) + # Test with Structure B + m.setattr( + "handler.filesystem.roms_handler.glob.glob", + lambda _: [f"{LIBRARY_BASE_PATH}/{fs_slug}/roms"], + ) 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 + m.setattr("handler.filesystem.roms_handler.glob.glob", lambda _: []) structure = handler.get_roms_fs_structure(fs_slug) assert structure == f"roms/{fs_slug}" From fc8d69dc0c9745c194de7f1d68c04efb423b0158 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 30 Apr 2026 14:18:49 -0400 Subject: [PATCH 022/186] update tests --- backend/config/config_manager.py | 10 +++ .../handler/filesystem/firmware_handler.py | 3 +- .../handler/filesystem/platforms_handler.py | 5 +- backend/handler/filesystem/roms_handler.py | 3 +- .../filesystem/test_firmware_handler.py | 19 ++-- .../filesystem/test_platforms_handler.py | 87 +++++++------------ .../handler/filesystem/test_roms_handler.py | 85 ++++++++---------- backend/watcher.py | 5 +- env.template | 2 +- 9 files changed, 89 insertions(+), 130 deletions(-) diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index 37dea145d..cca771065 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -1,4 +1,6 @@ import enum +import functools +import glob import json import os import sys @@ -137,6 +139,14 @@ class Config: self.STRUCTURE_PATH_A = f"{LIBRARY_BASE_PATH}/{self.ROMS_FOLDER_NAME}/*" self.STRUCTURE_PATH_B = f"{LIBRARY_BASE_PATH}/*/{self.ROMS_FOLDER_NAME}" + @functools.cached_property + def has_structure_b(self) -> bool: + """True when any `///` directory exists.""" + for match in glob.iglob(self.STRUCTURE_PATH_B): + if os.path.isdir(match): + return True + return False + class ConfigManager: """ diff --git a/backend/handler/filesystem/firmware_handler.py b/backend/handler/filesystem/firmware_handler.py index ef6d8e6da..c0ac7daf4 100644 --- a/backend/handler/filesystem/firmware_handler.py +++ b/backend/handler/filesystem/firmware_handler.py @@ -1,5 +1,4 @@ import binascii -import glob import hashlib import os @@ -19,7 +18,7 @@ class FSFirmwareHandler(FSHandler): cnfg = cm.get_config() return ( f"{fs_slug}/{cnfg.FIRMWARE_FOLDER_NAME}" - if glob.glob(cnfg.STRUCTURE_PATH_B) + if cnfg.has_structure_b else f"{cnfg.FIRMWARE_FOLDER_NAME}/{fs_slug}" ) diff --git a/backend/handler/filesystem/platforms_handler.py b/backend/handler/filesystem/platforms_handler.py index ea1019f67..c20c3632f 100644 --- a/backend/handler/filesystem/platforms_handler.py +++ b/backend/handler/filesystem/platforms_handler.py @@ -1,4 +1,3 @@ -import glob import os from anyio import Path as AnyioPath @@ -63,7 +62,7 @@ class FSPlatformsHandler(FSHandler): cnfg = cm.get_config() # Fallback to config hint when detection is inconclusive - return "" if glob.glob(cnfg.STRUCTURE_PATH_B) else cnfg.ROMS_FOLDER_NAME + return "" if cnfg.has_structure_b else cnfg.ROMS_FOLDER_NAME def get_platform_fs_structure(self, fs_slug: str) -> str: cnfg = cm.get_config() @@ -71,7 +70,7 @@ class FSPlatformsHandler(FSHandler): # Fallback to config hint when detection is inconclusive return ( f"{fs_slug}/{cnfg.ROMS_FOLDER_NAME}" - if glob.glob(cnfg.STRUCTURE_PATH_B) + if cnfg.has_structure_b else f"{cnfg.ROMS_FOLDER_NAME}/{fs_slug}" ) diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index ef6561462..af48b9a58 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -1,7 +1,6 @@ import binascii import bz2 import fnmatch -import glob import hashlib import os import re @@ -315,7 +314,7 @@ class FSRomsHandler(FSHandler): cnfg = cm.get_config() return ( f"{fs_slug}/{cnfg.ROMS_FOLDER_NAME}" - if glob.glob(cnfg.STRUCTURE_PATH_B) + if cnfg.has_structure_b else f"{cnfg.ROMS_FOLDER_NAME}/{fs_slug}" ) diff --git a/backend/tests/handler/filesystem/test_firmware_handler.py b/backend/tests/handler/filesystem/test_firmware_handler.py index 23143be1b..0e0f7523c 100644 --- a/backend/tests/handler/filesystem/test_firmware_handler.py +++ b/backend/tests/handler/filesystem/test_firmware_handler.py @@ -143,33 +143,26 @@ class TestFSFirmwareHandler: ): """Test that firmware paths are constructed correctly for Structure A""" platform_fs_slug = "n64" + config.has_structure_b = False with patch( "handler.filesystem.firmware_handler.cm.get_config", return_value=config ): - with patch( - "handler.filesystem.firmware_handler.glob.glob", return_value=[] - ): - path = handler.get_firmware_fs_structure(platform_fs_slug) - assert path == f"{config.FIRMWARE_FOLDER_NAME}/{platform_fs_slug}" + 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_b = True with patch( "handler.filesystem.firmware_handler.cm.get_config", return_value=config ): - with patch( - "handler.filesystem.firmware_handler.glob.glob", - return_value=[ - f"{LIBRARY_BASE_PATH}/{platform_fs_slug}/{config.ROMS_FOLDER_NAME}" - ], - ): - path = handler.get_firmware_fs_structure(platform_fs_slug) - assert path == f"{platform_fs_slug}/{config.FIRMWARE_FOLDER_NAME}" + path = handler.get_firmware_fs_structure(platform_fs_slug) + assert path == f"{platform_fs_slug}/{config.FIRMWARE_FOLDER_NAME}" async def test_multiple_platform_handling(self, handler: FSFirmwareHandler, config): """Test handling of different platform slugs""" diff --git a/backend/tests/handler/filesystem/test_platforms_handler.py b/backend/tests/handler/filesystem/test_platforms_handler.py index a302cabc3..24c5302ce 100644 --- a/backend/tests/handler/filesystem/test_platforms_handler.py +++ b/backend/tests/handler/filesystem/test_platforms_handler.py @@ -90,80 +90,60 @@ class TestFSPlatformsHandler: self, handler: FSPlatformsHandler, config ): """Test get_platforms_directory with Structure A (roms/{platform})""" + config.has_structure_b = False with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): - with patch( - "handler.filesystem.platforms_handler.glob.glob", return_value=[] - ): - 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_structure_b( self, handler: FSPlatformsHandler, config ): """Test get_platforms_directory with Structure B ({platform}/roms)""" + config.has_structure_b = True with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): - with patch( - "handler.filesystem.platforms_handler.glob.glob", - return_value=[f"{LIBRARY_BASE_PATH}/n64/{config.ROMS_FOLDER_NAME}"], - ): - result = handler.get_platforms_directory() - assert result == "" + result = handler.get_platforms_directory() + assert result == "" def test_get_platform_fs_structure_structure_a( self, handler: FSPlatformsHandler, config ): """Test get_platform_fs_structure with Structure A (roms/{platform})""" fs_slug = "n64" - + config.has_structure_b = False with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): - with patch( - "handler.filesystem.platforms_handler.glob.glob", return_value=[] - ): - 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_structure_b( self, handler: FSPlatformsHandler, config ): """Test get_platform_fs_structure with Structure B ({platform}/roms)""" fs_slug = "n64" - + config.has_structure_b = True with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): - with patch( - "handler.filesystem.platforms_handler.glob.glob", - return_value=[ - f"{LIBRARY_BASE_PATH}/{fs_slug}/{config.ROMS_FOLDER_NAME}" - ], - ): - result = handler.get_platform_fs_structure(fs_slug) - assert result == f"{fs_slug}/{config.ROMS_FOLDER_NAME}" + result = handler.get_platform_fs_structure(fs_slug) + assert result == f"{fs_slug}/{config.ROMS_FOLDER_NAME}" def test_get_platform_fs_structure_custom_folder_name( self, handler: FSPlatformsHandler, config_custom_folder ): """Test get_platform_fs_structure with custom folder name (Structure B)""" fs_slug = "psx" - + config_custom_folder.has_structure_b = True with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config_custom_folder, ): - with patch( - "handler.filesystem.platforms_handler.glob.glob", - return_value=[ - f"{LIBRARY_BASE_PATH}/{fs_slug}/{config_custom_folder.ROMS_FOLDER_NAME}" - ], - ): - result = handler.get_platform_fs_structure(fs_slug) - assert result == f"{fs_slug}/{config_custom_folder.ROMS_FOLDER_NAME}" + result = handler.get_platform_fs_structure(fs_slug) + assert result == f"{fs_slug}/{config_custom_folder.ROMS_FOLDER_NAME}" async def test_add_platform_creates_directory( self, handler: FSPlatformsHandler, config @@ -171,16 +151,14 @@ class TestFSPlatformsHandler: """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_b = False with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): - with patch( - "handler.filesystem.platforms_handler.glob.glob", return_value=[] - ): - 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 @@ -188,19 +166,14 @@ class TestFSPlatformsHandler: """Test that add_platform creates directory with Structure B""" fs_slug = "gba" expected_path = f"{fs_slug}/{config.ROMS_FOLDER_NAME}" + config.has_structure_b = True with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): - with patch( - "handler.filesystem.platforms_handler.glob.glob", - return_value=[ - f"{LIBRARY_BASE_PATH}/{fs_slug}/{config.ROMS_FOLDER_NAME}" - ], - ): - 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 @@ -230,17 +203,15 @@ class TestFSPlatformsHandler: self, handler: FSPlatformsHandler, config ): """Test that get_platforms calls list_directories with correct path""" + config.has_structure_b = False with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): - with patch( - "handler.filesystem.platforms_handler.glob.glob", return_value=[] - ): - 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 diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index a882827a0..4153ac5b0 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -105,27 +105,22 @@ class TestFSRomsHandler: def test_get_roms_fs_structure_structure_b(self, handler: FSRomsHandler): """Test get_roms_fs_structure with Structure B ({platform}/roms)""" fs_slug = "n64" + cfg = 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", + ) + cfg.has_structure_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( - "handler.filesystem.roms_handler.glob.glob", - lambda _: [f"{LIBRARY_BASE_PATH}/{fs_slug}/roms"], - ) + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: cfg) result = handler.get_roms_fs_structure(fs_slug) assert result == f"{fs_slug}/roms" @@ -133,24 +128,22 @@ class TestFSRomsHandler: def test_get_roms_fs_structure_structure_a(self, handler: FSRomsHandler): """Test get_roms_fs_structure with Structure A (roms/{platform})""" fs_slug = "n64" + cfg = 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", + ) + cfg.has_structure_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("handler.filesystem.roms_handler.glob.glob", lambda _: []) + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: cfg) result = handler.get_roms_fs_structure(fs_slug) assert result == f"roms/{fs_slug}" @@ -509,7 +502,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) @@ -520,11 +513,10 @@ class TestFSRomsHandler: non_hashable_platform.fs_slug = "n64" non_hashable_platform.slug = "nintendo-64" + config.has_structure_b = True + with pytest.MonkeyPatch.context() as m: - m.setattr( - "handler.filesystem.roms_handler.glob.glob", - lambda _: [f"{LIBRARY_BASE_PATH}/n64/roms"], - ) # Structure B + 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( @@ -551,23 +543,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 Structure B - m.setattr( - "handler.filesystem.roms_handler.glob.glob", - lambda _: [f"{LIBRARY_BASE_PATH}/{fs_slug}/roms"], - ) + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + # Test with Structure B + config.has_structure_b = True structure = handler.get_roms_fs_structure(fs_slug) assert structure == f"{fs_slug}/roms" # Test with Structure A - m.setattr("handler.filesystem.roms_handler.glob.glob", lambda _: []) - + config.has_structure_b = False structure = handler.get_roms_fs_structure(fs_slug) assert structure == f"roms/{fs_slug}" diff --git a/backend/watcher.py b/backend/watcher.py index 80675c20b..9234dea43 100644 --- a/backend/watcher.py +++ b/backend/watcher.py @@ -1,6 +1,5 @@ import enum import fnmatch -import glob import json import os from collections.abc import Sequence @@ -50,8 +49,8 @@ sentry_sdk.init( ) tracer = trace.get_tracer(__name__) -_cfg = cm.get_config() -structure_level = 1 if glob.glob(_cfg.STRUCTURE_PATH_B) else 2 +cfg = cm.get_config() +structure_level = 1 if cfg.has_structure_b else 2 @enum.unique diff --git a/env.template b/env.template index 7baa37177..fa9079aeb 100644 --- a/env.template +++ b/env.template @@ -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 (CORS origin, OIDC redirect base, links in container logs) ROMM_PORT=8080 # Port on which the application listens KIOSK_MODE=false # Read-only mode for public displays or kiosks From 962a9bfa7e31dad36ef29d2d07adf07154e1775e Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 30 Apr 2026 14:39:52 -0400 Subject: [PATCH 023/186] one more --- backend/config/config_manager.py | 15 ++-- .../handler/filesystem/firmware_handler.py | 2 +- .../handler/filesystem/platforms_handler.py | 27 +++---- backend/handler/filesystem/roms_handler.py | 2 +- .../filesystem/test_firmware_handler.py | 4 +- .../filesystem/test_platforms_handler.py | 78 ++++++++----------- .../handler/filesystem/test_roms_handler.py | 10 +-- backend/watcher.py | 2 +- env.template | 2 +- 9 files changed, 59 insertions(+), 83 deletions(-) diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index cca771065..53637bea7 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -116,8 +116,6 @@ class Config: ROMS_FOLDER_NAME: str FIRMWARE_FOLDER_NAME: str SKIP_HASH_CALCULATION: bool - STRUCTURE_PATH_A: str - STRUCTURE_PATH_B: str EJS_DEBUG: bool EJS_CACHE_LIMIT: int | None EJS_DISABLE_AUTO_UNLOAD: bool @@ -136,15 +134,16 @@ class Config: def __init__(self, **entries): self.__dict__.update(entries) - self.STRUCTURE_PATH_A = f"{LIBRARY_BASE_PATH}/{self.ROMS_FOLDER_NAME}/*" - self.STRUCTURE_PATH_B = f"{LIBRARY_BASE_PATH}/*/{self.ROMS_FOLDER_NAME}" @functools.cached_property - def has_structure_b(self) -> bool: + def has_structure_path_b(self) -> bool: """True when any `///` directory exists.""" - for match in glob.iglob(self.STRUCTURE_PATH_B): - if os.path.isdir(match): - return True + try: + for match in glob.iglob(f"{LIBRARY_BASE_PATH}/*/{self.ROMS_FOLDER_NAME}"): + if os.path.isdir(match): + return True + except OSError: + pass return False diff --git a/backend/handler/filesystem/firmware_handler.py b/backend/handler/filesystem/firmware_handler.py index c0ac7daf4..8422e0220 100644 --- a/backend/handler/filesystem/firmware_handler.py +++ b/backend/handler/filesystem/firmware_handler.py @@ -18,7 +18,7 @@ class FSFirmwareHandler(FSHandler): cnfg = cm.get_config() return ( f"{fs_slug}/{cnfg.FIRMWARE_FOLDER_NAME}" - if cnfg.has_structure_b + if cnfg.has_structure_path_b else f"{cnfg.FIRMWARE_FOLDER_NAME}/{fs_slug}" ) diff --git a/backend/handler/filesystem/platforms_handler.py b/backend/handler/filesystem/platforms_handler.py index c20c3632f..eed0e969a 100644 --- a/backend/handler/filesystem/platforms_handler.py +++ b/backend/handler/filesystem/platforms_handler.py @@ -34,35 +34,28 @@ 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 "" if cnfg.has_structure_b else cnfg.ROMS_FOLDER_NAME + 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() @@ -70,7 +63,7 @@ class FSPlatformsHandler(FSHandler): # Fallback to config hint when detection is inconclusive return ( f"{fs_slug}/{cnfg.ROMS_FOLDER_NAME}" - if cnfg.has_structure_b + if cnfg.has_structure_path_b else f"{cnfg.ROMS_FOLDER_NAME}/{fs_slug}" ) diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index af48b9a58..8145a1f1e 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -314,7 +314,7 @@ class FSRomsHandler(FSHandler): cnfg = cm.get_config() return ( f"{fs_slug}/{cnfg.ROMS_FOLDER_NAME}" - if cnfg.has_structure_b + if cnfg.has_structure_path_b else f"{cnfg.ROMS_FOLDER_NAME}/{fs_slug}" ) diff --git a/backend/tests/handler/filesystem/test_firmware_handler.py b/backend/tests/handler/filesystem/test_firmware_handler.py index 0e0f7523c..28472933c 100644 --- a/backend/tests/handler/filesystem/test_firmware_handler.py +++ b/backend/tests/handler/filesystem/test_firmware_handler.py @@ -143,7 +143,7 @@ class TestFSFirmwareHandler: ): """Test that firmware paths are constructed correctly for Structure A""" platform_fs_slug = "n64" - config.has_structure_b = False + config.has_structure_path_b = False with patch( "handler.filesystem.firmware_handler.cm.get_config", return_value=config @@ -156,7 +156,7 @@ class TestFSFirmwareHandler: ): """Test that firmware paths are constructed correctly for Structure B""" platform_fs_slug = "n64" - config.has_structure_b = True + config.has_structure_path_b = True with patch( "handler.filesystem.firmware_handler.cm.get_config", return_value=config diff --git a/backend/tests/handler/filesystem/test_platforms_handler.py b/backend/tests/handler/filesystem/test_platforms_handler.py index 24c5302ce..fdcc12b1f 100644 --- a/backend/tests/handler/filesystem/test_platforms_handler.py +++ b/backend/tests/handler/filesystem/test_platforms_handler.py @@ -90,7 +90,7 @@ class TestFSPlatformsHandler: self, handler: FSPlatformsHandler, config ): """Test get_platforms_directory with Structure A (roms/{platform})""" - config.has_structure_b = False + config.has_structure_path_b = False with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): @@ -101,7 +101,7 @@ class TestFSPlatformsHandler: self, handler: FSPlatformsHandler, config ): """Test get_platforms_directory with Structure B ({platform}/roms)""" - config.has_structure_b = True + config.has_structure_path_b = True with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): @@ -113,7 +113,7 @@ class TestFSPlatformsHandler: ): """Test get_platform_fs_structure with Structure A (roms/{platform})""" fs_slug = "n64" - config.has_structure_b = False + config.has_structure_path_b = False with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): @@ -125,7 +125,7 @@ class TestFSPlatformsHandler: ): """Test get_platform_fs_structure with Structure B ({platform}/roms)""" fs_slug = "n64" - config.has_structure_b = True + config.has_structure_path_b = True with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): @@ -137,7 +137,7 @@ class TestFSPlatformsHandler: ): """Test get_platform_fs_structure with custom folder name (Structure B)""" fs_slug = "psx" - config_custom_folder.has_structure_b = True + config_custom_folder.has_structure_path_b = True with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config_custom_folder, @@ -151,7 +151,7 @@ class TestFSPlatformsHandler: """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_b = False + config.has_structure_path_b = False with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config @@ -166,7 +166,7 @@ class TestFSPlatformsHandler: """Test that add_platform creates directory with Structure B""" fs_slug = "gba" expected_path = f"{fs_slug}/{config.ROMS_FOLDER_NAME}" - config.has_structure_b = True + config.has_structure_path_b = True with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config @@ -203,7 +203,7 @@ class TestFSPlatformsHandler: self, handler: FSPlatformsHandler, config ): """Test that get_platforms calls list_directories with correct path""" - config.has_structure_b = False + config.has_structure_path_b = False with patch( "handler.filesystem.platforms_handler.cm.get_config", return_value=config ): @@ -316,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 @@ -331,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 diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index 4153ac5b0..7026dd97b 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -117,7 +117,7 @@ class TestFSRomsHandler: ROMS_FOLDER_NAME="roms", FIRMWARE_FOLDER_NAME="bios", ) - cfg.has_structure_b = True + cfg.has_structure_path_b = True with pytest.MonkeyPatch.context() as m: m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: cfg) @@ -140,7 +140,7 @@ class TestFSRomsHandler: ROMS_FOLDER_NAME="roms", FIRMWARE_FOLDER_NAME="bios", ) - cfg.has_structure_b = False + cfg.has_structure_path_b = False with pytest.MonkeyPatch.context() as m: m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: cfg) @@ -513,7 +513,7 @@ class TestFSRomsHandler: non_hashable_platform.fs_slug = "n64" non_hashable_platform.slug = "nintendo-64" - config.has_structure_b = True + config.has_structure_path_b = True with pytest.MonkeyPatch.context() as m: m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) @@ -551,12 +551,12 @@ class TestFSRomsHandler: m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) # Test with Structure B - config.has_structure_b = True + config.has_structure_path_b = True structure = handler.get_roms_fs_structure(fs_slug) assert structure == f"{fs_slug}/roms" # Test with Structure A - config.has_structure_b = False + config.has_structure_path_b = False structure = handler.get_roms_fs_structure(fs_slug) assert structure == f"roms/{fs_slug}" diff --git a/backend/watcher.py b/backend/watcher.py index 9234dea43..c3bf3d913 100644 --- a/backend/watcher.py +++ b/backend/watcher.py @@ -50,7 +50,7 @@ sentry_sdk.init( tracer = trace.get_tracer(__name__) cfg = cm.get_config() -structure_level = 1 if cfg.has_structure_b else 2 +structure_level = 1 if cfg.has_structure_path_b else 2 @enum.unique diff --git a/env.template b/env.template index fa9079aeb..74f9bf52b 100644 --- a/env.template +++ b/env.template @@ -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 # Public URL of this instance (CORS origin, OIDC redirect base, links in container logs) +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 From 07af3d0f64c912d98fd93249220abb7b1600fad2 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 30 Apr 2026 14:48:20 -0400 Subject: [PATCH 024/186] run fmt --- backend/handler/filesystem/firmware_handler.py | 1 - 1 file changed, 1 deletion(-) diff --git a/backend/handler/filesystem/firmware_handler.py b/backend/handler/filesystem/firmware_handler.py index 8422e0220..de6979576 100644 --- a/backend/handler/filesystem/firmware_handler.py +++ b/backend/handler/filesystem/firmware_handler.py @@ -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 From c4431e0ae4dc05a1ddcb332e8764a2f2e23d1dba Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 30 Apr 2026 15:22:22 -0400 Subject: [PATCH 025/186] cleanup --- backend/config/config_manager.py | 2 +- .../tests/handler/filesystem/test_roms_handler.py | 12 ++++++------ backend/watcher.py | 12 +++++------- 3 files changed, 12 insertions(+), 14 deletions(-) diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index 53637bea7..faebe31ca 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -137,8 +137,8 @@ class Config: @functools.cached_property def has_structure_path_b(self) -> bool: - """True when any `///` directory exists.""" try: + # Check for structure path B for match in glob.iglob(f"{LIBRARY_BASE_PATH}/*/{self.ROMS_FOLDER_NAME}"): if os.path.isdir(match): return True diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index 7026dd97b..e6c5bdc74 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -105,7 +105,7 @@ class TestFSRomsHandler: def test_get_roms_fs_structure_structure_b(self, handler: FSRomsHandler): """Test get_roms_fs_structure with Structure B ({platform}/roms)""" fs_slug = "n64" - cfg = Config( + cnfg = Config( EXCLUDED_PLATFORMS=[], EXCLUDED_SINGLE_EXT=[], EXCLUDED_SINGLE_FILES=[], @@ -117,10 +117,10 @@ class TestFSRomsHandler: ROMS_FOLDER_NAME="roms", FIRMWARE_FOLDER_NAME="bios", ) - cfg.has_structure_path_b = True + cnfg.has_structure_path_b = True with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: cfg) + 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" @@ -128,7 +128,7 @@ class TestFSRomsHandler: def test_get_roms_fs_structure_structure_a(self, handler: FSRomsHandler): """Test get_roms_fs_structure with Structure A (roms/{platform})""" fs_slug = "n64" - cfg = Config( + cnfg = Config( EXCLUDED_PLATFORMS=[], EXCLUDED_SINGLE_EXT=[], EXCLUDED_SINGLE_FILES=[], @@ -140,10 +140,10 @@ class TestFSRomsHandler: ROMS_FOLDER_NAME="roms", FIRMWARE_FOLDER_NAME="bios", ) - cfg.has_structure_path_b = False + cnfg.has_structure_path_b = False with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: cfg) + 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}" diff --git a/backend/watcher.py b/backend/watcher.py index c3bf3d913..a9e47142e 100644 --- a/backend/watcher.py +++ b/backend/watcher.py @@ -49,9 +49,6 @@ sentry_sdk.init( ) tracer = trace.get_tracer(__name__) -cfg = cm.get_config() -structure_level = 1 if cfg.has_structure_path_b else 2 - @enum.unique class EventType(enum.StrEnum): @@ -123,11 +120,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: From 699466b37f49b4416074bf579959bbe760e3249b Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 30 Apr 2026 19:31:13 -0400 Subject: [PATCH 026/186] cleanup --- backend/config/config_manager.py | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index faebe31ca..6f9dac97f 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -1,5 +1,4 @@ import enum -import functools import glob import json import os @@ -135,15 +134,13 @@ class Config: def __init__(self, **entries): self.__dict__.update(entries) - @functools.cached_property def has_structure_path_b(self) -> bool: - try: - # Check for structure path B - for match in glob.iglob(f"{LIBRARY_BASE_PATH}/*/{self.ROMS_FOLDER_NAME}"): - if os.path.isdir(match): - return True - except OSError: - pass + 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 From 580ee4c694acba1a622f33d0ae77bc2c2c72c716 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 30 Apr 2026 21:01:22 -0400 Subject: [PATCH 027/186] whatevefr --- backend/config/config_manager.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index 6f9dac97f..92f89b6bc 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -1,4 +1,5 @@ import enum +import functools import glob import json import os @@ -134,6 +135,7 @@ class Config: def __init__(self, **entries): self.__dict__.update(entries) + @functools.cached_property def has_structure_path_b(self) -> bool: pattern = os.path.join( LIBRARY_BASE_PATH, "*", glob.escape(self.ROMS_FOLDER_NAME) From 9fe025806e5c7d8e47eeba4f74e65c127e330d2b Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Fri, 1 May 2026 15:06:29 -0400 Subject: [PATCH 028/186] Allow bypassing OIDC autologin via bypass_autologin URL param Co-Authored-By: Claude Opus 4.7 (1M context) --- frontend/src/views/Auth/Login.vue | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/frontend/src/views/Auth/Login.vue b/frontend/src/views/Auth/Login.vue index d1ae0512c..94c1ea180 100644 --- a/frontend/src/views/Auth/Login.vue +++ b/frontend/src/views/Auth/Login.vue @@ -97,7 +97,9 @@ async function loginOIDC() { } onMounted(async () => { - if (oidcEnabled && oidcAutologin) { + const params = new URLSearchParams(window.location.search); + const bypassAutologin = params.get("bypass_autologin") === "true"; + if (oidcEnabled && oidcAutologin && !bypassAutologin) { loginOIDC(); } }); From 21de7e21f816a96bc1e2694e2dc1a138be2ec5a9 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 2 May 2026 16:50:30 +0000 Subject: [PATCH 030/186] Fix file exclusion for multi-dot filenames (e.g. game.nds.hash.txt) Agent-Logs-Url: https://github.com/rommapp/romm/sessions/2f711770-100b-4e9e-a66e-ab1a74f025f8 Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com> --- backend/handler/filesystem/base_handler.py | 14 ++++++++--- backend/handler/filesystem/roms_handler.py | 9 +++++-- .../handler/filesystem/test_base_handler.py | 25 +++++++++++++++++++ 3 files changed, 42 insertions(+), 6 deletions(-) diff --git a/backend/handler/filesystem/base_handler.py b/backend/handler/filesystem/base_handler.py index cea4a20e1..61a1fe13f 100644 --- a/backend/handler/filesystem/base_handler.py +++ b/backend/handler/filesystem/base_handler.py @@ -215,14 +215,20 @@ class FSHandler: excluded_files: list[str] = [] for file_name in files: - # Split the file name to get the extension. + # Get the compound extension (e.g. "nds.hash.txt" for "game.nds.hash.txt") + # and the last single extension (e.g. "txt") for multi-dot filenames. ext = self.parse_file_extension(file_name) + suffix = Path(file_name).suffix.lstrip(".") - # Exclude the file if it has no extension or the extension is in the excluded list. - if ext and ext.lower() in excluded_extensions: + # Exclude the file if the compound extension or the last single extension + # is in the excluded list. Checking both handles files with multiple dots + # (e.g. "game.nds.hash.txt" should be excluded when "txt" is excluded). + if (ext and ext.lower() in excluded_extensions) or ( + suffix and suffix.lower() in excluded_extensions + ): excluded_files.append(file_name) - # Additionally, check if the file name mathes a pattern in the excluded list. + # Additionally, check if the file name matches 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) diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 8145a1f1e..6b6d36c74 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -455,9 +455,14 @@ class FSRomsHandler(FSHandler): for f_path, file_name in iter_files( f"{abs_fs_path}/{rom.fs_name}", recursive=True ): - # Check if file is excluded + # Check if file is excluded by extension. + # Also check the last single extension for multi-dot filenames + # (e.g. "game.nds.hash.txt" should be excluded when "txt" is excluded). ext = self.parse_file_extension(file_name) - if ext in excluded_file_exts: + suffix = Path(file_name).suffix.lstrip(".") + if (ext and ext.lower() in excluded_file_exts) or ( + suffix and suffix.lower() in excluded_file_exts + ): continue if any( diff --git a/backend/tests/handler/filesystem/test_base_handler.py b/backend/tests/handler/filesystem/test_base_handler.py index 0df61ccfb..3dd59dd96 100644 --- a/backend/tests/handler/filesystem/test_base_handler.py +++ b/backend/tests/handler/filesystem/test_base_handler.py @@ -161,6 +161,31 @@ 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 based on their last 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: + mock_config.return_value.EXCLUDED_SINGLE_EXT = ["txt"] + mock_config.return_value.EXCLUDED_SINGLE_FILES = [] + + result = handler.exclude_single_files(files) + + # Files with .txt as the last extension should be excluded regardless of + # how many dots are in the filename + assert "game.nds.hash.txt" not in result + assert "game.nds.enc.hash.txt" not in result + assert "readme.txt" not in result + # Non-txt files should not be excluded + 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") From 55cd0cfc4fb32889be97927163328443b8e035e6 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 3 May 2026 01:29:04 +0000 Subject: [PATCH 031/186] Support compound suffix exclusions like "hash.txt" for multi-dot filenames Agent-Logs-Url: https://github.com/rommapp/romm/sessions/d1c69638-bfa0-480e-8050-d565b234ea44 Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com> --- backend/handler/filesystem/base_handler.py | 28 +++++++++------ backend/handler/filesystem/roms_handler.py | 11 +++--- .../handler/filesystem/test_base_handler.py | 36 ++++++++++++++++--- 3 files changed, 55 insertions(+), 20 deletions(-) diff --git a/backend/handler/filesystem/base_handler.py b/backend/handler/filesystem/base_handler.py index 61a1fe13f..61b1c122c 100644 --- a/backend/handler/filesystem/base_handler.py +++ b/backend/handler/filesystem/base_handler.py @@ -205,6 +205,19 @@ class FSHandler: match = EXTENSION_REGEX.search(file_name) return match.group(1) if match else "" + def iter_file_extensions(self, file_name: str) -> list[str]: + """Return all right-anchored sub-extensions for a filename. + + For "game.nds.enc.hash.txt" this yields: + ["nds.enc.hash.txt", "enc.hash.txt", "hash.txt", "txt"] + This allows exclusion rules like "hash.txt" to match multi-dot filenames. + """ + ext = self.parse_file_extension(file_name) + if not ext: + return [] + parts = ext.split(".") + return [".".join(parts[i:]) for i in range(len(parts))] + def extract_uuid_v4_from_filename(self, file_name: str) -> str: match = UUID_V4_REGEX.search(file_name) return match.group(0) if match else "" @@ -215,16 +228,11 @@ class FSHandler: excluded_files: list[str] = [] for file_name in files: - # Get the compound extension (e.g. "nds.hash.txt" for "game.nds.hash.txt") - # and the last single extension (e.g. "txt") for multi-dot filenames. - ext = self.parse_file_extension(file_name) - suffix = Path(file_name).suffix.lstrip(".") - - # Exclude the file if the compound extension or the last single extension - # is in the excluded list. Checking both handles files with multiple dots - # (e.g. "game.nds.hash.txt" should be excluded when "txt" is excluded). - if (ext and ext.lower() in excluded_extensions) or ( - suffix and suffix.lower() in excluded_extensions + # Check all right-anchored sub-extensions so that rules like "hash.txt" + # match multi-dot filenames such as "game.nds.enc.hash.txt". + if any( + e.lower() in excluded_extensions + for e in self.iter_file_extensions(file_name) ): excluded_files.append(file_name) diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 6b6d36c74..90f0aa0c8 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -456,12 +456,11 @@ class FSRomsHandler(FSHandler): f"{abs_fs_path}/{rom.fs_name}", recursive=True ): # Check if file is excluded by extension. - # Also check the last single extension for multi-dot filenames - # (e.g. "game.nds.hash.txt" should be excluded when "txt" is excluded). - ext = self.parse_file_extension(file_name) - suffix = Path(file_name).suffix.lstrip(".") - if (ext and ext.lower() in excluded_file_exts) or ( - suffix and suffix.lower() in excluded_file_exts + # Check all right-anchored sub-extensions so that rules like "hash.txt" + # match multi-dot filenames such as "game.nds.enc.hash.txt". + if any( + e.lower() in excluded_file_exts + for e in self.iter_file_extensions(file_name) ): continue diff --git a/backend/tests/handler/filesystem/test_base_handler.py b/backend/tests/handler/filesystem/test_base_handler.py index 3dd59dd96..5d9e329d4 100644 --- a/backend/tests/handler/filesystem/test_base_handler.py +++ b/backend/tests/handler/filesystem/test_base_handler.py @@ -145,6 +145,22 @@ class TestFSHandler: assert handler.parse_file_extension("no_extension") == "" assert handler.parse_file_extension("file.with.dots.txt") == "with.dots.txt" + def test_iter_file_extensions(self, handler: FSHandler): + """Test that all right-anchored sub-extensions are returned""" + assert handler.iter_file_extensions("game.nds") == ["nds"] + assert handler.iter_file_extensions("game.nds.hash.txt") == [ + "nds.hash.txt", + "hash.txt", + "txt", + ] + assert handler.iter_file_extensions("game.nds.enc.hash.txt") == [ + "nds.enc.hash.txt", + "enc.hash.txt", + "hash.txt", + "txt", + ] + assert handler.iter_file_extensions("no_extension") == [] + def test_exclude_single_files(self, handler: FSHandler): """Test file exclusion functionality""" files = ["test.txt", "game.rom", "excluded.tmp", "data.json"] @@ -162,7 +178,7 @@ class TestFSHandler: assert "data.json" in result def test_exclude_single_files_multi_dot(self, handler: FSHandler): - """Test that files with multiple dots are excluded based on their last extension""" + """Test that files with multiple dots are excluded by last or compound extension""" files = [ "game.nds", "game.nds.hash.txt", @@ -172,17 +188,29 @@ class TestFSHandler: ] 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) - # Files with .txt as the last extension should be excluded regardless of - # how many dots are in the filename assert "game.nds.hash.txt" not in result assert "game.nds.enc.hash.txt" not in result assert "readme.txt" not in result - # Non-txt files should not be excluded + 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" — should remain + assert "readme.txt" in result assert "game.nds" in result assert "game.rom" in result From 101629628e0a62a72bbcb242dab75c31f8d557df Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 3 May 2026 22:46:21 +0000 Subject: [PATCH 032/186] Simplify extension exclusion to use ends-with check instead of sub-extension iteration Agent-Logs-Url: https://github.com/rommapp/romm/sessions/a81b2023-a243-4721-bc5e-c6fa1a473a79 Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com> --- backend/handler/filesystem/base_handler.py | 22 +++++-------------- backend/handler/filesystem/roms_handler.py | 8 +++---- .../handler/filesystem/test_base_handler.py | 16 -------------- 3 files changed, 9 insertions(+), 37 deletions(-) diff --git a/backend/handler/filesystem/base_handler.py b/backend/handler/filesystem/base_handler.py index 61b1c122c..bfcb48057 100644 --- a/backend/handler/filesystem/base_handler.py +++ b/backend/handler/filesystem/base_handler.py @@ -205,19 +205,6 @@ class FSHandler: match = EXTENSION_REGEX.search(file_name) return match.group(1) if match else "" - def iter_file_extensions(self, file_name: str) -> list[str]: - """Return all right-anchored sub-extensions for a filename. - - For "game.nds.enc.hash.txt" this yields: - ["nds.enc.hash.txt", "enc.hash.txt", "hash.txt", "txt"] - This allows exclusion rules like "hash.txt" to match multi-dot filenames. - """ - ext = self.parse_file_extension(file_name) - if not ext: - return [] - parts = ext.split(".") - return [".".join(parts[i:]) for i in range(len(parts))] - def extract_uuid_v4_from_filename(self, file_name: str) -> str: match = UUID_V4_REGEX.search(file_name) return match.group(0) if match else "" @@ -228,11 +215,12 @@ class FSHandler: excluded_files: list[str] = [] for file_name in files: - # Check all right-anchored sub-extensions so that rules like "hash.txt" - # match multi-dot filenames such as "game.nds.enc.hash.txt". + # Check whether the filename ends with any excluded extension entry. + # Using ends-with handles both simple rules ("txt") and compound rules + # ("hash.txt") against multi-dot filenames like "game.nds.enc.hash.txt". if any( - e.lower() in excluded_extensions - for e in self.iter_file_extensions(file_name) + file_name.lower().endswith("." + ext.lower()) + for ext in excluded_extensions ): excluded_files.append(file_name) diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 90f0aa0c8..29c021c33 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -456,11 +456,11 @@ class FSRomsHandler(FSHandler): f"{abs_fs_path}/{rom.fs_name}", recursive=True ): # Check if file is excluded by extension. - # Check all right-anchored sub-extensions so that rules like "hash.txt" - # match multi-dot filenames such as "game.nds.enc.hash.txt". + # Using ends-with handles both simple rules ("txt") and compound + # rules ("hash.txt") for multi-dot filenames like "game.nds.enc.hash.txt". if any( - e.lower() in excluded_file_exts - for e in self.iter_file_extensions(file_name) + file_name.lower().endswith("." + ext.lower()) + for ext in excluded_file_exts ): continue diff --git a/backend/tests/handler/filesystem/test_base_handler.py b/backend/tests/handler/filesystem/test_base_handler.py index 5d9e329d4..3fe7efbd7 100644 --- a/backend/tests/handler/filesystem/test_base_handler.py +++ b/backend/tests/handler/filesystem/test_base_handler.py @@ -145,22 +145,6 @@ class TestFSHandler: assert handler.parse_file_extension("no_extension") == "" assert handler.parse_file_extension("file.with.dots.txt") == "with.dots.txt" - def test_iter_file_extensions(self, handler: FSHandler): - """Test that all right-anchored sub-extensions are returned""" - assert handler.iter_file_extensions("game.nds") == ["nds"] - assert handler.iter_file_extensions("game.nds.hash.txt") == [ - "nds.hash.txt", - "hash.txt", - "txt", - ] - assert handler.iter_file_extensions("game.nds.enc.hash.txt") == [ - "nds.enc.hash.txt", - "enc.hash.txt", - "hash.txt", - "txt", - ] - assert handler.iter_file_extensions("no_extension") == [] - def test_exclude_single_files(self, handler: FSHandler): """Test file exclusion functionality""" files = ["test.txt", "game.rom", "excluded.tmp", "data.json"] From 9593c302926ea7973da13e52a2810bb1cfb6cde7 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 3 May 2026 23:34:30 +0000 Subject: [PATCH 033/186] Address PR review: normalize exclusion sets, avoid duplicates, add multi-dot test for get_rom_files Agent-Logs-Url: https://github.com/rommapp/romm/sessions/8cbbc2ca-a3e3-4c61-9e47-f8544d59231a Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com> --- backend/handler/filesystem/base_handler.py | 22 ++++--- backend/handler/filesystem/roms_handler.py | 6 +- .../handler/filesystem/test_roms_handler.py | 61 ++++++++++++++++++- 3 files changed, 78 insertions(+), 11 deletions(-) diff --git a/backend/handler/filesystem/base_handler.py b/backend/handler/filesystem/base_handler.py index bfcb48057..689d3ef42 100644 --- a/backend/handler/filesystem/base_handler.py +++ b/backend/handler/filesystem/base_handler.py @@ -210,24 +210,30 @@ 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 + config = cm.get_config() + # Config already stores extensions lowercased; use a set for O(1) lookups. + excluded_extensions = set(config.EXCLUDED_SINGLE_EXT) + excluded_names = config.EXCLUDED_SINGLE_FILES excluded_files: list[str] = [] for file_name in files: + file_name_lower = file_name.lower() + # Check whether the filename ends with any excluded extension entry. # Using ends-with handles both simple rules ("txt") and compound rules # ("hash.txt") against multi-dot filenames like "game.nds.enc.hash.txt". if any( - file_name.lower().endswith("." + ext.lower()) - for ext in excluded_extensions + file_name_lower.endswith("." + ext) for ext in excluded_extensions ): excluded_files.append(file_name) + continue - # Additionally, check if the file name matches 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 any( + file_name == name or 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] diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 29c021c33..8c7fb256e 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -434,7 +434,8 @@ class FSRomsHandler(FSHandler): ) excluded_file_names = cm.get_config().EXCLUDED_MULTI_PARTS_FILES - excluded_file_exts = cm.get_config().EXCLUDED_MULTI_PARTS_EXT + # Config already stores extensions lowercased; use a set for O(1) lookups. + excluded_file_exts = set(cm.get_config().EXCLUDED_MULTI_PARTS_EXT) rom_crc_c = 0 rom_md5_h = hashlib.md5(usedforsecurity=False) if calculate_hashes else None @@ -458,8 +459,9 @@ class FSRomsHandler(FSHandler): # Check if file is excluded by extension. # Using ends-with handles both simple rules ("txt") and compound # rules ("hash.txt") for multi-dot filenames like "game.nds.enc.hash.txt". + file_name_lower = file_name.lower() if any( - file_name.lower().endswith("." + ext.lower()) + file_name_lower.endswith("." + ext) for ext in excluded_file_exts ): continue diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index e6c5bdc74..9e1dbce39 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -378,7 +378,66 @@ class TestFSRomsHandler: assert rom_file.file_size_bytes > 0 assert rom_file.last_modified is not None - async def test_rename_fs_rom_same_name(self, handler: FSRomsHandler): + @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.nds.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.nds.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.nds.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) + + """Test rename_fs_rom when old and new names are the same""" old_name = "test_rom.n64" new_name = "test_rom.n64" From 78c0b5b8948d1615e1919fba1ae548050313c63a Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 3 May 2026 23:35:19 +0000 Subject: [PATCH 034/186] Fix broken test_rename_fs_rom_same_name function definition after new test insertion Agent-Logs-Url: https://github.com/rommapp/romm/sessions/8cbbc2ca-a3e3-4c61-9e47-f8544d59231a Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com> --- backend/tests/handler/filesystem/test_roms_handler.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index 9e1dbce39..2a373cff6 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -437,7 +437,7 @@ class TestFSRomsHandler: 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" new_name = "test_rom.n64" From da005cf81a3d8f29b69c1f958e607e670f6af8db Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 3 May 2026 23:36:23 +0000 Subject: [PATCH 035/186] Optimize fnmatch check and use consistent n64 filename in test Agent-Logs-Url: https://github.com/rommapp/romm/sessions/8cbbc2ca-a3e3-4c61-9e47-f8544d59231a Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com> --- backend/handler/filesystem/base_handler.py | 6 +++--- backend/tests/handler/filesystem/test_roms_handler.py | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/backend/handler/filesystem/base_handler.py b/backend/handler/filesystem/base_handler.py index 689d3ef42..268b4e3b5 100644 --- a/backend/handler/filesystem/base_handler.py +++ b/backend/handler/filesystem/base_handler.py @@ -229,9 +229,9 @@ class FSHandler: continue # Check if the file name matches a pattern in the excluded list. - if any( - file_name == name or fnmatch.fnmatch(file_name, name) - for name in excluded_names + # Check exact match first (O(1) via set), then fall back to glob patterns. + if file_name in excluded_names or any( + fnmatch.fnmatch(file_name, name) for name in excluded_names ): excluded_files.append(file_name) diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index 2a373cff6..fa4f3f2d2 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -385,7 +385,7 @@ class TestFSRomsHandler: """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.nds.hash.txt" + / "n64/roms/Super Mario 64 (J) (Rev A)/game.n64.hash.txt" ) multi_dot_file.write_text("hash data") @@ -409,7 +409,7 @@ class TestFSRomsHandler: ) parsed = await handler.get_rom_files(rom_multi) file_names = [rf.file_name for rf in parsed.rom_files] - assert "game.nds.hash.txt" not in file_names + 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" @@ -432,7 +432,7 @@ class TestFSRomsHandler: ) parsed = await handler.get_rom_files(rom_multi) file_names = [rf.file_name for rf in parsed.rom_files] - assert "game.nds.hash.txt" not in file_names + 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) From 5e3a2707b0134fc0c9b4aeba9663a278a71237e8 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sun, 3 May 2026 19:39:19 -0400 Subject: [PATCH 036/186] cleanup --- backend/handler/filesystem/base_handler.py | 14 ++++---------- backend/handler/filesystem/roms_handler.py | 12 +++++------- .../tests/handler/filesystem/test_roms_handler.py | 3 +-- 3 files changed, 10 insertions(+), 19 deletions(-) diff --git a/backend/handler/filesystem/base_handler.py b/backend/handler/filesystem/base_handler.py index 268b4e3b5..b93042cf4 100644 --- a/backend/handler/filesystem/base_handler.py +++ b/backend/handler/filesystem/base_handler.py @@ -210,26 +210,20 @@ class FSHandler: return match.group(0) if match else "" def exclude_single_files(self, files: list[str]) -> list[str]: - config = cm.get_config() - # Config already stores extensions lowercased; use a set for O(1) lookups. - excluded_extensions = set(config.EXCLUDED_SINGLE_EXT) - excluded_names = 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: file_name_lower = file_name.lower() # Check whether the filename ends with any excluded extension entry. - # Using ends-with handles both simple rules ("txt") and compound rules - # ("hash.txt") against multi-dot filenames like "game.nds.enc.hash.txt". - if any( - file_name_lower.endswith("." + ext) for ext in excluded_extensions - ): + if any(file_name_lower.endswith("." + ext) for ext in excluded_extensions): excluded_files.append(file_name) continue # Check if the file name matches a pattern in the excluded list. - # Check exact match first (O(1) via set), then fall back to glob patterns. if file_name in excluded_names or any( fnmatch.fnmatch(file_name, name) for name in excluded_names ): diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 8c7fb256e..411f24f6c 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -433,9 +433,9 @@ class FSRomsHandler(FSHandler): rom.platform_slug not in NON_HASHABLE_PLATFORMS and calculate_hashes ) - excluded_file_names = cm.get_config().EXCLUDED_MULTI_PARTS_FILES - # Config already stores extensions lowercased; use a set for O(1) lookups. - excluded_file_exts = set(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 @@ -457,15 +457,13 @@ class FSRomsHandler(FSHandler): f"{abs_fs_path}/{rom.fs_name}", recursive=True ): # Check if file is excluded by extension. - # Using ends-with handles both simple rules ("txt") and compound - # rules ("hash.txt") for multi-dot filenames like "game.nds.enc.hash.txt". file_name_lower = file_name.lower() if any( - file_name_lower.endswith("." + ext) - for ext in excluded_file_exts + 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 diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index fa4f3f2d2..ed7787931 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -384,8 +384,7 @@ class TestFSRomsHandler: ): """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" + handler.base_path / "n64/roms/Super Mario 64 (J) (Rev A)/game.n64.hash.txt" ) multi_dot_file.write_text("hash data") From 228c640f183e12b299447831e6da0e9559459831 Mon Sep 17 00:00:00 2001 From: sabuswai Date: Thu, 7 May 2026 01:13:07 -0500 Subject: [PATCH 037/186] Add credentialless attribute to YouTube iframe add credentialless attribute to YouTube iframe for COEP compatibility --- frontend/src/components/Details/Info/MediaCarousel.vue | 1 + 1 file changed, 1 insertion(+) diff --git a/frontend/src/components/Details/Info/MediaCarousel.vue b/frontend/src/components/Details/Info/MediaCarousel.vue index 35cdda892..221dff0b7 100644 --- a/frontend/src/components/Details/Info/MediaCarousel.vue +++ b/frontend/src/components/Details/Info/MediaCarousel.vue @@ -80,6 +80,7 @@ const carouselHeight = computed(() => { height="100%" width="100%" :src="`${heartbeat.FRONTEND.YOUTUBE_BASE_URL}/embed/${youtubeVideoId}`" + credentialless title="YouTube video player" frameborder="0" allow=" From d0b2c89e6060120b421a257fc1ac0968b3cc3458 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 8 May 2026 09:10:01 +0000 Subject: [PATCH 038/186] chore(deps): bump axios from 1.15.0 to 1.16.0 in /frontend Bumps [axios](https://github.com/axios/axios) from 1.15.0 to 1.16.0. - [Release notes](https://github.com/axios/axios/releases) - [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md) - [Commits](https://github.com/axios/axios/compare/v1.15.0...v1.16.0) --- updated-dependencies: - dependency-name: axios dependency-version: 1.16.0 dependency-type: direct:production ... Signed-off-by: dependabot[bot] --- frontend/package-lock.json | 10 +++++----- frontend/package.json | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/frontend/package-lock.json b/frontend/package-lock.json index f63272b52..62c770050 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -11,7 +11,7 @@ "dependencies": { "@mdi/font": "7.4.47", "@vueuse/core": "^13.7.0", - "axios": "^1.15.0", + "axios": "^1.16.0", "cronstrue": "^2.57.0", "date-fns": "^4.1.0", "js-cookie": "^3.0.5", @@ -4616,12 +4616,12 @@ } }, "node_modules/axios": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.15.0.tgz", - "integrity": "sha512-wWyJDlAatxk30ZJer+GeCWS209sA42X+N5jU2jy6oHTp7ufw8uzUTVFBX9+wTfAlhiJXGS0Bq7X6efruWjuK9Q==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.16.0.tgz", + "integrity": "sha512-6hp5CwvTPlN2A31g5dxnwAX0orzM7pmCRDLnZSX772mv8WDqICwFjowHuPs04Mc8deIld1+ejhtaMn5vp6b+1w==", "license": "MIT", "dependencies": { - "follow-redirects": "^1.15.11", + "follow-redirects": "^1.16.0", "form-data": "^4.0.5", "proxy-from-env": "^2.1.0" } diff --git a/frontend/package.json b/frontend/package.json index f6bbd6845..282aac8d4 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -30,7 +30,7 @@ "dependencies": { "@mdi/font": "7.4.47", "@vueuse/core": "^13.7.0", - "axios": "^1.15.0", + "axios": "^1.16.0", "cronstrue": "^2.57.0", "date-fns": "^4.1.0", "js-cookie": "^3.0.5", From fdd9047b37e5fb29213502971a045a95a4ea02e4 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 8 May 2026 13:52:53 +0000 Subject: [PATCH 041/186] feat(config): auto-create missing config.yml on startup Agent-Logs-Url: https://github.com/rommapp/romm/sessions/0c94e1c8-0f79-4f5f-a72b-e45832906d00 Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com> --- backend/config/config_manager.py | 22 +++++++++++++++++++--- backend/tests/config/test_config_loader.py | 11 +++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index 92f89b6bc..1c17ad854 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -178,9 +178,7 @@ class ConfigManager: # 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." @@ -190,6 +188,24 @@ class ConfigManager: self._parse_config() self._validate_config() + 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: + os.makedirs(os.path.dirname(self.config_file), exist_ok=True) + with open(self.config_file, "x"): + pass + + self._config_file_mounted = True + self._config_file_writable = os.access(self.config_file, os.W_OK) + except FileExistsError: + self._config_file_mounted = True + self._config_file_writable = os.access(self.config_file, os.W_OK) + except PermissionError: + 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 diff --git a/backend/tests/config/test_config_loader.py b/backend/tests/config/test_config_loader.py index 37c29cfa4..faa9c8d10 100644 --- a/backend/tests/config/test_config_loader.py +++ b/backend/tests/config/test_config_loader.py @@ -113,3 +113,14 @@ 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.exists() + assert config_file.read_text() == "" + assert loader.config.CONFIG_FILE_MOUNTED + assert loader.config.CONFIG_FILE_WRITABLE From 9ef217339f7fca7e1557c193f71a514068bd4e1f Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 8 May 2026 13:54:19 +0000 Subject: [PATCH 042/186] test(config): cover auto-created config directory Agent-Logs-Url: https://github.com/rommapp/romm/sessions/0c94e1c8-0f79-4f5f-a72b-e45832906d00 Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com> --- backend/config/config_manager.py | 11 +++++------ backend/tests/config/test_config_loader.py | 1 + 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index 1c17ad854..283ffbc5d 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -4,6 +4,7 @@ import glob import json import os import sys +from pathlib import Path from typing import Final, NotRequired, TypedDict import pydash @@ -189,16 +190,14 @@ class ConfigManager: self._validate_config() def _create_missing_config_file(self) -> None: - log.warning(f"Config file not found, creating an empty config at {hl(self.config_file, BLUE)}") + log.warning( + f"Config file not found, creating an empty config at {hl(self.config_file, BLUE)}" + ) try: os.makedirs(os.path.dirname(self.config_file), exist_ok=True) - with open(self.config_file, "x"): - pass + Path(self.config_file).touch(exist_ok=True) - self._config_file_mounted = True - self._config_file_writable = os.access(self.config_file, os.W_OK) - except FileExistsError: self._config_file_mounted = True self._config_file_writable = os.access(self.config_file, os.W_OK) except PermissionError: diff --git a/backend/tests/config/test_config_loader.py b/backend/tests/config/test_config_loader.py index faa9c8d10..72b57f940 100644 --- a/backend/tests/config/test_config_loader.py +++ b/backend/tests/config/test_config_loader.py @@ -120,6 +120,7 @@ def test_missing_config_file_is_created(tmp_path): 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 From 2bb86e4836aab745d8f40c51f5e1ff8d429c7759 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 8 May 2026 13:55:00 +0000 Subject: [PATCH 043/186] Make setup platform rows toggle checkbox selection on click Agent-Logs-Url: https://github.com/rommapp/romm/sessions/00a7f2a2-cabf-470b-a73e-a127ffcdccd5 Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com> --- frontend/src/components/Setup/PlatformGroupList.vue | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/frontend/src/components/Setup/PlatformGroupList.vue b/frontend/src/components/Setup/PlatformGroupList.vue index 9c15fd20b..76a38416d 100644 --- a/frontend/src/components/Setup/PlatformGroupList.vue +++ b/frontend/src/components/Setup/PlatformGroupList.vue @@ -28,6 +28,17 @@ const countSelectedInGroup = (platforms: Platform[]) => { selectedPlatformsModel.value.includes(p.fs_slug), ).length; }; + +const togglePlatformSelection = (platformSlug: string) => { + if (!props.showCheckboxes) return; + + const selected = selectedPlatformsModel.value; + const isSelected = selected.includes(platformSlug); + + selectedPlatformsModel.value = isSelected + ? selected.filter((slug) => slug !== platformSlug) + : [...selected, platformSlug]; +};