Merge pull request #4 from zurdi15/develop

v1.0
This commit is contained in:
Zurdi
2023-03-25 02:59:35 +01:00
committed by GitHub
219 changed files with 939 additions and 554 deletions

View File

@@ -1,5 +1,5 @@
requests==2.28.2
fastapi==0.92.0
uvicorn==0.20.0
mariadb==1.0.11 # works in python base image
# mariadb==1.1.6 # works in ubuntu base image
mariadb==1.1.6
SQLAlchemy==2.0.7

View File

@@ -2,30 +2,31 @@ import os
import pathlib
# Uvicorn
PORT: int = 5000
HOST: str = "0.0.0.0"
DEV_PORT: int = 5000
DEV_HOST: str = "0.0.0.0"
# PATHS
EMULATION_BASE_PATH: str = f"{pathlib.Path(__file__).parent.parent.parent.parent.resolve()}/emulation"
DEFAULT_LOGO_URL: str = "https://images.igdb.com/igdb/image/upload/t_cover_big/nocover.png"
DEFAULT_LOGO_PATH: str = f"/assets/emulation/resources/default/logo_big.png"
DEFAULT_URL_LOGO: str = "https://images.igdb.com/igdb/image/upload/t_cover_big/nocover.png"
DEFAULT_PATH_LOGO: str = f"/assets/emulation/resources/default/logo_l.png"
DEFAULT_COVER_URL_BIG: str = "https://images.igdb.com/igdb/image/upload/t_cover_big/nocover.png"
DEFAULT_COVER_PATH_BIG: str = f"/assets/emulation/resources/default/cover_big.png"
DEFAULT_COVER_URL_SMALL: str = "https://images.igdb.com/igdb/image/upload/t_cover_small/nocover.png"
DEFAULT_COVER_PATH_SMALL: str = f"/assets/emulation/resources/default/cover_small.png"
DEFAULT_URL_COVER_L: str = "https://images.igdb.com/igdb/image/upload/t_cover_big/nocover.png"
DEFAULT_PATH_COVER_L: str = f"/assets/emulation/resources/default/cover_l.png"
DEFAULT_URL_COVER_S: str = "https://images.igdb.com/igdb/image/upload/t_cover_small/nocover.png"
DEFAULT_PATH_COVER_S: str = f"/assets/emulation/resources/default/cover_s.png"
# IGDB
CLIENT_ID=os.getenv('CLIENT_ID')
CLIENT_SECRET=os.getenv('CLIENT_SECRET')
CLIENT_ID: str = os.getenv('CLIENT_ID')
CLIENT_SECRET: str = os.getenv('CLIENT_SECRET')
# STEAMGRIDDB
STEAMGRIDDB_API_KEY=os.getenv('STEAMGRIDDB_API_KEY')
STEAMGRIDDB_API_KEY: str = os.getenv('STEAMGRIDDB_API_KEY')
# DB
DB_HOST=os.getenv('DB_HOST')
DB_PORT=int(os.getenv('DB_PORT'))
DB_ROOT_PASSWD=os.getenv('DB_ROOT_PASSWD')
DB_USER=os.getenv('DB_USER')
DB_PASSWD=os.getenv('DB_PASSWD')
DB_HOST: str = os.getenv('DB_HOST')
DB_PORT: int = int(os.getenv('DB_PORT'))
DB_ROOT_PASSWD: str = os.getenv('DB_ROOT_PASSWD')
DB_USER: str = os.getenv('DB_USER')
DB_PASSWD: str = os.getenv('DB_PASSWD')
DB_NAME: str = 'romm'

View File

@@ -1,27 +0,0 @@
from dataclasses import dataclass
from config.config import DEFAULT_LOGO_PATH, DEFAULT_COVER_PATH_BIG, DEFAULT_COVER_PATH_SMALL
@dataclass
class Platform:
igdb_id: str = ""
sgdb_id: str = ""
slug: str = ""
name: str = ""
path_logo: str = DEFAULT_LOGO_PATH
@dataclass
class Rom:
igdb_id: str = ""
sgdb_id: str = ""
platform_igdb_id: str = ""
platform_sgdb_id: str = ""
filename: str = ""
name: str = ""
slug: str = ""
summary: str = ""
platform_slug: str = ""
path_cover_big: str = DEFAULT_COVER_PATH_BIG
path_cover_small: str = DEFAULT_COVER_PATH_SMALL

View File

