From 49c50ad8105cf1fe0548e89435a1f12ef44dd90e Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 19 Dec 2024 22:21:51 -0500 Subject: [PATCH 01/33] Move hash calc for roms to bacakground task --- backend/endpoints/sockets/scan.py | 51 ++++++++++++++++++- backend/handler/database/platforms_handler.py | 12 ++--- backend/handler/scan_handler.py | 23 ++------- 3 files changed, 58 insertions(+), 28 deletions(-) diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index cd83a316a..4766a86f7 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -1,5 +1,6 @@ from __future__ import annotations +import zlib from dataclasses import dataclass from itertools import batched from typing import Any, Final @@ -23,10 +24,10 @@ from handler.filesystem import ( fs_rom_handler, ) from handler.filesystem.roms_handler import FSRom -from handler.redis_handler import high_prio_queue, redis_client +from handler.redis_handler import high_prio_queue, low_prio_queue, redis_client from handler.scan_handler import ScanType, scan_firmware, scan_platform, scan_rom from handler.socket_handler import socket_handler -from logger.formatter import LIGHTYELLOW +from logger.formatter import LIGHTYELLOW, RED from logger.formatter import highlight as hl from logger.logger import log from models.platform import Platform @@ -37,6 +38,7 @@ from sqlalchemy.inspection import inspect from utils.context import initialize_context STOP_SCAN_FLAG: Final = "scan:stop" +NON_HASHABLE_PLATFORMS = ["pc", "win", "mac", "linux"] @dataclass @@ -333,6 +335,41 @@ async def _identify_firmware( return scan_stats +def _set_rom_hashes(rom_id: int): + """Set the hashes for the given rom + + Args: + rom_id (int): Rom id + """ + rom = db_rom_handler.get_rom(rom_id) + if not rom: + return + + try: + rom_hashes = fs_rom_handler.get_rom_hashes(rom.file_name, rom.file_path) + db_rom_handler.update_rom( + rom_id, + { + "crc_hash": rom_hashes["crc_hash"], + "md5_hash": rom_hashes["md5_hash"], + "sha1_hash": rom_hashes["sha1_hash"], + }, + ) + except zlib.error as e: + # Set empty hashes if calculating them fails for corrupted files + log.error( + f"Hashes of {rom.file_name} couldn't be calculated: {hl(str(e), color=RED)}" + ) + db_rom_handler.update_rom( + rom_id, + { + "crc_hash": "", + "md5_hash": "", + "sha1_hash": "", + }, + ) + + async def _identify_rom( platform: Platform, fs_rom: FSRom, @@ -376,6 +413,16 @@ async def _identify_rom( _added_rom = db_rom_handler.add_rom(scanned_rom) + # Calculating hashes is expensive, so we only do it if necessary + if not rom or scan_type == ScanType.COMPLETE or scan_type == ScanType.HASHES: + # Skip hashing games for platforms that don't have a hash database + if platform.slug not in NON_HASHABLE_PLATFORMS: + low_prio_queue.enqueue( + _set_rom_hashes, + _added_rom.id, + job_timeout=60 * 15, # Timeout (15 minutes) + ) + # Return early if we're only scanning for hashes if scan_type == ScanType.HASHES: return scan_stats diff --git a/backend/handler/database/platforms_handler.py b/backend/handler/database/platforms_handler.py index abd9205ff..56ee6261b 100644 --- a/backend/handler/database/platforms_handler.py +++ b/backend/handler/database/platforms_handler.py @@ -12,7 +12,7 @@ class DBPlatformsHandler(DBBaseHandler): def add_platform( self, platform: Platform, - session: Session, + session: Session = None, ) -> Platform: platform = session.merge(platform) session.flush() @@ -26,11 +26,11 @@ class DBPlatformsHandler(DBBaseHandler): return new_platform @begin_session - def get_platform(self, id: int, *, session: Session) -> Platform | None: + def get_platform(self, id: int, *, session: Session = None) -> Platform | None: return session.scalar(select(Platform).filter_by(id=id).limit(1)) @begin_session - def get_platforms(self, *, session: Session) -> Select[tuple[Platform]]: + def get_platforms(self, *, session: Session = None) -> Select[tuple[Platform]]: return ( session.scalars(select(Platform).order_by(Platform.name.asc())) # type: ignore[attr-defined] .unique() @@ -39,12 +39,12 @@ class DBPlatformsHandler(DBBaseHandler): @begin_session def get_platform_by_fs_slug( - self, fs_slug: str, session: Session + self, fs_slug: str, session: Session = None ) -> Platform | None: return session.scalar(select(Platform).filter_by(fs_slug=fs_slug).limit(1)) @begin_session - def delete_platform(self, id: int, session: Session) -> None: + def delete_platform(self, id: int, session: Session = None) -> None: # Remove all roms from that platforms first session.execute( delete(Rom) @@ -60,7 +60,7 @@ class DBPlatformsHandler(DBBaseHandler): @begin_session def purge_platforms( - self, fs_platforms: list[str], session: Session + self, fs_platforms: list[str], session: Session = None ) -> Select[tuple[Platform]]: purged_platforms = ( session.scalars( diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 91aa0d137..2faa2cb6e 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -1,5 +1,4 @@ import asyncio -import zlib from enum import Enum from typing import Any @@ -11,7 +10,7 @@ from handler.filesystem.roms_handler import FSRom from handler.metadata import meta_igdb_handler, meta_moby_handler from handler.metadata.igdb_handler import IGDBPlatform, IGDBRom from handler.metadata.moby_handler import MobyGamesPlatform, MobyGamesRom -from logger.formatter import BLUE, RED +from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log from models.assets import Save, Screenshot, State @@ -20,8 +19,6 @@ from models.platform import Platform from models.rom import Rom from models.user import User -NON_HASHABLE_PLATFORMS = ["pc", "win", "mac", "linux"] - class ScanType(Enum): NEW_PLATFORMS = "new_platforms" @@ -239,23 +236,9 @@ async def scan_rom( } ) - # Calculating hashes is expensive, so we only do it if necessary + # Set empty hashes when we plan to recalculate them if not rom or scan_type == ScanType.COMPLETE or scan_type == ScanType.HASHES: - # Skip hashing games for platforms that don't have a hash database - if platform.slug in NON_HASHABLE_PLATFORMS: - rom_attrs.update({"crc_hash": "", "md5_hash": "", "sha1_hash": ""}) - else: - try: - rom_hashes = fs_rom_handler.get_rom_hashes( - rom_attrs["file_name"], roms_path - ) - rom_attrs.update(**rom_hashes) - except zlib.error as e: - # Return empty hashes if calculating them fails for corrupted files - log.error( - f"Hashes of {rom_attrs['file_name']} couldn't be calculated: {hl(str(e), color=RED)}" - ) - rom_attrs.update({"crc_hash": "", "md5_hash": "", "sha1_hash": ""}) + rom_attrs.update({"crc_hash": "", "md5_hash": "", "sha1_hash": ""}) # If no metadata scan is required if scan_type == ScanType.HASHES: From e1ef8225c3238f2b96e167606274dbe33f4bd4ae Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Fri, 20 Dec 2024 10:42:53 -0500 Subject: [PATCH 02/33] Create migration for new romfile --- backend/alembic/versions/bd11e20ae1d4_.py | 217 ++++++++++++++++++++++ backend/endpoints/responses/rom.py | 21 ++- backend/models/rom.py | 42 +++-- 3 files changed, 260 insertions(+), 20 deletions(-) create mode 100644 backend/alembic/versions/bd11e20ae1d4_.py diff --git a/backend/alembic/versions/bd11e20ae1d4_.py b/backend/alembic/versions/bd11e20ae1d4_.py new file mode 100644 index 000000000..bb1a39e12 --- /dev/null +++ b/backend/alembic/versions/bd11e20ae1d4_.py @@ -0,0 +1,217 @@ +"""empty message + +Revision ID: bd11e20ae1d4 +Revises: 0028_user_email +Create Date: 2024-12-19 23:16:11.053536 + +""" + +import sqlalchemy as sa +from alembic import op +from config import IS_PYTEST_RUN, SCAN_TIMEOUT +from endpoints.sockets.scan import scan_platforms +from handler.redis_handler import high_prio_queue +from handler.scan_handler import ScanType +from sqlalchemy.dialects import mysql + +# revision identifiers, used by Alembic. +revision = "bd11e20ae1d4" +down_revision = "0028_user_email" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "rom_files", + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("rom_id", sa.Integer(), nullable=False), + sa.Column("file_name", sa.String(length=450), nullable=False), + sa.Column("file_path", sa.String(length=1000), nullable=False), + sa.Column("file_size_bytes", sa.BigInteger(), nullable=False), + sa.Column("last_modified", sa.Float(), nullable=True), + sa.Column("crc_hash", sa.String(length=100), nullable=True), + sa.Column("md5_hash", sa.String(length=100), nullable=True), + sa.Column("sha1_hash", sa.String(length=100), nullable=True), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column( + "updated_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.ForeignKeyConstraint(["rom_id"], ["roms.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + ) + + op.execute( + """ + WITH extracted_files AS ( + SELECT + r.id AS rom_id, + r.file_path AS file_path, + jsonb_array_elements(r.files) AS file_data + FROM roms r + ) + INSERT INTO rom_files ( + rom_id, + file_name, + file_path, + file_size_bytes, + last_modified, + crc_hash, + md5_hash, + sha1_hash + ) + SELECT + rom_id, + file_data->>'filename' AS file_name, + file_path, + (file_data->>'size')::BIGINT AS file_size_bytes, + (file_data->>'last_modified')::DOUBLE PRECISION AS last_modified, + NULL AS crc_hash, + NULL AS md5_hash, + NULL AS sha1_hash + FROM extracted_files; + """ + ) + + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.alter_column( + "file_name", new_column_name="fs_name", existing_type=sa.String(length=450) + ) + batch_op.alter_column( + "file_name_no_tags", + new_column_name="fs_name_no_tags", + existing_type=sa.String(length=450), + ) + batch_op.alter_column( + "file_name_no_ext", + new_column_name="fs_name_no_ext", + existing_type=sa.String(length=450), + ) + batch_op.alter_column( + "file_extension", + new_column_name="fs_extension", + existing_type=sa.String(length=100), + ) + batch_op.alter_column( + "file_path", new_column_name="fs_path", existing_type=sa.String(length=1000) + ) + batch_op.drop_column("files") + batch_op.drop_column("multi") + batch_op.drop_column("file_size_bytes") + + with op.batch_alter_table("users", schema=None) as batch_op: + batch_op.alter_column( + "role", + existing_type=mysql.ENUM("VIEWER", "EDITOR", "ADMIN"), + nullable=False, + ) + batch_op.alter_column( + "avatar_path", existing_type=mysql.VARCHAR(length=255), nullable=False + ) + + # Run a no-scan in the background on migrate + if not IS_PYTEST_RUN: + high_prio_queue.enqueue( + scan_platforms, [], ScanType.QUICK, [], [], job_timeout=SCAN_TIMEOUT + ) + + high_prio_queue.enqueue( + scan_platforms, [], ScanType.HASHES, [], [], job_timeout=SCAN_TIMEOUT + ) + + +def downgrade() -> None: + with op.batch_alter_table("users", schema=None) as batch_op: + batch_op.alter_column( + "avatar_path", existing_type=mysql.VARCHAR(length=255), nullable=True + ) + batch_op.alter_column( + "role", existing_type=mysql.ENUM("VIEWER", "EDITOR", "ADMIN"), nullable=True + ) + + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.add_column( + sa.Column( + "multi", + mysql.TINYINT(display_width=1), + autoincrement=False, + nullable=False, + ) + ) + batch_op.add_column( + sa.Column( + "files", + mysql.LONGTEXT(charset="utf8mb4", collation="utf8mb4_bin"), + nullable=True, + ) + ) + batch_op.add_column( + sa.Column( + "file_size_bytes", + mysql.BIGINT(display_width=20), + autoincrement=False, + nullable=False, + ) + ) + batch_op.alter_column( + "fs_path", new_column_name="file_path", existing_type=sa.String(length=1000) + ) + batch_op.alter_column( + "fs_extension", + new_column_name="file_extension", + existing_type=sa.String(length=100), + ) + batch_op.alter_column( + "fs_name_no_ext", + new_column_name="file_name_no_ext", + existing_type=sa.String(length=450), + ) + batch_op.alter_column( + "fs_name_no_tags", + new_column_name="file_name_no_tags", + existing_type=sa.String(length=450), + ) + batch_op.alter_column( + "fs_name", new_column_name="file_name", existing_type=sa.String(length=450) + ) + + op.execute( + """ + UPDATE roms + SET + files = ( + SELECT jsonb_agg(jsonb_build_object( + 'filename', file_name, + 'size', file_size_bytes, + 'last_modified', last_modified + )) + FROM rom_files + WHERE rom_files.rom_id = roms.id + ), + multi = ( + SELECT COUNT(*) > 1 + FROM rom_files + WHERE rom_files.rom_id = roms.id + ), + file_size_bytes = ( + SELECT COALESCE(SUM(file_size_bytes), 0) + FROM rom_files + WHERE rom_files.rom_id = roms.id + ) + WHERE EXISTS ( + SELECT 1 + FROM rom_files + WHERE rom_files.rom_id = roms.id + ); + """ + ) + + op.drop_table("rom_files") diff --git a/backend/endpoints/responses/rom.py b/backend/endpoints/responses/rom.py index e80ac99c0..f101a7b6c 100644 --- a/backend/endpoints/responses/rom.py +++ b/backend/endpoints/responses/rom.py @@ -9,7 +9,7 @@ from endpoints.responses.collection import CollectionSchema from fastapi import Request from handler.metadata.igdb_handler import IGDBMetadata from handler.metadata.moby_handler import MobyMetadata -from models.rom import Rom, RomFile, RomUserStatus +from models.rom import Rom, RomUserStatus from pydantic import BaseModel, computed_field SORT_COMPARE_REGEX = re.compile(r"^([Tt]he|[Aa]|[Aa]nd)\s") @@ -92,6 +92,20 @@ class RomUserSchema(BaseModel): ] +class RomFileSchema(BaseModel): + id: int + rom_id: int + file_name: str + file_path: str + file_size_bytes: int + created_at: datetime + updated_at: datetime + last_modified: datetime + + class Config: + from_attributes = True + + class RomSchema(BaseModel): id: int igdb_id: int | None @@ -137,10 +151,7 @@ class RomSchema(BaseModel): tags: list[str] multi: bool - files: list[RomFile] - crc_hash: str | None - md5_hash: str | None - sha1_hash: str | None + files: list[RomFileSchema] full_path: str created_at: datetime updated_at: datetime diff --git a/backend/models/rom.py b/backend/models/rom.py index 14259efce..f885b5c2c 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -3,7 +3,7 @@ from __future__ import annotations import enum from datetime import datetime from functools import cached_property -from typing import TYPE_CHECKING, Any, TypedDict +from typing import TYPE_CHECKING, Any from config import FRONTEND_RESOURCES_PATH from models.base import BaseModel @@ -29,10 +29,20 @@ if TYPE_CHECKING: from models.user import User -class RomFile(TypedDict): - filename: str - size: int - last_modified: float | None +class RomFile(BaseModel): + __tablename__ = "rom_files" + + id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + rom_id: Mapped[int] = mapped_column(ForeignKey("roms.id", ondelete="CASCADE")) + file_name: Mapped[str] = mapped_column(String(length=450)) + file_path: Mapped[str] = mapped_column(String(length=1000)) + file_size_bytes: Mapped[int] = mapped_column(BigInteger(), default=0) + last_modified: Mapped[float | None] = mapped_column(default=None) + crc_hash: Mapped[str | None] = mapped_column(String(100)) + md5_hash: Mapped[str | None] = mapped_column(String(100)) + sha1_hash: Mapped[str | None] = mapped_column(String(100)) + + rom: Mapped[Rom] = relationship(lazy="joined") class Rom(BaseModel): @@ -49,12 +59,11 @@ class Rom(BaseModel): Index("idx_roms_moby_id", "moby_id"), ) - file_name: Mapped[str] = mapped_column(String(length=450)) - file_name_no_tags: Mapped[str] = mapped_column(String(length=450)) - file_name_no_ext: Mapped[str] = mapped_column(String(length=450)) - file_extension: Mapped[str] = mapped_column(String(length=100)) - file_path: Mapped[str] = mapped_column(String(length=1000)) - file_size_bytes: Mapped[int] = mapped_column(BigInteger(), default=0) + fs_name: Mapped[str] = mapped_column(String(length=450)) + fs_name_no_tags: Mapped[str] = mapped_column(String(length=450)) + fs_name_no_ext: Mapped[str] = mapped_column(String(length=450)) + fs_extension: Mapped[str] = mapped_column(String(length=100)) + fs_path: Mapped[str] = mapped_column(String(length=1000)) name: Mapped[str | None] = mapped_column(String(length=350)) slug: Mapped[str | None] = mapped_column(String(length=400)) @@ -82,8 +91,6 @@ class Rom(BaseModel): JSON, default=[], doc="URLs to screenshots stored in IGDB" ) - multi: Mapped[bool] = mapped_column(default=False) - files: Mapped[list[RomFile] | None] = mapped_column(JSON, default=[]) crc_hash: Mapped[str | None] = mapped_column(String(100)) md5_hash: Mapped[str | None] = mapped_column(String(100)) sha1_hash: Mapped[str | None] = mapped_column(String(100)) @@ -99,6 +106,7 @@ class Rom(BaseModel): secondaryjoin="Rom.id == SiblingRom.sibling_rom_id", ) + files: Mapped[list[RomFile]] = relationship(back_populates="rom") saves: Mapped[list[Save]] = relationship(back_populates="rom") states: Mapped[list[State]] = relationship(back_populates="rom") screenshots: Mapped[list[Screenshot]] = relationship(back_populates="rom") @@ -118,7 +126,7 @@ class Rom(BaseModel): @cached_property def full_path(self) -> str: - return f"{self.file_path}/{self.file_name}" + return f"{self.fs_path}/{self.fs_name}" @cached_property def has_cover(self) -> bool: @@ -133,6 +141,10 @@ class Rom(BaseModel): ] return screenshots + @cached_property + def multi(self) -> bool: + return len(self.files) > 1 + def get_collections(self) -> list[Collection]: from handler.database import db_rom_handler @@ -202,7 +214,7 @@ class Rom(BaseModel): return f"roms/{str(self.platform_id)}/{str(self.id)}" def __repr__(self) -> str: - return self.file_name + return self.fs_name class RomUserStatus(enum.StrEnum): From 0850c0cbcfeee89673ee8e67d20bfec458d00029 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Fri, 20 Dec 2024 18:09:31 -0500 Subject: [PATCH 03/33] migration to create and move to rom_file --- ...0ae1d4_.py => 0029_rom_file_and_hashes.py} | 77 +++++++++---------- 1 file changed, 35 insertions(+), 42 deletions(-) rename backend/alembic/versions/{bd11e20ae1d4_.py => 0029_rom_file_and_hashes.py} (79%) diff --git a/backend/alembic/versions/bd11e20ae1d4_.py b/backend/alembic/versions/0029_rom_file_and_hashes.py similarity index 79% rename from backend/alembic/versions/bd11e20ae1d4_.py rename to backend/alembic/versions/0029_rom_file_and_hashes.py index bb1a39e12..da2dc2102 100644 --- a/backend/alembic/versions/bd11e20ae1d4_.py +++ b/backend/alembic/versions/0029_rom_file_and_hashes.py @@ -1,6 +1,6 @@ """empty message -Revision ID: bd11e20ae1d4 +Revision ID: 0029_rom_file_and_hashes Revises: 0028_user_email Create Date: 2024-12-19 23:16:11.053536 @@ -15,7 +15,7 @@ from handler.scan_handler import ScanType from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. -revision = "bd11e20ae1d4" +revision = "0029_rom_file_and_hashes" down_revision = "0028_user_email" branch_labels = None depends_on = None @@ -51,13 +51,6 @@ def upgrade() -> None: op.execute( """ - WITH extracted_files AS ( - SELECT - r.id AS rom_id, - r.file_path AS file_path, - jsonb_array_elements(r.files) AS file_data - FROM roms r - ) INSERT INTO rom_files ( rom_id, file_name, @@ -69,15 +62,20 @@ def upgrade() -> None: sha1_hash ) SELECT - rom_id, - file_data->>'filename' AS file_name, - file_path, - (file_data->>'size')::BIGINT AS file_size_bytes, - (file_data->>'last_modified')::DOUBLE PRECISION AS last_modified, - NULL AS crc_hash, - NULL AS md5_hash, - NULL AS sha1_hash - FROM extracted_files; + r.id AS rom_id, + JSON_UNQUOTE(JSON_EXTRACT(file_data, '$.filename')) AS file_name, + r.file_path AS file_path, + JSON_UNQUOTE(JSON_EXTRACT(file_data, '$.size')) AS file_size_bytes, + JSON_UNQUOTE(JSON_EXTRACT(file_data, '$.last_modified')) AS last_modified, + CASE WHEN r.multi = 0 THEN r.crc_hash ELSE NULL END AS crc_hash, + CASE WHEN r.multi = 0 THEN r.md5_hash ELSE NULL END AS md5_hash, + CASE WHEN r.multi = 0 THEN r.sha1_hash ELSE NULL END AS sha1_hash + FROM roms r, + JSON_TABLE(r.files, '$[*]' + COLUMNS ( + file_data JSON PATH '$' + ) + ) AS extracted_files; """ ) @@ -186,31 +184,26 @@ def downgrade() -> None: op.execute( """ UPDATE roms - SET - files = ( - SELECT jsonb_agg(jsonb_build_object( - 'filename', file_name, - 'size', file_size_bytes, - 'last_modified', last_modified - )) - FROM rom_files - WHERE rom_files.rom_id = roms.id - ), - multi = ( - SELECT COUNT(*) > 1 - FROM rom_files - WHERE rom_files.rom_id = roms.id - ), - file_size_bytes = ( - SELECT COALESCE(SUM(file_size_bytes), 0) - FROM rom_files - WHERE rom_files.rom_id = roms.id - ) - WHERE EXISTS ( - SELECT 1 + JOIN ( + SELECT + rom_id, + JSON_ARRAYAGG( + JSON_OBJECT( + 'filename', file_name, + 'size', file_size_bytes, + 'last_modified', last_modified + ) + ) AS files, + COUNT(*) > 1 AS multi, + COALESCE(SUM(file_size_bytes), 0) AS total_size FROM rom_files - WHERE rom_files.rom_id = roms.id - ); + GROUP BY rom_id + ) AS aggregated_data + ON roms.id = aggregated_data.rom_id + SET + roms.files = aggregated_data.files, + roms.multi = aggregated_data.multi, + roms.file_size_bytes = aggregated_data.total_size; """ ) From 3fcce6606ccf4e752ce2ca912ca852ea46b410ae Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Fri, 20 Dec 2024 22:41:56 -0500 Subject: [PATCH 04/33] complete updating the endpoints and models --- backend/endpoints/auth.py | 5 +- backend/endpoints/collections.py | 22 +++-- backend/endpoints/feeds.py | 10 +- backend/endpoints/firmware.py | 46 ++++++++-- backend/endpoints/platform.py | 13 ++- backend/endpoints/responses/rom.py | 33 +++---- backend/endpoints/rom.py | 92 ++++++++++--------- backend/endpoints/saves.py | 21 +++-- backend/endpoints/screenshots.py | 28 ++++-- backend/endpoints/search.py | 21 +++-- backend/endpoints/sockets/scan.py | 20 ++-- backend/endpoints/states.py | 24 +++-- backend/endpoints/user.py | 14 ++- .../handler/database/collections_handler.py | 25 +++-- backend/handler/database/firmware_handler.py | 10 +- backend/handler/database/platforms_handler.py | 12 ++- backend/handler/database/saves_handler.py | 24 ++++- .../handler/database/screenshots_handler.py | 34 +++++-- backend/handler/database/states_handler.py | 24 ++++- backend/handler/database/stats_handler.py | 15 +-- backend/handler/database/users_handler.py | 8 +- .../handler/filesystem/resources_handler.py | 6 +- backend/handler/filesystem/roms_handler.py | 18 ++-- backend/handler/metadata/igdb_handler.py | 2 +- backend/handler/metadata/moby_handler.py | 2 +- backend/models/rom.py | 4 + 26 files changed, 332 insertions(+), 201 deletions(-) diff --git a/backend/endpoints/auth.py b/backend/endpoints/auth.py index d973ceb7a..2c7240e6d 100644 --- a/backend/endpoints/auth.py +++ b/backend/endpoints/auth.py @@ -105,15 +105,14 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp status_code=status.HTTP_400_BAD_REQUEST, detail="Missing refresh token" ) - potential_user = await oauth_handler.get_current_active_user_from_bearer_token( + user, claims = await oauth_handler.get_current_active_user_from_bearer_token( token ) - if not potential_user: + if not user or not claims: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid refresh token" ) - user, claims = potential_user if claims.get("type") != "refresh": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid refresh token" diff --git a/backend/endpoints/collections.py b/backend/endpoints/collections.py index 8dff4fe4a..390649f79 100644 --- a/backend/endpoints/collections.py +++ b/backend/endpoints/collections.py @@ -57,7 +57,7 @@ async def add_collection( _added_collection = db_collection_handler.add_collection(Collection(**cleaned_data)) - if artwork is not None: + if artwork is not None and artwork.filename is not None: file_ext = artwork.filename.split(".")[-1] ( path_cover_l, @@ -82,8 +82,9 @@ async def add_collection( _added_collection.path_cover_s = path_cover_s _added_collection.path_cover_l = path_cover_l + # Update the collection with the cover path and update database - return db_collection_handler.update_collection( + created_collection = db_collection_handler.update_collection( _added_collection.id, { c: getattr(_added_collection, c) @@ -91,6 +92,8 @@ async def add_collection( }, ) + return CollectionSchema.model_validate(created_collection) + @protected_route(router.get, "/collections", [Scope.COLLECTIONS_READ]) def get_collections(request: Request) -> list[CollectionSchema]: @@ -105,7 +108,7 @@ def get_collections(request: Request) -> list[CollectionSchema]: """ collections = db_collection_handler.get_collections() - return CollectionSchema.for_user(request.user.id, collections) + return CollectionSchema.for_user(request.user.id, [c for c in collections]) @protected_route(router.get, "/collections/{id}", [Scope.COLLECTIONS_READ]) @@ -125,7 +128,7 @@ def get_collection(request: Request, id: int) -> CollectionSchema: if not collection: raise CollectionNotFoundInDatabaseException(id) - return collection + return CollectionSchema.model_validate(collection) @protected_route(router.put, "/collections/{id}", [Scope.COLLECTIONS_WRITE]) @@ -148,6 +151,8 @@ async def update_collection( data = await request.form() collection = db_collection_handler.get_collection(id) + if not collection: + raise CollectionNotFoundInDatabaseException(id) if collection.user_id != request.user.id: raise CollectionPermissionError(id) @@ -156,7 +161,7 @@ async def update_collection( raise CollectionNotFoundInDatabaseException(id) try: - roms = json.loads(data["roms"]) + roms = json.loads(data["roms"]) # type: ignore except json.JSONDecodeError as e: raise ValueError("Invalid list for roms field in update collection") from e except KeyError: @@ -174,7 +179,7 @@ async def update_collection( cleaned_data.update(fs_resource_handler.remove_cover(collection)) cleaned_data.update({"url_cover": ""}) else: - if artwork is not None: + if artwork is not None and artwork.filename is not None: file_ext = artwork.filename.split(".")[-1] ( path_cover_l, @@ -205,13 +210,14 @@ async def update_collection( path_cover_s, path_cover_l = await fs_resource_handler.get_cover( overwrite=True, entity=collection, - url_cover=data.get("url_cover", ""), + url_cover=data.get("url_cover", ""), # type: ignore ) cleaned_data.update( {"path_cover_s": path_cover_s, "path_cover_l": path_cover_l} ) - return db_collection_handler.update_collection(id, cleaned_data) + updated_collection = db_collection_handler.update_collection(id, cleaned_data) + return CollectionSchema.model_validate(updated_collection) @protected_route(router.delete, "/collections/{id}", [Scope.COLLECTIONS_WRITE]) diff --git a/backend/endpoints/feeds.py b/backend/endpoints/feeds.py index 40f305999..0f61bec9f 100644 --- a/backend/endpoints/feeds.py +++ b/backend/endpoints/feeds.py @@ -57,7 +57,7 @@ def platforms_webrcade_feed(request: Request) -> WebrcadeFeedSchema: request.url_for( "get_rom_content", id=rom.id, - file_name=rom.file_name, + file_name=rom.fs_name, ) ), ), @@ -135,10 +135,10 @@ async def tinfoil_index_feed( async def extract_titledb(roms: list[Rom]) -> dict[str, TinfoilFeedTitleDBSchema]: titledb = {} for rom in roms: - match = SWITCH_TITLEDB_REGEX.search(rom.file_name) + match = SWITCH_TITLEDB_REGEX.search(rom.fs_name) if match: _search_term, index_entry = ( - await meta_igdb_handler._switch_titledb_format(match, rom.file_name) + await meta_igdb_handler._switch_titledb_format(match, rom.fs_name) ) if index_entry: titledb[str(index_entry["nsuId"])] = TinfoilFeedTitleDBSchema( @@ -160,9 +160,7 @@ async def tinfoil_index_feed( files=[ TinfoilFeedFileSchema( url=str( - request.url_for( - "get_rom_content", id=rom.id, file_name=rom.file_name - ) + request.url_for("get_rom_content", id=rom.id, file_name=rom.fs_name) ), size=rom.file_size_bytes, ) diff --git a/backend/endpoints/firmware.py b/backend/endpoints/firmware.py index 39a1dc5b6..6f6a4c16d 100644 --- a/backend/endpoints/firmware.py +++ b/backend/endpoints/firmware.py @@ -28,25 +28,28 @@ def add_firmware( files (list[UploadFile], optional): List of files to upload Raises: - HTTPException: No files were uploaded + HTTPException Returns: AddFirmwareResponse: Standard message response """ db_platform = db_platform_handler.get_platform(platform_id) + if not db_platform: + error = f"Platform with ID {platform_id} not found" + log.error(error) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error) + log.info(f"Uploading firmware to {db_platform.fs_slug}") - if files is None: - log.error("No files were uploaded") - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="No files were uploaded", - ) uploaded_firmware = [] firmware_path = fs_firmware_handler.build_upload_file_path(db_platform.fs_slug) for file in files: + if not file.filename: + log.warning("Empty filename, skipping") + continue + fs_firmware_handler.write_file(file=file, path=firmware_path) db_firmware = db_firmware_handler.get_firmware_by_filename( @@ -70,10 +73,14 @@ def add_firmware( uploaded_firmware.append(scanned_firmware) db_platform = db_platform_handler.get_platform(platform_id) + if not db_platform: + error = f"Platform with ID {platform_id} not found" + log.error(error) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error) return { "uploaded": len(files), - "firmware": db_platform.firmware, + "firmware": [FirmwareSchema.model_validate(f) for f in db_platform.firmware], } @@ -90,7 +97,10 @@ def get_platform_firmware( Returns: list[FirmwareSchema]: Firmware stored in the database """ - return db_firmware_handler.list_firmware(platform_id=platform_id) + return [ + FirmwareSchema.model_validate(f) + for f in db_firmware_handler.list_firmware(platform_id=platform_id) + ] @protected_route( @@ -108,7 +118,13 @@ def get_firmware(request: Request, id: int) -> FirmwareSchema: Returns: FirmwareSchema: Firmware stored in the database """ - return FirmwareSchema(**db_firmware_handler.get_firmware(id)) + firmware = db_firmware_handler.get_firmware(id) + if not firmware: + error = f"Firmware with ID {id} not found" + log.error(error) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error) + + return FirmwareSchema.model_validate(firmware) @protected_route( @@ -129,6 +145,11 @@ def head_firmware_content(request: Request, id: int, file_name: str): """ firmware = db_firmware_handler.get_firmware(id) + if not firmware: + error = f"Firmware with ID {id} not found" + log.error(error) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error) + firmware_path = f"{LIBRARY_BASE_PATH}/{firmware.full_path}" return FileResponse( @@ -162,6 +183,11 @@ def get_firmware_content( """ firmware = db_firmware_handler.get_firmware(id) + if not firmware: + error = f"Firmware with ID {id} not found" + log.error(error) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error) + firmware_path = f"{LIBRARY_BASE_PATH}/{firmware.full_path}" return FileResponse(path=firmware_path, filename=firmware.file_name) diff --git a/backend/endpoints/platform.py b/backend/endpoints/platform.py index b7b7daf3a..7d9f2e9e1 100644 --- a/backend/endpoints/platform.py +++ b/backend/endpoints/platform.py @@ -12,7 +12,6 @@ from handler.filesystem import fs_platform_handler from handler.metadata.igdb_handler import IGDB_PLATFORM_LIST from handler.scan_handler import scan_platform from logger.logger import log -from models.platform import Platform from utils.router import APIRouter router = APIRouter() @@ -36,7 +35,9 @@ async def add_platforms(request: Request) -> PlatformSchema: except PlatformAlreadyExistsException: log.info(f"Detected platform: {fs_slug}") scanned_platform = await scan_platform(fs_slug, [fs_slug]) - return db_platform_handler.add_platform(scanned_platform) + return PlatformSchema.model_validate( + db_platform_handler.add_platform(scanned_platform) + ) @protected_route(router.get, "/platforms", [Scope.PLATFORMS_READ]) @@ -51,7 +52,9 @@ def get_platforms(request: Request) -> list[PlatformSchema]: list[PlatformSchema]: List of platforms """ - return db_platform_handler.get_platforms() + return [ + PlatformSchema.model_validate(p) for p in db_platform_handler.get_platforms() + ] @protected_route(router.get, "/platforms/supported", [Scope.PLATFORMS_READ]) @@ -66,7 +69,7 @@ def get_supported_platforms(request: Request) -> list[PlatformSchema]: """ supported_platforms = [] - db_platforms: list[Platform] = db_platform_handler.get_platforms() + db_platforms = db_platform_handler.get_platforms() db_platforms_map = {p.name: p.id for p in db_platforms} for platform in IGDB_PLATFORM_LIST: @@ -108,7 +111,7 @@ def get_platform(request: Request, id: int) -> PlatformSchema: if not platform: raise PlatformNotFoundInDatabaseException(id) - return platform + return PlatformSchema.model_validate(platform) @protected_route(router.put, "/platforms/{id}", [Scope.PLATFORMS_WRITE]) diff --git a/backend/endpoints/responses/rom.py b/backend/endpoints/responses/rom.py index f101a7b6c..fac0bbe12 100644 --- a/backend/endpoints/responses/rom.py +++ b/backend/endpoints/responses/rom.py @@ -16,12 +16,12 @@ SORT_COMPARE_REGEX = re.compile(r"^([Tt]he|[Aa]|[Aa]nd)\s") RomIGDBMetadata = TypedDict( # type: ignore[misc] "RomIGDBMetadata", - {k: NotRequired[v] for k, v in get_type_hints(IGDBMetadata).items()}, + dict((k, NotRequired[v]) for k, v in get_type_hints(IGDBMetadata).items()), total=False, ) RomMobyMetadata = TypedDict( # type: ignore[misc] "RomMobyMetadata", - {k: NotRequired[v] for k, v in get_type_hints(MobyMetadata).items()}, + dict((k, NotRequired[v]) for k, v in get_type_hints(MobyMetadata).items()), total=False, ) @@ -179,16 +179,15 @@ class SimpleRomSchema(RomSchema): @classmethod def from_orm_with_request(cls, db_rom: Rom, request: Request) -> SimpleRomSchema: user_id = request.user.id - - db_rom.rom_user = RomUserSchema.for_user(user_id, db_rom) - - return cls.model_validate(db_rom) + rom = cls.model_validate(db_rom) + rom.rom_user = RomUserSchema.for_user(user_id, db_rom) + return rom @classmethod def from_orm_with_factory(cls, db_rom: Rom) -> SimpleRomSchema: - db_rom.rom_user = rom_user_schema_factory() - - return cls.model_validate(db_rom) + rom = cls.model_validate(db_rom) + rom.rom_user = rom_user_schema_factory() + return rom class DetailedRomSchema(RomSchema): @@ -205,24 +204,26 @@ class DetailedRomSchema(RomSchema): def from_orm_with_request(cls, db_rom: Rom, request: Request) -> DetailedRomSchema: user_id = request.user.id - db_rom.rom_user = RomUserSchema.for_user(user_id, db_rom) - db_rom.user_notes = RomUserSchema.notes_for_user(user_id, db_rom) - db_rom.user_saves = [ + rom = cls.model_validate(db_rom) + + rom.rom_user = RomUserSchema.for_user(user_id, db_rom) + rom.user_notes = RomUserSchema.notes_for_user(user_id, db_rom) + rom.user_saves = [ SaveSchema.model_validate(s) for s in db_rom.saves if s.user_id == user_id ] - db_rom.user_states = [ + rom.user_states = [ StateSchema.model_validate(s) for s in db_rom.states if s.user_id == user_id ] - db_rom.user_screenshots = [ + rom.user_screenshots = [ ScreenshotSchema.model_validate(s) for s in db_rom.screenshots if s.user_id == user_id ] - db_rom.user_collections = CollectionSchema.for_user( + rom.user_collections = CollectionSchema.for_user( user_id, db_rom.get_collections() ) - return cls.model_validate(db_rom) + return rom class UserNotesSchema(TypedDict): diff --git a/backend/endpoints/rom.py b/backend/endpoints/rom.py index e97ff30e3..ab05d7ce3 100644 --- a/backend/endpoints/rom.py +++ b/backend/endpoints/rom.py @@ -187,16 +187,16 @@ async def head_rom_content( raise RomNotFoundInDatabaseException(id) rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}" - files_to_check = files or [r["filename"] for r in rom.files] + files_to_check = files or [r.file_name for r in rom.files] if not rom.multi: # Serve the file directly in development mode for emulatorjs if DEV_MODE: return FileResponse( path=rom_path, - filename=rom.file_name, + filename=rom.fs_name, headers={ - "Content-Disposition": f'attachment; filename="{quote(rom.file_name)}"', + "Content-Disposition": f'attachment; filename="{quote(rom.fs_name)}"', "Content-Type": "application/octet-stream", "Content-Length": str(rom.file_size_bytes), }, @@ -204,7 +204,7 @@ async def head_rom_content( return FileRedirectResponse( download_path=Path(f"/library/{rom.full_path}"), - filename=rom.file_name, + filename=rom.fs_name, ) if len(files_to_check) == 1: @@ -252,14 +252,14 @@ async def get_rom_content( raise RomNotFoundInDatabaseException(id) rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}" - files_to_download = sorted(files or [r["filename"] for r in rom.files]) + files_to_download = sorted(files or [r.file_name for r in rom.files]) - log.info(f"User {current_username} is downloading {rom.file_name}") + log.info(f"User {current_username} is downloading {rom.fs_name}") if not rom.multi: return FileRedirectResponse( download_path=Path(f"/library/{rom.full_path}"), - filename=rom.file_name, + filename=rom.fs_name, ) if len(files_to_download) == 1: @@ -332,7 +332,7 @@ async def update_rom( "igdb_id": None, "sgdb_id": None, "moby_id": None, - "name": rom.file_name, + "name": rom.fs_name, "summary": "", "url_screenshots": [], "path_screenshots": [], @@ -346,20 +346,20 @@ async def update_rom( }, ) - return DetailedRomSchema.from_orm_with_request( - db_rom_handler.get_rom(id), request - ) + rom = db_rom_handler.get_rom(id) + if not rom: + raise RomNotFoundInDatabaseException(id) - cleaned_data = { - "igdb_id": data.get("igdb_id", None), - "moby_id": data.get("moby_id", None), + return DetailedRomSchema.from_orm_with_request(rom, request) + + cleaned_data: dict = { + "igdb_id": str(data.get("igdb_id", "")), + "moby_id": str(data.get("moby_id", "")), } - if ( - cleaned_data.get("moby_id", "") - and int(cleaned_data.get("moby_id", "")) != rom.moby_id - ): - moby_rom = await meta_moby_handler.get_rom_by_id(cleaned_data["moby_id"]) + moby_id: str = cleaned_data["moby_id"] + if moby_id and int(moby_id) != rom.moby_id: + moby_rom = await meta_moby_handler.get_rom_by_id(int(moby_id)) cleaned_data.update(moby_rom) path_screenshots = await fs_resource_handler.get_rom_screenshots( rom=rom, @@ -367,11 +367,9 @@ async def update_rom( ) cleaned_data.update({"path_screenshots": path_screenshots}) - if ( - cleaned_data.get("igdb_id", "") - and int(cleaned_data.get("igdb_id", "")) != rom.igdb_id - ): - igdb_rom = await meta_igdb_handler.get_rom_by_id(cleaned_data["igdb_id"]) + igdb_id: str = cleaned_data["igdb_id"] + if igdb_id and int(igdb_id) != rom.igdb_id: + igdb_rom = await meta_igdb_handler.get_rom_by_id(int(igdb_id)) cleaned_data.update(igdb_rom) path_screenshots = await fs_resource_handler.get_rom_screenshots( rom=rom, @@ -386,26 +384,26 @@ async def update_rom( } ) - new_file_name = data.get("file_name", rom.file_name) + new_file_name = str(data.get("file_name", rom.fs_name)) try: if rename_as_source: - new_file_name = rom.file_name.replace( - rom.file_name_no_tags or rom.file_name_no_ext, - data.get("name", rom.name), + new_file_name = rom.fs_name.replace( + rom.fs_name_no_tags or rom.fs_name_no_ext, + str(data.get("name", rom.name)), ) new_file_name = sanitize_filename(new_file_name) fs_rom_handler.rename_file( - old_name=rom.file_name, + old_name=rom.fs_name, new_name=new_file_name, - file_path=rom.file_path, + file_path=rom.fs_path, ) - elif rom.file_name != new_file_name: + elif rom.fs_name != new_file_name: new_file_name = sanitize_filename(new_file_name) fs_rom_handler.rename_file( - old_name=rom.file_name, + old_name=rom.fs_name, new_name=new_file_name, - file_path=rom.file_path, + file_path=rom.fs_path, ) except RomAlreadyExistsException as exc: log.error(exc) @@ -429,7 +427,7 @@ async def update_rom( cleaned_data.update(fs_resource_handler.remove_cover(rom)) cleaned_data.update({"url_cover": ""}) else: - if artwork: + if artwork is not None and artwork.filename is not None: file_ext = artwork.filename.split(".")[-1] ( path_cover_l, @@ -459,15 +457,18 @@ async def update_rom( path_cover_s, path_cover_l = await fs_resource_handler.get_cover( overwrite=True, entity=rom, - url_cover=data.get("url_cover", ""), + url_cover=str(data.get("url_cover", "")), ) cleaned_data.update( {"path_cover_s": path_cover_s, "path_cover_l": path_cover_l} ) db_rom_handler.update_rom(id, cleaned_data) + rom = db_rom_handler.get_rom(id) + if not rom: + raise RomNotFoundInDatabaseException(id) - return DetailedRomSchema.from_orm_with_request(db_rom_handler.get_rom(id), request) + return DetailedRomSchema.from_orm_with_request(rom, request) @protected_route(router.post, "/roms/delete", [Scope.ROMS_WRITE]) @@ -497,13 +498,15 @@ async def delete_roms( if not rom: raise RomNotFoundInDatabaseException(id) - log.info(f"Deleting {rom.file_name} from database") + log.info(f"Deleting {rom.fs_name} from database") db_rom_handler.delete_rom(id) # Update collections to remove the deleted rom collections = db_collection_handler.get_collections_by_rom_id(id) for collection in collections: - collection.roms = [rom_id for rom_id in collection.roms if rom_id != id] + collection.roms = set( + [rom_id for rom_id in collection.roms if rom_id != id] + ) db_collection_handler.update_collection( collection.id, {"roms": collection.roms} ) @@ -514,13 +517,13 @@ async def delete_roms( log.error(f"Couldn't find resources to delete for {rom.name}") if id in delete_from_fs: - log.info(f"Deleting {rom.file_name} from filesystem") + log.info(f"Deleting {rom.fs_name} from filesystem") try: - fs_rom_handler.remove_file( - file_name=rom.file_name, file_path=rom.file_path - ) + fs_rom_handler.remove_file(file_name=rom.fs_name, file_path=rom.fs_name) except FileNotFoundError as exc: - error = f"Rom file {rom.file_name} not found for platform {rom.platform_slug}" + error = ( + f"Rom file {rom.fs_name} not found for platform {rom.platform_slug}" + ) log.error(error) raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=error @@ -556,5 +559,6 @@ async def update_rom_user(request: Request, id: int) -> RomUserSchema: ] cleaned_data = {field: data[field] for field in fields_to_update if field in data} + rom_user = db_rom_handler.update_rom_user(db_rom_user.id, cleaned_data) - return db_rom_handler.update_rom_user(db_rom_user.id, cleaned_data) + return RomUserSchema.model_validate(rom_user) diff --git a/backend/endpoints/saves.py b/backend/endpoints/saves.py index 5cee897ec..448cb8aa2 100644 --- a/backend/endpoints/saves.py +++ b/backend/endpoints/saves.py @@ -29,18 +29,15 @@ def add_saves( current_user = request.user log.info(f"Uploading saves to {rom.name}") - if saves is None: - log.error("No saves were uploaded") - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="No saves were uploaded", - ) - saves_path = fs_asset_handler.build_saves_file_path( user=request.user, platform_fs_slug=rom.platform.fs_slug, emulator=emulator ) for save in saves: + if not save.filename: + log.error("Save file has no filename") + continue + fs_asset_handler.write_file(file=save, path=saves_path) # Scan or update save @@ -79,7 +76,11 @@ def add_saves( return { "uploaded": len(saves), - "saves": [s for s in rom.saves if s.user_id == current_user.id], + "saves": [ + SaveSchema.model_validate(s) + for s in rom.saves + if s.user_id == current_user.id + ], } @@ -109,7 +110,7 @@ async def update_save(request: Request, id: int) -> SaveSchema: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=error) if "file" in data: - file: UploadFile = data["file"] + file: UploadFile = data["file"] # type: ignore fs_asset_handler.write_file(file=file, path=db_save.file_path) db_save_handler.update_save(db_save.id, {"file_size_bytes": file.size}) @@ -124,7 +125,7 @@ async def update_save(request: Request, id: int) -> SaveSchema: # Refetch the save to get updated fields db_save = db_save_handler.get_save(id) - return db_save + return SaveSchema.model_validate(db_save) @protected_route(router.post, "/saves/delete", [Scope.ASSETS_WRITE]) diff --git a/backend/endpoints/screenshots.py b/backend/endpoints/screenshots.py index 480a52407..10fc9b8d5 100644 --- a/backend/endpoints/screenshots.py +++ b/backend/endpoints/screenshots.py @@ -1,6 +1,7 @@ from decorators.auth import protected_route -from endpoints.responses.assets import UploadedScreenshotsResponse -from fastapi import File, HTTPException, Request, UploadFile, status +from endpoints.responses.assets import ScreenshotSchema, UploadedScreenshotsResponse +from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException +from fastapi import File, Request, UploadFile from handler.auth.base_handler import Scope from handler.database import db_rom_handler, db_screenshot_handler from handler.filesystem import fs_asset_handler @@ -18,21 +19,21 @@ def add_screenshots( screenshots: list[UploadFile] = File(...), # noqa: B008 ) -> UploadedScreenshotsResponse: rom = db_rom_handler.get_rom(rom_id) + if not rom: + raise RomNotFoundInDatabaseException(rom_id) + current_user = request.user log.info(f"Uploading screenshots to {rom.name}") - if screenshots is None: - log.error("No screenshots were uploaded") - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="No screenshots were uploaded", - ) - screenshots_path = fs_asset_handler.build_screenshots_file_path( user=request.user, platform_fs_slug=rom.platform_slug ) for screenshot in screenshots: + if not screenshot.filename: + log.warning("Skipping empty screenshot") + continue + fs_asset_handler.write_file(file=screenshot, path=screenshots_path) # Scan or update screenshot @@ -56,8 +57,15 @@ def add_screenshots( db_screenshot_handler.add_screenshot(scanned_screenshot) rom = db_rom_handler.get_rom(rom_id) + if not rom: + raise RomNotFoundInDatabaseException(rom_id) + return { "uploaded": len(screenshots), - "screenshots": [s for s in rom.screenshots if s.user_id == current_user.id], + "screenshots": [ + ScreenshotSchema.model_validate(s) + for s in rom.screenshots + if s.user_id == current_user.id + ], "merged_screenshots": rom.merged_screenshots, } diff --git a/backend/endpoints/search.py b/backend/endpoints/search.py index e07d757f1..ce8a103c1 100644 --- a/backend/endpoints/search.py +++ b/backend/endpoints/search.py @@ -5,8 +5,8 @@ from fastapi import HTTPException, Request, status from handler.auth.base_handler import Scope from handler.database import db_rom_handler from handler.metadata import meta_igdb_handler, meta_moby_handler, meta_sgdb_handler -from handler.metadata.igdb_handler import IGDB_API_ENABLED -from handler.metadata.moby_handler import MOBY_API_ENABLED +from handler.metadata.igdb_handler import IGDB_API_ENABLED, IGDBRom +from handler.metadata.moby_handler import MOBY_API_ENABLED, MobyGamesRom from handler.metadata.sgdb_handler import STEAMGRIDDB_API_ENABLED from handler.scan_handler import _get_main_platform_igdb_id from logger.logger import log @@ -43,11 +43,11 @@ async def search_rom( detail="No metadata providers enabled", ) - rom = db_rom_handler.get_rom(rom_id) + rom = db_rom_handler.get_rom(int(rom_id)) if not rom: return [] - search_term = search_term or rom.file_name_no_tags + search_term = search_term or rom.fs_name_no_tags if not search_term: return [] @@ -57,7 +57,11 @@ async def search_rom( matched_roms: list = [] log.info(f"Searching by {search_by.lower()}: {search_term}") - log.info(emoji.emojize(f":video_game: {rom.platform_slug}: {rom.file_name}")) + log.info(emoji.emojize(f":video_game: {rom.platform_slug}: {rom.fs_name}")) + + igdb_matched_roms: list[IGDBRom] = [] + moby_matched_roms: list[MobyGamesRom] = [] + if search_by.lower() == "id": try: igdb_matched_roms = await meta_igdb_handler.get_matched_roms_by_id( @@ -73,19 +77,20 @@ async def search_rom( detail=f"Tried searching by ID, but '{search_term}' is not a valid ID", ) from exc elif search_by.lower() == "name": + main_platform_igdb_id = await _get_main_platform_igdb_id(rom.platform) igdb_matched_roms = await meta_igdb_handler.get_matched_roms_by_name( - search_term, (await _get_main_platform_igdb_id(rom.platform)) + search_term, main_platform_igdb_id or rom.platform.igdb_id ) moby_matched_roms = await meta_moby_handler.get_matched_roms_by_name( search_term, rom.platform.moby_id ) merged_dict = { - item["name"]: {**item, "igdb_url_cover": item.pop("url_cover", "")} + item["name"]: {**item, "igdb_url_cover": item.pop("url_cover", "")} # type: ignore for item in igdb_matched_roms } for item in moby_matched_roms: - merged_dict[item["name"]] = { + merged_dict[item["name"]] = { # type: ignore **item, "moby_url_cover": item.pop("url_cover", ""), **merged_dict.get(item.get("name", ""), {}), diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 4766a86f7..188f46f67 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -143,7 +143,9 @@ async def scan_platforms( try: platform_list = [ - db_platform_handler.get_platform(s).fs_slug for s in platform_ids + platform.fs_slug + for s in platform_ids + if (platform := db_platform_handler.get_platform(s)) is not None ] or fs_platforms if len(platform_list) == 0: @@ -271,14 +273,14 @@ async def _identify_platform( for fs_roms_batch in batched(fs_roms, 200): rom_by_filename_map = db_rom_handler.get_roms_by_filename( platform_id=platform.id, - file_names={fs_rom["file_name"] for fs_rom in fs_roms_batch}, + file_names={fs_rom["fs_name"] for fs_rom in fs_roms_batch}, ) for fs_rom in fs_roms_batch: scan_stats += await _identify_rom( platform=platform, fs_rom=fs_rom, - rom=rom_by_filename_map.get(fs_rom["file_name"]), + rom=rom_by_filename_map.get(fs_rom["fs_name"]), scan_type=scan_type, roms_ids=roms_ids, metadata_sources=metadata_sources, @@ -290,12 +292,12 @@ async def _identify_platform( # the folder structure is not correct or the drive is not mounted if len(fs_roms) > 0: purged_roms = db_rom_handler.purge_roms( - platform.id, [rom["file_name"] for rom in fs_roms] + platform.id, [rom["fs_name"] for rom in fs_roms] ) if len(purged_roms) > 0: log.info("Purging roms not found in the filesystem:") for r in purged_roms: - log.info(f" - {r.file_name}") + log.info(f" - {r.fs_name}") # Same protection for firmware if len(fs_firmware) > 0: @@ -346,7 +348,7 @@ def _set_rom_hashes(rom_id: int): return try: - rom_hashes = fs_rom_handler.get_rom_hashes(rom.file_name, rom.file_path) + rom_hashes = fs_rom_handler.get_rom_hashes(rom.fs_name, rom.fs_path) db_rom_handler.update_rom( rom_id, { @@ -358,7 +360,7 @@ def _set_rom_hashes(rom_id: int): except zlib.error as e: # Set empty hashes if calculating them fails for corrupted files log.error( - f"Hashes of {rom.file_name} couldn't be calculated: {hl(str(e), color=RED)}" + f"Hashes of {rom.fs_name} couldn't be calculated: {hl(str(e), color=RED)}" ) db_rom_handler.update_rom( rom_id, @@ -387,12 +389,12 @@ async def _identify_rom( if not _should_scan_rom(scan_type=scan_type, rom=rom, roms_ids=roms_ids): if rom and ( - rom.file_name != fs_rom["file_name"] + rom.fs_name != fs_rom["fs_name"] or rom.multi != fs_rom["multi"] or rom.files != fs_rom["files"] ): # Just to update the filesystem data - rom.file_name = fs_rom["file_name"] + rom.fs_name = fs_rom["fs_name"] rom.multi = fs_rom["multi"] rom.files = fs_rom["files"] db_rom_handler.add_rom(rom) diff --git a/backend/endpoints/states.py b/backend/endpoints/states.py index dc95311c6..70e4200b7 100644 --- a/backend/endpoints/states.py +++ b/backend/endpoints/states.py @@ -29,18 +29,15 @@ def add_states( current_user = request.user log.info(f"Uploading states to {rom.name}") - if states is None: - log.error("No states were uploaded") - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="No states were uploaded", - ) - states_path = fs_asset_handler.build_states_file_path( user=request.user, platform_fs_slug=rom.platform.fs_slug, emulator=emulator ) for state in states: + if not state.filename: + log.warning("Skipping file with no filename") + continue + fs_asset_handler.write_file(file=state, path=states_path) # Scan or update state @@ -73,9 +70,16 @@ def add_states( ) rom = db_rom_handler.get_rom(rom_id) + if not rom: + raise RomNotFoundInDatabaseException(rom_id) + return { "uploaded": len(states), - "states": [s for s in rom.states if s.user_id == current_user.id], + "states": [ + StateSchema.model_validate(s) + for s in rom.states + if s.user_id == current_user.id + ], } @@ -105,7 +109,7 @@ async def update_state(request: Request, id: int) -> StateSchema: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=error) if "file" in data: - file: UploadFile = data["file"] + file: UploadFile = data["file"] # type: ignore fs_asset_handler.write_file(file=file, path=db_state.file_path) db_state_handler.update_state(db_state.id, {"file_size_bytes": file.size}) @@ -119,7 +123,7 @@ async def update_state(request: Request, id: int) -> StateSchema: ) db_state = db_state_handler.get_state(id) - return db_state + return StateSchema.model_validate(db_state) @protected_route(router.post, "/states/delete", [Scope.ASSETS_WRITE]) diff --git a/backend/endpoints/user.py b/backend/endpoints/user.py index 98940147b..1488159e7 100644 --- a/backend/endpoints/user.py +++ b/backend/endpoints/user.py @@ -76,7 +76,7 @@ def add_user( role=Role[role.upper()], ) - return db_user_handler.add_user(user) + return UserSchema.model_validate(db_user_handler.add_user(user)) @protected_route(router.get, "/users", [Scope.USERS_READ]) @@ -90,7 +90,7 @@ def get_users(request: Request) -> list[UserSchema]: list[UserSchema]: All users stored in the RomM's database """ - return [u for u in db_user_handler.get_users()] + return [UserSchema.model_validate(u) for u in db_user_handler.get_users()] @protected_route(router.get, "/users/me", [Scope.ME_READ]) @@ -122,7 +122,7 @@ def get_user(request: Request, id: int) -> UserSchema: if not user: raise HTTPException(status_code=404, detail="User not found") - return user + return UserSchema.model_validate(user) @protected_route(router.put, "/users/{id}", [Scope.ME_WRITE]) @@ -215,7 +215,13 @@ async def update_user( if request.user.id == id and creds_updated: request.session.clear() - return db_user_handler.get_user(id) + db_user = db_user_handler.get_user(id) + if not db_user: + msg = f"Username with id {id} not found" + log.error(msg) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=msg) + + return UserSchema.model_validate(db_user) @protected_route(router.delete, "/users/{id}", [Scope.USERS_WRITE]) diff --git a/backend/handler/database/collections_handler.py b/backend/handler/database/collections_handler.py index 4faadc963..9e60b7549 100644 --- a/backend/handler/database/collections_handler.py +++ b/backend/handler/database/collections_handler.py @@ -1,6 +1,8 @@ +from typing import Sequence + from decorators.database import begin_session from models.collection import Collection -from sqlalchemy import Select, delete, select, update +from sqlalchemy import delete, select, update from sqlalchemy.orm import Session from .base_handler import DBBaseHandler @@ -10,10 +12,17 @@ class DBCollectionsHandler(DBBaseHandler): @begin_session def add_collection( self, collection: Collection, session: Session = None - ) -> Collection | None: + ) -> Collection: collection = session.merge(collection) session.flush() - return session.scalar(select(Collection).filter_by(id=collection.id).limit(1)) + + new_collection = session.scalar( + select(Collection).filter_by(id=collection.id).limit(1) + ) + if not new_collection: + raise ValueError("Could not find newly created collection") + + return new_collection @begin_session def get_collection(self, id: int, session: Session = None) -> Collection | None: @@ -28,9 +37,9 @@ class DBCollectionsHandler(DBBaseHandler): ) @begin_session - def get_collections(self, session: Session = None) -> Select[tuple[Collection]]: + def get_collections(self, session: Session = None) -> Sequence[Collection]: return ( - session.scalars(select(Collection).order_by(Collection.name.asc())) # type: ignore[attr-defined] + session.scalars(select(Collection).order_by(Collection.name.asc())) .unique() .all() ) @@ -38,7 +47,7 @@ class DBCollectionsHandler(DBBaseHandler): @begin_session def get_collections_by_rom_id( self, rom_id: int, session: Session = None - ) -> list[Collection]: + ) -> Sequence[Collection]: return session.scalars( select(Collection).filter(Collection.roms.contains(rom_id)) ).all() @@ -56,8 +65,8 @@ class DBCollectionsHandler(DBBaseHandler): return session.query(Collection).filter_by(id=id).one() @begin_session - def delete_collection(self, id: int, session: Session = None) -> int: - return session.execute( + def delete_collection(self, id: int, session: Session = None) -> None: + session.execute( delete(Collection) .where(Collection.id == id) .execution_options(synchronize_session="evaluate") diff --git a/backend/handler/database/firmware_handler.py b/backend/handler/database/firmware_handler.py index 88ccebadd..f99ebc36f 100644 --- a/backend/handler/database/firmware_handler.py +++ b/backend/handler/database/firmware_handler.py @@ -1,3 +1,5 @@ +from typing import Sequence + from decorators.database import begin_session from models.firmware import Firmware from sqlalchemy import and_, delete, select, update @@ -26,7 +28,7 @@ class DBFirmwareHandler(DBBaseHandler): *, platform_id: int | None = None, session: Session = None, - ) -> list[Firmware]: + ) -> Sequence[Firmware]: return session.scalars( select(Firmware) .filter_by(platform_id=platform_id) @@ -45,7 +47,7 @@ class DBFirmwareHandler(DBBaseHandler): @begin_session def update_firmware(self, id: int, data: dict, session: Session = None) -> Firmware: - return session.execute( + return session.scalar( update(Firmware) .where(Firmware.id == id) .values(**data) @@ -54,7 +56,7 @@ class DBFirmwareHandler(DBBaseHandler): @begin_session def delete_firmware(self, id: int, session: Session = None) -> None: - return session.execute( + session.execute( delete(Firmware) .where(Firmware.id == id) .execution_options(synchronize_session="evaluate") @@ -63,7 +65,7 @@ class DBFirmwareHandler(DBBaseHandler): @begin_session def purge_firmware( self, platform_id: int, fs_firmwares: list[str], session: Session = None - ) -> None: + ) -> Sequence[Firmware]: purged_firmware = ( session.scalars( select(Firmware) diff --git a/backend/handler/database/platforms_handler.py b/backend/handler/database/platforms_handler.py index 56ee6261b..e17c5de1f 100644 --- a/backend/handler/database/platforms_handler.py +++ b/backend/handler/database/platforms_handler.py @@ -1,7 +1,9 @@ +from typing import Sequence + from decorators.database import begin_session from models.platform import Platform from models.rom import Rom -from sqlalchemy import Select, delete, or_, select +from sqlalchemy import delete, or_, select from sqlalchemy.orm import Session from .base_handler import DBBaseHandler @@ -21,7 +23,7 @@ class DBPlatformsHandler(DBBaseHandler): select(Platform).filter_by(id=platform.id).limit(1) ) if not new_platform: - raise ValueError("Could not find newlyewly created platform") + raise ValueError("Could not find newly created platform") return new_platform @@ -30,9 +32,9 @@ class DBPlatformsHandler(DBBaseHandler): return session.scalar(select(Platform).filter_by(id=id).limit(1)) @begin_session - def get_platforms(self, *, session: Session = None) -> Select[tuple[Platform]]: + def get_platforms(self, *, session: Session = None) -> Sequence[Platform]: return ( - session.scalars(select(Platform).order_by(Platform.name.asc())) # type: ignore[attr-defined] + session.scalars(select(Platform).order_by(Platform.name.asc())) .unique() .all() ) @@ -61,7 +63,7 @@ class DBPlatformsHandler(DBBaseHandler): @begin_session def purge_platforms( self, fs_platforms: list[str], session: Session = None - ) -> Select[tuple[Platform]]: + ) -> Sequence[Platform]: purged_platforms = ( session.scalars( select(Platform) diff --git a/backend/handler/database/saves_handler.py b/backend/handler/database/saves_handler.py index ac65a177d..698c0279d 100644 --- a/backend/handler/database/saves_handler.py +++ b/backend/handler/database/saves_handler.py @@ -1,3 +1,5 @@ +from typing import Sequence + from decorators.database import begin_session from models.assets import Save from sqlalchemy import and_, delete, select, update @@ -12,7 +14,7 @@ class DBSavesHandler(DBBaseHandler): return session.merge(save) @begin_session - def get_save(self, id: int, session: Session = None) -> Save: + def get_save(self, id: int, session: Session = None) -> Save | None: return session.get(Save, id) @begin_session @@ -27,7 +29,7 @@ class DBSavesHandler(DBBaseHandler): @begin_session def update_save(self, id: int, data: dict, session: Session = None) -> Save: - return session.execute( + return session.scalar( update(Save) .where(Save.id == id) .values(**data) @@ -36,7 +38,7 @@ class DBSavesHandler(DBBaseHandler): @begin_session def delete_save(self, id: int, session: Session = None) -> None: - return session.execute( + session.execute( delete(Save) .where(Save.id == id) .execution_options(synchronize_session="evaluate") @@ -45,8 +47,18 @@ class DBSavesHandler(DBBaseHandler): @begin_session def purge_saves( self, rom_id: int, user_id: int, saves: list[str], session: Session = None - ) -> None: - return session.execute( + ) -> Sequence[Save]: + purged_saves = session.scalars( + select(Save).filter( + and_( + Save.rom_id == rom_id, + Save.user_id == user_id, + Save.file_name.not_in(saves), + ) + ) + ).all() + + session.execute( delete(Save) .where( and_( @@ -57,3 +69,5 @@ class DBSavesHandler(DBBaseHandler): ) .execution_options(synchronize_session="evaluate") ) + + return purged_saves diff --git a/backend/handler/database/screenshots_handler.py b/backend/handler/database/screenshots_handler.py index d7b50c637..94d30f43a 100644 --- a/backend/handler/database/screenshots_handler.py +++ b/backend/handler/database/screenshots_handler.py @@ -1,6 +1,8 @@ +from typing import Sequence + from decorators.database import begin_session from models.assets import Screenshot -from sqlalchemy import delete, select, update +from sqlalchemy import and_, delete, select, update from sqlalchemy.orm import Session from .base_handler import DBBaseHandler @@ -14,7 +16,7 @@ class DBScreenshotsHandler(DBBaseHandler): return session.merge(screenshot) @begin_session - def get_screenshot(self, id, session: Session = None) -> Screenshot: + def get_screenshot(self, id, session: Session = None) -> Screenshot | None: return session.get(Screenshot, id) @begin_session @@ -31,7 +33,7 @@ class DBScreenshotsHandler(DBBaseHandler): def update_screenshot( self, id: int, data: dict, session: Session = None ) -> Screenshot: - return session.execute( + return session.scalar( update(Screenshot) .where(Screenshot.id == id) .values(**data) @@ -40,7 +42,7 @@ class DBScreenshotsHandler(DBBaseHandler): @begin_session def delete_screenshot(self, id: int, session: Session = None) -> None: - return session.execute( + session.execute( delete(Screenshot) .where(Screenshot.id == id) .execution_options(synchronize_session="evaluate") @@ -49,13 +51,27 @@ class DBScreenshotsHandler(DBBaseHandler): @begin_session def purge_screenshots( self, rom_id: int, user_id: int, screenshots: list[str], session: Session = None - ) -> None: - return session.execute( + ) -> Sequence[Screenshot]: + purged_screenshots = session.scalars( + select(Screenshot).filter( + and_( + Screenshot.rom_id == rom_id, + Screenshot.user_id == user_id, + Screenshot.file_name.not_in(screenshots), + ) + ) + ).all() + + session.execute( delete(Screenshot) .where( - Screenshot.rom_id == rom_id, - Screenshot.user_id == user_id, - Screenshot.file_name.not_in(screenshots), + and_( + Screenshot.rom_id == rom_id, + Screenshot.user_id == user_id, + Screenshot.file_name.not_in(screenshots), + ) ) .execution_options(synchronize_session="evaluate") ) + + return purged_screenshots diff --git a/backend/handler/database/states_handler.py b/backend/handler/database/states_handler.py index c70daca14..8b3315e8c 100644 --- a/backend/handler/database/states_handler.py +++ b/backend/handler/database/states_handler.py @@ -1,3 +1,5 @@ +from typing import Sequence + from decorators.database import begin_session from models.assets import State from sqlalchemy import and_, delete, select, update @@ -12,7 +14,7 @@ class DBStatesHandler(DBBaseHandler): return session.merge(state) @begin_session - def get_state(self, id: int, session: Session = None) -> State: + def get_state(self, id: int, session: Session = None) -> State | None: return session.get(State, id) @begin_session @@ -27,7 +29,7 @@ class DBStatesHandler(DBBaseHandler): @begin_session def update_state(self, id: int, data: dict, session: Session = None) -> State: - return session.execute( + return session.scalar( update(State) .where(State.id == id) .values(**data) @@ -36,7 +38,7 @@ class DBStatesHandler(DBBaseHandler): @begin_session def delete_state(self, id: int, session: Session = None) -> None: - return session.execute( + session.execute( delete(State) .where(State.id == id) .execution_options(synchronize_session="evaluate") @@ -45,8 +47,18 @@ class DBStatesHandler(DBBaseHandler): @begin_session def purge_states( self, rom_id: int, user_id: int, states: list[str], session: Session = None - ) -> None: - return session.execute( + ) -> Sequence[State]: + purged_states = session.scalars( + select(State).filter( + and_( + State.rom_id == rom_id, + State.user_id == user_id, + State.file_name.not_in(states), + ) + ) + ).all() + + session.execute( delete(State) .where( and_( @@ -57,3 +69,5 @@ class DBStatesHandler(DBBaseHandler): ) .execution_options(synchronize_session="evaluate") ) + + return purged_states diff --git a/backend/handler/database/stats_handler.py b/backend/handler/database/stats_handler.py index c526456f1..8a8af03db 100644 --- a/backend/handler/database/stats_handler.py +++ b/backend/handler/database/stats_handler.py @@ -11,25 +11,28 @@ class DBStatsHandler(DBBaseHandler): @begin_session def get_platforms_count(self, session: Session = None) -> int: """Get the number of platforms with any roms.""" - return session.scalar( - select(func.count(distinct(Rom.platform_id))).select_from(Rom) + return ( + session.scalar( + select(func.count(distinct(Rom.platform_id))).select_from(Rom) + ) + or 0 ) @begin_session def get_roms_count(self, session: Session = None) -> int: - return session.scalar(select(func.count()).select_from(Rom)) + return session.scalar(select(func.count()).select_from(Rom)) or 0 @begin_session def get_saves_count(self, session: Session = None) -> int: - return session.scalar(select(func.count()).select_from(Save)) + return session.scalar(select(func.count()).select_from(Save)) or 0 @begin_session def get_states_count(self, session: Session = None) -> int: - return session.scalar(select(func.count()).select_from(State)) + return session.scalar(select(func.count()).select_from(State)) or 0 @begin_session def get_screenshots_count(self, session: Session = None) -> int: - return session.scalar(select(func.count()).select_from(Screenshot)) + return session.scalar(select(func.count()).select_from(Screenshot)) or 0 @begin_session def get_total_filesize(self, session: Session = None) -> int: diff --git a/backend/handler/database/users_handler.py b/backend/handler/database/users_handler.py index 1a5da23c3..c17641f06 100644 --- a/backend/handler/database/users_handler.py +++ b/backend/handler/database/users_handler.py @@ -1,3 +1,5 @@ +from typing import Sequence + from decorators.database import begin_session from models.user import Role, User from sqlalchemy import delete, select, update @@ -27,7 +29,7 @@ class DBUsersHandler(DBBaseHandler): @begin_session def update_user(self, id: int, data: dict, session: Session = None) -> User: - return session.execute( + return session.scalar( update(User) .where(User.id == id) .values(**data) @@ -35,7 +37,7 @@ class DBUsersHandler(DBBaseHandler): ) @begin_session - def get_users(self, session: Session = None) -> list[User]: + def get_users(self, session: Session = None) -> Sequence[User]: return session.scalars(select(User)).all() @begin_session @@ -47,5 +49,5 @@ class DBUsersHandler(DBBaseHandler): ) @begin_session - def get_admin_users(self, session: Session = None) -> list[User]: + def get_admin_users(self, session: Session = None) -> Sequence[User]: return session.scalars(select(User).filter_by(role=Role.ADMIN)).all() diff --git a/backend/handler/filesystem/resources_handler.py b/backend/handler/filesystem/resources_handler.py index 033327ef9..df00ecab7 100644 --- a/backend/handler/filesystem/resources_handler.py +++ b/backend/handler/filesystem/resources_handler.py @@ -95,7 +95,7 @@ class FSResourcesHandler(FSHandler): return "" async def get_cover( - self, entity: Rom | Collection | None, overwrite: bool, url_cover: str = "" + self, entity: Rom | Collection | None, overwrite: bool, url_cover: str | None ) -> tuple[str, str]: if not entity: return "", "" @@ -192,9 +192,9 @@ class FSResourcesHandler(FSHandler): return f"{rom.fs_resources_path}/screenshots/{idx}.jpg" async def get_rom_screenshots( - self, rom: Rom | None, url_screenshots: list + self, rom: Rom | None, url_screenshots: list | None ) -> list[str]: - if not rom: + if not rom or not url_screenshots: return [] path_screenshots: list[str] = [] diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 0e425049f..d9f2dcf71 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -8,7 +8,7 @@ import tarfile import zipfile from collections.abc import Callable, Iterator from pathlib import Path -from typing import Any, Final, TypedDict +from typing import Any, Final, Literal, TypedDict import magic import py7zr @@ -59,7 +59,7 @@ FILE_READ_CHUNK_SIZE = 1024 * 8 class FSRom(TypedDict): multi: bool - file_name: str + fs_name: str files: list[RomFile] @@ -90,7 +90,9 @@ def read_zip_file(file_path: Path) -> Iterator[bytes]: yield chunk -def read_tar_file(file_path: Path, mode: str = "r") -> Iterator[bytes]: +def read_tar_file( + file_path: Path, mode: Literal["r", "r:*", "r:", "r:gz", "r:bz2", "r:xz"] = "r" +) -> Iterator[bytes]: try: with tarfile.open(file_path, mode) as f: for member in f.getmembers(): @@ -339,10 +341,10 @@ class FSRomsHandler(FSHandler): raise RomsNotFoundException(platform_fs_slug) from exc fs_roms: list[dict] = [ - {"multi": False, "file_name": rom} + {"multi": False, "fs_name": rom} for rom in self._exclude_files(fs_single_roms, "single") ] + [ - {"multi": True, "file_name": rom} + {"multi": True, "fs_name": rom} for rom in self._exclude_multi_roms(fs_multi_roms) ] @@ -350,12 +352,12 @@ class FSRomsHandler(FSHandler): [ FSRom( multi=rom["multi"], - file_name=rom["file_name"], - files=self.get_rom_files(rom["file_name"], roms_file_path), + fs_name=rom["fs_name"], + files=self.get_rom_files(rom["fs_name"], roms_file_path), ) for rom in fs_roms ], - key=lambda rom: rom["file_name"], + key=lambda rom: rom["fs_name"], ) def file_exists(self, path: str, file_name: str) -> bool: diff --git a/backend/handler/metadata/igdb_handler.py b/backend/handler/metadata/igdb_handler.py index d387540d9..b5a1a17ce 100644 --- a/backend/handler/metadata/igdb_handler.py +++ b/backend/handler/metadata/igdb_handler.py @@ -567,7 +567,7 @@ class IGDBBaseHandler(MetadataHandler): @check_twitch_token async def get_matched_roms_by_name( - self, search_term: str, platform_igdb_id: int + self, search_term: str, platform_igdb_id: int | None ) -> list[IGDBRom]: if not IGDB_API_ENABLED: return [] diff --git a/backend/handler/metadata/moby_handler.py b/backend/handler/metadata/moby_handler.py index 53cba5d3f..c2c57025e 100644 --- a/backend/handler/metadata/moby_handler.py +++ b/backend/handler/metadata/moby_handler.py @@ -310,7 +310,7 @@ class MobyGamesHandler(MetadataHandler): return [rom] if rom["moby_id"] else [] async def get_matched_roms_by_name( - self, search_term: str, platform_moby_id: int + self, search_term: str, platform_moby_id: int | None ) -> list[MobyGamesRom]: if not MOBY_API_ENABLED: return [] diff --git a/backend/models/rom.py b/backend/models/rom.py index f885b5c2c..027aad78f 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -145,6 +145,10 @@ class Rom(BaseModel): def multi(self) -> bool: return len(self.files) > 1 + @cached_property + def file_size_bytes(self) -> int: + return sum(f.file_size_bytes for f in self.files) + def get_collections(self) -> list[Collection]: from handler.database import db_rom_handler From 7bde4aee7037e89604d47d658adbb1de2b1ba42c Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Fri, 20 Dec 2024 23:45:25 -0500 Subject: [PATCH 05/33] complete the rst of the files --- backend/handler/auth/hybrid_auth.py | 21 ++-- backend/handler/auth/tests/test_auth.py | 98 +++++++++++-------- backend/handler/filesystem/assets_handler.py | 4 + .../handler/filesystem/firmware_handler.py | 4 + backend/handler/filesystem/tests/test_fs.py | 4 +- backend/handler/metadata/igdb_handler.py | 4 +- backend/handler/metadata/moby_handler.py | 4 +- backend/handler/scan_handler.py | 8 +- backend/handler/tests/test_db_handler.py | 1 + backend/handler/tests/test_fastapi.py | 4 +- backend/logger/formatter.py | 6 +- backend/models/tests/test_rom.py | 7 +- backend/tasks/tasks.py | 3 +- 13 files changed, 99 insertions(+), 69 deletions(-) diff --git a/backend/handler/auth/hybrid_auth.py b/backend/handler/auth/hybrid_auth.py index 2bcd30d75..e9a258404 100644 --- a/backend/handler/auth/hybrid_auth.py +++ b/backend/handler/auth/hybrid_auth.py @@ -1,11 +1,14 @@ from fastapi.security.http import HTTPBasic from handler.auth import auth_handler, oauth_handler +from models.user import User from starlette.authentication import AuthCredentials, AuthenticationBackend from starlette.requests import HTTPConnection class HybridAuthBackend(AuthenticationBackend): - async def authenticate(self, conn: HTTPConnection): + async def authenticate( + self, conn: HTTPConnection + ) -> tuple[AuthCredentials, User] | None: # Check if session key already stored in cache user = await auth_handler.get_current_active_user_from_session(conn) if user: @@ -14,7 +17,7 @@ class HybridAuthBackend(AuthenticationBackend): # Check if Authorization header exists if "Authorization" not in conn.headers: - return (AuthCredentials([]), None) + return None scheme, token = conn.headers["Authorization"].split() @@ -22,13 +25,13 @@ class HybridAuthBackend(AuthenticationBackend): if scheme.lower() == "basic": credentials = await HTTPBasic().__call__(conn) # type: ignore[arg-type] if not credentials: - return (AuthCredentials([]), None) + return None user = auth_handler.authenticate_user( credentials.username, credentials.password ) if user is None: - return (AuthCredentials([]), None) + return None user.set_last_active() return (AuthCredentials(user.oauth_scopes), user) @@ -39,18 +42,18 @@ class HybridAuthBackend(AuthenticationBackend): user, claims, ) = await oauth_handler.get_current_active_user_from_bearer_token(token) - if user is None: - return (AuthCredentials([]), None) + if user is None or claims is None: + return None # Only access tokens can request resources if claims.get("type") != "access": - return (AuthCredentials([]), None) + return None # Only grant access to resources with overlapping scopes - token_scopes = set(list(claims.get("scopes").split(" "))) + token_scopes = set(list(claims.get("scopes", "").split(" "))) overlapping_scopes = list(token_scopes & set(user.oauth_scopes)) user.set_last_active() return (AuthCredentials(overlapping_scopes), user) - return (AuthCredentials([]), None) + return None diff --git a/backend/handler/auth/tests/test_auth.py b/backend/handler/auth/tests/test_auth.py index 9de47ec02..e0fffdb92 100644 --- a/backend/handler/auth/tests/test_auth.py +++ b/backend/handler/auth/tests/test_auth.py @@ -7,6 +7,7 @@ from handler.auth.base_handler import WRITE_SCOPES from handler.auth.hybrid_auth import HybridAuthBackend from handler.database import db_user_handler from models.user import User +from starlette.requests import HTTPConnection def test_verify_password(): @@ -26,9 +27,9 @@ def test_authenticate_user(admin_user: User): async def test_get_current_active_user_from_session(editor_user: User): - class MockConnection: + class MockConnection(HTTPConnection): def __init__(self): - self.session = {"iss": "romm:auth", "sub": editor_user.username} + self.scope["session"] = {"iss": "romm:auth", "sub": editor_user.username} conn = MockConnection() current_user = await auth_handler.get_current_active_user_from_session(conn) @@ -39,9 +40,9 @@ async def test_get_current_active_user_from_session(editor_user: User): async def test_get_current_active_user_from_session_bad_username(editor_user: User): - class MockConnection: + class MockConnection(HTTPConnection): def __init__(self): - self.session = {"iss": "romm:auth", "sub": "not_real_username"} + self.scope["session"] = {"iss": "romm:auth", "sub": "not_real_username"} conn = MockConnection() @@ -53,10 +54,10 @@ async def test_get_current_active_user_from_session_bad_username(editor_user: Us async def test_get_current_active_user_from_session_disabled_user(editor_user: User): - class MockConnection: + class MockConnection(HTTPConnection): def __init__(self): - self.session = {"iss": "romm:auth", "sub": editor_user.username} - self.headers = {} + self.scope["session"] = {"iss": "romm:auth", "sub": editor_user.username} + self._headers = {} conn = MockConnection() @@ -70,32 +71,35 @@ async def test_get_current_active_user_from_session_disabled_user(editor_user: U async def test_hybrid_auth_backend_session(editor_user: User): - class MockConnection: + class MockConnection(HTTPConnection): def __init__(self): - self.session = {"iss": "romm:auth", "sub": editor_user.username} + self.scope["session"] = {"iss": "romm:auth", "sub": editor_user.username} backend = HybridAuthBackend() conn = MockConnection() - creds, user = await backend.authenticate(conn) + result = await backend.authenticate(conn) + assert result is not None + creds, user = result assert user.id == editor_user.id assert creds.scopes == editor_user.oauth_scopes assert creds.scopes == WRITE_SCOPES async def test_hybrid_auth_backend_empty_session_and_headers(editor_user: User): - class MockConnection: + class MockConnection(HTTPConnection): def __init__(self): - self.session = {} - self.headers = {} + self.scope["session"] = {} + self._headers = {} backend = HybridAuthBackend() conn = MockConnection() - creds, user = await backend.authenticate(conn) + result = await backend.authenticate(conn) + assert result is not None - assert not user + creds, user = result assert creds.scopes == [] @@ -109,25 +113,27 @@ async def test_hybrid_auth_backend_bearer_auth_header(editor_user: User): }, ) - class MockConnection: + class MockConnection(HTTPConnection): def __init__(self): - self.session = {} - self.headers = {"Authorization": f"Bearer {access_token}"} + self.scope["session"] = {} + self._headers = {"Authorization": f"Bearer {access_token}"} backend = HybridAuthBackend() conn = MockConnection() - creds, user = await backend.authenticate(conn) + result = await backend.authenticate(conn) + assert result is not None + creds, user = result assert user.id == editor_user.id assert set(creds.scopes).issubset(editor_user.oauth_scopes) async def test_hybrid_auth_backend_bearer_invalid_token(editor_user: User): - class MockConnection: + class MockConnection(HTTPConnection): def __init__(self): - self.session = {} - self.headers = {"Authorization": "Bearer invalid_token"} + self.scope["session"] = {} + self._headers = {"Authorization": "Bearer invalid_token"} backend = HybridAuthBackend() conn = MockConnection() @@ -139,26 +145,28 @@ async def test_hybrid_auth_backend_bearer_invalid_token(editor_user: User): async def test_hybrid_auth_backend_basic_auth_header(editor_user: User): token = b64encode(b"test_editor:test_editor_password").decode() - class MockConnection: + class MockConnection(HTTPConnection): def __init__(self): - self.session = {} - self.headers = {"Authorization": f"Basic {token}"} + self.scope["session"] = {} + self._headers = {"Authorization": f"Basic {token}"} backend = HybridAuthBackend() conn = MockConnection() - creds, user = await backend.authenticate(conn) + result = await backend.authenticate(conn) + assert result is not None + creds, user = result assert user.id == editor_user.id assert creds.scopes == WRITE_SCOPES assert set(creds.scopes).issubset(editor_user.oauth_scopes) async def test_hybrid_auth_backend_basic_auth_header_unencoded(editor_user: User): - class MockConnection: + class MockConnection(HTTPConnection): def __init__(self): - self.session = {} - self.headers = {"Authorization": "Basic test_editor:test_editor_password"} + self.scope["session"] = {} + self._headers = {"Authorization": "Basic test_editor:test_editor_password"} backend = HybridAuthBackend() conn = MockConnection() @@ -168,17 +176,18 @@ async def test_hybrid_auth_backend_basic_auth_header_unencoded(editor_user: User async def test_hybrid_auth_backend_invalid_scheme(): - class MockConnection: + class MockConnection(HTTPConnection): def __init__(self): - self.session = {} - self.headers = {"Authorization": "Some invalid_scheme"} + self.scope["session"] = {} + self._headers = {"Authorization": "Some invalid_scheme"} backend = HybridAuthBackend() conn = MockConnection() - creds, user = await backend.authenticate(conn) + result = await backend.authenticate(conn) + assert result is not None - assert not user + creds, user = result assert creds.scopes == [] @@ -192,17 +201,18 @@ async def test_hybrid_auth_backend_with_refresh_token(editor_user: User): }, ) - class MockConnection: + class MockConnection(HTTPConnection): def __init__(self): - self.session = {} - self.headers = {"Authorization": f"Bearer {refresh_token}"} + self.scope["session"] = {} + self._headers = {"Authorization": f"Bearer {refresh_token}"} backend = HybridAuthBackend() conn = MockConnection() - creds, user = await backend.authenticate(conn) + result = await backend.authenticate(conn) + assert result is not None - assert not user + creds, user = result assert creds.scopes == [] @@ -217,16 +227,18 @@ async def test_hybrid_auth_backend_scope_subset(editor_user: User): }, ) - class MockConnection: + class MockConnection(HTTPConnection): def __init__(self): - self.session = {} - self.headers = {"Authorization": f"Bearer {access_token}"} + self.scope["session"] = {} + self._headers = {"Authorization": f"Bearer {access_token}"} backend = HybridAuthBackend() conn = MockConnection() - creds, user = await backend.authenticate(conn) + result = await backend.authenticate(conn) + assert result is not None + creds, user = result assert user.id == editor_user.id assert set(creds.scopes).issubset(editor_user.oauth_scopes) assert set(creds.scopes).issubset(scopes) diff --git a/backend/handler/filesystem/assets_handler.py b/backend/handler/filesystem/assets_handler.py index 5d5a8f667..5de48cd12 100644 --- a/backend/handler/filesystem/assets_handler.py +++ b/backend/handler/filesystem/assets_handler.py @@ -21,6 +21,10 @@ class FSAssetsHandler(FSHandler): shutil.rmtree(os.path.join(ASSETS_BASE_PATH, file_path, file_name)) def write_file(self, file: UploadFile, path: str) -> None: + if not file.filename: + log.error("No file name provided") + return + Path(os.path.join(ASSETS_BASE_PATH, path)).mkdir(parents=True, exist_ok=True) log.info(f" - Uploading {file.filename}") file_location = os.path.join(ASSETS_BASE_PATH, path, file.filename) diff --git a/backend/handler/filesystem/firmware_handler.py b/backend/handler/filesystem/firmware_handler.py index 4aa00c13f..82b70d798 100644 --- a/backend/handler/filesystem/firmware_handler.py +++ b/backend/handler/filesystem/firmware_handler.py @@ -85,6 +85,10 @@ class FSFirmwareHandler(FSHandler): return f"{LIBRARY_BASE_PATH}/{file_path}" def write_file(self, file: UploadFile, path: str) -> None: + if not file.filename: + log.error("No file name provided") + return + Path(path).mkdir(parents=True, exist_ok=True) log.info(f" - Uploading {file.filename}") file_location = os.path.join(path, file.filename) diff --git a/backend/handler/filesystem/tests/test_fs.py b/backend/handler/filesystem/tests/test_fs.py index 360539046..652259149 100644 --- a/backend/handler/filesystem/tests/test_fs.py +++ b/backend/handler/filesystem/tests/test_fs.py @@ -32,10 +32,10 @@ def test_get_roms(): roms = fs_rom_handler.get_roms(platform_fs_slug=platform.fs_slug) assert len(roms) == 2 - assert roms[0]["file_name"] == "Paper Mario (USA).z64" + assert roms[0]["fs_name"] == "Paper Mario (USA).z64" assert not roms[0]["multi"] - assert roms[1]["file_name"] == "Super Mario 64 (J) (Rev A)" + assert roms[1]["fs_name"] == "Super Mario 64 (J) (Rev A)" assert roms[1]["multi"] diff --git a/backend/handler/metadata/igdb_handler.py b/backend/handler/metadata/igdb_handler.py index b5a1a17ce..3d83d74d8 100644 --- a/backend/handler/metadata/igdb_handler.py +++ b/backend/handler/metadata/igdb_handler.py @@ -236,6 +236,8 @@ class IGDBBaseHandler(MetadataHandler): async def _request(self, url: str, data: str, timeout: int = 120) -> list: httpx_client = ctx_httpx_client.get() + masked_headers = {} + try: masked_headers = self._mask_sensitive_values(self.headers) log.debug( @@ -637,7 +639,7 @@ class IGDBBaseHandler(MetadataHandler): ) ), "url_screenshots": [ - self._normalize_cover_url(s.get("url", "")).replace( + self._normalize_cover_url(s.get("url", "")).replace( # type: ignore[attr-defined] "t_thumb", "t_720p" ) for s in rom.get("screenshots", []) diff --git a/backend/handler/metadata/moby_handler.py b/backend/handler/metadata/moby_handler.py index c2c57025e..efc4655f6 100644 --- a/backend/handler/metadata/moby_handler.py +++ b/backend/handler/metadata/moby_handler.py @@ -325,8 +325,8 @@ class MobyGamesHandler(MetadataHandler): matched_roms = (await self._request(str(url))).get("games", []) return [ - MobyGamesRom( # type: ignore[misc] - { + MobyGamesRom( + { # type: ignore[misc] k: v for k, v in { "moby_id": rom["game_id"], diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 2faa2cb6e..131745ea1 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -175,18 +175,18 @@ async def scan_rom( roms_path = fs_rom_handler.get_roms_fs_structure(platform.fs_slug) - log.info(f"\t · {hl(fs_rom['file_name'])}") + log.info(f"\t · {hl(fs_rom['fs_name'])}") if fs_rom.get("multi", False): for file in fs_rom["files"]: - log.info(f"\t\t · {file['filename']}") + log.info(f"\t\t · {file.file_name}") # Set default properties rom_attrs = { **fs_rom, "id": rom.id if rom else None, "platform_id": platform.id, - "name": fs_rom["file_name"], + "name": fs_rom["fs_name"], "url_cover": "", "url_screenshots": [], } @@ -257,7 +257,7 @@ async def scan_rom( ): main_platform_igdb_id = await _get_main_platform_igdb_id(platform) return await meta_igdb_handler.get_rom( - rom_attrs["file_name"], main_platform_igdb_id + rom_attrs["file_name"], main_platform_igdb_id or platform.igdb_id ) return IGDBRom(igdb_id=None) diff --git a/backend/handler/tests/test_db_handler.py b/backend/handler/tests/test_db_handler.py index 6e0f589d0..78cfe7df6 100644 --- a/backend/handler/tests/test_db_handler.py +++ b/backend/handler/tests/test_db_handler.py @@ -24,6 +24,7 @@ def test_platforms(): assert len(platforms) == 1 platform = db_platform_handler.get_platform_by_fs_slug(platform.fs_slug) + assert platform is not None assert platform.name == "test_platform" db_platform_handler.purge_platforms([]) diff --git a/backend/handler/tests/test_fastapi.py b/backend/handler/tests/test_fastapi.py index 6b17b5d6c..a307f42c5 100644 --- a/backend/handler/tests/test_fastapi.py +++ b/backend/handler/tests/test_fastapi.py @@ -40,12 +40,12 @@ async def test_scan_rom(): rom = await scan_rom( platform, - {"file_name": "Paper Mario (USA).z64", "multi": False, "files": files}, + {"fs_name": "Paper Mario (USA).z64", "multi": False, "files": files}, ScanType.QUICK, ) assert type(rom) is Rom - assert rom.file_name == "Paper Mario (USA).z64" + assert rom.fs_name == "Paper Mario (USA).z64" assert rom.name == "Paper Mario" assert rom.igdb_id == 3340 assert rom.file_size_bytes == 1024 diff --git a/backend/logger/formatter.py b/backend/logger/formatter.py index 501e664d9..fee4e816a 100644 --- a/backend/logger/formatter.py +++ b/backend/logger/formatter.py @@ -45,17 +45,17 @@ class Formatter(logging.Formatter): level = "%(levelname)s" dots = f"{Fore.RESET}:" identifier = ( - f"\t {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[{str(record.module_name).lower()}]" + f"\t {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[{record.module.lower()}]" if hasattr(record, "module_name") else f"\t {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[%(module)s]" ) identifier_warning = ( - f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[{str(record.module_name).lower()}]" + f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[{record.module.lower()}]" if hasattr(record, "module_name") else f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[%(module)s]" ) identifier_critical = ( - f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[{str(record.module_name).lower()}]" + f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[{record.module.lower()}]" if hasattr(record, "module_name") else f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[%(module)s]" ) diff --git a/backend/models/tests/test_rom.py b/backend/models/tests/test_rom.py index d716e60dd..e65d4b4c0 100644 --- a/backend/models/tests/test_rom.py +++ b/backend/models/tests/test_rom.py @@ -1,3 +1,6 @@ -def test_rom(rom): - assert rom.file_path == "test_platform_slug/roms" +from models.rom import Rom + + +def test_rom(rom: Rom): + assert rom.fs_path == "test_platform_slug/roms" assert rom.full_path == "test_platform_slug/roms/test_rom.zip" diff --git a/backend/tasks/tasks.py b/backend/tasks/tasks.py index 9846507c6..0e3329e73 100644 --- a/backend/tasks/tasks.py +++ b/backend/tasks/tasks.py @@ -5,6 +5,7 @@ import httpx from exceptions.task_exceptions import SchedulerException from handler.redis_handler import low_prio_queue from logger.logger import log +from rq.job import Job from rq_scheduler import Scheduler from utils.context import ctx_httpx_client @@ -27,7 +28,7 @@ class PeriodicTask(ABC): def _get_existing_job(self): existing_jobs = tasks_scheduler.get_jobs() for job in existing_jobs: - if job.func_name == self.func: + if isinstance(job, Job) and job.func_name == self.func: return job return None From 55eee458a1b217a8de0c07952698678310ff3210 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 21 Dec 2024 00:37:37 -0500 Subject: [PATCH 06/33] actaully complete backend --- backend/endpoints/feeds.py | 8 +- backend/endpoints/responses/rom.py | 16 ++-- backend/endpoints/rom.py | 26 +++---- backend/endpoints/sockets/scan.py | 4 +- backend/endpoints/tests/test_rom.py | 4 +- backend/handler/database/roms_handler.py | 67 +++++++++-------- backend/handler/database/stats_handler.py | 7 +- .../handler/filesystem/resources_handler.py | 9 +-- backend/handler/filesystem/roms_handler.py | 18 ++--- backend/handler/metadata/igdb_handler.py | 12 +-- backend/handler/metadata/moby_handler.py | 12 +-- backend/handler/scan_handler.py | 28 ++++--- backend/handler/tests/conftest.py | 11 ++- backend/handler/tests/test_db_handler.py | 74 ++++++++++--------- backend/models/rom.py | 4 +- 15 files changed, 155 insertions(+), 145 deletions(-) diff --git a/backend/endpoints/feeds.py b/backend/endpoints/feeds.py index 0f61bec9f..7f802cac0 100644 --- a/backend/endpoints/feeds.py +++ b/backend/endpoints/feeds.py @@ -1,3 +1,5 @@ +from typing import Sequence + from config import DISABLE_DOWNLOAD_ENDPOINT_AUTH from decorators.auth import protected_route from endpoints.responses.feeds import ( @@ -130,9 +132,11 @@ async def tinfoil_index_feed( error="Nintendo Switch platform not found", ) - roms: list[Rom] = db_rom_handler.get_roms(platform_id=switch.id) + roms = db_rom_handler.get_roms(platform_id=switch.id) - async def extract_titledb(roms: list[Rom]) -> dict[str, TinfoilFeedTitleDBSchema]: + async def extract_titledb( + roms: Sequence[Rom], + ) -> dict[str, TinfoilFeedTitleDBSchema]: titledb = {} for rom in roms: match = SWITCH_TITLEDB_REGEX.search(rom.fs_name) diff --git a/backend/endpoints/responses/rom.py b/backend/endpoints/responses/rom.py index fac0bbe12..3ef30bb6c 100644 --- a/backend/endpoints/responses/rom.py +++ b/backend/endpoints/responses/rom.py @@ -116,12 +116,11 @@ class RomSchema(BaseModel): platform_slug: str platform_name: str - file_name: str - file_name_no_tags: str - file_name_no_ext: str - file_extension: str - file_path: str - file_size_bytes: int + fs_name: str + fs_name_no_tags: str + fs_name_no_ext: str + fs_extension: str + fs_path: str name: str | None slug: str | None @@ -152,6 +151,7 @@ class RomSchema(BaseModel): multi: bool files: list[RomFileSchema] + file_size_bytes: int full_path: str created_at: datetime updated_at: datetime @@ -165,7 +165,7 @@ class RomSchema(BaseModel): return ( SORT_COMPARE_REGEX.sub( "", - self.name or self.file_name_no_tags, + self.name or self.fs_name_no_tags, ) .strip() .lower() @@ -220,7 +220,7 @@ class DetailedRomSchema(RomSchema): if s.user_id == user_id ] rom.user_collections = CollectionSchema.for_user( - user_id, db_rom.get_collections() + user_id, [c for c in db_rom.get_collections()] ) return rom diff --git a/backend/endpoints/rom.py b/backend/endpoints/rom.py index ab05d7ce3..fea7a9cd3 100644 --- a/backend/endpoints/rom.py +++ b/backend/endpoints/rom.py @@ -384,25 +384,25 @@ async def update_rom( } ) - new_file_name = str(data.get("file_name", rom.fs_name)) + new_fs_name = str(data.get("fs_name", rom.fs_name)) try: if rename_as_source: - new_file_name = rom.fs_name.replace( + new_fs_name = rom.fs_name.replace( rom.fs_name_no_tags or rom.fs_name_no_ext, str(data.get("name", rom.name)), ) - new_file_name = sanitize_filename(new_file_name) + new_fs_name = sanitize_filename(new_fs_name) fs_rom_handler.rename_file( old_name=rom.fs_name, - new_name=new_file_name, + new_name=new_fs_name, file_path=rom.fs_path, ) - elif rom.fs_name != new_file_name: - new_file_name = sanitize_filename(new_file_name) + elif rom.fs_name != new_fs_name: + new_fs_name = sanitize_filename(new_fs_name) fs_rom_handler.rename_file( old_name=rom.fs_name, - new_name=new_file_name, + new_name=new_fs_name, file_path=rom.fs_path, ) except RomAlreadyExistsException as exc: @@ -413,12 +413,10 @@ async def update_rom( cleaned_data.update( { - "file_name": new_file_name, - "file_name_no_tags": fs_rom_handler.get_file_name_with_no_tags( - new_file_name - ), - "file_name_no_ext": fs_rom_handler.get_file_name_with_no_extension( - new_file_name + "fs_name": new_fs_name, + "fs_name_no_tags": fs_rom_handler.get_file_name_with_no_tags(new_fs_name), + "fs_name_no_ext": fs_rom_handler.get_file_name_with_no_extension( + new_fs_name ), } ) @@ -519,7 +517,7 @@ async def delete_roms( if id in delete_from_fs: log.info(f"Deleting {rom.fs_name} from filesystem") try: - fs_rom_handler.remove_file(file_name=rom.fs_name, file_path=rom.fs_name) + fs_rom_handler.remove_file(fs_name=rom.fs_name, file_path=rom.fs_name) except FileNotFoundError as exc: error = ( f"Rom file {rom.fs_name} not found for platform {rom.platform_slug}" diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 188f46f67..32677059b 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -271,9 +271,9 @@ async def _identify_platform( log.info(f" {len(fs_roms)} roms found in the file system") for fs_roms_batch in batched(fs_roms, 200): - rom_by_filename_map = db_rom_handler.get_roms_by_filename( + rom_by_filename_map = db_rom_handler.get_roms_by_fs_name( platform_id=platform.id, - file_names={fs_rom["fs_name"] for fs_rom in fs_roms_batch}, + fs_names={fs_rom["fs_name"] for fs_rom in fs_roms_batch}, ) for fs_rom in fs_roms_batch: diff --git a/backend/endpoints/tests/test_rom.py b/backend/endpoints/tests/test_rom.py index b37d763f8..0221e3d2a 100644 --- a/backend/endpoints/tests/test_rom.py +++ b/backend/endpoints/tests/test_rom.py @@ -48,7 +48,7 @@ def test_update_rom(rename_file_mock, get_rom_by_id_mock, client, access_token, "igdb_id": "236663", "name": "Metroid Prime Remastered", "slug": "metroid-prime-remastered", - "file_name": "Metroid Prime Remastered.zip", + "fs_name": "Metroid Prime Remastered.zip", "summary": "summary test", "url_cover": "https://images.igdb.com/igdb/image/upload/t_cover_big/co2l7z.jpg", "genres": '[{"id": 5, "name": "Shooter"}, {"id": 8, "name": "Platform"}, {"id": 31, "name": "Adventure"}]', @@ -70,7 +70,7 @@ def test_update_rom(rename_file_mock, get_rom_by_id_mock, client, access_token, assert response.status_code == 200 body = response.json() - assert body["file_name"] == "Metroid Prime Remastered.zip" + assert body["fs_name"] == "Metroid Prime Remastered.zip" assert rename_file_mock.called assert get_rom_by_id_mock.called diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index e5fd65d15..53d3ccdd6 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -1,5 +1,6 @@ import functools from collections.abc import Iterable +from typing import Sequence from decorators.database import begin_session from models.collection import Collection @@ -72,8 +73,8 @@ class DBRomsHandler(DBBaseHandler): if search_term: data = data.filter( or_( - Rom.file_name.ilike(f"%{search_term}%"), # type: ignore[attr-defined] - Rom.name.ilike(f"%{search_term}%"), # type: ignore[attr-defined] + Rom.fs_name.ilike(f"%{search_term}%"), + Rom.name.ilike(f"%{search_term}%"), ) ) @@ -119,7 +120,7 @@ class DBRomsHandler(DBBaseHandler): offset: int | None = None, query: Query = None, session: Session = None, - ) -> list[Rom]: + ) -> Sequence[Rom]: filtered_query = self._filter( query, platform_id, collection_id, search_term, session ) @@ -130,60 +131,56 @@ class DBRomsHandler(DBBaseHandler): @begin_session @with_details - def get_rom_by_filename( + def get_rom_by_fs_name( self, platform_id: int, - file_name: str, + fs_name: str, query: Query = None, session: Session = None, ) -> Rom | None: return session.scalar( - query.filter_by(platform_id=platform_id, file_name=file_name).limit(1) + query.filter_by(platform_id=platform_id, fs_name=fs_name).limit(1) ) @begin_session - def get_roms_by_filename( + def get_roms_by_fs_name( self, platform_id: int, - file_names: Iterable[str], + fs_names: Iterable[str], query: Query = None, session: Session = None, ) -> dict[str, Rom]: - """Retrieve a dictionary of roms by their file names.""" + """Retrieve a dictionary of roms by their filesystem names.""" query = query or select(Rom) roms = ( session.scalars( - query.filter(Rom.file_name.in_(file_names)).filter_by( + query.filter(Rom.fs_name.in_(fs_names)).filter_by( platform_id=platform_id ) ) .unique() .all() ) - return {rom.file_name: rom for rom in roms} + return {rom.fs_name: rom for rom in roms} @begin_session @with_details - def get_rom_by_filename_no_tags( - self, file_name_no_tags: str, query: Query = None, session: Session = None + def get_rom_by_fs_name_no_tags( + self, fs_name_no_tags: str, query: Query = None, session: Session = None ) -> Rom | None: - return session.scalar( - query.filter_by(file_name_no_tags=file_name_no_tags).limit(1) - ) + return session.scalar(query.filter_by(fs_name_no_tags=fs_name_no_tags).limit(1)) @begin_session @with_details - def get_rom_by_filename_no_ext( - self, file_name_no_ext: str, query: Query = None, session: Session = None + def get_rom_by_fs_name_no_ext( + self, fs_name_no_ext: str, query: Query = None, session: Session = None ) -> Rom | None: - return session.scalar( - query.filter_by(file_name_no_ext=file_name_no_ext).limit(1) - ) + return session.scalar(query.filter_by(fs_name_no_ext=fs_name_no_ext).limit(1)) @begin_session def get_rom_collections( self, rom: Rom, session: Session = None - ) -> list[Collection]: + ) -> Sequence[Collection]: return ( session.scalars( select(Collection) @@ -196,7 +193,7 @@ class DBRomsHandler(DBBaseHandler): @begin_session def update_rom(self, id: int, data: dict, session: Session = None) -> Rom: - return session.execute( + return session.scalar( update(Rom) .where(Rom.id == id) .values(**data) @@ -204,8 +201,8 @@ class DBRomsHandler(DBBaseHandler): ) @begin_session - def delete_rom(self, id: int, session: Session = None) -> Rom: - return session.execute( + def delete_rom(self, id: int, session: Session = None) -> None: + session.execute( delete(Rom) .where(Rom.id == id) .execution_options(synchronize_session="evaluate") @@ -214,21 +211,21 @@ class DBRomsHandler(DBBaseHandler): @begin_session def purge_roms( self, platform_id: int, fs_roms: list[str], session: Session = None - ) -> list[Rom]: + ) -> Sequence[Rom]: purged_roms = ( session.scalars( select(Rom) - .order_by(Rom.file_name.asc()) + .order_by(Rom.fs_name.asc()) .where( - and_(Rom.platform_id == platform_id, Rom.file_name.not_in(fs_roms)) + and_(Rom.platform_id == platform_id, Rom.fs_name.not_in(fs_roms)) ) - ) # type: ignore[attr-defined] + ) .unique() .all() ) session.execute( delete(Rom) - .where(and_(Rom.platform_id == platform_id, Rom.file_name.not_in(fs_roms))) # type: ignore[attr-defined] + .where(and_(Rom.platform_id == platform_id, Rom.fs_name.not_in(fs_roms))) .execution_options(synchronize_session="evaluate") ) return purged_roms @@ -261,9 +258,13 @@ class DBRomsHandler(DBBaseHandler): ) rom_user = self.get_rom_user_by_id(id) + if not rom_user: + raise ValueError(f"RomUser with id {id} not found") if data.get("is_main_sibling", False): rom = self.get_rom(rom_user.rom_id) + if not rom: + raise ValueError(f"Rom with id {rom_user.rom_id} not found") session.execute( update(RomUser) @@ -276,4 +277,8 @@ class DBRomsHandler(DBBaseHandler): .values(is_main_sibling=False) ) - return self.get_rom_user_by_id(id) + rom_user = self.get_rom_user_by_id(id) + if not rom_user: + raise ValueError(f"RomUser with id {id} not found") + + return rom_user diff --git a/backend/handler/database/stats_handler.py b/backend/handler/database/stats_handler.py index 8a8af03db..2bc0f3e56 100644 --- a/backend/handler/database/stats_handler.py +++ b/backend/handler/database/stats_handler.py @@ -1,6 +1,6 @@ from decorators.database import begin_session from models.assets import Save, Screenshot, State -from models.rom import Rom +from models.rom import Rom, RomFile from sqlalchemy import distinct, func, select from sqlalchemy.orm import Session @@ -38,5 +38,8 @@ class DBStatsHandler(DBBaseHandler): def get_total_filesize(self, session: Session = None) -> int: """Get the total filesize of all roms in the database, in bytes.""" return ( - session.scalar(select(func.sum(Rom.file_size_bytes)).select_from(Rom)) or 0 + session.scalar( + select(func.sum(RomFile.file_size_bytes)).select_from(RomFile) + ) + or 0 ) diff --git a/backend/handler/filesystem/resources_handler.py b/backend/handler/filesystem/resources_handler.py index df00ecab7..feaa1f5c4 100644 --- a/backend/handler/filesystem/resources_handler.py +++ b/backend/handler/filesystem/resources_handler.py @@ -84,8 +84,7 @@ class FSResourcesHandler(FSHandler): """Returns rom cover filesystem path adapted to frontend folder structure Args: - fs_slug: short name of the platform - file_name: name of rom file + entity: Rom or Collection object size: size of the cover """ async for matched_file in Path( @@ -155,8 +154,7 @@ class FSResourcesHandler(FSHandler): """Store roms resources in filesystem Args: - fs_slug: short name of the platform - file_name: name of rom + rom: Rom object url: url to get the screenshot """ screenshot_file = f"{idx}.jpg" @@ -185,8 +183,7 @@ class FSResourcesHandler(FSHandler): """Returns rom cover filesystem path adapted to frontend folder structure Args: - fs_slug: short name of the platform - file_name: name of rom + rom: Rom object idx: index number of screenshot """ return f"{rom.fs_resources_path}/screenshots/{idx}.jpg" diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index d9f2dcf71..10456f3f8 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -166,18 +166,18 @@ class FSRomsHandler(FSHandler): def __init__(self) -> None: pass - def remove_file(self, file_name: str, file_path: str) -> None: + def remove_file(self, fs_name: str, file_path: str) -> None: try: - os.remove(f"{LIBRARY_BASE_PATH}/{file_path}/{file_name}") + os.remove(f"{LIBRARY_BASE_PATH}/{file_path}/{fs_name}") except IsADirectoryError: - shutil.rmtree(f"{LIBRARY_BASE_PATH}/{file_path}/{file_name}") + shutil.rmtree(f"{LIBRARY_BASE_PATH}/{file_path}/{fs_name}") - def parse_tags(self, file_name: str) -> tuple: + def parse_tags(self, fs_name: str) -> tuple: rev = "" regs = [] langs = [] other_tags = [] - tags = [tag[0] or tag[1] for tag in TAG_REGEX.findall(file_name)] + tags = [tag[0] or tag[1] for tag in TAG_REGEX.findall(fs_name)] tags = [tag for subtags in tags for tag in subtags.split(",")] tags = [tag.strip() for tag in tags] @@ -360,20 +360,20 @@ class FSRomsHandler(FSHandler): key=lambda rom: rom["fs_name"], ) - def file_exists(self, path: str, file_name: str) -> bool: + def file_exists(self, path: str, fs_name: str) -> bool: """Check if file exists in filesystem Args: path: path to file - file_name: name of file + fs_name: name of file Returns True if file exists in filesystem else False """ - return bool(os.path.exists(f"{LIBRARY_BASE_PATH}/{path}/{file_name}")) + return bool(os.path.exists(f"{LIBRARY_BASE_PATH}/{path}/{fs_name}")) def rename_file(self, old_name: str, new_name: str, file_path: str) -> None: if new_name != old_name: - if self.file_exists(path=file_path, file_name=new_name): + if self.file_exists(path=file_path, fs_name=new_name): raise RomAlreadyExistsException(new_name) os.rename( diff --git a/backend/handler/metadata/igdb_handler.py b/backend/handler/metadata/igdb_handler.py index 3d83d74d8..871b29033 100644 --- a/backend/handler/metadata/igdb_handler.py +++ b/backend/handler/metadata/igdb_handler.py @@ -415,7 +415,7 @@ class IGDBBaseHandler(MetadataHandler): return IGDBPlatform(igdb_id=None, slug=slug) @check_twitch_token - async def get_rom(self, file_name: str, platform_igdb_id: int) -> IGDBRom: + async def get_rom(self, fs_name: str, platform_igdb_id: int) -> IGDBRom: from handler.filesystem import fs_rom_handler if not IGDB_API_ENABLED: @@ -424,17 +424,17 @@ class IGDBBaseHandler(MetadataHandler): if not platform_igdb_id: return IGDBRom(igdb_id=None) - search_term = fs_rom_handler.get_file_name_with_no_tags(file_name) + search_term = fs_rom_handler.get_file_name_with_no_tags(fs_name) fallback_rom = IGDBRom(igdb_id=None) # Support for PS2 OPL filename format - match = PS2_OPL_REGEX.match(file_name) + match = PS2_OPL_REGEX.match(fs_name) if platform_igdb_id == PS2_IGDB_ID and match: search_term = await self._ps2_opl_format(match, search_term) fallback_rom = IGDBRom(igdb_id=None, name=search_term) # Support for sony serial filename format (PS, PS3, PS3) - match = SONY_SERIAL_REGEX.search(file_name, re.IGNORECASE) + match = SONY_SERIAL_REGEX.search(fs_name, re.IGNORECASE) if platform_igdb_id == PS1_IGDB_ID and match: search_term = await self._ps1_serial_format(match, search_term) fallback_rom = IGDBRom(igdb_id=None, name=search_term) @@ -448,7 +448,7 @@ class IGDBBaseHandler(MetadataHandler): fallback_rom = IGDBRom(igdb_id=None, name=search_term) # Support for switch titleID filename format - match = SWITCH_TITLEDB_REGEX.search(file_name) + match = SWITCH_TITLEDB_REGEX.search(fs_name) if platform_igdb_id == SWITCH_IGDB_ID and match: search_term, index_entry = await self._switch_titledb_format( match, search_term @@ -463,7 +463,7 @@ class IGDBBaseHandler(MetadataHandler): ) # Support for switch productID filename format - match = SWITCH_PRODUCT_ID_REGEX.search(file_name) + match = SWITCH_PRODUCT_ID_REGEX.search(fs_name) if platform_igdb_id == SWITCH_IGDB_ID and match: search_term, index_entry = await self._switch_productid_format( match, search_term diff --git a/backend/handler/metadata/moby_handler.py b/backend/handler/metadata/moby_handler.py index efc4655f6..a4ea3e57b 100644 --- a/backend/handler/metadata/moby_handler.py +++ b/backend/handler/metadata/moby_handler.py @@ -180,7 +180,7 @@ class MobyGamesHandler(MetadataHandler): name=platform["name"], ) - async def get_rom(self, file_name: str, platform_moby_id: int) -> MobyGamesRom: + async def get_rom(self, fs_name: str, platform_moby_id: int) -> MobyGamesRom: from handler.filesystem import fs_rom_handler if not MOBY_API_ENABLED: @@ -189,17 +189,17 @@ class MobyGamesHandler(MetadataHandler): if not platform_moby_id: return MobyGamesRom(moby_id=None) - search_term = fs_rom_handler.get_file_name_with_no_tags(file_name) + search_term = fs_rom_handler.get_file_name_with_no_tags(fs_name) fallback_rom = MobyGamesRom(moby_id=None) # Support for PS2 OPL filename format - match = PS2_OPL_REGEX.match(file_name) + match = PS2_OPL_REGEX.match(fs_name) if platform_moby_id == PS2_MOBY_ID and match: search_term = await self._ps2_opl_format(match, search_term) fallback_rom = MobyGamesRom(moby_id=None, name=search_term) # Support for sony serial filename format (PS, PS3, PS3) - match = SONY_SERIAL_REGEX.search(file_name, re.IGNORECASE) + match = SONY_SERIAL_REGEX.search(fs_name, re.IGNORECASE) if platform_moby_id == PS1_MOBY_ID and match: search_term = await self._ps1_serial_format(match, search_term) fallback_rom = MobyGamesRom(moby_id=None, name=search_term) @@ -213,7 +213,7 @@ class MobyGamesHandler(MetadataHandler): fallback_rom = MobyGamesRom(moby_id=None, name=search_term) # Support for switch titleID filename format - match = SWITCH_TITLEDB_REGEX.search(file_name) + match = SWITCH_TITLEDB_REGEX.search(fs_name) if platform_moby_id == SWITCH_MOBY_ID and match: search_term, index_entry = await self._switch_titledb_format( match, search_term @@ -228,7 +228,7 @@ class MobyGamesHandler(MetadataHandler): ) # Support for switch productID filename format - match = SWITCH_PRODUCT_ID_REGEX.search(file_name) + match = SWITCH_PRODUCT_ID_REGEX.search(fs_name) if platform_moby_id == SWITCH_MOBY_ID and match: search_term, index_entry = await self._switch_productid_format( match, search_term diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 131745ea1..3eed55285 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -212,22 +212,20 @@ async def scan_rom( ) # Update properties that don't require metadata - file_size = sum([file["size"] for file in rom_attrs["files"]]) - regs, rev, langs, other_tags = fs_rom_handler.parse_tags(rom_attrs["file_name"]) + filesize = sum([file["size"] for file in rom_attrs["files"]]) + regs, rev, langs, other_tags = fs_rom_handler.parse_tags(rom_attrs["fs_name"]) rom_attrs.update( { - "file_path": roms_path, - "file_name": rom_attrs["file_name"], - "file_name_no_tags": fs_rom_handler.get_file_name_with_no_tags( - rom_attrs["file_name"] + "fs_path": roms_path, + "fs_name": rom_attrs["fs_name"], + "fs_name_no_tags": fs_rom_handler.get_file_name_with_no_tags( + rom_attrs["fs_name"] ), - "file_name_no_ext": fs_rom_handler.get_file_name_with_no_extension( - rom_attrs["file_name"] + "fs_name_no_ext": fs_rom_handler.get_file_name_with_no_extension( + rom_attrs["fs_name"] ), - "file_extension": fs_rom_handler.parse_file_extension( - rom_attrs["file_name"] - ), - "file_size_bytes": file_size, + "fs_extension": fs_rom_handler.parse_file_extension(rom_attrs["fs_name"]), + "fs_size_bytes": filesize, "multi": rom_attrs["multi"], "regions": regs, "revision": rev, @@ -257,7 +255,7 @@ async def scan_rom( ): main_platform_igdb_id = await _get_main_platform_igdb_id(platform) return await meta_igdb_handler.get_rom( - rom_attrs["file_name"], main_platform_igdb_id or platform.igdb_id + rom_attrs["fs_name"], main_platform_igdb_id or platform.igdb_id ) return IGDBRom(igdb_id=None) @@ -274,7 +272,7 @@ async def scan_rom( ) ): return await meta_moby_handler.get_rom( - rom_attrs["file_name"], platform_moby_id=platform.moby_id + rom_attrs["fs_name"], platform_moby_id=platform.moby_id ) return MobyGamesRom(moby_id=None) @@ -290,7 +288,7 @@ async def scan_rom( # If not found in IGDB or MobyGames if not igdb_handler_rom.get("igdb_id") and not moby_handler_rom.get("moby_id"): log.warning( - emoji.emojize(f"\t {rom_attrs['file_name']} not identified :cross_mark:") + emoji.emojize(f"\t {rom_attrs['fs_name']} not identified :cross_mark:") ) return Rom(**rom_attrs) diff --git a/backend/handler/tests/conftest.py b/backend/handler/tests/conftest.py index bf8e149cb..63133aeeb 100644 --- a/backend/handler/tests/conftest.py +++ b/backend/handler/tests/conftest.py @@ -51,12 +51,11 @@ def rom(platform: Platform): platform_id=platform.id, name="test_rom", slug="test_rom_slug", - file_name="test_rom.zip", - file_name_no_tags="test_rom", - file_name_no_ext="test_rom", - file_extension="zip", - file_path=f"{platform.slug}/roms", - file_size_bytes=1000.0, + fs_name="test_rom.zip", + fs_name_no_tags="test_rom", + fs_name_no_ext="test_rom", + fs_extension="zip", + fs_path=f"{platform.slug}/roms", ) return db_rom_handler.add_rom(rom) diff --git a/backend/handler/tests/test_db_handler.py b/backend/handler/tests/test_db_handler.py index 78cfe7df6..7b1045b49 100644 --- a/backend/handler/tests/test_db_handler.py +++ b/backend/handler/tests/test_db_handler.py @@ -38,33 +38,32 @@ def test_roms(rom: Rom, platform: Platform): platform_id=rom.platform_id, name="test_rom_2", slug="test_rom_slug_2", - file_name="test_rom_2", - file_name_no_tags="test_rom_2", - file_name_no_ext="test_rom_2", - file_extension="zip", - file_path=f"{platform.slug}/roms", - file_size_bytes=1000.0, + fs_name="test_rom_2", + fs_name_no_tags="test_rom_2", + fs_name_no_ext="test_rom_2", + fs_extension="zip", + fs_path=f"{platform.slug}/roms", ) ) roms = db_rom_handler.get_roms(platform_id=platform.id) assert len(roms) == 2 - rom = db_rom_handler.get_rom(roms[0].id) - assert rom is not None - assert rom.file_name == "test_rom.zip" + rom_1 = db_rom_handler.get_rom(roms[0].id) + assert rom_1 is not None + assert rom_1.fs_name == "test_rom.zip" db_rom_handler.update_rom(roms[1].id, {"file_name": "test_rom_2_updated"}) rom_2 = db_rom_handler.get_rom(roms[1].id) assert rom_2 is not None - assert rom_2.file_name == "test_rom_2_updated" + assert rom_2.fs_name == "test_rom_2_updated" db_rom_handler.delete_rom(rom.id) roms = db_rom_handler.get_roms(platform_id=platform.id) assert len(roms) == 1 - db_rom_handler.purge_roms(rom_2.platform_id, [rom_2.id]) + db_rom_handler.purge_roms(rom_2.platform_id, [rom_2.fs_name]) roms = db_rom_handler.get_roms(platform_id=platform.id) assert len(roms) == 0 @@ -72,12 +71,11 @@ def test_roms(rom: Rom, platform: Platform): def test_utils(rom: Rom, platform: Platform): roms = db_rom_handler.get_roms(platform_id=platform.id) - assert ( - db_rom_handler.get_rom_by_filename( - platform_id=platform.id, file_name=rom.file_name - ).id - == roms[0].id + rom_1 = db_rom_handler.get_rom_by_fs_name( + platform_id=platform.id, fs_name=rom.fs_name ) + assert rom_1 + assert rom_1.id == roms[0].id def test_users(admin_user): @@ -92,6 +90,7 @@ def test_users(admin_user): assert len(all_users) == 2 new_user = db_user_handler.get_user_by_username("new_user") + assert new_user is not None assert new_user.username == "new_user" assert new_user.role == Role.VIEWER assert new_user.enabled @@ -99,6 +98,7 @@ def test_users(admin_user): db_user_handler.update_user(new_user.id, {"role": Role.EDITOR}) new_user = db_user_handler.get_user(new_user.id) + assert new_user is not None assert new_user.role == Role.EDITOR db_user_handler.delete_user(new_user.id) @@ -137,14 +137,16 @@ def test_saves(save: Save, platform: Platform, admin_user: User): assert rom is not None assert len(rom.saves) == 2 - save = db_save_handler.get_save(rom.saves[0].id) - assert save.file_name == "test_save.sav" + new_save = db_save_handler.get_save(rom.saves[0].id) + assert new_save is not None + assert new_save.file_name == "test_save.sav" - db_save_handler.update_save(save.id, {"file_name": "test_save_2.sav"}) - save = db_save_handler.get_save(save.id) - assert save.file_name == "test_save_2.sav" + db_save_handler.update_save(new_save.id, {"file_name": "test_save_2.sav"}) + new_save = db_save_handler.get_save(new_save.id) + assert new_save is not None + assert new_save.file_name == "test_save_2.sav" - db_save_handler.delete_save(save.id) + db_save_handler.delete_save(new_save.id) rom = db_rom_handler.get_rom(save.rom_id) assert rom is not None @@ -169,14 +171,16 @@ def test_states(state: State, platform: Platform, admin_user: User): assert rom is not None assert len(rom.states) == 2 - state = db_state_handler.get_state(rom.states[0].id) - assert state.file_name == "test_state.state" + new_state = db_state_handler.get_state(rom.states[0].id) + assert new_state is not None + assert new_state.file_name == "test_state.state" - db_state_handler.update_state(state.id, {"file_name": "test_state_2.state"}) - state = db_state_handler.get_state(state.id) - assert state.file_name == "test_state_2.state" + db_state_handler.update_state(new_state.id, {"file_name": "test_state_2.state"}) + new_state = db_state_handler.get_state(new_state.id) + assert new_state is not None + assert new_state.file_name == "test_state_2.state" - db_state_handler.delete_state(state.id) + db_state_handler.delete_state(new_state.id) rom = db_rom_handler.get_rom(state.rom_id) assert rom is not None @@ -201,16 +205,18 @@ def test_screenshots(screenshot: Screenshot, platform: Platform, admin_user: Use assert rom is not None assert len(rom.screenshots) == 2 - screenshot = db_screenshot_handler.get_screenshot(rom.screenshots[0].id) - assert screenshot.file_name == "test_screenshot.png" + new_screenshot = db_screenshot_handler.get_screenshot(rom.screenshots[0].id) + assert new_screenshot is not None + assert new_screenshot.file_name == "test_screenshot.png" db_screenshot_handler.update_screenshot( - screenshot.id, {"file_name": "test_screenshot_2.png"} + new_screenshot.id, {"file_name": "test_screenshot_2.png"} ) - screenshot = db_screenshot_handler.get_screenshot(screenshot.id) - assert screenshot.file_name == "test_screenshot_2.png" + new_screenshot = db_screenshot_handler.get_screenshot(new_screenshot.id) + assert new_screenshot is not None + assert new_screenshot.file_name == "test_screenshot_2.png" - db_screenshot_handler.delete_screenshot(screenshot.id) + db_screenshot_handler.delete_screenshot(new_screenshot.id) rom = db_rom_handler.get_rom(screenshot.rom_id) assert rom is not None diff --git a/backend/models/rom.py b/backend/models/rom.py index 027aad78f..ce9b90914 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -3,7 +3,7 @@ from __future__ import annotations import enum from datetime import datetime from functools import cached_property -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Sequence from config import FRONTEND_RESOURCES_PATH from models.base import BaseModel @@ -149,7 +149,7 @@ class Rom(BaseModel): def file_size_bytes(self) -> int: return sum(f.file_size_bytes for f in self.files) - def get_collections(self) -> list[Collection]: + def get_collections(self) -> Sequence[Collection]: from handler.database import db_rom_handler return db_rom_handler.get_rom_collections(self) From 5b02983aa54486e870e3157bede685a8625b167d Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 21 Dec 2024 09:19:54 -0500 Subject: [PATCH 07/33] update frontne dto match --- backend/endpoints/responses/rom.py | 4 ++++ frontend/src/__generated__/index.ts | 2 +- .../__generated__/models/DetailedRomSchema.ts | 18 +++++++++--------- frontend/src/__generated__/models/RomFile.ts | 11 ----------- .../src/__generated__/models/RomFileSchema.ts | 16 ++++++++++++++++ frontend/src/__generated__/models/RomSchema.ts | 18 +++++++++--------- .../__generated__/models/SimpleRomSchema.ts | 18 +++++++++--------- .../src/components/Details/Info/FileInfo.vue | 8 ++++---- .../components/common/Game/Dialog/EditRom.vue | 6 +++--- .../components/common/Game/Dialog/MatchRom.vue | 10 +++------- .../src/components/common/Game/ListItem.vue | 2 +- frontend/src/components/common/Game/Table.vue | 4 +--- frontend/src/services/api/rom.ts | 2 +- frontend/src/stores/roms.ts | 2 +- frontend/src/utils/index.ts | 4 +--- .../src/views/Player/EmulatorJS/Player.vue | 6 +++--- frontend/src/views/Player/RuffleRS/Base.vue | 2 +- 17 files changed, 67 insertions(+), 66 deletions(-) delete mode 100644 frontend/src/__generated__/models/RomFile.ts create mode 100644 frontend/src/__generated__/models/RomFileSchema.ts diff --git a/backend/endpoints/responses/rom.py b/backend/endpoints/responses/rom.py index 3ef30bb6c..30f7b3674 100644 --- a/backend/endpoints/responses/rom.py +++ b/backend/endpoints/responses/rom.py @@ -149,6 +149,10 @@ class RomSchema(BaseModel): languages: list[str] tags: list[str] + crc_hash: str | None + md5_hash: str | None + sha1_hash: str | None + multi: bool files: list[RomFileSchema] file_size_bytes: int diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index 93cef8064..443b1da64 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -30,7 +30,7 @@ export type { MobyMetadataPlatform } from './models/MobyMetadataPlatform'; export type { OIDCDict } from './models/OIDCDict'; export type { PlatformSchema } from './models/PlatformSchema'; export type { Role } from './models/Role'; -export type { RomFile } from './models/RomFile'; +export type { RomFileSchema } from './models/RomFileSchema'; export type { RomIGDBMetadata } from './models/RomIGDBMetadata'; export type { RomMobyMetadata } from './models/RomMobyMetadata'; export type { RomSchema } from './models/RomSchema'; diff --git a/frontend/src/__generated__/models/DetailedRomSchema.ts b/frontend/src/__generated__/models/DetailedRomSchema.ts index c7517e44f..94e213887 100644 --- a/frontend/src/__generated__/models/DetailedRomSchema.ts +++ b/frontend/src/__generated__/models/DetailedRomSchema.ts @@ -4,7 +4,7 @@ /* eslint-disable */ import type { CollectionSchema } from './CollectionSchema'; -import type { RomFile } from './RomFile'; +import type { RomFileSchema } from './RomFileSchema'; import type { RomIGDBMetadata } from './RomIGDBMetadata'; import type { RomMobyMetadata } from './RomMobyMetadata'; import type { RomSchema } from './RomSchema'; @@ -22,12 +22,11 @@ export type DetailedRomSchema = { platform_id: number; platform_slug: string; platform_name: string; - file_name: string; - file_name_no_tags: string; - file_name_no_ext: string; - file_extension: string; - file_path: string; - file_size_bytes: number; + fs_name: string; + fs_name_no_tags: string; + fs_name_no_ext: string; + fs_extension: string; + fs_path: string; name: (string | null); slug: (string | null); summary: (string | null); @@ -50,11 +49,12 @@ export type DetailedRomSchema = { regions: Array; languages: Array; tags: Array; - multi: boolean; - files: Array; crc_hash: (string | null); md5_hash: (string | null); sha1_hash: (string | null); + multi: boolean; + files: Array; + file_size_bytes: number; full_path: string; created_at: string; updated_at: string; diff --git a/frontend/src/__generated__/models/RomFile.ts b/frontend/src/__generated__/models/RomFile.ts deleted file mode 100644 index 3880f3ef8..000000000 --- a/frontend/src/__generated__/models/RomFile.ts +++ /dev/null @@ -1,11 +0,0 @@ -/* generated using openapi-typescript-codegen -- do no edit */ -/* istanbul ignore file */ -/* tslint:disable */ -/* eslint-disable */ - -export type RomFile = { - filename: string; - size: number; - last_modified: (number | null); -}; - diff --git a/frontend/src/__generated__/models/RomFileSchema.ts b/frontend/src/__generated__/models/RomFileSchema.ts new file mode 100644 index 000000000..c8186463d --- /dev/null +++ b/frontend/src/__generated__/models/RomFileSchema.ts @@ -0,0 +1,16 @@ +/* generated using openapi-typescript-codegen -- do no edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ + +export type RomFileSchema = { + id: number; + rom_id: number; + file_name: string; + file_path: string; + file_size_bytes: number; + created_at: string; + updated_at: string; + last_modified: string; +}; + diff --git a/frontend/src/__generated__/models/RomSchema.ts b/frontend/src/__generated__/models/RomSchema.ts index a29ed3217..31e98b3f2 100644 --- a/frontend/src/__generated__/models/RomSchema.ts +++ b/frontend/src/__generated__/models/RomSchema.ts @@ -3,7 +3,7 @@ /* tslint:disable */ /* eslint-disable */ -import type { RomFile } from './RomFile'; +import type { RomFileSchema } from './RomFileSchema'; import type { RomIGDBMetadata } from './RomIGDBMetadata'; import type { RomMobyMetadata } from './RomMobyMetadata'; @@ -15,12 +15,11 @@ export type RomSchema = { platform_id: number; platform_slug: string; platform_name: string; - file_name: string; - file_name_no_tags: string; - file_name_no_ext: string; - file_extension: string; - file_path: string; - file_size_bytes: number; + fs_name: string; + fs_name_no_tags: string; + fs_name_no_ext: string; + fs_extension: string; + fs_path: string; name: (string | null); slug: (string | null); summary: (string | null); @@ -43,11 +42,12 @@ export type RomSchema = { regions: Array; languages: Array; tags: Array; - multi: boolean; - files: Array; crc_hash: (string | null); md5_hash: (string | null); sha1_hash: (string | null); + multi: boolean; + files: Array; + file_size_bytes: number; full_path: string; created_at: string; updated_at: string; diff --git a/frontend/src/__generated__/models/SimpleRomSchema.ts b/frontend/src/__generated__/models/SimpleRomSchema.ts index 43ecf715b..92d56a742 100644 --- a/frontend/src/__generated__/models/SimpleRomSchema.ts +++ b/frontend/src/__generated__/models/SimpleRomSchema.ts @@ -3,7 +3,7 @@ /* tslint:disable */ /* eslint-disable */ -import type { RomFile } from './RomFile'; +import type { RomFileSchema } from './RomFileSchema'; import type { RomIGDBMetadata } from './RomIGDBMetadata'; import type { RomMobyMetadata } from './RomMobyMetadata'; import type { RomSchema } from './RomSchema'; @@ -17,12 +17,11 @@ export type SimpleRomSchema = { platform_id: number; platform_slug: string; platform_name: string; - file_name: string; - file_name_no_tags: string; - file_name_no_ext: string; - file_extension: string; - file_path: string; - file_size_bytes: number; + fs_name: string; + fs_name_no_tags: string; + fs_name_no_ext: string; + fs_extension: string; + fs_path: string; name: (string | null); slug: (string | null); summary: (string | null); @@ -45,11 +44,12 @@ export type SimpleRomSchema = { regions: Array; languages: Array; tags: Array; - multi: boolean; - files: Array; crc_hash: (string | null); md5_hash: (string | null); sha1_hash: (string | null); + multi: boolean; + files: Array; + file_size_bytes: number; full_path: string; created_at: string; updated_at: string; diff --git a/frontend/src/components/Details/Info/FileInfo.vue b/frontend/src/components/Details/Info/FileInfo.vue index 72b0cd701..4f9f164a0 100644 --- a/frontend/src/components/Details/Info/FileInfo.vue +++ b/frontend/src/components/Details/Info/FileInfo.vue @@ -81,7 +81,7 @@ watch( {{ t("rom.file") }} - {{ rom.file_name }} + {{ rom.fs_name }} @@ -91,9 +91,9 @@ watch( - /romm/library/{{ rom.file_path }}/{{ rom.file_name }} + /romm/library/{{ rom.fs_path }}/{{ rom.fs_name }} diff --git a/frontend/src/components/common/Game/Dialog/MatchRom.vue b/frontend/src/components/common/Game/Dialog/MatchRom.vue index 8d8e780a8..deac345b4 100644 --- a/frontend/src/components/common/Game/Dialog/MatchRom.vue +++ b/frontend/src/components/common/Game/Dialog/MatchRom.vue @@ -51,7 +51,7 @@ emitter?.on("showMatchRomDialog", (romToSearch) => { searchTerm.value = romToSearch.igdb_id || romToSearch.moby_id ? (romToSearch.name ?? "") - : romToSearch.file_name_no_tags; + : romToSearch.fs_name_no_tags; if (searchTerm.value) { searchRom(); @@ -449,16 +449,12 @@ onBeforeUnmount(() => {
{{ t("rom.rename-file-part3") }}{{ rom?.file_name_no_tags }}.{{ - rom?.file_extension - }}{{ rom?.fs_name_no_tags }}.{{ rom?.fs_extension }}
{{ t("rom.rename-file-part4") }}{{ selectedMatchRom?.name }}.{{ - rom?.file_extension - }}{{ selectedMatchRom?.name }}.{{ rom?.fs_extension }}
{{ rom.name }}
{{ rom.file_name }}{{ rom.fs_name }}