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..a19cde7a7 --- /dev/null +++ b/backend/alembic/versions/0015_rom_filesize.py @@ -0,0 +1,58 @@ +"""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}) + + if not updates: + return + + # 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/responses/rom.py b/backend/endpoints/responses/rom.py index 818aa89e1..7f833bfd5 100644 --- a/backend/endpoints/responses/rom.py +++ b/backend/endpoints/responses/rom.py @@ -18,8 +18,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/endpoints/rom.py b/backend/endpoints/rom.py index e9503a2d1..66ea8e2ea 100644 --- a/backend/endpoints/rom.py +++ b/backend/endpoints/rom.py @@ -28,6 +28,7 @@ router = APIRouter() def add_roms( request: Request, platform_id: int, roms: list[UploadFile] = File(...) ) -> AddRomsResponse: + """Upload roms endpoint (one or more at the same time) Args: diff --git a/backend/handler/db_handler/db_handler.py b/backend/handler/db_handler/db_handler.py index 1dc1404ea..3cc6932e5 100644 --- a/backend/handler/db_handler/db_handler.py +++ b/backend/handler/db_handler/db_handler.py @@ -94,3 +94,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/fs_handler/fs_roms_handler.py b/backend/handler/fs_handler/fs_roms_handler.py index 02c44b9c2..704eb59e8 100644 --- a/backend/handler/fs_handler/fs_roms_handler.py +++ b/backend/handler/fs_handler/fs_roms_handler.py @@ -160,14 +160,7 @@ class FSRomsHandler(FSHandler): 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]) @staticmethod def file_exists(path: str, file_name: str): diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index d76e69efc..18dd99f36 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -71,7 +71,7 @@ async def scan_rom( log.info(f"\t\t ยท {file}") # Update properties that don't require IGDB - file_size, file_size_units = fsromh.get_rom_file_size( + file_size = fsromh.get_rom_file_size( multi=rom_attrs["multi"], file_name=rom_attrs["file_name"], multi_files=rom_attrs["files"], @@ -82,12 +82,9 @@ async def scan_rom( { "file_path": roms_path, "file_name": rom_attrs["file_name"], - "file_name_no_tags": fsromh.get_file_name_with_no_tags( - rom_attrs["file_name"] - ), + "file_name_no_tags": fsromh.get_file_name_with_no_tags(rom_attrs["file_name"]), "file_extension": fsromh.parse_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/handler/tests/conftest.py b/backend/handler/tests/conftest.py index 125b3146f..aec56fb7b 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 1dfbcb818..55d2984c1 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 6d6fdf673..835219ecc 100644 --- a/backend/main.py +++ b/backend/main.py @@ -1,5 +1,6 @@ import re import sys +from typing_extensions import TypedDict import alembic.config import uvicorn @@ -75,6 +76,33 @@ add_pagination(app) app.mount("/ws", socketh.socket_app) +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 c7de143e9..374cf2a9b 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -9,18 +9,9 @@ from config import ( ) from models.assets import Save, Screenshot, State from models.base import BaseModel -from sqlalchemy import JSON, Boolean, Column, Float, ForeignKey, Integer, String, Text +from sqlalchemy import JSON, Boolean, Column, ForeignKey, Integer, String, Text from sqlalchemy.orm import Mapped, relationship -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" @@ -36,8 +27,7 @@ class Rom(BaseModel): 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)) @@ -98,10 +88,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/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 c50a13f4d..0d3c1f1f1 100644 --- a/backend/utils/tests/test_fs.py +++ b/backend/utils/tests/test_fs.py @@ -113,7 +113,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"), @@ -125,7 +125,7 @@ def test_rom_size(): ], ) - assert rom_size == (2.0, "KB") + assert rom_size == 2048 def test_exclude_files(): diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index e9eb450bd..e7390d3a5 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -25,6 +25,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 80c05f876..039edbd48 100644 --- a/frontend/src/__generated__/models/EnhancedRomSchema.ts +++ b/frontend/src/__generated__/models/EnhancedRomSchema.ts @@ -17,8 +17,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 a010d24a1..d944b5ae2 100644 --- a/frontend/src/__generated__/models/RomSchema.ts +++ b/frontend/src/__generated__/models/RomSchema.ts @@ -16,8 +16,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..83b5afc69 100644 --- a/frontend/src/components/Dashboard/Summary.vue +++ b/frontend/src/components/Dashboard/Summary.vue @@ -1,8 +1,21 @@