import asyncio from collections.abc import Awaitable from typing import Final, NotRequired, TypedDict from adapters.services.steam import SteamService from adapters.services.steam_types import ( SteamAppDetails, SteamPlatforms, SteamStoreSearchItem, ) from config import STEAM_API_ENABLED from logger.logger import log from utils.datetime import parse_utc_timestamp from utils.html_text import html_to_text from utils.platform_slugs import UniversalPlatformSlug as UPS from .base_handler import ( BaseRom, CoverResource, CoverResult, MetadataHandler, provider_tag_regex, tag_id_from_filename, ) # Half-Life 2: never region locked, so a fetch failing means Steam is down. STEAM_HEARTBEAT_APP_ID: Final[int] = 220 STEAM_PLATFORMS: Final[frozenset[UPS]] = frozenset({UPS.WIN, UPS.LINUX, UPS.MAC}) # The OS flag a store hit carries for each of those platforms. STEAM_PLATFORM_KEYS: Final[dict[UPS, str]] = { UPS.WIN: "windows", UPS.LINUX: "linux", UPS.MAC: "mac", } # How many store hits the manual match and cover pickers offer. STEAM_SEARCH_RESULT_LIMIT: Final[int] = 15 # How long the pickers wait on the CDN for cover art, in seconds. STEAM_COVER_PROBE_TIMEOUT: Final[float] = 5.0 # The sizes the CDN serves the portrait capsule and the landscape header at. STEAM_LIBRARY_CAPSULE_SIZE: Final[tuple[int, int]] = (600, 900) STEAM_HEADER_IMAGE_SIZE: Final[tuple[int, int]] = (460, 215) # Regex to detect Steam app ID tags in filenames like (steam-12345) STEAM_TAG_REGEX = provider_tag_regex("steam") # Steam category IDs mapped onto the game-mode vocabulary the other providers use. STEAM_CATEGORY_GAME_MODES: Final[dict[int, str]] = { 1: "Multiplayer", 2: "Single player", 9: "Co-operative", 20: "Massively Multiplayer Online (MMO)", 24: "Split screen", 37: "Split screen", 38: "Co-operative", 39: "Co-operative", } class SteamMetadata(TypedDict): # Shared keys keep the other providers' names and shapes, so the UI reads # Steam through the same components. total_rating: NotRequired[str] first_release_date: NotRequired[int] genres: NotRequired[list[str]] companies: NotRequired[list[str]] publishers: NotRequired[list[str]] developers: NotRequired[list[str]] game_modes: NotRequired[list[str]] # Steam-specific extras. platforms: NotRequired[SteamPlatforms] controller_support: NotRequired[str] metacritic_url: NotRequired[str] website: NotRequired[str] is_free: NotRequired[bool] required_age: NotRequired[int] class SteamRom(BaseRom): steam_id: int | None steam_metadata: NotRequired[SteamMetadata] def _runs_on(app: SteamStoreSearchItem, platform_slug: str) -> bool: """Whether a store hit is sold for the library's operating system.""" platforms = app.get("platforms") os_key = STEAM_PLATFORM_KEYS.get(UPS(platform_slug)) # A hit with no OS flags, or a platform that maps to none, is kept rather # than dropped: only a flag that says "not for this OS" rules a hit out. if not platforms or not os_key: return True return bool(platforms.get(os_key, False)) def _cover_resource(url: str, size: tuple[int, int]) -> CoverResource: """A store asset in the picker's shape; the flags are SteamGridDB's.""" width, height = size return CoverResource( thumb=url, url=url, type="static", width=width, height=height, style="", author="", score=0, nsfw=False, humor=False, epilepsy=False, ) def _parse_release_date(raw_date: str) -> int | None: """Convert Steam's release date into an epoch timestamp, or None if coarse. The store mixes "10 Dec, 2020" and "Dec 10, 2020" across apps, and returns year-only or quarter values for unreleased ones. """ return parse_utc_timestamp( raw_date, ("%d %b, %Y", "%b %d, %Y", "%d %B, %Y", "%B %d, %Y") ) def extract_steam_metadata(details: SteamAppDetails) -> SteamMetadata: """Extract metadata from a Steam store payload.""" metadata = SteamMetadata() genres = [ genre["description"] for genre in details.get("genres", []) if genre.get("description") ] if genres: metadata["genres"] = genres developers = [dev for dev in details.get("developers", []) if dev] publishers = [pub for pub in details.get("publishers", []) if pub] if developers: metadata["developers"] = developers if publishers: metadata["publishers"] = publishers # dict.fromkeys dedupes while keeping developers ahead of publishers. companies = list(dict.fromkeys(developers + publishers)) if companies: metadata["companies"] = companies game_modes = list( dict.fromkeys( mode for category in details.get("categories", []) if (mode := STEAM_CATEGORY_GAME_MODES.get(category.get("id", 0))) ) ) if game_modes: metadata["game_modes"] = game_modes metacritic = details.get("metacritic") if metacritic: if metacritic.get("score"): metadata["total_rating"] = str(metacritic["score"]) if metacritic.get("url"): metadata["metacritic_url"] = metacritic["url"] release_date = details.get("release_date") if release_date and not release_date.get("coming_soon"): timestamp = _parse_release_date(release_date.get("date", "")) if timestamp is not None: metadata["first_release_date"] = timestamp platforms = details.get("platforms") if platforms: metadata["platforms"] = platforms if details.get("controller_support"): metadata["controller_support"] = details["controller_support"] website = details.get("website") if website: metadata["website"] = website if details.get("is_free") is not None: metadata["is_free"] = bool(details["is_free"]) required_age = details.get("required_age") if required_age: try: metadata["required_age"] = int(required_age) except TypeError, ValueError: pass return metadata class SteamHandler(MetadataHandler): """ Handler for the Steam storefront, which covers the PC platforms only. """ def __init__(self) -> None: self.steam_service = SteamService() self.min_similarity_score: Final[float] = 0.85 @classmethod def is_enabled(cls) -> bool: return STEAM_API_ENABLED async def heartbeat(self) -> bool: async def probe() -> bool: details = await self.steam_service.get_app_details( STEAM_HEARTBEAT_APP_ID, filters="basic" ) return details is not None return await self._heartbeat("Steam API", probe) async def get_rom(self, fs_name: str, platform_slug: str) -> SteamRom: """ Get ROM information from the Steam storefront. :param fs_name: The filename to search for. :param platform_slug: The platform slug, used to skip non-PC platforms. :return: A SteamRom object. """ from handler.filesystem import fs_rom_handler if not self.is_enabled(): return SteamRom(steam_id=None) # Skip non-PC platforms rather than spend requests that cannot match. if platform_slug not in STEAM_PLATFORMS: return SteamRom(steam_id=None) steam_id_from_tag = tag_id_from_filename(STEAM_TAG_REGEX, fs_name) if steam_id_from_tag is not None: return await self.get_rom_by_id(steam_id_from_tag) search_term = fs_rom_handler.get_file_name_with_no_tags(fs_name) search_term = self.normalize_search_term(search_term, remove_punctuation=False) if not search_term: return SteamRom(steam_id=None) return await self._search_and_match(search_term) async def get_rom_by_id(self, steam_id: int) -> SteamRom: """Build a ROM from a known Steam app ID.""" if not self.is_enabled(): return SteamRom(steam_id=None) details = await self.steam_service.get_app_details(steam_id) if not details: log.debug("Could not find Steam app %s", steam_id) return SteamRom(steam_id=None) return await self._build_rom(details) async def get_matched_rom_by_id( self, steam_id: int, platform_slug: str ) -> SteamRom: """Manual match by Steam app ID, skipped for non-PC platforms.""" if platform_slug not in STEAM_PLATFORMS: return SteamRom(steam_id=None) return await self.get_rom_by_id(steam_id) async def get_matched_roms_by_name( self, search_term: str, platform_slug: str ) -> list[SteamRom]: """Candidate list for the manual match flow. Built from the store search alone: an app page per candidate would spend the storefront's budget on rows nobody picks, and applying a match refetches the chosen app by ID. """ if not self.is_enabled() or not search_term: return [] if platform_slug not in STEAM_PLATFORMS: return [] apps = await self.steam_service.search_apps(search_term) candidates = [ app for app in self._store_hits(apps) if _runs_on(app, platform_slug) ][:STEAM_SEARCH_RESULT_LIMIT] covers = await self._probe_covers( [ self.steam_service.get_library_capsule_url(app["id"]) for app in candidates ] ) return [ SteamRom(steam_id=app["id"], name=app["name"], url_cover=cover or "") for app, cover in zip(candidates, covers, strict=True) ] async def get_details(self, search_term: str) -> list[CoverResult]: """Store artwork for the manual cover search, one entry per store hit.""" if not self.is_enabled() or not search_term: return [] apps = await self.steam_service.search_apps(search_term) candidates = self._store_hits(apps)[:STEAM_SEARCH_RESULT_LIMIT] cover_probes = ( (self.steam_service.get_library_capsule_url, STEAM_LIBRARY_CAPSULE_SIZE), (self.steam_service.get_header_image_url, STEAM_HEADER_IMAGE_SIZE), ) urls = await self._probe_covers( [probe(app["id"]) for app in candidates for probe, _ in cover_probes] ) results: list[CoverResult] = [] for index, app in enumerate(candidates): app_urls = urls[index * len(cover_probes) : (index + 1) * len(cover_probes)] resources = [ _cover_resource(url, size) for (_, size), url in zip(cover_probes, app_urls, strict=True) if url ] if resources: results.append(CoverResult(name=app["name"], resources=resources)) return results @staticmethod def _store_hits(apps: list[SteamStoreSearchItem]) -> list[SteamStoreSearchItem]: """The search hits that name an app, dropping DLC, soundtracks and tools.""" return [ app for app in apps if app.get("type") == "app" and app.get("id") and app.get("name") ] async def _probe_covers( self, probes: list[Awaitable[str | None]] ) -> list[str | None]: """Run the CDN probes under one budget, so a slow CDN costs thumbnails rather than the results the user is waiting on.""" try: return await asyncio.wait_for( asyncio.gather(*probes), timeout=STEAM_COVER_PROBE_TIMEOUT ) except TimeoutError: log.debug("Steam cover probes timed out") return [None] * len(probes) async def _search_and_match(self, search_term: str) -> SteamRom: apps = await self.steam_service.search_apps(search_term) candidates = self._store_hits(apps) if not candidates: log.debug("Could not find '%s' on Steam", search_term) return SteamRom(steam_id=None) best_match, best_score = self.find_best_match( search_term, [app["name"] for app in candidates], min_similarity_score=self.min_similarity_score, ) if not best_match: log.debug("No good match found for '%s' on Steam", search_term) return SteamRom(steam_id=None) best_app = next(app for app in candidates if app["name"] == best_match) details = await self.steam_service.get_app_details(best_app["id"]) # `type` on a search hit is the store's coarse kind; only the app page # distinguishes a game from a demo, video or piece of hardware. if not details or details.get("type") != "game": log.debug( "Steam match for '%s' -> '%s' is not a game, skipping", search_term, best_match, ) return SteamRom(steam_id=None) log.debug( "Found Steam match for '%s' -> '%s' (score: %.3f)", search_term, best_match, best_score, ) return await self._build_rom(details) async def _build_rom(self, details: SteamAppDetails) -> SteamRom: app_id = details["steam_appid"] rom = SteamRom( steam_id=app_id, name=details["name"], url_cover=await self._resolve_cover_url(app_id, details), url_screenshots=[ screenshot["path_full"] for screenshot in details.get("screenshots", []) if screenshot.get("path_full") ], steam_metadata=extract_steam_metadata(details), ) summary = html_to_text(details.get("short_description")) if summary: rom["summary"] = summary return rom async def _resolve_cover_url(self, app_id: int, details: SteamAppDetails) -> str: """Prefer the portrait capsule, falling back to the landscape header.""" capsule_url = await self.steam_service.get_library_capsule_url(app_id) return capsule_url or details.get("header_image", "")