diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 337a45976..dcd3d1698 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -821,11 +821,29 @@ def get_rom_identifiers( async def download_roms( request: Request, rom_ids: Annotated[ - str, + str | None, Query( description="Comma-separated list of ROM IDs to download as a zip file.", ), - ], + ] = None, + platform_id: Annotated[ + int | None, + Query(description="Download every ROM in this platform as a zip file."), + ] = None, + collection_id: Annotated[ + int | None, + Query(description="Download every ROM in this collection as a zip file."), + ] = None, + virtual_collection_id: Annotated[ + str | None, + Query( + description="Download every ROM in this virtual collection as a zip file.", + ), + ] = None, + smart_collection_id: Annotated[ + int | None, + Query(description="Download every ROM in this smart collection as a zip file."), + ] = None, filename: Annotated[ str | None, Query( @@ -838,33 +856,46 @@ async def download_roms( current_username = ( request.user.username if request.user.is_authenticated else "unknown" ) + perms = get_permissions(request) - if not rom_ids: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="No ROM IDs provided", + # Resolve the target ROM IDs + if platform_id or collection_id or virtual_collection_id or smart_collection_id: + rom_rows = db_rom_handler.get_roms_scalar( + user_id=request.user.id, + only_fields=[Rom.id], + platform_ids=[platform_id] if platform_id else None, + collection_id=collection_id, + virtual_collection_id=virtual_collection_id, + smart_collection_id=smart_collection_id, + hidden_platform_ids=list(perms.hidden_platform_ids), + hidden_rom_ids=list(perms.hidden_rom_ids), ) - - # Parse comma-separated string into list of integers - try: - rom_id_list = [int(id.strip()) for id in rom_ids.split(",") if id.strip()] - except ValueError as e: + rom_id_list = list(dict.fromkeys(rom.id for rom in rom_rows)) + elif rom_ids: + # Parse comma-separated string into list of integers + try: + rom_id_list = [int(id.strip()) for id in rom_ids.split(",") if id.strip()] + except ValueError as e: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Invalid ROM ID format. Must be comma-separated integers.", + ) from e + else: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, - detail="Invalid ROM ID format. Must be comma-separated integers.", - ) from e + detail="No ROM IDs or platform/collection selector provided", + ) if not rom_id_list: raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="No valid ROM IDs provided", + status_code=status.HTTP_404_NOT_FOUND, + detail="No ROMs found to download", ) rom_objects = db_rom_handler.get_roms_by_ids(rom_id_list) # Drop roms hidden from the caller so they can't be pulled by direct id. if request.user.is_authenticated: - perms = get_permissions(request) rom_objects = [ rom for rom in rom_objects if perms.can_see_rom(rom.id, rom.platform_id) ] diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index c70789fcb..6ed97a3e3 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -1201,6 +1201,7 @@ class DBRomsHandler(DBBaseHandler): platform_ids=kwargs.get("platform_ids", None), collection_id=kwargs.get("collection_id", None), virtual_collection_id=kwargs.get("virtual_collection_id", None), + smart_collection_id=kwargs.get("smart_collection_id", None), search_term=kwargs.get("search_term", None), matched=kwargs.get("matched", None), favorite=kwargs.get("favorite", None), diff --git a/backend/tests/endpoints/roms/test_rom.py b/backend/tests/endpoints/roms/test_rom.py index 419d3686f..58336ef93 100644 --- a/backend/tests/endpoints/roms/test_rom.py +++ b/backend/tests/endpoints/roms/test_rom.py @@ -4,7 +4,7 @@ from unittest.mock import AsyncMock, patch from fastapi import status from fastapi.testclient import TestClient -from handler.database import db_rom_handler +from handler.database import db_collection_handler, db_rom_handler from handler.filesystem.resources_handler import FSResourcesHandler from handler.filesystem.roms_handler import FSRomsHandler from handler.metadata.flashpoint_handler import FlashpointHandler, FlashpointRom @@ -14,8 +14,10 @@ from handler.metadata.launchbox_handler.types import LaunchboxRom from handler.metadata.moby_handler import MobyGamesHandler, MobyGamesRom from handler.metadata.ra_handler import RAGameRom, RAHandler from handler.metadata.ss_handler import SSHandler, SSRom +from models.collection import Collection from models.platform import Platform from models.rom import Rom, RomFile, compute_name_sort_key +from models.user import User MOCK_IGDB_ID = 11111 MOCK_MOBY_ID = 22222 @@ -62,6 +64,64 @@ def test_download_multi_file_rom_content( assert f"{multi_file_rom.fs_name}.m3u" in body +def test_download_roms_by_platform( + client: TestClient, + access_token: str, + platform: Platform, + rom_file: RomFile, +): + """The `platform_id` selector expands server-side to every ROM in the + platform, so no ID list rides in the URL.""" + 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 response.headers["X-Archive-Files"] == "zip" + assert rom_file.file_name in response.text + + +def test_download_roms_by_collection( + client: TestClient, + access_token: str, + admin_user: User, + rom_file: RomFile, +): + """The `collection_id` selector expands to the collection's ROMs.""" + collection = db_collection_handler.add_collection( + Collection( + name="Download Test", + description="", + is_public=False, + is_favorite=False, + user_id=admin_user.id, + ) + ) + db_collection_handler.add_roms_to_collection(collection.id, [rom_file.rom_id]) + + response = client.get( + f"/api/roms/download?collection_id={collection.id}", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + assert response.headers["X-Archive-Files"] == "zip" + assert rom_file.file_name in response.text + + +def test_download_roms_without_selector_is_bad_request( + client: TestClient, access_token: str +): + """Neither an ID list nor a platform/collection selector -> 400.""" + response = client.get( + "/api/roms/download", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + + def test_get_all_roms( client: TestClient, access_token: str, rom: Rom, platform: Platform ): diff --git a/frontend/src/services/api/rom.ts b/frontend/src/services/api/rom.ts index 320b6a705..b11a1e70c 100644 --- a/frontend/src/services/api/rom.ts +++ b/frontend/src/services/api/rom.ts @@ -452,17 +452,39 @@ async function downloadRom({ return triggerFileDownload(getDownloadPath({ rom, fileIDs })); } +// A platform/collection selector is expanded server-side into the full ROM +// list, keeping the URL short (an explicit `romIDs` list can overflow the +// browser's URL length limit for large libraries). Pass exactly one selector; +// `romIDs` stays the fallback for ad-hoc multi-selections. async function bulkDownloadRoms({ romIDs, + platformId, + collectionId, + virtualCollectionId, + smartCollectionId, filename, }: { - romIDs: number[]; + romIDs?: number[]; + platformId?: number; + collectionId?: number; + virtualCollectionId?: string; + smartCollectionId?: number; filename?: string; }) { - if (romIDs.length === 0) return; - const queryParams = new URLSearchParams(); - queryParams.append("rom_ids", romIDs.join(",")); + if (platformId != null) { + queryParams.append("platform_id", String(platformId)); + } else if (collectionId != null) { + queryParams.append("collection_id", String(collectionId)); + } else if (virtualCollectionId != null) { + queryParams.append("virtual_collection_id", virtualCollectionId); + } else if (smartCollectionId != null) { + queryParams.append("smart_collection_id", String(smartCollectionId)); + } else if (romIDs && romIDs.length > 0) { + queryParams.append("rom_ids", romIDs.join(",")); + } else { + return; + } if (filename) queryParams.append("filename", filename); return triggerFileDownload(`/api/roms/download?${queryParams.toString()}`); diff --git a/frontend/src/v2/views/Gallery/Collection.vue b/frontend/src/v2/views/Gallery/Collection.vue index b024d35bc..7657b3062 100644 --- a/frontend/src/v2/views/Gallery/Collection.vue +++ b/frontend/src/v2/views/Gallery/Collection.vue @@ -242,11 +242,20 @@ watch( }, ); +// ── Download ─────────────────────────────────────────────────── +// Triggered from the InfoPanel's download button. Delegates to the +// API's bulk-download endpoint, which streams a ZIP of all ROMs in the +// collection. The endpoint is smart enough to handle regular / virtual +// / smart collections, so we just pass the right ID and let it figure +// out which ROMs to include. function onDownload() { const c = currentCollection.value; if (!c || !c.rom_count) return; + const kind = currentKind.value; void romApi.bulkDownloadRoms({ - romIDs: c.rom_ids, + collectionId: kind === "regular" ? Number(c.id) : undefined, + virtualCollectionId: kind === "virtual" ? String(c.id) : undefined, + smartCollectionId: kind === "smart" ? Number(c.id) : undefined, filename: `${c.name}.zip`, }); snackbar.info(t("gallery.selection-download-many", { n: c.rom_count })); diff --git a/frontend/src/v2/views/Gallery/Platform.vue b/frontend/src/v2/views/Gallery/Platform.vue index b1a666c9f..a265ce4d6 100644 --- a/frontend/src/v2/views/Gallery/Platform.vue +++ b/frontend/src/v2/views/Gallery/Platform.vue @@ -43,7 +43,7 @@ const platformsStore = storePlatforms(); const galleryRoms = storeGalleryRoms(); const snackbar = useSnackbar(); const confirm = useConfirm(); -const { currentPlatform, total, romIdIndex } = storeToRefs(galleryRoms); +const { currentPlatform, total } = storeToRefs(galleryRoms); const notFound = ref(false); const shellRef = ref | null>(null); @@ -355,15 +355,15 @@ async function onRandomGame() { } } -// Download all — `romIdIndex` already holds every matching ROM ID for -// this platform (the gallery store populates it on load), so hand that -// straight to the zip download without a second fetch. +// Download all function onDownload() { const p = currentPlatform.value; - const romIDs = romIdIndex.value; - if (!p || romIDs.length === 0) return; - void romApi.bulkDownloadRoms({ romIDs, filename: `${p.display_name}.zip` }); - snackbar.info(t("gallery.selection-download-many", { n: romIDs.length })); + if (!p || !p.rom_count) return; + void romApi.bulkDownloadRoms({ + platformId: p.id, + filename: `${p.display_name}.zip`, + }); + snackbar.info(t("gallery.selection-download-many", { n: p.rom_count })); } async function onDelete() {