mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 10:32:57 +01:00
* chore(mypy): switch to strict mode with listed exceptions Replace the hand-picked flags with `strict = True`, turning off only the four flags that aren't clean yet (disallow_any_generics, warn_return_any, disallow_untyped_calls, disallow_untyped_decorators). Any other strict flag, including those future mypy releases add to the preset, is on by default. That turns on no_implicit_reexport, strict_equality and extra_checks: - Import each name from the module that defines it. About 240 test sites patched a dependency through the module that imported it (`scan_module.fs_rom_handler`); they now import the same object from its source, so every patch targets what it did before. Tests that replace a module attribute are unchanged. - handler.streaming.memory_cards re-exports store_memory_card_version explicitly, since endpoints call it there and tests patch it there. - mutagen gets implicit_reexport, as it re-exports without __all__. - Test comparisons build typed values (CoverResult, a typed expected dict, enum .value) and the CORS lookup casts for its identity check. - One ss_handler ** spread keeps a coded ignore: extra_checks wants its NotRequired dump_* keys spelled out, and the media dict never has them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G * chore(mypy): give every generic its type arguments Drop disallow_any_generics from the strict-mode exceptions and fix the 347 bare generics it reports, 230 of them in app code. - Bare `dict` becomes `dict[str, Any]`: update payloads, raw provider JSON and endpoint bodies map string keys to mixed values, so the Any is real and now written down. The OpenAPI document is unchanged. - Rom query filters take and return RomSelect; _music_facet_joins and _exclude_hidden are generic over the Select they're given, and _build_hash_selects returns id-only selects. - Redis clients are typed by what they return: the decoding caches are Redis[str], the RQ connection and binary cache Redis[bytes]. - The rest get explicit parameters: Row, Pattern, ColumnElement, QueryableAttribute, SpooledTemporaryFile, Task, Future and friends. Precise types reached callers that had been getting Any, which surfaced: - The LaunchBox cache writer is fed binary-cache pipelines. - The flashpoint and IGDB request helpers return raw JSON of varying shape, not always a dict. - The rom search endpoint returned dicts under a list[SearchRomSchema] annotation; it now validates them into that schema. - The audit filter's id subquery selects strings. - In tests the binary cache is the non-decoding fake shared with async_cache, so it is cast to Redis[bytes] rather than changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G * test(upload): assert cleanup against the patched upload directory The 409 test checked config's ROM_UPLOAD_TMP_BASE while the fixture patches the endpoint's copy to tmp_path/uploads, so it passed even if cleanup failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G * chore(mypy): keep the row type through the ROM filter helpers filter_roms and its helpers also receive select(Rom.id) membership queries, so they now take and return the caller's Select type instead of narrowing to RomSelect. merged_ra_metadata mixes scalar and list values. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
393 lines
14 KiB
Python
393 lines
14 KiB
Python
import asyncio
|
|
from collections.abc import Callable, Mapping, 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, MetadataHandler
|
|
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[str, Any]] = {}
|
|
|
|
source_configs: dict[
|
|
MetadataSource, tuple[Sequence[Mapping[str, Any]], MetadataHandler, str, str]
|
|
] = {
|
|
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:
|
|
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(merged_dict.values())
|
|
|
|
log.info("Results:")
|
|
for m_rom in matched_roms:
|
|
log.info(f"\t - {m_rom['name']}")
|
|
|
|
return [SearchRomSchema.model_validate(m_rom) for m_rom in 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
|