Merge pull request #311 from zurdi15/fix-case-sensitive-platforms

Fix case sensitive platforms
This commit is contained in:
Zurdi
2023-08-01 14:06:37 +02:00
committed by GitHub
5 changed files with 74 additions and 56 deletions

View File

@@ -1,7 +1,7 @@
import sys
import functools
from unidecode import unidecode as uc
from time import time
from unidecode import unidecode as uc
import requests
from config import CLIENT_ID, CLIENT_SECRET
@@ -23,7 +23,7 @@ class IGDBHandler():
'Authorization': f'Bearer {self.twitch_auth.get_oauth_token()}',
'Accept': 'application/json'
}
def check_twitch_token(func) -> tuple:
@functools.wraps(func)
@@ -31,47 +31,56 @@ class IGDBHandler():
args[0].headers['Authorization'] = f'Bearer {args[0].twitch_auth.get_oauth_token()}'
return func(*args)
return wrapper
def _search_rom(self, search_term: str, p_igdb_id: str, category: int = None) -> dict:
category_filter: str = f"& category={category}" if category else ""
try:
return requests.post(self.games_url, headers=self.headers,
data=f"search \"{search_term}\"; \
fields id, slug, name, summary, screenshots; \
where platforms=[{p_igdb_id}] {category_filter};").json()[0]
except IndexError:
return {}
def _search_rom(self, search_term: str, p_igdb_id: int, category: int = None) -> dict:
category_filter: str = f"& category={category}" if category else ""
try:
return requests.post(self.games_url,
headers=self.headers,
data=f"""search \"{search_term}\";
fields id, slug, name, summary, screenshots;
where platforms=[{p_igdb_id}] {category_filter};""",
timeout=120).json()[0]
except IndexError:
return {}
@staticmethod
def _normalize_cover_url(url: str) -> str:
url = f"https:{url.replace('https:', '')}"
return url
return f"https:{url.replace('https:', '')}"
def _search_cover(self, rom_id: str) -> str:
try:
res: dict = requests.post(self.covers_url, headers=self.headers,
data=f"fields url; where game={rom_id};").json()[0]
res: dict = requests.post(self.covers_url,
headers=self.headers,
data=f"fields url; where game={rom_id};",
timeout=120).json()[0]
except IndexError:
return ""
return self._normalize_cover_url(res['url']) if 'url' in res.keys() else ""
def _search_screenshots(self, rom_id: str) -> list:
res: dict = requests.post(self.screenshots_url, headers=self.headers,
data=f"fields url; where game={rom_id}; limit 5;").json()
return [self._normalize_cover_url(r['url']).replace('t_thumb', 't_original') for r in res if 'url' in r.keys()]
res: dict = requests.post(self.screenshots_url,
headers=self.headers,
data=f"fields url; where game={rom_id}; limit 5;",
timeout=120).json()
return [self._normalize_cover_url(r['url']).replace('t_thumb', 't_original')
for r in res if 'url' in r.keys()]
@check_twitch_token
def get_platform(self, slug: str) -> tuple:
def get_platform(self, slug: str) -> dict:
igdb_id: str = ""
name: str = slug
try:
res: dict = requests.post(self.platform_url, headers=self.headers,
data=f"fields id, name; where slug=\"{slug}\";").json()[0]
res: dict = requests.post(self.platform_url,
headers=self.headers,
data=f"fields id, name; where slug=\"{slug.lower()}\";",
timeout=120).json()[0]
igdb_id = res['id']
name = res['name']
except IndexError:
@@ -88,67 +97,75 @@ class IGDBHandler():
r_igdb_id = res['id'] if 'id' in res.keys() else ""
r_slug = res['slug'] if 'slug' in res.keys() else ""
r_name = res['name'] if 'name' in res.keys() else ""
r_name = res['name'] if 'name' in res.keys() else search_term
summary = res['summary'] if 'summary' in res.keys() else ""
if not r_name: r_name = search_term
if not r_igdb_id: log.warning(f"{r_name} not found in IGDB")
return {'r_igdb_id': r_igdb_id, 'r_slug': r_slug, 'r_name': r_name, 'summary': summary, 'url_cover': self._search_cover(r_igdb_id), 'url_screenshots': self._search_screenshots(r_igdb_id)}
if not r_igdb_id:
log.warning(f"{r_name} not found in IGDB")
return {'r_igdb_id': r_igdb_id, 'r_slug': r_slug, 'r_name': r_name, 'summary': summary,
'url_cover': self._search_cover(r_igdb_id),
'url_screenshots': self._search_screenshots(r_igdb_id)}
@check_twitch_token
def get_rom_by_id(self, r_igdb_id: str) -> list:
res: list = requests.post(self.games_url, headers=self.headers,
data=f"fields slug, name, summary; where id={r_igdb_id};")
res = requests.post(self.games_url,
headers=self.headers,
data=f"fields slug, name, summary; where id={r_igdb_id};",
timeout=120)
if res.status_code == 200:
rom: dict = res.json()[0]
r_slug = rom['slug'] if 'slug' in rom.keys() else ""
r_name = rom['name'] if 'name' in rom.keys() else ""
summary = rom['summary'] if 'summary' in rom.keys() else ""
return [{'r_igdb_id': r_igdb_id, 'r_slug': r_slug, 'r_name': r_name, 'summary': summary, 'url_cover': self._search_cover(r_igdb_id), 'url_screenshots': self._search_screenshots(r_igdb_id)}]
else:
return []
return [{'r_igdb_id': r_igdb_id, 'r_slug': r_slug, 'r_name': r_name, 'summary': summary,
'url_cover': self._search_cover(r_igdb_id),
'url_screenshots': self._search_screenshots(r_igdb_id)}]
return []
@check_twitch_token
def get_matched_rom_by_id(self, igdb_id: str) -> list:
matched_roms: list = self.get_rom_by_id(igdb_id)
for rom in matched_roms:
rom['url_cover'] = rom['url_cover'].replace('t_thumb', f't_cover_big')
rom['url_cover'] = rom['url_cover'].replace('t_thumb', 't_cover_big')
rom['url_screenshots'] = self._search_screenshots(igdb_id)
return matched_roms
@check_twitch_token
def get_matched_roms_by_name(self, search_term: str, p_igdb_id: int) -> list:
matched_roms: list = requests.post(self.games_url, headers=self.headers,
data=f"search \"{uc(search_term)}\"; \
fields id, slug, name, summary; \
where platforms=[{p_igdb_id}];").json()
data=f"""search \"{uc(search_term)}\";
fields id, slug, name, summary;
where platforms=[{p_igdb_id}];""",
timeout=120).json()
for rom in matched_roms:
rom['url_cover'] = self._search_cover(rom['id']).replace('t_thumb', f't_cover_big')
rom['url_cover'] = self._search_cover(rom['id']).replace('t_thumb', 't_cover_big')
rom['url_screenshots'] = self._search_screenshots(rom['id'])
rom['r_igdb_id'] = rom.pop('id')
rom['r_slug'] = rom.pop('slug')
rom['r_name'] = rom.pop('name')
return matched_roms
@check_twitch_token
def get_matched_roms(self, file_name: str, p_igdb_id: int, p_slug: str) -> list:
matched_roms: list[dict] = []
if p_igdb_id:
matched_roms: list = requests.post(self.games_url, headers=self.headers,
data=f"search \"{uc(get_search_term(file_name))}\"; \
fields id, slug, name, summary; \
where platforms=[{p_igdb_id}];").json()
data=f"""search \"{uc(get_search_term(file_name))}\";
fields id, slug, name, summary;
where platforms=[{p_igdb_id}];""",
timeout=120).json()
for rom in matched_roms:
rom['url_cover'] = self._search_cover(rom['id']).replace('t_thumb', f't_cover_big')
rom['url_cover'] = self._search_cover(rom['id']).replace('t_thumb', 't_cover_big')
rom['url_screenshots'] = self._search_screenshots(rom['id'])
rom['r_igdb_id'] = rom.pop('id')
rom['r_slug'] = rom.pop('slug')
rom['r_name'] = rom.pop('name')
else:
matched_roms: list[dict] = []
log.warning(f"{p_slug} is not supported!")
return matched_roms
@@ -160,22 +177,23 @@ class TwitchAuth():
self.base_url: str = 'https://id.twitch.tv/oauth2/token'
self.token: str = ""
self.token_checkout: int = int(time())
self.SECURE_SECONDS_OFFSET: int = 10 # seconds offset to avoid invalid token
self.secure_seconds_offset: int = 10 # seconds offset to avoid invalid token
self.token_valid_seconds: int = 0
self.client_id: str = CLIENT_ID
self.client_secret: str = CLIENT_SECRET
def _is_token_valid(self) -> str:
return True if int(time()) + self.SECURE_SECONDS_OFFSET - self.token_checkout < self.token_valid_seconds else False
def _is_token_valid(self) -> bool:
return True if int(time()) + self.secure_seconds_offset - self.token_checkout < self.token_valid_seconds else False
def _update_twitch_token(self) -> str:
def _update_twitch_token(self) -> None:
res = requests.post(url=self.base_url,
params={
'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': 'client_credentials'}
'grant_type': 'client_credentials'},
timeout=30
).json()
self.token_checkout = int(time())
try:

