mirror of
https://github.com/rommapp/romm.git
synced 2026-12-06 07:54:18 +01:00
Merge pull request #1951 from rommapp/misc/retroachievements-service-adapter
misc: Create RetroAchievements service adapter
This commit is contained in:
2 files changed
+203
-42
No files matched your search
@@ -0,0 +1,187 @@
|
||||
import asyncio
|
||||
import http
|
||||
from typing import Generator, cast
|
||||
|
||||
import httpx
|
||||
import yarl
|
||||
from adapters.services.retroachievements_types import (
|
||||
RAGameExtendedDetails,
|
||||
RAGameInfoAndUserProgress,
|
||||
RAGameListItem,
|
||||
RAUserCompletionProgress,
|
||||
)
|
||||
from config import RETROACHIEVEMENTS_API_KEY
|
||||
from fastapi import HTTPException, status
|
||||
from logger.logger import log
|
||||
from utils.context import ctx_httpx_client
|
||||
|
||||
|
||||
class RetroAchievementsAuth(httpx.Auth):
|
||||
"""RetroAchievements API authentication class.
|
||||
|
||||
Reference: https://api-docs.retroachievements.org/getting-started.html#quick-start-http-requests
|
||||
"""
|
||||
|
||||
def __init__(self, token: str):
|
||||
self.token = token
|
||||
|
||||
def auth_flow(
|
||||
self, request: httpx.Request
|
||||
) -> Generator[httpx.Request, httpx.Response, None]:
|
||||
request.url = request.url.copy_merge_params({"y": self.token})
|
||||
yield request
|
||||
|
||||
|
||||
class RetroAchievementsService:
|
||||
"""Service to interact with the RetroAchievements API.
|
||||
|
||||
Reference: https://api-docs.retroachievements.org/
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
token: str = RETROACHIEVEMENTS_API_KEY,
|
||||
) -> None:
|
||||
self.url = yarl.URL(base_url or "https://retroachievements.org/API")
|
||||
self.token = token
|
||||
|
||||
@property
|
||||
def _auth(self) -> httpx.Auth:
|
||||
return RetroAchievementsAuth(token=self.token)
|
||||
|
||||
async def _request(self, url: str, request_timeout: int = 120) -> dict:
|
||||
httpx_client = ctx_httpx_client.get()
|
||||
log.debug(
|
||||
"API request: URL=%s, Timeout=%s",
|
||||
url,
|
||||
request_timeout,
|
||||
)
|
||||
try:
|
||||
res = await httpx_client.get(url, auth=self._auth, timeout=request_timeout)
|
||||
res.raise_for_status()
|
||||
return res.json()
|
||||
except httpx.NetworkError as exc:
|
||||
log.critical(
|
||||
"Connection error: can't connect to RetroAchievements", exc_info=True
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Can't connect to RetroAchievements, check your internet connection",
|
||||
) from exc
|
||||
except httpx.HTTPStatusError as err:
|
||||
if err.response.status_code == http.HTTPStatus.TOO_MANY_REQUESTS:
|
||||
# Retry after 2 seconds if rate limit hit
|
||||
await asyncio.sleep(2)
|
||||
else:
|
||||
# Log the error and return an empty dict if the request fails with a different code
|
||||
log.error(err)
|
||||
return {}
|
||||
except httpx.TimeoutException:
|
||||
# Retry the request once if it times out
|
||||
pass
|
||||
|
||||
try:
|
||||
log.debug(
|
||||
"API request: URL=%s, Timeout=%s",
|
||||
url,
|
||||
request_timeout,
|
||||
)
|
||||
res = await httpx_client.get(url, auth=self._auth, timeout=request_timeout)
|
||||
res.raise_for_status()
|
||||
except (httpx.HTTPStatusError, httpx.TimeoutException) as err:
|
||||
if (
|
||||
isinstance(err, httpx.HTTPStatusError)
|
||||
and err.response.status_code == http.HTTPStatus.UNAUTHORIZED
|
||||
):
|
||||
return {}
|
||||
|
||||
log.error(err)
|
||||
return {}
|
||||
|
||||
return res.json()
|
||||
|
||||
async def get_game_extended_details(self, game_id: int) -> RAGameExtendedDetails:
|
||||
"""Retrieve extended metadata about a game, targeted via its unique ID.
|
||||
|
||||
Reference: https://api-docs.retroachievements.org/v1/get-game-extended.html
|
||||
"""
|
||||
url = self.url.joinpath("API_GetGameExtended.php").with_query(
|
||||
i=[game_id],
|
||||
)
|
||||
response = await self._request(str(url))
|
||||
return cast(RAGameExtendedDetails, response)
|
||||
|
||||
async def get_game_list(
|
||||
self,
|
||||
system_id: int,
|
||||
*,
|
||||
only_games_with_achievements: bool = False,
|
||||
include_hashes: bool = False,
|
||||
limit: int | None = None,
|
||||
offset: int | None = None,
|
||||
) -> list[RAGameListItem]:
|
||||
"""Retrieve the complete list of games for a specified console on the site, targeted by the console ID.
|
||||
|
||||
Reference: https://api-docs.retroachievements.org/v1/get-game-list.html
|
||||
"""
|
||||
params: dict[str, list[str]] = {"i": [str(system_id)]}
|
||||
if only_games_with_achievements:
|
||||
params["f"] = ["1"]
|
||||
if include_hashes:
|
||||
params["h"] = ["1"]
|
||||
if limit is not None:
|
||||
params["c"] = [str(limit)]
|
||||
if offset is not None:
|
||||
params["o"] = [str(offset)]
|
||||
|
||||
url = self.url.joinpath("API_GetGameList.php").with_query(**params)
|
||||
response = await self._request(str(url))
|
||||
return cast(list[RAGameListItem], response)
|
||||
|
||||
async def get_user_completion_progress(
|
||||
self,
|
||||
username: str,
|
||||
*,
|
||||
limit: int | None = None,
|
||||
offset: int | None = None,
|
||||
) -> RAUserCompletionProgress:
|
||||
"""Retrieve a given user's completion progress, targeted by their username.
|
||||
|
||||
Reference: https://api-docs.retroachievements.org/v1/get-user-completion-progress.html
|
||||
"""
|
||||
params: dict[str, list[str]] = {"u": [username]}
|
||||
if limit is not None:
|
||||
params["c"] = [str(limit)]
|
||||
if offset is not None:
|
||||
params["o"] = [str(offset)]
|
||||
|
||||
url = self.url.joinpath("API_GetUserCompletionProgress.php").with_query(
|
||||
**params
|
||||
)
|
||||
response = await self._request(str(url))
|
||||
return cast(RAUserCompletionProgress, response)
|
||||
|
||||
async def get_user_game_progress(
|
||||
self,
|
||||
username: str,
|
||||
game_id: int,
|
||||
*,
|
||||
include_award_metadata: bool = False,
|
||||
) -> RAGameInfoAndUserProgress:
|
||||
"""Retrieve extended metadata about a game, in addition to a user's progress about that game.
|
||||
|
||||
Reference: https://api-docs.retroachievements.org/v1/get-game-info-and-user-progress.html
|
||||
"""
|
||||
params: dict[str, list[str]] = {
|
||||
"u": [username],
|
||||
"g": [str(game_id)],
|
||||
}
|
||||
if include_award_metadata:
|
||||
params["a"] = ["1"]
|
||||
|
||||
url = self.url.joinpath("API_GetGameInfoAndUserProgress.php").with_query(
|
||||
**params
|
||||
)
|
||||
response = await self._request(str(url))
|
||||
return cast(RAGameInfoAndUserProgress, response)
|
||||
@@ -4,16 +4,12 @@ import json
|
||||
import os
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from typing import Final, NotRequired, TypedDict, cast
|
||||
from typing import Final, NotRequired, TypedDict
|
||||
|
||||
import httpx
|
||||
import yarl
|
||||
from adapters.services.retroachievements_types import (
|
||||
RAGameExtendedDetails,
|
||||
RAGameInfoAndUserProgress,
|
||||
RAGameListItem,
|
||||
RAUserCompletionProgress,
|
||||
)
|
||||
from adapters.services.retroachievements import RetroAchievementsService
|
||||
from adapters.services.retroachievements_types import RAGameListItem
|
||||
from anyio import open_file
|
||||
from config import (
|
||||
REFRESH_RETROACHIEVEMENTS_CACHE_DAYS,
|
||||
@@ -83,15 +79,7 @@ class RAUserProgression(TypedDict):
|
||||
|
||||
class RAHandler(MetadataHandler):
|
||||
def __init__(self) -> None:
|
||||
self.BASE_URL = "https://retroachievements.org/API"
|
||||
self.search_endpoint = f"{self.BASE_URL}/API_GetGameList.php"
|
||||
self.game_details_endpoint = f"{self.BASE_URL}/API_GetGameExtended.php"
|
||||
self.user_complete_progression_endpoint = (
|
||||
f"{self.BASE_URL}/API_GetUserCompletionProgress.php"
|
||||
)
|
||||
self.user_game_progression_endpoint = (
|
||||
f"{self.BASE_URL}/API_GetGameInfoAndUserProgress.php"
|
||||
)
|
||||
self.ra_service = RetroAchievementsService()
|
||||
self.HASHES_FILE_NAME = "ra_hashes.json"
|
||||
|
||||
def _get_rom_base_path(self, platform_id: int, rom_id: int) -> str:
|
||||
@@ -199,13 +187,6 @@ class RAHandler(MetadataHandler):
|
||||
|
||||
self._create_resources_path(platform.id, rom_id)
|
||||
|
||||
url = yarl.URL(self.search_endpoint).with_query(
|
||||
i=[platform.ra_id],
|
||||
f=["1"], # If 1, only return games that have achievements. Defaults to 0.
|
||||
h=["1"], # If 1, also return supported hashes for games. Defaults to 0.
|
||||
y=[RETROACHIEVEMENTS_API_KEY],
|
||||
)
|
||||
|
||||
# Fetch all hashes for specific platform
|
||||
roms: list[RAGameListItem]
|
||||
if (
|
||||
@@ -214,7 +195,11 @@ class RAHandler(MetadataHandler):
|
||||
or not self._exists_cache_file(platform.id)
|
||||
):
|
||||
# Write the roms result to a JSON file if older than REFRESH_RETROACHIEVEMENTS_CACHE_DAYS days
|
||||
roms = cast(list[RAGameListItem], await self._request(str(url)))
|
||||
roms = await self.ra_service.get_game_list(
|
||||
system_id=platform.ra_id,
|
||||
only_games_with_achievements=True,
|
||||
include_hashes=True,
|
||||
)
|
||||
async with await open_file(
|
||||
self._get_hashes_file_path(platform.id),
|
||||
"w",
|
||||
@@ -236,13 +221,6 @@ class RAHandler(MetadataHandler):
|
||||
|
||||
return None
|
||||
|
||||
async def _get_rom_details(self, ra_id: int) -> RAGameExtendedDetails:
|
||||
url = yarl.URL(self.game_details_endpoint).with_query(
|
||||
i=[ra_id],
|
||||
y=[RETROACHIEVEMENTS_API_KEY],
|
||||
)
|
||||
return cast(RAGameExtendedDetails, await self._request(str(url)))
|
||||
|
||||
def get_platform(self, slug: str) -> RAGamesPlatform:
|
||||
platform = SLUG_TO_RA_ID.get(slug.lower(), None)
|
||||
|
||||
@@ -265,7 +243,7 @@ class RAHandler(MetadataHandler):
|
||||
return RAGameRom(ra_id=None)
|
||||
|
||||
try:
|
||||
rom_details = await self._get_rom_details(rom["ID"])
|
||||
rom_details = await self.ra_service.get_game_extended_details(rom["ID"])
|
||||
return RAGameRom(
|
||||
ra_id=rom["ID"],
|
||||
ra_metadata=RAMetadata(
|
||||
@@ -295,23 +273,19 @@ class RAHandler(MetadataHandler):
|
||||
return RAGameRom(ra_id=None)
|
||||
|
||||
async def get_user_progression(self, username: str) -> RAUserProgression:
|
||||
url = yarl.URL(self.user_complete_progression_endpoint).with_query(
|
||||
u=[username], y=[RETROACHIEVEMENTS_API_KEY], c=[500]
|
||||
)
|
||||
user_complete_progression = cast(
|
||||
RAUserCompletionProgress, await self._request(str(url))
|
||||
user_complete_progression = await self.ra_service.get_user_completion_progress(
|
||||
username=username,
|
||||
limit=500,
|
||||
)
|
||||
roms_with_progression = user_complete_progression.get("Results", [])
|
||||
rom_earned_achievements: dict[int, list[EarnedAchievement]] = defaultdict(list)
|
||||
for rom in roms_with_progression:
|
||||
rom_game_id = rom.get("GameID")
|
||||
if rom_game_id:
|
||||
url = yarl.URL(self.user_game_progression_endpoint).with_query(
|
||||
g=[rom_game_id],
|
||||
u=[username],
|
||||
y=[RETROACHIEVEMENTS_API_KEY],
|
||||
result = await self.ra_service.get_user_game_progress(
|
||||
username=username,
|
||||
game_id=rom_game_id,
|
||||
)
|
||||
result = cast(RAGameInfoAndUserProgress, await self._request(str(url)))
|
||||
for achievement in result.get("Achievements", {}).values():
|
||||
if achievement.get("DateEarned") and achievement.get("BadgeName"):
|
||||
rom_earned_achievements[rom_game_id].append(
|
||||
|
||||
Reference in new issue
Block a user