Merge pull request #1997 from rommapp/hasheous-igdb-proxy

Use hasheous as igdb proxy
This commit is contained in:
Georges-Antoine Assi
2025-07-06 11:56:31 -04:00
committed by GitHub
4 changed files with 250 additions and 153 deletions

View File

@@ -1,14 +1,23 @@
import json
from typing import NotRequired, TypedDict
from datetime import datetime
from typing import Any, NotRequired, TypedDict
import httpx
from config import HASHEOUS_API_ENABLED
import pydash
from config import DEV_MODE, HASHEOUS_API_ENABLED
from fastapi import HTTPException, status
from logger.logger import log
from utils import get_version
from utils.context import ctx_httpx_client
from .base_hander import MetadataHandler
from .igdb_handler import (
IGDB_AGE_RATINGS,
IGDBMetadata,
IGDBMetadataPlatform,
IGDBRom,
)
from .ra_handler import RAGameRom
class HasheousMetadata(TypedDict):
@@ -31,26 +40,73 @@ class HasheousPlatform(TypedDict):
ra_id: NotRequired[int | None]
class HasheousRom(TypedDict):
class HasheousRom(IGDBRom, RAGameRom):
hasheous_id: int | None
name: NotRequired[str]
url_cover: NotRequired[str]
igdb_id: NotRequired[int | None]
tgdb_id: NotRequired[int | None]
ra_id: NotRequired[int | None]
hasheous_metadata: NotRequired[HasheousMetadata]
def extract_metadata_from_igdb_rom(rom: dict[str, Any]) -> IGDBMetadata:
return IGDBMetadata(
{
"youtube_video_id": list(rom["videos"].values())[0]["video_id"],
"total_rating": str(round(rom.get("total_rating", 0.0), 2)),
"aggregated_rating": str(round(rom.get("aggregated_rating", 0.0), 2)),
"first_release_date": (
int(
datetime.fromisoformat(
rom["first_release_date"].replace("Z", "+00:00")
).timestamp()
)
if rom.get("first_release_date")
else None
),
"genres": pydash.map_(rom.get("genres", {}), "name"),
"franchises": pydash.compact(
[rom.get("franchise.name", None)]
+ pydash.map_(rom.get("franchises", {}), "name")
),
"alternative_names": pydash.map_(rom.get("alternative_names", {}), "name"),
"collections": pydash.map_(rom.get("collections", {}), "name"),
"game_modes": pydash.map_(rom.get("game_modes", {}), "name"),
"companies": pydash.compact(
pydash.map_(rom.get("involved_companies", {}), "company.name")
),
"platforms": [
IGDBMetadataPlatform(igdb_id=p.get("id", ""), name=p.get("name", ""))
for p in pydash.map_(rom.get("platforms", {}))
],
"age_ratings": [
IGDB_AGE_RATINGS[r]
for r in pydash.map_(rom.get("age_ratings", {}), "rating_category")
if r in IGDB_AGE_RATINGS
],
"expansions": [],
"dlcs": [],
"ports": [],
"remakes": [],
"remasters": [],
"similar_games": [],
"expanded_games": [],
}
)
class HasheousHandler(MetadataHandler):
def __init__(self) -> None:
self.BASE_URL = "https://hasheous.org/api/v1"
self.BASE_URL = (
"https://beta.hasheous.org/api/v1"
if DEV_MODE
else "https://hasheous.org/api/v1"
)
self.platform_endpoint = f"{self.BASE_URL}/Lookup/Platforms"
self.games_endpoint = f"{self.BASE_URL}/Lookup/ByHash"
# self.proxy_igdb_game_endpoint = f"{self.BASE_URL}/MetadataProxy/IGDB/Game"
# self.proxy_igdb_cover_endpoint = f"{self.BASE_URL}/MetadataProxy/IGDB/Cover"
# self.app_api_key = (
# "JNoFBA-jEh4HbxuxEHM6MVzydKoAXs9eCcp2dvcg5LRCnpp312voiWmjuaIssSzS"
# )
self.proxy_igdb_game_endpoint = f"{self.BASE_URL}/MetadataProxy/IGDB/Game"
self.proxy_igdb_cover_endpoint = f"{self.BASE_URL}/MetadataProxy/IGDB/Cover"
self.proxy_ra_game_endpoint = f"{self.BASE_URL}/MetadataProxy/RA/Game"
self.app_api_key = (
"JNoFBA-jEh4HbxuxEHM6MVzydKoAXs9eCcp2dvcg5LRCnpp312voiWmjuaIssSzS"
)
async def _request(
self,
@@ -82,7 +138,7 @@ class HasheousHandler(MetadataHandler):
"headers": {
"Content-Type": "application/json-patch+json",
"User-Agent": f"RomM/{get_version()}",
# "X-Client-API-Key": self.app_api_key,
"X-Client-API-Key": self.app_api_key,
},
"timeout": 120,
}
@@ -142,7 +198,9 @@ class HasheousHandler(MetadataHandler):
)
async def get_rom(self, rom_attrs: dict) -> HasheousRom:
fallback_rom = HasheousRom(hasheous_id=None)
fallback_rom = HasheousRom(
hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None
)
if not HASHEOUS_API_ENABLED:
return fallback_rom
@@ -219,52 +277,82 @@ class HasheousHandler(MetadataHandler):
),
)
# Not in use while fibble works on the proxy
# async def get_igdb_game(
# self, hasheous_rom: HasheousRom, igdb_id: int
# ) -> HasheousRom:
# fallback_rom = HasheousRom(
# hasheous_id=None,
# igdb_id=None,
# tgdb_id=None,
# ra_id=None,
# )
async def get_igdb_game(self, hasheous_rom: HasheousRom) -> HasheousRom:
fallback_rom = HasheousRom(
hasheous_id=None,
igdb_id=None,
tgdb_id=None,
ra_id=None,
)
# if not HASHEOUS_API_ENABLED:
# return fallback_rom
if not HASHEOUS_API_ENABLED:
return fallback_rom
# if not igdb_id:
# log.warning("No IGDB ID provided for Hasheous IGDB game lookup.")
# return fallback_rom
if hasheous_rom["igdb_id"] is None:
log.warning("No IGDB ID provided for Hasheous IGDB game lookup.")
return fallback_rom
# igdb_game = await self._request(
# self.proxy_igdb_game_endpoint,
# params={"Id": igdb_id},
# method="GET",
# )
igdb_game = await self._request(
self.proxy_igdb_game_endpoint,
params={
"Id": hasheous_rom["igdb_id"],
"expandColumns": "age_ratings, alternative_names, collections, cover, dlcs, expanded_games, franchise, franchises, game_modes, genres, involved_companies, platforms, ports, remakes, screenshots, similar_games, videos",
},
method="GET",
)
# if not igdb_game:
# log.warning(f"No Hasheous game found for IGDB ID {igdb_id}.")
# return fallback_rom
if not igdb_game:
log.warning(
f"No Hasheous game found for IGDB ID {hasheous_rom["igdb_id"]}."
)
return fallback_rom
# return HasheousRom(
# {
# **hasheous_rom,
# "slug": igdb_game.get("slug", ""),
# "name": igdb_game.get("name", ""),
# "summary": igdb_game.get("summary", ""),
# "url_cover": self._normalize_cover_url(
# igdb_game.get("cover", {}).get("url", "")
# ).replace("t_thumb", "t_1080p"),
# "url_screenshots": [
# self._normalize_cover_url(s.get("url", "")).replace(
# "t_thumb", "t_720p"
# )
# for s in igdb_game.get("screenshots", [])
# ],
# "igdb_metadata": extract_metadata_from_igdb_rom(igdb_game),
# }
# )
return HasheousRom(
{
**hasheous_rom,
"slug": igdb_game.get("slug") or hasheous_rom.get("slug") or "",
"name": igdb_game.get("name") or hasheous_rom.get("name") or "",
"summary": igdb_game.get("summary", ""),
"url_cover": self._normalize_cover_url(
pydash.get(igdb_game, "cover.url", "")
).replace("t_thumb", "t_1080p")
or hasheous_rom.get("url_cover", ""),
"url_screenshots": [
self._normalize_cover_url(s.get("url", "")).replace(
"t_thumb", "t_720p"
)
for s in igdb_game.get("screenshots", []).values()
],
"igdb_metadata": extract_metadata_from_igdb_rom(igdb_game),
}
)
async def get_ra_game(self, hasheous_rom: HasheousRom) -> HasheousRom:
fallback_rom = HasheousRom(
hasheous_id=None,
igdb_id=None,
tgdb_id=None,
ra_id=None,
)
if not HASHEOUS_API_ENABLED:
return fallback_rom
if hasheous_rom["ra_id"] is None:
log.warning("No RA ID provided for Hasheous RA game lookup.")
return fallback_rom
ra_game = await self._request(
self.proxy_ra_game_endpoint,
params={"Id": hasheous_rom["ra_id"]},
method="GET",
)
if not ra_game:
log.warning(f"No Hasheous game found for RA ID {hasheous_rom['ra_id']}.")
return fallback_rom
return hasheous_rom
class SlugToHasheousId(TypedDict):

