diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 59a49d476..e1375e5d5 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -1932,17 +1932,11 @@ async def update_rom( media_type, ) - media_path = cleaned_data.get("ss_metadata", {}).get( - f"{media_type.value}_path" + ss_metadata = cleaned_data.get("ss_metadata") + if ss_metadata: + await fs_resource_handler.store_metadata_media( + ss_metadata, preferred_media_types, add_ss_auth_to_url ) - media_url = cleaned_data.get("ss_metadata", {}).get( - f"{media_type.value}_url" - ) - if media_path and media_url: - await fs_resource_handler.store_media_file( - add_ss_auth_to_url(media_url), - media_path, - ) # Handle local media files from LaunchBox when the ID has changed if ( @@ -1962,17 +1956,11 @@ async def update_rom( media_type, ) - media_path = cleaned_data.get("launchbox_metadata", {}).get( - f"{media_type.value}_path" + launchbox_metadata = cleaned_data.get("launchbox_metadata") + if launchbox_metadata: + await fs_resource_handler.store_metadata_media( + launchbox_metadata, preferred_media_types ) - media_url = cleaned_data.get("launchbox_metadata", {}).get( - f"{media_type.value}_url" - ) - if media_path and media_url: - await fs_resource_handler.store_media_file( - media_url, - media_path, - ) log.debug( f"Updating {hl(cleaned_data.get('name', ''), color=BLUE)} [{hl(cleaned_data.get('fs_name', ''))}] with data {cleaned_data}" diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 475dcef77..f0db7f4b7 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -555,37 +555,32 @@ async def _identify_rom( }, ) - # Handle special media files from Screenscraper + # Handle special media files from Screenscraper, ES-DE gamelist.xml and + # LaunchBox. Media that didn't land on disk has its recorded path cleared, so + # write those dicts back when that happens. + preferred_media_types = get_preferred_media_types() + media_updates: dict[str, Any] = {} + if _added_rom.ss_metadata and MetadataSource.SS in metadata_sources: - preferred_media_types = get_preferred_media_types() - for media_type in preferred_media_types: - media_path = _added_rom.ss_metadata.get(f"{media_type.value}_path") - media_url = _added_rom.ss_metadata.get(f"{media_type.value}_url") - if media_path and media_url: - await fs_resource_handler.store_media_file( - add_ss_auth_to_url(media_url), - media_path, - ) + if await fs_resource_handler.store_metadata_media( + _added_rom.ss_metadata, preferred_media_types, add_ss_auth_to_url + ): + media_updates["ss_metadata"] = _added_rom.ss_metadata - # Handle special media files from ES-DE gamelist.xml if _added_rom.gamelist_metadata and MetadataSource.GAMELIST in metadata_sources: - preferred_media_types = get_preferred_media_types() - for media_type in preferred_media_types: - if _added_rom.gamelist_metadata.get(f"{media_type.value}_path"): - await fs_resource_handler.store_media_file( - _added_rom.gamelist_metadata[f"{media_type.value}_url"], - _added_rom.gamelist_metadata[f"{media_type.value}_path"], - ) + if await fs_resource_handler.store_metadata_media( + _added_rom.gamelist_metadata, preferred_media_types + ): + media_updates["gamelist_metadata"] = _added_rom.gamelist_metadata - # Handle special media files from LaunchBox if _added_rom.launchbox_metadata and MetadataSource.LAUNCHBOX in metadata_sources: - preferred_media_types = get_preferred_media_types() - for media_type in preferred_media_types: - if _added_rom.launchbox_metadata.get(f"{media_type.value}_path"): - await fs_resource_handler.store_media_file( - _added_rom.launchbox_metadata[f"{media_type.value}_url"], - _added_rom.launchbox_metadata[f"{media_type.value}_path"], - ) + if await fs_resource_handler.store_metadata_media( + _added_rom.launchbox_metadata, preferred_media_types + ): + media_updates["launchbox_metadata"] = _added_rom.launchbox_metadata + + if media_updates: + db_rom_handler.update_rom(_added_rom.id, media_updates) # Store normal and locked badges if _added_rom.ra_metadata and MetadataSource.RA in metadata_sources: diff --git a/backend/handler/filesystem/resources_handler.py b/backend/handler/filesystem/resources_handler.py index b88fa1329..4138fc9fd 100644 --- a/backend/handler/filesystem/resources_handler.py +++ b/backend/handler/filesystem/resources_handler.py @@ -1,7 +1,9 @@ import gzip import os +from collections.abc import Callable, Iterable from io import BytesIO from pathlib import Path +from typing import Any import httpx from anyio import Path as AnyioPath @@ -661,7 +663,12 @@ class FSResourcesHandler(FSHandler): ) -> str: return os.path.join("roms", str(platform_id), str(rom_id), media_type.value) - async def store_media_file(self, url_media: str, dest_path: str) -> None: + async def store_media_file(self, url_media: str, dest_path: str) -> bool: + """Fetch a media file into ``dest_path``. + + Returns whether the file is on disk afterwards, so callers can stop + recording a path for media that never landed. + """ directory, filename = os.path.split(dest_path) if await self.file_exists(dest_path): @@ -679,7 +686,7 @@ class FSResourcesHandler(FSHandler): except Exception as exc: log.error(f"Unable to copy media file {url_media}: {str(exc)}") await self._discard_partial_file(dest_path) - return None + return False else: # Handle HTTP URLs httpx_client = ctx_httpx_client.get() @@ -696,7 +703,7 @@ class FSResourcesHandler(FSHandler): ("image/", "video/", "application/pdf"), "media", ): - return None + return False async with await self.write_file_streamed( path=directory, filename=filename @@ -706,17 +713,54 @@ class FSResourcesHandler(FSHandler): except httpx.TransportError as exc: log.error(f"Unable to fetch media file at {url_media}: {str(exc)}") await self._discard_partial_file(dest_path) - return None + return False except OSError as exc: log.error(f"Unable to write media file for {url_media}: {str(exc)}") await self._discard_partial_file(dest_path) - return None + return False # Drop ScreenScraper's green "missing art" placeholder so a box face # (box-2D-back / box-2D-side) falls back to the dark placeholder rather # than rendering bright green. Runs for pre-existing files too, cleaning # them up on rescan. - await self._discard_if_chroma_key(dest_path) + if await self._discard_if_chroma_key(dest_path): + return False + + # A non-200 response, or a local URI that resolved to nothing, leaves no + # file behind without raising. + return await self.file_exists(dest_path) + + async def store_metadata_media( + self, + metadata: dict[str, Any], + media_types: Iterable[MetadataMediaType], + url_transform: Callable[[str], str] | None = None, + ) -> bool: + """Fetch every recorded media file of a provider metadata dict. + + Providers record where each media file should live before it's fetched, + so a failed download (or discarded placeholder art) would otherwise leave + the dict pointing at a file that isn't there. Clears those ``*_path`` + entries and returns whether the dict was modified. + """ + changed = False + + for media_type in media_types: + path_key = f"{media_type.value}_path" + media_path = metadata.get(path_key) + media_url = metadata.get(f"{media_type.value}_url") + if not media_path or not media_url: + continue + + stored = await self.store_media_file( + url_transform(media_url) if url_transform else media_url, + media_path, + ) + if not stored: + metadata[path_key] = None + changed = True + + return changed async def remove_media_resources_path( self, diff --git a/backend/tests/handler/filesystem/test_resources_handler.py b/backend/tests/handler/filesystem/test_resources_handler.py index 57c65aa9c..34443e44c 100644 --- a/backend/tests/handler/filesystem/test_resources_handler.py +++ b/backend/tests/handler/filesystem/test_resources_handler.py @@ -13,6 +13,7 @@ from adapters.services.screenscraper import ( SS_DEFAULT_MEDIA_TIMEOUT, ) from config import RESOURCES_BASE_PATH +from config.config_manager import MetadataMediaType from handler.filesystem.base_handler import CoverSize from handler.filesystem.resources_handler import ( FSResourcesHandler, @@ -771,6 +772,194 @@ class TestChromaKeyDetection: assert (tmp_path / rel).exists() +class TestStoreMediaFileResult: + """store_media_file reports whether the media actually landed on disk, so + callers can drop the recorded path instead of pointing at a missing file.""" + + @pytest.fixture + def handler(self): + return FSResourcesHandler() + + @pytest.mark.asyncio + async def test_returns_true_for_downloaded_file( + self, handler: FSResourcesHandler, tmp_path + ): + handler.base_path = tmp_path + rel = "roms/1/1/box2d_back/box2d_back.png" + + with patch("handler.filesystem.resources_handler.ctx_httpx_client") as mock_ctx: + mock_ctx.get.return_value = _FakeHttpxClient(_FakeResponse()) + assert await handler.store_media_file("http://example.com/x.png", rel) + + assert (tmp_path / rel).exists() + + @pytest.mark.asyncio + async def test_returns_true_for_pre_existing_file( + self, handler: FSResourcesHandler, tmp_path + ): + handler.base_path = tmp_path + rel = "roms/1/1/box2d_back/box2d_back.png" + (tmp_path / rel).parent.mkdir(parents=True) + (tmp_path / rel).write_bytes(b"art") + + assert await handler.store_media_file("http://example.com/x.png", rel) + + @pytest.mark.asyncio + async def test_returns_false_on_error_response( + self, handler: FSResourcesHandler, tmp_path + ): + handler.base_path = tmp_path + response = _FakeResponse() + response.status_code = 404 + + with patch("handler.filesystem.resources_handler.ctx_httpx_client") as mock_ctx: + mock_ctx.get.return_value = _FakeHttpxClient(response) + stored = await handler.store_media_file( + "http://example.com/x.png", "roms/1/1/box2d_back/box2d_back.png" + ) + + assert stored is False + + @pytest.mark.asyncio + async def test_returns_false_on_unexpected_content_type( + self, handler: FSResourcesHandler, tmp_path + ): + handler.base_path = tmp_path + response = _FakeResponse() + response.headers = {"content-type": "text/html"} + + with patch("handler.filesystem.resources_handler.ctx_httpx_client") as mock_ctx: + mock_ctx.get.return_value = _FakeHttpxClient(response) + stored = await handler.store_media_file( + "http://example.com/x.png", "roms/1/1/box2d_back/box2d_back.png" + ) + + assert stored is False + + @pytest.mark.asyncio + async def test_returns_false_on_transport_error( + self, handler: FSResourcesHandler, tmp_path + ): + handler.base_path = tmp_path + + with patch("handler.filesystem.resources_handler.ctx_httpx_client") as mock_ctx: + client = Mock() + client.stream.side_effect = httpx.ConnectError("no route") + mock_ctx.get.return_value = client + stored = await handler.store_media_file( + "http://example.com/x.png", "roms/1/1/box2d_back/box2d_back.png" + ) + + assert stored is False + + @pytest.mark.asyncio + async def test_returns_false_for_discarded_chroma_key( + self, handler: FSResourcesHandler, tmp_path + ): + handler.base_path = tmp_path + rel = "roms/1/1/box2d_back/box2d_back.png" + (tmp_path / rel).parent.mkdir(parents=True) + Image.new("RGB", (64, 64), (0, 255, 0)).save(tmp_path / rel) + + assert await handler.store_media_file("http://example.com/x.png", rel) is False + + @pytest.mark.asyncio + async def test_returns_false_for_unresolvable_local_uri( + self, handler: FSResourcesHandler, tmp_path + ): + handler.base_path = tmp_path + stored = await handler.store_media_file( + "launchbox-file://Videos/NES/missing.mp4", "roms/1/1/video/video.mp4" + ) + + assert stored is False + + +class TestStoreMetadataMedia: + """Recorded media paths must not survive a download that didn't produce a + file, or exports and artwork URLs would point at nothing.""" + + @pytest.fixture + def handler(self): + return FSResourcesHandler() + + @pytest.mark.asyncio + async def test_clears_paths_for_media_that_did_not_land( + self, handler: FSResourcesHandler + ): + metadata = { + "box2d_back_url": "http://example.com/back.png", + "box2d_back_path": "roms/1/1/box2d_back/box2d_back.png", + "fanart_url": "http://example.com/fanart.png", + "fanart_path": "roms/1/1/fanart/fanart.png", + } + + async def fake_store(_url: str, dest_path: str) -> bool: + return "fanart" in dest_path + + with patch.object(handler, "store_media_file", side_effect=fake_store): + changed = await handler.store_metadata_media( + metadata, + [MetadataMediaType.BOX2D_BACK, MetadataMediaType.FANART], + ) + + assert changed is True + assert metadata["box2d_back_path"] is None + assert metadata["fanart_path"] == "roms/1/1/fanart/fanart.png" + # The URL is kept so a later scan can retry the download + assert metadata["box2d_back_url"] == "http://example.com/back.png" + + @pytest.mark.asyncio + async def test_leaves_metadata_untouched_when_all_media_lands( + self, handler: FSResourcesHandler + ): + metadata = { + "fanart_url": "http://example.com/fanart.png", + "fanart_path": "roms/1/1/fanart/fanart.png", + } + + with patch.object(handler, "store_media_file", return_value=True): + changed = await handler.store_metadata_media( + metadata, [MetadataMediaType.FANART] + ) + + assert changed is False + assert metadata["fanart_path"] == "roms/1/1/fanart/fanart.png" + + @pytest.mark.asyncio + async def test_skips_media_types_without_a_url_or_path( + self, handler: FSResourcesHandler + ): + metadata = {"fanart_url": "http://example.com/fanart.png"} + + with patch.object(handler, "store_media_file") as store_mock: + changed = await handler.store_metadata_media( + metadata, + [MetadataMediaType.FANART, MetadataMediaType.BOX2D_BACK], + ) + + assert changed is False + store_mock.assert_not_called() + + @pytest.mark.asyncio + async def test_applies_the_url_transform(self, handler: FSResourcesHandler): + metadata = { + "fanart_url": "http://example.com/fanart.png", + "fanart_path": "roms/1/1/fanart/fanart.png", + } + + with patch.object(handler, "store_media_file", return_value=True) as store_mock: + await handler.store_metadata_media( + metadata, + [MetadataMediaType.FANART], + lambda url: f"{url}?ssid=user", + ) + + store_mock.assert_awaited_once_with( + "http://example.com/fanart.png?ssid=user", "roms/1/1/fanart/fanart.png" + ) + + class _FakeResponse: """Minimal stand-in for an httpx streaming response.""" diff --git a/backend/tests/utils/test_gamelist_exporter.py b/backend/tests/utils/test_gamelist_exporter.py index 7bbbc9169..b5b1a0898 100644 --- a/backend/tests/utils/test_gamelist_exporter.py +++ b/backend/tests/utils/test_gamelist_exporter.py @@ -397,10 +397,9 @@ async def test_export_platform_to_file_omits_tags_when_copy_fails( # Successful copies present assert (platform_dir / "assets/covers/Super Mario World (USA).jpg").is_file() assert (platform_dir / "assets/screenshots/Super Mario World (USA).jpg").is_file() - # Failed copies don't produce destination files (an empty subdir may be - # left behind because _copy_asset mkdirs before opening the source). - assert not (platform_dir / "assets/manuals/Super Mario World (USA).pdf").exists() - assert not (platform_dir / "assets/videos/Super Mario World (USA).mp4").exists() + # A missing source produces neither a destination file nor an empty subdir + assert not (platform_dir / "assets/manuals").exists() + assert not (platform_dir / "assets/videos").exists() game = fromstring((platform_dir / "gamelist.xml").read_text()).findall("game")[0] assert game.find("manual") is None diff --git a/backend/utils/gamelist_exporter.py b/backend/utils/gamelist_exporter.py index 1607c02c9..a6edbb818 100644 --- a/backend/utils/gamelist_exporter.py +++ b/backend/utils/gamelist_exporter.py @@ -155,10 +155,17 @@ class GamelistExporter: def _copy_asset(self, source: Path, dest: Path) -> bool: """Place ``source`` at ``dest`` via hardlink (same filesystem) or copy (otherwise). Returns True on success.""" - dest.parent.mkdir(parents=True, exist_ok=True) if dest.exists(): return True + # Metadata scanned before RomM cleared unfetched media paths can still + # point at files that were never downloaded. + if not source.is_file(): + log.debug(f"Skipping asset {source}: source file is missing") + return False + + dest.parent.mkdir(parents=True, exist_ok=True) + try: link_or_copy_file(source, dest) return True diff --git a/backend/utils/pegasus_exporter.py b/backend/utils/pegasus_exporter.py index 17d32afc8..ed7ea1204 100644 --- a/backend/utils/pegasus_exporter.py +++ b/backend/utils/pegasus_exporter.py @@ -292,10 +292,17 @@ class PegasusExporter: def _copy_asset(self, source: Path, dest: Path) -> bool: """Place ``source`` at ``dest`` via hardlink (same filesystem) or copy (otherwise). Returns True on success.""" - dest.parent.mkdir(parents=True, exist_ok=True) if dest.exists(): return True + # Metadata scanned before RomM cleared unfetched media paths can still + # point at files that were never downloaded. + if not source.is_file(): + log.debug(f"Skipping asset {source}: source file is missing") + return False + + dest.parent.mkdir(parents=True, exist_ok=True) + try: link_or_copy_file(source, dest) return True