@@ -1,122 +1,83 @@
import os
import sys
from dataclasses import asdict
from fastapi import HTTPException
import mariadb as db
from sqlalchemy import select
from sqlalchemy.exc import ProgrammingError
from config.config import DB_HOST, DB_PORT, DB_USER, DB_PASSWD
from models.base import Session, BaseModel, engine
from models.platform import Platform
from models.rom import Rom
from logger.logger import log
class DBHandler:
class DBHandler:
def __init__(self) -> None:
self.DATABASE: str = 'romm'
self.PLATFORM_TABLE: str = 'platform'
self.ROM_TABLE: str = 'rom'
try:
self.conn = db.connect(
host=DB_HOST,
port=DB_PORT,
user=DB_USER,
password=DB_PASSWD,
database=self.DATABASE,
autocommit=True
)
self.conn.auto_reconnect = True
except db.Error as e:
log.error(f"error connecting to the database: {e}")
sys.exit(1)
self.cur = self.conn.cursor()
def regenerate_platform_table(self, igdb_id: str, sgdb_id: str,
slug: str, name: str, path_logo: str) -> None:
try:
self.cur.execute(f"""
create table if not exists {self.PLATFORM_TABLE}
({igdb_id} varchar(20), {sgdb_id} varchar(20),
{slug} varchar(50), {name} varchar(100),
{path_logo} varchar(500))
""")
log.info(f"{self.PLATFORM_TABLE} table created")
except Exception as e:
log.error(f"{self.PLATFORM_TABLE} table can't be created: {e}")
raise HTTPException(status_code=500, detail=f"Can't create platform table. {e}")
try:
self.cur.execute(f"truncate {self.PLATFORM_TABLE}")
log.info(f"{self.PLATFORM_TABLE} table truncated")
except Exception as e:
log.error(f"{self.PLATFORM_TABLE} table can't be truncated: {e}")
raise HTTPException(status_code=500, detail=f"Can't truncate platform table. {e}")
BaseModel.metadata.create_all(engine)
self.session = Session()
def regenerate_rom_table(self, igdb_id: str, sgdb_id: str, platform_igdb_id: str, platform_sgdb_id: str,
rom_filename: str, rom_name: str, rom_slug: str, summary: str, platform_slug: str, path_cover_big: str, path_cover_small: str) -> None:
try:
self.cur.execute(f"""
create table if not exists {self.ROM_TABLE}
({igdb_id} varchar(20), {sgdb_id} varchar(20),
{platform_igdb_id} varchar(20), {platform_sgdb_id} varchar(20),
{rom_filename} varchar(200), {rom_name} varchar(100),
{rom_slug} varchar(100), {summary} text, {platform_slug} varchar(100),
{path_cover_big} varchar(500), {path_cover_small} varchar(500))
""")
log.info(f"{self.ROM_TABLE} table created")
except Exception as e:
log.error(f"{self.ROM_TABLE} table can't be created: {e}")
raise HTTPException(status_code=500, detail=f"Can't create rom table. {e}")
try:
self.cur.execute(f"truncate {self.ROM_TABLE}")
log.info(f"{self.ROM_TABLE} table truncated")
except Exception as e:
log.error(f"{self.ROM_TABLE} table can't be truncated: {e}")
raise HTTPException(status_code=500, detail=f"Can't truncate rom table. {e}")
def add_platform(self, **kargs) -> None:
with Session.begin() as session:
session.merge(Platform(**kargs))
def write_platforms(self, platforms: list) -> None:
values: list = [{k: str(v) for k, v in asdict(p).items()} for p in platforms]
def add_platform(self, **kargs) -> None:
with Session.begin() as session:
session.merge(Platform(**kargs))
def get_platforms(self) -> list[Platform]:
try:
self.cur.executemany(f"insert into {self.PLATFORM_TABLE} (igdb_id, sgdb_id, slug, name, path_logo) \
values (%(igdb_id)s, %(sgdb_id)s, %(slug)s, %(name)s, %(path_logo)s)", values)
log.info(f"{self.PLATFORM_TABLE} table populated")
except Exception as e:
log.error(f"{self.PLATFORM_TABLE} can't be populated: {e}")
raise HTTPException(status_code=500, detail=f"Can't write in platform table. {e}")
with Session.begin() as session:
return session.scalars(select(Platform)).all()
except ProgrammingError as e:
raise HTTPException(status_code=404, detail=f"Platforms table not found: {e}")
def add_platform(self, **kargs) -> None:
try:
with Session.begin() as session:
session.merge(Platform(**kargs))
except ProgrammingError as e:
raise HTTPException(status_code=404, detail=f"Roms table not found: {e}")
def get_roms(self, p_slug: str) -> list[Rom]:
with Session.begin() as session:
return session.scalars(select(Rom).filter_by(p_slug=p_slug)).all()
def get_rom(self, p_slug: str, filename: str) -> Rom:
with Session.begin() as session:
return session.scalars(select(Rom).filter_by(p_slug=p_slug, filename=filename)).first()
def add_rom(self, **kargs) -> None:
with Session.begin() as session:
session.merge(Rom(**kargs))
def write_roms(self, roms: list) -> None:
values: list = [{k: str(v) for k, v in asdict(p).items()} for p in roms]
try:
self.cur.executemany(f"insert into {self.ROM_TABLE} (igdb_id, sgdb_id, platform_igdb_id, platform_sgdb_id, filename, name, slug, summary, platform_slug, path_cover_big, path_cover_small) \
values (%(igdb_id)s, %(sgdb_id)s, %(platform_igdb_id)s, %(platform_sgdb_id)s, %(filename)s, %(name)s, %(slug)s, %(summary)s, %(platform_slug)s, %(path_cover_big)s, %(path_cover_small)s)", values)
log.info(f"{self.ROM_TABLE} table populated")
except Exception as e:
log.error(f"{self.ROM_TABLE} can't be populated: {e}")
raise HTTPException(status_code=500, detail=f"Can't write in platform table. {e}")
def update_rom(self, p_slug: str, filename: str, data: dict) -> None:
with Session.begin() as session:
session.query(Rom) \
.filter(Rom.p_slug==p_slug, Rom.filename==filename) \
.update(data, synchronize_session='evaluate')
def get_platforms(self) -> list:
try:
self.cur.execute(f"select igdb_id, sgdb_id, slug, name, path_logo from {self.PLATFORM_TABLE} order by name asc")
log.info(f"platforms details fetch from {self.PLATFORM_TABLE}")
except Exception as e:
log.error(f"platforms details can't be fetch from {self.PLATFORM_TABLE}")
raise HTTPException(status_code=500, detail=f"Can't read platform table. {e}")
return self.cur
def get_roms(self, platform_slug: str) -> list:
try:
self.cur.execute(f"select igdb_id, sgdb_id, platform_igdb_id, platform_sgdb_id, filename, name, slug, summary, platform_slug, path_cover_big, path_cover_small from {self.ROM_TABLE} where platform_slug = '{platform_slug}' order by name asc")
log.info(f"platforms details fetch from {self.ROM_TABLE}")
except Exception as e:
log.error(f"platforms details can't be fetch from {self.ROM_TABLE}")
raise HTTPException(status_code=500, detail=f"Can't read rom table. {e}")
return self.cur
def delete_rom(self, p_slug: str, filename: str) -> None:
with Session.begin() as session:
session.query(Rom) \
.filter(Rom.p_slug==p_slug, Rom.filename==filename) \
.delete(synchronize_session='evaluate')
def close_conn(self) -> None:
log.info("closing database connection")
self.conn.close()
def purge_platforms(self, platforms: list) -> None:
with Session.begin() as session:
session.query(Platform) \
.filter(Platform.slug.not_in(platforms)) \
.delete(synchronize_session='evaluate')
def purge_roms(self, p_slug: str, roms: list) -> None:
with Session.begin() as session:
session.query(Rom) \
.filter(Rom.p_slug==p_slug, Rom.filename.not_in(roms)) \
.delete(synchronize_session='evaluate')

