Merge pull request #938 from rommapp/refactor/main_layout_backend

backend tweaks + refactor
This commit is contained in:
Georges-Antoine Assi
2024-06-19 14:49:52 -04:00
committed by GitHub
6 changed files with 104 additions and 104 deletions

View File

@@ -28,68 +28,79 @@ def upgrade() -> None:
connection = op.get_bind()
# Fetch all entries from the roms table
platforms = connection.execute(sa.text("select id, slug from platforms"))
platforms_row = platforms.fetchall()
platforms = connection.execute(sa.text("select id, slug from platforms")).fetchall()
platform_map = {platform.id: platform.slug for platform in platforms}
roms = connection.execute(
sa.text(
"SELECT id, name, platform_id, path_cover_s, path_cover_l, path_screenshots FROM roms"
)
)
roms_row = roms.fetchall()
).fetchall()
for rom in roms:
platform_slug = platform_map.get(rom.platform_id, "")
platform_folder_name = str(rom.platform_id)
rom_folder_name = str(rom.id)
old_folder_path = f"{RESOURCES_BASE_PATH}/{platform_slug}/{rom.name}"
new_folder_path = (
f"{RESOURCES_BASE_PATH}/{platform_folder_name}/{rom_folder_name}"
)
for rom in roms_row:
platform_slug = ""
for platform in platforms_row:
if platform.id == rom.platform_id:
platform_slug = platform.slug
old_folder_name = f"{RESOURCES_BASE_PATH}/{platform_slug}/{rom.name}"
new_folder_name = f"{RESOURCES_BASE_PATH}/{rom.platform_id}/{rom.id}"
print("INFO:\t [Resources migration] Renaming folder:")
print(f"INFO:\t [Resources migration] - old: {old_folder_name}")
print(f"INFO:\t [Resources migration] - new: {new_folder_name}")
print(f"INFO:\t [Resources migration] - old: {old_folder_path}")
print(f"INFO:\t [Resources migration] - new: {new_folder_path}")
try:
os.makedirs(f"{RESOURCES_BASE_PATH}/{rom.platform_id}", exist_ok=True)
os.makedirs(f"{RESOURCES_BASE_PATH}/{platform_folder_name}", exist_ok=True)
except OSError as error:
print(error)
if os.path.exists(old_folder_name):
os.rename(old_folder_name, new_folder_name)
if os.path.exists(old_folder_path):
os.rename(old_folder_path, new_folder_path)
else:
print(
f"ERROR:\t [Resources migration] Folder '{old_folder_name}' does not exist"
f"ERROR:\t [Resources migration] Folder '{old_folder_path}' does not exist"
)
quoted_rom_name = re.escape(quote(rom.name))
quoted_platform_slug = re.escape(quote(platform_slug))
updated_path_cover_s = re.sub(
quoted_platform_slug,
str(rom.platform_id),
re.sub(quoted_rom_name, str(rom.id), rom.path_cover_s),
)
connection.execute(
sa.text("UPDATE roms SET path_cover_s = :path_cover_s WHERE id = :id"),
{"path_cover_s": updated_path_cover_s, "id": rom.id},
platform_folder_name,
re.sub(quoted_rom_name, rom_folder_name, rom.path_cover_s),
)
updated_path_cover_l = re.sub(
quoted_platform_slug,
str(rom.platform_id),
re.sub(quoted_rom_name, str(rom.id), rom.path_cover_l),
)
connection.execute(
sa.text("UPDATE roms SET path_cover_l = :path_cover_l WHERE id = :id"),
{"path_cover_l": updated_path_cover_l, "id": rom.id},
platform_folder_name,
re.sub(quoted_rom_name, rom_folder_name, rom.path_cover_l),
)
updated_path_screenshots = re.sub(
quoted_platform_slug,
str(rom.platform_id),
re.sub(quoted_rom_name, str(rom.id), rom.path_screenshots),
platform_folder_name,
re.sub(quoted_rom_name, rom_folder_name, rom.path_screenshots),
)
connection.execute(
sa.text(
"UPDATE roms SET path_screenshots = :path_screenshots WHERE id = :id"
"""
UPDATE roms
SET path_cover_s = :path_cover_s,
path_cover_l = :path_cover_l,
path_screenshots = :path_screenshots
WHERE id = :id
"""
),
{"path_screenshots": updated_path_screenshots, "id": rom.id},
{
"id": rom.id,
"path_cover_s": updated_path_cover_s,
"path_cover_l": updated_path_cover_l,
"path_screenshots": updated_path_screenshots,
},
)
for platform in platforms_row:
for platform in platforms:
try:
rmtree(f"{RESOURCES_BASE_PATH}/{platform.slug}")
except FileNotFoundError:

