From 9f58919612c9a1c7bb2e9ce917f5bd943210d04c Mon Sep 17 00:00:00 2001 From: Spinnich Date: Thu, 2 Jul 2026 16:50:27 +0000 Subject: [PATCH 1/5] fix(collections): download whole collections as one zip (#3641, #3659) - Extend GET /api/roms/download to accept collection_id, virtual_collection_id or smart_collection_id as an alternative to rom_ids, with owner/public access checks and the zip named after the collection - v2 SelectionBar: bundle multi-selections into a single server-side zip instead of one anchor download per ROM (#3641) - v2 collection head: add a download-collection action that downloads by collection id, independent of gallery pagination (#3659) Co-Authored-By: Claude Fable 5 --- backend/endpoints/roms/__init__.py | 106 +++++- backend/tests/endpoints/roms/test_download.py | 309 ++++++++++++++++++ docs/BACKEND_ARCHITECTURE.md | 23 +- frontend/src/locales/bg_BG/collection.json | 1 + frontend/src/locales/cs_CZ/collection.json | 1 + frontend/src/locales/de_DE/collection.json | 1 + frontend/src/locales/en_GB/collection.json | 1 + frontend/src/locales/en_US/collection.json | 1 + frontend/src/locales/es_ES/collection.json | 1 + frontend/src/locales/fr_FR/collection.json | 1 + frontend/src/locales/hu_HU/collection.json | 1 + frontend/src/locales/it_IT/collection.json | 1 + frontend/src/locales/ja_JP/collection.json | 1 + frontend/src/locales/ko_KR/collection.json | 1 + frontend/src/locales/pl_PL/collection.json | 1 + frontend/src/locales/pt_BR/collection.json | 1 + frontend/src/locales/ro_RO/collection.json | 1 + frontend/src/locales/ru_RU/collection.json | 1 + frontend/src/locales/tr_TR/collection.json | 1 + frontend/src/locales/zh_CN/collection.json | 1 + frontend/src/locales/zh_TW/collection.json | 1 + frontend/src/services/api/rom.ts | 64 ++-- .../v2/components/Gallery/CollectionHead.vue | 27 +- .../v2/components/Gallery/SelectionBar.vue | 25 +- frontend/src/v2/views/Gallery/Collection.vue | 21 ++ 25 files changed, 524 insertions(+), 69 deletions(-) create mode 100644 backend/tests/endpoints/roms/test_download.py diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 3361b8c39..40323e5c6 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -44,7 +44,11 @@ from endpoints.responses.rom import ( RomUserSchema, SimpleRomSchema, ) -from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException +from exceptions.endpoint_exceptions import ( + CollectionNotFoundInDatabaseException, + CollectionPermissionError, + RomNotFoundInDatabaseException, +) from exceptions.fs_exceptions import RomAlreadyExistsException from handler.auth.constants import Scope from handler.auth.dependencies import ( @@ -52,7 +56,7 @@ from handler.auth.dependencies import ( assert_rom_visible, get_permissions, ) -from handler.database import db_rom_handler, db_save_handler +from handler.database import db_collection_handler, db_rom_handler, db_save_handler from handler.database.base_handler import sync_session from handler.filesystem import fs_resource_handler, fs_rom_handler from handler.filesystem.assets_handler import validate_image_upload @@ -814,11 +818,26 @@ 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, + collection_id: Annotated[ + int | None, + Query(description="Collection internal id to download as a zip file.", ge=1), + ] = None, + virtual_collection_id: Annotated[ + str | None, + Query(description="Virtual collection internal id to download as a zip file."), + ] = None, + smart_collection_id: Annotated[ + int | None, + Query( + description="Smart collection internal id to download as a zip file.", + ge=1, + ), + ] = None, filename: Annotated[ str | None, Query( @@ -826,31 +845,82 @@ async def download_roms( ), ] = None, ): - """Download a list of roms as a zip file.""" + """Download a list of roms, or a whole collection, as a zip file.""" current_username = ( request.user.username if request.user.is_authenticated else "unknown" ) - if not rom_ids: + sources = (rom_ids, collection_id, virtual_collection_id, smart_collection_id) + if sum(1 for source in sources if source) != 1: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, - detail="No ROM IDs provided", + detail=( + "Exactly one of rom_ids, collection_id, virtual_collection_id or" + " smart_collection_id must be provided" + ), ) - # 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 + collection_name: str | None = None - if not rom_id_list: + if 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 + + if not rom_id_list: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="No valid ROM IDs provided", + ) + elif collection_id: + collection = db_collection_handler.get_collection(collection_id) + if not collection: + raise CollectionNotFoundInDatabaseException(collection_id) + if collection.user_id != request.user.id and not collection.is_public: + raise CollectionPermissionError(collection_id) + + collection_name = collection.name + rom_id_list = collection.rom_ids + elif virtual_collection_id: + try: + virtual_collection = db_collection_handler.get_virtual_collection( + virtual_collection_id + ) + except (binascii.Error, ValueError, KeyError, UnicodeDecodeError): + # Malformed opaque id (base64-encoded name/type pair) + virtual_collection = None + if not virtual_collection: + raise CollectionNotFoundInDatabaseException(virtual_collection_id) + + collection_name = virtual_collection.name + rom_id_list = list(virtual_collection.rom_ids) + elif smart_collection_id: + smart_collection = db_collection_handler.get_smart_collection( + smart_collection_id + ) + if not smart_collection: + raise CollectionNotFoundInDatabaseException(smart_collection_id) + if ( + smart_collection.user_id != request.user.id + and not smart_collection.is_public + ): + raise CollectionPermissionError(smart_collection_id) + + # Recompute membership so the zip reflects the current filter results + smart_collection = smart_collection.update_properties(request.user.id) + collection_name = smart_collection.name + rom_id_list = list(smart_collection.rom_ids) + else: + # Unreachable: the single-source check above guarantees one branch raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, - detail="No valid ROM IDs provided", + detail="No download source provided", ) rom_objects = db_rom_handler.get_roms_by_ids(rom_id_list) @@ -895,6 +965,8 @@ async def download_roms( if filename: file_name = sanitize_filename(filename) + elif collection_name: + file_name = f"{sanitize_filename(collection_name)}.zip" else: base64_content = b64encode( ("\n".join([str(line) for line in content_lines])).encode() diff --git a/backend/tests/endpoints/roms/test_download.py b/backend/tests/endpoints/roms/test_download.py new file mode 100644 index 000000000..83f7401f5 --- /dev/null +++ b/backend/tests/endpoints/roms/test_download.py @@ -0,0 +1,309 @@ +from datetime import timedelta + +import pytest +from fastapi import status +from fastapi.testclient import TestClient + +from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS +from handler.auth import oauth_handler +from handler.database import db_collection_handler, db_rom_handler +from models.collection import Collection, SmartCollection +from models.platform import Platform +from models.rom import Rom, RomFile +from models.user import User + + +@pytest.fixture +def second_rom(admin_user: User, platform: Platform) -> Rom: + rom = Rom( + platform_id=platform.id, + name="test_rom_2", + slug="test_rom_slug_2", + fs_name="test_rom_2.zip", + fs_name_no_tags="test_rom_2", + fs_name_no_ext="test_rom_2", + fs_extension="zip", + fs_path=f"{platform.slug}/roms", + ) + rom = db_rom_handler.add_rom(rom) + db_rom_handler.add_rom_file( + RomFile( + rom_id=rom.id, + file_name="test_rom_2.zip", + file_path=rom.fs_path, + file_size_bytes=2000, + ) + ) + return rom + + +@pytest.fixture +def collection(admin_user: User, rom: Rom, second_rom: Rom) -> Collection: + collection = db_collection_handler.add_collection( + Collection( + name="Best Games", + description="", + is_public=False, + is_favorite=False, + user_id=admin_user.id, + ) + ) + return db_collection_handler.update_collection( + collection.id, {"name": collection.name}, rom_ids=[rom.id, second_rom.id] + ) + + +@pytest.fixture +def viewer_token(viewer_user: User) -> str: + return oauth_handler.create_access_token( + data={ + "sub": viewer_user.username, + "iss": "romm:oauth", + "scopes": " ".join(viewer_user.oauth_scopes), + }, + expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS), + ) + + +def test_download_roms_by_ids( + client: TestClient, access_token: str, rom: Rom, rom_file: RomFile, second_rom: Rom +): + response = client.get( + "/api/roms/download", + headers={"Authorization": f"Bearer {access_token}"}, + params={"rom_ids": f"{rom.id},{second_rom.id}"}, + ) + assert response.status_code == status.HTTP_200_OK + assert response.headers["X-Archive-Files"] == "zip" + assert "2%20ROMs" in response.headers["Content-Disposition"] + assert "test_rom.zip" in response.text + assert "test_rom_2.zip" in response.text + + +def test_download_roms_by_ids_invalid_format(client: TestClient, access_token: str): + response = client.get( + "/api/roms/download", + headers={"Authorization": f"Bearer {access_token}"}, + params={"rom_ids": "1,abc"}, + ) + assert response.status_code == status.HTTP_400_BAD_REQUEST + + +def test_download_requires_exactly_one_source( + client: TestClient, access_token: str, rom: Rom, collection: Collection +): + response = client.get( + "/api/roms/download", + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert response.status_code == status.HTTP_400_BAD_REQUEST + + response = client.get( + "/api/roms/download", + headers={"Authorization": f"Bearer {access_token}"}, + params={"rom_ids": str(rom.id), "collection_id": collection.id}, + ) + assert response.status_code == status.HTTP_400_BAD_REQUEST + + +def test_download_collection( + client: TestClient, + access_token: str, + rom: Rom, + rom_file: RomFile, + second_rom: Rom, + collection: Collection, +): + response = client.get( + "/api/roms/download", + headers={"Authorization": f"Bearer {access_token}"}, + params={"collection_id": collection.id}, + ) + assert response.status_code == status.HTTP_200_OK + assert response.headers["X-Archive-Files"] == "zip" + # The zip is named after the collection instead of the generic "N ROMs" + assert "Best%20Games.zip" in response.headers["Content-Disposition"] + assert "test_rom.zip" in response.text + assert "test_rom_2.zip" in response.text + + +def test_download_collection_explicit_filename_wins( + client: TestClient, + access_token: str, + rom: Rom, + rom_file: RomFile, + collection: Collection, +): + response = client.get( + "/api/roms/download", + headers={"Authorization": f"Bearer {access_token}"}, + params={"collection_id": collection.id, "filename": "custom.zip"}, + ) + assert response.status_code == status.HTTP_200_OK + assert "custom.zip" in response.headers["Content-Disposition"] + + +def test_download_collection_not_found(client: TestClient, access_token: str): + response = client.get( + "/api/roms/download", + headers={"Authorization": f"Bearer {access_token}"}, + params={"collection_id": 999999}, + ) + assert response.status_code == status.HTTP_404_NOT_FOUND + + +def test_download_private_collection_of_other_user_forbidden( + client: TestClient, viewer_token: str, collection: Collection +): + response = client.get( + "/api/roms/download", + headers={"Authorization": f"Bearer {viewer_token}"}, + params={"collection_id": collection.id}, + ) + assert response.status_code == status.HTTP_403_FORBIDDEN + + +def test_download_public_collection_of_other_user_allowed( + client: TestClient, + viewer_token: str, + rom: Rom, + rom_file: RomFile, + collection: Collection, +): + db_collection_handler.update_collection(collection.id, {"is_public": True}) + + response = client.get( + "/api/roms/download", + headers={"Authorization": f"Bearer {viewer_token}"}, + params={"collection_id": collection.id}, + ) + assert response.status_code == status.HTTP_200_OK + assert "test_rom.zip" in response.text + + +def test_download_smart_collection( + client: TestClient, + access_token: str, + admin_user: User, + platform: Platform, + rom: Rom, + rom_file: RomFile, + second_rom: Rom, +): + smart_collection = db_collection_handler.add_smart_collection( + SmartCollection( + name="Platform Games", + description="", + is_public=False, + filter_criteria={"platform_ids": [platform.id]}, + user_id=admin_user.id, + ) + ) + + response = client.get( + "/api/roms/download", + headers={"Authorization": f"Bearer {access_token}"}, + params={"smart_collection_id": smart_collection.id}, + ) + assert response.status_code == status.HTTP_200_OK + assert "Platform%20Games.zip" in response.headers["Content-Disposition"] + # Membership is recomputed from the filter criteria at download time + assert "test_rom.zip" in response.text + assert "test_rom_2.zip" in response.text + + +def test_download_private_smart_collection_of_other_user_forbidden( + client: TestClient, + viewer_token: str, + admin_user: User, + platform: Platform, +): + smart_collection = db_collection_handler.add_smart_collection( + SmartCollection( + name="Admin Only", + description="", + is_public=False, + filter_criteria={"platform_ids": [platform.id]}, + user_id=admin_user.id, + ) + ) + + response = client.get( + "/api/roms/download", + headers={"Authorization": f"Bearer {viewer_token}"}, + params={"smart_collection_id": smart_collection.id}, + ) + assert response.status_code == status.HTTP_403_FORBIDDEN + + +def test_download_virtual_collection( + client: TestClient, + access_token: str, + admin_user: User, + platform: Platform, + rom: Rom, + rom_file: RomFile, + second_rom: Rom, +): + # The virtual_collections DB view derives a "genre" collection from + # each rom's igdb_metadata genres, and only materializes it once more + # than two roms share the value. + third_rom = db_rom_handler.add_rom( + Rom( + platform_id=platform.id, + name="test_rom_3", + slug="test_rom_slug_3", + fs_name="test_rom_3.zip", + fs_name_no_tags="test_rom_3", + fs_name_no_ext="test_rom_3", + fs_extension="zip", + fs_path=f"{platform.slug}/roms", + ) + ) + for rom_id in (rom.id, second_rom.id, third_rom.id): + db_rom_handler.update_rom(rom_id, {"igdb_metadata": {"genres": ["Action"]}}) + + virtual_collections = db_collection_handler.get_virtual_collections("genre") + assert len(virtual_collections) == 1 + + response = client.get( + "/api/roms/download", + headers={"Authorization": f"Bearer {access_token}"}, + params={"virtual_collection_id": virtual_collections[0].id}, + ) + assert response.status_code == status.HTTP_200_OK + assert "Action.zip" in response.headers["Content-Disposition"] + assert "test_rom.zip" in response.text + assert "test_rom_2.zip" in response.text + + +def test_download_virtual_collection_malformed_id( + client: TestClient, access_token: str +): + response = client.get( + "/api/roms/download", + headers={"Authorization": f"Bearer {access_token}"}, + params={"virtual_collection_id": "not-a-valid-id"}, + ) + assert response.status_code == status.HTTP_404_NOT_FOUND + + +def test_download_empty_collection_returns_404( + client: TestClient, access_token: str, admin_user: User +): + empty = db_collection_handler.add_collection( + Collection( + name="Empty", + description="", + is_public=False, + is_favorite=False, + user_id=admin_user.id, + ) + ) + + response = client.get( + "/api/roms/download", + headers={"Authorization": f"Bearer {access_token}"}, + params={"collection_id": empty.id}, + ) + assert response.status_code == status.HTTP_404_NOT_FOUND diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index ec3b3ef54..a40ea15e4 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -818,17 +818,18 @@ Migrations support batch mode for SQLite and DB-specific SQL for MariaDB/MySQL/P ### 6.5 ROMs (`/api/roms`) -| Method | Path | Scope | Description | -| ------ | ---------------------------- | ---------- | --------------------------------- | -| GET | `/` | ROMS_READ | List ROMs (paginated, filterable) | -| GET | `/identifiers` | ROMS_READ | Get ROM IDs | -| GET | `/{id}` | ROMS_READ | Get ROM details | -| PUT | `/{id}` | ROMS_WRITE | Update ROM metadata | -| PUT | `/{id}/user` | ME_WRITE | Update user-specific ROM data | -| DELETE | `/{id}` | ROMS_WRITE | Delete ROM | -| POST | `/delete` | ROMS_WRITE | Bulk delete | -| POST | `/download/{id}/{file_name}` | ROMS_READ | Download ROM | -| POST | `/unidentified` | ROMS_READ | Get unidentified ROMs | +| Method | Path | Scope | Description | +| ------ | ---------------------------- | ---------- | --------------------------------------------------- | +| GET | `/` | ROMS_READ | List ROMs (paginated, filterable) | +| GET | `/identifiers` | ROMS_READ | Get ROM IDs | +| GET | `/{id}` | ROMS_READ | Get ROM details | +| PUT | `/{id}` | ROMS_WRITE | Update ROM metadata | +| PUT | `/{id}/user` | ME_WRITE | Update user-specific ROM data | +| DELETE | `/{id}` | ROMS_WRITE | Delete ROM | +| POST | `/delete` | ROMS_WRITE | Bulk delete | +| GET | `/download` | ROMS_READ | Bulk download as one zip (ROM ids or collection id) | +| POST | `/download/{id}/{file_name}` | ROMS_READ | Download ROM | +| POST | `/unidentified` | ROMS_READ | Get unidentified ROMs | #### ROM Upload (Chunked) diff --git a/frontend/src/locales/bg_BG/collection.json b/frontend/src/locales/bg_BG/collection.json index 5afcce804..d9771ee1c 100644 --- a/frontend/src/locales/bg_BG/collection.json +++ b/frontend/src/locales/bg_BG/collection.json @@ -6,6 +6,7 @@ "danger-zone": "Опасна зона", "delete-collection": "Изтрий колекция", "description": "Описание", + "download-collection": "Изтегли колекция", "edit-collection": "Редактирай колекция", "name": "Име", "owner": "Собственик", diff --git a/frontend/src/locales/cs_CZ/collection.json b/frontend/src/locales/cs_CZ/collection.json index c3e235a98..3f409ccaf 100644 --- a/frontend/src/locales/cs_CZ/collection.json +++ b/frontend/src/locales/cs_CZ/collection.json @@ -8,6 +8,7 @@ "delete-collection": "Smazat kolekci", "delete-collection-hint": "Odstraní kolekci z RomM. Samotné soubory ROM se nesmažou.", "description": "Popis", + "download-collection": "Stáhnout kolekci", "edit-collection": "Upravit kolekci", "filters": "Filtry", "name": "Název", diff --git a/frontend/src/locales/de_DE/collection.json b/frontend/src/locales/de_DE/collection.json index b8ba15693..72816d330 100644 --- a/frontend/src/locales/de_DE/collection.json +++ b/frontend/src/locales/de_DE/collection.json @@ -6,6 +6,7 @@ "danger-zone": "Gefahrenzone", "delete-collection": "Sammlung löschen", "description": "Beschreibung", + "download-collection": "Sammlung herunterladen", "edit-collection": "Sammlung bearbeiten", "name": "Name", "owner": "Besitzer", diff --git a/frontend/src/locales/en_GB/collection.json b/frontend/src/locales/en_GB/collection.json index 0d52d0955..a31ff029e 100644 --- a/frontend/src/locales/en_GB/collection.json +++ b/frontend/src/locales/en_GB/collection.json @@ -6,6 +6,7 @@ "danger-zone": "Danger zone", "delete-collection": "Delete collection", "description": "Description", + "download-collection": "Download collection", "edit-collection": "Edit collection", "name": "Name", "owner": "Owner", diff --git a/frontend/src/locales/en_US/collection.json b/frontend/src/locales/en_US/collection.json index 0da4d1a48..760cbbdb5 100644 --- a/frontend/src/locales/en_US/collection.json +++ b/frontend/src/locales/en_US/collection.json @@ -8,6 +8,7 @@ "delete-collection": "Delete collection", "delete-collection-hint": "Removes the collection from RomM. The ROM files themselves are not deleted.", "description": "Description", + "download-collection": "Download collection", "edit-collection": "Edit collection", "filters": "Filters", "name": "Name", diff --git a/frontend/src/locales/es_ES/collection.json b/frontend/src/locales/es_ES/collection.json index 5c54495cd..0153101f0 100644 --- a/frontend/src/locales/es_ES/collection.json +++ b/frontend/src/locales/es_ES/collection.json @@ -6,6 +6,7 @@ "danger-zone": "Zona de peligro", "delete-collection": "Eliminar colección", "description": "Descripción", + "download-collection": "Descargar colección", "edit-collection": "Editar colección", "name": "Nombre", "owner": "Propietario", diff --git a/frontend/src/locales/fr_FR/collection.json b/frontend/src/locales/fr_FR/collection.json index 652530d28..6d774ec91 100644 --- a/frontend/src/locales/fr_FR/collection.json +++ b/frontend/src/locales/fr_FR/collection.json @@ -6,6 +6,7 @@ "danger-zone": "Zone de danger", "delete-collection": "Supprimer la collection", "description": "Description", + "download-collection": "Télécharger la collection", "edit-collection": "Modifier la collection", "name": "Nom", "owner": "Propriétaire", diff --git a/frontend/src/locales/hu_HU/collection.json b/frontend/src/locales/hu_HU/collection.json index f8f9c6ae0..145a44031 100644 --- a/frontend/src/locales/hu_HU/collection.json +++ b/frontend/src/locales/hu_HU/collection.json @@ -6,6 +6,7 @@ "danger-zone": "Veszélyzóna", "delete-collection": "Gyüjtemény törlése", "description": "Leírás", + "download-collection": "Gyüjtemény letöltése", "edit-collection": "Gyüjtemény szerkesztése", "name": "Név", "owner": "Tulajdonos", diff --git a/frontend/src/locales/it_IT/collection.json b/frontend/src/locales/it_IT/collection.json index 55a0863f3..a909efd8f 100644 --- a/frontend/src/locales/it_IT/collection.json +++ b/frontend/src/locales/it_IT/collection.json @@ -6,6 +6,7 @@ "danger-zone": "Zona pericolosa", "delete-collection": "Elimina collezione", "description": "Descrizione", + "download-collection": "Scarica collezione", "edit-collection": "Modifica collezione", "name": "Nome", "owner": "Proprietario", diff --git a/frontend/src/locales/ja_JP/collection.json b/frontend/src/locales/ja_JP/collection.json index 8288ca859..86a9ba7ff 100644 --- a/frontend/src/locales/ja_JP/collection.json +++ b/frontend/src/locales/ja_JP/collection.json @@ -6,6 +6,7 @@ "danger-zone": "危険", "delete-collection": "コレクションを削除", "description": "説明", + "download-collection": "コレクションをダウンロード", "edit-collection": "コレクションを編集", "name": "名前", "owner": "所有者", diff --git a/frontend/src/locales/ko_KR/collection.json b/frontend/src/locales/ko_KR/collection.json index 4477d8b1d..4db6f10dd 100644 --- a/frontend/src/locales/ko_KR/collection.json +++ b/frontend/src/locales/ko_KR/collection.json @@ -6,6 +6,7 @@ "danger-zone": "위험 구역", "delete-collection": "모음집 삭제", "description": "설명", + "download-collection": "모음집 다운로드", "edit-collection": "모음집 수정", "name": "이름", "owner": "소유자", diff --git a/frontend/src/locales/pl_PL/collection.json b/frontend/src/locales/pl_PL/collection.json index 680cdf8fd..5efa1aa3a 100644 --- a/frontend/src/locales/pl_PL/collection.json +++ b/frontend/src/locales/pl_PL/collection.json @@ -6,6 +6,7 @@ "danger-zone": "Strefa Śmierci", "delete-collection": "Usuń kolekcje", "description": "Opis", + "download-collection": "Pobierz kolekcje", "edit-collection": "Edytuj kolekcje", "name": "Nazwa", "owner": "Właściciel", diff --git a/frontend/src/locales/pt_BR/collection.json b/frontend/src/locales/pt_BR/collection.json index 85abcec9d..b0d9f305d 100644 --- a/frontend/src/locales/pt_BR/collection.json +++ b/frontend/src/locales/pt_BR/collection.json @@ -6,6 +6,7 @@ "danger-zone": "Zona de perigo", "delete-collection": "Excluir coleção", "description": "Descrição", + "download-collection": "Baixar coleção", "edit-collection": "Editar coleção", "name": "Nome", "owner": "Proprietário", diff --git a/frontend/src/locales/ro_RO/collection.json b/frontend/src/locales/ro_RO/collection.json index 034ba8e15..defe11e7a 100644 --- a/frontend/src/locales/ro_RO/collection.json +++ b/frontend/src/locales/ro_RO/collection.json @@ -8,6 +8,7 @@ "delete-collection": "Șterge colecția", "delete-collection-hint": "Elimină colecția din RomM. Fișierele ROM nu sunt șterse.", "description": "Descriere", + "download-collection": "Descarcă colecția", "edit-collection": "Editează colecția", "filters": "Filtre", "name": "Nume", diff --git a/frontend/src/locales/ru_RU/collection.json b/frontend/src/locales/ru_RU/collection.json index 0d693e846..0f1c6fb02 100644 --- a/frontend/src/locales/ru_RU/collection.json +++ b/frontend/src/locales/ru_RU/collection.json @@ -6,6 +6,7 @@ "danger-zone": "Опасная зона", "delete-collection": "Удалить коллекцию", "description": "Описание", + "download-collection": "Скачать коллекцию", "edit-collection": "Редактировать коллекцию", "name": "Имя", "owner": "Владелец", diff --git a/frontend/src/locales/tr_TR/collection.json b/frontend/src/locales/tr_TR/collection.json index 418241ef2..7fa6b1802 100644 --- a/frontend/src/locales/tr_TR/collection.json +++ b/frontend/src/locales/tr_TR/collection.json @@ -8,6 +8,7 @@ "delete-collection": "Koleksiyonu sil", "delete-collection-hint": "Koleksiyonu RomM'den kaldırır. ROM dosyalarının kendisi silinmez.", "description": "Açıklama", + "download-collection": "Koleksiyonu indir", "edit-collection": "Koleksiyonu düzenle", "filters": "Filtreler", "name": "İsim", diff --git a/frontend/src/locales/zh_CN/collection.json b/frontend/src/locales/zh_CN/collection.json index d829e7cae..7c56ad54b 100644 --- a/frontend/src/locales/zh_CN/collection.json +++ b/frontend/src/locales/zh_CN/collection.json @@ -6,6 +6,7 @@ "danger-zone": "危险区", "delete-collection": "删除收藏", "description": "描述", + "download-collection": "下载收藏", "edit-collection": "编辑收藏", "name": "名称", "owner": "创建者", diff --git a/frontend/src/locales/zh_TW/collection.json b/frontend/src/locales/zh_TW/collection.json index 54ed98593..70fe5768f 100644 --- a/frontend/src/locales/zh_TW/collection.json +++ b/frontend/src/locales/zh_TW/collection.json @@ -6,6 +6,7 @@ "danger-zone": "危險操作", "delete-collection": "刪除收藏庫", "description": "說明", + "download-collection": "下載收藏庫", "edit-collection": "編輯收藏庫", "name": "名稱", "owner": "建立者", diff --git a/frontend/src/services/api/rom.ts b/frontend/src/services/api/rom.ts index 840f522b9..e53c994e7 100644 --- a/frontend/src/services/api/rom.ts +++ b/frontend/src/services/api/rom.ts @@ -426,16 +426,10 @@ async function searchRom({ }); } -async function downloadRom({ - rom, - fileIDs = [], -}: { - rom: SimpleRom; - fileIDs?: number[]; -}) { +function triggerFileDownload(href: string) { return new Promise((resolve) => { const a = document.createElement("a"); - a.href = getDownloadPath({ rom, fileIDs }); + a.href = href; a.style.display = "none"; document.body.appendChild(a); @@ -448,6 +442,16 @@ async function downloadRom({ }); } +async function downloadRom({ + rom, + fileIDs = [], +}: { + rom: SimpleRom; + fileIDs?: number[]; +}) { + return triggerFileDownload(getDownloadPath({ rom, fileIDs })); +} + async function bulkDownloadRoms({ roms, filename, @@ -455,27 +459,38 @@ async function bulkDownloadRoms({ roms: SimpleRom[]; filename?: string; }) { - return new Promise((resolve) => { - if (roms.length === 0) return resolve(); + if (roms.length === 0) return; - const romIds = roms.map((rom) => rom.id); + const romIds = roms.map((rom) => rom.id); - const queryParams = new URLSearchParams(); - queryParams.append("rom_ids", romIds.join(",")); - if (filename) queryParams.append("filename", filename); + const queryParams = new URLSearchParams(); + queryParams.append("rom_ids", romIds.join(",")); + if (filename) queryParams.append("filename", filename); - const a = document.createElement("a"); - a.href = `/api/roms/download?${queryParams.toString()}`; - a.style.display = "none"; + return triggerFileDownload(`/api/roms/download?${queryParams.toString()}`); +} - document.body.appendChild(a); - a.click(); +async function downloadCollectionRoms({ + collectionId, + kind, + filename, +}: { + collectionId: number | string; + kind: "regular" | "virtual" | "smart"; + filename?: string; +}) { + const paramName = + kind === "virtual" + ? "virtual_collection_id" + : kind === "smart" + ? "smart_collection_id" + : "collection_id"; - setTimeout(() => { - document.body.removeChild(a); - resolve(); - }, DOWNLOAD_CLEANUP_DELAY); - }); + const queryParams = new URLSearchParams(); + queryParams.append(paramName, String(collectionId)); + if (filename) queryParams.append("filename", filename); + + return triggerFileDownload(`/api/roms/download?${queryParams.toString()}`); } export type UpdateRom = SimpleRom & { @@ -886,6 +901,7 @@ export default { getRomByMetadataProvider, downloadRom, bulkDownloadRoms, + downloadCollectionRoms, searchRom, updateRom, uploadManuals, diff --git a/frontend/src/v2/components/Gallery/CollectionHead.vue b/frontend/src/v2/components/Gallery/CollectionHead.vue index 8a9b3f5c9..b90499d2f 100644 --- a/frontend/src/v2/components/Gallery/CollectionHead.vue +++ b/frontend/src/v2/components/Gallery/CollectionHead.vue @@ -13,9 +13,10 @@ // plain scroll wrapper. The head scrolls together with the // tab content. // -// No action ribbon — edit and delete moved inline into the Settings -// tab (editable form + danger zone), matching the Platform layout. -import { RChip, RTabNav } from "@v2/lib"; +// The action ribbon only carries the whole-collection download — +// edit and delete moved inline into the Settings tab (editable form +// + danger zone), matching the Platform layout. +import { RBtn, RChip, RTabNav } from "@v2/lib"; import type { RTabNavItem } from "@v2/lib"; import { useI18n } from "vue-i18n"; import type { @@ -44,10 +45,14 @@ defineProps<{ covers: string[]; tab: string; tabs: RTabNavItem[]; + /** Permission flag — already evaluated against `useCan` in the + * parent, mirroring PlatformHead's prop-based gating. */ + canDownload: boolean; }>(); defineEmits<{ (e: "update:tab", v: string): void; + (e: "download"): void; }>(); @@ -77,6 +82,22 @@ defineEmits<{ + + + 1) { - snackbar.info(t("gallery.selection-download-many", { n: roms.length })); + if (roms.length === 1) { + void romApi.downloadRom({ rom: roms[0] }); + return; } + // Bundle multi-selections into a single zip server-side; firing one + // anchor download per ROM trips browser multi-download blocking. + void romApi.bulkDownloadRoms({ roms }); + snackbar.info(t("gallery.selection-download-many", { n: roms.length })); } function bulkRefresh() { diff --git a/frontend/src/v2/views/Gallery/Collection.vue b/frontend/src/v2/views/Gallery/Collection.vue index 748b15406..67aec0b62 100644 --- a/frontend/src/v2/views/Gallery/Collection.vue +++ b/frontend/src/v2/views/Gallery/Collection.vue @@ -20,6 +20,7 @@ import { useI18n } from "vue-i18n"; import { onBeforeRouteUpdate, useRoute, useRouter } from "vue-router"; import { ROUTES } from "@/plugins/router"; import collectionApi from "@/services/api/collection"; +import romApi from "@/services/api/rom"; import storeAuth from "@/stores/auth"; import storeCollections, { type Collection, @@ -29,6 +30,7 @@ import storeCollections, { import CollectionHead from "@/v2/components/Gallery/CollectionHead.vue"; import CollectionSettingsTab from "@/v2/components/Gallery/CollectionSettingsTab.vue"; import GalleryShell from "@/v2/components/Gallery/GalleryShell.vue"; +import { useCan } from "@/v2/composables/useCan"; import { useConfirm } from "@/v2/composables/useConfirm"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import { useWebpSupport } from "@/v2/composables/useWebpSupport"; @@ -53,6 +55,7 @@ const currentKind = ref("regular"); const currentCollection = ref(null); const shellRef = ref | null>(null); const deleting = ref(false); +const canDownload = useCan("rom.download"); // Virtual collections are computed (no editable fields) — only // regular / smart get the Settings tab. @@ -239,6 +242,20 @@ watch( }, ); +// ── Download ──────────────────────────────────────────────────── +// Whole-collection download by id — the server resolves the current +// member list and streams one zip, so nothing depends on how many +// pages the gallery has loaded (issue #3659). +function onDownload() { + const c = currentCollection.value; + if (!c || !c.rom_count) return; + void romApi.downloadCollectionRoms({ + collectionId: c.id, + kind: currentKind.value, + }); + snackbar.info(t("gallery.selection-download-many", { n: c.rom_count })); +} + // ── Delete ────────────────────────────────────────────────────── // Mirrors the Platform.vue admin flow: confirm dialog with // `requireTyped` on the collection name, then API call → store remove @@ -313,7 +330,9 @@ async function onDelete() { :covers="mosaicCovers" :tab="tab" :tabs="tabs" + :can-download="canDownload" @update:tab="onTabChange" + @download="onDownload" /> @@ -331,7 +350,9 @@ async function onDelete() { :covers="mosaicCovers" :tab="tab" :tabs="tabs" + :can-download="canDownload" @update:tab="onTabChange" + @download="onDownload" />
Date: Sat, 4 Jul 2026 12:49:31 -0400 Subject: [PATCH 2/5] simplification --- backend/endpoints/roms/__init__.py | 100 +----- backend/tests/endpoints/roms/test_download.py | 309 ------------------ .../src/components/Gallery/FabOverlay.vue | 4 +- frontend/src/services/api/rom.ts | 34 +- .../v2/components/Gallery/CollectionHead.vue | 5 - .../v2/components/Gallery/SelectionBar.vue | 2 +- frontend/src/v2/views/Gallery/Collection.vue | 9 +- 7 files changed, 24 insertions(+), 439 deletions(-) delete mode 100644 backend/tests/endpoints/roms/test_download.py diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 802640bbd..0a457c362 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -713,8 +713,8 @@ def get_roms( filter_query = db_rom_handler.filter_roms( query=unfiltered_query, user_id=request.user.id, - hidden_platform_ids=perms.hidden_platform_ids, - hidden_rom_ids=perms.hidden_rom_ids, + hidden_platform_ids=list(perms.hidden_platform_ids), + hidden_rom_ids=list(perms.hidden_rom_ids), platform_ids=platform_ids, collection_id=collection_id, virtual_collection_id=virtual_collection_id, @@ -825,26 +825,11 @@ def get_rom_identifiers( async def download_roms( request: Request, rom_ids: Annotated[ - str | None, + str, Query( description="Comma-separated list of ROM IDs to download as a zip file.", ), - ] = None, - collection_id: Annotated[ - int | None, - Query(description="Collection internal id to download as a zip file.", ge=1), - ] = None, - virtual_collection_id: Annotated[ - str | None, - Query(description="Virtual collection internal id to download as a zip file."), - ] = None, - smart_collection_id: Annotated[ - int | None, - Query( - description="Smart collection internal id to download as a zip file.", - ge=1, - ), - ] = None, + ], filename: Annotated[ str | None, Query( @@ -852,83 +837,28 @@ async def download_roms( ), ] = None, ): - """Download a list of roms, or a whole collection, as a zip file.""" + """Download a list of roms as a zip file.""" current_username = ( request.user.username if request.user.is_authenticated else "unknown" ) - sources = (rom_ids, collection_id, virtual_collection_id, smart_collection_id) - if sum(1 for source in sources if source) != 1: + if not rom_ids: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, - detail=( - "Exactly one of rom_ids, collection_id, virtual_collection_id or" - " smart_collection_id must be provided" - ), + detail="No ROM IDs provided", ) - collection_name: str | None = None + collection_name: str | None = None - if 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 - - if not rom_id_list: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="No valid ROM IDs provided", - ) - elif collection_id: - collection = db_collection_handler.get_collection(collection_id) - if not collection: - raise CollectionNotFoundInDatabaseException(collection_id) - if collection.user_id != request.user.id and not collection.is_public: - raise CollectionPermissionError(collection_id) - - collection_name = collection.name - rom_id_list = collection.rom_ids - elif virtual_collection_id: - try: - virtual_collection = db_collection_handler.get_virtual_collection( - virtual_collection_id - ) - except (binascii.Error, ValueError, KeyError, UnicodeDecodeError): - # Malformed opaque id (base64-encoded name/type pair) - virtual_collection = None - if not virtual_collection: - raise CollectionNotFoundInDatabaseException(virtual_collection_id) - - collection_name = virtual_collection.name - rom_id_list = list(virtual_collection.rom_ids) - elif smart_collection_id: - smart_collection = db_collection_handler.get_smart_collection( - smart_collection_id - ) - if not smart_collection: - raise CollectionNotFoundInDatabaseException(smart_collection_id) - if ( - smart_collection.user_id != request.user.id - and not smart_collection.is_public - ): - raise CollectionPermissionError(smart_collection_id) - - # Recompute membership so the zip reflects the current filter results - smart_collection = smart_collection.update_properties(request.user.id) - collection_name = smart_collection.name - rom_id_list = list(smart_collection.rom_ids) - else: - # Unreachable: the single-source check above guarantees one branch + # 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="No download source provided", - ) + detail="Invalid ROM ID format. Must be comma-separated integers.", + ) from e rom_objects = db_rom_handler.get_roms_by_ids(rom_id_list) @@ -972,8 +902,6 @@ async def download_roms( if filename: file_name = sanitize_filename(filename) - elif collection_name: - file_name = f"{sanitize_filename(collection_name)}.zip" else: base64_content = b64encode( ("\n".join([str(line) for line in content_lines])).encode() diff --git a/backend/tests/endpoints/roms/test_download.py b/backend/tests/endpoints/roms/test_download.py deleted file mode 100644 index 83f7401f5..000000000 --- a/backend/tests/endpoints/roms/test_download.py +++ /dev/null @@ -1,309 +0,0 @@ -from datetime import timedelta - -import pytest -from fastapi import status -from fastapi.testclient import TestClient - -from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS -from handler.auth import oauth_handler -from handler.database import db_collection_handler, db_rom_handler -from models.collection import Collection, SmartCollection -from models.platform import Platform -from models.rom import Rom, RomFile -from models.user import User - - -@pytest.fixture -def second_rom(admin_user: User, platform: Platform) -> Rom: - rom = Rom( - platform_id=platform.id, - name="test_rom_2", - slug="test_rom_slug_2", - fs_name="test_rom_2.zip", - fs_name_no_tags="test_rom_2", - fs_name_no_ext="test_rom_2", - fs_extension="zip", - fs_path=f"{platform.slug}/roms", - ) - rom = db_rom_handler.add_rom(rom) - db_rom_handler.add_rom_file( - RomFile( - rom_id=rom.id, - file_name="test_rom_2.zip", - file_path=rom.fs_path, - file_size_bytes=2000, - ) - ) - return rom - - -@pytest.fixture -def collection(admin_user: User, rom: Rom, second_rom: Rom) -> Collection: - collection = db_collection_handler.add_collection( - Collection( - name="Best Games", - description="", - is_public=False, - is_favorite=False, - user_id=admin_user.id, - ) - ) - return db_collection_handler.update_collection( - collection.id, {"name": collection.name}, rom_ids=[rom.id, second_rom.id] - ) - - -@pytest.fixture -def viewer_token(viewer_user: User) -> str: - return oauth_handler.create_access_token( - data={ - "sub": viewer_user.username, - "iss": "romm:oauth", - "scopes": " ".join(viewer_user.oauth_scopes), - }, - expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS), - ) - - -def test_download_roms_by_ids( - client: TestClient, access_token: str, rom: Rom, rom_file: RomFile, second_rom: Rom -): - response = client.get( - "/api/roms/download", - headers={"Authorization": f"Bearer {access_token}"}, - params={"rom_ids": f"{rom.id},{second_rom.id}"}, - ) - assert response.status_code == status.HTTP_200_OK - assert response.headers["X-Archive-Files"] == "zip" - assert "2%20ROMs" in response.headers["Content-Disposition"] - assert "test_rom.zip" in response.text - assert "test_rom_2.zip" in response.text - - -def test_download_roms_by_ids_invalid_format(client: TestClient, access_token: str): - response = client.get( - "/api/roms/download", - headers={"Authorization": f"Bearer {access_token}"}, - params={"rom_ids": "1,abc"}, - ) - assert response.status_code == status.HTTP_400_BAD_REQUEST - - -def test_download_requires_exactly_one_source( - client: TestClient, access_token: str, rom: Rom, collection: Collection -): - response = client.get( - "/api/roms/download", - headers={"Authorization": f"Bearer {access_token}"}, - ) - assert response.status_code == status.HTTP_400_BAD_REQUEST - - response = client.get( - "/api/roms/download", - headers={"Authorization": f"Bearer {access_token}"}, - params={"rom_ids": str(rom.id), "collection_id": collection.id}, - ) - assert response.status_code == status.HTTP_400_BAD_REQUEST - - -def test_download_collection( - client: TestClient, - access_token: str, - rom: Rom, - rom_file: RomFile, - second_rom: Rom, - collection: Collection, -): - response = client.get( - "/api/roms/download", - headers={"Authorization": f"Bearer {access_token}"}, - params={"collection_id": collection.id}, - ) - assert response.status_code == status.HTTP_200_OK - assert response.headers["X-Archive-Files"] == "zip" - # The zip is named after the collection instead of the generic "N ROMs" - assert "Best%20Games.zip" in response.headers["Content-Disposition"] - assert "test_rom.zip" in response.text - assert "test_rom_2.zip" in response.text - - -def test_download_collection_explicit_filename_wins( - client: TestClient, - access_token: str, - rom: Rom, - rom_file: RomFile, - collection: Collection, -): - response = client.get( - "/api/roms/download", - headers={"Authorization": f"Bearer {access_token}"}, - params={"collection_id": collection.id, "filename": "custom.zip"}, - ) - assert response.status_code == status.HTTP_200_OK - assert "custom.zip" in response.headers["Content-Disposition"] - - -def test_download_collection_not_found(client: TestClient, access_token: str): - response = client.get( - "/api/roms/download", - headers={"Authorization": f"Bearer {access_token}"}, - params={"collection_id": 999999}, - ) - assert response.status_code == status.HTTP_404_NOT_FOUND - - -def test_download_private_collection_of_other_user_forbidden( - client: TestClient, viewer_token: str, collection: Collection -): - response = client.get( - "/api/roms/download", - headers={"Authorization": f"Bearer {viewer_token}"}, - params={"collection_id": collection.id}, - ) - assert response.status_code == status.HTTP_403_FORBIDDEN - - -def test_download_public_collection_of_other_user_allowed( - client: TestClient, - viewer_token: str, - rom: Rom, - rom_file: RomFile, - collection: Collection, -): - db_collection_handler.update_collection(collection.id, {"is_public": True}) - - response = client.get( - "/api/roms/download", - headers={"Authorization": f"Bearer {viewer_token}"}, - params={"collection_id": collection.id}, - ) - assert response.status_code == status.HTTP_200_OK - assert "test_rom.zip" in response.text - - -def test_download_smart_collection( - client: TestClient, - access_token: str, - admin_user: User, - platform: Platform, - rom: Rom, - rom_file: RomFile, - second_rom: Rom, -): - smart_collection = db_collection_handler.add_smart_collection( - SmartCollection( - name="Platform Games", - description="", - is_public=False, - filter_criteria={"platform_ids": [platform.id]}, - user_id=admin_user.id, - ) - ) - - response = client.get( - "/api/roms/download", - headers={"Authorization": f"Bearer {access_token}"}, - params={"smart_collection_id": smart_collection.id}, - ) - assert response.status_code == status.HTTP_200_OK - assert "Platform%20Games.zip" in response.headers["Content-Disposition"] - # Membership is recomputed from the filter criteria at download time - assert "test_rom.zip" in response.text - assert "test_rom_2.zip" in response.text - - -def test_download_private_smart_collection_of_other_user_forbidden( - client: TestClient, - viewer_token: str, - admin_user: User, - platform: Platform, -): - smart_collection = db_collection_handler.add_smart_collection( - SmartCollection( - name="Admin Only", - description="", - is_public=False, - filter_criteria={"platform_ids": [platform.id]}, - user_id=admin_user.id, - ) - ) - - response = client.get( - "/api/roms/download", - headers={"Authorization": f"Bearer {viewer_token}"}, - params={"smart_collection_id": smart_collection.id}, - ) - assert response.status_code == status.HTTP_403_FORBIDDEN - - -def test_download_virtual_collection( - client: TestClient, - access_token: str, - admin_user: User, - platform: Platform, - rom: Rom, - rom_file: RomFile, - second_rom: Rom, -): - # The virtual_collections DB view derives a "genre" collection from - # each rom's igdb_metadata genres, and only materializes it once more - # than two roms share the value. - third_rom = db_rom_handler.add_rom( - Rom( - platform_id=platform.id, - name="test_rom_3", - slug="test_rom_slug_3", - fs_name="test_rom_3.zip", - fs_name_no_tags="test_rom_3", - fs_name_no_ext="test_rom_3", - fs_extension="zip", - fs_path=f"{platform.slug}/roms", - ) - ) - for rom_id in (rom.id, second_rom.id, third_rom.id): - db_rom_handler.update_rom(rom_id, {"igdb_metadata": {"genres": ["Action"]}}) - - virtual_collections = db_collection_handler.get_virtual_collections("genre") - assert len(virtual_collections) == 1 - - response = client.get( - "/api/roms/download", - headers={"Authorization": f"Bearer {access_token}"}, - params={"virtual_collection_id": virtual_collections[0].id}, - ) - assert response.status_code == status.HTTP_200_OK - assert "Action.zip" in response.headers["Content-Disposition"] - assert "test_rom.zip" in response.text - assert "test_rom_2.zip" in response.text - - -def test_download_virtual_collection_malformed_id( - client: TestClient, access_token: str -): - response = client.get( - "/api/roms/download", - headers={"Authorization": f"Bearer {access_token}"}, - params={"virtual_collection_id": "not-a-valid-id"}, - ) - assert response.status_code == status.HTTP_404_NOT_FOUND - - -def test_download_empty_collection_returns_404( - client: TestClient, access_token: str, admin_user: User -): - empty = db_collection_handler.add_collection( - Collection( - name="Empty", - description="", - is_public=False, - is_favorite=False, - user_id=admin_user.id, - ) - ) - - response = client.get( - "/api/roms/download", - headers={"Authorization": f"Bearer {access_token}"}, - params={"collection_id": empty.id}, - ) - assert response.status_code == status.HTTP_404_NOT_FOUND diff --git a/frontend/src/components/Gallery/FabOverlay.vue b/frontend/src/components/Gallery/FabOverlay.vue index 5e49ffb4b..6bbfb0916 100644 --- a/frontend/src/components/Gallery/FabOverlay.vue +++ b/frontend/src/components/Gallery/FabOverlay.vue @@ -130,7 +130,9 @@ async function removeFromFavorites() { } async function onDownload() { - await romApi.bulkDownloadRoms({ roms: romsStore.selectedRoms }); + await romApi.bulkDownloadRoms({ + romIDs: romsStore.selectedRoms.map((r) => r.id), + }); } diff --git a/frontend/src/services/api/rom.ts b/frontend/src/services/api/rom.ts index e53c994e7..320b6a705 100644 --- a/frontend/src/services/api/rom.ts +++ b/frontend/src/services/api/rom.ts @@ -453,41 +453,16 @@ async function downloadRom({ } async function bulkDownloadRoms({ - roms, + romIDs, filename, }: { - roms: SimpleRom[]; + romIDs: number[]; filename?: string; }) { - if (roms.length === 0) return; - - const romIds = roms.map((rom) => rom.id); + if (romIDs.length === 0) return; const queryParams = new URLSearchParams(); - queryParams.append("rom_ids", romIds.join(",")); - if (filename) queryParams.append("filename", filename); - - return triggerFileDownload(`/api/roms/download?${queryParams.toString()}`); -} - -async function downloadCollectionRoms({ - collectionId, - kind, - filename, -}: { - collectionId: number | string; - kind: "regular" | "virtual" | "smart"; - filename?: string; -}) { - const paramName = - kind === "virtual" - ? "virtual_collection_id" - : kind === "smart" - ? "smart_collection_id" - : "collection_id"; - - const queryParams = new URLSearchParams(); - queryParams.append(paramName, String(collectionId)); + queryParams.append("rom_ids", romIDs.join(",")); if (filename) queryParams.append("filename", filename); return triggerFileDownload(`/api/roms/download?${queryParams.toString()}`); @@ -901,7 +876,6 @@ export default { getRomByMetadataProvider, downloadRom, bulkDownloadRoms, - downloadCollectionRoms, searchRom, updateRom, uploadManuals, diff --git a/frontend/src/v2/components/Gallery/CollectionHead.vue b/frontend/src/v2/components/Gallery/CollectionHead.vue index a8d4bd139..d0cf607c7 100644 --- a/frontend/src/v2/components/Gallery/CollectionHead.vue +++ b/frontend/src/v2/components/Gallery/CollectionHead.vue @@ -45,8 +45,6 @@ defineProps<{ covers: string[]; tab: string; tabs: RTabNavItem[]; - /** Permission flag — already evaluated against `useCan` in the - * parent, mirroring PlatformHead's prop-based gating. */ canDownload: boolean; }>(); @@ -83,9 +81,6 @@ defineEmits<{ - @@ -444,12 +459,14 @@ async function onDelete() { :providers="providerChips" :can-edit="canEditPlatform" :can-scan="canScan" + :can-download="canDownload" :random-loading="randomLoading" :labels="headLabels" @update:tab="onTabChange" @upload="onUploadRoms" @scan="onScan" @random="onRandomGame" + @download="onDownload" />
From f3cc4516159ea6a459e28633e49ea9510094422e Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 4 Jul 2026 14:12:16 -0400 Subject: [PATCH 5/5] add back backend --- backend/endpoints/roms/__init__.py | 63 +++++++++++++++----- backend/handler/database/roms_handler.py | 1 + backend/tests/endpoints/roms/test_rom.py | 62 ++++++++++++++++++- frontend/src/services/api/rom.ts | 30 ++++++++-- frontend/src/v2/views/Gallery/Collection.vue | 11 +++- frontend/src/v2/views/Gallery/Platform.vue | 16 ++--- 6 files changed, 153 insertions(+), 30 deletions(-) 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() {