View File

@@ -34,7 +34,7 @@ class IGDBHandler():
url_logo: str = ""
try:
res_details: dict = requests.post("https://api.igdb.com/v4/platforms/", headers=self.headers,
data=f"fields id, name, platform_logo; where slug=\"{slug}\";").json()[0]
data=f"fields id, name, platform_logo; where slug=\"{slug}\";").json()[0]
igdb_id = res_details['id']
name = res_details['name']
id_logo = res_details['platform_logo']
@@ -47,34 +47,35 @@ class IGDBHandler():
url_logo: str = f"https://images.igdb.com/igdb/image/upload/t_logo_med/{res_logo['image_id']}.png"
except IndexError:
log.warning(f"{slug} logo not found in igdb")
return (igdb_id, name, url_logo)
if not name: name = slug
return igdb_id, name, url_logo
@check_twitch_token
def get_rom_details(self, rom_filename: str, platform_id: int) -> dict:
term: str = rom_filename.split('.')[0]
def get_rom_details(self, filename: str, p_igdb_id: int, r_igdb_id: str) -> dict:
filename_no_ext: str = filename.split('.')[0]
igdb_id: str = ""
slug: str = ""
name: str = ""
summary: str = ""
url_cover: str = ""
if platform_id:
if r_igdb_id:
res_details: dict = requests.post("https://api.igdb.com/v4/games/", headers=self.headers,
data=f"fields id, slug, name, summary; where id={r_igdb_id};").json()[0]
igdb_id = res_details['id']
slug = res_details['slug']
name = res_details['name']
try:
res_details: dict = requests.post("https://api.igdb.com/v4/games/",
headers=self.headers,
data=f"search \"{term}\";fields id, slug, name, summary; where platforms=[{platform_id}] & category=0;").json()[0]
igdb_id = res_details['id']
slug = res_details['slug']
name = res_details['name']
summary = res_details['summary']
except KeyError:
pass
else:
if p_igdb_id:
try:
summary = res_details['summary']
except KeyError:
pass
except IndexError:
try:
res_details: dict = requests.post("https://api.igdb.com/v4/games/",
headers=self.headers,
data=f"search \"{term}\";fields name, id, slug, summary; where platforms=[{platform_id}] & category=10;").json()[0]
res_details: dict = requests.post("https://api.igdb.com/v4/games/", headers=self.headers,
data=f"search \"{filename_no_ext}\";fields id, slug, name, summary; where platforms=[{p_igdb_id}] & category=0;").json()[0]
igdb_id = res_details['id']
slug = res_details['slug']
name = res_details['name']
@@ -84,9 +85,8 @@ class IGDBHandler():
pass
except IndexError:
try:
res_details: dict = requests.post("https://api.igdb.com/v4/games/",
headers=self.headers,
data=f"search \"{term}\";fields name, id, slug, summary; where platforms=[{platform_id}];").json()[0]
res_details: dict = requests.post("https://api.igdb.com/v4/games/", headers=self.headers,
data=f"search \"{filename_no_ext}\";fields name, id, slug, summary; where platforms=[{p_igdb_id}] & category=10;").json()[0]
igdb_id = res_details['id']
slug = res_details['slug']
name = res_details['name']
@@ -95,16 +95,38 @@ class IGDBHandler():
except KeyError:
pass
except IndexError:
log.warning(f"{rom_filename} rom not found in igdb")
if igdb_id:
try:
res_details: dict = requests.post("https://api.igdb.com/v4/covers/",
headers=self.headers,
data=f"fields url; where game={igdb_id};").json()[0]
url_cover: str = f"https:{res_details['url']}"
except IndexError:
log.warning(f"{name} cover not found in igdb")
return (igdb_id, slug, name, summary, url_cover)
try:
res_details: dict = requests.post("https://api.igdb.com/v4/games/", headers=self.headers,
data=f"search \"{filename_no_ext}\";fields name, id, slug, summary; where platforms=[{p_igdb_id}];").json()[0]
igdb_id = res_details['id']
slug = res_details['slug']
name = res_details['name']
try:
summary = res_details['summary']
except KeyError:
pass
except IndexError:
log.warning(f"{filename} rom not found in igdb")
if igdb_id:
try:
res_details: dict = requests.post("https://api.igdb.com/v4/covers/", headers=self.headers,
data=f"fields url; where game={igdb_id};").json()[0]
url_cover: str = f"https:{res_details['url']}"
except IndexError:
log.warning(f"{name} cover not found in igdb")
if not name: name = filename_no_ext
return (igdb_id, filename_no_ext, slug, name, summary, url_cover)
@check_twitch_token
def get_matched_roms(self, filename: str, p_igdb_id: int) -> list:
matched_roms: list = requests.post("https://api.igdb.com/v4/games/", headers=self.headers,
data=f"search \"{filename.split('.')[0]}\";fields name, id, slug, summary; where platforms=[{p_igdb_id}];").json()
for rom in matched_roms:
res_details: dict = requests.post("https://api.igdb.com/v4/covers/", headers=self.headers,
data=f"fields url; where game={rom['id']};").json()[0]
rom['url_cover'] = f"https:{res_details['url']}".replace('t_thumb', f't_cover_big')
return matched_roms