View File

@@ -326,9 +326,7 @@ async def update_rom(
)
if remove_cover:
cleaned_data.update(
fs_resource_handler.remove_cover(rom_id=id, platform_id=db_rom.platform_id)
)
cleaned_data.update(fs_resource_handler.remove_cover(rom=db_rom))
cleaned_data.update({"url_cover": ""})
else:
if artwork is not None:
@@ -337,7 +335,7 @@ async def update_rom(
path_cover_l,
path_cover_s,
artwork_path,
) = fs_resource_handler.build_artwork_path(id, db_rom.platform_id, file_ext)
) = fs_resource_handler.build_artwork_path(db_rom, file_ext)
cleaned_data["path_cover_l"] = path_cover_l
cleaned_data["path_cover_s"] = path_cover_s
@@ -355,8 +353,7 @@ async def update_rom(
cleaned_data["url_cover"] = data.get("url_cover", db_rom.url_cover)
path_cover_s, path_cover_l = fs_resource_handler.get_rom_cover(
overwrite=True,
platform_id=db_rom.platform_id,
rom_id=id,
rom=db_rom,
url_cover=cleaned_data.get("url_cover", ""),
)
cleaned_data.update(
@@ -368,8 +365,7 @@ async def update_rom(
or cleaned_data["moby_id"] != db_rom.moby_id
):
path_screenshots = fs_resource_handler.get_rom_screenshots(
platform_id=db_rom.platform_id,
rom_id=id,
rom=db_rom,
url_screenshots=cleaned_data.get("url_screenshots", []),
)
cleaned_data.update({"path_screenshots": path_screenshots})
@@ -411,7 +407,7 @@ async def delete_roms(
db_rom_handler.delete_rom(id)
try:
rmtree(f"{RESOURCES_BASE_PATH}/{rom.platform_id}/{rom.id}")
rmtree(f"{RESOURCES_BASE_PATH}/{rom.fs_resources_path}")
except FileNotFoundError:
log.error(f"Couldn't find resources to delete for {rom.name}")

View File

@@ -230,14 +230,12 @@ async def scan_platforms(
path_cover_s, path_cover_l = fs_resource_handler.get_rom_cover(
overwrite=True,
platform_id=platform.id,
rom_id=_added_rom.id,
rom=_added_rom,
url_cover=_added_rom.url_cover,
)
path_screenshots = fs_resource_handler.get_rom_screenshots(
platform_id=platform.id,
rom_id=_added_rom.id,
rom=_added_rom,
url_screenshots=_added_rom.url_screenshots,
)

View File

@@ -6,6 +6,7 @@ import requests
from config import RESOURCES_BASE_PATH
from fastapi import HTTPException, status
from logger.logger import log
from models.rom import Rom
from PIL import Image
from urllib3.exceptions import ProtocolError
@@ -17,7 +18,7 @@ class FSResourcesHandler(FSHandler):
pass
@staticmethod
def _cover_exists(platform_id: int, rom_id: int, size: CoverSize):
def _cover_exists(rom: Rom, size: CoverSize):
"""Check if rom cover exists in filesystem
Args:
@@ -29,7 +30,7 @@ class FSResourcesHandler(FSHandler):
"""
return bool(
os.path.exists(
f"{RESOURCES_BASE_PATH}/{platform_id}/{rom_id}/cover/{size.value}.png"
f"{RESOURCES_BASE_PATH}/{rom.fs_resources_path}/cover/{size.value}.png"
)
)
@@ -43,9 +44,7 @@ class FSResourcesHandler(FSHandler):
small_img = cover.resize(small_size)
small_img.save(cover_path)
def _store_cover(
self, platform_id: int, rom_id: int, url_cover: str, size: CoverSize
):
def _store_cover(self, rom: Rom, url_cover: str, size: CoverSize):
"""Store roms resources in filesystem
Args:
@@ -55,7 +54,7 @@ class FSResourcesHandler(FSHandler):
size: size of the cover
"""
cover_file = f"{size.value}.png"
cover_path = f"{RESOURCES_BASE_PATH}/{platform_id}/{rom_id}/cover"
cover_path = f"{RESOURCES_BASE_PATH}/{rom.fs_resources_path}/cover"
try:
res = requests.get(
@@ -86,7 +85,7 @@ class FSResourcesHandler(FSHandler):
self.resize_cover_to_small(f"{cover_path}/{cover_file}")
@staticmethod
def _get_cover_path(platform_id: int, rom_id: int, size: CoverSize):
def _get_cover_path(rom: Rom, size: CoverSize):
"""Returns rom cover filesystem path adapted to frontend folder structure
Args:
@@ -94,59 +93,63 @@ class FSResourcesHandler(FSHandler):
file_name: name of rom file
size: size of the cover
"""
return f"{platform_id}/{rom_id}/cover/{size.value}.png"
return f"{rom.fs_resources_path}/cover/{size.value}.png"
def get_rom_cover(
self, overwrite: bool, platform_id: int, rom_id: int, url_cover: str = ""
self, rom: Rom | None, overwrite: bool, url_cover: str = ""
) -> tuple[str, str]:
if (
overwrite or not self._cover_exists(platform_id, rom_id, CoverSize.SMALL)
) and url_cover:
self._store_cover(platform_id, rom_id, url_cover, CoverSize.SMALL)
if not rom:
return "", ""
if (overwrite or not self._cover_exists(rom, CoverSize.SMALL)) and url_cover:
self._store_cover(rom, url_cover, CoverSize.SMALL)
path_cover_s = (
self._get_cover_path(platform_id, rom_id, CoverSize.SMALL)
if self._cover_exists(platform_id, rom_id, CoverSize.SMALL)
self._get_cover_path(rom, CoverSize.SMALL)
if self._cover_exists(rom, CoverSize.SMALL)
else ""
)
if (
overwrite or not self._cover_exists(platform_id, rom_id, CoverSize.BIG)
) and url_cover:
self._store_cover(platform_id, rom_id, url_cover, CoverSize.BIG)
if (overwrite or not self._cover_exists(rom, CoverSize.BIG)) and url_cover:
self._store_cover(rom, url_cover, CoverSize.BIG)
path_cover_l = (
self._get_cover_path(platform_id, rom_id, CoverSize.BIG)
if self._cover_exists(platform_id, rom_id, CoverSize.BIG)
self._get_cover_path(rom, CoverSize.BIG)
if self._cover_exists(rom, CoverSize.BIG)
else ""
)
return path_cover_s, path_cover_l
@staticmethod
def remove_cover(
rom_id: int,
platform_id: int,
):
def remove_cover(rom: Rom | None):
if not rom:
return {"path_cover_s": "", "path_cover_l": ""}
try:
cover_path = os.path.join(
RESOURCES_BASE_PATH, str(platform_id), str(rom_id), "cover"
)
cover_path = f"{RESOURCES_BASE_PATH}/{rom.fs_resources_path}/cover"
shutil.rmtree(cover_path)
except FileNotFoundError:
log.warning(f"Couldn't remove {rom_id} cover. {cover_path} doesn't exists.")
log.warning(
f"Couldn't remove rom '{rom.name or rom.id}' cover since '{cover_path}' doesn't exists."
)
return {"path_cover_s": "", "path_cover_l": ""}
@staticmethod
def build_artwork_path(rom_id: int, platform_id: int, file_ext: str):
path_cover_l = f"{platform_id}/{rom_id}/cover/{CoverSize.BIG.value}.{file_ext}"
def build_artwork_path(rom: Rom | None, file_ext: str):
if not rom:
return "", "", ""
path_cover_l = f"{rom.fs_resources_path}/cover/{CoverSize.BIG.value}.{file_ext}"
path_cover_s = (
f"{platform_id}/{rom_id}/cover/{CoverSize.SMALL.value}.{file_ext}"
f"{rom.fs_resources_path}/cover/{CoverSize.SMALL.value}.{file_ext}"
)
artwork_path = f"{RESOURCES_BASE_PATH}/{platform_id}/{rom_id}/cover"
artwork_path = f"{RESOURCES_BASE_PATH}/{rom.fs_resources_path}/cover"
Path(artwork_path).mkdir(parents=True, exist_ok=True)
return path_cover_l, path_cover_s, artwork_path
@staticmethod
def _store_screenshot(platform_id: int, rom_id: int, url: str, idx: int):
def _store_screenshot(rom: Rom, url: str, idx: int):
"""Store roms resources in filesystem
Args:
@@ -155,7 +158,7 @@ class FSResourcesHandler(FSHandler):
url: url to get the screenshot
"""
screenshot_file = f"{idx}.jpg"
screenshot_path = f"{RESOURCES_BASE_PATH}/{platform_id}/{rom_id}/screenshots"
screenshot_path = f"{RESOURCES_BASE_PATH}/{rom.fs_resources_path}/screenshots"
try:
res = requests.get(url, stream=True, timeout=120)
@@ -177,7 +180,7 @@ class FSResourcesHandler(FSHandler):
)
@staticmethod
def _get_screenshot_path(platform_id: int, rom_id: int, idx: str):
def _get_screenshot_path(rom: Rom, idx: str):
"""Returns rom cover filesystem path adapted to frontend folder structure
Args:
@@ -185,15 +188,15 @@ class FSResourcesHandler(FSHandler):
file_name: name of rom
idx: index number of screenshot
"""
return f"{platform_id}/{rom_id}/screenshots/{idx}.jpg"
return f"{rom.fs_resources_path}/screenshots/{idx}.jpg"
def get_rom_screenshots(self, rom: Rom | None, url_screenshots: list) -> list[str]:
if not rom:
return []
def get_rom_screenshots(
self, platform_id: int, rom_id: int, url_screenshots: list
) -> list[str]:
path_screenshots: list[str] = []
for idx, url in enumerate(url_screenshots):
self._store_screenshot(platform_id, rom_id, url, idx)
path_screenshots.append(
self._get_screenshot_path(platform_id, rom_id, str(idx))
)
self._store_screenshot(rom, url, idx)
path_screenshots.append(self._get_screenshot_path(rom, str(idx)))
return path_screenshots

View File

@@ -8,25 +8,13 @@ from models.platform import Platform
@pytest.mark.vcr
def test_get_rom_cover():
# Game: Metroid Prime (EUR).iso - ID: 1
path_cover_s, path_cover_l = fs_resource_handler.get_rom_cover(
overwrite=False, platform_id=1, rom_id=2, url_cover=""
overwrite=False, rom=None, url_cover=""
)
assert "" in path_cover_s
assert "" in path_cover_l
# Game: Paper Mario (USA).z64 - ID: 2
path_cover_s, path_cover_l = fs_resource_handler.get_rom_cover(
overwrite=True,
platform_id=1,
rom_id=2,
url_cover="https://images.igdb.com/igdb/image/upload/t_thumb/co1qda.png",
)
assert "1/2/cover/small.png" in path_cover_s
assert "1/2/cover/big.png" in path_cover_l
def test_get_platforms():
platforms = fs_platform_handler.get_platforms()

View File

@@ -170,6 +170,10 @@ class Rom(BaseModel):
def game_modes(self) -> list[str]:
return self.igdb_metadata.get("game_modes", [])
@property
def fs_resources_path(self) -> str:
return f"{str(self.platform_id)}/{str(self.id)}"
def __repr__(self) -> str:
return self.file_name