diff --git a/backend/adapters/services/rahasher.py b/backend/adapters/services/rahasher.py index c3dbca028..afd25b58b 100644 --- a/backend/adapters/services/rahasher.py +++ b/backend/adapters/services/rahasher.py @@ -1,5 +1,6 @@ import asyncio import re +from pathlib import Path from handler.metadata.base_handler import UniversalPlatformSlug as UPS from handler.metadata.ra_handler import RAGamesPlatform @@ -119,6 +120,38 @@ class RAHasherService: ) return "" + # For folder-based multi-file ROMs the path ends with /*. RAHasher + # cannot process compressed files via a glob — it fails with "Could not + # open file". When the folder contains archives, switch to hashing the + # largest archive directly (cartridge platforms support buffer hashing), + # or skip entirely for disc platforms that don't. + if file_path.endswith("/*"): + folder = Path(file_path[:-2]) + + def _find_archives() -> list[Path]: + if not folder.is_dir(): + return [] + return [ + f + for f in folder.iterdir() + if f.is_file() + and f.name.lower().endswith(tuple(COMPRESSED_FILE_EXTENSIONS)) + ] + + archive_files = await asyncio.to_thread(_find_archives) + if archive_files: + if platform["ra_id"] in RA_BUFFER_HASH_UNSUPPORTED_IDS: + log.debug( + f"Skipping {hl('RAHasher', color=LIGHTMAGENTA)} for folder " + f"{hl(file_path)}: contains compressed files on disc-based platform" + ) + return "" + # Cartridge platform: buffer-hash the largest archive directly + largest = await asyncio.to_thread( + max, archive_files, key=lambda f: f.stat().st_size + ) + file_path = str(largest) + log.debug( f"Executing {hl('RAHasher', color=LIGHTMAGENTA)} for platform: {hl(platform['slug'], color=LIGHTMAGENTA)} - file: {hl(file_path)}" ) diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index f724675df..10ba0bd27 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -478,6 +478,14 @@ class FSRomsHandler(FSHandler): ) if members: + if calculate_hashes: + ra_platform = meta_ra_handler.get_platform(rom.platform_slug) + if ra_platform and ra_platform["ra_id"]: + rom_ra_h = await RAHasherService().calculate_hash( + ra_platform, + f"{abs_fs_path}/{rom.fs_name}", + ) + rom_files.append( self._build_rom_file( rom=rom, diff --git a/backend/tests/adapters/services/test_rahasher.py b/backend/tests/adapters/services/test_rahasher.py index 716e4a18a..eb358802e 100644 --- a/backend/tests/adapters/services/test_rahasher.py +++ b/backend/tests/adapters/services/test_rahasher.py @@ -301,6 +301,81 @@ class TestRAHasherArchiveSkip: assert result == "a1b2c3d4e5f6789012345678901234ab" mock_subprocess.assert_called_once() + @pytest.mark.asyncio + async def test_skips_wildcard_folder_with_archives_on_disc_platform( + self, service: RAHasherService, tmp_path + ): + """Folder-based ROM whose directory contains compressed files must be + skipped for disc-based platforms — same as a single archive file.""" + platform_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.PSX] + (tmp_path / "disc1.zip").write_bytes(b"fake") + (tmp_path / "disc2.zip").write_bytes(b"fake") + + with patch("asyncio.create_subprocess_exec") as mock_subprocess: + result = await service.calculate_hash( + {"ra_id": platform_id, "slug": "psx"}, + f"{tmp_path}/*", + ) + + assert result == "" + mock_subprocess.assert_not_called() + + @pytest.mark.asyncio + async def test_does_not_skip_wildcard_folder_without_archives_on_disc_platform( + self, service: RAHasherService, tmp_path + ): + """Folder-based ROM with only raw disc images must still go through RAHasher.""" + platform_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.PSX] + (tmp_path / "disc1.bin").write_bytes(b"fake") + (tmp_path / "disc1.cue").write_bytes(b"fake") + + mock_proc = AsyncMock() + mock_proc.wait.return_value = 0 + mock_proc.stdout.read.return_value = b"a1b2c3d4e5f6789012345678901234ab\n" + mock_proc.stderr = None + + with patch( + "asyncio.create_subprocess_exec", return_value=mock_proc + ) as mock_subprocess: + result = await service.calculate_hash( + {"ra_id": platform_id, "slug": "psx"}, + f"{tmp_path}/*", + ) + + assert result == "a1b2c3d4e5f6789012345678901234ab" + mock_subprocess.assert_called_once() + + @pytest.mark.asyncio + async def test_cartridge_platform_folder_with_archives_hashes_largest( + self, service: RAHasherService, tmp_path + ): + """Cartridge platforms: folder with archives should hash the largest archive directly.""" + assert UPS.GBA not in RA_BUFFER_HASH_UNSUPPORTED + platform_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.GBA] + small = tmp_path / "small.zip" + large = tmp_path / "large.zip" + small.write_bytes(b"s" * 100) + large.write_bytes(b"l" * 500) + + mock_proc = AsyncMock() + mock_proc.wait.return_value = 0 + mock_proc.stdout.read.return_value = b"a1b2c3d4e5f6789012345678901234ab\n" + mock_proc.stderr = None + + with patch( + "asyncio.create_subprocess_exec", return_value=mock_proc + ) as mock_subprocess: + result = await service.calculate_hash( + {"ra_id": platform_id, "slug": "gba"}, + f"{tmp_path}/*", + ) + + assert result == "a1b2c3d4e5f6789012345678901234ab" + mock_subprocess.assert_called_once() + # RAHasher must be called with the largest archive path, not the glob + call_args = mock_subprocess.call_args[0] + assert str(large) in call_args + @pytest.mark.asyncio async def test_does_not_skip_raw_iso_for_disc_platform( self, service: RAHasherService diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index 263b65885..508b22f47 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -1,7 +1,7 @@ import os import shutil from pathlib import Path -from unittest.mock import Mock +from unittest.mock import Mock, patch import pytest from tests._zipfile_shim import reload_zipfile @@ -1085,6 +1085,67 @@ class TestFSRomsHandler: assert parsed_rom_files.rom_files[0].md5_hash == parsed_rom_files.md5_hash assert parsed_rom_files.rom_files[0].sha1_hash == parsed_rom_files.sha1_hash + @pytest.mark.asyncio + async def test_get_rom_files_archive_computes_ra_hash_for_cartridge_platform( + self, tmp_path: Path + ): + """RA hash is computed for cartridge-platform archives (buffer hashing supported).""" + import io + import zipfile + + from tests._zipfile_shim import reload_zipfile + + cartridge_platform = Platform( + name="Game Boy Advance", slug="gba", fs_slug="gba" + ) + + reload_zipfile() + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as zf: + zf.writestr("game.gba", b"fake GBA ROM content") + + test_handler, rom = self._setup_archive_rom( + tmp_path, cartridge_platform, "game.zip", "zip", buf.getvalue() + ) + + with patch( + "adapters.services.rahasher.RAHasherService.calculate_hash", + return_value="abcdef1234567890abcdef1234567890", + ): + parsed = await test_handler.get_rom_files(rom) + + assert parsed.ra_hash == "abcdef1234567890abcdef1234567890" + + @pytest.mark.asyncio + async def test_get_rom_files_archive_skips_ra_hash_for_disc_platform( + self, tmp_path: Path + ): + """RA hash is not computed for disc-platform archives (buffer hashing unsupported).""" + import io + import zipfile + + from tests._zipfile_shim import reload_zipfile + + disc_platform = Platform(name="PlayStation", slug="psx", fs_slug="psx") + + reload_zipfile() + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as zf: + zf.writestr("game.bin", b"fake PSX disc content") + + test_handler, rom = self._setup_archive_rom( + tmp_path, disc_platform, "game.zip", "zip", buf.getvalue() + ) + + with patch( + "adapters.services.rahasher.RAHasherService.calculate_hash", + return_value="", + ) as mock_calculate: + parsed = await test_handler.get_rom_files(rom) + + mock_calculate.assert_called_once() + assert parsed.ra_hash == "" + class TestExtractCHDHash: """Test suite for extract_chd_hash function""" diff --git a/backend/utils/filesystem.py b/backend/utils/filesystem.py index be87aead5..0bbfa85f0 100644 --- a/backend/utils/filesystem.py +++ b/backend/utils/filesystem.py @@ -9,7 +9,7 @@ from pathlib import Path # (roms_handler for hashing decisions, rahasher for skipping disc-platform # buffer-hash attempts, feeds for PKGi passthrough). COMPRESSED_FILE_EXTENSIONS: frozenset[str] = frozenset( - (".7z", ".bz2", ".gz", ".rar", ".tar", ".zip") + (".7z", ".bz2", ".gz", ".rar", ".tar", ".zip", ".xz", ".tgz", ".tbz2", ".txz") )