View File

@@ -1,5 +1,3 @@
import os
import requests
from config.config import STEAMGRIDDB_API_KEY

View File

@@ -1,14 +1,11 @@
from dataclasses import asdict
from fastapi import FastAPI
from fastapi import FastAPI, Request
import uvicorn
from logger.logger import log
from handler.igdb_handler import IGDBHandler
from handler.sgdb_handler import SGDBHandler
from handler.db_handler import DBHandler
from config.config import PORT, HOST, DEFAULT_LOGO_URL, DEFAULT_COVER_URL_BIG, DEFAULT_COVER_URL_SMALL
from data.data import Platform, Rom
from config.config import DEV_PORT, DEV_HOST
from utils import fs, fastapi
@@ -16,78 +13,90 @@ app = FastAPI()
fastapi.allow_cors(app)
igdbh: IGDBHandler = IGDBHandler()
sgdbh: SGDBHandler = SGDBHandler()
dbh: DBHandler = DBHandler()
@app.get("/platforms/{slug}/roms")
async def platforms(slug):
"""Returns roms data of the desired platform"""
return {'data': [Rom(*r) for r in dbh.get_roms(slug)]}
@app.patch("/platforms/{p_slug}/roms/{filename}")
async def updateRom(req: Request, p_slug: str, filename: str):
"""Updates rom details"""
data: dict = await req.json()
if 'r_igdb_id' in data:
r_igdb_id, filename_no_ext, r_slug, r_name, summary, url_cover = igdbh.get_rom_details(filename, data['p_igdb_id'], data['r_igdb_id'])
path_cover_s, path_cover_l, has_cover = fs.get_cover_details(True, p_slug, filename_no_ext, url_cover)
data['r_igdb_id'] = r_igdb_id
data['filename_no_ext'] = filename_no_ext
data['r_slug'] = r_slug
data['name'] = r_name
data['summary'] = summary
data['path_cover_s'] = path_cover_s
data['path_cover_l'] = path_cover_l
data['has_cover'] = has_cover
data['p_slug'] = p_slug
else:
fs.rename_rom(p_slug, filename, data)
data['filename_no_ext'] = data['filename'].split('.')[0]
dbh.update_rom(p_slug, filename, data)
return {'data': data}
@app.delete("/platforms/{p_slug}/roms/{filename}")
async def delete_rom(p_slug: str, filename: str):
"""Detele rom from filesystem and database"""
log.info("deleting rom...")
fs.delete_rom(p_slug, filename)
dbh.delete_rom(p_slug, filename)
return {'msg': 'success'}
@app.get("/platforms/{p_slug}/roms/{filename}")
async def rom(p_slug: str, filename: str):
"""Returns one rom data of the desired platform"""
return {'data': dbh.get_rom(p_slug, filename)}
@app.get("/platforms/{p_slug}/roms")
async def roms(p_slug: str):
"""Returns all roms of the desired platform"""
return {'data': dbh.get_roms(p_slug)}
@app.get("/platforms")
async def platforms():
"""Returns platforms data"""
return {'data': [Platform(*p) for p in dbh.get_platforms()]}
return {'data': dbh.get_platforms()}
@app.get("/scan")
async def scan(overwrite: bool=False):
@app.put("/scan")
async def scan(req: Request, overwrite: bool=False):
"""Scan platforms and roms and write them in database."""
log.info("scaning...")
if overwrite or not fs.platform_logo_exists('default'):
fs.store_platform_logo('default', DEFAULT_LOGO_URL)
if overwrite or not fs.rom_cover_exists('default', 'cover', 'big'):
fs.store_rom_cover('default', 'cover', DEFAULT_COVER_URL_BIG, 'big')
if overwrite or not fs.rom_cover_exists('default', 'cover', 'small'):
fs.store_rom_cover('default', 'cover', DEFAULT_COVER_URL_SMALL, 'small')
platforms: list = []
roms: list = []
for platform_slug in fs.get_platforms():
platform_igdb_id, platform_name, url_logo = igdbh.get_platform_details(platform_slug)
platform_sgdb_id: str = ""
if not platform_name: platform_name = platform_slug
details: list = [platform_igdb_id, platform_sgdb_id, platform_slug, platform_name]
if (overwrite or not fs.platform_logo_exists(platform_slug)) and url_logo:
fs.store_platform_logo(platform_slug, url_logo)
if fs.platform_logo_exists(platform_slug):
details.append(fs.get_platform_logo_path(platform_slug))
platforms.append(Platform(*details))
for rom_filename in fs.get_roms(platform_slug):
log.info(f"Getting {rom_filename} details")
rom_igdb_id, rom_slug, rom_name, summary, url_cover = igdbh.get_rom_details(rom_filename, platform_igdb_id)
rom_sgdb_id: str = ""
if not rom_name: rom_name = rom_filename
details: list = [rom_igdb_id, rom_sgdb_id, platform_igdb_id, platform_sgdb_id, rom_filename, rom_name, rom_slug, summary, platform_slug]
if (overwrite or not fs.rom_cover_exists(platform_slug, rom_filename, 'big')) and url_cover:
fs.store_rom_cover(platform_slug, rom_filename, url_cover, 'big')
if (overwrite or not fs.rom_cover_exists(platform_slug, rom_filename, 'small')) and url_cover:
fs.store_rom_cover(platform_slug, rom_filename, url_cover, 'small')
if fs.rom_cover_exists(platform_slug, rom_filename, 'big'):
details.append(fs.get_rom_cover_path(platform_slug, rom_filename, 'big'))
if fs.rom_cover_exists(platform_slug, rom_filename, 'small'):
details.append(fs.get_rom_cover_path(platform_slug, rom_filename, 'small'))
roms.append(Rom(*details))
dbh.regenerate_platform_table(*asdict(Platform()).keys())
dbh.write_platforms(platforms)
dbh.regenerate_rom_table(*asdict(Rom()).keys())
dbh.write_roms(roms)
log.info("complete scaning...")
fs.store_default_resources(overwrite)
data: dict = await req.json()
platforms = data['platforms'] if data['platforms'] else fs.get_platforms()
for p_slug in platforms:
p_igdb_id: str = fastapi.scan_platform(overwrite, p_slug, igdbh, dbh)
for filename in fs.get_roms(p_slug):
fastapi.scan_rom(overwrite, filename, p_igdb_id, p_slug, igdbh, dbh)
fastapi.purge(dbh, p_slug=p_slug)
fastapi.purge(dbh)
return {'msg': 'success'}
@app.put("/search/roms/igdb")
async def search_rom_igdb(req: Request):
"""Get all the roms matched from igdb."""
data: dict = await req.json()
log.info(f"getting {data['filename']} roms from {data['p_igdb_id']} igdb ...")
return {'data': igdbh.get_matched_roms(data['filename'], data['p_igdb_id'])}
if __name__ == '__main__':
uvicorn.run("main:app", host=HOST, port=PORT, reload=True, workers=4)
dbh.close_conn()
uvicorn.run("main:app", host=DEV_HOST, port=DEV_PORT, reload=True)