View File

@@ -21,7 +21,7 @@ const emitter = inject("emitter");
emitter.on("refreshPlatforms", async () => {
try {
const { data } = await fetchPlatformsApi();
platforms.set(data.data);
platforms.set(data);
} catch (error) {
console.error("Couldn't fetch platforms:", error);
} finally {

View File

@@ -2,7 +2,7 @@
import { ref } from "vue";
const props = defineProps(["platform"]);
const platformIconUrl = ref(`/assets/platforms/${props.platform.slug}.ico`);
const platformIconUrl = ref(`/assets/platforms/${props.platform.slug.toLowerCase()}.ico`);
function onImageError() {
platformIconUrl.value = "/assets/platforms/default.ico";

View File

@@ -15,7 +15,7 @@ const props = defineProps(["platform", "rail"]);
}}</span>
<template v-slot:prepend>
<v-avatar :rounded="0" size="40">
<v-img :src="`/assets/platforms/${platform.slug}.ico`"></v-img>
<v-img :src="`/assets/platforms/${platform.slug.toLowerCase()}.ico`"></v-img>
</v-avatar>
</template>
<template v-slot:append>

View File

@@ -122,7 +122,7 @@ async function scan() {
<v-row no-gutters class="align-center pa-4" v-for="platform in scannedPlatforms">
<v-col>
<v-avatar :rounded="0" size="40">
<v-img :src="`/assets/platforms/${platform['p_slug']}.ico`"></v-img>
<v-img :src="`/assets/platforms/${platform['p_slug'].toLowerCase()}.ico`"></v-img>
</v-avatar>
<span class="text-body-2 ml-5"> {{ platform["p_name"] }}</span>
<v-list-item v-for="rom in platform['rom']" class="text-body-2" disabled>