View File

@@ -236,7 +236,7 @@ class IGDBHandler(MetadataHandler):
return wrapper
async def _request(self, url: str, data: str, timeout: int = 120) -> list:
async def _request(self, url: str, data: str) -> list:
httpx_client = ctx_httpx_client.get()
masked_headers = {}
@@ -247,13 +247,13 @@ class IGDBHandler(MetadataHandler):
url,
masked_headers,
f"{data} limit {self.pagination_limit};",
timeout,
120,
)
res = await httpx_client.post(
url,
content=f"{data} limit {self.pagination_limit};",
headers=self.headers,
timeout=timeout,
timeout=120,
)
res.raise_for_status()
@@ -301,13 +301,13 @@ class IGDBHandler(MetadataHandler):
url,
masked_headers,
f"{data} limit {self.pagination_limit};",
timeout,
120,
)
res = await httpx_client.post(
url,
content=f"{data} limit {self.pagination_limit};",
headers=self.headers,
timeout=timeout,
timeout=120,
)
res.raise_for_status()
return res.json()
@@ -539,7 +539,7 @@ class IGDBHandler(MetadataHandler):
name=rom["name"],
summary=rom.get("summary", ""),
url_cover=self._normalize_cover_url(
rom.get("cover", {}).get("url", "")
pydash.get(rom, "cover.url", "")
).replace("t_thumb", "t_1080p"),
url_screenshots=[
self._normalize_cover_url(s.get("url", "")).replace("t_thumb", "t_720p")
@@ -568,7 +568,7 @@ class IGDBHandler(MetadataHandler):
name=rom["name"],
summary=rom.get("summary", ""),
url_cover=self._normalize_cover_url(
rom.get("cover", {}).get("url", "")
pydash.get(rom, "cover.url", "")
).replace("t_thumb", "t_1080p"),
url_screenshots=[
self._normalize_cover_url(s.get("url", "")).replace("t_thumb", "t_720p")
@@ -610,7 +610,7 @@ class IGDBHandler(MetadataHandler):
alternative_roms_ids = []
for rom in alternative_matched_roms:
alternative_roms_ids.append(
rom.get("game").get("id", "")
pydash.get(rom, "game.id", "")
if "game" in rom.keys()
else rom.get("id", "")
)
@@ -618,7 +618,7 @@ class IGDBHandler(MetadataHandler):
list(
map(
lambda rom: (
f'id={rom.get("game").get("id", "")}'
f'id={pydash.get(rom, "game.id", "")}'
if "game" in rom.keys()
else f'id={rom.get("id", "")}'
),
@@ -960,7 +960,6 @@ IGDB_PLATFORM_LIST: list[SlugToIGDB] = [
{"slug": "atari-st", "name": "Atari ST/STE"},
{"slug": "tatung-einstein", "name": "Tatung Einstein"},
{"slug": "amstrad-pcw", "name": "Amstrad PCW"},
{"slug": "amstrad-gx4000", "name": "Amstrad GX4000"},
{"slug": "epoch-super-cassette-vision", "name": "Epoch Super Cassette Vision"},
{"slug": "atari7800", "name": "Atari 7800"},
{"slug": "hp3000", "name": "HP 3000"},

View File

@@ -11,18 +11,10 @@ from utils.context import ctx_httpx_client
class PlaymatchProvider(str, Enum):
"""
Enum for Playmatch Providers.
"""
IGDB = "IGDB"
class GameMatchType(str, Enum):
"""
Enum for Game Match Types.
"""
SHA256 = "SHA256"
SHA1 = "SHA1"
MD5 = "MD5"
@@ -41,9 +33,7 @@ class PlaymatchExternalMetadata(TypedDict):
class PlaymatchRomMatch(TypedDict):
provider: PlaymatchProvider
provider_game_id: int
game_match_type: GameMatchType
igdb_id: int | None
class PlaymatchHandler:
@@ -54,61 +44,6 @@ class PlaymatchHandler:
def __init__(self):
self.base_url = "https://playmatch.retrorealm.dev/api"
async def lookup_rom(self, rom_attrs: dict) -> list[PlaymatchRomMatch]:
"""
Identify a ROM file using Playmatch API.
:param rom_attrs: A dictionary containing the ROM attributes.
:return: A list of PlaymatchRomMatch objects containing the matched ROM information.
:raises HTTPException: If the request fails or the service is unavailable.
"""
if not PLAYMATCH_API_ENABLED:
return []
url = f"{self.base_url}/identify/ids"
try:
response = await self._request(
url,
{
"fileName": rom_attrs["fs_name"],
"fileSize": rom_attrs["fs_size_bytes"],
"md5": rom_attrs["md5_hash"],
"sha1": rom_attrs["sha1_hash"],
},
)
except httpx.HTTPStatusError:
# We silently fail if the service is unavailable as this should not block the rest of RomM.
return []
game_match_type = response.get("gameMatchType", None)
if game_match_type == GameMatchType.NoMatch:
log.debug("No match found for the provided ROM file.")
return []
externalMetadata = response.get("externalMetadata", [])
if len(externalMetadata) == 0:
log.debug("No external metadata found for the matched ROM file.")
return []
rom_matches: list[PlaymatchRomMatch] = []
for metadata in externalMetadata:
provider_name = metadata.get("providerName", None)
provider_game_id = metadata.get("providerId", None)
if provider_name == PlaymatchProvider.IGDB and provider_game_id is not None:
log.debug("Found IGDB match with IGDB ID: %s", provider_game_id)
rom_matches.append(
PlaymatchRomMatch(
provider=PlaymatchProvider.IGDB,
provider_game_id=int(provider_game_id),
game_match_type=GameMatchType(game_match_type),
)
)
return rom_matches
async def _request(self, url: str, query: dict) -> dict:
"""
Sends a Request to Playmatch API.
@@ -150,3 +85,54 @@ class PlaymatchHandler:
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Can't connect to Playmatch, check your internet connection",
) from e
async def lookup_rom(self, rom_attrs: dict) -> PlaymatchRomMatch:
"""
Identify a ROM file using Playmatch API.
:param rom_attrs: A dictionary containing the ROM attributes.
:return: A PlaymatchRomMatch objects containing the matched ROM information.
:raises HTTPException: If the request fails or the service is unavailable.
"""
if not PLAYMATCH_API_ENABLED:
return PlaymatchRomMatch(igdb_id=None)
url = f"{self.base_url}/identify/ids"
try:
response = await self._request(
url,
{
"fileName": rom_attrs["fs_name"],
"fileSize": rom_attrs["fs_size_bytes"],
"md5": rom_attrs["md5_hash"],
"sha1": rom_attrs["sha1_hash"],
},
)
except httpx.HTTPStatusError:
# We silently fail if the service is unavailable as this should not block the rest of RomM.
return PlaymatchRomMatch(igdb_id=None)
game_match_type = response.get("gameMatchType", None)
if game_match_type == GameMatchType.NoMatch:
log.debug("No match found for the provided ROM file.")
return PlaymatchRomMatch(igdb_id=None)
externalMetadata = response.get("externalMetadata", [])
if len(externalMetadata) == 0:
log.debug("No external metadata found for the matched ROM file.")
return PlaymatchRomMatch(igdb_id=None)
igdb_id = None
for metadata in externalMetadata:
provider_name = metadata.get("providerName", None)
provider_game_id = metadata.get("providerId", None)
if provider_name == PlaymatchProvider.IGDB and provider_game_id is not None:
log.debug(
"Playmatch found IGDB match with IGDB ID: %s", provider_game_id
)
igdb_id = int(provider_game_id)
return PlaymatchRomMatch(igdb_id=igdb_id)

View File

@@ -21,7 +21,7 @@ from handler.metadata.hasheous_handler import HasheousPlatform, HasheousRom
from handler.metadata.igdb_handler import IGDBPlatform, IGDBRom
from handler.metadata.launchbox_handler import LaunchboxPlatform, LaunchboxRom
from handler.metadata.moby_handler import MobyGamesPlatform, MobyGamesRom
from handler.metadata.playmatch_handler import PlaymatchProvider, PlaymatchRomMatch
from handler.metadata.playmatch_handler import PlaymatchRomMatch
from handler.metadata.ra_handler import RAGameRom, RAGamesPlatform
from handler.metadata.ss_handler import SSPlatform, SSRom
from handler.metadata.tgdb_handler import TGDBPlatform
@@ -322,7 +322,7 @@ async def scan_rom(
}
)
async def fetch_playmatch_roms() -> list[PlaymatchRomMatch]:
async def fetch_playmatch_hash_match() -> PlaymatchRomMatch:
if (
MetadataSource.IGDB in metadata_sources
and platform.igdb_id
@@ -335,9 +335,9 @@ async def scan_rom(
):
return await meta_playmatch_handler.lookup_rom(rom_attrs)
return []
return PlaymatchRomMatch(igdb_id=None)
async def fetch_hasheous_rom() -> HasheousRom:
async def fetch_hasheous_hash_match() -> HasheousRom:
if (
MetadataSource.HASHEOUS in metadata_sources
and platform.hasheous_id
@@ -354,15 +354,15 @@ async def scan_rom(
# Run hash fetches concurrently
(
playmatch_handler_roms,
hasheous_handler_rom,
playmatch_hash_match,
hasheous_hash_match,
) = await asyncio.gather(
fetch_playmatch_roms(),
fetch_hasheous_rom(),
fetch_playmatch_hash_match(),
fetch_hasheous_hash_match(),
)
async def fetch_igdb_rom(
playmatch_roms: list[PlaymatchRomMatch], hasheous_rom: HasheousRom
playmatch_rom: PlaymatchRomMatch, hasheous_rom: HasheousRom
) -> IGDBRom:
if (
MetadataSource.IGDB in metadata_sources
@@ -387,23 +387,16 @@ async def scan_rom(
return await meta_igdb_handler.get_rom_by_id(h_igdb_id)
# Use Playmatch matches to get the IGDB ID
for playmatch_match in playmatch_roms:
if playmatch_match["provider"] != PlaymatchProvider.IGDB:
continue
p_igdb_id = playmatch_match.get("provider_game_id")
if p_igdb_id is None:
continue
if playmatch_rom["igdb_id"] is not None:
log.debug(
emoji.emojize(
f"{hl(rom_attrs['fs_name'])} identified by Playmatch as "
f"{hl(str(p_igdb_id), color=BLUE)} :alien_monster:"
f"{hl(str(playmatch_rom["igdb_id"]), color=BLUE)} :alien_monster:"
),
extra=LOGGER_MODULE_NAME,
)
return await meta_igdb_handler.get_rom_by_id(p_igdb_id)
return await meta_igdb_handler.get_rom_by_id(playmatch_rom["igdb_id"])
# If no matches found, use the file name to get the IGDB ID
main_platform_igdb_id = await _get_main_platform_igdb_id(platform)
@@ -488,6 +481,35 @@ async def scan_rom(
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.PARTIAL and not rom.hasheous_id)
or (scan_type == ScanType.UNIDENTIFIED and not rom.hasheous_id)
)
):
(
igdb_game,
ra_game,
) = await asyncio.gather(
meta_hasheous_handler.get_igdb_game(hasheous_rom),
meta_hasheous_handler.get_ra_game(hasheous_rom),
)
return HasheousRom(
{
**hasheous_rom,
**ra_game,
**igdb_game,
}
)
return HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None)
# Run metadata fetches concurrently
(
igdb_handler_rom,
@@ -495,12 +517,14 @@ async def scan_rom(
ss_handler_rom,
ra_handler_rom,
launchbox_handler_rom,
hasheous_handler_rom,
) = await asyncio.gather(
fetch_igdb_rom(playmatch_handler_roms, hasheous_handler_rom),
fetch_igdb_rom(playmatch_hash_match, hasheous_hash_match),
fetch_moby_rom(),
fetch_ss_rom(),
fetch_ra_rom(hasheous_handler_rom),
fetch_ra_rom(hasheous_hash_match),
fetch_launchbox_rom(platform.slug),
fetch_hasheous_rom(hasheous_hash_match),
)
# Only update fields if match is found