diff --git a/backend/endpoints/heartbeat.py b/backend/endpoints/heartbeat.py index b04deadf4..63e9bb6c2 100644 --- a/backend/endpoints/heartbeat.py +++ b/backend/endpoints/heartbeat.py @@ -72,6 +72,10 @@ from handler.redis_handler import sync_cache from handler.scan.sources import MetadataSource from logger.logger import log from utils import get_git_branch, get_version +from utils.platform_aliases import ( + resolve_builtin_platform_slug, + resolve_platform_slug, +) from utils.platforms import get_supported_platforms from utils.rate_limit import enforce_rate_limit, get_client_ip from utils.router import APIRouter @@ -103,6 +107,7 @@ async def heartbeat() -> HeartbeatResponse: title_id_extraction_enabled = ( SigilService.is_enabled() and not cm.get_config().SKIP_TITLE_ID_EXTRACTION ) + fs_platforms = await fs_platform_handler.get_platforms() igdb_enabled = meta_igdb_handler.is_enabled() flashpoint_enabled = meta_flashpoint_handler.is_enabled() @@ -165,7 +170,12 @@ async def heartbeat() -> HeartbeatResponse: "LIBRETRO_API_ENABLED": libretro_enabled, }, "FILESYSTEM": { - "FS_PLATFORMS": await fs_platform_handler.get_platforms(), + "FS_PLATFORMS": fs_platforms, + "FS_PLATFORM_SLUGS": { + fs_slug: slug + for fs_slug in fs_platforms + if (slug := resolve_builtin_platform_slug(fs_slug)) + }, "TITLE_ID_EXTRACTION_ENABLED": title_id_extraction_enabled, }, "EMULATION": { @@ -307,6 +317,7 @@ async def get_setup_library_info(request: Request) -> SetupLibraryResponse: ) library_ready = fs_platform_handler.library_structure_exists() + config = cm.get_config() # The per-platform rom counts below are a first-run hint, so a fresh # instance can show what RomM already sees on disk. Once the database @@ -315,7 +326,7 @@ async def get_setup_library_info(request: Request) -> SetupLibraryResponse: if db_stats_handler.get_roms_count() > 0: return { "library_ready": library_ready, - "library_structure": cm.get_config().default_structure_pattern, + "library_structure": config.default_structure_pattern, "existing_platforms": [], "supported_platforms": get_supported_platforms( get_rom_visibility_filter(request) @@ -361,6 +372,7 @@ async def get_setup_library_info(request: Request) -> SetupLibraryResponse: existing_platforms.append( { "fs_slug": fs_slug, + "slug": resolve_platform_slug(fs_slug, config), "rom_count": rom_count, } ) @@ -370,7 +382,7 @@ async def get_setup_library_info(request: Request) -> SetupLibraryResponse: return { "library_ready": library_ready, - "library_structure": cm.get_config().default_structure_pattern, + "library_structure": config.default_structure_pattern, "existing_platforms": existing_platforms, "supported_platforms": supported_platforms, } diff --git a/backend/endpoints/responses/heartbeat.py b/backend/endpoints/responses/heartbeat.py index 20b3a5b1b..3edf1d543 100644 --- a/backend/endpoints/responses/heartbeat.py +++ b/backend/endpoints/responses/heartbeat.py @@ -32,6 +32,7 @@ class MetadataSourcesDict(TypedDict): class FilesystemDict(TypedDict): FS_PLATFORMS: list[str] + FS_PLATFORM_SLUGS: dict[str, str] TITLE_ID_EXTRACTION_ENABLED: bool @@ -98,6 +99,7 @@ class HeartbeatResponse(TypedDict): class SetupExistingPlatform(TypedDict): fs_slug: str + slug: str rom_count: int diff --git a/backend/tests/endpoints/test_heartbeat.py b/backend/tests/endpoints/test_heartbeat.py index 6468e0f9e..0d819535b 100644 --- a/backend/tests/endpoints/test_heartbeat.py +++ b/backend/tests/endpoints/test_heartbeat.py @@ -45,6 +45,7 @@ def test_heartbeat(client): assert "FILESYSTEM" in heartbeat filesystem = heartbeat["FILESYSTEM"] assert isinstance(filesystem["FS_PLATFORMS"], list) + assert isinstance(filesystem["FS_PLATFORM_SLUGS"], dict) assert "EMULATION" in heartbeat emulation = heartbeat["EMULATION"] @@ -67,6 +68,19 @@ def test_heartbeat(client): assert isinstance(heartbeat["CONVERTO"]["ENABLED"], bool) +def test_heartbeat_maps_folders_to_builtin_slugs(client): + with patch( + "endpoints.heartbeat.fs_platform_handler.get_platforms", + AsyncMock(return_value=["gamecube", "N64", "mystery"]), + ): + response = client.get("/api/heartbeat") + + assert response.json()["FILESYSTEM"]["FS_PLATFORM_SLUGS"] == { + "gamecube": "ngc", + "N64": "n64", + } + + @pytest.mark.parametrize( "authorization_header", ["Bearer ", "Foo", "a b c", "Bearer bogus", "Basic not_base64"], @@ -218,11 +232,10 @@ def test_get_setup_library_info_reports_a_ready_library(client, access_token): data = response.json() assert data["library_ready"] is True - assert len(data["existing_platforms"]) == 2 - assert data["existing_platforms"][0]["fs_slug"] == "n64" - assert data["existing_platforms"][0]["rom_count"] == 2 - assert data["existing_platforms"][1]["fs_slug"] == "psx" - assert data["existing_platforms"][1]["rom_count"] == 1 + assert data["existing_platforms"] == [ + {"fs_slug": "n64", "slug": "n64", "rom_count": 2}, + {"fs_slug": "psx", "slug": "psx", "rom_count": 1}, + ] assert "supported_platforms" in data @@ -266,9 +279,9 @@ def test_get_setup_library_info_counts_one_platform(client, admin_user, access_t data = response.json() assert data["library_ready"] is True - assert len(data["existing_platforms"]) == 1 - assert data["existing_platforms"][0]["fs_slug"] == "gba" - assert data["existing_platforms"][0]["rom_count"] == 3 + assert data["existing_platforms"] == [ + {"fs_slug": "gba", "slug": "gba", "rom_count": 3} + ] def test_get_setup_library_info_no_library_yet(client, admin_user, access_token): @@ -384,7 +397,44 @@ def test_get_setup_library_info_walks_when_platforms_have_no_roms( assert response.status_code == status.HTTP_200_OK data = response.json() - assert data["existing_platforms"] == [{"fs_slug": "n64", "rom_count": 1}] + assert data["existing_platforms"] == [ + {"fs_slug": "n64", "slug": "n64", "rom_count": 1} + ] + + +def test_get_setup_library_info_resolves_folder_aliases( + client, admin_user, access_token +): + """A folder alias reports the platform slug it resolves to, next to its folder name.""" + with ( + patch( + "endpoints.heartbeat.fs_platform_handler.library_structure_exists" + ) as mock_detect, + patch( + "endpoints.heartbeat.fs_platform_handler.get_platforms" + ) as mock_get_platforms, + patch("endpoints.heartbeat.AnyioPath") as mock_anyio_path, + ): + mock_detect.return_value = True + mock_get_platforms.return_value = ["gamecube", "megadrive", "gba"] + + async def mock_iterdir(): + return + yield + + mock_path = AsyncMock() + mock_path.exists = AsyncMock(return_value=True) + mock_path.iterdir = mock_iterdir + mock_anyio_path.return_value = mock_path + + response = client.get( + "/api/setup/library", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + folders = {p["fs_slug"]: p["slug"] for p in response.json()["existing_platforms"]} + assert folders == {"gamecube": "ngc", "megadrive": "genesis", "gba": "gba"} def test_create_setup_platforms_success(client, admin_user, access_token): diff --git a/backend/tests/utils/test_platform_aliases.py b/backend/tests/utils/test_platform_aliases.py index 8a5cc141a..ae8ee2207 100644 --- a/backend/tests/utils/test_platform_aliases.py +++ b/backend/tests/utils/test_platform_aliases.py @@ -7,6 +7,7 @@ from config.config_manager import Config from utils.platform_aliases import ( PLATFORM_FS_ALIASES, PLATFORM_SLUG_FOLDERS, + resolve_builtin_platform_slug, resolve_fs_folder, resolve_fs_slug, resolve_platform_slug, @@ -159,3 +160,11 @@ def test_example_configs_list_only_needed_overrides(config_file: Path): if resolve_platform_slug(fs_slug, empty) == slug } assert not redundant + + +@pytest.mark.parametrize( + ("folder", "slug"), + [("gamecube", "ngc"), ("MegaDrive", "genesis"), ("N64", "n64"), ("mystery", None)], +) +def test_resolves_builtin_slug_without_config(folder: str, slug: str | None): + assert resolve_builtin_platform_slug(folder) == slug diff --git a/backend/utils/platform_aliases.py b/backend/utils/platform_aliases.py index 12c52e661..8a4edede5 100644 --- a/backend/utils/platform_aliases.py +++ b/backend/utils/platform_aliases.py @@ -175,6 +175,16 @@ def _to_slug(name: str) -> str: return alias.value if alias else name +def resolve_builtin_platform_slug(fs_slug: str) -> str | None: + """Resolve a folder name to a platform slug by its name or built-in alias. + + Returns: + The platform slug, or None when the folder needs a config mapping. + """ + slug = _to_slug(fs_slug) + return slug if slug in UPS else None + + def resolve_platform_slug(fs_slug: str, config: Config) -> str: """Resolve a platform folder name to a RomM platform slug.""" key = fs_slug.lower() diff --git a/frontend/src/__generated__/models/FilesystemDict.ts b/frontend/src/__generated__/models/FilesystemDict.ts index 133a6fb2e..bd27aaf83 100644 --- a/frontend/src/__generated__/models/FilesystemDict.ts +++ b/frontend/src/__generated__/models/FilesystemDict.ts @@ -4,6 +4,7 @@ /* eslint-disable */ export type FilesystemDict = { FS_PLATFORMS: Array; + FS_PLATFORM_SLUGS: Record; TITLE_ID_EXTRACTION_ENABLED: boolean; }; diff --git a/frontend/src/__generated__/models/SetupExistingPlatform.ts b/frontend/src/__generated__/models/SetupExistingPlatform.ts index 20cdc3cc5..9e4eb0926 100644 --- a/frontend/src/__generated__/models/SetupExistingPlatform.ts +++ b/frontend/src/__generated__/models/SetupExistingPlatform.ts @@ -4,6 +4,7 @@ /* eslint-disable */ export type SetupExistingPlatform = { fs_slug: string; + slug: string; rom_count: number; }; diff --git a/frontend/src/components/Auth/SetupStepPlatforms.test.ts b/frontend/src/components/Auth/SetupStepPlatforms.test.ts new file mode 100644 index 000000000..6ccce75d7 --- /dev/null +++ b/frontend/src/components/Auth/SetupStepPlatforms.test.ts @@ -0,0 +1,101 @@ +import { mount } from "@vue/test-utils"; +import { describe, expect, it, vi } from "vitest"; +import type { SetupExistingPlatform } from "@/__generated__"; +import { RCheckbox } from "@/lib"; +import { platformFixture } from "@/utils/platform.fixtures"; +import SetupStepPlatforms from "./SetupStepPlatforms.vue"; + +vi.mock("vue-i18n"); + +const supported = [ + platformFixture({ slug: "ngc", name: "Nintendo GameCube" }), + platformFixture({ slug: "genesis", name: "Sega Genesis" }), + platformFixture({ slug: "n64", name: "Nintendo 64" }), +]; + +function mountStep( + existing: SetupExistingPlatform[], + supportedPlatforms = supported, +) { + return mount(SetupStepPlatforms, { + props: { + libraryInfo: { + library_ready: true, + library_structure: "{platform}/roms", + existing_platforms: existing, + supported_platforms: supportedPlatforms, + }, + selectedNewPlatforms: [], + }, + global: { + stubs: { + PlatformIcon: true, + RChip: { template: "" }, + RCollapsible: true, + REmptyState: true, + RIcon: true, + RSegmentedControl: true, + RTag: true, + RTextField: true, + }, + }, + }); +} + +function detectedRows(wrapper: ReturnType) { + return wrapper.findAll("[data-state='detected']").map((row) => ({ + name: row.get(".r-setup-platforms__item-name").text(), + folder: row.get(".r-setup-platforms__item-slug").text(), + roms: row.get(".r-setup-platforms__item-state .chip").text(), + })); +} + +async function selectAll(wrapper: ReturnType) { + await wrapper.getComponent(RCheckbox).vm.$emit("update:modelValue", true); + return wrapper.emitted("update:selectedNewPlatforms")?.[0]?.[0]; +} + +describe("SetupStepPlatforms detected folders", () => { + it("identifies alias folders by their resolved slug, one row per folder", () => { + const wrapper = mountStep([ + { fs_slug: "gamecube", slug: "ngc", rom_count: 2 }, + { fs_slug: "megadrive", slug: "genesis", rom_count: 3 }, + { fs_slug: "genesis", slug: "genesis", rom_count: 1 }, + { fs_slug: "mystery", slug: "mystery", rom_count: 4 }, + ]); + + expect(detectedRows(wrapper)).toEqual([ + { name: "mystery", folder: "mystery", roms: "4" }, + { name: "Nintendo GameCube", folder: "gamecube", roms: "2" }, + { name: "Sega Genesis", folder: "megadrive", roms: "3" }, + { name: "Sega Genesis", folder: "genesis", roms: "1" }, + ]); + }); + + it("only offers platforms that no folder resolves to", async () => { + const wrapper = mountStep([ + { fs_slug: "gamecube", slug: "ngc", rom_count: 2 }, + ]); + + expect(await selectAll(wrapper)).toEqual(["genesis", "n64"]); + }); + + it("matches a platform row whose fs_slug is the alias folder", async () => { + const wrapper = mountStep( + [{ fs_slug: "gamecube", slug: "ngc", rom_count: 0 }], + [ + platformFixture({ + slug: "ngc", + fs_slug: "gamecube", + name: "Nintendo GameCube", + }), + platformFixture({ slug: "n64", name: "Nintendo 64" }), + ], + ); + + expect(detectedRows(wrapper)).toEqual([ + { name: "Nintendo GameCube", folder: "gamecube", roms: "0" }, + ]); + expect(await selectAll(wrapper)).toEqual(["n64"]); + }); +}); diff --git a/frontend/src/components/Auth/SetupStepPlatforms.vue b/frontend/src/components/Auth/SetupStepPlatforms.vue index a8d9c0c17..19e5c1a63 100644 --- a/frontend/src/components/Auth/SetupStepPlatforms.vue +++ b/frontend/src/components/Auth/SetupStepPlatforms.vue @@ -65,42 +65,33 @@ const SEARCH_LIMIT = 80; // through the cracks. const detectedSlugSet = computed( - () => new Set(props.libraryInfo.existing_platforms.map((p) => p.fs_slug)), + () => new Set(props.libraryInfo.existing_platforms.map((p) => p.slug)), ); -const romCountBySlug = computed(() => { - const map = new Map(); - for (const p of props.libraryInfo.existing_platforms) - map.set(p.fs_slug, p.rom_count); - return map; -}); - -const supportedSlugSet = computed( - () => new Set(props.libraryInfo.supported_platforms.map((p) => p.fs_slug)), +const supportedBySlug = computed( + () => new Map(props.libraryInfo.supported_platforms.map((p) => [p.slug, p])), ); +// One row per folder, so an alias folder shows its own name and rom count. const detectedPlatforms = computed>( () => { if (!props.libraryInfo.library_ready) return []; - const identified = props.libraryInfo.supported_platforms - .filter((p) => detectedSlugSet.value.has(p.fs_slug)) - .map((p) => ({ ...p, unidentified: false })); - const unidentified = props.libraryInfo.existing_platforms - .filter((p) => !supportedSlugSet.value.has(p.fs_slug)) - .map( - (p) => - ({ - fs_slug: p.fs_slug, - slug: p.fs_slug, + return props.libraryInfo.existing_platforms + .map((p) => { + const supported = supportedBySlug.value.get(p.slug); + return { + ...(supported ?? { + slug: p.slug, name: p.fs_slug, family_name: UNIDENTIFIED, generation: 999, - unidentified: true, - }) as Platform & { unidentified: boolean }, - ); - return [...identified, ...unidentified].sort((a, b) => - (a.name ?? a.fs_slug).localeCompare(b.name ?? b.fs_slug), - ); + }), + fs_slug: p.fs_slug, + rom_count: p.rom_count, + unidentified: !supported, + } as Platform & { unidentified: boolean }; + }) + .sort((a, b) => (a.name ?? a.fs_slug).localeCompare(b.name ?? b.fs_slug)); }, ); @@ -163,11 +154,11 @@ const filteredDetectedPlatforms = computed(() => { // ── Supported (selectable) platforms ─────────────────────────────── // // Filter out anything already on disk, since those are shown in the detected -// section. We never present the same fs_slug twice. +// section. We never present the same platform twice. const supportedAvailable = computed(() => props.libraryInfo.supported_platforms.filter( - (p) => !detectedSlugSet.value.has(p.fs_slug), + (p) => !detectedSlugSet.value.has(p.slug), ), ); @@ -230,7 +221,6 @@ function isSelected(slug: string): boolean { } function togglePlatform(slug: string, next: boolean) { - if (detectedSlugSet.value.has(slug)) return; const set = new Set(props.selectedNewPlatforms); if (next) set.add(slug); else set.delete(slug); @@ -238,9 +228,7 @@ function togglePlatform(slug: string, next: boolean) { } function newSlugsInGroup(items: Platform[]): string[] { - return items - .filter((p) => !detectedSlugSet.value.has(p.fs_slug)) - .map((p) => p.fs_slug); + return items.map((p) => p.fs_slug); } function groupSelectedState(items: Platform[]): boolean | null { @@ -404,29 +392,21 @@ const detectedPlatformCount = computed(
- + + {{ t("setup.unidentified") }} + - {{ romCountBySlug.get(platform.fs_slug) ?? 0 }} + {{ platform.rom_count }}
diff --git a/frontend/src/components/Settings/FolderMappingsSection.test.ts b/frontend/src/components/Settings/FolderMappingsSection.test.ts index 95bf91a54..c8f2df7df 100644 --- a/frontend/src/components/Settings/FolderMappingsSection.test.ts +++ b/frontend/src/components/Settings/FolderMappingsSection.test.ts @@ -46,6 +46,12 @@ vi.mock("@/composables/usePlatformIconCache", () => ({ const N64 = { id: 1, slug: "n64", name: "Nintendo 64", display_name: "N64" }; const PS2 = { id: 2, slug: "ps2", name: "PlayStation 2", display_name: "PS2" }; +const NGC = { + id: 3, + slug: "ngc", + name: "Nintendo GameCube", + display_name: "GameCube", +}; // Exposes the built rows and renders the Platform cell the edit actions hang off. const RTableStub = { @@ -55,9 +61,13 @@ const RTableStub = { '
', }; -async function mountWith(folders: string[]) { +async function mountWith( + folders: string[], + folderSlugs: Record = {}, +) { const heartbeat = storeHeartbeat(); heartbeat.value.FILESYSTEM.FS_PLATFORMS = folders; + heartbeat.value.FILESYSTEM.FS_PLATFORM_SLUGS = folderSlugs; vi.spyOn(heartbeat, "fetchHeartbeat").mockResolvedValue(heartbeat.value); const wrapper = mount(FolderMappingsSection, { @@ -123,12 +133,35 @@ describe("FolderMappingsSection", () => { expect(rows[0]).toMatchObject({ slug: "ps2", type: "variant" }); }); - it("marks a folder matching a platform slug as auto-detected whatever its case", async () => { - const { rows } = await mountWith(["PS2"]); + it("marks a folder the backend resolves to a platform as auto-detected", async () => { + const { rows } = await mountWith(["PS2"], { PS2: "ps2" }); expect(rows[0]).toMatchObject({ slug: "ps2", type: "auto" }); }); + it("marks a built-in alias folder as auto-detected", async () => { + getSupportedPlatforms.mockResolvedValue({ data: [N64, PS2, NGC] }); + + const { rows } = await mountWith(["gamecube", "unknown"], { + gamecube: "ngc", + }); + + expect(rows).toEqual([ + { + fsSlug: "gamecube", + slug: "ngc", + displayName: "GameCube", + type: "auto", + }, + { + fsSlug: "unknown", + slug: undefined, + displayName: undefined, + type: null, + }, + ]); + }); + // A bare add on a folder that already has a binding is a no-op server-side. it("replaces the binding when a mapped folder is pointed at another platform", async () => { storeConfig().config.PLATFORMS_BINDING = { "nintendo 64": "n64" }; diff --git a/frontend/src/components/Settings/FolderMappingsSection.vue b/frontend/src/components/Settings/FolderMappingsSection.vue index 5d7503e2f..f7b3d3ddf 100644 --- a/frontend/src/components/Settings/FolderMappingsSection.vue +++ b/frontend/src/components/Settings/FolderMappingsSection.vue @@ -63,9 +63,7 @@ const TYPE_ORDER: Record | "none", number> = { const mappings = computed(() => { const rows: Row[] = []; const folders = heartbeat.value?.FILESYSTEM?.FS_PLATFORMS || []; - const autoSlug: Record = {}; - - for (const p of supportedPlatforms.value) autoSlug[p.slug] = p.slug; + const autoSlug = heartbeat.value?.FILESYSTEM?.FS_PLATFORM_SLUGS || {}; for (const folder of folders) { const binding = configStore.getPlatformBinding(folder); @@ -90,8 +88,7 @@ const mappings = computed(() => { }); continue; } - // Platform slugs are lowercase; the folder on disk may not be. - const auto = autoSlug[folder.toLowerCase()]; + const auto = autoSlug[folder]; if (auto) { const platform = supportedPlatforms.value.find((p) => p.slug === auto); rows.push({ diff --git a/frontend/src/stores/heartbeat.ts b/frontend/src/stores/heartbeat.ts index d545dab0a..7b9a04d86 100644 --- a/frontend/src/stores/heartbeat.ts +++ b/frontend/src/stores/heartbeat.ts @@ -40,6 +40,7 @@ const defaultHeartbeat: Heartbeat = { }, FILESYSTEM: { FS_PLATFORMS: [], + FS_PLATFORM_SLUGS: {}, TITLE_ID_EXTRACTION_ENABLED: false, }, EMULATION: {