mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* fix(scan): fall back to filename name when only libretro matches Libretro matches by filename and supplies no name. On a complete scan or a newly added ROM that only libretro identifies, rom_attrs had no name, so the identified-as log raised KeyError and the scan result was discarded. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * fix(scan): keep a new rom's own name when libretro alone matches code-review (xhigh) pass. A physical game is created with the name the user typed, and the filename fallback would rebuild it from the sanitized fs_name ("Kingdom Hearts HD 2.5" -> "Kingdom Hearts HD 2"). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(scan): simplify the new-rom name fallback expression simplify pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(scan): clarify the name fallback comment humanizer pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
1978 lines
75 KiB
Python
1978 lines
75 KiB
Python
import asyncio
|
|
import enum
|
|
import functools
|
|
from collections.abc import Callable, Mapping
|
|
from typing import Any, Final, NotRequired, TypedDict
|
|
|
|
import socketio
|
|
|
|
from adapters.services.igdb import IGDB_PLATFORM_LIST
|
|
from adapters.services.screenscraper import ScreenScraperRateLimitError
|
|
from config.config_manager import config_manager as cm
|
|
from endpoints.responses.rom import SimpleRomSchema
|
|
from handler.database import db_platform_handler, db_rom_handler
|
|
from handler.filesystem import (
|
|
fs_asset_handler,
|
|
fs_firmware_handler,
|
|
fs_resource_handler,
|
|
fs_rom_handler,
|
|
)
|
|
from handler.filesystem.roms_handler import FSRom, build_empty_fs_rom
|
|
from handler.metadata import (
|
|
meta_csdb_handler,
|
|
meta_demozoo_handler,
|
|
meta_flashpoint_handler,
|
|
meta_gamelist_handler,
|
|
meta_hasheous_handler,
|
|
meta_hltb_handler,
|
|
meta_igdb_handler,
|
|
meta_launchbox_handler,
|
|
meta_libretro_handler,
|
|
meta_moby_handler,
|
|
meta_playmatch_handler,
|
|
meta_pouet_handler,
|
|
meta_ra_handler,
|
|
meta_sgdb_handler,
|
|
meta_ss_handler,
|
|
meta_steam_handler,
|
|
meta_tgdb_handler,
|
|
)
|
|
from handler.metadata.csdb_handler import CsdbRom
|
|
from handler.metadata.demozoo_handler import (
|
|
DemozooRom,
|
|
_append_unique,
|
|
splice_csdb_url,
|
|
splice_pouet_vote,
|
|
)
|
|
from handler.metadata.flashpoint_handler import FLASHPOINT_PLATFORM_LIST, FlashpointRom
|
|
from handler.metadata.gamelist_handler import GamelistRom
|
|
from handler.metadata.hasheous_handler import HASHEOUS_PLATFORM_LIST, HasheousRom
|
|
from handler.metadata.hltb_handler import HLTB_PLATFORM_LIST, HLTBRom
|
|
from handler.metadata.igdb_handler import IGDBRom
|
|
from handler.metadata.launchbox_handler.media import populate_rom_specific_paths
|
|
from handler.metadata.launchbox_handler.platforms import LAUNCHBOX_PLATFORM_LIST
|
|
from handler.metadata.launchbox_handler.types import LaunchboxRom
|
|
from handler.metadata.libretro_handler import LIBRETRO_PLATFORM_LIST, LibretroRom
|
|
from handler.metadata.moby_handler import MOBYGAMES_PLATFORM_LIST, MobyGamesRom
|
|
from handler.metadata.platform_names import resolve_platform_name
|
|
from handler.metadata.playmatch_handler import (
|
|
PLAYMATCH_SUPPORTED_SOURCES,
|
|
PlaymatchRomMatch,
|
|
)
|
|
from handler.metadata.pouet_handler import PouetRom
|
|
from handler.metadata.ra_handler import RA_PLATFORM_LIST, RAGameRom
|
|
from handler.metadata.sgdb_handler import SGDBRom
|
|
from handler.metadata.ss_handler import (
|
|
SCREENSAVER_PLATFORM_LIST,
|
|
ScreenScraperExhaustedError,
|
|
SSRom,
|
|
add_ss_auth_to_url,
|
|
get_preferred_media_types,
|
|
note_rate_limited_rom,
|
|
)
|
|
from handler.metadata.steam_handler import STEAM_PLATFORMS, SteamRom
|
|
from logger.formatter import BLUE, LIGHTYELLOW
|
|
from logger.formatter import highlight as hl
|
|
from logger.logger import log
|
|
from models.assets import MemoryCardVersion, Save, Screenshot, State
|
|
from models.firmware import Firmware
|
|
from models.platform import Platform
|
|
from models.rom import (
|
|
METADATA_SOURCE_COLUMNS,
|
|
PROVIDER_METADATA_COLUMNS,
|
|
Rom,
|
|
RomFile,
|
|
RomFileCategory,
|
|
RomIdentity,
|
|
)
|
|
from models.user import User
|
|
from utils import emoji
|
|
from utils.audio_tags import persist_embedded_cover, remove_persisted_cover
|
|
from utils.concurrency import gather_all
|
|
from utils.filesystem import sanitize_filename
|
|
from utils.platform_aliases import (
|
|
resolve_fs_folder,
|
|
resolve_fs_slug,
|
|
resolve_platform_slug,
|
|
)
|
|
|
|
LOGGER_MODULE_NAME = {"module_name": "scan"}
|
|
|
|
|
|
@enum.unique
|
|
class ScanType(enum.StrEnum):
|
|
NEW_PLATFORMS = "new_platforms"
|
|
QUICK = "quick"
|
|
UPDATE = "update"
|
|
UNMATCHED = "unmatched"
|
|
COMPLETE = "complete"
|
|
HASHES = "hashes"
|
|
|
|
|
|
@enum.unique
|
|
class MetadataSource(enum.StrEnum):
|
|
IGDB = "igdb" # IGDB
|
|
MOBY = "moby" # MobyGames
|
|
SS = "ss" # Screenscraper
|
|
RA = "ra" # RetroAchievements
|
|
LAUNCHBOX = "launchbox" # Launchbox
|
|
HASHEOUS = "hasheous" # Hasheous
|
|
TGDB = "tgdb" # TheGamesDB
|
|
SGDB = "sgdb" # SteamGridDB
|
|
FLASHPOINT = "flashpoint" # Flashpoint Project
|
|
HLTB = "hltb" # HowLongToBeat
|
|
DEMOZOO = "demozoo" # Demozoo
|
|
POUET = "pouet" # Pouët
|
|
CSDB = "csdb" # CSDb (C64)
|
|
STEAM = "steam" # Steam storefront
|
|
GAMELIST = "gamelist" # ES-DE gamelist.xml
|
|
LIBRETRO = "libretro" # Libretro thumbnails
|
|
PLAYMATCH = "playmatch" # Playmatch
|
|
|
|
|
|
# Demozoo / Pouët identify a production, not a retail game. Game catalogs
|
|
# (IGDB, Moby, ScreenScraper, SteamGridDB, …) still run and will happily
|
|
# attach a similarly titled box: "Desert Dream" → Desert Fox, "State of
|
|
# the Art" → a skate game. Once a scene ID exists, only Demozoo / Pouët /
|
|
# CSDb may set name, summary, or artwork. Regular games never have those
|
|
# IDs, so they keep the usual fuzzy cover matching.
|
|
SCENE_METADATA_SOURCES = frozenset(
|
|
{MetadataSource.DEMOZOO, MetadataSource.POUET, MetadataSource.CSDB}
|
|
)
|
|
|
|
# Sources that report the dump a hash matched rather than the title. Their tags
|
|
# fill an empty slot only: a filename and a gamelist.xml are curated with the
|
|
# library, so they own these fields and the locale pickers read them back.
|
|
HASH_MATCHED_TAG_SOURCES = frozenset({MetadataSource.SS, MetadataSource.HASHEOUS})
|
|
PROVIDER_TAG_FIELDS = ("regions", "languages")
|
|
# Tags merge rather than fill: being a translation says nothing about being a
|
|
# revision, so a dump's tags join the filename's instead of replacing them.
|
|
PROVIDER_MERGED_TAG_FIELDS = ("tags",)
|
|
PROVIDER_ALL_TAG_FIELDS = PROVIDER_TAG_FIELDS + PROVIDER_MERGED_TAG_FIELDS
|
|
# Where a hash source's blob keeps each tag field its dump gave.
|
|
DUMP_TAG_KEYS = {field: f"dump_{field}" for field in PROVIDER_ALL_TAG_FIELDS}
|
|
|
|
|
|
def hash_source_tags(
|
|
fields: dict[str, Any], rom_attrs: dict[str, Any]
|
|
) -> tuple[dict[str, list[str]], bool]:
|
|
"""The tags a hash-matched source vouches for, and whether it said so this scan.
|
|
|
|
Args:
|
|
fields: The source's entry in the scan's handler table, its blob already
|
|
holding this scan's dump tags.
|
|
rom_attrs: The ROM's attributes, still holding its stored ids and blobs.
|
|
|
|
Returns:
|
|
Each tag field's values, empty when the source doesn't cover the ROM, and
|
|
whether they are this scan's answer rather than the stored one.
|
|
"""
|
|
handler = fields["handler"]
|
|
answered = bool(handler.get(fields["id_field"]))
|
|
if answered:
|
|
blob = handler.get(fields["metadata_field"]) or {}
|
|
elif rom_attrs.get(fields["id_field"]):
|
|
blob = rom_attrs.get(fields["metadata_field"]) or {}
|
|
else:
|
|
blob = {}
|
|
# A hand edit of the raw metadata can store any JSON; only lists of strings count.
|
|
if not isinstance(blob, dict):
|
|
blob = {}
|
|
claims = {}
|
|
for field in PROVIDER_ALL_TAG_FIELDS:
|
|
value = blob.get(DUMP_TAG_KEYS[field])
|
|
claims[field] = (
|
|
[tag for tag in value if isinstance(tag, str)]
|
|
if isinstance(value, list)
|
|
else []
|
|
)
|
|
return claims, answered
|
|
|
|
|
|
def scene_apply_sources(
|
|
available_sources: list[MetadataSource],
|
|
*,
|
|
scene_locked: bool = False,
|
|
) -> list[MetadataSource]:
|
|
"""Sources allowed to write identity and artwork for this ROM.
|
|
|
|
Scene-matched ROMs stay on Demozoo/Pouët/CSDb. Everything else is unchanged.
|
|
A ROM already carrying a scene id stays locked even when this scan's scene
|
|
lookup came back empty, so an unreachable provider can't hand a known
|
|
production back to the catalogs.
|
|
"""
|
|
scene = [source for source in available_sources if source in SCENE_METADATA_SOURCES]
|
|
if scene:
|
|
return scene
|
|
return [] if scene_locked else list(available_sources)
|
|
|
|
|
|
# Sentinel folder for manually-added physical games; it never exists on disk.
|
|
PHYSICAL_FS_SUBDIR = ".physical"
|
|
|
|
|
|
def build_physical_fs_path(platform: Platform) -> str:
|
|
"""Sentinel `fs_path` for a file-less physical game on the given platform."""
|
|
return (
|
|
f"{fs_rom_handler.get_roms_fs_structure(platform.fs_slug)}/{PHYSICAL_FS_SUBDIR}"
|
|
)
|
|
|
|
|
|
def build_physical_fs_name(name: str) -> str:
|
|
"""`fs_name` for a physical game: the sanitized name, with no fake extension.
|
|
|
|
Physical games all share one folder, so the unique index on
|
|
(platform_id, full_path_hash) rejects a second copy of the same title on a
|
|
platform, which is not a library a user can own anyway.
|
|
"""
|
|
return sanitize_filename(name)
|
|
|
|
|
|
def build_hashless_fs_rom(fs_name: str, fs_path: str, *, flat: bool) -> FSRom:
|
|
"""An `FSRom` for a rom with no filesystem listing to consult."""
|
|
return build_empty_fs_rom(fs_name, fs_path, flat=flat)
|
|
|
|
|
|
def fs_rom_file_attrs(fs_rom: FSRom) -> dict[str, Any]:
|
|
"""The hash, size and title id columns a listed `fs_rom` sets on its rom."""
|
|
if not fs_rom["files"]:
|
|
return {}
|
|
|
|
attrs: dict[str, Any] = {
|
|
"crc_hash": fs_rom["crc_hash"],
|
|
"md5_hash": fs_rom["md5_hash"],
|
|
"sha1_hash": fs_rom["sha1_hash"],
|
|
"ra_hash": fs_rom["ra_hash"],
|
|
"fs_size_bytes": sum(file.file_size_bytes for file in fs_rom["files"]),
|
|
}
|
|
# Only when extraction produced an id, so a hash-only or extraction-disabled
|
|
# rescan can't wipe the stored one.
|
|
identity = fs_rom.get("identity")
|
|
if identity and identity.title_id:
|
|
attrs.update(identity.as_rom_attrs())
|
|
return attrs
|
|
|
|
|
|
def get_main_platform_igdb_id(platform: Platform) -> int | None:
|
|
cnfg = cm.get_config()
|
|
|
|
main_platform_slug = cnfg.PLATFORMS_VERSIONS.get(platform.fs_slug.lower())
|
|
if main_platform_slug:
|
|
main_platform = db_platform_handler.get_platform_by_fs_slug(main_platform_slug)
|
|
if main_platform:
|
|
main_platform_igdb_id = main_platform.igdb_id
|
|
else:
|
|
igdb_platform = meta_igdb_handler.get_platform(main_platform_slug)
|
|
main_platform_igdb_id = igdb_platform["igdb_id"]
|
|
if not main_platform_igdb_id:
|
|
main_platform_igdb_id = platform.igdb_id
|
|
else:
|
|
main_platform_igdb_id = platform.igdb_id
|
|
return main_platform_igdb_id
|
|
|
|
|
|
def get_priority_ordered_metadata_sources(
|
|
metadata_sources: list[MetadataSource], priority_type: str = "metadata"
|
|
) -> list[MetadataSource]:
|
|
"""Get metadata sources ordered by priority from config
|
|
|
|
Args:
|
|
metadata_sources: List of available metadata sources
|
|
priority_type: Priority list to use: "metadata", "artwork", or an artwork
|
|
field name (e.g. "url_cover") that can carry a per-field override.
|
|
|
|
Returns:
|
|
List of metadata sources ordered by priority
|
|
"""
|
|
cnfg = cm.get_config()
|
|
|
|
if priority_type == "metadata":
|
|
priority_order = cnfg.SCAN_METADATA_PRIORITY
|
|
else:
|
|
# Per-field artwork overrides win, otherwise fall back to the shared
|
|
# artwork priority list.
|
|
priority_order = cnfg.SCAN_ARTWORK_PRIORITY_OVERRIDES.get(
|
|
priority_type, cnfg.SCAN_ARTWORK_PRIORITY
|
|
)
|
|
|
|
# Filter priority order to only include sources that are available. A
|
|
# source listed twice in config.yml keeps its first position.
|
|
ordered_sources = list(
|
|
dict.fromkeys(
|
|
MetadataSource(source)
|
|
for source in priority_order
|
|
if source in metadata_sources
|
|
)
|
|
)
|
|
|
|
# Add any remaining sources that weren't in the priority list
|
|
remaining_sources = [
|
|
MetadataSource(source)
|
|
for source in metadata_sources
|
|
if source not in ordered_sources
|
|
]
|
|
|
|
return ordered_sources + remaining_sources
|
|
|
|
|
|
def get_enabled_metadata_sources() -> list[str]:
|
|
"""The metadata sources a library scan can use, per their provider's config."""
|
|
handlers = {
|
|
MetadataSource.IGDB: meta_igdb_handler,
|
|
MetadataSource.SS: meta_ss_handler,
|
|
MetadataSource.MOBY: meta_moby_handler,
|
|
MetadataSource.RA: meta_ra_handler,
|
|
MetadataSource.LAUNCHBOX: meta_launchbox_handler,
|
|
MetadataSource.HASHEOUS: meta_hasheous_handler,
|
|
MetadataSource.PLAYMATCH: meta_playmatch_handler,
|
|
MetadataSource.SGDB: meta_sgdb_handler,
|
|
MetadataSource.FLASHPOINT: meta_flashpoint_handler,
|
|
MetadataSource.HLTB: meta_hltb_handler,
|
|
MetadataSource.DEMOZOO: meta_demozoo_handler,
|
|
MetadataSource.POUET: meta_pouet_handler,
|
|
MetadataSource.CSDB: meta_csdb_handler,
|
|
MetadataSource.STEAM: meta_steam_handler,
|
|
MetadataSource.TGDB: meta_tgdb_handler,
|
|
MetadataSource.LIBRETRO: meta_libretro_handler,
|
|
}
|
|
return [source for source, handler in handlers.items() if handler.is_enabled()]
|
|
|
|
|
|
def persist_soundtrack_cover(rom_file: RomFile, rom: Rom) -> None:
|
|
"""Persist a scanned soundtrack file's embedded cover and record its path on
|
|
the track_meta row. No-op for non-soundtrack files or ones without a cover."""
|
|
track_meta = rom_file.track_meta
|
|
if not (rom_file.category == RomFileCategory.SOUNDTRACK and track_meta):
|
|
return
|
|
|
|
if not track_meta.has_embedded_cover:
|
|
# The cover was stripped from the file since the last scan. Keep the
|
|
# path when the unlink fails, so the next scan retries it rather than
|
|
# stranding the file with nothing pointing at it.
|
|
if track_meta.cover_path and remove_persisted_cover(track_meta.cover_path):
|
|
db_rom_handler.upsert_track_meta(rom_file.id, rom.id, {"cover_path": None})
|
|
return
|
|
|
|
abs_audio_path = fs_rom_handler.validate_path(rom_file.full_path)
|
|
cover_path = persist_embedded_cover(
|
|
audio_full_path=str(abs_audio_path),
|
|
platform_id=rom.platform_id,
|
|
rom_id=rom.id,
|
|
file_id=rom_file.id,
|
|
)
|
|
if cover_path:
|
|
db_rom_handler.upsert_track_meta(
|
|
rom_file.id, rom.id, {"cover_path": cover_path}
|
|
)
|
|
else:
|
|
log.error(f"[audio_tags] cover persist failed for {abs_audio_path}")
|
|
db_rom_handler.upsert_track_meta(
|
|
rom_file.id, rom.id, {"has_embedded_cover": False}
|
|
)
|
|
|
|
|
|
async def scan_platform(
|
|
fs_slug: str,
|
|
fs_platforms: list[str],
|
|
) -> Platform:
|
|
"""Get platform details
|
|
|
|
Args:
|
|
fs_slug: short name of the platform
|
|
Returns
|
|
Platform object
|
|
"""
|
|
platform_attrs: dict[str, Any] = {}
|
|
platform_attrs["fs_slug"] = fs_slug
|
|
|
|
cnfg = cm.get_config()
|
|
|
|
# Sometimes users change the name of the folder, so we try to match it with the config
|
|
if fs_slug not in fs_platforms:
|
|
log.warning(
|
|
f"{hl(fs_slug)} not found in file system, trying to match via config",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
platform = db_platform_handler.get_platform_by_fs_slug(fs_slug)
|
|
if platform:
|
|
known_fs_slug = resolve_fs_slug(platform.slug, cnfg)
|
|
if known_fs_slug:
|
|
# `resolve_fs_slug` answers with a lowercased config key, but
|
|
# every path is built from the folder's own casing.
|
|
platform_attrs["fs_slug"] = (
|
|
resolve_fs_folder(known_fs_slug, fs_platforms) or known_fs_slug
|
|
)
|
|
|
|
platform_attrs["slug"] = resolve_platform_slug(fs_slug, cnfg)
|
|
|
|
igdb_platform = meta_igdb_handler.get_platform(platform_attrs["slug"])
|
|
moby_platform = meta_moby_handler.get_platform(platform_attrs["slug"])
|
|
ss_platform = meta_ss_handler.get_platform(platform_attrs["slug"])
|
|
ra_platform = meta_ra_handler.get_platform(platform_attrs["slug"])
|
|
launchbox_platform = meta_launchbox_handler.get_platform(platform_attrs["slug"])
|
|
hasheous_platform = meta_hasheous_handler.get_platform(platform_attrs["slug"])
|
|
tgdb_platform = meta_tgdb_handler.get_platform(platform_attrs["slug"])
|
|
flashpoint_platform = meta_flashpoint_handler.get_platform(platform_attrs["slug"])
|
|
hltb_platform = meta_hltb_handler.get_platform(platform_attrs["slug"])
|
|
libretro_platform = meta_libretro_handler.get_platform(platform_attrs["slug"])
|
|
|
|
platform_attrs["name"] = platform_attrs["slug"].replace("-", " ").title()
|
|
platform_attrs.update(
|
|
{
|
|
**libretro_platform,
|
|
**hltb_platform,
|
|
**flashpoint_platform,
|
|
**tgdb_platform,
|
|
**hasheous_platform,
|
|
**launchbox_platform,
|
|
**ra_platform,
|
|
**moby_platform,
|
|
**ss_platform,
|
|
**igdb_platform,
|
|
"igdb_id": igdb_platform.get("igdb_id")
|
|
or hasheous_platform.get("igdb_id")
|
|
or None,
|
|
"ra_id": ra_platform.get("ra_id") or hasheous_platform.get("ra_id") or None,
|
|
"tgdb_id": moby_platform.get("tgdb_id")
|
|
or hasheous_platform.get("tgdb_id")
|
|
or tgdb_platform.get("tgdb_id")
|
|
or None,
|
|
"name": resolve_platform_name(platform_attrs["slug"]),
|
|
"url_logo": igdb_platform.get("url_logo")
|
|
or tgdb_platform.get("url_logo")
|
|
or "",
|
|
}
|
|
)
|
|
|
|
platform_attrs["missing_from_fs"] = False
|
|
scanned_platform = Platform(**platform_attrs)
|
|
|
|
if scanned_platform.is_identified:
|
|
log.info(
|
|
f"Folder {hl(platform_attrs['slug'])}[{hl(fs_slug, color=LIGHTYELLOW)}] identified as {hl(platform_attrs['name'], color=BLUE)} {emoji.EMOJI_VIDEO_GAME}",
|
|
extra={"module_name": "scan"},
|
|
)
|
|
else:
|
|
log.warning(
|
|
f"Platform {hl(platform_attrs['slug'])} not identified {emoji.EMOJI_CROSS_MARK}",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
|
|
return scanned_platform
|
|
|
|
|
|
async def scan_firmware(
|
|
platform: Platform,
|
|
file_name: str,
|
|
firmware: Firmware | None = None,
|
|
) -> Firmware:
|
|
firmware_path = fs_firmware_handler.get_firmware_fs_structure(platform.fs_slug)
|
|
|
|
# Set default properties
|
|
firmware_attrs: dict[str, Any] = {
|
|
"id": firmware.id if firmware else None,
|
|
"platform_id": platform.id,
|
|
}
|
|
|
|
file_path = f"{firmware_path}/{file_name}"
|
|
file_size = await fs_firmware_handler.get_file_size(file_path)
|
|
|
|
firmware_attrs.update(
|
|
{
|
|
"file_path": firmware_path,
|
|
"file_name": file_name,
|
|
"file_size_bytes": file_size,
|
|
}
|
|
)
|
|
|
|
file_hashes = await fs_firmware_handler.calculate_file_hashes(
|
|
firmware_path=firmware_path,
|
|
file_name=file_name,
|
|
)
|
|
|
|
firmware_attrs.update(**file_hashes)
|
|
|
|
return Firmware(**firmware_attrs)
|
|
|
|
|
|
async def resolve_launchbox_rom(
|
|
*,
|
|
rom: Rom,
|
|
fs_name: str,
|
|
platform_slug: str,
|
|
scan_type: ScanType,
|
|
playmatch_rom: PlaymatchRomMatch,
|
|
remote_enabled: bool,
|
|
) -> LaunchboxRom:
|
|
"""Resolve a ROM's LaunchBox match, by ID where one is known, else by filename."""
|
|
# An ID already on the ROM is a decision (often a manual match), so it is
|
|
# never traded for a filename guess.
|
|
if (
|
|
remote_enabled
|
|
and rom.launchbox_id
|
|
and (
|
|
scan_type == ScanType.UPDATE
|
|
or (scan_type == ScanType.UNMATCHED and not rom.launchbox_metadata)
|
|
)
|
|
):
|
|
return await meta_launchbox_handler.get_rom_by_id(
|
|
rom.launchbox_id,
|
|
remote_enabled=True,
|
|
fs_name=fs_name,
|
|
platform_slug=platform_slug,
|
|
)
|
|
|
|
launchbox_rom = LaunchboxRom(launchbox_id=None)
|
|
|
|
if playmatch_rom["launchbox_id"] is not None and remote_enabled:
|
|
log.debug(
|
|
f"{hl(fs_name)} identified by Playmatch as LaunchBox "
|
|
f"{hl(str(playmatch_rom['launchbox_id']), color=BLUE)} {emoji.EMOJI_ALIEN_MONSTER}",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
launchbox_rom = await meta_launchbox_handler.get_rom_by_id(
|
|
playmatch_rom["launchbox_id"],
|
|
remote_enabled=True,
|
|
fs_name=fs_name,
|
|
platform_slug=platform_slug,
|
|
)
|
|
|
|
# Playmatch suggests an ID the metadata store may not hold, and on some
|
|
# platforms it answers for nearly every ROM. Letting that miss stand would
|
|
# strand the whole platform unmatched, so the filename lookup still runs.
|
|
if not launchbox_rom.get("launchbox_id"):
|
|
launchbox_rom = await meta_launchbox_handler.get_rom(
|
|
fs_name,
|
|
platform_slug,
|
|
remote_enabled=remote_enabled,
|
|
)
|
|
|
|
return launchbox_rom
|
|
|
|
|
|
async def resolve_steam_rom(
|
|
*,
|
|
rom: Rom,
|
|
fs_name: str,
|
|
platform_slug: str,
|
|
scan_type: ScanType,
|
|
) -> SteamRom:
|
|
"""Resolve a ROM's Steam match, by app ID where one is known, else by filename."""
|
|
# A stored app ID is often a manual match, so it is never traded for the
|
|
# filename search, which can land on any app above the similarity floor.
|
|
if rom.steam_id and (
|
|
scan_type == ScanType.UPDATE
|
|
or (scan_type == ScanType.UNMATCHED and not rom.steam_metadata)
|
|
):
|
|
return await meta_steam_handler.get_rom_by_id(rom.steam_id)
|
|
|
|
return await meta_steam_handler.get_rom(fs_name, platform_slug)
|
|
|
|
|
|
# `files` is left out so a scan does not ship every file row of every rom.
|
|
_SCANNING_ROM_EXCLUDE: Final = {
|
|
"created_at",
|
|
"updated_at",
|
|
"rom_user",
|
|
"last_modified",
|
|
"files",
|
|
"sibling_roms",
|
|
}
|
|
|
|
|
|
async def emit_scanning_rom(
|
|
socket_manager: socketio.AsyncRedisManager, rom: Rom, *, is_new: bool
|
|
) -> None:
|
|
"""Report a scanned rom; `is_new` lets clients count only roms the scan added."""
|
|
payload = SimpleRomSchema.from_orm_with_factory(rom).model_dump(
|
|
exclude=_SCANNING_ROM_EXCLUDE
|
|
)
|
|
payload["is_new"] = is_new
|
|
await socket_manager.emit("scan:scanning_rom", payload)
|
|
|
|
|
|
async def scan_rom(
|
|
scan_type: ScanType,
|
|
platform: Platform,
|
|
rom: Rom,
|
|
fs_rom: FSRom,
|
|
metadata_sources: list[str],
|
|
newly_added: bool,
|
|
launchbox_remote_enabled: bool = True,
|
|
socket_manager: socketio.AsyncRedisManager | None = None,
|
|
) -> Rom:
|
|
rom_attrs = {
|
|
"id": rom.id,
|
|
"platform_id": platform.id,
|
|
"fs_name": fs_rom["fs_name"],
|
|
"fs_path": rom.fs_path,
|
|
"regions": rom.regions,
|
|
"revision": rom.revision,
|
|
"version": rom.version,
|
|
"languages": rom.languages,
|
|
"tags": rom.tags,
|
|
"crc_hash": rom.crc_hash,
|
|
"md5_hash": rom.md5_hash,
|
|
"sha1_hash": rom.sha1_hash,
|
|
"ra_hash": rom.ra_hash,
|
|
**RomIdentity.from_rom(rom).as_rom_attrs(),
|
|
"fs_size_bytes": rom.fs_size_bytes,
|
|
"is_physical": rom.is_physical,
|
|
"upc": rom.upc,
|
|
}
|
|
|
|
file_attrs = fs_rom_file_attrs(fs_rom)
|
|
rom_attrs.update(file_attrs)
|
|
if file_attrs.get("title_id"):
|
|
# Metadata matching reads the id off the instance, so a rescan searches
|
|
# by what was just extracted rather than the stored value.
|
|
rom.title_id = file_attrs["title_id"]
|
|
|
|
# Update properties from existing rom if not a complete rescan
|
|
if not newly_added and scan_type != ScanType.COMPLETE:
|
|
rom_attrs.update(
|
|
{
|
|
"name": rom.name,
|
|
"name_sort_key": rom.name_sort_key,
|
|
"slug": rom.slug,
|
|
"summary": rom.summary,
|
|
"url_cover": rom.url_cover,
|
|
"url_screenshots": rom.url_screenshots,
|
|
"url_manual": rom.url_manual,
|
|
"path_cover_s": rom.path_cover_s,
|
|
"path_cover_l": rom.path_cover_l,
|
|
"path_screenshots": rom.path_screenshots,
|
|
"path_manual": rom.path_manual,
|
|
"locked_fields": rom.locked_fields,
|
|
"igdb_id": rom.igdb_id,
|
|
"moby_id": rom.moby_id,
|
|
"ss_id": rom.ss_id,
|
|
"sgdb_id": rom.sgdb_id,
|
|
"ra_id": rom.ra_id,
|
|
"launchbox_id": rom.launchbox_id,
|
|
"hasheous_id": rom.hasheous_id,
|
|
"tgdb_id": rom.tgdb_id,
|
|
"gamelist_id": rom.gamelist_id,
|
|
"flashpoint_id": rom.flashpoint_id,
|
|
"hltb_id": rom.hltb_id,
|
|
"demozoo_id": rom.demozoo_id,
|
|
"pouet_id": rom.pouet_id,
|
|
"csdb_id": rom.csdb_id,
|
|
"steam_id": rom.steam_id,
|
|
"libretro_id": rom.libretro_id,
|
|
**{c: getattr(rom, c) for c in PROVIDER_METADATA_COLUMNS},
|
|
}
|
|
)
|
|
|
|
is_complete_rescan = not newly_added and scan_type == ScanType.COMPLETE
|
|
|
|
# Sources whose lookup actually ran. One skipped because the platform carries
|
|
# no id for it never enters the set, so a rescan can't clear what it can't redo.
|
|
attempted_sources: set[MetadataSource] = set()
|
|
|
|
# Sources this scan asked and never got an answer from. A miss they did not
|
|
# rule out is not a coverage gap, so the outcome must not be reported as one.
|
|
inconclusive_sources: set[MetadataSource] = set()
|
|
|
|
def note_inconclusive(source: MetadataSource) -> None:
|
|
"""Record a source that was consulted and never answered."""
|
|
# It ruled nothing out, so it stops counting as attempted too and a
|
|
# complete rescan keeps the id it already had.
|
|
attempted_sources.discard(source)
|
|
inconclusive_sources.add(source)
|
|
|
|
def resolve_fetch(source: MetadataSource, result: Any, fallback: Any) -> Any:
|
|
"""Unwrap a gathered lookup, falling back to an empty match when it failed."""
|
|
if not isinstance(result, BaseException):
|
|
return result
|
|
if not isinstance(result, Exception):
|
|
raise result
|
|
|
|
note_inconclusive(source)
|
|
log.error(
|
|
f"Error fetching {hl(source)} metadata for {hl(rom_attrs['fs_name'])}: {result}",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
return fallback
|
|
|
|
@functools.cache
|
|
def get_match_files() -> list[RomFile]:
|
|
"""Files used for hash-based metadata matching, fetched at most once."""
|
|
return fs_rom["files"] or db_rom_handler.rom_files_for_rom_id(rom.id)
|
|
|
|
async def fetch_playmatch_hash_match() -> PlaymatchRomMatch:
|
|
if (
|
|
meta_playmatch_handler.is_enabled()
|
|
and MetadataSource.PLAYMATCH in metadata_sources
|
|
and any(PLAYMATCH_SUPPORTED_SOURCES.intersection(metadata_sources))
|
|
and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or scan_type == ScanType.UPDATE
|
|
or scan_type == ScanType.UNMATCHED
|
|
)
|
|
):
|
|
return await meta_playmatch_handler.lookup_rom(get_match_files())
|
|
|
|
return 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,
|
|
libretro_id=None,
|
|
gamelist_id=None,
|
|
)
|
|
|
|
async def fetch_hasheous_hash_match() -> tuple[HasheousRom, bool]:
|
|
if (
|
|
MetadataSource.HASHEOUS in metadata_sources
|
|
and platform.hasheous_id
|
|
and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or scan_type == ScanType.HASHES
|
|
or (scan_type == ScanType.UPDATE and rom.hasheous_id)
|
|
or (
|
|
scan_type == ScanType.UNMATCHED
|
|
and (not rom.hasheous_id or not rom.hasheous_metadata)
|
|
and rom.platform_slug in HASHEOUS_PLATFORM_LIST
|
|
)
|
|
)
|
|
):
|
|
match, conclusive = await meta_hasheous_handler.lookup_rom(
|
|
platform.slug, get_match_files()
|
|
)
|
|
# Hasheous swallows its own failures, so an empty match that is not
|
|
# conclusive is the only sign the lookup never got an answer. A
|
|
# disabled handler reports the same flag without being consulted.
|
|
if not conclusive and meta_hasheous_handler.is_enabled():
|
|
note_inconclusive(MetadataSource.HASHEOUS)
|
|
return match, conclusive
|
|
|
|
return (
|
|
HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None),
|
|
False,
|
|
)
|
|
|
|
# A new rom is already the reloaded row its caller inserted. An existing one
|
|
# is written so its rescanned columns land before identification.
|
|
scanning_rom = rom if newly_added else db_rom_handler.add_rom(Rom(**rom_attrs))
|
|
scanning_rom.is_identifying = True
|
|
|
|
if socket_manager:
|
|
await emit_scanning_rom(socket_manager, scanning_rom, is_new=newly_added)
|
|
|
|
# Run hash fetches concurrently
|
|
(
|
|
playmatch_hash_match,
|
|
(hasheous_hash_match, hasheous_lookup_conclusive),
|
|
) = await asyncio.gather(
|
|
fetch_playmatch_hash_match(),
|
|
fetch_hasheous_hash_match(),
|
|
)
|
|
|
|
async def fetch_igdb_rom(
|
|
playmatch_rom: PlaymatchRomMatch, hasheous_rom: HasheousRom
|
|
) -> IGDBRom:
|
|
if (
|
|
MetadataSource.IGDB in metadata_sources
|
|
and platform.igdb_id
|
|
and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or (scan_type == ScanType.UPDATE and rom.igdb_id)
|
|
or (
|
|
scan_type == ScanType.UNMATCHED
|
|
and (not rom.igdb_id or not rom.igdb_metadata)
|
|
and rom.platform_slug in IGDB_PLATFORM_LIST
|
|
)
|
|
)
|
|
):
|
|
attempted_sources.add(MetadataSource.IGDB)
|
|
# Use Hasheous match to get the IGDB ID
|
|
h_igdb_id = hasheous_rom.get("igdb_id")
|
|
if h_igdb_id:
|
|
log.debug(
|
|
f"{hl(rom_attrs['fs_name'])} identified by Hasheous as "
|
|
f"{hl(str(h_igdb_id), color=BLUE)} {emoji.EMOJI_ALIEN_MONSTER}",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
return await meta_igdb_handler.get_rom_by_id(rom, h_igdb_id)
|
|
|
|
# Use Playmatch matches to get the IGDB ID
|
|
if playmatch_rom["igdb_id"] is not None:
|
|
log.debug(
|
|
f"{hl(rom_attrs['fs_name'])} identified by Playmatch as "
|
|
f"{hl(str(playmatch_rom['igdb_id']), color=BLUE)} {emoji.EMOJI_ALIEN_MONSTER}",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
|
|
return await meta_igdb_handler.get_rom_by_id(
|
|
rom, playmatch_rom["igdb_id"]
|
|
)
|
|
|
|
main_platform_igdb_id = get_main_platform_igdb_id(platform)
|
|
if scan_type == ScanType.UPDATE and rom.igdb_id:
|
|
# Use the ID to refetch the metadata from IGDB
|
|
return await meta_igdb_handler.get_rom_by_id(rom, rom.igdb_id)
|
|
else:
|
|
# If no matches found, use the file name to get the IGDB ID
|
|
return await meta_igdb_handler.get_rom(
|
|
rom,
|
|
rom_attrs["fs_name"],
|
|
main_platform_igdb_id or platform.igdb_id,
|
|
)
|
|
|
|
return IGDBRom(igdb_id=None)
|
|
|
|
async def fetch_gamelist_rom() -> GamelistRom:
|
|
if MetadataSource.GAMELIST in metadata_sources and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or (scan_type == ScanType.UPDATE and rom.gamelist_id)
|
|
or (
|
|
scan_type == ScanType.UNMATCHED
|
|
and (not rom.gamelist_id or not rom.gamelist_metadata)
|
|
)
|
|
):
|
|
attempted_sources.add(MetadataSource.GAMELIST)
|
|
return await meta_gamelist_handler.get_rom(
|
|
rom_attrs["fs_name"], platform, rom
|
|
)
|
|
|
|
return GamelistRom(gamelist_id=None)
|
|
|
|
async def fetch_flashpoint_rom() -> FlashpointRom:
|
|
if (
|
|
MetadataSource.FLASHPOINT in metadata_sources
|
|
and platform.slug in FLASHPOINT_PLATFORM_LIST
|
|
and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or (scan_type == ScanType.UPDATE and rom.flashpoint_id)
|
|
or (
|
|
scan_type == ScanType.UNMATCHED
|
|
and (not rom.flashpoint_id or not rom.flashpoint_metadata)
|
|
and platform.slug in FLASHPOINT_PLATFORM_LIST
|
|
)
|
|
)
|
|
):
|
|
attempted_sources.add(MetadataSource.FLASHPOINT)
|
|
if (scan_type == ScanType.UPDATE and rom.flashpoint_id) or (
|
|
scan_type == ScanType.UNMATCHED
|
|
and rom.flashpoint_id
|
|
and not rom.flashpoint_metadata
|
|
):
|
|
return await meta_flashpoint_handler.get_rom_by_id(rom.flashpoint_id)
|
|
else:
|
|
return await meta_flashpoint_handler.get_rom(
|
|
rom_attrs["fs_name"], platform.slug
|
|
)
|
|
|
|
return FlashpointRom(flashpoint_id=None)
|
|
|
|
async def fetch_libretro_rom() -> LibretroRom:
|
|
if (
|
|
MetadataSource.LIBRETRO in metadata_sources
|
|
and platform.slug in LIBRETRO_PLATFORM_LIST
|
|
and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or (scan_type == ScanType.UPDATE and rom.libretro_id)
|
|
or (scan_type == ScanType.UNMATCHED and not rom.libretro_id)
|
|
)
|
|
):
|
|
attempted_sources.add(MetadataSource.LIBRETRO)
|
|
return await meta_libretro_handler.get_rom(
|
|
rom_attrs["fs_name"], platform.slug
|
|
)
|
|
|
|
return LibretroRom(libretro_id=None)
|
|
|
|
async def fetch_hltb_rom() -> HLTBRom:
|
|
if (
|
|
MetadataSource.HLTB in metadata_sources
|
|
and platform.slug in HLTB_PLATFORM_LIST
|
|
and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or (scan_type == ScanType.UPDATE and rom.hltb_id)
|
|
or (
|
|
scan_type == ScanType.UNMATCHED
|
|
and (not rom.hltb_id or not rom.hltb_metadata)
|
|
)
|
|
)
|
|
):
|
|
attempted_sources.add(MetadataSource.HLTB)
|
|
# A refresh keeps the ID already on the ROM, often a manual match,
|
|
# rather than trading it for a filename guess. COMPLETE rematches.
|
|
if rom.hltb_id and (
|
|
scan_type == ScanType.UPDATE
|
|
or (scan_type == ScanType.UNMATCHED and not rom.hltb_metadata)
|
|
):
|
|
return await meta_hltb_handler.get_rom_by_id(rom.hltb_id)
|
|
|
|
return await meta_hltb_handler.get_rom(rom_attrs["fs_name"], platform.slug)
|
|
|
|
return HLTBRom(hltb_id=None)
|
|
|
|
async def fetch_demozoo_rom() -> DemozooRom:
|
|
if MetadataSource.DEMOZOO in metadata_sources and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or (scan_type == ScanType.UPDATE and rom.demozoo_id)
|
|
or (
|
|
scan_type == ScanType.UNMATCHED
|
|
and (not rom.demozoo_id or not rom.demozoo_metadata)
|
|
)
|
|
):
|
|
attempted_sources.add(MetadataSource.DEMOZOO)
|
|
return await meta_demozoo_handler.get_rom(
|
|
rom_attrs["fs_name"], platform.slug
|
|
)
|
|
return DemozooRom(demozoo_id=None)
|
|
|
|
async def fetch_pouet_rom() -> PouetRom:
|
|
if MetadataSource.POUET in metadata_sources and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or (scan_type == ScanType.UPDATE and rom.pouet_id)
|
|
or (
|
|
scan_type == ScanType.UNMATCHED
|
|
and (not rom.pouet_id or not rom.pouet_metadata)
|
|
)
|
|
):
|
|
attempted_sources.add(MetadataSource.POUET)
|
|
if rom.pouet_id:
|
|
return await meta_pouet_handler.get_rom_by_id(int(rom.pouet_id))
|
|
return await meta_pouet_handler.get_rom(rom_attrs["fs_name"], platform.slug)
|
|
return PouetRom(pouet_id=None)
|
|
|
|
async def fetch_csdb_rom() -> CsdbRom:
|
|
if MetadataSource.CSDB in metadata_sources and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or (scan_type == ScanType.UPDATE and rom.csdb_id)
|
|
or (
|
|
scan_type == ScanType.UNMATCHED
|
|
and (not rom.csdb_id or not rom.csdb_metadata)
|
|
)
|
|
):
|
|
attempted_sources.add(MetadataSource.CSDB)
|
|
if rom.csdb_id:
|
|
return await meta_csdb_handler.get_rom_by_id(int(rom.csdb_id))
|
|
return await meta_csdb_handler.get_rom(rom_attrs["fs_name"], platform.slug)
|
|
return CsdbRom(csdb_id=None)
|
|
|
|
async def fetch_steam_rom() -> SteamRom:
|
|
if (
|
|
MetadataSource.STEAM in metadata_sources
|
|
and platform.slug in STEAM_PLATFORMS
|
|
and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or (scan_type == ScanType.UPDATE and rom.steam_id)
|
|
or (
|
|
scan_type == ScanType.UNMATCHED
|
|
and (not rom.steam_id or not rom.steam_metadata)
|
|
)
|
|
)
|
|
):
|
|
attempted_sources.add(MetadataSource.STEAM)
|
|
return await resolve_steam_rom(
|
|
rom=rom,
|
|
fs_name=str(rom_attrs["fs_name"]),
|
|
platform_slug=platform.slug,
|
|
scan_type=scan_type,
|
|
)
|
|
|
|
return SteamRom(steam_id=None)
|
|
|
|
async def fetch_moby_rom(playmatch_rom: PlaymatchRomMatch) -> MobyGamesRom:
|
|
if (
|
|
MetadataSource.MOBY in metadata_sources
|
|
and platform.moby_id
|
|
and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or (scan_type == ScanType.UPDATE and rom.moby_id)
|
|
or (
|
|
scan_type == ScanType.UNMATCHED
|
|
and (not rom.moby_id or not rom.moby_metadata)
|
|
and rom.platform_slug in MOBYGAMES_PLATFORM_LIST
|
|
)
|
|
)
|
|
):
|
|
attempted_sources.add(MetadataSource.MOBY)
|
|
if scan_type == ScanType.UPDATE and rom.moby_id:
|
|
return await meta_moby_handler.get_rom_by_id(rom.moby_id)
|
|
|
|
if playmatch_rom["moby_id"] is not None:
|
|
log.debug(
|
|
f"{hl(rom_attrs['fs_name'])} identified by Playmatch as MobyGames "
|
|
f"{hl(str(playmatch_rom['moby_id']), color=BLUE)} {emoji.EMOJI_ALIEN_MONSTER}",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
return await meta_moby_handler.get_rom_by_id(playmatch_rom["moby_id"])
|
|
|
|
return await meta_moby_handler.get_rom(
|
|
rom, rom_attrs["fs_name"], platform_moby_id=platform.moby_id
|
|
)
|
|
|
|
return MobyGamesRom(moby_id=None)
|
|
|
|
async def fetch_ss_rom(playmatch_rom: PlaymatchRomMatch) -> SSRom:
|
|
if (
|
|
MetadataSource.SS in metadata_sources
|
|
and platform.ss_id
|
|
and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or (scan_type == ScanType.UPDATE and rom.ss_id)
|
|
or (
|
|
scan_type == ScanType.UNMATCHED
|
|
and (not rom.ss_id or not rom.ss_metadata)
|
|
and rom.platform_slug in SCREENSAVER_PLATFORM_LIST
|
|
)
|
|
)
|
|
):
|
|
attempted_sources.add(MetadataSource.SS)
|
|
# A breaker answering in ScreenScraper's place rules nothing out for
|
|
# this rom, whichever of the lookups below it short-circuits.
|
|
short_circuited = False
|
|
try:
|
|
# Use the ID to refetch metadata
|
|
if scan_type == ScanType.UPDATE and rom.ss_id:
|
|
# With the files, the refetch still finds our own dump among
|
|
# the game's, so a rescan keeps the tags the hash earned.
|
|
return await meta_ss_handler.get_rom_by_id(
|
|
rom, rom.ss_id, get_match_files()
|
|
)
|
|
|
|
# Use Playmatch's hash-based id when available
|
|
if playmatch_rom["ss_id"] is not None:
|
|
log.debug(
|
|
f"{hl(rom_attrs['fs_name'])} identified by Playmatch as ScreenScraper "
|
|
f"{hl(str(playmatch_rom['ss_id']), color=BLUE)} {emoji.EMOJI_ALIEN_MONSTER}",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
return await meta_ss_handler.get_rom_by_id(
|
|
rom, playmatch_rom["ss_id"], get_match_files()
|
|
)
|
|
|
|
# Use the file hashes for lookup
|
|
try:
|
|
game_by_hash, is_not_game = await meta_ss_handler.lookup_rom(
|
|
rom, platform.ss_id, get_match_files()
|
|
)
|
|
except ScreenScraperExhaustedError:
|
|
# The filename lookup below still derives a name for some
|
|
# platforms, and the breaker can clear before it runs.
|
|
short_circuited = True
|
|
else:
|
|
if game_by_hash.get("ss_id") or is_not_game:
|
|
return game_by_hash
|
|
|
|
# Fallback to the filename
|
|
return await meta_ss_handler.get_rom(
|
|
rom, rom_attrs["fs_name"], platform_ss_id=platform.ss_id
|
|
)
|
|
except ScreenScraperExhaustedError as exc:
|
|
short_circuited = True
|
|
return exc.fallback
|
|
except ScreenScraperRateLimitError:
|
|
# The per-minute budget is already spent, so give up on this ROM
|
|
# rather than spending a retried request on the fallback lookups.
|
|
note_rate_limited_rom(rom_attrs["fs_name"])
|
|
short_circuited = True
|
|
return SSRom(ss_id=None)
|
|
finally:
|
|
if short_circuited:
|
|
note_inconclusive(MetadataSource.SS)
|
|
|
|
return SSRom(ss_id=None)
|
|
|
|
async def fetch_launchbox_rom(
|
|
platform_slug: str, playmatch_rom: PlaymatchRomMatch
|
|
) -> LaunchboxRom:
|
|
if MetadataSource.LAUNCHBOX in metadata_sources and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or (scan_type == ScanType.UPDATE and rom.launchbox_id)
|
|
or (
|
|
scan_type == ScanType.UNMATCHED
|
|
and (not rom.launchbox_id or not rom.launchbox_metadata)
|
|
and rom.platform_slug in LAUNCHBOX_PLATFORM_LIST
|
|
)
|
|
):
|
|
attempted_sources.add(MetadataSource.LAUNCHBOX)
|
|
launchbox_rom = await resolve_launchbox_rom(
|
|
rom=rom,
|
|
fs_name=str(rom_attrs["fs_name"]),
|
|
platform_slug=platform_slug,
|
|
scan_type=scan_type,
|
|
playmatch_rom=playmatch_rom,
|
|
remote_enabled=launchbox_remote_enabled,
|
|
)
|
|
|
|
metadata = launchbox_rom.get("launchbox_metadata")
|
|
if metadata:
|
|
populate_rom_specific_paths(metadata, rom)
|
|
|
|
return launchbox_rom
|
|
|
|
return LaunchboxRom(launchbox_id=None)
|
|
|
|
async def fetch_ra_rom() -> RAGameRom:
|
|
if (
|
|
MetadataSource.RA in metadata_sources
|
|
and platform.ra_id
|
|
and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or scan_type == ScanType.HASHES
|
|
or (scan_type == ScanType.UPDATE and rom.ra_id)
|
|
or (
|
|
scan_type == ScanType.UNMATCHED
|
|
and (not rom.ra_id or not rom.ra_metadata)
|
|
and rom.platform_slug in RA_PLATFORM_LIST
|
|
)
|
|
)
|
|
):
|
|
attempted_sources.add(MetadataSource.RA)
|
|
if (scan_type == ScanType.UPDATE and rom.ra_id) or (
|
|
scan_type == ScanType.UNMATCHED and rom.ra_id and not rom.ra_metadata
|
|
):
|
|
return await meta_ra_handler.get_rom_by_id(
|
|
rom=rom, ra_id=rom.ra_id, ra_hash=rom_attrs["ra_hash"]
|
|
)
|
|
else:
|
|
return await meta_ra_handler.get_rom(
|
|
rom=rom, ra_hash=rom_attrs["ra_hash"]
|
|
)
|
|
|
|
return RAGameRom(ra_id=None)
|
|
|
|
async def fetch_hasheous_rom(hasheous_rom: HasheousRom) -> HasheousRom:
|
|
if (
|
|
MetadataSource.HASHEOUS in metadata_sources
|
|
and platform.hasheous_id
|
|
and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or scan_type == ScanType.HASHES
|
|
or (scan_type == ScanType.UPDATE and rom.hasheous_id)
|
|
or (
|
|
scan_type == ScanType.UNMATCHED
|
|
and (not rom.hasheous_id or not rom.hasheous_metadata)
|
|
and rom.platform_slug in HASHEOUS_PLATFORM_LIST
|
|
)
|
|
)
|
|
):
|
|
# The hash lookup is the only thing that identifies a rom here, so one
|
|
# that never answered leaves a complete rescan nothing to redo.
|
|
if MetadataSource.HASHEOUS not in inconclusive_sources:
|
|
attempted_sources.add(MetadataSource.HASHEOUS)
|
|
return await meta_hasheous_handler.get_igdb_game(hasheous_rom)
|
|
|
|
return HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None)
|
|
|
|
# Run metadata fetches concurrently. One provider raising must not discard the
|
|
# others' results for this ROM, so each failure falls back to an empty match.
|
|
provider_fetches = (
|
|
(
|
|
MetadataSource.IGDB,
|
|
fetch_igdb_rom(playmatch_hash_match, hasheous_hash_match),
|
|
IGDBRom(igdb_id=None),
|
|
),
|
|
(
|
|
MetadataSource.MOBY,
|
|
fetch_moby_rom(playmatch_hash_match),
|
|
MobyGamesRom(moby_id=None),
|
|
),
|
|
(MetadataSource.SS, fetch_ss_rom(playmatch_hash_match), SSRom(ss_id=None)),
|
|
(MetadataSource.RA, fetch_ra_rom(), RAGameRom(ra_id=None)),
|
|
(
|
|
MetadataSource.LAUNCHBOX,
|
|
fetch_launchbox_rom(platform.slug, playmatch_hash_match),
|
|
LaunchboxRom(launchbox_id=None),
|
|
),
|
|
(
|
|
MetadataSource.HASHEOUS,
|
|
fetch_hasheous_rom(hasheous_hash_match),
|
|
HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None),
|
|
),
|
|
(
|
|
MetadataSource.FLASHPOINT,
|
|
fetch_flashpoint_rom(),
|
|
FlashpointRom(flashpoint_id=None),
|
|
),
|
|
(MetadataSource.HLTB, fetch_hltb_rom(), HLTBRom(hltb_id=None)),
|
|
(MetadataSource.DEMOZOO, fetch_demozoo_rom(), DemozooRom(demozoo_id=None)),
|
|
(MetadataSource.POUET, fetch_pouet_rom(), PouetRom(pouet_id=None)),
|
|
(MetadataSource.CSDB, fetch_csdb_rom(), CsdbRom(csdb_id=None)),
|
|
(MetadataSource.STEAM, fetch_steam_rom(), SteamRom(steam_id=None)),
|
|
(MetadataSource.GAMELIST, fetch_gamelist_rom(), GamelistRom(gamelist_id=None)),
|
|
(MetadataSource.LIBRETRO, fetch_libretro_rom(), LibretroRom(libretro_id=None)),
|
|
)
|
|
fetch_results = await asyncio.gather(
|
|
*(coro for _, coro, _ in provider_fetches), return_exceptions=True
|
|
)
|
|
|
|
resolved: list[Any] = [
|
|
resolve_fetch(source, result, fallback)
|
|
for (source, _, fallback), result in zip(
|
|
provider_fetches, fetch_results, strict=True
|
|
)
|
|
]
|
|
|
|
(
|
|
igdb_handler_rom,
|
|
moby_handler_rom,
|
|
ss_handler_rom,
|
|
ra_handler_rom,
|
|
launchbox_handler_rom,
|
|
hasheous_handler_rom,
|
|
flashpoint_handler_rom,
|
|
hltb_handler_rom,
|
|
demozoo_handler_rom,
|
|
pouet_handler_rom,
|
|
csdb_handler_rom,
|
|
steam_handler_rom,
|
|
gamelist_handler_rom,
|
|
libretro_handler_rom,
|
|
) = resolved
|
|
|
|
# Filename is usually only (demozoo-N). Demozoo's Pouët link is the
|
|
# ID we would have used if the tag had been (pouet-N).
|
|
if MetadataSource.POUET in metadata_sources and not pouet_handler_rom.get(
|
|
"pouet_id"
|
|
):
|
|
linked = (demozoo_handler_rom.get("demozoo_metadata") or {}).get("pouet_id")
|
|
if linked:
|
|
try:
|
|
followed = await meta_pouet_handler.get_rom_by_id(int(linked))
|
|
except Exception as exc:
|
|
log.error(
|
|
f"Error following Demozoo Pouët id {hl(str(linked))}: {exc}",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
else:
|
|
if followed.get("pouet_id"):
|
|
pouet_handler_rom = followed
|
|
|
|
if MetadataSource.CSDB in metadata_sources and not csdb_handler_rom.get("csdb_id"):
|
|
linked_csdb = (demozoo_handler_rom.get("demozoo_metadata") or {}).get("csdb_id")
|
|
if linked_csdb:
|
|
try:
|
|
followed_csdb = await meta_csdb_handler.get_rom_by_id(int(linked_csdb))
|
|
except Exception as exc:
|
|
log.error(
|
|
f"Error following Demozoo CSDb id {hl(str(linked_csdb))}: {exc}",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
else:
|
|
if followed_csdb.get("csdb_id"):
|
|
csdb_handler_rom = followed_csdb
|
|
|
|
# Pouët is later in metadata priority, so its short summary would
|
|
# replace Demozoo's party / credits / YouTube. Keep the richer line
|
|
# and splice in Pouët score / rank / extra links.
|
|
if demozoo_handler_rom.get("demozoo_id") and pouet_handler_rom.get("pouet_id"):
|
|
dz_meta = demozoo_handler_rom.get("demozoo_metadata") or {}
|
|
pq_meta = pouet_handler_rom.get("pouet_metadata") or {}
|
|
merged = splice_pouet_vote(
|
|
str(demozoo_handler_rom.get("summary") or ""),
|
|
pq_meta.get("vote_avg"),
|
|
pq_meta.get("pouet_rank"),
|
|
pq_meta.get("pouet_cdc"),
|
|
)
|
|
if merged:
|
|
demozoo_handler_rom["summary"] = merged
|
|
pouet_handler_rom["summary"] = merged
|
|
urls: list[str] = []
|
|
for url in (dz_meta.get("download_urls") or []) + (
|
|
pq_meta.get("download_urls") or []
|
|
):
|
|
_append_unique(urls, url)
|
|
if urls:
|
|
dz_meta["download_urls"] = urls
|
|
pq_meta["download_urls"] = urls
|
|
if not dz_meta.get("youtube_video_id") and pq_meta.get("youtube_video_id"):
|
|
dz_meta["youtube_video_id"] = pq_meta["youtube_video_id"]
|
|
demozoo_handler_rom["demozoo_metadata"] = dz_meta
|
|
pouet_handler_rom["pouet_metadata"] = pq_meta
|
|
|
|
# Same idea: Demozoo's Overview is richer; just add the CSDb page.
|
|
csdb_url = (csdb_handler_rom.get("csdb_metadata") or {}).get("csdb_url") or (
|
|
(demozoo_handler_rom.get("demozoo_metadata") or {}).get("csdb_url")
|
|
)
|
|
if csdb_url:
|
|
for blob in (demozoo_handler_rom, pouet_handler_rom, csdb_handler_rom):
|
|
if blob.get("summary") or blob.get("csdb_id") or blob.get("demozoo_id"):
|
|
merged_csdb = splice_csdb_url(str(blob.get("summary") or ""), csdb_url)
|
|
if merged_csdb:
|
|
blob["summary"] = merged_csdb
|
|
|
|
metadata_handlers: dict[MetadataSource, dict[str, Any]] = {
|
|
MetadataSource.IGDB: {
|
|
"handler": igdb_handler_rom,
|
|
"id_field": "igdb_id",
|
|
"metadata_field": "igdb_metadata",
|
|
},
|
|
MetadataSource.MOBY: {
|
|
"handler": moby_handler_rom,
|
|
"id_field": "moby_id",
|
|
"metadata_field": "moby_metadata",
|
|
},
|
|
MetadataSource.SS: {
|
|
"handler": ss_handler_rom,
|
|
"id_field": "ss_id",
|
|
"metadata_field": "ss_metadata",
|
|
},
|
|
MetadataSource.RA: {
|
|
"handler": ra_handler_rom,
|
|
"id_field": "ra_id",
|
|
"metadata_field": "ra_metadata",
|
|
},
|
|
MetadataSource.LAUNCHBOX: {
|
|
"handler": launchbox_handler_rom,
|
|
"id_field": "launchbox_id",
|
|
"metadata_field": "launchbox_metadata",
|
|
},
|
|
MetadataSource.HASHEOUS: {
|
|
"handler": hasheous_handler_rom,
|
|
"id_field": "hasheous_id",
|
|
"metadata_field": "hasheous_metadata",
|
|
},
|
|
MetadataSource.FLASHPOINT: {
|
|
"handler": flashpoint_handler_rom,
|
|
"id_field": "flashpoint_id",
|
|
"metadata_field": "flashpoint_metadata",
|
|
},
|
|
MetadataSource.HLTB: {
|
|
"handler": hltb_handler_rom,
|
|
"id_field": "hltb_id",
|
|
"metadata_field": "hltb_metadata",
|
|
},
|
|
MetadataSource.DEMOZOO: {
|
|
"handler": demozoo_handler_rom,
|
|
"id_field": "demozoo_id",
|
|
"metadata_field": "demozoo_metadata",
|
|
},
|
|
MetadataSource.POUET: {
|
|
"handler": pouet_handler_rom,
|
|
"id_field": "pouet_id",
|
|
"metadata_field": "pouet_metadata",
|
|
},
|
|
MetadataSource.CSDB: {
|
|
"handler": csdb_handler_rom,
|
|
"id_field": "csdb_id",
|
|
"metadata_field": "csdb_metadata",
|
|
},
|
|
MetadataSource.STEAM: {
|
|
"handler": steam_handler_rom,
|
|
"id_field": "steam_id",
|
|
"metadata_field": "steam_metadata",
|
|
},
|
|
MetadataSource.GAMELIST: {
|
|
"handler": gamelist_handler_rom,
|
|
"id_field": "gamelist_id",
|
|
"metadata_field": "gamelist_metadata",
|
|
},
|
|
MetadataSource.LIBRETRO: {
|
|
"handler": libretro_handler_rom,
|
|
"id_field": "libretro_id",
|
|
"metadata_field": None,
|
|
},
|
|
MetadataSource.SGDB: {
|
|
"handler": {},
|
|
"id_field": "sgdb_id",
|
|
"metadata_field": None,
|
|
},
|
|
MetadataSource.TGDB: {
|
|
"handler": {},
|
|
"id_field": "tgdb_id",
|
|
"metadata_field": None,
|
|
},
|
|
}
|
|
|
|
# Reset the id and blob of every source this rescan could rematch: the ones it
|
|
# consulted, whose miss has to undo the old match, and the deselected ones.
|
|
if is_complete_rescan:
|
|
for source, fields in metadata_handlers.items():
|
|
if source in attempted_sources or source not in metadata_sources:
|
|
rom_attrs[fields["id_field"]] = None
|
|
if fields["metadata_field"]:
|
|
rom_attrs[fields["metadata_field"]] = {}
|
|
|
|
# Reset artwork fields so stale values are cleared when no source supplies
|
|
# them. The locks go too, since a complete rescan deletes the files.
|
|
rom_attrs.update(
|
|
{
|
|
"url_cover": "",
|
|
"url_screenshots": [],
|
|
"url_manual": "",
|
|
"path_cover_s": "",
|
|
"path_cover_l": "",
|
|
"path_screenshots": [],
|
|
"path_manual": "",
|
|
"locked_fields": [],
|
|
}
|
|
)
|
|
|
|
# Determine which metadata sources are available
|
|
available_sources = [
|
|
name
|
|
for name, fields in metadata_handlers.items()
|
|
if fields["handler"].get(fields["id_field"])
|
|
]
|
|
# A persisted id locks the ROM too, so an unreachable provider can't hand an
|
|
# identified production back to the catalogs. Deselecting the source on a
|
|
# complete rescan clears the id above, which is the way out.
|
|
scene_locked = any(
|
|
source in SCENE_METADATA_SOURCES for source in available_sources
|
|
) or any(
|
|
rom_attrs.get(metadata_handlers[source]["id_field"])
|
|
for source in SCENE_METADATA_SOURCES
|
|
)
|
|
apply_sources = scene_apply_sources(available_sources, scene_locked=scene_locked)
|
|
if scene_locked:
|
|
log.info(
|
|
f"{hl(rom_attrs['fs_name'])} is a Demozoo/Pouët/CSDb production, "
|
|
"using scene artwork and title, not similar game catalogs",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
|
|
# A rehash that no longer matches must drop the previous Hasheous match, or
|
|
# the ROM keeps showing verification flags earned by hashes it no longer has.
|
|
# Only a conclusive lookup clears them, so an unreachable Hasheous can't
|
|
# silently de-verify a library.
|
|
if (
|
|
scan_type == ScanType.HASHES
|
|
and hasheous_lookup_conclusive
|
|
and not hasheous_hash_match.get("hasheous_id")
|
|
):
|
|
rom_attrs["hasheous_id"] = None
|
|
rom_attrs["hasheous_metadata"] = {}
|
|
|
|
# Same for the RA hash match, once an RA lookup that ran found nothing.
|
|
ra_metadata = rom_attrs.get("ra_metadata") or {}
|
|
if (
|
|
scan_type == ScanType.HASHES
|
|
and MetadataSource.RA in attempted_sources
|
|
and not ra_handler_rom.get("ra_id")
|
|
and ra_metadata.get("hash_match")
|
|
):
|
|
rom_attrs["ra_metadata"] = {**ra_metadata, "hash_match": False}
|
|
|
|
# A skipped source's tags can't be told apart on the row, so each hash source
|
|
# keeps the ones its dump gave in its own blob.
|
|
for source_name in HASH_MATCHED_TAG_SOURCES:
|
|
fields = metadata_handlers[source_name]
|
|
handler = fields["handler"]
|
|
if handler.get(fields["id_field"]):
|
|
dump_tags = {
|
|
DUMP_TAG_KEYS[field]: list(handler.get(field) or [])
|
|
for field in PROVIDER_ALL_TAG_FIELDS
|
|
}
|
|
blob = {**(handler.get(fields["metadata_field"]) or {}), **dump_tags}
|
|
fields["handler"] = {**handler, fields["metadata_field"]: blob}
|
|
|
|
# One ordering pass for both lists, since each one rereads config.yml.
|
|
hash_sources = [] if scene_locked else list(HASH_MATCHED_TAG_SOURCES)
|
|
ordered = get_priority_ordered_metadata_sources(
|
|
list(dict.fromkeys([*apply_sources, *hash_sources])), "metadata"
|
|
)
|
|
priority_ordered = [source for source in ordered if source in apply_sources]
|
|
hash_claims = [
|
|
hash_source_tags(metadata_handlers[source], rom_attrs)
|
|
for source in ordered
|
|
if source in hash_sources
|
|
]
|
|
|
|
# Apply metadata priority order
|
|
# Reverse priority order to apply highest priority last
|
|
for source_name in reversed(priority_ordered):
|
|
handler_data = metadata_handlers[source_name]["handler"]
|
|
# Only update fields that have valid values
|
|
for key, field_value in handler_data.items():
|
|
if (
|
|
key in PROVIDER_ALL_TAG_FIELDS
|
|
and source_name in HASH_MATCHED_TAG_SOURCES
|
|
):
|
|
continue
|
|
if field_value:
|
|
rom_attrs[key] = field_value
|
|
|
|
# Re-read rather than taken off the row, which cannot say whether its value
|
|
# is a tag the user wrote or what a provider left there on an earlier scan.
|
|
filename_tags = fs_rom_handler.parse_tags(rom_attrs["fs_name"])
|
|
local_tags = {
|
|
"regions": filename_tags.regions,
|
|
"languages": filename_tags.languages,
|
|
"tags": filename_tags.other_tags,
|
|
}
|
|
for field in PROVIDER_TAG_FIELDS:
|
|
if local_tags[field] or any(
|
|
metadata_handlers[source_name]["handler"].get(field)
|
|
for source_name in priority_ordered
|
|
if source_name not in HASH_MATCHED_TAG_SOURCES
|
|
):
|
|
continue
|
|
for claims, answered in hash_claims:
|
|
# What a source said on an earlier scan fills only an empty slot: the
|
|
# row's value may come from a source this scan didn't ask either.
|
|
if claims[field] and (answered or not rom_attrs.get(field)):
|
|
rom_attrs[field] = claims[field]
|
|
break
|
|
|
|
for field in PROVIDER_MERGED_TAG_FIELDS:
|
|
# The base is what a local source says now, never the stored list: a
|
|
# dump that stops being a translation has to lose the tag again.
|
|
merged_tags = list(local_tags[field])
|
|
for source_name in priority_ordered:
|
|
if source_name in HASH_MATCHED_TAG_SOURCES:
|
|
continue
|
|
claimed = metadata_handlers[source_name]["handler"].get(field)
|
|
if claimed:
|
|
merged_tags = list(claimed)
|
|
break
|
|
for claims, _ in hash_claims:
|
|
for tag in claims[field]:
|
|
if tag not in merged_tags:
|
|
merged_tags.append(tag)
|
|
rom_attrs[field] = merged_tags
|
|
|
|
# Artwork sources are prioritized separately, and each field can carry its
|
|
# own override on top of the shared artwork priority.
|
|
for field in ["url_cover", "url_screenshots", "url_manual"]:
|
|
priority_ordered_artwork = get_priority_ordered_metadata_sources(
|
|
apply_sources, field
|
|
)
|
|
# Reverse priority order to apply highest priority last
|
|
for source_name in reversed(priority_ordered_artwork):
|
|
# Only update fields that have valid values
|
|
field_value = metadata_handlers[source_name]["handler"].get(field)
|
|
if field_value:
|
|
rom_attrs[field] = field_value
|
|
|
|
# Don't overwrite existing base fields on update, unmatched and hashes scans
|
|
if not newly_added and scan_type in (
|
|
ScanType.UNMATCHED,
|
|
ScanType.UPDATE,
|
|
ScanType.HASHES,
|
|
):
|
|
# A ROM's name defaults to a filename-derived placeholder when first
|
|
# created. Treat that placeholder as "no name" so a freshly matched provider
|
|
# name replaces it (while preserving user-edited names).
|
|
fs_name_no_tags = fs_rom_handler.get_file_name_with_no_tags(
|
|
rom_attrs["fs_name"]
|
|
)
|
|
# Both the existing name and the seeded rom_attrs name can hold the
|
|
# placeholder. Discard either when it's a placeholder so the parsed
|
|
# filename fallback can win.
|
|
placeholders = (None, "", rom.fs_name, fs_name_no_tags)
|
|
existing_name = None if rom.name in placeholders else rom.name
|
|
matched_name = rom_attrs.get("name")
|
|
matched_name = None if matched_name in placeholders else matched_name
|
|
rom_attrs.update(
|
|
{
|
|
"name": existing_name or matched_name or fs_name_no_tags or None,
|
|
"summary": rom.summary or rom_attrs.get("summary") or None,
|
|
# Only a locked slot resists the freshly resolved url. A stored
|
|
# manual is pinned regardless, since one with no url was uploaded.
|
|
"url_cover": (
|
|
""
|
|
if rom.is_field_locked("url_cover")
|
|
else rom_attrs.get("url_cover") or None
|
|
),
|
|
"url_manual": (
|
|
rom.url_manual
|
|
if rom.url_manual
|
|
or rom.path_manual
|
|
or rom.is_field_locked("url_manual")
|
|
else rom_attrs.get("url_manual") or None
|
|
),
|
|
"url_screenshots": rom_attrs.get("url_screenshots") or [],
|
|
}
|
|
)
|
|
|
|
# Use PICO-8 cartridge PNG as cover art if no cover is set.
|
|
# PICO-8 .p8.png files are valid PNG images whose visual content is the
|
|
# cartridge label, so the ROM file itself serves as the cover art.
|
|
if not rom_attrs.get("url_cover") and not rom_attrs.get("path_cover_s"):
|
|
pico8_url = fs_rom_handler.get_pico8_cover_url(
|
|
platform.slug, rom_attrs["fs_name"], rom_attrs["fs_path"]
|
|
)
|
|
if pico8_url:
|
|
rom_attrs["url_cover"] = pico8_url
|
|
|
|
# If not found in any metadata source, we return the rom with the default values
|
|
if not any(
|
|
rom_attrs.get(column.key) for column in METADATA_SOURCE_COLUMNS.values()
|
|
):
|
|
if inconclusive_sources:
|
|
# Reporting a plain "not identified" here writes the ROM up as a
|
|
# coverage gap the providers confirmed, when one of them simply
|
|
# never answered.
|
|
silent = ", ".join(hl(source) for source in sorted(inconclusive_sources))
|
|
log.warning(
|
|
f"{hl(rom_attrs['fs_name'])} not identified, but {silent} gave "
|
|
f"no answer, so this is not a confirmed miss - an UNMATCHED "
|
|
f"scan will retry it {emoji.EMOJI_WARNING}",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
else:
|
|
log.warning(
|
|
f"{hl(rom_attrs['fs_name'])} not identified {emoji.EMOJI_CROSS_MARK}",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
return Rom(**rom_attrs)
|
|
|
|
async def fetch_sgdb_details(playmatch_rom: PlaymatchRomMatch) -> SGDBRom:
|
|
"""Fetch SteamGridDB details for the ROM."""
|
|
# SGDB searches by title (and by IGDB's similar-name match). That is
|
|
# the same collision we just locked out for scene productions.
|
|
if scene_locked:
|
|
return SGDBRom(sgdb_id=None)
|
|
|
|
if MetadataSource.SGDB in metadata_sources and (
|
|
newly_added
|
|
or scan_type == ScanType.COMPLETE
|
|
or (scan_type == ScanType.UPDATE and rom.sgdb_id)
|
|
or (scan_type == ScanType.UNMATCHED and not rom.sgdb_id)
|
|
):
|
|
attempted_sources.add(MetadataSource.SGDB)
|
|
if scan_type == ScanType.UPDATE and rom.sgdb_id:
|
|
return await meta_sgdb_handler.get_rom_by_id(rom.sgdb_id)
|
|
|
|
if playmatch_rom["sgdb_id"] is not None:
|
|
log.debug(
|
|
f"{hl(rom_attrs['fs_name'])} identified by Playmatch as SteamGridDB "
|
|
f"{hl(str(playmatch_rom['sgdb_id']), color=BLUE)} {emoji.EMOJI_ALIEN_MONSTER}",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
return await meta_sgdb_handler.get_rom_by_id(playmatch_rom["sgdb_id"])
|
|
|
|
file_name_no_tags = fs_rom_handler.get_file_name_with_no_tags(
|
|
str(rom_attrs["fs_name"])
|
|
)
|
|
game_names = [
|
|
igdb_handler_rom.get("name", None),
|
|
hasheous_handler_rom.get("name", None),
|
|
ss_handler_rom.get("name", None),
|
|
moby_handler_rom.get("name", None),
|
|
launchbox_handler_rom.get("name", None),
|
|
gamelist_handler_rom.get("name", None),
|
|
file_name_no_tags,
|
|
]
|
|
valid_names = [name for name in game_names if name]
|
|
return await meta_sgdb_handler.get_details_by_names(valid_names)
|
|
|
|
return SGDBRom(sgdb_id=None)
|
|
|
|
# SteamGridDB searches on the names the other providers just produced, so it
|
|
# can't join the gather above, but it resolves the same way.
|
|
(sgdb_result,) = await asyncio.gather(
|
|
fetch_sgdb_details(playmatch_hash_match), return_exceptions=True
|
|
)
|
|
sgdb_hander_rom = resolve_fetch(
|
|
MetadataSource.SGDB, sgdb_result, SGDBRom(sgdb_id=None)
|
|
)
|
|
|
|
# Resolving this late means missing the reset block above, so clear its id here.
|
|
if is_complete_rescan and MetadataSource.SGDB in attempted_sources:
|
|
rom_attrs["sgdb_id"] = None
|
|
|
|
if sgdb_hander_rom.get("sgdb_id"):
|
|
rom_attrs["sgdb_id"] = sgdb_hander_rom["sgdb_id"]
|
|
|
|
# Apply SGDB's cover only when it outranks every other source that
|
|
# already produced one under the cover priority, and never over a
|
|
# locked cover.
|
|
sgdb_cover = sgdb_hander_rom.get("url_cover")
|
|
if sgdb_cover and not rom.is_field_locked("url_cover"):
|
|
cover_sources = [
|
|
name
|
|
for name, fields in metadata_handlers.items()
|
|
if fields["handler"].get("url_cover")
|
|
]
|
|
ranked = get_priority_ordered_metadata_sources(
|
|
cover_sources + [MetadataSource.SGDB], "url_cover"
|
|
)
|
|
if ranked[0] == MetadataSource.SGDB:
|
|
rom_attrs["url_cover"] = sgdb_cover
|
|
|
|
# Providers like libretro match without supplying a name. A new rom keeps the
|
|
# name it was created with, which for a physical game is what the user typed.
|
|
if not rom_attrs.get("name"):
|
|
rom_attrs["name"] = (
|
|
newly_added and rom.name
|
|
) or fs_rom_handler.get_file_name_with_no_tags(rom_attrs["fs_name"])
|
|
|
|
log.info(
|
|
f"{hl(rom_attrs['fs_name'])} identified as {hl(rom_attrs['name'], color=BLUE)} {emoji.EMOJI_ALIEN_MONSTER}",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
|
|
if not fs_rom["flat"]:
|
|
for file in fs_rom["files"]:
|
|
log.info(
|
|
f"\t · {hl(file.file_name, color=LIGHTYELLOW)}",
|
|
extra=LOGGER_MODULE_NAME,
|
|
)
|
|
|
|
rom_attrs["missing_from_fs"] = False
|
|
return Rom(**rom_attrs)
|
|
|
|
|
|
# The provider columns that store media, highest priority first: the order
|
|
# their files land in shared paths.
|
|
MEDIA_PROVIDERS: Final[tuple[tuple[str, str, Callable[[str], str] | None], ...]] = (
|
|
("ss_metadata", MetadataSource.SS, add_ss_auth_to_url),
|
|
("gamelist_metadata", MetadataSource.GAMELIST, None),
|
|
("launchbox_metadata", MetadataSource.LAUNCHBOX, None),
|
|
)
|
|
|
|
|
|
async def download_rom_resources(
|
|
added_rom: Rom,
|
|
previous_url_cover: str | None,
|
|
previous_url_manual: str | None,
|
|
previous_url_screenshots: list[str] | None,
|
|
metadata_sources: list[str],
|
|
previous_media: Mapping[str, dict[str, Any] | None] | None = None,
|
|
) -> None:
|
|
"""Download and persist cover, manual, screenshots and provider media for a rom.
|
|
|
|
Shared by the scan socket flow and the manual physical-game endpoint. Only
|
|
re-downloads when the source URL changed, then stores the resulting paths.
|
|
|
|
Args:
|
|
previous_media: Each provider column's metadata before this scan, keyed
|
|
like ``ss_metadata``, so media whose source changed is fetched again.
|
|
"""
|
|
url_screenshots = added_rom.url_screenshots or []
|
|
# Files are named by position, so a reorder is a change too.
|
|
screenshots_changed = url_screenshots != (previous_url_screenshots or [])
|
|
|
|
preferred_media_types = get_preferred_media_types()
|
|
providers = MEDIA_PROVIDERS
|
|
provider_media: list[tuple[str, dict[str, Any], Callable[[str], str] | None]] = [
|
|
(column, metadata, url_transform)
|
|
for column, source, url_transform in providers
|
|
if (metadata := getattr(added_rom, column)) and source in metadata_sources
|
|
]
|
|
|
|
# Filled as each provider finishes, so a later one failing keeps the rest.
|
|
media_updates: dict[str, dict[str, Any]] = {}
|
|
|
|
async def store_provider_media() -> None:
|
|
# Compared across every provider at once, before any stores, since a
|
|
# shared path's file belongs to whichever provider records it first.
|
|
if previous_media:
|
|
await fs_resource_handler.remove_stale_media(
|
|
[previous_media.get(column) for column, *_ in providers],
|
|
[getattr(added_rom, column) for column, *_ in providers],
|
|
preferred_media_types,
|
|
)
|
|
# Providers share media paths, so they take turns: a later one finds the
|
|
# file an earlier one landed on disk and keeps it.
|
|
for column, metadata, url_transform in provider_media:
|
|
# Paths of media that didn't land are cleared, so the dict is written back.
|
|
if await fs_resource_handler.store_metadata_media(
|
|
metadata, preferred_media_types, url_transform
|
|
):
|
|
media_updates[column] = metadata
|
|
|
|
achievements = (
|
|
added_rom.ra_metadata.get("achievements", [])
|
|
if added_rom.ra_metadata and MetadataSource.RA in metadata_sources
|
|
else []
|
|
)
|
|
|
|
# ScreenScraper media and RA badges are bounded by their own limiters. What
|
|
# landed is saved even when another download failed, then that failure raised.
|
|
outcomes: tuple[Any, ...] = await asyncio.gather(
|
|
gather_all(
|
|
fs_resource_handler.get_cover(
|
|
entity=added_rom,
|
|
overwrite=added_rom.url_cover != previous_url_cover,
|
|
url_cover=add_ss_auth_to_url(added_rom.url_cover),
|
|
),
|
|
fs_resource_handler.get_manual(
|
|
rom=added_rom,
|
|
overwrite=added_rom.url_manual != previous_url_manual,
|
|
url_manual=add_ss_auth_to_url(added_rom.url_manual),
|
|
),
|
|
fs_resource_handler.get_rom_screenshots(
|
|
rom=added_rom,
|
|
overwrite=screenshots_changed,
|
|
url_screenshots=[add_ss_auth_to_url(u) for u in url_screenshots],
|
|
),
|
|
),
|
|
store_provider_media(),
|
|
fs_resource_handler.store_ra_badges(achievements),
|
|
return_exceptions=True,
|
|
)
|
|
paths = outcomes[0]
|
|
|
|
updates: dict[str, Any] = dict(media_updates)
|
|
if not isinstance(paths, BaseException):
|
|
(path_cover_s, path_cover_l), path_manual, path_screenshots = paths
|
|
added_rom.path_cover_s = path_cover_s
|
|
added_rom.path_cover_l = path_cover_l
|
|
added_rom.path_screenshots = path_screenshots
|
|
added_rom.path_manual = path_manual
|
|
updates.update(
|
|
path_cover_s=path_cover_s,
|
|
path_cover_l=path_cover_l,
|
|
path_screenshots=path_screenshots,
|
|
path_manual=path_manual,
|
|
)
|
|
if updates:
|
|
db_rom_handler.update_rom(added_rom.id, updates)
|
|
|
|
for outcome in outcomes:
|
|
if isinstance(outcome, BaseException):
|
|
raise outcome
|
|
|
|
|
|
async def refresh_provider_media(
|
|
rom: Rom, pending: Mapping[str, dict[str, Any] | None]
|
|
) -> dict[str, dict[str, Any]]:
|
|
"""Bring a rom's provider media in line with re-matched metadata.
|
|
|
|
Args:
|
|
rom: The rom, still holding each provider's stored metadata.
|
|
pending: The metadata about to be stored, keyed like ``ss_metadata``;
|
|
a provider left out keeps what the rom holds.
|
|
|
|
Returns:
|
|
The dicts whose paths were cleared because their media didn't land.
|
|
"""
|
|
preferred_media_types = get_preferred_media_types()
|
|
current = [
|
|
pending[column] if column in pending else getattr(rom, column)
|
|
for column, *_ in MEDIA_PROVIDERS
|
|
]
|
|
await fs_resource_handler.remove_stale_media(
|
|
[getattr(rom, column) for column, *_ in MEDIA_PROVIDERS],
|
|
current,
|
|
preferred_media_types,
|
|
)
|
|
|
|
updates: dict[str, dict[str, Any]] = {}
|
|
for (column, _source, url_transform), metadata in zip(
|
|
MEDIA_PROVIDERS, current, strict=True
|
|
):
|
|
if metadata and await fs_resource_handler.store_metadata_media(
|
|
metadata, preferred_media_types, url_transform
|
|
):
|
|
updates[column] = metadata
|
|
return updates
|
|
|
|
|
|
class ScannedAsset(TypedDict):
|
|
file_path: str
|
|
file_name: str
|
|
file_size_bytes: int
|
|
content_hash: NotRequired[str | None]
|
|
|
|
|
|
async def _scan_asset(
|
|
file_name: str, asset_path: str, should_hash: bool = False
|
|
) -> ScannedAsset:
|
|
file_path = f"{asset_path}/{file_name}"
|
|
file_size = await fs_asset_handler.get_file_size(file_path)
|
|
|
|
result: ScannedAsset = {
|
|
"file_path": asset_path,
|
|
"file_name": file_name,
|
|
"file_size_bytes": file_size,
|
|
}
|
|
|
|
if should_hash:
|
|
result["content_hash"] = await fs_asset_handler.compute_content_hash(file_path)
|
|
|
|
return result
|
|
|
|
|
|
async def scan_save(
|
|
file_name: str,
|
|
user: User,
|
|
platform_fs_slug: str,
|
|
rom_id: int,
|
|
emulator: str | None = None,
|
|
) -> Save:
|
|
saves_path = fs_asset_handler.build_saves_file_path(
|
|
user=user, platform_fs_slug=platform_fs_slug, rom_id=rom_id, emulator=emulator
|
|
)
|
|
scanned_asset = await _scan_asset(file_name, saves_path, should_hash=True)
|
|
return Save(**scanned_asset)
|
|
|
|
|
|
async def scan_state(
|
|
file_name: str,
|
|
user: User,
|
|
platform_fs_slug: str,
|
|
rom_id: int,
|
|
emulator: str | None = None,
|
|
content_hash: str | None = None,
|
|
) -> State:
|
|
"""`content_hash` skips the re-read, for a caller that hashed the bytes already."""
|
|
states_path = fs_asset_handler.build_states_file_path(
|
|
user=user, platform_fs_slug=platform_fs_slug, rom_id=rom_id, emulator=emulator
|
|
)
|
|
scanned_asset = await _scan_asset(
|
|
file_name, states_path, should_hash=content_hash is None
|
|
)
|
|
if content_hash is not None:
|
|
scanned_asset["content_hash"] = content_hash
|
|
return State(**scanned_asset)
|
|
|
|
|
|
async def scan_memory_card_version(
|
|
file_name: str,
|
|
user: User,
|
|
emulator: str,
|
|
card_id: int,
|
|
content_hash: str | None = None,
|
|
) -> MemoryCardVersion:
|
|
"""Scan a card archive that is already on disk.
|
|
|
|
`content_hash` skips the re-read: a caller that hashed the same bytes in
|
|
memory has the answer already, and a card archive runs to hundreds of
|
|
megabytes.
|
|
"""
|
|
cards_path = fs_asset_handler.build_memory_cards_file_path(
|
|
user=user, emulator=emulator, card_id=card_id
|
|
)
|
|
scanned_asset = await _scan_asset(
|
|
file_name, cards_path, should_hash=content_hash is None
|
|
)
|
|
if content_hash is not None:
|
|
scanned_asset["content_hash"] = content_hash
|
|
return MemoryCardVersion(**scanned_asset, memory_card_id=card_id)
|
|
|
|
|
|
async def scan_screenshot(
|
|
file_name: str,
|
|
user: User,
|
|
platform_fs_slug: str,
|
|
rom_id: int,
|
|
emulator: str | None = None,
|
|
) -> Screenshot:
|
|
screenshots_path = fs_asset_handler.build_screenshots_file_path(
|
|
user=user, platform_fs_slug=platform_fs_slug, rom_id=rom_id, emulator=emulator
|
|
)
|
|
scanned_asset = await _scan_asset(file_name, screenshots_path)
|
|
return Screenshot(**scanned_asset)
|