Merge pull request #3661 from Spinnich/fix/collection-bulk-download

fix(collections): download whole collections as a single zip
This commit is contained in:
Georges-Antoine Assi
2026-07-04 14:18:18 -04:00
committed by GitHub
47 changed files with 284 additions and 68 deletions

View File

@@ -709,8 +709,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,
@@ -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)
]

View File

@@ -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),

View File

@@ -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
):

View File

@@ -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),
});
}
</script>

View File

@@ -6,6 +6,7 @@
"danger-zone": "Опасна зона",
"delete-collection": "Изтрий колекция",
"description": "Описание",
"download-collection": "Изтегли колекция",
"edit-collection": "Редактирай колекция",
"name": "Име",
"owner": "Собственик",

View File

@@ -12,6 +12,7 @@
"danger-zone": "Опасна зона",
"delete-platform": "Изтрий платформата",
"delete-platform-hint": "Премахва платформата и нейните записи в ROM базата данни. Файловете на диска НЕ се изтриват.",
"download-platform": "Изтегли платформа",
"edit-platform": "Редактирай платформата",
"export": "Експортирай",
"family": "Фамилия",

View File

@@ -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",

View File

@@ -12,6 +12,7 @@
"danger-zone": "Nebezpečná zóna",
"delete-platform": "Smazat platformu",
"delete-platform-hint": "Odstraní platformu a její záznamy ROM z databáze. Soubory na disku NEBUDOU smazány.",
"download-platform": "Stáhnout platformu",
"edit-platform": "Upravit platformu",
"export": "Export",
"family": "Rodina",

View File

@@ -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",

View File

@@ -12,6 +12,7 @@
"danger-zone": "Gefahrenzone",
"delete-platform": "Plattform löschen",
"delete-platform-hint": "Entfernt die Plattform und ihre ROM-Datenbankeinträge. Dateien auf dem Datenträger werden NICHT gelöscht.",
"download-platform": "Plattform herunterladen",
"edit-platform": "Plattform bearbeiten",
"export": "Exportieren",
"family": "Familie",

View File

@@ -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",

View File

@@ -12,6 +12,7 @@
"danger-zone": "Danger zone",
"delete-platform": "Delete platform",
"delete-platform-hint": "Removes the platform and its ROM database entries. Files on disk are NOT deleted.",
"download-platform": "Download platform",
"edit-platform": "Edit platform",
"export": "Export",
"family": "Family",

View File

@@ -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",

View File

@@ -12,6 +12,7 @@
"danger-zone": "Danger zone",
"delete-platform": "Delete platform",
"delete-platform-hint": "Removes the platform and its ROM database entries. Files on disk are NOT deleted.",
"download-platform": "Download platform",
"edit-platform": "Edit platform",
"export": "Export",
"family": "Family",

View File

@@ -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",

View File

@@ -12,6 +12,7 @@
"danger-zone": "Zona de peligro",
"delete-platform": "Eliminar platforma",
"delete-platform-hint": "Elimina la plataforma y sus entradas de ROM. Los archivos en disco NO se eliminan.",
"download-platform": "Descargar plataforma",
"edit-platform": "Editar plataforma",
"export": "Exportar",
"family": "Familia",

View File

@@ -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",

View File

@@ -12,6 +12,7 @@
"danger-zone": "Zone de danger",
"delete-platform": "Supprimer la plateforme",
"delete-platform-hint": "Supprime la plateforme et ses entrées de la base de données des ROMs. Les fichiers sur le disque ne sont PAS supprimés.",
"download-platform": "Télécharger la plateforme",
"edit-platform": "Modifier la plateforme",
"export": "Exporter",
"family": "Famille",

View File

@@ -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",

View File

@@ -12,6 +12,7 @@
"danger-zone": "Veszély zóna",
"delete-platform": "Platform törlése",
"delete-platform-hint": "Eltávolítja a platformot és a ROM-adatbázis bejegyzéseit. A lemezen lévő fájlok NEM törlődnek.",
"download-platform": "Platform letöltése",
"edit-platform": "Platform szerkesztése",
"export": "Exportálás",
"family": "Család",

View File

@@ -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",

View File

