mirror of
https://github.com/rommapp/romm.git
synced 2026-12-04 12:52:19 +01:00
* fix(scan): delete screenshots and media a rescan leaves unreferenced A complete rescan keeps the stored artwork, so two kinds of file stayed on disk with nothing pointing at them: - screenshots indexed past a shorter new list, since files are named by position and only the indexes in range were rewritten - media of a type removed from the preferences, since providers record no path for it and stale media was compared over the preferred types only get_rom_screenshots now deletes the indexes past the new list, and remove_stale_media compares every media type. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(scan): split scan_rom's merge into named steps scan_rom held seeding the row, following Demozoo links, splicing scene summaries, resetting rematched sources, the scene lock, rehash cleanup, priority merges for fields, tags and artwork, and the SteamGridDB pass in one body. Each step is now its own helper, the SteamGridDB lookup a _RomLookups method, and the providers' answers a dict keyed by source instead of fourteen locals. The Pouet and CSDb link follows share one helper. Behaviour is unchanged. McCabe complexity of scan_rom goes from 68 to 13, and the function from 664 to 215 lines. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(scan): trim remove_stale_media's docstring per Greptile review Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(scan): move the scan vocabulary, lookups and merge into handler/scan scan_handler.py held the scan types and metadata sources, the per-source lookups, the merge of their answers and the orchestration in one 2,000-line module. It now builds on a handler/scan package: - sources.py: ScanType, MetadataSource, the tag constants, RESCAN_RULES, should_consult, stored_match_id and the priority ordering - lookups.py: RomLookups, the LaunchBox and Steam resolvers and get_main_platform_igdb_id - merge.py: the pure steps that merge the sources' answers into a rom's columns scan_handler.py keeps scan_platform, scan_rom, the asset scans and the media downloads. Importers point at the module that now defines each name, and the helpers that crossed a module boundary lost their leading underscore. clear_rehash_misses takes the attempted sources instead of the lookups, so merge does not depend on lookups. Behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(ci): import ScanType from handler.scan.sources in the e2e seed script Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(scan): harden leftover screenshot cleanup (pr-ready: code-review) List the screenshots folder once, use isdecimal() for the index test, and log rather than raise when a leftover can't be removed. Point three comments at handler/scan instead of scan_handler. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(scan): tidy the merge helpers and patch paths (pr-ready: simplify) - fetch_sgdb_rom refetches by stored_id and builds the SGDB name list itself, so the name sources stay private to lookups. - follow_demozoo_link checks the source is enabled; scan_rom loops over Pouët and CSDb. - order_merge_sources holds the one ordering pass, and build_metadata_handlers adds the empty SGDB entry. - Leftover screenshots go through the quiet-delete helper, renamed _discard_file. - Tests patch rom lookups through handler.scan.lookups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(scan): never leave a recorded media or screenshot path without its file - remove_stale_media only deletes a file whose owner or source changed when that new owner stores the type again in this pass. A file nothing records is still deleted. - Screenshots past a shorter list are pruned by remove_screenshots_past once the new paths are saved, in both download_rom_resources and update_rom, so a failed cover or manual leaves them in place. - The release-notes schema diff watches scan_handler.py beside scan/sources.py, for ranges that span the move. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
388 lines
14 KiB
Python
388 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_rom_visibility_filter
|
|
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.lookups import get_main_platform_igdb_id
|
|
from handler.scan.sources import MetadataSource, 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 not get_rom_visibility_filter(request).allows(rom):
|
|
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
|