Merge remote-tracking branch 'origin/stats-endpoint' into refactor/backend

This commit is contained in:
Zurdi
2024-01-16 18:37:22 +01:00
21 changed files with 272 additions and 117 deletions

View File

@@ -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 ###

View File

@@ -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 ###

View File

@@ -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]

View File

@@ -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:

View File

@@ -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

View File

@@ -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):

View File

@@ -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,

View File

@@ -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)

View File

@@ -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,
)
)

View File

@@ -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."""

View File

@@ -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 (

View File

@@ -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

View File

@@ -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():

View File

@@ -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';

View File

@@ -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);

View File

@@ -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);

View File

@@ -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;
};

View File

@@ -1,8 +1,21 @@
<script setup lang="ts">
import storePlatforms from "@/stores/platforms";
import { onBeforeMount, ref } from "vue";
// Props
const platforms = storePlatforms();
import { api } from "@/services/api";
const stats = ref({
PLATFORMS: 0,
ROMS: 0,
SAVES: 0,
STATES: 0,
SCREENSHOTS: 0,
FILESIZE: 0,
});
onBeforeMount(async () => {
const { data } = await api.get("/stats");
stats.value = data;
});
</script>
<template>
<v-card rounded="0">
@@ -10,10 +23,22 @@ const platforms = storePlatforms();
<v-chip-group>
<v-chip class="text-overline" variant="text" label>
<v-icon class="mr-2">mdi-controller</v-icon
>{{ platforms.filledPlatforms.length }} Platforms
>{{ stats.PLATFORMS }} Platforms
</v-chip>
<v-chip class="text-overline" variant="text" label>
<v-icon class="mr-2">mdi-disc</v-icon>{{ platforms.totalGames }} Games
<v-icon class="mr-2">mdi-disc</v-icon>{{ stats.ROMS }} Games
</v-chip>
<v-chip class="text-overline" variant="text" label>
<v-icon class="mr-2">mdi-disc</v-icon>{{ stats.SAVES }} Games
</v-chip>
<v-chip class="text-overline" variant="text" label>
<v-icon class="mr-2">mdi-disc</v-icon>{{ stats.STATES }} Games
</v-chip>
<v-chip class="text-overline" variant="text" label>
<v-icon class="mr-2">mdi-disc</v-icon>{{ stats.SCREENSHOTS }} Games
</v-chip>
<v-chip class="text-overline" variant="text" label>
<v-icon class="mr-2">mdi-disc</v-icon>{{ stats.FILESIZE }} Games
</v-chip>
</v-chip-group>
</v-card-text>

View File

@@ -2,6 +2,7 @@
import type { EnhancedRomSchema, PlatformSchema } from "@/__generated__";
import VersionSwitcher from "@/components/Details/VersionSwitcher.vue";
import storeDownload from "@/stores/download";
import { formatBytes } from "@/utils";
defineProps<{ rom: EnhancedRomSchema, platform: PlatformSchema }>();
const downloadStore = storeDownload();
@@ -53,7 +54,7 @@ const downloadStore = storeDownload();
<span>Size</span>
</v-col>
<v-col>
<span>{{ rom.file_size }} {{ rom.file_size_units }}</span>
<span>{{ formatBytes(rom.file_size_bytes) }}</span>
</v-col>
</v-row>
<v-row v-if="rom.igdb_id" class="align-center py-2" no-gutters>

View File

@@ -8,7 +8,7 @@ import api_rom from "@/services/api_rom";
import storeAuth from "@/stores/auth";
import storeDownload from "@/stores/download";
import storeRoms from "@/stores/roms";
import { languageToEmoji, regionToEmoji } from "@/utils";
import { regionToEmoji, languageToEmoji, formatBytes } from "@/utils";
const HEADERS = [
{
@@ -104,8 +104,7 @@ function rowClick(_: Event, row: any) {
</template>
<template v-slot:item.file_size_bytes="{ item }">
<span>
{{ item.raw.file_size }}
{{ item.raw.file_size_units }}
{{ formatBytes(item.raw.file_size_bytes) }}
</span>
</template>
<template v-slot:item.regions="{ item }">

View File

@@ -44,17 +44,14 @@ const editable = ref(false);
md="3"
lg="2"
xl="2"
v-for="slug, fsSlug in platformsBinding"
v-for="(slug, fsSlug) in platformsBinding"
:key="slug"
:title="slug"
>
<v-list-item class="bg-terciary ma-1 pa-1 text-truncate">
<template v-slot:prepend>
<v-avatar :rounded="0" size="40" class="mx-2">
<platform-icon
class="platform-icon"
:slug="slug"
/>
<platform-icon class="platform-icon" :slug="slug" />
</v-avatar>
</template>
<v-list-item class="bg-primary pr-2 pl-2">
@@ -63,15 +60,17 @@ const editable = ref(false);
<v-slide-x-reverse-transition>
<v-btn
v-if="
authStore.scopes.includes('platforms.write') &&
editable
authStore.scopes.includes('platforms.write') && editable
"
rounded="0"
variant="text"
size="x-small"
icon="mdi-pencil"
@click="
emitter?.emit('showCreatePlatformBindingDialog', {fsSlug, slug})
emitter?.emit('showCreatePlatformBindingDialog', {
fsSlug,
slug,
})
"
class="ml-2"
/>
@@ -79,15 +78,17 @@ const editable = ref(false);
<v-slide-x-reverse-transition>
<v-btn
v-if="
authStore.scopes.includes('platforms.write') &&
editable
authStore.scopes.includes('platforms.write') && editable
"
rounded="0"
variant="text"
size="x-small"
icon="mdi-delete"
@click="
emitter?.emit('showDeletePlatformBindingDialog', {fsSlug, slug})
emitter?.emit('showDeletePlatformBindingDialog', {
fsSlug,
slug,
})
"
class="text-romm-red"
/>
@@ -99,16 +100,19 @@ const editable = ref(false);
<v-col cols="6" sm="4" md="3" lg="2" xl="2" class="px-1">
<v-expand-transition>
<v-btn
v-if="
authStore.scopes.includes('platforms.write') && editable
"
v-if="authStore.scopes.includes('platforms.write') && editable"
block
rounded="0"
size="large"
prepend-icon="mdi-plus"
variant="outlined"
class="text-romm-accent-1"
@click="emitter?.emit('showCreatePlatformBindingDialog', {fsSlug: '', slug: ''})"
@click="
emitter?.emit('showCreatePlatformBindingDialog', {
fsSlug: '',
slug: '',
})
"
>
Add
</v-btn>