Merge pull request #147 from zurdi15/feature/multi_file_game

Feature/multi file game
This commit is contained in:
Zurdi
2023-04-11 17:44:32 +02:00
committed by GitHub
8 changed files with 36 additions and 35 deletions

View File

@@ -5,4 +5,5 @@ mariadb==1.1.6
SQLAlchemy==2.0.7
alembic==1.10.3
PyYAML==6.0
Unidecode==1.3.6
Unidecode==1.3.6
emoji==2.2.0

View File

@@ -27,5 +27,5 @@ def get_db_engine():
return f"sqlite:////{SQLITE_DB_BASE_PATH}/romm.db"
else:
log.critical(f"Not supported {ROMM_DB_DRIVER} database")
log.critical(f"{ROMM_DB_DRIVER} database not supported")
sys.exit(3)

View File

@@ -39,7 +39,7 @@ class IGDBHandler():
igdb_id = res_details['id']
name = res_details['name']
except IndexError:
log.warning("platform not found in igdb")
log.warning(f"{slug} not found in IGDB")
if not name: name = slug
return {'igdb_id': igdb_id, 'name': name, 'slug': slug, 'logo_path': ''}
@@ -101,14 +101,14 @@ class IGDBHandler():
except KeyError:
pass
except IndexError:
log.warning(f"{file_name} rom not found in igdb")
log.warning(f"{file_name} not found in IGDB")
if r_igdb_id:
try:
res_details: dict = requests.post("https://api.igdb.com/v4/covers/", headers=self.headers,
data=f"fields url; where game={r_igdb_id};").json()[0]
url_cover: str = f"https:{res_details['url']}"
except IndexError:
log.warning(f"{name} cover not found in igdb")
log.warning(f"{name} cover not found in IGDB")
if not name: name = file_name_no_tags
return (r_igdb_id, file_name_no_tags, slug, name, summary, url_cover)
@@ -119,8 +119,7 @@ class IGDBHandler():
if p_igdb_id != '':
search_term: str = unidecode.unidecode(re.sub('[\(\[].*?[\)\]]', '', file_name.split('.')[0]))
matched_roms: list = requests.post("https://api.igdb.com/v4/games/", headers=self.headers,
data=f"search \"{search_term}\";fields name, id, slug, summary; where platforms=[{p_igdb_id}];").json()
log.info(f"Matched roms for {file_name}: {matched_roms}")
data=f"search \"{search_term}\";fields name, id, slug, summary; where platforms=[{p_igdb_id}];").json()
for rom in matched_roms:
try:
res_details: dict = requests.post("https://api.igdb.com/v4/covers/", headers=self.headers,
@@ -162,14 +161,14 @@ class TwitchAuth():
try:
self.token_valid_seconds = res['expires_in']
self.token = res['access_token']
log.info("twitch token fetched!")
log.info("Twitch token fetched!")
except KeyError:
log.error("could not get twitch auth token: check client_id and client_secret")
log.error("Could not get twitch auth token: check client_id and client_secret")
sys.exit(2)
def get_oauth_token(self) -> str:
if not self._is_token_valid():
log.warning("twitch token invalid: fetching a new one")
log.warning("Twitch token invalid: fetching a new one")
self._update_twitch_token()
return self.token

View File

@@ -6,6 +6,7 @@ COLORS: dict = {
'blue': '\033[94m',
'cyan': '\033[96m',
'orange': '\033[93m',
'orange_i': '\033[3;93m',
'red': '\033[91m',
'bold_red': '\033[1;91m',
'reset': '\033[0m',

View File

@@ -1,9 +1,7 @@
import sys
import subprocess
from subprocess import CalledProcessError
from fastapi import FastAPI, Request
import uvicorn
import json
import emoji
from logger.logger import log, COLORS
from handler import igdbh, dbh
@@ -26,46 +24,45 @@ def startup() -> None:
def scan(platforms_to_scan: str, full_scan: bool=False) -> dict:
"""Scan platforms and roms and write them in database."""
log.info("Scaning...")
log.info(emoji.emojize(":magnifying_glass_tilted_right: Scanning "))
fs.store_default_resources()
fs_platforms: list[str] = fs.get_platforms()
log.info(f"Platforms found: {', '.join(fs_platforms)}")
log.info(f"Platforms detected: {', '.join(fs_platforms)}")
platforms: list[str] = json.loads(platforms_to_scan) if len(json.loads(platforms_to_scan)) > 0 else fs_platforms
for p_slug in platforms:
log.info(f"{COLORS['pink']}== {p_slug} =={COLORS['reset']}")
log.info(emoji.emojize(f":video_game: {p_slug} {COLORS['reset']}"))
platform: Platform = fastapi.scan_platform(p_slug)
log.info(f"{p_slug} identified as {COLORS['blue']}{platform}{COLORS['reset']}")
if p_slug != str(platform): log.info(f"Identified as {COLORS['blue']}{platform}{COLORS['reset']}")
dbh.add_platform(platform)
log.info(f"Searching new roms...")
log.info(f"Searching new roms")
roms: list[dict] = fs.get_roms(p_slug, full_scan)
for rom in roms:
log.info(f"Getting {COLORS['orange']}{rom['file_name']}{COLORS['reset']} details")
if rom['multi']: [log.info(f"\t - {COLORS['orange']}{file}{COLORS['reset']}") for file in rom['files']]
if rom['multi']: [log.info(f"\t - {COLORS['orange_i']}{file}{COLORS['reset']}") for file in rom['files']]
rom = fastapi.scan_rom(platform, rom)
dbh.add_rom(rom)
log.info(f"Purging {platform} roms")
dbh.purge_roms(p_slug, fs.get_roms(p_slug, True))
log.info("Purging platforms")
dbh.add_rom(rom)
log.info(emoji.emojize(":wastebasket: Purging database"))
[dbh.purge_roms(p_slug, fs.get_roms(p_slug, True)) for p_slug in platforms]
dbh.purge_platforms(fs_platforms)
return {'msg': 'success'}
@app.get("/platforms")
async def platforms() -> dict:
def platforms() -> dict:
"""Returns platforms data"""
return {'data': dbh.get_platforms()}
@app.get("/platforms/{p_slug}/roms/{file_name}")
async def rom(p_slug: str, file_name: str) -> dict:
def rom(p_slug: str, file_name: str) -> dict:
"""Returns one rom data of the desired platform"""
return {'data': dbh.get_rom(p_slug, file_name)}
@app.get("/platforms/{p_slug}/roms")
async def roms(p_slug: str) -> dict:
def roms(p_slug: str) -> dict:
"""Returns all roms of the desired platform"""
return {'data': dbh.get_roms(p_slug)}
@@ -102,10 +99,10 @@ async def updateRom(req: Request, p_slug: str) -> dict:
@app.delete("/platforms/{p_slug}/roms/{file_name}")
async def delete_rom(p_slug: str, file_name: str, filesystem: bool=False) -> dict:
def delete_rom(p_slug: str, file_name: str, filesystem: bool=False) -> dict:
"""Detele rom from filesystem and database"""
log.info("deleting rom...")
log.info(f"Deleting {file_name}")
if filesystem: fs.delete_rom(p_slug, file_name)
dbh.delete_rom(p_slug, file_name)
return {'msg': 'success'}
@@ -116,8 +113,12 @@ async def search_rom_igdb(req: Request) -> dict:
"""Get all the roms matched from igdb."""
data: dict = await req.json()
log.info(f"getting {data['rom']['file_name']} roms from {data['rom']['p_slug']} igdb ...")
return {'data': igdbh.get_matched_roms(data['rom']['file_name'], data['rom']['p_igdb_id'], data['rom']['p_slug'])}
log.info(emoji.emojize(":magnifying_glass_tilted_right: IGDB Searching"))
log.info(emoji.emojize(f":video_game: {data['rom']['p_slug']}: {COLORS['orange']}{data['rom']['file_name']}{COLORS['reset']}"))
matched_roms = igdbh.get_matched_roms(data['rom']['file_name'], data['rom']['p_igdb_id'], data['rom']['p_slug'])
log.info("Results:")
[log.info(f"\t - {COLORS['blue']}{rom['name']}{COLORS['reset']}") for rom in matched_roms]
return {'data': matched_roms}
if __name__ == '__main__':

View File

@@ -16,7 +16,6 @@ def allow_cors(app: FastAPI) -> None:
allow_methods=["*"],
allow_headers=["*"],
)
log.info("CORS enabled")
def scan_platform(p_slug: str) -> Platform:

View File

@@ -35,7 +35,7 @@ def get_platforms() -> list[str]:
pass
return platforms
except IndexError:
error: str = "Platforms not found."
error: str = "Platforms not found"
log.critical(error)
raise HTTPException(status_code=404, detail=error)
@@ -148,7 +148,7 @@ def delete_rom(p_slug: str, file_name: str) -> None:
except IsADirectoryError:
shutil.rmtree(f"{rom_path}/{file_name}")
except FileNotFoundError:
log.warning(f"Rom not found in filesystem: {rom_path}/{file_name}")
log.error(f"{rom_path}/{file_name} not found in filesystem")
def _cover_exists(p_slug: str, file_name: str, size: str) -> bool:
@@ -184,7 +184,7 @@ def _store_cover(p_slug: str, file_name: str, url_cover: str, size: str) -> None
shutil.copyfileobj(res.raw, f)
log.info(f"{file_name} {sizes[size]} cover downloaded successfully!")
else:
log.warning(f"{file_name} {sizes[size]} cover couldn't be downloaded")
log.error(f"{file_name} {sizes[size]} cover couldn't be downloaded")
def _get_cover_path(p_slug: str, file_name: str, size: str) -> str:

View File

@@ -1,4 +1,4 @@
#!/bin/bash
cd /back
alembic upgrade head && uvicorn main:app --proxy-headers --host 0.0.0.0 --port 5000 --workers 3
alembic upgrade head && uvicorn main:app --proxy-headers --host 0.0.0.0 --port 5000