View File

@@ -0,0 +1,11 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from config.config import DB_HOST, DB_PORT, DB_USER, DB_PASSWD, DB_NAME
BaseModel = declarative_base()
engine = create_engine(f"mariadb+mariadbconnector://{DB_USER}:{DB_PASSWD}@{DB_HOST}:{DB_PORT}/{DB_NAME}")
Session = sessionmaker(bind=engine, expire_on_commit=False)

View File

@@ -0,0 +1,13 @@
from sqlalchemy import Column, String
from config.config import DEFAULT_PATH_LOGO
from models.base import BaseModel
class Platform(BaseModel):
__tablename__ = 'platforms'
igdb_id = Column(String(length=50), default="")
sgdb_id = Column(String(length=50), default="")
slug = Column(String(length=100), primary_key=True)
name = Column(String(length=200), default="")
path_logo = Column(String(length=500), default=DEFAULT_PATH_LOGO)

21
backend/src/models/rom.py Normal file
View File

@@ -0,0 +1,21 @@
from sqlalchemy import Column, String, Text, Boolean
from config.config import DEFAULT_PATH_COVER_S, DEFAULT_PATH_COVER_L
from models.base import BaseModel
class Rom(BaseModel):
__tablename__ = 'roms'
filename = Column(String(length=200), primary_key=True)
filename_no_ext = Column(String(length=200), default="")
r_igdb_id = Column(String(length=50), default="")
p_igdb_id = Column(String(length=50), default="")
r_sgdb_id = Column(String(length=50), default="")
p_sgdb_id = Column(String(length=50), default="")
name = Column(String(length=100), default="")
r_slug = Column(String(length=100), default="")
p_slug = Column(String(length=100), default="")
summary = Column(Text, default="")
path_cover_s = Column(String(length=500), default=DEFAULT_PATH_COVER_S)
path_cover_l = Column(String(length=500), default=DEFAULT_PATH_COVER_L)
has_cover = Column(Boolean, default=False)

