From 33645641b83d109a654bdf71f50b29cd3573c7f9 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 16 Jan 2024 10:49:16 -0500 Subject: [PATCH 1/2] Add stats endpoint + refactor rom file size --- backend/alembic/versions/0014_asset_files.py | 119 ++++++++++-------- backend/alembic/versions/0015_rom_filesize.py | 55 ++++++++ backend/endpoints/rom.py | 2 - backend/handler/db_handler.py | 36 ++++++ backend/handler/tests/conftest.py | 3 +- backend/handler/tests/test_db_handler.py | 3 +- backend/main.py | 27 ++++ backend/models/rom.py | 18 +-- backend/utils/fastapi.py | 5 +- backend/utils/fs.py | 10 +- backend/utils/tests/test_fastapi.py | 3 +- backend/utils/tests/test_fs.py | 4 +- frontend/src/__generated__/index.ts | 1 + .../__generated__/models/EnhancedRomSchema.ts | 2 - .../src/__generated__/models/RomSchema.ts | 2 - .../src/__generated__/models/StatsReturn.ts | 14 +++ frontend/src/components/Dashboard/Summary.vue | 23 +++- .../src/components/Details/DetailsInfo.vue | 3 +- .../src/components/Game/DataTable/Base.vue | 5 +- .../Settings/Config/PlatformBindingCard.vue | 3 +- 20 files changed, 238 insertions(+), 100 deletions(-) create mode 100644 backend/alembic/versions/0015_rom_filesize.py create mode 100644 frontend/src/__generated__/models/StatsReturn.ts diff --git a/backend/alembic/versions/0014_asset_files.py b/backend/alembic/versions/0014_asset_files.py index b57925e0d..31b385fb0 100644 --- a/backend/alembic/versions/0014_asset_files.py +++ b/backend/alembic/versions/0014_asset_files.py @@ -10,67 +10,88 @@ import sqlalchemy as sa # revision identifiers, used by Alembic. -revision = '0014_asset_files' -down_revision = '0013_upgrade_file_extension' +revision = "0014_asset_files" +down_revision = "0013_upgrade_file_extension" branch_labels = None depends_on = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - op.create_table('saves', - sa.Column('emulator', sa.String(length=50), nullable=True), - sa.Column('rom_id', sa.Integer(), nullable=False), - sa.Column('platform_slug', sa.String(length=50), nullable=False), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False), - sa.Column('updated_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False), - sa.Column('file_name', sa.String(length=450), nullable=False), - sa.Column('file_name_no_tags', sa.String(length=450), nullable=False), - sa.Column('file_extension', sa.String(length=10), nullable=False), - sa.Column('file_path', sa.String(length=1000), nullable=False), - sa.Column('file_size_bytes', sa.Integer(), nullable=False), - sa.ForeignKeyConstraint(['platform_slug'], ['platforms.slug'], ondelete='CASCADE'), - sa.ForeignKeyConstraint(['rom_id'], ['roms.id'], ondelete='CASCADE'), - sa.PrimaryKeyConstraint('id') + op.create_table( + "saves", + sa.Column("emulator", sa.String(length=50), nullable=True), + sa.Column("rom_id", sa.Integer(), nullable=False), + sa.Column("platform_slug", sa.String(length=50), nullable=False), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column( + "created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False + ), + sa.Column( + "updated_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False + ), + sa.Column("file_name", sa.String(length=450), nullable=False), + sa.Column("file_name_no_tags", sa.String(length=450), nullable=False), + sa.Column("file_extension", sa.String(length=10), nullable=False), + sa.Column("file_path", sa.String(length=1000), nullable=False), + sa.Column("file_size_bytes", sa.Integer(), nullable=False), + sa.ForeignKeyConstraint( + ["platform_slug"], ["platforms.slug"], ondelete="CASCADE" + ), + sa.ForeignKeyConstraint(["rom_id"], ["roms.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), ) - op.create_table('screenshots', - sa.Column('rom_id', sa.Integer(), nullable=False), - sa.Column('platform_slug', sa.String(length=50), nullable=True), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False), - sa.Column('updated_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False), - sa.Column('file_name', sa.String(length=450), nullable=False), - sa.Column('file_name_no_tags', sa.String(length=450), nullable=False), - sa.Column('file_extension', sa.String(length=10), nullable=False), - sa.Column('file_path', sa.String(length=1000), nullable=False), - sa.Column('file_size_bytes', sa.Integer(), nullable=False), - sa.ForeignKeyConstraint(['platform_slug'], ['platforms.slug'], ondelete='CASCADE'), - sa.ForeignKeyConstraint(['rom_id'], ['roms.id'], ondelete='CASCADE'), - sa.PrimaryKeyConstraint('id') + op.create_table( + "screenshots", + sa.Column("rom_id", sa.Integer(), nullable=False), + sa.Column("platform_slug", sa.String(length=50), nullable=True), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column( + "created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False + ), + sa.Column( + "updated_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False + ), + sa.Column("file_name", sa.String(length=450), nullable=False), + sa.Column("file_name_no_tags", sa.String(length=450), nullable=False), + sa.Column("file_extension", sa.String(length=10), nullable=False), + sa.Column("file_path", sa.String(length=1000), nullable=False), + sa.Column("file_size_bytes", sa.Integer(), nullable=False), + sa.ForeignKeyConstraint( + ["platform_slug"], ["platforms.slug"], ondelete="CASCADE" + ), + sa.ForeignKeyConstraint(["rom_id"], ["roms.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), ) - op.create_table('states', - sa.Column('emulator', sa.String(length=50), nullable=True), - sa.Column('rom_id', sa.Integer(), nullable=False), - sa.Column('platform_slug', sa.String(length=50), nullable=False), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False), - sa.Column('updated_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False), - sa.Column('file_name', sa.String(length=450), nullable=False), - sa.Column('file_name_no_tags', sa.String(length=450), nullable=False), - sa.Column('file_extension', sa.String(length=10), nullable=False), - sa.Column('file_path', sa.String(length=1000), nullable=False), - sa.Column('file_size_bytes', sa.Integer(), nullable=False), - sa.ForeignKeyConstraint(['platform_slug'], ['platforms.slug'], ondelete='CASCADE'), - sa.ForeignKeyConstraint(['rom_id'], ['roms.id'], ondelete='CASCADE'), - sa.PrimaryKeyConstraint('id') + op.create_table( + "states", + sa.Column("emulator", sa.String(length=50), nullable=True), + sa.Column("rom_id", sa.Integer(), nullable=False), + sa.Column("platform_slug", sa.String(length=50), nullable=False), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column( + "created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False + ), + sa.Column( + "updated_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False + ), + sa.Column("file_name", sa.String(length=450), nullable=False), + sa.Column("file_name_no_tags", sa.String(length=450), nullable=False), + sa.Column("file_extension", sa.String(length=10), nullable=False), + sa.Column("file_path", sa.String(length=1000), nullable=False), + sa.Column("file_size_bytes", sa.Integer(), nullable=False), + sa.ForeignKeyConstraint( + ["platform_slug"], ["platforms.slug"], ondelete="CASCADE" + ), + sa.ForeignKeyConstraint(["rom_id"], ["roms.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), ) # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('states') - op.drop_table('screenshots') - op.drop_table('saves') + op.drop_table("states") + op.drop_table("screenshots") + op.drop_table("saves") # ### end Alembic commands ### diff --git a/backend/alembic/versions/0015_rom_filesize.py b/backend/alembic/versions/0015_rom_filesize.py new file mode 100644 index 000000000..73f056b92 --- /dev/null +++ b/backend/alembic/versions/0015_rom_filesize.py @@ -0,0 +1,55 @@ +"""empty message + +Revision ID: 0015_rom_filesize +Revises: 0014_asset_files +Create Date: 2024-01-16 10:28:15.812026 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.sql import text + + +# revision identifiers, used by Alembic. +revision = "0015_rom_filesize" +down_revision = "0014_asset_files" +branch_labels = None +depends_on = None + +SIZE_UNIT_TO_BYTES = { + "B": 1, + "KB": 1024, + "MB": 1024**2, + "GB": 1024**3, + "TB": 1024**4, + "PB": 1024**5, +} + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.add_column(sa.Column("file_size_bytes", sa.Integer(), nullable=False)) + # ### end Alembic commands ### + + connection = op.get_bind() + result = connection.execute(text("SELECT id, file_size, file_size_units FROM roms")) + + # Process the data and prepare for bulk update + updates = [] + for row in result: + file_size_bytes = int(row[1] * SIZE_UNIT_TO_BYTES.get(row[2], 1)) + updates.append({"id": row[0], "file_size_bytes": file_size_bytes}) + + # Perform bulk update + connection.execute( + text("UPDATE roms SET file_size_bytes = :file_size_bytes WHERE id = :id"), + updates, + ) + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.drop_column("file_size_bytes") + # ### end Alembic commands ### diff --git a/backend/endpoints/rom.py b/backend/endpoints/rom.py index d334b819b..8e978f3cd 100644 --- a/backend/endpoints/rom.py +++ b/backend/endpoints/rom.py @@ -52,8 +52,6 @@ class RomSchema(BaseModel): file_name_no_tags: str file_extension: str file_path: str - file_size: float - file_size_units: str file_size_bytes: int name: Optional[str] diff --git a/backend/handler/db_handler.py b/backend/handler/db_handler.py index b227d33de..6e65753bc 100644 --- a/backend/handler/db_handler.py +++ b/backend/handler/db_handler.py @@ -346,3 +346,39 @@ class DBHandler: @begin_session def get_admin_users(self, session: Session = None): return session.scalars(select(User).filter_by(role=Role.ADMIN)).all() + + # ========= Stats ========= + @begin_session + def get_platforms_count(self, session: Session = None): + # Only count platforms with more then 0 roms + return session.scalar( + select(func.count()) + .select_from(Platform) + .where( + select(func.count()) + .select_from(Rom) + .filter_by(platform_slug=Platform.slug) + .as_scalar() + > 0 + ) + ) + + @begin_session + def get_roms_count(self, session: Session = None) -> int: + return session.scalar(select(func.count()).select_from(Rom)) + + @begin_session + def get_saves_count(self, session: Session = None) -> int: + return session.scalar(select(func.count()).select_from(Save)) + + @begin_session + def get_states_count(self, session: Session = None) -> int: + return session.scalar(select(func.count()).select_from(State)) + + @begin_session + def get_screenshots_count(self, session: Session = None) -> int: + return session.scalar(select(func.count()).select_from(Screenshot)) + + @begin_session + def get_total_filesize(self, session: Session = None) -> int: + return 0 diff --git a/backend/handler/tests/conftest.py b/backend/handler/tests/conftest.py index 18ed2ebd7..95eae34ce 100644 --- a/backend/handler/tests/conftest.py +++ b/backend/handler/tests/conftest.py @@ -47,8 +47,7 @@ def rom(platform: Platform): file_name_no_tags="test_rom", file_extension="zip", file_path=f"{platform.slug}/roms", - file_size=1.0, - file_size_units="MB", + file_size_bytes=1000.0, ) return dbh.add_rom(rom) diff --git a/backend/handler/tests/test_db_handler.py b/backend/handler/tests/test_db_handler.py index 706237b6e..ac1f23d73 100644 --- a/backend/handler/tests/test_db_handler.py +++ b/backend/handler/tests/test_db_handler.py @@ -35,8 +35,7 @@ def test_roms(rom): file_name_no_tags="test_rom_2", file_extension="zip", file_path=f"{rom.platform_slug}/roms", - file_size=1.0, - file_size_units="MB", + file_size_bytes=1000.0, ) ) diff --git a/backend/main.py b/backend/main.py index 5b038209f..9f85db48c 100644 --- a/backend/main.py +++ b/backend/main.py @@ -146,6 +146,33 @@ def heartbeat() -> HeartbeatReturn: } +class StatsReturn(TypedDict): + PLATFORMS: int + ROMS: int + SAVES: int + STATES: int + SCREENSHOTS: int + FILESIZE: int + + +@app.get("/stats") +def stats() -> StatsReturn: + """Endpoint to return the current RomM stats + + Returns: + dict: Dictionary with all the stats + """ + + return { + "PLATFORMS": dbh.get_platforms_count(), + "ROMS": dbh.get_roms_count(), + "SAVES": dbh.get_saves_count(), + "STATES": dbh.get_states_count(), + "SCREENSHOTS": dbh.get_screenshots_count(), + "FILESIZE": dbh.get_total_filesize(), + } + + @app.on_event("startup") def startup() -> None: """Event to handle RomM startup logic.""" diff --git a/backend/models/rom.py b/backend/models/rom.py index 4589d5cba..50fb67829 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -12,15 +12,6 @@ from sqlalchemy.orm import Mapped, relationship from .base import BaseModel -SIZE_UNIT_TO_BYTES = { - "B": 1, - "KB": 1024, - "MB": 1024 ^ 2, - "GB": 1024 ^ 3, - "TB": 1024 ^ 4, - "PB": 1024 ^ 5, -} - SORT_COMPARE_REGEX = r"^([Tt]he|[Aa]|[Aa]nd)\s" @@ -59,14 +50,15 @@ class Rom(BaseModel): p_name: str = Column(String(length=150), default="") p_igdb_id: str = Column(String(length=10), default="") p_sgdb_id: str = Column(String(length=10), default="") + file_size = Column(Float, default=0.0, nullable=False) + file_size_units: str = Column(String(length=10), default="B", nullable=False) ### DEPRECATED ### file_name: str = Column(String(length=450), nullable=False) file_name_no_tags: str = Column(String(length=450), nullable=False) file_extension: str = Column(String(length=100), nullable=False) file_path: str = Column(String(length=1000), nullable=False) - file_size = Column(Float, default=0.0, nullable=False) - file_size_units: str = Column(String(length=10), nullable=False) + file_size_bytes: int = Column(Integer(), default=0, nullable=False) name: str = Column(String(length=350)) slug: str = Column(String(length=400)) @@ -97,10 +89,6 @@ class Rom(BaseModel): def download_path(self) -> str: return f"{FRONTEND_LIBRARY_PATH}/{self.full_path}" - @property - def file_size_bytes(self) -> int: - return int(self.file_size * SIZE_UNIT_TO_BYTES[self.file_size_units or "B"]) - @cached_property def has_cover(self) -> bool: return ( diff --git a/backend/utils/fastapi.py b/backend/utils/fastapi.py index e05b1954c..2c78796d1 100644 --- a/backend/utils/fastapi.py +++ b/backend/utils/fastapi.py @@ -70,7 +70,7 @@ async def scan_rom( log.info(f"\t\t ยท {file}") # Update properties that don't require IGDB - file_size, file_size_units = fs.get_rom_file_size( + file_size = fs.get_rom_file_size( multi=rom_attrs["multi"], file_name=rom_attrs["file_name"], multi_files=rom_attrs["files"], @@ -83,8 +83,7 @@ async def scan_rom( "file_name": rom_attrs["file_name"], "file_name_no_tags": get_file_name_with_no_tags(rom_attrs["file_name"]), "file_extension": get_file_extension(rom_attrs["file_name"]), - "file_size": file_size, - "file_size_units": file_size_units, + "file_size_bytes": file_size, "multi": rom_attrs["multi"], "regions": regs, "revision": rev, diff --git a/backend/utils/fs.py b/backend/utils/fs.py index 200cf50d2..49d95568d 100644 --- a/backend/utils/fs.py +++ b/backend/utils/fs.py @@ -395,14 +395,8 @@ def get_rom_file_size( for file in multi_files ] ) - total_size: float = 0.0 - for file in files: - total_size += os.stat(file).st_size - for unit in ["B", "KB", "MB", "GB", "TB", "PB"]: - if total_size < 1024.0 or unit == "PB": - break - total_size /= 1024.0 - return round(total_size, 2), unit + + return sum([os.stat(file).st_size for file in files]) def get_fs_file_size(asset_path: str, file_name: str): diff --git a/backend/utils/tests/test_fastapi.py b/backend/utils/tests/test_fastapi.py index 4e5f73735..dfbfd9768 100644 --- a/backend/utils/tests/test_fastapi.py +++ b/backend/utils/tests/test_fastapi.py @@ -37,8 +37,7 @@ async def test_scan_rom(): assert rom.file_name == "Paper Mario (USA).z64" assert rom.name == "Paper Mario" assert rom.igdb_id == 3340 - assert rom.file_size == 1.0 - assert rom.file_size_units == "KB" + assert rom.file_size_bytes == 1024 assert rom.files == ["Paper Mario (USA).z64"] assert rom.tags == [] assert not rom.multi diff --git a/backend/utils/tests/test_fs.py b/backend/utils/tests/test_fs.py index 74ecd49a9..cf49e5620 100644 --- a/backend/utils/tests/test_fs.py +++ b/backend/utils/tests/test_fs.py @@ -117,7 +117,7 @@ def test_rom_size(): multi=False, ) - assert rom_size == (1.0, "KB") + assert rom_size == 1024 rom_size = get_rom_file_size( roms_path=get_fs_structure(fs_slug="n64"), @@ -129,7 +129,7 @@ def test_rom_size(): ], ) - assert rom_size == (2.0, "KB") + assert rom_size == 2048 def test__exclude_files(): from config.config_loader import config diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index 93659d3c2..63e7997ed 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -28,6 +28,7 @@ export type { SaveSchema } from './models/SaveSchema'; export type { SchedulerDict } from './models/SchedulerDict'; export type { ScreenshotSchema } from './models/ScreenshotSchema'; export type { StateSchema } from './models/StateSchema'; +export type { StatsReturn } from './models/StatsReturn'; export type { TaskDict } from './models/TaskDict'; export type { TokenResponse } from './models/TokenResponse'; export type { UploadedSavesResponse } from './models/UploadedSavesResponse'; diff --git a/frontend/src/__generated__/models/EnhancedRomSchema.ts b/frontend/src/__generated__/models/EnhancedRomSchema.ts index 416895b3b..8f86ff83e 100644 --- a/frontend/src/__generated__/models/EnhancedRomSchema.ts +++ b/frontend/src/__generated__/models/EnhancedRomSchema.ts @@ -18,8 +18,6 @@ export type EnhancedRomSchema = { file_name_no_tags: string; file_extension: string; file_path: string; - file_size: number; - file_size_units: string; file_size_bytes: number; name: (string | null); slug: (string | null); diff --git a/frontend/src/__generated__/models/RomSchema.ts b/frontend/src/__generated__/models/RomSchema.ts index c1801d045..5e47c314b 100644 --- a/frontend/src/__generated__/models/RomSchema.ts +++ b/frontend/src/__generated__/models/RomSchema.ts @@ -17,8 +17,6 @@ export type RomSchema = { file_name_no_tags: string; file_extension: string; file_path: string; - file_size: number; - file_size_units: string; file_size_bytes: number; name: (string | null); slug: (string | null); diff --git a/frontend/src/__generated__/models/StatsReturn.ts b/frontend/src/__generated__/models/StatsReturn.ts new file mode 100644 index 000000000..5ef1e66b5 --- /dev/null +++ b/frontend/src/__generated__/models/StatsReturn.ts @@ -0,0 +1,14 @@ +/* generated using openapi-typescript-codegen -- do no edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ + +export type StatsReturn = { + PLATFORMS: number; + ROMS: number; + SAVES: number; + STATES: number; + SCREENSHOTS: number; + FILESIZE: number; +}; + diff --git a/frontend/src/components/Dashboard/Summary.vue b/frontend/src/components/Dashboard/Summary.vue index 586c5d6d1..ebebd0d47 100644 --- a/frontend/src/components/Dashboard/Summary.vue +++ b/frontend/src/components/Dashboard/Summary.vue @@ -1,8 +1,21 @@