Files
romm/backend/handler/metadata/playmatch_handler.py
Georges-Antoine Assi b35eb4d07c fix(scan): clean up unreferenced rescan media, split scan_rom and move its parts into handler/scan (#5408)
* 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>
2026-10-30 15:23:13 -04:00

335 lines
12 KiB
Python

import asyncio
import json
from collections.abc import Iterable
from enum import Enum
from typing import Any, Final, Literal, TypedDict, TypeIs, get_args
import httpx2
import yarl
from fastapi import status
from adapters.services.provider_http import unavailable
from adapters.services.response_validation import parse_response
from config import PLAYMATCH_API_ENABLED, PLAYMATCH_API_URL
from handler.metadata.base_handler import HTTPX_REQUEST_ERRORS, MetadataHandler
from logger.logger import log
from models.rom import Rom, RomFile
from utils import get_version
from utils.context import ctx_httpx_client
from utils.rate_limiter import RateLimiter
# Playmatch caps clients at 4 req/s per IP
PLAYMATCH_MAX_REQUESTS_PER_SECOND: Final[float] = 4
PLAYMATCH_MAX_REQUEST_ATTEMPTS: Final[int] = 2
_rate_limiter = RateLimiter(PLAYMATCH_MAX_REQUESTS_PER_SECOND)
# Tag is the uppercased Playmatch MetadataProvider name.
# Playmatch parses it case-insensitively but spacing must match.
# Tags Playmatch doesn't yet know are kept so older RomM clients keep
# submitting the right tag once Playmatch adds support.
PLAYMATCH_TAG_TO_ATTR: Final[dict[str, str]] = {
"IGDB": "igdb_id",
"MOBYGAMES": "moby_id",
"SCREENSCRAPER": "ss_id",
"RETRO_ACHIEVEMENTS": "ra_id",
"LAUNCHBOX": "launchbox_id",
"HASHEOUS": "hasheous_id",
"TGDB": "tgdb_id",
"FLASHPOINT": "flashpoint_id",
"HOWLONGTOBEAT": "hltb_id",
"LIBRETRO": "libretro_id",
"STEAMGRIDDB": "sgdb_id",
"GAMELIST": "gamelist_id",
}
# Rom attrs the scan handler actually consumes from a Playmatch lookup.
# Other tags exist only for outbound suggestions.
PlaymatchLookupAttr = Literal["igdb_id", "moby_id", "ss_id", "launchbox_id", "sgdb_id"]
PLAYMATCH_LOOKUP_ROM_ATTRS: Final = frozenset(get_args(PlaymatchLookupAttr))
def _is_lookup_attr(attr: str | None) -> TypeIs[PlaymatchLookupAttr]:
return attr in PLAYMATCH_LOOKUP_ROM_ATTRS
# MetadataSource values (StrEnum) for which Playmatch can return ids. Typed as
# strings so this module stays free of handler.scan imports. EmuReady and
# OpenVGDB are in Playmatch's enum but have no RomM counterpart yet.
PLAYMATCH_SUPPORTED_SOURCES: frozenset[str] = frozenset(
{"igdb", "moby", "ss", "launchbox", "sgdb"}
)
def _select_lookup_file(files: Iterable[RomFile]) -> RomFile | None:
"""The single file a ROM is identified by: the biggest top-level one, which
is how Hasheous and ScreenScraper choose theirs.
Equally sized files break the tie on path, so a two-disc set resolves to
disc 1. The scanner walks the filesystem unsorted, so without that two
machines scanning the same library ask about different files.
"""
return min(
(file for file in files if file.file_size_bytes > 0 and file.is_top_level),
key=lambda file: (-file.file_size_bytes, file.full_path),
default=None,
)
class GameMatchType(str, Enum):
SHA256 = "SHA256"
SHA1 = "SHA1"
MD5 = "MD5"
CRC = "CRC"
FILE_NAME_AND_SIZE = "FileNameAndSize"
NO_MATCH = "NoMatch"
class PlaymatchRomMatch(TypedDict):
igdb_id: int | None
moby_id: int | None
ss_id: int | None
launchbox_id: int | None
sgdb_id: int | None
ra_id: int | None
hasheous_id: int | None
tgdb_id: int | None
flashpoint_id: str | None
hltb_id: int | None
gamelist_id: str | None
libretro_id: str | None
class PlaymatchHandler(MetadataHandler):
"""
Handler for [Playmatch](https://github.com/RetroRealm/playmatch), a service for matching ROMs by Hashes.
"""
def __init__(self) -> None:
self.base_url = PLAYMATCH_API_URL
self.identify_url = f"{self.base_url}/identify/ids"
self.healthcheck_url = f"{self.base_url}/health"
self.suggestion_url = f"{self.base_url}/suggestion/external/game"
@classmethod
def is_enabled(cls) -> bool:
return PLAYMATCH_API_ENABLED
async def heartbeat(self) -> bool:
async def probe() -> bool:
await _rate_limiter.acquire()
# /health answers plain text ("Healthy"), so any 2xx means it is up.
res = await ctx_httpx_client.get().get(
self.healthcheck_url,
headers={"user-agent": f"RomM/{get_version()}"},
timeout=60,
)
res.raise_for_status()
return True
return await self._heartbeat("Playmatch API", probe)
async def _request(self, url: str, query: dict[str, Any]) -> dict[str, Any]:
"""
Sends a Request to Playmatch API.
:param url: The API endpoint URL.
:param query: A dictionary containing the query parameters.
:return: A dictionary with the json result.
:raises HTTPException: If the request fails or the service is unavailable.
"""
httpx_client = ctx_httpx_client.get()
filtered_query = {
key: value
for key, value in query.items()
if value is not None and value != "" # drop None and ""
}
url_with_query = yarl.URL(url).update_query(filtered_query)
log.debug(
"API request: URL=%s, Timeout=%s",
url_with_query,
60,
)
headers = {"user-agent": f"RomM/{get_version()}"}
for attempt in range(PLAYMATCH_MAX_REQUEST_ATTEMPTS):
await _rate_limiter.acquire()
try:
res = await httpx_client.get(
str(url_with_query), headers=headers, timeout=60
)
res.raise_for_status()
return (
parse_response(dict[str, Any], res.content, source="Playmatch")
or {}
)
except HTTPX_REQUEST_ERRORS as exc:
if (
attempt == 0
and isinstance(exc, httpx2.HTTPStatusError)
and exc.response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
):
log.warning("Playmatch: rate limit hit, retrying after 2s")
await asyncio.sleep(2)
continue
log.warning(
"Connection error: can't connect to Playmatch", exc_info=True
)
raise unavailable("Playmatch") from exc
except json.JSONDecodeError as exc:
log.error("Error decoding JSON response from Playmatch: %s", exc)
return {}
return {}
async def lookup_rom(self, files: list[RomFile]) -> PlaymatchRomMatch:
"""
Identify a ROM file using Playmatch API.
:param rom_attrs: A dictionary containing the ROM attributes.
:return: A PlaymatchRomMatch with the matched IDs, or an empty match if the
lookup fails. Playmatch is best-effort and never raises to the caller.
"""
fallback_rom = PlaymatchRomMatch(
igdb_id=None,
moby_id=None,
ss_id=None,
launchbox_id=None,
sgdb_id=None,
ra_id=None,
hasheous_id=None,
tgdb_id=None,
flashpoint_id=None,
hltb_id=None,
gamelist_id=None,
libretro_id=None,
)
if not self.is_enabled():
return fallback_rom
match_file = _select_lookup_file(files)
if match_file is None:
return fallback_rom
hashes = match_file.lookup_hashes
# Folder ROM members carry generic names (a Wii U title's 00000005.app),
# so name and size alone match an unrelated game.
if not any(hashes) and match_file.full_path != match_file.rom.full_path:
log.debug(
"Skipping Playmatch lookup for %s: no hashes to identify it by",
match_file.full_path,
)
return fallback_rom
try:
response = await self._request(
self.identify_url,
{
"fileName": match_file.file_name,
"fileSize": match_file.file_size_bytes,
"md5": hashes.md5,
"sha1": hashes.sha1,
"crc": hashes.crc,
},
)
except Exception as exc:
# We silently fail if the service is unavailable as this should not block the rest of RomM.
log.warning("Playmatch lookup failed, skipping: %s", exc)
return fallback_rom
game_match_type = response.get("gameMatchType", None)
if game_match_type == GameMatchType.NO_MATCH:
log.debug("No match found for the provided ROM file.")
return fallback_rom
external_metadata = response.get("externalMetadata")
if not isinstance(external_metadata, list) or not external_metadata:
log.debug("No external metadata found for the matched ROM file.")
return fallback_rom
result = fallback_rom
for metadata in external_metadata:
if not isinstance(metadata, dict):
continue
provider_name = metadata.get("providerName", None)
provider_game_id = metadata.get("providerId", None)
if not isinstance(provider_name, str) or provider_game_id is None:
continue
attr = PLAYMATCH_TAG_TO_ATTR.get(provider_name.upper())
if not _is_lookup_attr(attr):
continue
try:
parsed_id = int(provider_game_id)
except TypeError, ValueError:
log.debug(
"Playmatch returned non-int ID for %s: %r",
provider_name,
provider_game_id,
)
continue
log.debug("Playmatch found %s match with id: %s", provider_name, parsed_id)
result[attr] = parsed_id
return result
@staticmethod
def is_manual_match(form_fields_set: set[str]) -> bool:
"""True if the submitted form contains any Playmatch-tracked provider id field."""
return any(attr in form_fields_set for attr in PLAYMATCH_TAG_TO_ATTR.values())
async def submit_manual_match_suggestion(self, rom: Rom) -> None:
"""
Fire-and-forget suggestion POST.
No-ops if disabled or no provider IDs are set.
"""
try:
if not self.is_enabled():
return
mappings = [
{"provider": tag, "providerId": str(getattr(rom, attr))}
for tag, attr in PLAYMATCH_TAG_TO_ATTR.items()
if getattr(rom, attr, None)
]
if not mappings:
return
# A suggestion writes a hash-to-game mapping into a public index.
# With no file to take one from, the ROM-level hash is a composite
# spanning every file or archive member, so there is nothing here
# worth contributing.
match_file = _select_lookup_file(rom.files)
if match_file is None:
return
hashes = match_file.lookup_hashes
payload = {
"md5": hashes.md5,
"sha1": hashes.sha1,
"sha256": None,
"fileName": match_file.file_name,
"fileSize": match_file.file_size_bytes,
"mappings": mappings,
}
httpx_client = ctx_httpx_client.get()
await _rate_limiter.acquire()
res = await httpx_client.post(
self.suggestion_url,
json=payload,
headers={"user-agent": f"RomM/{get_version()}"},
timeout=30,
)
res.raise_for_status()
except Exception:
log.debug("Playmatch match suggestion failed (ignored)", exc_info=True)