mirror of
https://github.com/rommapp/romm.git
synced 2026-12-04 21:02:21 +01:00
refactor(steam): share one Steam Web API client between library import and achievements
The library import's `SteamWebAPIService` folds into `SteamWebApiService` in adapters/services/steam.py. Its requests raise `SteamWebAPIError` with the messages the link and sync flows show; the achievement calls catch that error and degrade to no achievements. The key comes from the shared middleware instead of a constructor argument. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NH5s4hBCkRF6nyKoFy6MXw
This commit is contained in:
@@ -13,10 +13,15 @@ from adapters.services.steam_types import (
|
||||
SteamAppDetailsEnvelope,
|
||||
SteamGlobalAchievementPercent,
|
||||
SteamGlobalAchievementPercentagesResponse,
|
||||
SteamOwnedGame,
|
||||
SteamOwnedGamesResponse,
|
||||
SteamPlayerSummariesResponse,
|
||||
SteamPlayerSummary,
|
||||
SteamSchemaAchievement,
|
||||
SteamSchemaForGameResponse,
|
||||
SteamStoreSearchItem,
|
||||
SteamStoreSearchResponse,
|
||||
SteamVanityResponse,
|
||||
)
|
||||
from config import STEAM_API_KEY
|
||||
from logger.logger import log
|
||||
@@ -34,6 +39,8 @@ _rate_limiter = RateLimiter(STEAM_MAX_REQUESTS_PER_SECOND)
|
||||
# The Web API allows 100,000 calls a day per key, with no documented burst limit.
|
||||
STEAM_WEB_API_MAX_REQUESTS_PER_SECOND: Final[float] = 4
|
||||
_web_api_rate_limiter = RateLimiter(STEAM_WEB_API_MAX_REQUESTS_PER_SECOND)
|
||||
# ResolveVanityURL's `success` when the name belongs to a profile.
|
||||
STEAM_VANITY_RESOLVED: Final[int] = 1
|
||||
|
||||
# Undocumented conventions, so an app can have no asset at these URLs.
|
||||
STEAM_LIBRARY_CAPSULE_URL = (
|
||||
@@ -199,6 +206,10 @@ async def web_api_key_middleware(
|
||||
return await handler(req)
|
||||
|
||||
|
||||
class SteamWebAPIError(Exception):
|
||||
"""The Steam Web API refused a request or could not be reached."""
|
||||
|
||||
|
||||
class SteamWebApiService:
|
||||
"""Service to interact with the keyed Steam Web API.
|
||||
|
||||
@@ -210,7 +221,13 @@ class SteamWebApiService:
|
||||
|
||||
async def _request[T](
|
||||
self, url: yarl.URL, tp: type[T], request_timeout: int = 60
|
||||
) -> T | None:
|
||||
) -> T:
|
||||
"""Fetch one method's reply.
|
||||
|
||||
Raises:
|
||||
SteamWebAPIError: Steam refused the request, could not be reached, or
|
||||
sent a reply that could not be read.
|
||||
"""
|
||||
aiohttp_session = ctx_aiohttp_session.get()
|
||||
|
||||
async def send() -> T | None:
|
||||
@@ -229,23 +246,36 @@ class SteamWebApiService:
|
||||
)
|
||||
|
||||
try:
|
||||
return await send_with_retries(
|
||||
response = await send_with_retries(
|
||||
send,
|
||||
provider="Steam Web API",
|
||||
url=str(url),
|
||||
attempts=STEAM_MAX_REQUEST_ATTEMPTS,
|
||||
backoff=STEAM_RATE_LIMIT_BACKOFF_SECONDS,
|
||||
)
|
||||
except TimeoutError:
|
||||
log.debug("Request to URL=%s timed out on every attempt", url)
|
||||
return None
|
||||
except TimeoutError as exc:
|
||||
raise SteamWebAPIError("Steam did not answer in time") from exc
|
||||
# A connection failure arrives as the 503 `send_with_retries` raises.
|
||||
except (aiohttp.ClientError, HTTPException) as exc:
|
||||
log.error(exc)
|
||||
return None
|
||||
# Also a body that is not UTF-8, which `json` raises as a UnicodeDecodeError.
|
||||
except ValueError as exc:
|
||||
log.error("Error decoding JSON response from Steam Web API: %s", exc)
|
||||
except HTTPException as exc:
|
||||
raise SteamWebAPIError("Can't connect to Steam") from exc
|
||||
except aiohttp.ClientResponseError as exc:
|
||||
if exc.status in (401, 403):
|
||||
raise SteamWebAPIError("Steam rejected the API key") from exc
|
||||
raise SteamWebAPIError(f"Steam answered with HTTP {exc.status}") from exc
|
||||
# Also a truncated body, or one that is not UTF-8 JSON.
|
||||
except (aiohttp.ClientError, ValueError) as exc:
|
||||
raise SteamWebAPIError("Steam sent a reply that could not be read") from exc
|
||||
|
||||
if response is None:
|
||||
raise SteamWebAPIError("Steam sent a reply that could not be read")
|
||||
return response
|
||||
|
||||
async def _optional_request[T](self, url: yarl.URL, tp: type[T]) -> T | None:
|
||||
"""Fetch an optional extra, logging a failure instead of raising it."""
|
||||
try:
|
||||
return await self._request(url, tp)
|
||||
except SteamWebAPIError as exc:
|
||||
log.error("Steam Web API %s failed: %s", url.parent.parent.name, exc)
|
||||
return None
|
||||
|
||||
async def get_schema_achievements(
|
||||
@@ -255,7 +285,7 @@ class SteamWebApiService:
|
||||
url = self.url.joinpath("ISteamUserStats/GetSchemaForGame/v2/").with_query(
|
||||
appid=str(app_id), l=language
|
||||
)
|
||||
response = await self._request(url, SteamSchemaForGameResponse)
|
||||
response = await self._optional_request(url, SteamSchemaForGameResponse)
|
||||
if not response:
|
||||
return []
|
||||
|
||||
@@ -269,8 +299,39 @@ class SteamWebApiService:
|
||||
url = self.url.joinpath(
|
||||
"ISteamUserStats/GetGlobalAchievementPercentagesForApp/v2/"
|
||||
).with_query(gameid=str(app_id))
|
||||
response = await self._request(url, SteamGlobalAchievementPercentagesResponse)
|
||||
response = await self._optional_request(
|
||||
url, SteamGlobalAchievementPercentagesResponse
|
||||
)
|
||||
if not response:
|
||||
return []
|
||||
|
||||
return response.get("achievementpercentages", {}).get("achievements") or []
|
||||
|
||||
async def resolve_vanity_url(self, vanity_name: str) -> str | None:
|
||||
"""The SteamID64 behind a custom profile URL name, or None if unused."""
|
||||
url = self.url.joinpath("ISteamUser/ResolveVanityURL/v1/").with_query(
|
||||
vanityurl=vanity_name
|
||||
)
|
||||
result = (await self._request(url, SteamVanityResponse)).get("response", {})
|
||||
if result.get("success") != STEAM_VANITY_RESOLVED:
|
||||
return None
|
||||
return result.get("steamid")
|
||||
|
||||
async def get_player_summary(self, steam_id: str) -> SteamPlayerSummary | None:
|
||||
"""The public profile of a SteamID64, or None if no account has it."""
|
||||
url = self.url.joinpath("ISteamUser/GetPlayerSummaries/v2/").with_query(
|
||||
steamids=steam_id
|
||||
)
|
||||
response = await self._request(url, SteamPlayerSummariesResponse)
|
||||
players = response.get("response", {}).get("players", [])
|
||||
return players[0] if players else None
|
||||
|
||||
async def get_owned_games(self, steam_id: str) -> list[SteamOwnedGame] | None:
|
||||
"""Every game the account owns, or None when its game details are private."""
|
||||
url = self.url.joinpath("IPlayerService/GetOwnedGames/v1/").with_query(
|
||||
steamid=steam_id, include_appinfo="1", include_played_free_games="1"
|
||||
)
|
||||
result = (await self._request(url, SteamOwnedGamesResponse)).get("response", {})
|
||||
if "game_count" not in result:
|
||||
return None
|
||||
return result.get("games", [])
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
import json
|
||||
from typing import Final
|
||||
|
||||
import aiohttp
|
||||
import yarl
|
||||
from aiohttp.client import ClientTimeout
|
||||
from fastapi import HTTPException
|
||||
|
||||
from adapters.services.provider_http import send_with_retries
|
||||
from adapters.services.response_validation import parse_response
|
||||
from adapters.services.steam_types import (
|
||||
SteamOwnedGame,
|
||||
SteamOwnedGamesResponse,
|
||||
SteamPlayerSummariesResponse,
|
||||
SteamPlayerSummary,
|
||||
SteamVanityResponse,
|
||||
)
|
||||
from logger.logger import log
|
||||
from utils import get_version
|
||||
from utils.context import ctx_aiohttp_session
|
||||
|
||||
STEAM_WEB_API_URL: Final[str] = "https://api.steampowered.com"
|
||||
STEAM_VANITY_RESOLVED: Final[int] = 1
|
||||
STEAM_PROFILE_PUBLIC: Final[int] = 3
|
||||
|
||||
|
||||
class SteamWebAPIError(Exception):
|
||||
"""The Steam Web API refused a request or could not be reached."""
|
||||
|
||||
|
||||
class SteamWebAPIService:
|
||||
"""Client for the keyed Steam Web API, which reads a player's account."""
|
||||
|
||||
def __init__(self, api_key: str, base_url: str | None = None) -> None:
|
||||
self.api_key = api_key
|
||||
self.url = yarl.URL(base_url or STEAM_WEB_API_URL)
|
||||
|
||||
async def _request[T](
|
||||
self, path: str, tp: type[T], params: dict[str, str], request_timeout: int = 60
|
||||
) -> T:
|
||||
aiohttp_session = ctx_aiohttp_session.get()
|
||||
url = self.url.joinpath(path).with_query({**params, "key": self.api_key})
|
||||
|
||||
async def send() -> T | None:
|
||||
# The query carries the API key, so only the path is logged.
|
||||
log.debug("Steam Web API request: %s", path)
|
||||
res = await aiohttp_session.get(
|
||||
url,
|
||||
headers={"user-agent": f"RomM/{get_version()}"},
|
||||
timeout=ClientTimeout(total=request_timeout),
|
||||
)
|
||||
res.raise_for_status()
|
||||
return parse_response(tp, await res.read(), source=f"Steam {path}")
|
||||
|
||||
try:
|
||||
response = await send_with_retries(send, provider="Steam", url=path)
|
||||
except TimeoutError as exc:
|
||||
raise SteamWebAPIError("Steam did not answer in time") from exc
|
||||
except HTTPException as exc:
|
||||
raise SteamWebAPIError("Can't connect to Steam") from exc
|
||||
except json.JSONDecodeError as exc:
|
||||
raise SteamWebAPIError("Steam sent a reply that could not be read") from exc
|
||||
except aiohttp.ClientResponseError as exc:
|
||||
if exc.status in (401, 403):
|
||||
raise SteamWebAPIError("Steam rejected the API key") from exc
|
||||
raise SteamWebAPIError(f"Steam answered with HTTP {exc.status}") from exc
|
||||
|
||||
if response is None:
|
||||
raise SteamWebAPIError("Steam sent a reply that could not be read")
|
||||
return response
|
||||
|
||||
async def resolve_vanity_url(self, vanity_name: str) -> str | None:
|
||||
"""The SteamID64 behind a custom profile URL name, or None if unused."""
|
||||
response = await self._request(
|
||||
"ISteamUser/ResolveVanityURL/v1/",
|
||||
SteamVanityResponse,
|
||||
{"vanityurl": vanity_name},
|
||||
)
|
||||
result = response.get("response", {})
|
||||
if result.get("success") != STEAM_VANITY_RESOLVED:
|
||||
return None
|
||||
return result.get("steamid")
|
||||
|
||||
async def get_player_summary(self, steam_id: str) -> SteamPlayerSummary | None:
|
||||
"""The public profile of a SteamID64, or None if no account has it."""
|
||||
response = await self._request(
|
||||
"ISteamUser/GetPlayerSummaries/v2/",
|
||||
SteamPlayerSummariesResponse,
|
||||
{"steamids": steam_id},
|
||||
)
|
||||
players = response.get("response", {}).get("players", [])
|
||||
return players[0] if players else None
|
||||
|
||||
async def get_owned_games(self, steam_id: str) -> list[SteamOwnedGame] | None:
|
||||
"""Every game the account owns, or None when its game details are private."""
|
||||
response = await self._request(
|
||||
"IPlayerService/GetOwnedGames/v1/",
|
||||
SteamOwnedGamesResponse,
|
||||
{
|
||||
"steamid": steam_id,
|
||||
"include_appinfo": "1",
|
||||
"include_played_free_games": "1",
|
||||
},
|
||||
)
|
||||
result = response.get("response", {})
|
||||
if "game_count" not in result:
|
||||
return None
|
||||
return result.get("games", [])
|
||||
@@ -8,8 +8,8 @@ from typing import Final
|
||||
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from adapters.services.steam import SteamWebAPIError, SteamWebApiService
|
||||
from adapters.services.steam_types import SteamOwnedGame, SteamPlayerSummary
|
||||
from adapters.services.steam_web_api import SteamWebAPIError, SteamWebAPIService
|
||||
from config import STEAM_API_KEY
|
||||
from exceptions.fs_exceptions import PlatformAlreadyExistsException
|
||||
from handler.database import (
|
||||
@@ -56,10 +56,10 @@ class SteamSyncResult:
|
||||
unmatched_rom_ids: list[int] = field(default_factory=list)
|
||||
|
||||
|
||||
def steam_web_api() -> SteamWebAPIService:
|
||||
def steam_web_api() -> SteamWebApiService:
|
||||
if not STEAM_API_KEY:
|
||||
raise SteamLibraryError("Set STEAM_API_KEY to import Steam libraries")
|
||||
return SteamWebAPIService(STEAM_API_KEY)
|
||||
return SteamWebApiService()
|
||||
|
||||
|
||||
def parse_steam_profile(profile: str) -> tuple[str | None, str | None]:
|
||||
|
||||
@@ -4,7 +4,11 @@ from unittest.mock import AsyncMock, MagicMock, patch
|
||||
import aiohttp
|
||||
import pytest
|
||||
|
||||
from adapters.services.steam_web_api import SteamWebAPIError, SteamWebAPIService
|
||||
from adapters.services.steam import (
|
||||
SteamWebAPIError,
|
||||
SteamWebApiService,
|
||||
web_api_key_middleware,
|
||||
)
|
||||
|
||||
STEAM_ID = "76561197960287930"
|
||||
|
||||
@@ -31,26 +35,28 @@ def no_backoff_sleep():
|
||||
@pytest.fixture
|
||||
def session():
|
||||
mock_session = AsyncMock()
|
||||
with patch("adapters.services.steam_web_api.ctx_aiohttp_session") as mock_ctx:
|
||||
with patch("adapters.services.steam.ctx_aiohttp_session") as mock_ctx:
|
||||
mock_ctx.get.return_value = mock_session
|
||||
yield mock_session
|
||||
|
||||
|
||||
def _service() -> SteamWebAPIService:
|
||||
return SteamWebAPIService("secret-key")
|
||||
def _service() -> SteamWebApiService:
|
||||
return SteamWebApiService()
|
||||
|
||||
|
||||
async def test_sends_the_key_and_parameters(session):
|
||||
async def test_sends_the_parameters_with_the_key_middleware(session):
|
||||
session.get.return_value = _response(
|
||||
{"response": {"success": 1, "steamid": STEAM_ID}}
|
||||
)
|
||||
|
||||
await _service().resolve_vanity_url("gabe")
|
||||
|
||||
url = session.get.await_args.args[0]
|
||||
await_args = session.get.await_args
|
||||
url = await_args.args[0]
|
||||
assert url.path == "/ISteamUser/ResolveVanityURL/v1/"
|
||||
assert url.query["key"] == "secret-key"
|
||||
assert url.query["vanityurl"] == "gabe"
|
||||
assert "key" not in url.query
|
||||
assert await_args.kwargs["middlewares"] == (web_api_key_middleware,)
|
||||
|
||||
|
||||
async def test_resolves_a_custom_name(session):
|
||||
|
||||
@@ -4,8 +4,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
|
||||
import pytest
|
||||
from tests.factories import make_platform, make_rom
|
||||
|
||||
from adapters.services.steam import SteamWebAPIError
|
||||
from adapters.services.steam_types import SteamOwnedGame
|
||||
from adapters.services.steam_web_api import SteamWebAPIError
|
||||
from handler.database import (
|
||||
db_collection_handler,
|
||||
db_platform_handler,
|
||||
|
||||
@@ -1974,14 +1974,14 @@ Falls back to `FakeRedis` in test mode.
|
||||
|
||||
#### API Keys
|
||||
|
||||
| Variable | Description |
|
||||
| ----------------------------------------------- | ---------------------------- |
|
||||
| `IGDB_CLIENT_ID` + `IGDB_CLIENT_SECRET` | IGDB (via Twitch) |
|
||||
| `MOBYGAMES_API_KEY` | MobyGames |
|
||||
| `SCREENSCRAPER_USER` + `SCREENSCRAPER_PASSWORD` | ScreenScraper |
|
||||
| `STEAMGRIDDB_API_KEY` | SteamGridDB |
|
||||
| `RETROACHIEVEMENTS_API_KEY` | RetroAchievements |
|
||||
| `STEAM_API_KEY` | Steam Web API (achievements) |
|
||||
| Variable | Description |
|
||||
| ----------------------------------------------- | -------------------------------------------- |
|
||||
| `IGDB_CLIENT_ID` + `IGDB_CLIENT_SECRET` | IGDB (via Twitch) |
|
||||
| `MOBYGAMES_API_KEY` | MobyGames |
|
||||
| `SCREENSCRAPER_USER` + `SCREENSCRAPER_PASSWORD` | ScreenScraper |
|
||||
| `STEAMGRIDDB_API_KEY` | SteamGridDB |
|
||||
| `RETROACHIEVEMENTS_API_KEY` | RetroAchievements |
|
||||
| `STEAM_API_KEY` | Steam Web API (library import, achievements) |
|
||||
|
||||
#### Feature Toggles
|
||||
|
||||
|
||||
Reference in New Issue
Block a user