diff --git a/backend/alembic/versions/0113_roms_locked_fields.py b/backend/alembic/versions/0113_roms_locked_fields.py index c595dac53..3eb2b65d2 100644 --- a/backend/alembic/versions/0113_roms_locked_fields.py +++ b/backend/alembic/versions/0113_roms_locked_fields.py @@ -57,8 +57,6 @@ def upgrade() -> None: roms = _roms_table() connection = op.get_bind() - connection.execute(roms.update().values(locked_fields=[])) - # A stored cover path with an empty url is the pre-migration marker for an # upload. Values go through the JSON type rather than a literal so each # dialect serialises its own way. diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 0591ca3e5..cce048e8f 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -2059,15 +2059,12 @@ async def update_rom( } ) - # The cover and manual blocks below both take and release locks, so they - # share one running set that is written back once. Deriving each change from - # rom.locked_fields instead would let the later block discard the earlier - # block's change, since both would start from the same pre-update state. + # Cover and manual both take and release locks, so they accumulate into one + # running set rather than each deriving from the same pre-update state. locked_fields = set(rom.locked_fields or []) if remove_cover: cleaned_data.update(await fs_resource_handler.remove_cover(rom)) - # Dropping the hand-supplied cover hands the slot back to the providers. cleaned_data.update({"url_cover": ""}) locked_fields.discard("url_cover") else: @@ -2106,10 +2103,8 @@ async def update_rom( "path_cover_l": path_cover_l, } ) - # Naming a different source url is a handover back to the - # providers. Testing that it changed, not merely that one was - # sent, matters because the client posts the stored url on every - # save, so a plain save must not release the lock. + # The client posts the stored url on every save, so only a url + # that actually changed counts as a handover back to providers. if url_cover and url_cover != rom.url_cover: locked_fields.discard("url_cover") except ValidationError as e: @@ -2131,9 +2126,7 @@ async def update_rom( "path_manual": path_manual, } ) - # Same handover as the cover. An upload leaves url_manual untouched, so - # unlike the cover this url is often already set on a locked manual, - # which is exactly why only an actual change may release it. + # Same handover rule as the cover. if url_manual and url_manual != rom.url_manual: locked_fields.discard("url_manual") except ValidationError as e: diff --git a/backend/endpoints/roms/manual.py b/backend/endpoints/roms/manual.py index 34198b823..62d5b071b 100644 --- a/backend/endpoints/roms/manual.py +++ b/backend/endpoints/roms/manual.py @@ -120,8 +120,8 @@ async def add_rom_manuals( detail="There was an error uploading the manual", ) from exc - # An uploaded manual and a scraped one share this path and neither clears - # url_manual, so the lock is the only thing that will tell them apart. + # An uploaded manual and a scraped one share this path, so only the lock + # tells them apart. db_rom_handler.update_rom( id, { @@ -387,16 +387,15 @@ async def delete_rom_manuals( detail="No manual found for this ROM", ) + cleared = { + "path_manual": "", + "url_manual": "", + "locked_fields": rom.locked_fields_without("url_manual"), + } + try: await fs_resource_handler.remove_manual(rom) - db_rom_handler.update_rom( - id, - { - "path_manual": "", - "url_manual": "", - "locked_fields": rom.locked_fields_without("url_manual"), - }, - ) + db_rom_handler.update_rom(id, cleared) log.info( f"Deleted manual for {hl(rom.name or 'ROM', color=BLUE)} [{hl(rom.fs_name)}]" @@ -406,14 +405,7 @@ async def delete_rom_manuals( f"Manual file not found for {hl(rom.name or 'ROM', color=BLUE)} [{hl(rom.fs_name)}]" ) # Still update the database even if file doesn't exist - db_rom_handler.update_rom( - id, - { - "path_manual": "", - "url_manual": "", - "locked_fields": rom.locked_fields_without("url_manual"), - }, - ) + db_rom_handler.update_rom(id, cleared) except Exception as exc: log.error( f"Error deleting manual for {hl(rom.name or 'ROM', color=BLUE)} [{hl(rom.fs_name)}]", diff --git a/backend/handler/filesystem/resources_handler.py b/backend/handler/filesystem/resources_handler.py index 68a1fdb6a..d8778f6be 100644 --- a/backend/handler/filesystem/resources_handler.py +++ b/backend/handler/filesystem/resources_handler.py @@ -407,12 +407,14 @@ class FSResourcesHandler(FSHandler): ) # Screenshots - async def _store_screenshot(self, rom: Rom, url_screenhot: str, idx: int): + async def _store_screenshot(self, rom: Rom, url_screenhot: str, idx: int) -> bool: """Store roms resources in filesystem Args: rom: Rom object url_screenhot: URL to get the screenshot + Returns + True if the screenshot landed on disk else False """ screenshot_path = f"{rom.fs_resources_path}/screenshots" await self.make_directory(screenshot_path) @@ -423,14 +425,15 @@ class FSResourcesHandler(FSHandler): resolved = _resolve_local_file_uri(url_screenhot) if resolved is None or not await AnyioPath(resolved).exists(): log.warning(f"Screenshot file not found: {url_screenhot}") - return None + return False await self.copy_file( resolved, f"{screenshot_path}/{idx}.jpg", allow_link=True ) + return True except Exception as exc: log.error(f"Unable to copy screenshot file {url_screenhot}: {str(exc)}") await self._discard_partial_file(f"{screenshot_path}/{idx}.jpg") - return None + return False else: # Handle HTTP URLs httpx_client = ctx_httpx_client.get() @@ -443,7 +446,7 @@ class FSResourcesHandler(FSHandler): ): if response.status_code == status.HTTP_200_OK: if not _check_content_type(response, ("image/",), "screenshot"): - return None + return False # Check if content is gzipped from response headers is_gzipped = ( @@ -466,31 +469,22 @@ class FSResourcesHandler(FSHandler): # Content is not gzipped, stream directly async for chunk in response.aiter_raw(): await f.write(chunk) + + return True except httpx.TransportError as exc: log.error(f"Unable to fetch screenshot at {url_screenhot}: {str(exc)}") - return None + return False except OSError as exc: log.error(f"Unable to write screenshot for {url_screenhot}: {str(exc)}") - return None + return False - def _stored_screenshot_count(self, rom: Rom) -> int: - """How many screenshot files this rom actually has on disk.""" - full_path = self.validate_path(f"{rom.fs_resources_path}/screenshots") - return sum(1 for _ in full_path.glob("*.jpg")) - - def screenshots_exist(self, rom: Rom) -> bool: - """Check if rom screenshots exist in filesystem - - Args: - rom: Rom object - Returns - True if screenshots exists in filesystem else False - """ - full_path = self.validate_path(f"{rom.fs_resources_path}/screenshots") - for _ in full_path.glob("*.jpg"): - return True return False + def _stored_screenshot_indexes(self, rom: Rom) -> set[str]: + """Screenshot indexes this rom already has on disk.""" + full_path = self.validate_path(f"{rom.fs_resources_path}/screenshots") + return {path.stem for path in full_path.glob("*.jpg")} + def _get_screenshot_path(self, rom: Rom, idx: str): """Returns rom cover filesystem path adapted to frontend folder structure @@ -515,21 +509,18 @@ class FSResourcesHandler(FSHandler): if not url_screenshots: return rom.path_screenshots or [] - # Count what is on disk rather than what was recorded: fewer files than - # urls means an earlier run lost some, and the url set alone would never - # signal that, so fall through and fetch them again. - if not overwrite and self._stored_screenshot_count(rom) >= len(url_screenshots): - return rom.path_screenshots or [] + # Go by what is on disk rather than what was recorded: an unchanged url + # set still has to replace whatever an earlier run failed to write, and + # a path is only worth recording once its file is really there. + stored = set() if overwrite else self._stored_screenshot_indexes(rom) - # Download and store new screenshots path_screenshots: list[str] = [] for idx, url_screenshot in enumerate(url_screenshots): - await self._store_screenshot(rom, url_screenshot, idx) - path = self._get_screenshot_path(rom, str(idx)) - # A failed download leaves nothing behind, and recording its path - # anyway points the database at a file that isn't there. - if await self.file_exists(path): - path_screenshots.append(path) + if str(idx) not in stored and not await self._store_screenshot( + rom, url_screenshot, idx + ): + continue + path_screenshots.append(self._get_screenshot_path(rom, str(idx))) return path_screenshots diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index b5a36135b..fd7a5f57f 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -1122,21 +1122,17 @@ async def scan_rom( { "name": existing_name or matched_name or fs_name_no_tags or None, "summary": rom.summary or rom_attrs.get("summary") or None, - # A locked cover was supplied by hand and stays put. Anything - # else came from a provider, and the freshly resolved url - # replaces it so a changed source or source priority reaches the - # download step. + # Provider artwork yields to the freshly resolved url, so a + # changed source or priority reaches the download step. Only a + # locked slot stays put. Manuals are pinned regardless: rows + # predating the lock carry none, so an absent one is not yet + # evidence that a manual was scraped. "url_cover": ( "" if rom.is_field_locked("url_cover") else rom_attrs.get("url_cover") or None ), - # A manual keeps its stored url because an uploaded manual and a - # scraped one share a path and neither clears the url, so there - # is nothing here to tell them apart. "url_manual": rom.url_manual or rom_attrs.get("url_manual") or None, - # Screenshots have no upload path, so every stored url came from - # a provider and the freshly resolved set wins. "url_screenshots": rom_attrs.get("url_screenshots") or [], } ) @@ -1223,14 +1219,9 @@ async def scan_rom( # Apply SGDB's cover only when it outranks every other source that # already produced one under the cover priority, and never over a - # manually uploaded cover preserved by the UNMATCHED/UPDATE block above. + # locked cover. sgdb_cover = sgdb_hander_rom.get("url_cover") - manual_cover_preserved = ( - not newly_added - and scan_type in (ScanType.UNMATCHED, ScanType.UPDATE) - and rom.path_cover_s - ) - if sgdb_cover and not manual_cover_preserved: + if sgdb_cover and not rom.is_field_locked("url_cover"): cover_sources = [ name for name, fields in metadata_handlers.items() diff --git a/backend/models/rom.py b/backend/models/rom.py index 9bc7589e0..5b8b1003b 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -595,7 +595,7 @@ class Rom(BaseModel): locked_fields: Mapped[list[str] | None] = mapped_column( CustomJSON(), default=[], - doc="Fields a user supplied by hand, which scans must not overwrite", + doc="Slots a user owns, whose stored file a scan must leave alone", ) revision: Mapped[str | None] = mapped_column(String(length=100)) @@ -790,7 +790,7 @@ class Rom(BaseModel): def locked_fields_without(self, field: str) -> list[str]: """This rom's locks minus ``field``, for handing to an update.""" - return [f for f in (self.locked_fields or []) if f != field] + return sorted({*(self.locked_fields or [])} - {field}) @property def is_unidentified(self) -> bool: diff --git a/backend/tests/endpoints/roms/test_manual.py b/backend/tests/endpoints/roms/test_manual.py index 8be435846..0bd7896c3 100644 --- a/backend/tests/endpoints/roms/test_manual.py +++ b/backend/tests/endpoints/roms/test_manual.py @@ -89,8 +89,6 @@ def test_upload_manual_to_resources_success( assert written.read_bytes() == PDF_BYTES refreshed = db_rom_handler.get_rom(rom.id) assert refreshed.path_manual == f"{rom.fs_resources_path}/manual/{rom.id}.pdf" - # An uploaded manual and a scraped one land at the same path and neither - # clears url_manual, so the lock is the only thing telling them apart. assert refreshed.locked_fields == ["url_manual"] @@ -278,7 +276,6 @@ def test_redownload_manual_success( assert response.status_code == status.HTTP_200_OK refreshed = db_rom_handler.get_rom(rom.id) assert refreshed.path_manual == fake_path - # Asking for the provider's manual back is a handover. assert refreshed.locked_fields == [] @@ -337,7 +334,6 @@ def test_delete_manual_success( refreshed = db_rom_handler.get_rom(rom.id) assert refreshed.path_manual == "" assert refreshed.url_manual == "" - # Deleting the hand-supplied manual hands the slot back to the providers. assert refreshed.locked_fields == [] diff --git a/backend/tests/handler/filesystem/test_resources_handler.py b/backend/tests/handler/filesystem/test_resources_handler.py index eb58fe9b2..c16e56f88 100644 --- a/backend/tests/handler/filesystem/test_resources_handler.py +++ b/backend/tests/handler/filesystem/test_resources_handler.py @@ -406,6 +406,7 @@ class TestFSResourcesHandler: directory = tmp_path / f"{rom.fs_resources_path}/screenshots" directory.mkdir(parents=True, exist_ok=True) (directory / f"{idx}.jpg").write_bytes(b"jpeg") + return True with patch.object( handler, "_store_screenshot", side_effect=store @@ -652,6 +653,86 @@ class TestFSResourcesHandler: assert "retroachievements" in ra_base assert "badges" in ra_badges + @pytest.mark.asyncio + async def test_failed_screenshot_is_not_recorded( + self, handler: FSResourcesHandler, rom: Rom, tmp_path + ): + # Recording a path for a screenshot that never landed points the + # database at a missing file, and the gallery at a broken image. + handler.base_path = tmp_path + + async def store_only_the_first(_rom, _url, idx): + if idx != 0: + return False + path = tmp_path / "roms/1/1/screenshots" + path.mkdir(parents=True, exist_ok=True) + (path / "0.jpg").write_bytes(b"jpeg") + return True + + with patch.object( + handler, "_store_screenshot", side_effect=store_only_the_first + ): + paths = await handler.get_rom_screenshots( + rom=rom, + overwrite=True, + url_screenshots=["http://x/a.jpg", "http://x/b.jpg"], + ) + + assert paths == ["roms/1/1/screenshots/0.jpg"] + + @pytest.mark.asyncio + async def test_only_the_missing_screenshot_is_fetched( + self, handler: FSResourcesHandler, rom: Rom, tmp_path + ): + # The url set is unchanged after a partial failure, so the gap is only + # visible on disk. Refetching the whole set instead would re-download + # every screenshot on every scan whenever one url is permanently dead. + handler.base_path = tmp_path + rom.path_screenshots = ["roms/1/1/screenshots/0.jpg"] + screenshots = tmp_path / "roms/1/1/screenshots" + screenshots.mkdir(parents=True) + (screenshots / "0.jpg").write_bytes(b"jpeg") + + attempted: list[int] = [] + + async def record(_rom, _url, idx): + attempted.append(idx) + (screenshots / f"{idx}.jpg").write_bytes(b"jpeg") + return True + + with patch.object(handler, "_store_screenshot", side_effect=record): + paths = await handler.get_rom_screenshots( + rom=rom, + overwrite=False, + url_screenshots=["http://x/a.jpg", "http://x/b.jpg"], + ) + + assert attempted == [1] + assert paths == [ + "roms/1/1/screenshots/0.jpg", + "roms/1/1/screenshots/1.jpg", + ] + + @pytest.mark.asyncio + async def test_cover_with_no_source_url_is_rederived_from_disk( + self, handler: FSResourcesHandler, rom: Rom, tmp_path + ): + # Second half of what keeps a locked cover alive through an unmatch, + # which clears the stored paths but never deletes the files. + handler.base_path = tmp_path + cover = tmp_path / "roms/1/1/cover" + cover.mkdir(parents=True) + (cover / "big.png").write_bytes(b"uploaded") + (cover / "small.png").write_bytes(b"uploaded") + + path_s, path_l = await handler.get_cover( + entity=rom, overwrite=False, url_cover="" + ) + + assert path_s == "roms/1/1/cover/small.png" + assert path_l == "roms/1/1/cover/big.png" + assert (cover / "big.png").read_bytes() == b"uploaded" + class TestChromaKeyDetection: """Tests for ScreenScraper chroma-key green placeholder handling.""" @@ -1142,80 +1223,6 @@ class TestDiskFullHandling: assert list(cover_dir.iterdir()) == [] - @pytest.mark.asyncio - async def test_failed_screenshot_is_not_recorded( - self, handler: FSResourcesHandler, rom: Rom, tmp_path - ): - # Recording a path for a screenshot that never landed points the - # database at a missing file, and the gallery at a broken image. - handler.base_path = tmp_path - - async def store_only_the_first(_rom, _url, idx): - if idx != 0: - return None - path = tmp_path / "roms/1/1/screenshots" - path.mkdir(parents=True, exist_ok=True) - (path / "0.jpg").write_bytes(b"jpeg") - - handler._store_screenshot = store_only_the_first # type: ignore[method-assign] - - paths = await handler.get_rom_screenshots( - rom=rom, - overwrite=True, - url_screenshots=["http://x/a.jpg", "http://x/b.jpg"], - ) - - assert paths == ["roms/1/1/screenshots/0.jpg"] - - @pytest.mark.asyncio - async def test_short_screenshot_set_is_retried( - self, handler: FSResourcesHandler, rom: Rom, tmp_path - ): - # The url set is unchanged after a partial failure, so without this the - # missing screenshot would never be fetched again. - handler.base_path = tmp_path - rom.path_screenshots = ["roms/1/1/screenshots/0.jpg"] - screenshots = tmp_path / "roms/1/1/screenshots" - screenshots.mkdir(parents=True) - (screenshots / "0.jpg").write_bytes(b"jpeg") - - attempted: list[int] = [] - - async def record(_rom, _url, idx): - attempted.append(idx) - - handler._store_screenshot = record # type: ignore[method-assign] - - await handler.get_rom_screenshots( - rom=rom, - overwrite=False, - url_screenshots=["http://x/a.jpg", "http://x/b.jpg"], - ) - - assert attempted == [0, 1] - - @pytest.mark.asyncio - async def test_cover_with_no_source_url_is_rederived_from_disk( - self, handler: FSResourcesHandler, rom: Rom, tmp_path - ): - # Second half of what keeps a locked cover alive through an unmatch, - # which clears the stored paths but never deletes the files. A lock is - # not visible here: it resolves to an empty url upstream, and - # test_update_scan_keeps_uploaded_cover covers that half. - handler.base_path = tmp_path - cover = tmp_path / "roms/1/1/cover" - cover.mkdir(parents=True) - (cover / "big.png").write_bytes(b"uploaded") - (cover / "small.png").write_bytes(b"uploaded") - - path_s, path_l = await handler.get_cover( - entity=rom, overwrite=False, url_cover="" - ) - - assert path_s == "roms/1/1/cover/small.png" - assert path_l == "roms/1/1/cover/big.png" - assert (cover / "big.png").read_bytes() == b"uploaded" - @pytest.mark.asyncio async def test_interrupted_download_leaves_no_temp_file( self, handler: FSResourcesHandler, rom: Rom, tmp_path diff --git a/backend/tests/handler/test_fastapi.py b/backend/tests/handler/test_fastapi.py index bd7bc9393..d0802628e 100644 --- a/backend/tests/handler/test_fastapi.py +++ b/backend/tests/handler/test_fastapi.py @@ -528,6 +528,15 @@ def _scraped_cover_rom(platform: Platform, **overrides) -> Rom: return db_rom_handler.add_rom(Rom(**attrs)) +NEW_COVER_URL = "https://ss.fr/media?media=box-2D&id=new" + + +def _ss_returns_new_cover(mock_ss_get_by_id: AsyncMock) -> None: + mock_ss_get_by_id.return_value = SSRom( + ss_id=321, name="Game", url_cover=NEW_COVER_URL + ) + + async def _update_scan(platform: Platform, rom: Rom) -> Rom: async with initialize_context(): return await scan_rom( @@ -548,18 +557,14 @@ async def test_update_scan_replaces_scraped_cover_url( """A cover that carries a source url came from a provider, so an UPDATE scan hands the freshly resolved url downstream. Pinning it to the stored value is what kept a changed source priority from ever reaching the download step.""" - mock_ss_get_by_id.return_value = SSRom( - ss_id=321, - name="Game", - url_cover="https://ss.fr/media?media=box-2D&id=new", - ) + _ss_returns_new_cover(mock_ss_get_by_id) platform = _ss_quota_platform() rom = _scraped_cover_rom(platform) result = await _update_scan(platform, rom) - assert result.url_cover == "https://ss.fr/media?media=box-2D&id=new" + assert result.url_cover == NEW_COVER_URL @patch.object(meta_playmatch_handler, "is_enabled", return_value=False) @@ -569,11 +574,7 @@ async def test_update_scan_keeps_uploaded_cover( ): """Uploading artwork locks the cover, so the provider url must not be adopted over it.""" - mock_ss_get_by_id.return_value = SSRom( - ss_id=321, - name="Game", - url_cover="https://ss.fr/media?media=box-2D&id=new", - ) + _ss_returns_new_cover(mock_ss_get_by_id) platform = _ss_quota_platform() rom = _scraped_cover_rom(platform, url_cover="", locked_fields=["url_cover"]) @@ -592,11 +593,7 @@ async def test_update_scan_keeps_locked_cover_with_no_stored_path( """The lock has to outlive path_cover_s. That column tracks the filesystem and a scan clears it whenever the file is unreadable, so inferring the lock from it meant one scan against unavailable storage handed the cover to the provider.""" - mock_ss_get_by_id.return_value = SSRom( - ss_id=321, - name="Game", - url_cover="https://ss.fr/media?media=box-2D&id=new", - ) + _ss_returns_new_cover(mock_ss_get_by_id) platform = _ss_quota_platform() rom = _scraped_cover_rom(