mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 10:32:57 +01:00
* fix(backend): make type ignores match what mypy reports Third in the staged series clearing the errors #4655 made visible. Whole-project mypy: 91 errors in 26 files -> 64 in 23. Twenty `# type: ignore[assignment]` comments in endpoints/responses/rom.py never suppressed anything. The request-scoped values `from_orm_with_request` attaches to a Rom (rom_user, has_notes, user_saves and the rest) are not declared on the model, so mypy reports `attr-defined`; it does so under 1.19 as well as 2.3, so the code was wrong when the comments were written rather than drifting since. They now name the error they were meant to silence. Seventy-nine ignores across 24 files suppressed nothing at all under `--warn-unused-ignores`, and are removed. One of them, `utils/zip_cache.py`, keeps its `attr-defined` code for the private `zipfile._get_compressor` and drops only `assignment`. The unused set is identical under mypy 2.3.0 and 2.3.1, and removing them leaves the error count unchanged under both, so none was quietly needed. The two `filter` helpers typed as `[QueryT: Select | Update | Delete]` bound the TypeVar to the union, so `query.filter(...)` returned the union and could not be assigned back to `QueryT`. Constraining it to the three types lets mypy check each one separately, and the callers are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp * fix(backend): replace mypy and ASYNC240 trunk-ignores with real fixes A `trunk-ignore` only suppresses when Trunk runs the linter. Plain mypy does not read them, so the 13 on mypy findings were all still errors to `mypy .` and would fail a whole-project check. Each now has a fix. endpoints/tasks.py: `common_data` was a plain dict literal unpacked into eight TypedDict constructors, so mypy saw `dict[str, Any]` and could not match its keys. It holds exactly the fields of BaseTaskStatusResponse and is now annotated as one, so the unpacking is checked. handler/metadata/gamelist_handler.py: both media maps were inferred as `dict[str, str]`, so indexing the TypedDict with their keys was unprovable. Their keys are now typed `GamelistMediaKey`, the Literal of the TypedDict's fields. A misspelt map key is now an error at the entry; before, only the index site could have noticed, and it was suppressed. handler/metadata/playmatch_handler.py: `attr` was a bare `str`. A TypeIs guard narrows it to the five lookup attributes, and the frozenset is derived from that Literal so the names live in one place. mypy now checks that each name is a real PlaymatchRomMatch key. It does not check that each takes an int, since mypy is lenient about value types on a union key; that still rests on which five names are listed. endpoints/search.py: the per-source tuples mixed ROM-list and handler types, which mypy joined to `object`. The dict is now annotated with what the loop uses: Mapping rows and the MetadataHandler base. tests/handler/metadata/test_launchbox_handler.py: `Path.stat()` inside an async test (ASYNC240) now goes through `anyio.Path`, as the rest of the codebase already does. Whole-project mypy: 64 errors in 23 files -> 51 in 20, identical under 2.3.0 and 2.3.1. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp * fix(backend): keep gamelist media keys in one place Review pointed out that `GamelistMediaKey` repeated all fourteen fields of GamelistMetadataMedia. Python has no `keyof`, so any Literal of a TypedDict's keys is a second declaration of them, and a field added to the TypedDict would be left out of it without any error. The three index sites go back to suppressing `literal-required`, now as `# type: ignore[literal-required]` so plain mypy reads it as well as Trunk. The TypedDict stays the only declaration of the key set. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp --------- 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] = {}
|
|
|
|
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 = 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
|