View File

@@ -1,6 +1,9 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from handler.db_handler import DBHandler
from handler.igdb_handler import IGDBHandler
from utils import fs
from logger.logger import log
@@ -13,3 +16,53 @@ def allow_cors(app: FastAPI) -> None:
allow_headers=["*"],
)
log.info("CORS enabled")
def scan_platform(overwrite: bool, p_slug: str, igdbh: IGDBHandler, dbh: DBHandler) -> str:
platform: dict = {}
log.info(f"Getting {p_slug} details")
p_igdb_id, p_name, url_logo = igdbh.get_platform_details(p_slug)
platform['slug'] = p_slug
platform['igdb_id'] = p_igdb_id
platform['name'] = p_name
#TODO: refactor logo details logic
if (overwrite or not fs.p_logo_exists(p_slug)) and url_logo:
fs.store_p_logo(p_slug, url_logo)
if fs.p_logo_exists(p_slug):
platform['path_logo']: str = fs.get_p_path_logo(p_slug)
dbh.add_platform(**platform)
return p_igdb_id
def scan_rom(overwrite: bool, filename: str, p_igdb_id: str, p_slug: str, igdbh: IGDBHandler, dbh: DBHandler, r_igbd_id: str = '') -> None:
rom: dict = {}
log.info(f"Getting {filename} details")
r_igdb_id, filename_no_ext, r_slug, r_name, summary, url_cover = igdbh.get_rom_details(filename, p_igdb_id, r_igbd_id)
path_cover_s, path_cover_l, has_cover = fs.get_cover_details(overwrite, p_slug, filename_no_ext, url_cover)
rom['filename'] = filename
rom['filename_no_ext'] = filename_no_ext
rom['r_igdb_id'] = r_igdb_id
rom['p_igdb_id'] = p_igdb_id
rom['name'] = r_name
rom['r_slug'] = r_slug
rom['p_slug'] = p_slug
rom['summary'] = summary
rom['path_cover_s'] = path_cover_s
rom['path_cover_l'] = path_cover_l
rom['has_cover'] = has_cover
dbh.add_rom(**rom)
def purge(dbh: DBHandler, p_slug: str = '') -> None:
"""Clean the database from non existent platforms or roms"""
if p_slug:
# Purge only roms in platform
roms: list = fs.get_roms(p_slug)
dbh.purge_roms(p_slug, roms)
else:
# Purge all platforms / delete non existent platforms and non existen roms
platforms: list = fs.get_platforms()
dbh.purge_platforms(platforms)
for p_slug in platforms:
roms: list = fs.get_roms(p_slug)
dbh.purge_roms(p_slug, roms)

View File

