diff --git a/backend/endpoints/feeds.py b/backend/endpoints/feeds.py index 756914b95..f28e6e69a 100644 --- a/backend/endpoints/feeds.py +++ b/backend/endpoints/feeds.py @@ -50,7 +50,12 @@ from handler.metadata.base_handler import ( SWITCH_TITLEDB_REGEX, ) from handler.metadata.base_handler import UniversalPlatformSlug as UPS -from models.rom import Rom, RomFile, RomFileCategory +from models.rom import ( + HAS_FILE_ON_DISK_FILTERS, + Rom, + RomFile, + RomFileCategory, +) from utils.archives import is_compressed_file from utils.router import APIRouter @@ -93,24 +98,19 @@ def _hidden_ids(request: Request) -> tuple[list[int], list[int]]: return list(perms.hidden_platform_ids), list(perms.hidden_rom_ids) -def _servable_roms(roms: Sequence[Rom]) -> list[Rom]: - """Every feed entry carries a download URL, so a rom with no file has none.""" - return [rom for rom in roms if rom.has_file_on_disk] - - def _platform_roms( request: Request, platform_id: int, *, include_files: bool = False -) -> list[Rom]: - """Roms of a platform, excluding any hidden from the caller (cascade included).""" +) -> Sequence[Rom]: + """Roms of a platform a feed can serve: nothing hidden from the caller, and + nothing file-less (every feed entry carries a download URL).""" hidden_platforms, hidden_roms = _hidden_ids(request) if platform_id in hidden_platforms: return [] - return _servable_roms( - db_rom_handler.get_roms_scalar( - platform_ids=[platform_id], - include_files=include_files, - hidden_rom_ids=hidden_roms, - ) + return db_rom_handler.get_roms_scalar( + platform_ids=[platform_id], + include_files=include_files, + hidden_rom_ids=hidden_roms, + **HAS_FILE_ON_DISK_FILTERS, ) @@ -139,12 +139,11 @@ def platforms_webrcade_feed(request: Request) -> WebrcadeFeedSchema: continue category_items = [] - roms = _servable_roms( - db_rom_handler.get_roms_scalar( - platform_ids=[p.id], - hidden_platform_ids=hidden_platforms, - hidden_rom_ids=hidden_roms, - ) + roms = db_rom_handler.get_roms_scalar( + platform_ids=[p.id], + hidden_platform_ids=hidden_platforms, + hidden_rom_ids=hidden_roms, + **HAS_FILE_ON_DISK_FILTERS, ) for rom in roms: download_url = generate_rom_download_url(request, rom) @@ -257,13 +256,12 @@ async def tinfoil_index_feed( return titledb hidden_platforms, hidden_roms = _hidden_ids(request) - roms = _servable_roms( - db_rom_handler.get_roms_scalar( - platform_ids=[switch.id], - include_files=True, - hidden_platform_ids=hidden_platforms, - hidden_rom_ids=hidden_roms, - ) + roms = db_rom_handler.get_roms_scalar( + platform_ids=[switch.id], + include_files=True, + hidden_platform_ids=hidden_platforms, + hidden_rom_ids=hidden_roms, + **HAS_FILE_ON_DISK_FILTERS, ) return TinfoilFeedSchema( diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 742211ae0..05c682dfa 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -90,6 +90,7 @@ from logger.formatter import highlight as hl from logger.logger import log from models.permission import PermAction, PermEntity from models.rom import ( + HAS_FILE_ON_DISK_FILTERS, Rom, RomUserStatus, apply_file_stats, @@ -1056,6 +1057,7 @@ async def download_roms( smart_collection_id=smart_collection_id, hidden_platform_ids=list(perms.hidden_platform_ids), hidden_rom_ids=list(perms.hidden_rom_ids), + **HAS_FILE_ON_DISK_FILTERS, ) rom_id_list = list(dict.fromkeys(rom.id for rom in rom_rows)) elif rom_ids: diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index dbb0c0769..384976f91 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -1186,6 +1186,7 @@ class DBRomsHandler(DBBaseHandler): has_saves: bool | None = None, has_states: bool | None = None, missing: bool | None = None, + physical: bool | None = None, verified: bool | None = None, has_soundtrack: bool | None = None, group_by_meta_id: bool = False, @@ -1327,6 +1328,9 @@ class DBRomsHandler(DBBaseHandler): if missing is not None: query = self._filter_by_missing_from_fs(query, value=missing) + if physical is not None: + query = query.filter(Rom.is_physical.is_(physical)) + if verified is not None: query = self._filter_by_verified(query, value=verified) @@ -1614,6 +1618,7 @@ class DBRomsHandler(DBBaseHandler): has_states=kwargs.get("has_states", None), has_soundtrack=kwargs.get("has_soundtrack", None), missing=kwargs.get("missing", None), + physical=kwargs.get("physical", None), verified=kwargs.get("verified", None), genres=kwargs.get("genres", None), franchises=kwargs.get("franchises", None), diff --git a/backend/models/rom.py b/backend/models/rom.py index b0b56564e..5ae0e8df2 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -912,6 +912,11 @@ def apply_file_stats(rom: Rom, files: Sequence[RomFile]) -> None: ) +# Query-side twin of `Rom.has_file_on_disk`, for callers that enumerate roms and +# want the file-less ones dropped by the database rather than after loading. +HAS_FILE_ON_DISK_FILTERS = {"physical": False, "missing": False} + + # Maps a metadata-source slug (matching the MetadataSource enum) to the Rom # column holding that source's match id. A populated column means the ROM # matched that source. Shared by the stats coverage breakdown and the gallery diff --git a/backend/tests/endpoints/feeds.py b/backend/tests/endpoints/feeds.py index 646bc632a..d38b44fba 100644 --- a/backend/tests/endpoints/feeds.py +++ b/backend/tests/endpoints/feeds.py @@ -43,6 +43,45 @@ def test_webrcade_feed( assert len(body["categories"][0]["items"]) == 1 +def test_webrcade_feed_skips_roms_without_a_file( + client: TestClient, access_token: str, platform: Platform, rom: Rom +): + platform = db_platform_handler.update_platform( + platform.id, + {"name": "Nintendo Entertainment System", "slug": UPS.NES, "fs_slug": UPS.NES}, + ) + db_rom_handler.update_rom(rom.id, {"platform_id": platform.id}) + db_rom_handler.add_rom( + Rom( + platform_id=platform.id, + name="Physical Game", + fs_name="Physical Game", + fs_path=f"{platform.slug}/roms/.physical", + fs_size_bytes=0, + is_physical=True, + ) + ) + db_rom_handler.add_rom( + Rom( + platform_id=platform.id, + name="Gone Game", + fs_name="Gone Game.zip", + fs_path=f"{platform.slug}/roms", + fs_size_bytes=123, + missing_from_fs=True, + ) + ) + + response = client.get( + "/api/feeds/webrcade", + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert response.status_code == status.HTTP_200_OK + + items = response.json()["categories"][0]["items"] + assert [item["title"] for item in items] == [rom.name] + + def test_tinfoil_feed(client: TestClient, platform: Platform, rom: Rom): platform = db_platform_handler.update_platform( platform.id, diff --git a/backend/tests/endpoints/roms/test_rom.py b/backend/tests/endpoints/roms/test_rom.py index f982df60e..b000ddeae 100644 --- a/backend/tests/endpoints/roms/test_rom.py +++ b/backend/tests/endpoints/roms/test_rom.py @@ -1,5 +1,6 @@ import json from unittest.mock import AsyncMock, patch +from urllib.parse import unquote from fastapi import status from fastapi.testclient import TestClient @@ -226,6 +227,35 @@ def test_download_roms_by_platform( assert rom_file.file_name in response.text +def test_download_roms_by_platform_skips_roms_without_a_file( + client: TestClient, + access_token: str, + platform: Platform, + rom_file: RomFile, +): + """A physical game has no files to zip, so it must not swell the archive's + ROM count (and therefore its generated name).""" + db_rom_handler.add_rom( + Rom( + platform_id=platform.id, + name="Physical Game", + fs_name="Physical Game", + fs_path=f"{platform.slug}/roms/.physical", + fs_size_bytes=0, + is_physical=True, + ) + ) + + response = client.get( + f"/api/roms/download?platform_id={platform.id}", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + assert "1 ROMs" in unquote(response.headers["Content-Disposition"]) + assert rom_file.file_name in response.text + + def test_download_roms_by_collection( client: TestClient, access_token: str, diff --git a/backend/tests/handler/test_db_handler.py b/backend/tests/handler/test_db_handler.py index d56eb8069..c7b71e01a 100644 --- a/backend/tests/handler/test_db_handler.py +++ b/backend/tests/handler/test_db_handler.py @@ -77,6 +77,20 @@ def test_get_roms_scalar_missing_excludes_physical(platform: Platform): assert physical.id not in {r.id for r in missing} +def test_get_roms_scalar_physical_filter(rom: Rom, platform: Platform): + physical = _add_physical_rom(platform) + + only_physical = db_rom_handler.get_roms_scalar( + platform_ids=[platform.id], physical=True + ) + assert {r.id for r in only_physical} == {physical.id} + + no_physical = db_rom_handler.get_roms_scalar( + platform_ids=[platform.id], physical=False + ) + assert {r.id for r in no_physical} == {rom.id} + + def test_roms(rom: Rom, platform: Platform): db_rom_handler.add_rom( Rom( diff --git a/backend/utils/gamelist_exporter.py b/backend/utils/gamelist_exporter.py index 29d009b02..3f17b3c00 100644 --- a/backend/utils/gamelist_exporter.py +++ b/backend/utils/gamelist_exporter.py @@ -15,7 +15,7 @@ from config.config_manager import config_manager as cm from handler.database import db_platform_handler, db_rom_handler from handler.filesystem import fs_platform_handler, fs_resource_handler from logger.logger import log -from models.rom import Rom +from models.rom import HAS_FILE_ON_DISK_FILTERS, Rom from utils.filesystem import link_or_copy_file # Map gamelist asset keys to subdirectory names inside assets/ @@ -301,14 +301,16 @@ class GamelistExporter: if not platform: raise ValueError(f"Platform with ID {platform_id} not found") - roms = db_rom_handler.get_roms_scalar(platform_ids=[platform_id]) + roms = db_rom_handler.get_roms_scalar( + platform_ids=[platform_id], **HAS_FILE_ON_DISK_FILTERS + ) root = Element("gameList") media_image, media_thumbnail = get_media_options_for_export() count = 0 for rom in roms: - if not rom or not rom.has_file_on_disk or rom.fs_name == "gamelist.xml": + if rom.fs_name == "gamelist.xml": continue assets = self._collect_assets(rom) diff --git a/backend/utils/pegasus_exporter.py b/backend/utils/pegasus_exporter.py index f5eed5283..04a7eb8ef 100644 --- a/backend/utils/pegasus_exporter.py +++ b/backend/utils/pegasus_exporter.py @@ -8,7 +8,7 @@ from handler.filesystem import fs_platform_handler, fs_resource_handler from handler.metadata.base_handler import UniversalPlatformSlug as UPS from logger.logger import log from models.platform import Platform -from models.rom import Rom +from models.rom import HAS_FILE_ON_DISK_FILTERS, Rom from utils.filesystem import link_or_copy_file # Map RomM platform slugs to canonical Pegasus (collection name, shortname) pairs. @@ -326,7 +326,9 @@ class PegasusExporter: if not platform: raise ValueError(f"Platform with ID {platform_id} not found") - roms = db_rom_handler.get_roms_scalar(platform_ids=[platform_id]) + roms = db_rom_handler.get_roms_scalar( + platform_ids=[platform_id], **HAS_FILE_ON_DISK_FILTERS + ) lines: list[str] = [] @@ -339,11 +341,10 @@ class PegasusExporter: # Game entries game_count = 0 for rom in roms: - if rom.has_file_on_disk: - if game_count > 0: - lines.append("") - lines.append(self._create_game_entry(rom, request=request)) - game_count += 1 + if game_count > 0: + lines.append("") + lines.append(self._create_game_entry(rom, request=request)) + game_count += 1 log.info(f"Exported {game_count} ROMs for platform {platform.name}") return "\n".join(lines) + "\n" @@ -374,7 +375,9 @@ class PegasusExporter: ) platform_dir = fs_platform_handler.base_path / platform_fs_structure - roms = db_rom_handler.get_roms_scalar(platform_ids=[platform_id]) + roms = db_rom_handler.get_roms_scalar( + platform_ids=[platform_id], **HAS_FILE_ON_DISK_FILTERS + ) lines: list[str] = [] @@ -386,9 +389,6 @@ class PegasusExporter: game_count = 0 for rom in roms: - if not rom.has_file_on_disk: - continue - exported_assets: dict[str, str] = {} if self.local_export: