diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 6f7906876..1bfc3656c 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -10,7 +10,6 @@ from typing import Annotated, Any, Final, Literal, Sequence, cast from urllib.parse import quote from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile, ZipInfo -import pydash from anyio import Path, open_file from fastapi import ( Body, @@ -2175,12 +2174,13 @@ async def update_rom( cleaned_data.update({"hltb_id": None, "hltb_metadata": {}}) url_screenshots = cleaned_data.get("url_screenshots", []) - screenshots_changed = pydash.xor(url_screenshots, rom.url_screenshots or []) + # Files are named by position, so a reorder is a change too. + screenshots_changed = url_screenshots != (rom.url_screenshots or []) if url_screenshots: try: path_screenshots = await fs_resource_handler.get_rom_screenshots( rom=rom, - overwrite=bool(screenshots_changed), + overwrite=screenshots_changed, url_screenshots=[add_ss_auth_to_url(u) for u in url_screenshots], ) cleaned_data.update( diff --git a/backend/handler/filesystem/resources_handler.py b/backend/handler/filesystem/resources_handler.py index e40413ac4..f2125f258 100644 --- a/backend/handler/filesystem/resources_handler.py +++ b/backend/handler/filesystem/resources_handler.py @@ -613,11 +613,16 @@ class FSResourcesHandler(FSHandler): stored = set() if overwrite else self._stored_screenshot_indexes(rom) async def screenshot_path(idx: int, url_screenshot: str) -> str | None: + path = self._get_screenshot_path(rom, str(idx)) if str(idx) not in stored and not await self._store_screenshot( rom, url_screenshot, idx ): + # Otherwise the old image at this index passes for the new one + # on the next scan, and is never fetched again. + if overwrite: + await self._discard_partial_file(path) return None - return self._get_screenshot_path(rom, str(idx)) + return path paths = await gather_all( *(screenshot_path(idx, url) for idx, url in enumerate(url_screenshots)) diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 0d9cc5a5b..e9e73d1e9 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -4,7 +4,6 @@ import functools from collections.abc import Callable, Mapping from typing import Any, Final, NotRequired, TypedDict -import pydash import socketio from adapters.services.igdb import IGDB_PLATFORM_LIST @@ -1750,10 +1749,9 @@ async def download_rom_resources( previous_media: Each provider column's metadata before this scan, keyed like ``ss_metadata``, so media whose source changed is fetched again. """ - screenshots_changed = pydash.xor( - added_rom.url_screenshots or [], previous_url_screenshots or [] - ) url_screenshots = added_rom.url_screenshots or [] + # Files are named by position, so a reorder is a change too. + screenshots_changed = url_screenshots != (previous_url_screenshots or []) preferred_media_types = get_preferred_media_types() # Highest priority first, the order their files land in shared paths. @@ -1811,7 +1809,7 @@ async def download_rom_resources( ), fs_resource_handler.get_rom_screenshots( rom=added_rom, - overwrite=bool(screenshots_changed), + overwrite=screenshots_changed, url_screenshots=[add_ss_auth_to_url(u) for u in url_screenshots], ), ), diff --git a/backend/tests/endpoints/roms/test_rom.py b/backend/tests/endpoints/roms/test_rom.py index 186fd403c..9ba9fe255 100644 --- a/backend/tests/endpoints/roms/test_rom.py +++ b/backend/tests/endpoints/roms/test_rom.py @@ -1084,6 +1084,48 @@ def test_update_rom_refreshes_smart_collection_membership( assert refreshed.rom_ids == [rom.id] +@pytest.mark.parametrize( + "previous, expected", + [ + (["http://x/a.jpg", "http://x/b.jpg"], False), + (["http://x/b.jpg", "http://x/a.jpg"], True), + (["http://x/a.jpg"], True), + ], + ids=["unchanged", "reordered", "added"], +) +@patch.object( + FSResourcesHandler, "get_rom_screenshots", new_callable=AsyncMock, return_value=[] +) +@patch.object( + IGDBHandler, + "get_rom_by_id", + return_value=IGDBRom( + igdb_id=MOCK_IGDB_ID, url_screenshots=["http://x/a.jpg", "http://x/b.jpg"] + ), +) +def test_update_rom_redownloads_screenshots_when_their_order_changes( + _get_rom_by_id_mock: AsyncMock, + get_rom_screenshots_mock: AsyncMock, + client: TestClient, + access_token: str, + rom: Rom, + previous: list[str], + expected: bool, +): + db_rom_handler.update_rom(rom.id, {"url_screenshots": previous}) + + response = client.put( + f"/api/roms/{rom.id}", + headers={"Authorization": f"Bearer {access_token}"}, + data={"igdb_id": str(MOCK_IGDB_ID)}, + ) + assert response.status_code == status.HTTP_200_OK + + screenshot_call = get_rom_screenshots_mock.await_args + assert screenshot_call is not None + assert screenshot_call.kwargs["overwrite"] is expected + + # Minimal valid PNG (1x1 transparent pixel) _PNG_BYTES = ( b"\x89PNG\r\n\x1a\n" diff --git a/backend/tests/handler/filesystem/test_resources_handler.py b/backend/tests/handler/filesystem/test_resources_handler.py index 8b7c69284..14265052a 100644 --- a/backend/tests/handler/filesystem/test_resources_handler.py +++ b/backend/tests/handler/filesystem/test_resources_handler.py @@ -781,6 +781,33 @@ class TestFSResourcesHandler: assert paths == ["roms/1/1/screenshots/0.jpg"] + @pytest.mark.asyncio + async def test_failed_overwrite_removes_the_old_screenshot( + self, handler: FSResourcesHandler, rom: Rom, tmp_path + ): + handler.base_path = tmp_path + screenshots = tmp_path / "roms/1/1/screenshots" + screenshots.mkdir(parents=True) + (screenshots / "0.jpg").write_bytes(b"old") + (screenshots / "1.jpg").write_bytes(b"old") + + async def fail_the_second(_rom, _url, idx): + if idx == 1: + return False + (screenshots / "0.jpg").write_bytes(b"new") + return True + + with patch.object(handler, "_store_screenshot", side_effect=fail_the_second): + paths = await handler.get_rom_screenshots( + rom=rom, + overwrite=True, + url_screenshots=["http://x/b.jpg", "http://x/a.jpg"], + ) + + assert paths == ["roms/1/1/screenshots/0.jpg"] + assert (screenshots / "0.jpg").read_bytes() == b"new" + assert not (screenshots / "1.jpg").exists() + @pytest.mark.asyncio async def test_only_the_missing_screenshot_is_fetched( self, handler: FSResourcesHandler, rom: Rom, tmp_path diff --git a/backend/tests/handler/test_download_rom_resources.py b/backend/tests/handler/test_download_rom_resources.py index 28f05ee6c..3c46d9056 100644 --- a/backend/tests/handler/test_download_rom_resources.py +++ b/backend/tests/handler/test_download_rom_resources.py @@ -179,6 +179,35 @@ async def test_a_new_rom_has_no_stale_media(resources: SimpleNamespace): resources.remove_stale_media.assert_not_awaited() +@pytest.mark.parametrize( + "previous, expected", + [ + (["http://x/a.jpg", "http://x/b.jpg"], False), + (["http://x/b.jpg", "http://x/a.jpg"], True), + (["http://x/a.jpg"], True), + ], + ids=["unchanged", "reordered", "added"], +) +@pytest.mark.asyncio +async def test_screenshots_are_redownloaded_when_their_order_changes( + resources: SimpleNamespace, previous: list[str], expected: bool +): + rom = _rom() + rom.url_screenshots = ["http://x/a.jpg", "http://x/b.jpg"] + + await download_rom_resources( + added_rom=rom, + previous_url_cover=rom.url_cover, + previous_url_manual=rom.url_manual, + previous_url_screenshots=previous, + metadata_sources=[], + ) + + screenshot_call = resources.get_rom_screenshots.await_args + assert screenshot_call is not None + assert screenshot_call.kwargs["overwrite"] is expected + + @pytest.mark.asyncio async def test_writes_back_only_the_provider_media_that_changed( resources: SimpleNamespace,