@@ -5,26 +5,27 @@ from pathlib import Path
import requests
from fastapi import HTTPException
from config.config import EMULATION_BASE_PATH
from config.config import EMULATION_BASE_PATH, DEFAULT_URL_LOGO, DEFAULT_URL_COVER_L, DEFAULT_PATH_COVER_L, DEFAULT_URL_COVER_S, DEFAULT_PATH_COVER_S
from logger.logger import log
def get_platforms() -> list:
"""Gets all filesystem platforms
# ========= Defaults utils =========
def store_default_resources(overwrite: bool) -> None:
"""Store default no_cover resources in the filesystem
Returns list with all the filesystem platforms found in the EMULATION_BASE_PATH.
Automatically discards the default directory.
Args:
overwrite: flag to overwrite or not default resources
"""
try:
platforms: list = list(os.walk(EMULATION_BASE_PATH))[0][1]
if 'resources' in platforms: platforms.remove('resources')
log.info(f"filesystem platforms found: {platforms}")
return platforms
except IndexError:
raise HTTPException(status_code=404, detail="Platforms not found.")
if overwrite or not p_logo_exists('default'):
store_p_logo('default', DEFAULT_URL_LOGO)
if overwrite or not r_cover_exists('default', 'cover', 'l'):
store_r_cover('default', 'cover', DEFAULT_URL_COVER_L, 'l')
if overwrite or not r_cover_exists('default', 'cover', 's'):
store_r_cover('default', 'cover', DEFAULT_URL_COVER_S, 's')
def platform_logo_exists(slug: str) -> bool:
# ========= Platforms utils =========
def p_logo_exists(slug: str) -> bool:
"""Check if platform logo exists in filesystem
Args:
@@ -36,11 +37,16 @@ def platform_logo_exists(slug: str) -> bool:
return True if os.path.exists(logo_path) else False
def get_platform_logo_path(slug: str) -> str:
def get_p_path_logo(slug: str) -> str:
"""Returns platform logo filesystem path
Args:
slug: shor name of the platform
"""
return f"/assets/emulation/resources/{slug}/logo.png"
def store_platform_logo(platform_slug: str, url_logo: str) -> None:
def store_p_logo(slug: str, url_logo: str) -> None:
"""Store platform resources in filesystem
Args:
@@ -48,65 +54,137 @@ def store_platform_logo(platform_slug: str, url_logo: str) -> None:
url_logo: url to get logo
"""
logo_file: str = f"logo.png"
logo_path: str = f"{EMULATION_BASE_PATH}/resources/{platform_slug}"
logo_path: str = f"{EMULATION_BASE_PATH}/resources/{slug}"
res = requests.get(url_logo, stream=True)
if res.status_code == 200:
Path(logo_path).mkdir(parents=True, exist_ok=True)
with open(f"{logo_path}/{logo_file}", 'wb') as f:
shutil.copyfileobj(res.raw, f)
log.info(f"{platform_slug} logo downloaded successfully!")
log.info(f"{slug} logo downloaded successfully!")
else:
log.warning(f"{platform_slug} logo couldn't be downloaded")
log.warning(f"{slug} logo couldn't be downloaded")
def get_roms(platform_slug) -> list:
"""Gets all filesystem roms for a platform
def get_platforms() -> list:
"""Gets all filesystem platforms
Returns list with all the filesystem roms for a platform found in the EMULATION_BASE_PATH.
Returns list with all the filesystem platforms found in the EMULATION_BASE_PATH.
Automatically discards the default directory.
"""
try:
roms: list = []
roms = list(os.walk(f"{EMULATION_BASE_PATH}/{platform_slug}/roms/"))[0][2]
log.info(f"filesystem roms found for {platform_slug}: {roms}")
platforms: list[str] = list(os.walk(EMULATION_BASE_PATH))[0][1]
if 'resources' in platforms: platforms.remove('resources')
log.info(f"filesystem platforms found: {platforms}")
return platforms
except IndexError:
log.warning(f"roms not found for {platform_slug}")
pass
return roms
raise HTTPException(status_code=404, detail="Platforms not found.")
def rom_cover_exists(platform_slug: str, rom_filename: str, size: str) -> bool:
# ========= Roms utils =========
def r_cover_exists(p_slug: str, filename_no_ext: str, size: str) -> bool:
"""Check if rom cover exists in filesystem
Args:
slug: short name of the platform
rom_filename: name of rom file
p_slug: short name of the platform
filename_no_ext: name of rom file without extension
size: size of the cover -> big as 'l' | small as 's'
Returns
True if cover exists in filesystem else False
"""
logo_path: str = f"{EMULATION_BASE_PATH}/resources/{platform_slug}/{rom_filename.split('.')[0]}_{size}.png"
logo_path: str = f"{EMULATION_BASE_PATH}/resources/{p_slug}/{filename_no_ext}_{size}.png"
return True if os.path.exists(logo_path) else False
def get_rom_cover_path(platform_slug: str, rom_filename: str, size: str) -> str:
return f"/assets/emulation/resources/{platform_slug}/{rom_filename.split('.')[0]}_{size}.png"
def get_r_cover_path(p_slug: str, filename_no_ext: str, size: str) -> str:
"""Returns platform logo filesystem path
Args:
p_slug: short name of the platform
filename_no_ext: name of rom file without extension
size: size of the cover -> big as 'l' | small as 's'
"""
return f"/assets/emulation/resources/{p_slug}/{filename_no_ext}_{size}.png"
def store_rom_cover(platfom_slug: str, rom_filename: str, url_cover: str, size: str) -> None:
def store_r_cover(p_slug: str, filename_no_ext: str, url_cover: str, size: str) -> None:
"""Store roms resources in filesystem
Args:
platform_slug: short name of the platform
rom_filename: name of rom file
url_cover: url to get cover
p_slug: short name of the platform
filename_no_ext: name of rom file without extension
url_cover: url to get the cover
size: size of the cover -> big as 'l' | small as 's'
"""
cover_file: str = f"{rom_filename.split('.')[0]}_{size}.png"
cover_path: str = f"{EMULATION_BASE_PATH}/resources/{platfom_slug}/"
res = requests.get(url_cover.replace('t_thumb', f't_cover_{size}'), stream=True)
cover_file: str = f"{filename_no_ext}_{size}.png"
cover_path: str = f"{EMULATION_BASE_PATH}/resources/{p_slug}/"
sizes: dict = {'l': 'big', 's': 'small'}
res = requests.get(url_cover.replace('t_thumb', f't_cover_{sizes[size]}'), stream=True)
if res.status_code == 200:
Path(cover_path).mkdir(parents=True, exist_ok=True)
with open(f"{cover_path}/{cover_file}", 'wb') as f:
shutil.copyfileobj(res.raw, f)
log.info(f"{rom_filename} {size} cover downloaded successfully!")
log.info(f"{filename_no_ext} {sizes[size]} cover downloaded successfully!")
else:
log.warning(f"{rom_filename} {size} cover couldn't be downloaded")
log.warning(f"{filename_no_ext} {sizes[size]} cover couldn't be downloaded")
def get_cover_details(overwrite: bool, p_slug: str, filename_no_ext: str, url_cover: str) -> tuple:
path_cover_s: str = DEFAULT_PATH_COVER_S
path_cover_l: str = DEFAULT_PATH_COVER_L
has_cover: int = 0
if (overwrite or not r_cover_exists(p_slug, filename_no_ext, 's')) and url_cover:
store_r_cover(p_slug, filename_no_ext, url_cover, 's')
if r_cover_exists(p_slug, filename_no_ext, 's'):
path_cover_s = get_r_cover_path(p_slug, filename_no_ext, 's')
if (overwrite or not r_cover_exists(p_slug, filename_no_ext, 'l')) and url_cover:
store_r_cover(p_slug, filename_no_ext, url_cover, 'l')
if r_cover_exists(p_slug, filename_no_ext, 'l'):
path_cover_l = get_r_cover_path(p_slug, filename_no_ext, 'l')
has_cover = 1
return path_cover_s, path_cover_l, has_cover
def get_roms(p_slug: str) -> list:
"""Gets all filesystem roms for a platform
Args:
p_slug: short name of the platform
Returns: list with all the filesystem roms for a platform found in the EMULATION_BASE_PATH.
Automatically discards the default directory.
"""
try:
roms: list[str] = []
roms = list(os.walk(f"{EMULATION_BASE_PATH}/{p_slug}/roms/"))[0][2]
log.info(f"filesystem roms found for {p_slug}: {roms}")
except IndexError:
log.warning(f"roms not found for {p_slug}")
pass
return roms
def r_exists(p_slug: str, filename: str) -> bool:
"""Check if rom exists in filesystem
Args:
p_slug: short name of the platform
filename: rom filename
Returns
True if rom exists in filesystem else False
"""
rom_path: str = f"{EMULATION_BASE_PATH}/{p_slug}/roms/{filename}"
exists: bool = True if os.path.exists(rom_path) else False
return exists
def rename_rom(p_slug: str, filename: str, data: dict) -> None:
if r_exists(p_slug, data['filename']): raise HTTPException(status_code=500, detail=f"Can't rename: {data['filename']} already exists.")
os.rename(f"{EMULATION_BASE_PATH}/{p_slug}/roms/{filename}",
f"{EMULATION_BASE_PATH}/{p_slug}/roms/{data['filename']}")
def delete_rom(p_slug: str, filename: str) -> None:
try:
os.remove(f"{EMULATION_BASE_PATH}/{p_slug}/roms/{filename}")
except FileNotFoundError:
log.warning(f"Rom not found in filesystem: {p_slug}/{filename}")

View File

@@ -9,6 +9,7 @@ RUN npm run build
# setup frontend
FROM ubuntu/nginx:1.18-22.04_edge as production-stage
COPY --from=front-build-stage /front/dist /var/www/html
COPY ./frontend/assets/platforms /var/www/html/assets/platforms
RUN ln -s /emulation /var/www/html/assets/emulation
# setup backend

View File

@@ -37,6 +37,11 @@ http {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
location / {
try_files $uri $uri/ /index.html;
proxy_redirect off;
}
# Backend api calls
location /api {
rewrite /api/(.*) /$1 break;

View File

View File

View File

View File

View File

View File

View File

View File

View File

View File

View File

View File

View File

View File

View File

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

View File

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 20 KiB

View File

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

View File

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 26 KiB

View File

Before

Width:  |  Height:  |  Size: 4.9 KiB

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

View File

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 24 KiB

View File

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

View File

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 23 KiB

View File

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

View File

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 23 KiB

View File

Before

Width:  |  Height:  |  Size: 4.1 KiB

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

View File

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 24 KiB

View File

Before

Width:  |  Height:  |  Size: 4.5 KiB

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

View File

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 23 KiB

View File

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

View File

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 21 KiB

View File

Before

Width:  |  Height:  |  Size: 4.1 KiB

After

Width:  |  Height:  |  Size: 4.1 KiB

View File

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 32 KiB

View File

Before

Width:  |  Height:  |  Size: 5.1 KiB

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Some files were not shown because too many files have changed in this diff Show More