mirror of
https://github.com/rommapp/romm.git
synced 2026-12-02 10:08:40 +01:00
The cover search dialog only reached SteamGridDB, so a PC game whose capsule lives on Steam had no way to pick it up short of a full re-match. Steam now joins SteamGridDB behind `GET /search/cover`, ordered by the configured cover priority, and each result carries its provider so the dialog can filter by source and credit the artwork. The Steam handler builds the picker from the store search alone and probes the CDN for the portrait capsule and the landscape header under the same budget the match picker uses, so a slow CDN costs thumbnails rather than the dialog. Hits with no artwork are dropped. A failing provider costs only its own covers; a rejected SteamGridDB key is still reported, since that is the user's to fix. The "search cover" action in the edit dialog now opens whenever either provider is enabled, and the game overview credits Steam-hosted covers. The resource shape the picker consumes moves to the shared base handler as `CoverResource` / `CoverResult`, since it is no longer SteamGridDB's alone. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Untv32z88QMZ2yRSsTgGcC
391 lines
14 KiB
Python
391 lines
14 KiB
Python
import asyncio
|
|
from collections.abc import Callable, Sequence
|
|
from typing import Any, TypeVar
|
|
|
|
from fastapi import HTTPException, Request, status
|
|
|
|
from decorators.auth import protected_route
|
|
from endpoints.responses.search import SearchCoverSchema, SearchRomSchema
|
|
from handler.auth.constants import Scope
|
|
from handler.auth.dependencies import get_permissions
|
|
from handler.database import db_rom_handler
|
|
from handler.metadata import (
|
|
meta_demozoo_handler,
|
|
meta_flashpoint_handler,
|
|
meta_igdb_handler,
|
|
meta_launchbox_handler,
|
|
meta_libretro_handler,
|
|
meta_moby_handler,
|
|
meta_sgdb_handler,
|
|
meta_ss_handler,
|
|
meta_steam_handler,
|
|
)
|
|
from handler.metadata.base_handler import CoverResult
|
|
from handler.metadata.demozoo_handler import DemozooRom
|
|
from handler.metadata.flashpoint_handler import FlashpointRom
|
|
from handler.metadata.igdb_handler import IGDBRom
|
|
from handler.metadata.launchbox_handler.types import LaunchboxRom
|
|
from handler.metadata.libretro_handler import LibretroRom
|
|
from handler.metadata.moby_handler import MobyGamesRom
|
|
from handler.metadata.sgdb_handler import SGDBRom
|
|
from handler.metadata.ss_handler import SSRom
|
|
from handler.metadata.steam_handler import SteamRom
|
|
from handler.scan_handler import (
|
|
MetadataSource,
|
|
get_main_platform_igdb_id,
|
|
get_priority_ordered_metadata_sources,
|
|
)
|
|
from logger.formatter import BLUE, CYAN
|
|
from logger.formatter import highlight as hl
|
|
from logger.logger import log
|
|
from utils import emoji
|
|
from utils.router import APIRouter
|
|
|
|
_CoverRomT = TypeVar("_CoverRomT", SGDBRom, LibretroRom)
|
|
|
|
router = APIRouter(
|
|
prefix="/search",
|
|
tags=["search"],
|
|
)
|
|
|
|
|
|
def _without_failures(
|
|
results: list[tuple[str, _CoverRomT] | BaseException], provider: str
|
|
) -> list[tuple[str, _CoverRomT]]:
|
|
"""Drop the cover lookups that failed."""
|
|
fetched = []
|
|
for result in results:
|
|
if isinstance(result, BaseException):
|
|
log.error("Error fetching %s covers: %s", provider, result)
|
|
else:
|
|
fetched.append(result)
|
|
return fetched
|
|
|
|
|
|
# The order the provider lookups are gathered in, for reporting which one failed.
|
|
_ID_SEARCH_PROVIDERS = (
|
|
"IGDB",
|
|
"MobyGames",
|
|
"ScreenScraper",
|
|
"LaunchBox",
|
|
"Demozoo",
|
|
"Steam",
|
|
)
|
|
_NAME_SEARCH_PROVIDERS = (
|
|
"IGDB",
|
|
"MobyGames",
|
|
"ScreenScraper",
|
|
"Flashpoint",
|
|
"LaunchBox",
|
|
"Demozoo",
|
|
"Steam",
|
|
)
|
|
|
|
|
|
def _resolved(
|
|
results: Sequence[Any], providers: Sequence[str], fallback: Callable[[], Any]
|
|
) -> list[Any]:
|
|
"""Let a provider that could not answer cost only its own matches."""
|
|
resolved: list[Any] = []
|
|
for provider, result in zip(providers, results, strict=True):
|
|
if isinstance(result, BaseException):
|
|
log.error("Error searching %s: %s", provider, result)
|
|
resolved.append(fallback())
|
|
else:
|
|
resolved.append(result)
|
|
return resolved
|
|
|
|
|
|
@protected_route(router.get, "/roms", [Scope.ROMS_READ])
|
|
async def search_rom(
|
|
request: Request,
|
|
rom_id: int,
|
|
search_term: str | None = None,
|
|
search_by: str = "name",
|
|
) -> list[SearchRomSchema]:
|
|
"""Search for rom in metadata providers
|
|
|
|
Args:
|
|
request (Request): FastAPI request
|
|
rom_id (int): Rom ID
|
|
source (str): Source of the rom
|
|
search_term (str, optional): Search term. Defaults to None.
|
|
search_by (str, optional): Search by name or ID. Defaults to "name".
|
|
search_extended (bool, optional): Search extended info. Defaults to False.
|
|
|
|
Returns:
|
|
list[SearchRomSchema]: List of matched roms
|
|
"""
|
|
|
|
if (
|
|
not meta_igdb_handler.is_enabled()
|
|
and not meta_ss_handler.is_enabled()
|
|
and not meta_moby_handler.is_enabled()
|
|
and not meta_flashpoint_handler.is_enabled()
|
|
and not meta_launchbox_handler.is_cloud_enabled()
|
|
and not meta_demozoo_handler.is_enabled()
|
|
and not meta_steam_handler.is_enabled()
|
|
):
|
|
log.error("Search error: No metadata providers enabled")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail="No metadata providers enabled",
|
|
)
|
|
|
|
rom = db_rom_handler.get_rom(rom_id)
|
|
if not rom:
|
|
return []
|
|
|
|
# Treat a rom hidden from the caller as non-existent.
|
|
if request.user.is_authenticated and not get_permissions(request).can_see_rom(
|
|
rom.id, rom.platform_id
|
|
):
|
|
return []
|
|
|
|
search_term = search_term or rom.fs_name_no_tags
|
|
if not search_term:
|
|
return []
|
|
|
|
log.info(
|
|
f"{emoji.EMOJI_MAGNIFYING_GLASS_TILTED_RIGHT} Searching metadata providers..."
|
|
)
|
|
|
|
log.info(f"Searching by {hl(search_by.lower(), color=CYAN)}:")
|
|
log.info(
|
|
f"{emoji.EMOJI_VIDEO_GAME} {hl(rom.platform_display_name, color=BLUE)} [{rom.platform_fs_slug}]: {hl(search_term)}[{rom.fs_name}]"
|
|
)
|
|
|
|
igdb_matched_roms: list[IGDBRom] = []
|
|
moby_matched_roms: list[MobyGamesRom] = []
|
|
ss_matched_roms: list[SSRom] = []
|
|
flashpoint_matched_roms: list[FlashpointRom] = []
|
|
launchbox_matched_roms: list[LaunchboxRom] = []
|
|
demozoo_matched_roms: list[DemozooRom] = []
|
|
steam_matched_roms: list[SteamRom] = []
|
|
|
|
if search_by.lower() == "id":
|
|
try:
|
|
gathered = await asyncio.gather(
|
|
meta_igdb_handler.get_matched_rom_by_id(rom, int(search_term)),
|
|
meta_moby_handler.get_matched_rom_by_id(int(search_term)),
|
|
meta_ss_handler.get_matched_rom_by_id(rom, int(search_term)),
|
|
meta_launchbox_handler.get_matched_rom_by_id(int(search_term)),
|
|
meta_demozoo_handler.get_rom_by_id(int(search_term)),
|
|
meta_steam_handler.get_matched_rom_by_id(
|
|
int(search_term), rom.platform.slug
|
|
),
|
|
return_exceptions=True,
|
|
)
|
|
except ValueError as exc:
|
|
log.error(f"Search error: invalid ID '{search_term}'")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail=f"Tried searching by ID, but '{search_term}' is not a valid ID",
|
|
) from exc
|
|
else:
|
|
igdb_rom, moby_rom, ss_rom, lb_rom, dz_rom, steam_rom = _resolved(
|
|
gathered, _ID_SEARCH_PROVIDERS, lambda: None
|
|
)
|
|
igdb_matched_roms = [igdb_rom] if igdb_rom else []
|
|
moby_matched_roms = [moby_rom] if moby_rom else []
|
|
ss_matched_roms = [ss_rom] if ss_rom else []
|
|
launchbox_matched_roms = [lb_rom] if lb_rom else []
|
|
demozoo_matched_roms = (
|
|
[dz_rom] if dz_rom and dz_rom.get("demozoo_id") else []
|
|
)
|
|
steam_matched_roms = (
|
|
[steam_rom] if steam_rom and steam_rom.get("steam_id") else []
|
|
)
|
|
elif search_by.lower() == "name":
|
|
(
|
|
igdb_matched_roms,
|
|
moby_matched_roms,
|
|
ss_matched_roms,
|
|
flashpoint_matched_roms,
|
|
launchbox_matched_roms,
|
|
demozoo_matched_roms,
|
|
steam_matched_roms,
|
|
) = _resolved(
|
|
await asyncio.gather(
|
|
meta_igdb_handler.get_matched_roms_by_name(
|
|
rom, search_term, get_main_platform_igdb_id(rom.platform)
|
|
),
|
|
meta_moby_handler.get_matched_roms_by_name(
|
|
search_term, rom.platform.moby_id
|
|
),
|
|
meta_ss_handler.get_matched_roms_by_name(
|
|
rom, search_term, rom.platform.ss_id
|
|
),
|
|
meta_flashpoint_handler.get_matched_roms_by_name(
|
|
search_term, rom.platform.slug
|
|
),
|
|
meta_launchbox_handler.get_matched_roms_by_name(
|
|
search_term, rom.platform.slug
|
|
),
|
|
meta_demozoo_handler.get_matched_roms_by_name(
|
|
search_term, rom.platform.slug
|
|
),
|
|
meta_steam_handler.get_matched_roms_by_name(
|
|
search_term, rom.platform.slug
|
|
),
|
|
return_exceptions=True,
|
|
),
|
|
_NAME_SEARCH_PROVIDERS,
|
|
list,
|
|
)
|
|
|
|
merged_dict: dict[str, dict] = {}
|
|
|
|
source_configs = {
|
|
MetadataSource.IGDB: (
|
|
igdb_matched_roms,
|
|
meta_igdb_handler,
|
|
"igdb_id",
|
|
"igdb_url_cover",
|
|
),
|
|
MetadataSource.MOBY: (
|
|
moby_matched_roms,
|
|
meta_moby_handler,
|
|
"moby_id",
|
|
"moby_url_cover",
|
|
),
|
|
MetadataSource.FLASHPOINT: (
|
|
flashpoint_matched_roms,
|
|
meta_flashpoint_handler,
|
|
"flashpoint_id",
|
|
"flashpoint_url_cover",
|
|
),
|
|
MetadataSource.LAUNCHBOX: (
|
|
launchbox_matched_roms,
|
|
meta_launchbox_handler,
|
|
"launchbox_id",
|
|
"launchbox_url_cover",
|
|
),
|
|
MetadataSource.SS: (ss_matched_roms, meta_ss_handler, "ss_id", "ss_url_cover"),
|
|
MetadataSource.DEMOZOO: (
|
|
demozoo_matched_roms,
|
|
meta_demozoo_handler,
|
|
"demozoo_id",
|
|
"demozoo_url_cover",
|
|
),
|
|
MetadataSource.STEAM: (
|
|
steam_matched_roms,
|
|
meta_steam_handler,
|
|
"steam_id",
|
|
"steam_url_cover",
|
|
),
|
|
}
|
|
|
|
ordered_sources = get_priority_ordered_metadata_sources(
|
|
metadata_sources=list(source_configs.keys()), priority_type="metadata"
|
|
)
|
|
|
|
for meta_source in ordered_sources:
|
|
source_matched_roms, meta_handler, id_key, cover_key = source_configs[
|
|
meta_source
|
|
]
|
|
for source_rom in source_matched_roms: # trunk-ignore(mypy/attr-defined)
|
|
if source_rom[id_key]:
|
|
normalized_name = meta_handler.normalize_search_term(
|
|
source_rom.get("name", ""),
|
|
remove_articles=False,
|
|
)
|
|
merged_dict[normalized_name] = {
|
|
**source_rom,
|
|
"is_identified": True,
|
|
"is_unidentified": False,
|
|
"platform_id": rom.platform_id,
|
|
cover_key: source_rom.get("url_cover", ""),
|
|
**merged_dict.get(normalized_name, {}),
|
|
}
|
|
|
|
async def get_sgdb_rom(name: str) -> tuple[str, SGDBRom]:
|
|
return name, await meta_sgdb_handler.get_details_by_names([name])
|
|
|
|
async def get_libretro_rom(name: str) -> tuple[str, LibretroRom]:
|
|
return name, await meta_libretro_handler.get_rom(name, rom.platform.slug)
|
|
|
|
# These two only add cover art to matches the other providers already
|
|
# produced, so an unreachable one costs a thumbnail rather than the results.
|
|
merged_names = list(merged_dict.keys())
|
|
sgdb_roms, libretro_roms = await asyncio.gather(
|
|
asyncio.gather(
|
|
*[get_sgdb_rom(name) for name in merged_names], return_exceptions=True
|
|
),
|
|
asyncio.gather(
|
|
*[get_libretro_rom(name) for name in merged_names], return_exceptions=True
|
|
),
|
|
)
|
|
|
|
for name, sgdb_rom in _without_failures(sgdb_roms, "SteamGridDB"):
|
|
if sgdb_rom["sgdb_id"]:
|
|
merged_dict[name] = {
|
|
**merged_dict[name],
|
|
"sgdb_id": sgdb_rom.get("sgdb_id", ""),
|
|
"sgdb_url_cover": sgdb_rom.get("url_cover", ""),
|
|
}
|
|
|
|
for name, libretro_rom in _without_failures(libretro_roms, "Libretro"):
|
|
if libretro_rom["libretro_id"]:
|
|
merged_dict[name] = {
|
|
**merged_dict[name],
|
|
"libretro_id": libretro_rom.get("libretro_id", ""),
|
|
"libretro_url_cover": libretro_rom.get("url_cover", ""),
|
|
}
|
|
|
|
matched_roms: list = list(merged_dict.values())
|
|
|
|
log.info("Results:")
|
|
for m_rom in matched_roms:
|
|
log.info(f"\t - {m_rom['name']}")
|
|
|
|
return matched_roms
|
|
|
|
|
|
@protected_route(router.get, "/cover", [Scope.ROMS_READ])
|
|
async def search_cover(
|
|
request: Request,
|
|
search_term: str = "",
|
|
) -> list[SearchCoverSchema]:
|
|
"""Search the cover art providers, in the configured cover priority order."""
|
|
if not meta_sgdb_handler.is_enabled() and not meta_steam_handler.is_enabled():
|
|
log.error("Search error: No cover art providers enabled")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail="No cover art providers enabled",
|
|
)
|
|
|
|
lookups = {
|
|
MetadataSource.SGDB: meta_sgdb_handler.get_details(search_term=search_term),
|
|
MetadataSource.STEAM: meta_steam_handler.get_details(search_term=search_term),
|
|
}
|
|
gathered = await asyncio.gather(*lookups.values(), return_exceptions=True)
|
|
fetched: dict[MetadataSource, list[CoverResult] | BaseException] = dict(
|
|
zip(lookups, gathered, strict=True)
|
|
)
|
|
|
|
# A rejected key is the user's to fix, so it is reported rather than
|
|
# costing the SteamGridDB covers silently.
|
|
sgdb_result = fetched[MetadataSource.SGDB]
|
|
if (
|
|
isinstance(sgdb_result, HTTPException)
|
|
and sgdb_result.status_code == status.HTTP_401_UNAUTHORIZED
|
|
):
|
|
raise sgdb_result
|
|
|
|
ordered_sources = get_priority_ordered_metadata_sources(
|
|
metadata_sources=list(lookups.keys()), priority_type="url_cover"
|
|
)
|
|
covers: list[SearchCoverSchema] = []
|
|
for source in ordered_sources:
|
|
results = fetched[source]
|
|
if isinstance(results, BaseException):
|
|
log.error("Error fetching %s covers: %s", source.value, results)
|
|
continue
|
|
covers.extend(
|
|
SearchCoverSchema.model_validate({"provider": source.value, **cover})
|
|
for cover in results
|
|
)
|
|
|
|
return covers
|