igdb.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import json
  2. import logging
  3. from datetime import datetime
  4. from typing import Dict, Tuple
  5. from django.conf import settings
  6. import pytz
  7. import requests
  8. from django.contrib.auth import get_user_model
  9. TWITCH_AUTH_BASE = "https://id.twitch.tv/"
  10. REFRESH_TOKEN_URL = (
  11. TWITCH_AUTH_BASE
  12. + "oauth2/token?client_id={id}&client_secret={secret}&grant_type=client_credentials"
  13. )
  14. SEARCH_URL = "https://api.igdb.com/v4/search"
  15. GAMES_URL = "https://api.igdb.com/v4/games"
  16. ALT_NAMES_URL = "https://api.igdb.com/v4/alternative_names"
  17. SCREENSHOT_URL = "https://api.igdb.com/v4/screenshots"
  18. COVER_URL = "https://api.igdb.com/v4/covers"
  19. IGDB_CLIENT_ID = getattr(settings, "IGDB_CLIENT_ID")
  20. IGDB_CLIENT_SECRET = getattr(settings, "IGDB_CLIENT_SECRET")
  21. logger = logging.getLogger(__name__)
  22. User = get_user_model()
  23. def get_igdb_token() -> str:
  24. token_url = REFRESH_TOKEN_URL.format(
  25. id=IGDB_CLIENT_ID, secret=IGDB_CLIENT_SECRET
  26. )
  27. response = requests.post(token_url)
  28. results = json.loads(response.content)
  29. return results.get("access_token")
  30. def lookup_game_id_from_gdb(name: str) -> str:
  31. headers = {
  32. "Authorization": f"Bearer {get_igdb_token()}",
  33. "Client-ID": IGDB_CLIENT_ID,
  34. }
  35. body = f'fields name,game,published_at; search "{name}"; limit 20;'
  36. response = requests.post(SEARCH_URL, data=body, headers=headers)
  37. results = json.loads(response.content)
  38. if not results:
  39. logger.warn(f"Search of game on IGDB failed for name {name}")
  40. return ""
  41. return results[0]["game"]
  42. def lookup_game_from_igdb(igdb_id: str) -> Dict:
  43. """Given credsa and an IGDB game ID, lookup the game metadata and return it
  44. in a dictionary mapped to our internal game fields
  45. """
  46. headers = {
  47. "Authorization": f"Bearer {get_igdb_token()}",
  48. "Client-ID": IGDB_CLIENT_ID,
  49. }
  50. fields = "id,name,alternative_names.*,release_dates.*,cover.*,screenshots.*,rating,rating_count,summary"
  51. game_dict = {}
  52. body = f"fields {fields}; where id = {igdb_id};"
  53. response = requests.post(GAMES_URL, data=body, headers=headers)
  54. results = json.loads(response.content)
  55. if not results:
  56. logger.warn(f"Lookup of game on IGDB failed for ID {igdb_id}")
  57. return game_dict
  58. game = results[0]
  59. alt_name = None
  60. if "alternative_names" in game.keys():
  61. alt_name = game.get("alternative_names")[0].get("name")
  62. screenshot_url = None
  63. if "screenshots" in game.keys():
  64. screenshot_url = "https:" + game.get("screenshots")[0].get(
  65. "url"
  66. ).replace("t_thumb", "t_screenshot_big_2x")
  67. cover_url = None
  68. if "cover" in game.keys():
  69. cover_url = "https:" + game.get("cover").get("url").replace(
  70. "t_thumb", "t_cover_big_2x"
  71. )
  72. release_date = None
  73. if "release_dates" in game.keys():
  74. release_date = game.get("release_dates")[0].get("date")
  75. if release_date:
  76. release_date = datetime.utcfromtimestamp(release_date).replace(
  77. tzinfo=pytz.utc
  78. )
  79. game_dict = {
  80. "igdb_id": game.get("id"),
  81. "title": game.get("name"),
  82. "alternative_name": alt_name,
  83. "screenshot_url": screenshot_url,
  84. "cover_url": cover_url,
  85. "rating": game.get("rating"),
  86. "rating_count": game.get("rating_count"),
  87. "release_date": release_date,
  88. "summary": game.get("summary"),
  89. }
  90. return game_dict