|
| 1 | +import asyncio |
| 2 | +import http |
| 3 | +import json |
| 4 | +from collections.abc import Sequence |
| 5 | +from functools import partial |
| 6 | +from typing import TYPE_CHECKING |
| 7 | + |
| 8 | +import aiohttp |
| 9 | +import yarl |
| 10 | +from aiohttp.client import ClientTimeout |
| 11 | +from fastapi import HTTPException, status |
| 12 | +from unidecode import unidecode |
| 13 | + |
| 14 | +from adapters.services.igdb_types import Game |
| 15 | +from config import IGDB_CLIENT_ID |
| 16 | +from logger.logger import log |
| 17 | +from utils.context import ctx_aiohttp_session |
| 18 | + |
| 19 | +if TYPE_CHECKING: |
| 20 | + from handler.metadata.igdb_handler import TwitchAuth |
| 21 | + |
| 22 | + |
| 23 | +class IGDBInvalidCredentialsException(Exception): |
| 24 | + """Exception raised when IGDB credentials are invalid.""" |
| 25 | + |
| 26 | + |
| 27 | +async def auth_middleware( |
| 28 | + req: aiohttp.ClientRequest, |
| 29 | + handler: aiohttp.ClientHandlerType, |
| 30 | + *, |
| 31 | + twitch_auth: "TwitchAuth", |
| 32 | +) -> aiohttp.ClientResponse: |
| 33 | + """IGDB API authentication mechanism. |
| 34 | +
|
| 35 | + Reference: https://api-docs.igdb.com/#authentication |
| 36 | + """ |
| 37 | + token = await twitch_auth.get_oauth_token() |
| 38 | + if not token: |
| 39 | + raise IGDBInvalidCredentialsException() |
| 40 | + req.headers.update( |
| 41 | + { |
| 42 | + "Accept": "application/json", |
| 43 | + "Authorization": f"Bearer {token}", |
| 44 | + "Client-ID": IGDB_CLIENT_ID, |
| 45 | + } |
| 46 | + ) |
| 47 | + return await handler(req) |
| 48 | + |
| 49 | + |
| 50 | +class IGDBService: |
| 51 | + """Service to interact with the IGDB API. |
| 52 | +
|
| 53 | + Reference: https://api-docs.igdb.com/ |
| 54 | + """ |
| 55 | + |
| 56 | + def __init__( |
| 57 | + self, |
| 58 | + twitch_auth: "TwitchAuth", |
| 59 | + base_url: str | None = None, |
| 60 | + ) -> None: |
| 61 | + self.url = yarl.URL(base_url or "https://api.igdb.com/v4") |
| 62 | + self.twitch_auth = twitch_auth |
| 63 | + self.auth_middleware = partial(auth_middleware, twitch_auth=self.twitch_auth) |
| 64 | + |
| 65 | + async def _request( |
| 66 | + self, |
| 67 | + url: str, |
| 68 | + search_term: str | None = None, |
| 69 | + fields: Sequence[str] | None = None, |
| 70 | + where: str | None = None, |
| 71 | + limit: int | None = None, |
| 72 | + request_timeout: int = 120, |
| 73 | + ) -> list: |
| 74 | + aiohttp_session = ctx_aiohttp_session.get() |
| 75 | + |
| 76 | + content = "" |
| 77 | + if search_term: |
| 78 | + content += f'search "{unidecode(search_term)}"; ' |
| 79 | + if fields: |
| 80 | + content += f"fields {','.join(fields)}; " |
| 81 | + if where: |
| 82 | + content += f"where {where}; " |
| 83 | + if limit is not None: |
| 84 | + content += f"limit {limit}; " |
| 85 | + content = content.strip() |
| 86 | + |
| 87 | + log.debug( |
| 88 | + "API request: URL=%s, Content=%s, Timeout=%s", |
| 89 | + url, |
| 90 | + content, |
| 91 | + request_timeout, |
| 92 | + ) |
| 93 | + |
| 94 | + try: |
| 95 | + res = await aiohttp_session.post( |
| 96 | + url, |
| 97 | + data=content, |
| 98 | + middlewares=(self.auth_middleware,), |
| 99 | + timeout=ClientTimeout(total=request_timeout), |
| 100 | + ) |
| 101 | + res.raise_for_status() |
| 102 | + return await res.json() |
| 103 | + except aiohttp.ServerTimeoutError: |
| 104 | + # Retry the request once if it times out |
| 105 | + log.debug("Request to URL=%s timed out. Retrying...", url) |
| 106 | + except IGDBInvalidCredentialsException as exc: |
| 107 | + log.critical("IGDB Error: Invalid IGDB_CLIENT_ID or IGDB_CLIENT_SECRET") |
| 108 | + raise HTTPException( |
| 109 | + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, |
| 110 | + detail="Invalid IGDB credentials", |
| 111 | + ) from exc |
| 112 | + except aiohttp.ClientConnectionError as exc: |
| 113 | + log.critical("Connection error: can't connect to IGDB", exc_info=True) |
| 114 | + raise HTTPException( |
| 115 | + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, |
| 116 | + detail="Can't connect to IGDB, check your internet connection", |
| 117 | + ) from exc |
| 118 | + except aiohttp.ClientResponseError as exc: |
| 119 | + if exc.status == http.HTTPStatus.UNAUTHORIZED: |
| 120 | + # Refresh the token and retry if the auth token is invalid |
| 121 | + log.info("Twitch token invalid: fetching a new one...") |
| 122 | + await self.twitch_auth._update_twitch_token() |
| 123 | + elif exc.status == http.HTTPStatus.TOO_MANY_REQUESTS: |
| 124 | + # Retry after 2 seconds if rate limit hit |
| 125 | + await asyncio.sleep(2) |
| 126 | + else: |
| 127 | + # Log the error and return an empty list if the request fails with a different code |
| 128 | + log.error(exc) |
| 129 | + return [] |
| 130 | + except json.JSONDecodeError as exc: |
| 131 | + log.error("Error decoding JSON response from IGDB: %s", exc) |
| 132 | + return [] |
| 133 | + |
| 134 | + # Retry the request once if it times out |
| 135 | + try: |
| 136 | + log.debug( |
| 137 | + "API request: URL=%s, Content=%s, Timeout=%s", |
| 138 | + url, |
| 139 | + content, |
| 140 | + request_timeout, |
| 141 | + ) |
| 142 | + res = await aiohttp_session.post( |
| 143 | + url, |
| 144 | + data=content, |
| 145 | + middlewares=(self.auth_middleware,), |
| 146 | + timeout=ClientTimeout(total=request_timeout), |
| 147 | + ) |
| 148 | + res.raise_for_status() |
| 149 | + return await res.json() |
| 150 | + except (aiohttp.ClientResponseError, aiohttp.ServerTimeoutError) as exc: |
| 151 | + if ( |
| 152 | + isinstance(exc, aiohttp.ClientResponseError) |
| 153 | + and exc.status == http.HTTPStatus.UNAUTHORIZED |
| 154 | + ): |
| 155 | + return [] |
| 156 | + |
| 157 | + log.error(exc) |
| 158 | + return [] |
| 159 | + except json.JSONDecodeError as exc: |
| 160 | + log.error("Error decoding JSON response from IGDB: %s", exc) |
| 161 | + return [] |
| 162 | + |
| 163 | + async def list_games( |
| 164 | + self, |
| 165 | + *, |
| 166 | + search_term: str | None = None, |
| 167 | + fields: Sequence[str] | None = None, |
| 168 | + where: str | None = None, |
| 169 | + limit: int | None = None, |
| 170 | + ) -> list[Game]: |
| 171 | + """Retrieve games. |
| 172 | +
|
| 173 | + Reference: https://api-docs.igdb.com/#game |
| 174 | + """ |
| 175 | + url = self.url.joinpath("games") |
| 176 | + return await self._request( |
| 177 | + str(url), |
| 178 | + search_term=search_term, |
| 179 | + fields=fields, |
| 180 | + where=where, |
| 181 | + limit=limit, |
| 182 | + ) |
| 183 | + |
| 184 | + async def search( |
| 185 | + self, |
| 186 | + *, |
| 187 | + search_term: str | None = None, |
| 188 | + fields: Sequence[str] | None = None, |
| 189 | + where: str | None = None, |
| 190 | + limit: int | None = None, |
| 191 | + ) -> list[dict]: |
| 192 | + """Search for different entities. |
| 193 | +
|
| 194 | + Reference: https://api-docs.igdb.com/#search |
| 195 | + """ |
| 196 | + url = self.url.joinpath("search") |
| 197 | + return await self._request( |
| 198 | + str(url), |
| 199 | + search_term=search_term, |
| 200 | + fields=fields, |
| 201 | + where=where, |
| 202 | + limit=limit, |
| 203 | + ) |
0 commit comments