@@ -12,6 +12,7 @@
"danger-zone": "Zona pericolosa",
"delete-platform": "Elimina piattaforma",
"delete-platform-hint": "Rimuove la piattaforma e le voci di database delle sue ROM. I file su disco NON vengono eliminati.",
"download-platform": "Scarica piattaforma",
"edit-platform": "Modifica piattaforma",
"export": "Esporta",
"family": "Famiglia",

View File

@@ -6,6 +6,7 @@
"danger-zone": "危険",
"delete-collection": "コレクションを削除",
"description": "説明",
"download-collection": "コレクションをダウンロード",
"edit-collection": "コレクションを編集",
"name": "名前",
"owner": "所有者",

View File

@@ -12,6 +12,7 @@
"danger-zone": "危険",
"delete-platform": "プラットフォームの削除",
"delete-platform-hint": "プラットフォームとそのROMデータベースエントリを削除します。ディスク上のファイルは削除されません。",
"download-platform": "プラットフォームをダウンロード",
"edit-platform": "プラットフォームを編集",
"export": "エクスポート",
"family": "ファミリー",

View File

@@ -6,6 +6,7 @@
"danger-zone": "위험 구역",
"delete-collection": "모음집 삭제",
"description": "설명",
"download-collection": "모음집 다운로드",
"edit-collection": "모음집 수정",
"name": "이름",
"owner": "소유자",

View File

@@ -12,6 +12,7 @@
"danger-zone": "위험 구역",
"delete-platform": "플랫폼 지우기",
"delete-platform-hint": "플랫폼과 해당 ROM 데이터베이스 항목을 제거합니다. 디스크의 파일은 삭제되지 않습니다.",
"download-platform": "플랫폼 다운로드",
"edit-platform": "플랫폼 편집",
"export": "내보내기",
"family": "계열",

View File

@@ -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",

View File

@@ -12,6 +12,7 @@
"danger-zone": "Strefa zagrożenia",
"delete-platform": "Usuń platformę",
"delete-platform-hint": "Usuwa platformę i wpisy ROM-ów z bazy danych. Pliki na dysku NIE zostaną usunięte.",
"download-platform": "Pobierz platforme",
"edit-platform": "Edytuj platformę",
"export": "Eksportuj",
"family": "Rodzina",

View File

@@ -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",

View File

@@ -12,6 +12,7 @@
"danger-zone": "Zona de perigo",
"delete-platform": "Excluir plataforma",
"delete-platform-hint": "Remove a plataforma e seus registros de ROM no banco de dados. Os arquivos no disco NÃO são excluídos.",
"download-platform": "Baixar plataforma",
"edit-platform": "Editar plataforma",
"export": "Exportar",
"family": "Família",

View File

@@ -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",

View File

@@ -12,6 +12,7 @@
"danger-zone": "Zonă periculoasă",
"delete-platform": "Șterge platforma",
"delete-platform-hint": "Elimină platforma și intrările ROM din baza de date. Fișierele de pe disc NU sunt șterse.",
"download-platform": "Descarcă platforma",
"edit-platform": "Editează platforma",
"export": "Exportare",
"family": "Familie",

View File

@@ -6,6 +6,7 @@
"danger-zone": "Опасная зона",
"delete-collection": "Удалить коллекцию",
"description": "Описание",
"download-collection": "Скачать коллекцию",
"edit-collection": "Редактировать коллекцию",
"name": "Имя",
"owner": "Владелец",

View File

@@ -12,6 +12,7 @@
"danger-zone": "Опасная зона",
"delete-platform": "Удалить платформу",
"delete-platform-hint": "Удаляет платформу и её записи о ROM из базы. Файлы на диске НЕ удаляются.",
"download-platform": "Скачать платформу",
"edit-platform": "Редактировать платформу",
"export": "Экспорт",
"family": "Семейство",

View File

@@ -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",

View File

@@ -12,6 +12,7 @@
"danger-zone": "Tehlikeli bölge",
"delete-platform": "Platformu sil",
"delete-platform-hint": "Platformu ve ROM veritabanı kayıtlarını kaldırır. Diskteki dosyalar SİLİNMEZ.",
"download-platform": "Platformu indir",
"edit-platform": "Platformu düzenle",
"export": "Dışa aktar",
"family": "Aile",

View File

@@ -6,6 +6,7 @@
"danger-zone": "危险区",
"delete-collection": "删除收藏",
"description": "描述",
"download-collection": "下载收藏",
"edit-collection": "编辑收藏",
"name": "名称",
"owner": "创建者",

