fix(scan): refresh screenshots when only their order changes (#5029)

* fix(scan): refresh screenshots when only their order changes

Stored screenshots are named by position (0.jpg, 1.jpg, ...), but the
re-download check compared the provider's urls as an unordered set, so a
reorder was never picked up. Compare the lists directly, in both the scan
download step and update_rom.

Fixes #4103

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(scan): cover the screenshot reorder in update_rom

Address Greptile review on #5029: add an endpoint test for update_rom's
own reorder check, and narrow await_args before reading its kwargs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(scan): drop the old screenshot when its replacement fails

With overwrite on, a failed download left the previous image at that
index. The next scan saw matching urls and a file on disk, so it kept
the stale image for good. Remove it instead, so the next scan refetches.

Addresses Greptile review on #5029.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-10-02 18:58:37 -04:00
committed by GitHub
parent 27ddb88967
commit 746df798c0
6 changed files with 110 additions and 9 deletions

View File

@@ -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(

View File

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

View File

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

View File

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

View File

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

View File

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