View File

@@ -12,6 +12,7 @@
"danger-zone": "危险区域",
"delete-platform": "删除平台",
"delete-platform-hint": "移除该平台及其 ROM 数据库条目。磁盘上的文件不会被删除。",
"download-platform": "下载平台",
"edit-platform": "编辑平台",
"export": "导出",
"family": "家族",

View File

@@ -6,6 +6,7 @@
"danger-zone": "危險操作",
"delete-collection": "刪除收藏庫",
"description": "說明",
"download-collection": "下載收藏庫",
"edit-collection": "編輯收藏庫",
"name": "名稱",
"owner": "建立者",

View File

@@ -12,6 +12,7 @@
"danger-zone": "危險操作",
"delete-platform": "删除平台",
"delete-platform-hint": "移除此平台及其 ROM 資料庫項目。磁碟上的檔案不會被刪除。",
"download-platform": "下載平台",
"edit-platform": "編輯平台",
"export": "導出",
"family": "家族",

View File

@@ -426,16 +426,10 @@ async function searchRom({
});
}
async function downloadRom({
rom,
fileIDs = [],
}: {
rom: SimpleRom;
fileIDs?: number[];
}) {
function triggerFileDownload(href: string) {
return new Promise<void>((resolve) => {
const a = document.createElement("a");
a.href = getDownloadPath({ rom, fileIDs });
a.href = href;
a.style.display = "none";
document.body.appendChild(a);
@@ -448,34 +442,52 @@ async function downloadRom({
});
}
async function downloadRom({
rom,
fileIDs = [],
}: {
rom: SimpleRom;
fileIDs?: number[];
}) {
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({
roms,
romIDs,
platformId,
collectionId,
virtualCollectionId,
smartCollectionId,
filename,
}: {
roms: SimpleRom[];
romIDs?: number[];
platformId?: number;
collectionId?: number;
virtualCollectionId?: string;
smartCollectionId?: number;
filename?: string;
}) {
return new Promise<void>((resolve) => {
if (roms.length === 0) return resolve();
const queryParams = new URLSearchParams();
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);
const romIds = roms.map((rom) => rom.id);
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";
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
resolve();
}, DOWNLOAD_CLEANUP_DELAY);
});
return triggerFileDownload(`/api/roms/download?${queryParams.toString()}`);
}
export type UpdateRom = SimpleRom & {

View File

@@ -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,12 @@ defineProps<{
covers: string[];
tab: string;
tabs: RTabNavItem[];
canDownload: boolean;
}>();
defineEmits<{
(e: "update:tab", v: string): void;
(e: "download"): void;
}>();
</script>
@@ -77,6 +80,19 @@ defineEmits<{
<template #stats>
<Stat :value="collection.rom_count" :label="t('common.games')" />
</template>
<template v-if="canDownload" #actions>
<RBtn
variant="outlined"
surface
icon="mdi-download"
rounded="circle"
:disabled="collection.rom_count === 0"
:aria-label="t('collection.download-collection')"
:tooltip="t('collection.download-collection')"
@click="$emit('download')"
/>
</template>
</InfoPanel>
<RTabNav

View File

@@ -59,13 +59,14 @@ withDefaults(
<style scoped>
.info-panel {
display: flex;
align-items: center;
align-items: flex-start;
gap: 40px;
padding: 28px 0;
}
.info-panel__cover {
flex-shrink: 0;
align-self: stretch;
display: flex;
align-items: center;
justify-content: center;
@@ -153,4 +154,7 @@ html[data-bp~="xs"] .info-panel__providers {
html[data-bp~="xs"] .info-panel__stats {
gap: 16px;
}
html[data-bp~="xs"] .info-panel__cover {
align-self: center;
}
</style>

View File

@@ -50,6 +50,7 @@ defineProps<{
* of the page. */
canEdit: boolean;
canScan: boolean;
canDownload: boolean;
/** Spinner on the random-game button while the parent resolves which
* ROM to open. */
randomLoading?: boolean;
@@ -59,6 +60,7 @@ defineProps<{
upload: string;
scan: string;
random: string;
download: string;
};
}>();
@@ -67,6 +69,7 @@ defineEmits<{
(e: "upload"): void;
(e: "scan"): void;
(e: "random"): void;
(e: "download"): void;
}>();
// A square icon sized per breakpoint (smaller on phones). Driving the size
@@ -157,6 +160,17 @@ const iconSize = computed(() => (xs.value ? 116 : 148));
:tooltip="labels.random"
@click="$emit('random')"
/>
<RBtn
v-if="canDownload"
variant="outlined"
surface
icon="mdi-download"
rounded="circle"
:disabled="platform.rom_count === 0"
:aria-label="labels.download"
:tooltip="labels.download"
@click="$emit('download')"
/>
<RBtn
v-if="canEdit"
variant="outlined"

View File

@@ -18,8 +18,9 @@
// * manage collections — re-uses the existing
// `ManageCollectionsDialog` (already accepts SimpleRom[]) via
// the `showManageCollectionsDialog` emitter event.
// * download — iterates selected ROMs and triggers one anchor
// download per item. Same pattern as `useGameActions.download`.
// * download — a single selected ROM downloads directly (like the
// per-rom `useGameActions.download`); multi-selections go through
// the bulk endpoint so the server bundles them into one zip.
// * refresh metadata — emits `showRefreshMetadataDialog` for each
// ROM in turn. (Phase-2 follow-up: the dialog will accept arrays
// so the user only sees the scan-type picker once for the whole
@@ -49,7 +50,7 @@ import romApi from "@/services/api/rom";
import storeCollections from "@/stores/collections";
import storeRoms from "@/stores/roms";
import type { Events } from "@/types/emitter";
import { getDownloadPath, romStatusMap } from "@/utils";
import { romStatusMap } from "@/utils";
import { useBreakpoint } from "@/v2/composables/useBreakpoint";
import { useCan } from "@/v2/composables/useCan";
import { useSnackbar } from "@/v2/composables/useSnackbar";
@@ -226,18 +227,14 @@ function manageCollections() {
function bulkDownload() {
const roms = selection.roms;
if (roms.length === 0) return;
for (const rom of roms) {
const href = getDownloadPath({ rom });
const a = document.createElement("a");
a.href = href;
a.download = rom.fs_name;
document.body.appendChild(a);
a.click();
a.remove();
}
if (roms.length > 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({ romIDs: roms.map((r) => r.id) });
snackbar.info(t("gallery.selection-download-many", { n: roms.length }));
}
function bulkRefresh() {

View File

@@ -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<CollectionKind>("regular");
const currentCollection = ref<AnyCollection | null>(null);
const shellRef = ref<InstanceType<typeof GalleryShell> | 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,25 @@ 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({
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 }));
}
// ── Delete ──────────────────────────────────────────────────────
// Mirrors the Platform.vue admin flow: confirm dialog with
// `requireTyped` on the collection name, then API call → store remove
@@ -313,7 +335,9 @@ async function onDelete() {
:covers="mosaicCovers"
:tab="tab"
:tabs="tabs"
:can-download="canDownload"
@update:tab="onTabChange"
@download="onDownload"
/>
</template>
</GalleryShell>
@@ -331,7 +355,9 @@ async function onDelete() {
:covers="mosaicCovers"
:tab="tab"
:tabs="tabs"
:can-download="canDownload"
@update:tab="onTabChange"
@download="onDownload"
/>
<RDivider class="r-v2-coll-tabs__divider" />
<div

View File

@@ -55,6 +55,7 @@ const randomLoading = ref(false);
// ribbon buttons hide automatically when the user's role changes.
const canEditPlatform = useCan("platform.edit");
const canScan = useCan("library.scan");
const canDownload = useCan("rom.download");
// ── Tabs ─────────────────────────────────────────────────────────
// URL-persistent via `?tab=` (mirrors the GameDetails pattern). The
@@ -95,6 +96,7 @@ const headLabels = computed(() => ({
upload: t("platform.upload-roms"),
scan: t("platform.scan-platform"),
random: t("platform.random-rom"),
download: t("platform.download-platform"),
}));
function onTabChange(next: string) {
@@ -353,6 +355,17 @@ async function onRandomGame() {
}
}
// Download all
function onDownload() {
const p = currentPlatform.value;
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() {
const p = currentPlatform.value;
if (!p) return;
@@ -418,12 +431,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"
/>
</template>
</GalleryShell>
@@ -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"
/>
<RDivider class="r-v2-plat-tabs__divider" />
<div v-if="currentPlatform" class="r-v2-plat-tabs__panel">