diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index 65e033f98..1b4ad9889 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -2,7 +2,7 @@ # To learn more about the format of this file, see https://docs.trunk.io/reference/trunk-yaml version: 0.1 cli: - version: 1.22.12 + version: 1.22.15 # Trunk provides extensibility via plugins. (https://docs.trunk.io/plugins) plugins: sources: @@ -21,25 +21,25 @@ lint: - pyright enabled: - markdownlint@0.44.0 - - eslint@9.25.1 + - eslint@9.26.0 - actionlint@1.7.7 - bandit@1.8.3 - black@25.1.0 - - checkov@3.2.408 + - checkov@3.2.424 - git-diff-check - isort@6.0.1 - mypy@1.15.0 - - osv-scanner@2.0.1 - - oxipng@9.1.4 + - osv-scanner@2.0.2 + - oxipng@9.1.5 - prettier@3.5.3 - - ruff@0.11.6 + - ruff@0.11.10 - shellcheck@0.10.0 - shfmt@3.6.0 - svgo@3.3.2 - taplo@0.9.3 - - trivy@0.61.1 - - trufflehog@3.88.25 - - yamllint@1.37.0 + - trivy@0.62.1 + - trufflehog@3.88.29 + - yamllint@1.37.1 ignore: - linters: [ALL] paths: diff --git a/.vscode/settings.json b/.vscode/settings.json index 4c2d55129..0331bee6a 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -3,5 +3,19 @@ "python.testing.pytestArgs": ["."], "python.testing.unittestEnabled": false, "python.testing.pytestEnabled": true, - "postman.settings.dotenv-detection-notification-visibility": false + "sqltools.connections": [ + { + "mysqlOptions": { + "authProtocol": "default", + "enableSsl": "Disabled" + }, + "previewLimit": 50, + "server": "localhost", + "port": 3306, + "driver": "MariaDB", + "name": "romm (dev)", + "database": "romm", + "username": "root" + } + ] } diff --git a/DEVELOPER_SETUP.md b/DEVELOPER_SETUP.md index 134ef56b0..c5e984ec3 100644 --- a/DEVELOPER_SETUP.md +++ b/DEVELOPER_SETUP.md @@ -28,6 +28,14 @@ cp env.template .env ```sh # https://mariadb.com/docs/skysql-previous-release/connect/programming-languages/c/install/#Installation_via_Package_Repository_(Linux): sudo apt install libmariadb3 libmariadb-dev libpq-dev pipx + +# Build and configure RAHasher (optional) +# IMPORTANT! This is only required to calculate RA hashes. This is needed only if RA API is going to be enabled +git clone --recursive --branch 1.8.0 --depth 1 https://github.com/RetroAchievements/RALibretro.git +cd ./RALibretro +sed -i '22a #include ' ./src/Util.h +make HAVE_CHD=1 -f ./Makefile.RAHasher +cp ./bin64/RAHasher /usr/bin/RAHasher ``` #### - Install python dependencies diff --git a/backend/adapters/services/rahasher.py b/backend/adapters/services/rahasher.py index 938e7f689..6c9894879 100644 --- a/backend/adapters/services/rahasher.py +++ b/backend/adapters/services/rahasher.py @@ -1,7 +1,9 @@ import asyncio import re -from pathlib import Path +from handler.metadata.ra_handler import RA_ID_TO_SLUG +from logger.formatter import LIGHTMAGENTA +from logger.formatter import highlight as hl from logger.logger import log RAHASHER_VALID_HASH_REGEX = re.compile(r"^[0-9a-f]{32}$") @@ -87,16 +89,11 @@ class RAHasherError(Exception): ... class RAHasherService: """Service to calculate RetroAchievements hashes using RAHasher.""" - async def calculate_hash(self, platform_slug: str, file_path: Path) -> str: - platform_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID.get(platform_slug) - if not platform_id: - raise RAHasherError( - f"Platform not supported by RetroAchievements. {platform_slug=}" - ) - - args = (str(platform_id), str(file_path)) - log.debug("Executing RAHasher with args: %s", args) - + async def calculate_hash(self, platform_id: int, file_path: str) -> str: + log.debug( + f"Executing {hl('RAHasher', color=LIGHTMAGENTA)} for platform: {hl(RA_ID_TO_SLUG[platform_id])} - file: {hl(file_path.split('/')[-1])}" + ) + args = (str(platform_id), file_path) proc = await asyncio.create_subprocess_exec( "RAHasher", *args, @@ -109,19 +106,21 @@ class RAHasherService: stderr = (await proc.stderr.read()).decode("utf-8") else: stderr = None - raise RAHasherError(f"RAHasher failed with code {return_code}. {stderr=}") + log.error(f"RAHasher failed with code {return_code}. {stderr=}") + return "" if proc.stdout is None: - raise RAHasherError("RAHasher did not return a hash.") + log.error("RAHasher did not return a hash.") + return "" file_hash = (await proc.stdout.read()).decode("utf-8").strip() if not file_hash: - raise RAHasherError( - f"RAHasher returned an empty hash. {platform_id=}, {file_path=}" - ) + log.error(f"RAHasher returned an empty hash. {platform_id=}, {file_path=}") + return "" if not RAHASHER_VALID_HASH_REGEX.match(file_hash): - raise RAHasherError( + log.error( f"RAHasher returned an invalid hash: {file_hash=}, {platform_id=}, {file_path=}" ) + return "" return file_hash diff --git a/backend/alembic.ini b/backend/alembic.ini index 051854d0b..78c10646c 100644 --- a/backend/alembic.ini +++ b/backend/alembic.ini @@ -63,7 +63,7 @@ version_path_separator = os # Use os.pathsep. Default configuration used for ne sqlalchemy.url = '' -[post_write_hooks] +# [post_write_hooks] # post_write_hooks defines scripts or Python functions that are run # on newly generated revision scripts. See the documentation for further # detail and examples @@ -73,38 +73,3 @@ sqlalchemy.url = '' # black.type = console_scripts # black.entrypoint = black # black.options = -l 79 REVISION_SCRIPT_FILENAME - -# Logging configuration -[loggers] -keys = root,sqlalchemy,alembic - -[handlers] -keys = console - -[formatters] -keys = generic - -[logger_root] -level = WARN -handlers = console -qualname = - -[logger_sqlalchemy] -level = WARN -handlers = -qualname = sqlalchemy.engine - -[logger_alembic] -level = INFO -handlers = -qualname = alembic - -[handler_console] -class = StreamHandler -args = (sys.stderr,) -level = NOTSET -formatter = generic - -[formatter_generic] -format = %(levelname)s: [RomM][%(name)s] %(message)s -datefmt = %H:%M:%S diff --git a/backend/alembic/env.py b/backend/alembic/env.py index d99ef2fb5..9fed12b77 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -1,9 +1,9 @@ import sys -from logging.config import fileConfig from pathlib import Path from alembic import context from config.config_manager import ConfigManager +from logger.logger import unify_logger from models.assets import Save, Screenshot, State # noqa from models.base import BaseModel from models.collection import VirtualCollection @@ -17,10 +17,7 @@ from sqlalchemy import create_engine # access to the values within the .ini file in use. config = context.config -# Interpret the config file for Python logging. -# This line sets up loggers basically. -if config.config_file_name is not None: - fileConfig(config.config_file_name, disable_existing_loggers=False) +unify_logger("alembic") # add your model's MetaData object here # for 'autogenerate' support diff --git a/backend/alembic/versions/0039_add_retro_achievements.py b/backend/alembic/versions/0039_add_retro_achievements.py new file mode 100644 index 000000000..d717285b6 --- /dev/null +++ b/backend/alembic/versions/0039_add_retro_achievements.py @@ -0,0 +1,59 @@ +"""add retro achievements data + +Revision ID: 0039_add_retro_achievements +Revises: 0038_add_ssid_to_sibling_roms +Create Date: 2025-04-11 00:59:30.772416 + +""" + +import sqlalchemy as sa +from alembic import op +from utils.database import CustomJSON + +# revision identifiers, used by Alembic. +revision = "0039_add_retro_achievements" +down_revision = "0038_add_ssid_to_sibling_roms" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table("rom_user", schema=None) as batch_op: + batch_op.add_column(sa.Column("ra_metadata", CustomJSON(), nullable=True)) + + with op.batch_alter_table("rom_files", schema=None) as batch_op: + batch_op.add_column(sa.Column("ra_hash", sa.String(length=100), nullable=True)) + + with op.batch_alter_table("platforms", schema=None) as batch_op: + batch_op.add_column(sa.Column("ra_id", sa.Integer(), nullable=True)) + + with op.batch_alter_table("users", schema=None) as batch_op: + batch_op.add_column( + sa.Column("ra_username", sa.String(length=100), nullable=True) + ) + batch_op.add_column(sa.Column("ra_progression", CustomJSON(), nullable=True)) + + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.add_column(sa.Column("ra_id", sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column("ra_hash", sa.String(length=100), nullable=True)) + batch_op.add_column(sa.Column("ra_metadata", CustomJSON(), nullable=True)) + + +def downgrade() -> None: + with op.batch_alter_table("rom_user", schema=None) as batch_op: + batch_op.drop_column("ra_metadata") + + with op.batch_alter_table("platforms", schema=None) as batch_op: + batch_op.drop_column("ra_id") + + with op.batch_alter_table("users", schema=None) as batch_op: + batch_op.drop_column("ra_username") + batch_op.drop_column("ra_progression") + + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.drop_column("ra_id") + batch_op.drop_column("ra_hash") + batch_op.drop_column("ra_metadata") + + with op.batch_alter_table("rom_files", schema=None) as batch_op: + batch_op.drop_column("ra_hash") diff --git a/backend/alembic/versions/0040_migrate_assets_paths.py b/backend/alembic/versions/0040_migrate_assets_paths.py new file mode 100644 index 000000000..1cda51aed --- /dev/null +++ b/backend/alembic/versions/0040_migrate_assets_paths.py @@ -0,0 +1,117 @@ +"""migrate asset file paths to include rom_id + +Revision ID: 0040_migrate_assets_paths +Revises: 0039_add_retro_achievements +Create Date: 2025-05-14 18:10:23.522345 +""" + +import os + +from alembic import op +from config import ASSETS_BASE_PATH +from logger.logger import log +from sqlalchemy.sql import text +from utils.database import is_postgresql + +# revision identifiers, used by Alembic. +revision = "0040_migrate_assets_paths" +down_revision = "0039_add_retro_achievements" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + conn = op.get_bind() + + # Table configuration: whether each table has an emulator column + tables_with_emulator_column = { + "saves": True, + "states": True, + "screenshots": False, + } + + for table, has_emulator in tables_with_emulator_column.items(): + log.info(f"Processing table: {table}") + + # Database-specific LIKE clause + like_clause = ( + "file_path NOT LIKE '%%/' || rom_id::text || '/%%'" + if is_postgresql(conn) + else "file_path NOT LIKE CONCAT('%/', rom_id, '/%')" + ) + + # Build query based on whether emulator exists + select_cols = "id, file_path, rom_id" + (", emulator" if has_emulator else "") + results = conn.execute( + text( + f""" + SELECT {select_cols} + FROM {table} + WHERE {like_clause} + """ # nosec B608 + ) + ).fetchall() + + for row in results: + item_id = row.id + old_path = row.file_path + rom_id = row.rom_id + emulator = row.emulator if has_emulator else None + + if not old_path or not rom_id: + continue # Skip incomplete records + + parts = old_path.split("/") + try: + user_id = parts[1] + platform = parts[3] + except IndexError: + log.info(f"[{table}] Skipping malformed path: {old_path}") + continue + + # Always include rom_id in the path + path_parts = ["users", user_id, table, platform, str(rom_id)] + if emulator: + path_parts.append(emulator) + new_path = "/".join(path_parts) + + old_abs = os.path.join(ASSETS_BASE_PATH, *old_path.split("/")) + new_abs = os.path.join(ASSETS_BASE_PATH, *new_path.split("/")) + + try: + os.makedirs(os.path.dirname(new_abs), exist_ok=True) + + if os.path.exists(old_abs): + if table == "screenshots" and os.path.isdir(old_abs): + # Move files individually to avoid moving directory into itself + for filename in os.listdir(old_abs): + src = os.path.join(old_abs, filename) + dst = os.path.join(new_abs, filename) + os.makedirs(os.path.dirname(dst), exist_ok=True) + os.rename(src, dst) + log.info(f"[{table}] Moved file: {src} -> {dst}") + else: + os.rename(old_abs, new_abs) + log.info(f"[{table}] Moved: {old_abs} -> {new_abs}") + else: + log.info(f"[{table}] Old path does not exist: {old_abs}") + except Exception as e: + log.error(f"[{table}] Error moving {old_abs} to {new_abs}: {e}") + continue + + # Update DB + conn.execute( + text( + f""" + UPDATE {table} + SET file_path = :new_path + WHERE id = :item_id + """ # nosec B608 + ), + {"new_path": new_path, "item_id": item_id}, + ) + + +def downgrade() -> None: + # Optional: implement reverse logic if desired + pass diff --git a/backend/config/__init__.py b/backend/config/__init__.py index 1d4ebd411..567ada657 100644 --- a/backend/config/__init__.py +++ b/backend/config/__init__.py @@ -12,6 +12,8 @@ def str_to_bool(value: str) -> bool: return value.lower() in ("true", "1") +ROMM_BASE_URL = os.environ.get("ROMM_BASE_URL", "http://0.0.0.0") + # GUNICORN DEV_MODE: Final = str_to_bool(os.environ.get("DEV_MODE", "false")) DEV_HOST: Final = os.environ.get("DEV_HOST", "127.0.0.1") @@ -64,6 +66,12 @@ SCREENSCRAPER_PASSWORD: Final = os.environ.get("SCREENSCRAPER_PASSWORD", "") # STEAMGRIDDB STEAMGRIDDB_API_KEY: Final = os.environ.get("STEAMGRIDDB_API_KEY", "").strip() +# RETROACHIEVEMENTS +RETROACHIEVEMENTS_API_KEY: Final = os.environ.get("RETROACHIEVEMENTS_API_KEY", "") +REFRESH_RETROACHIEVEMENTS_CACHE_DAYS: Final = int( + os.environ.get("REFRESH_RETROACHIEVEMENTS_CACHE_DAYS", 30) +) + # MOBYGAMES MOBYGAMES_API_KEY: Final = os.environ.get("MOBYGAMES_API_KEY", "").strip() diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index 4e8fe3019..2689723bf 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -19,6 +19,8 @@ from exceptions.config_exceptions import ( ConfigNotReadableException, ConfigNotWritableException, ) +from logger.formatter import BLUE +from logger.formatter import highlight as hl from logger.logger import log from sqlalchemy import URL from yaml.loader import SafeLoader @@ -83,12 +85,6 @@ class ConfigManager: str: database connection string """ - # DEPRECATED - if ROMM_DB_DRIVER == "sqlite": - log.critical("Sqlite is not supported anymore, migrate to mariaDB") - sys.exit(6) - # DEPRECATED - if ROMM_DB_DRIVER == "mariadb": driver = "mariadb+mariadbconnector" elif ROMM_DB_DRIVER == "mysql": @@ -96,7 +92,7 @@ class ConfigManager: elif ROMM_DB_DRIVER == "postgresql": driver = "postgresql+psycopg" else: - log.critical(f"{ROMM_DB_DRIVER} database not supported") + log.critical(f"{hl(ROMM_DB_DRIVER)} database not supported") sys.exit(3) if not DB_USER or not DB_PASSWD: @@ -279,7 +275,7 @@ class ConfigManager: def add_platform_binding(self, fs_slug: str, slug: str) -> None: platform_bindings = self.config.PLATFORMS_BINDING if fs_slug in platform_bindings: - log.warning(f"Binding for {fs_slug} already exists") + log.warning(f"Binding for {hl(fs_slug)} already exists") return platform_bindings[fs_slug] = slug @@ -300,7 +296,7 @@ class ConfigManager: def add_platform_version(self, fs_slug: str, slug: str) -> None: platform_versions = self.config.PLATFORMS_VERSIONS if fs_slug in platform_versions: - log.warning(f"Version for {fs_slug} already exists") + log.warning(f"Version for {hl(fs_slug)} already exists") return platform_versions[fs_slug] = slug @@ -321,7 +317,9 @@ class ConfigManager: def add_exclusion(self, exclusion_type: str, exclusion_value: str): config_item = self.config.__getattribute__(exclusion_type) if exclusion_value in config_item: - log.warning(f"{exclusion_value} already excluded in {exclusion_type}") + log.warning( + f"{hl(exclusion_value)} already excluded in {hl(exclusion_type, color=BLUE)}" + ) return config_item.append(exclusion_value) diff --git a/backend/endpoints/auth.py b/backend/endpoints/auth.py index 4bb8c9626..69e94a64d 100644 --- a/backend/endpoints/auth.py +++ b/backend/endpoints/auth.py @@ -12,11 +12,14 @@ from exceptions.auth_exceptions import ( OIDCNotConfiguredException, UserDisabledException, ) -from fastapi import Depends, HTTPException, Request, status +from fastapi import Body, Depends, HTTPException, Request, status from fastapi.responses import RedirectResponse from fastapi.security.http import HTTPBasic from handler.auth import auth_handler, oauth_handler, oidc_handler from handler.database import db_user_handler +from logger.formatter import CYAN +from logger.formatter import highlight as hl +from logger.logger import log from utils.router import APIRouter ACCESS_TOKEN_EXPIRE_MINUTES: Final = 30 @@ -270,3 +273,48 @@ async def auth_openid(request: Request): ) return RedirectResponse(url="/") + + +@router.post("/forgot-password") +def request_password_reset(username: str = Body(..., embed=True)) -> MessageResponse: + """ "Request a password reset link for the user. + + Args: + username (str): Username of the user requesting the reset + Returns: + MessageResponse: Confirmation message + """ + user = db_user_handler.get_user_by_username(username) + + if user: + auth_handler.generate_password_reset_token(user) + else: + log.warning( + f"Reset password link requested for a user {hl(username, color=CYAN)}, but that username does not exist." + ) + + return {"msg": "If the username exists, a reset link has been sent."} + + +@router.post("/reset-password") +def reset_password( + token: str = Body(..., embed=True), + new_password: str = Body(..., embed=True), +) -> MessageResponse: + """Reset password using the token. + + Args: + token (str): Reset token from the URL + new_password (str): New user password + + Returns: + MessageResponse: Confirmation message + """ + user = auth_handler.verify_password_reset_token(token) + + auth_handler.set_user_new_password(user, new_password) + + log.info( + f"Password was successfully reset for user {hl(user.username, color=CYAN)}." + ) + return {"msg": "Password has been reset successfully."} diff --git a/backend/endpoints/collections.py b/backend/endpoints/collections.py index 6fbf9932c..8a23f00dd 100644 --- a/backend/endpoints/collections.py +++ b/backend/endpoints/collections.py @@ -17,6 +17,8 @@ from handler.auth.constants import Scope from handler.database import db_collection_handler from handler.filesystem import fs_resource_handler from handler.filesystem.base_handler import CoverSize +from logger.formatter import BLUE +from logger.formatter import highlight as hl from logger.logger import log from models.collection import Collection from PIL import Image @@ -284,12 +286,14 @@ async def delete_collections(request: Request, id: int) -> MessageResponse: if not collection: raise CollectionNotFoundInDatabaseException(id) - log.info(f"Deleting {collection.name} from database") + log.info(f"Deleting {hl(collection.name, color=BLUE)} from database") db_collection_handler.delete_collection(id) try: rmtree(f"{RESOURCES_BASE_PATH}/{collection.fs_resources_path}") except FileNotFoundError: - log.error(f"Couldn't find resources to delete for {collection.name}") + log.error( + f"Couldn't find resources to delete for {hl(collection.name, color=BLUE)}" + ) return {"msg": f"{collection.name} deleted successfully!"} diff --git a/backend/endpoints/firmware.py b/backend/endpoints/firmware.py index f50924061..b36175837 100644 --- a/backend/endpoints/firmware.py +++ b/backend/endpoints/firmware.py @@ -8,6 +8,8 @@ from handler.auth.constants import Scope from handler.database import db_firmware_handler, db_platform_handler from handler.filesystem import fs_firmware_handler from handler.scan_handler import scan_firmware +from logger.formatter import BLUE +from logger.formatter import highlight as hl from logger.logger import log from utils.router import APIRouter @@ -43,8 +45,6 @@ def add_firmware( log.error(error) raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error) - log.info(f"Uploading firmware to {db_platform.fs_slug}") - uploaded_firmware = [] firmware_path = fs_firmware_handler.build_upload_file_path(db_platform.fs_slug) @@ -53,6 +53,10 @@ def add_firmware( log.warning("Empty filename, skipping") continue + log.info( + f"Uploading firmware {hl(file.filename)} to {hl(db_platform.custom_name or db_platform.name, color=BLUE)}" + ) + fs_firmware_handler.write_file(file=file, path=firmware_path) db_firmware = db_firmware_handler.get_firmware_by_filename( @@ -217,21 +221,21 @@ async def delete_firmware( for id in firmare_ids: firmware = db_firmware_handler.get_firmware(id) if not firmware: - error = f"Firmware with ID {id} not found" + error = f"Firmware with ID {hl(id)} not found" log.error(error) raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error) - log.info(f"Deleting {firmware.file_name} from database") + log.info(f"Deleting {hl(firmware.file_name)} from database") db_firmware_handler.delete_firmware(id) if id in delete_from_fs: - log.info(f"Deleting {firmware.file_name} from filesystem") + log.info(f"Deleting {hl(firmware.file_name)} from filesystem") try: fs_firmware_handler.remove_file( file_name=firmware.file_name, file_path=firmware.file_path ) except FileNotFoundError as exc: - error = f"Firmware file {firmware.file_name} not found for platform {firmware.platform_slug}" + error = f"Firmware file {hl(firmware.file_name)} not found for platform {hl(firmware.platform_slug)}" log.error(error) raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=error diff --git a/backend/endpoints/forms/identity.py b/backend/endpoints/forms/identity.py index 479c76639..2d0961d33 100644 --- a/backend/endpoints/forms/identity.py +++ b/backend/endpoints/forms/identity.py @@ -11,6 +11,7 @@ class UserForm: role: str | None = None, enabled: bool | None = None, avatar: UploadFile | None = None, + ra_username: str | None = None, ): self.username = username self.password = password @@ -18,6 +19,7 @@ class UserForm: self.role = role self.enabled = enabled self.avatar = avatar + self.ra_username = ra_username class OAuth2RequestForm: diff --git a/backend/endpoints/heartbeat.py b/backend/endpoints/heartbeat.py index 0903fc335..2298bc525 100644 --- a/backend/endpoints/heartbeat.py +++ b/backend/endpoints/heartbeat.py @@ -17,6 +17,7 @@ from handler.database import db_user_handler from handler.filesystem import fs_platform_handler from handler.metadata.igdb_handler import IGDB_API_ENABLED from handler.metadata.moby_handler import MOBY_API_ENABLED +from handler.metadata.ra_handler import RA_API_ENABLED from handler.metadata.sgdb_handler import STEAMGRIDDB_API_ENABLED from handler.metadata.ss_handler import SS_API_ENABLED from utils import get_version @@ -42,12 +43,14 @@ def heartbeat() -> HeartbeatResponse: }, "METADATA_SOURCES": { "ANY_SOURCE_ENABLED": IGDB_API_ENABLED + or SS_API_ENABLED or MOBY_API_ENABLED - or SS_API_ENABLED, + or RA_API_ENABLED, "IGDB_API_ENABLED": IGDB_API_ENABLED, - "MOBY_API_ENABLED": MOBY_API_ENABLED, "SS_API_ENABLED": SS_API_ENABLED, + "MOBY_API_ENABLED": MOBY_API_ENABLED, "STEAMGRIDDB_ENABLED": STEAMGRIDDB_API_ENABLED, + "RA_ENABLED": RA_API_ENABLED, }, "FILESYSTEM": { "FS_PLATFORMS": fs_platform_handler.get_platforms(), diff --git a/backend/endpoints/platform.py b/backend/endpoints/platform.py index a6ed6986c..154805a8a 100644 --- a/backend/endpoints/platform.py +++ b/backend/endpoints/platform.py @@ -11,6 +11,8 @@ from handler.database import db_platform_handler 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.formatter import BLUE +from logger.formatter import highlight as hl from logger.logger import log from utils.router import APIRouter @@ -36,7 +38,7 @@ async def add_platforms(request: Request) -> PlatformSchema: try: fs_platform_handler.add_platforms(fs_slug=fs_slug) except PlatformAlreadyExistsException: - log.info(f"Detected platform: {fs_slug}") + log.info(f"Detected platform: {hl(fs_slug)}") scanned_platform = await scan_platform(fs_slug, [fs_slug]) return PlatformSchema.model_validate( db_platform_handler.add_platform(scanned_platform) @@ -164,7 +166,9 @@ async def delete_platforms(request: Request, id: int) -> MessageResponse: if not platform: raise PlatformNotFoundInDatabaseException(id) - log.info(f"Deleting {platform.name} [{platform.fs_slug}] from database") + log.info( + f"Deleting {hl(platform.name, color=BLUE)} [{hl(platform.fs_slug)}] from database" + ) db_platform_handler.delete_platform(id) return {"msg": f"{platform.name} - [{platform.fs_slug}] deleted successfully!"} diff --git a/backend/endpoints/responses/heartbeat.py b/backend/endpoints/responses/heartbeat.py index fc1778bf3..8c56d531f 100644 --- a/backend/endpoints/responses/heartbeat.py +++ b/backend/endpoints/responses/heartbeat.py @@ -27,6 +27,7 @@ class MetadataSourcesDict(TypedDict): MOBY_API_ENABLED: bool SS_API_ENABLED: bool STEAMGRIDDB_ENABLED: bool + RA_ENABLED: bool class FilesystemDict(TypedDict): diff --git a/backend/endpoints/responses/identity.py b/backend/endpoints/responses/identity.py index c45bbe778..229f462dc 100644 --- a/backend/endpoints/responses/identity.py +++ b/backend/endpoints/responses/identity.py @@ -1,9 +1,17 @@ from datetime import datetime +from typing import NotRequired, TypedDict, get_type_hints +from handler.metadata.ra_handler import RAUserProgression from models.user import Role from .base import BaseModel +RAProgression = TypedDict( # type: ignore[misc] + "RAProgression", + dict((k, NotRequired[v]) for k, v in get_type_hints(RAUserProgression).items()), + total=False, +) + class UserSchema(BaseModel): id: int @@ -15,9 +23,15 @@ class UserSchema(BaseModel): avatar_path: str last_login: datetime | None last_active: datetime | None + ra_username: str | None = None + ra_progression: RAProgression | None = None created_at: datetime updated_at: datetime class Config: from_attributes = True + + +class InviteLinkSchema(BaseModel): + token: str diff --git a/backend/endpoints/responses/platform.py b/backend/endpoints/responses/platform.py index 9e0068912..4c07d3301 100644 --- a/backend/endpoints/responses/platform.py +++ b/backend/endpoints/responses/platform.py @@ -18,6 +18,7 @@ class PlatformSchema(BaseModel): sgdb_id: int | None = None moby_id: int | None = None ss_id: int | None = None + ra_id: int | None = None category: str | None = None generation: int | None = None family_name: str | None = None diff --git a/backend/endpoints/responses/rom.py b/backend/endpoints/responses/rom.py index 7bea8dd3b..754706546 100644 --- a/backend/endpoints/responses/rom.py +++ b/backend/endpoints/responses/rom.py @@ -9,6 +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 handler.metadata.ra_handler import RAMetadata from handler.metadata.ss_handler import SSMetadata from models.rom import Rom, RomFileCategory, RomUserStatus from pydantic import computed_field, field_validator @@ -32,6 +33,11 @@ RomSSMetadata = TypedDict( # type: ignore[misc] dict((k, NotRequired[v]) for k, v in get_type_hints(SSMetadata).items()), total=False, ) +RomRAMetadata = TypedDict( # type: ignore[misc] + "RomRAMetadata", + dict((k, NotRequired[v]) for k, v in get_type_hints(RAMetadata).items()), + total=False, +) def rom_user_schema_factory() -> RomUserSchema: @@ -166,6 +172,7 @@ class RomSchema(BaseModel): sgdb_id: int | None moby_id: int | None ss_id: int | None + ra_id: int | None platform_id: int platform_slug: str @@ -284,6 +291,7 @@ class SimpleRomSchema(RomSchema): class DetailedRomSchema(RomSchema): + merged_ra_metadata: RomRAMetadata | None merged_screenshots: list[str] siblings: list[SiblingRomSchema] rom_user: RomUserSchema diff --git a/backend/endpoints/responses/stats.py b/backend/endpoints/responses/stats.py index c7b4229be..270cf6877 100644 --- a/backend/endpoints/responses/stats.py +++ b/backend/endpoints/responses/stats.py @@ -7,4 +7,4 @@ class StatsReturn(TypedDict): SAVES: int STATES: int SCREENSHOTS: int - FILESIZE: int + TOTAL_FILESIZE_BYTES: int diff --git a/backend/endpoints/rom.py b/backend/endpoints/rom.py index 0216afb3c..7bc1886b6 100644 --- a/backend/endpoints/rom.py +++ b/backend/endpoints/rom.py @@ -37,6 +37,7 @@ from handler.database.base_handler import sync_session from handler.filesystem import fs_resource_handler, fs_rom_handler from handler.filesystem.base_handler import CoverSize from handler.metadata import meta_igdb_handler, meta_moby_handler, meta_ss_handler +from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log from models.rom import RomFile @@ -85,7 +86,9 @@ async def add_rom(request: Request): platform_fs_slug = db_platform.fs_slug roms_path = fs_rom_handler.build_upload_fs_path(platform_fs_slug) - log.info(f"Uploading file to {platform_fs_slug}") + log.info( + f"Uploading file to {hl(db_platform.custom_name or db_platform.name, color=BLUE)}[{hl(platform_fs_slug)}]" + ) file_location = Path(f"{roms_path}/{filename}") parser = StreamingFormDataParser(headers=request.headers) @@ -93,7 +96,7 @@ async def add_rom(request: Request): parser.register(filename, FileTarget(str(file_location))) if await file_location.exists(): - log.warning(f" - Skipping {filename} since the file already exists") + log.warning(f" - Skipping {hl(filename)} since the file already exists") raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"File {filename} already exists", @@ -144,6 +147,7 @@ def get_roms( matched_only: bool = False, favourites_only: bool = False, duplicates_only: bool = False, + playables_only: bool = False, group_by_meta_id: bool = False, selected_genre: str | None = None, selected_franchise: str | None = None, @@ -168,6 +172,7 @@ def get_roms( matched_only (bool, optional): Filter only matched roms. Defaults to False. favourites_only (bool, optional): Filter only favourite roms. Defaults to False. duplicates_only (bool, optional): Filter only duplicate roms. Defaults to False. + playables_only (bool, optional): Filter only playable roms by emulatorjs. Defaults to False. group_by_meta_id (bool, optional): Group roms by igdb/moby/ssrf ID. Defaults to False. selected_genre (str, optional): Filter by genre. Defaults to None. selected_franchise (str, optional): Filter by franchise. Defaults to None. @@ -201,6 +206,7 @@ def get_roms( matched_only=matched_only, favourites_only=favourites_only, duplicates_only=duplicates_only, + playables_only=playables_only, selected_genre=selected_genre, selected_franchise=selected_franchise, selected_collection=selected_collection, @@ -361,7 +367,9 @@ async def get_rom_content( files = [f for f in rom.files if f.id in file_ids or not file_ids] files.sort(key=lambda x: x.file_name) - log.info(f"User {current_username} is downloading {rom.fs_name}") + log.info( + f"User {hl(current_username, color=BLUE)} is downloading {hl(rom.fs_name)}" + ) # Serve the file directly in development mode for emulatorjs if DEV_MODE: @@ -406,7 +414,7 @@ async def get_rom_content( zip_file.writestr(zip_info, content) except FileNotFoundError: - log.error(f"File {file_path} not found!") + log.error(f"File {hl(file_path)} not found!") raise # Add M3U file if not already present @@ -510,6 +518,7 @@ async def update_rom( "sgdb_id": None, "moby_id": None, "ss_id": None, + "ra_id": None, "name": rom.fs_name, "summary": "", "url_screenshots": [], @@ -522,6 +531,7 @@ async def update_rom( "igdb_metadata": {}, "moby_metadata": {}, "ss_metadata": {}, + "ra_metadata": {}, "revision": "", }, ) @@ -646,7 +656,7 @@ async def update_rom( cleaned_data.update({"path_manual": path_manual}) log.debug( - f"Updating {hl(cleaned_data.get('name', ''))} [{id}] with data {cleaned_data}" + f"Updating {hl(cleaned_data.get('name', ''), color=BLUE)} [{hl(cleaned_data.get('fs_name', ''))}] with data {cleaned_data}" ) db_rom_handler.update_rom(id, cleaned_data) @@ -704,7 +714,7 @@ async def add_rom_manuals(request: Request, id: int): manuals_path = f"{RESOURCES_BASE_PATH}/{rom.fs_resources_path}/manual" file_location = Path(f"{manuals_path}/{rom.id}.pdf") - log.info(f"Uploading {file_location}") + log.info(f"Uploading {hl(str(file_location))}") if not os.path.exists(manuals_path): await Path(manuals_path).mkdir(parents=True, exist_ok=True) @@ -767,22 +777,24 @@ async def delete_roms( if not rom: raise RomNotFoundInDatabaseException(id) - log.info(f"Deleting {rom.fs_name} from database") + log.info( + f"Deleting {hl(str(rom.name), color=BLUE)} [{hl(rom.fs_name)}] from database" + ) db_rom_handler.delete_rom(id) try: rmtree(f"{RESOURCES_BASE_PATH}/{rom.fs_resources_path}") except FileNotFoundError: - log.error(f"Couldn't find resources to delete for {rom.name}") + log.error( + f"Couldn't find resources to delete for {hl(str(rom.name), color=BLUE)}" + ) if id in delete_from_fs: - log.info(f"Deleting {rom.fs_name} from filesystem") + log.info(f"Deleting {hl(rom.fs_name)} from filesystem") try: fs_rom_handler.remove_from_fs(fs_path=rom.fs_path, fs_name=rom.fs_name) except FileNotFoundError as exc: - error = ( - f"Rom file {rom.fs_name} not found for platform {rom.platform_slug}" - ) + error = f"Rom file {hl(rom.fs_name)} not found for platform {hl(rom.platform_display_name, color=BLUE)}[{hl(rom.platform_slug)}]" log.error(error) raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=error @@ -885,7 +897,7 @@ async def get_romfile_content( detail="File not found", ) - log.info(f"User {current_username} is downloading {file_name}") + log.info(f"User {hl(current_username, color=BLUE)} is downloading {hl(file_name)}") # Serve the file directly in development mode for emulatorjs if DEV_MODE: diff --git a/backend/endpoints/saves.py b/backend/endpoints/saves.py index 19b2e7830..937f91c17 100644 --- a/backend/endpoints/saves.py +++ b/backend/endpoints/saves.py @@ -8,6 +8,8 @@ from handler.auth.constants import Scope from handler.database import db_rom_handler, db_save_handler, db_screenshot_handler from handler.filesystem import fs_asset_handler from handler.scan_handler import scan_save, scan_screenshot +from logger.formatter import BLUE +from logger.formatter import highlight as hl from logger.logger import log from utils.router import APIRouter @@ -32,7 +34,10 @@ async def add_save( log.info(f"Uploading save of {rom.name}") saves_path = fs_asset_handler.build_saves_file_path( - user=request.user, platform_fs_slug=rom.platform.fs_slug, emulator=emulator + user=request.user, + platform_fs_slug=rom.platform.fs_slug, + rom_id=rom_id, + emulator=emulator, ) if "saveFile" not in data: @@ -42,12 +47,26 @@ async def add_save( ) saveFile: UploadFile = data["saveFile"] # type: ignore + if not saveFile.filename: log.error("Save file has no filename") raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Save file has no filename" ) + rom = db_rom_handler.get_rom(rom_id) + if not rom: + raise RomNotFoundInDatabaseException(rom_id) + + log.info(f"Uploading save {hl(saveFile.filename)} for {hl(rom.name, color=BLUE)}") + + saves_path = fs_asset_handler.build_saves_file_path( + user=request.user, + platform_fs_slug=rom.platform.fs_slug, + rom_id=rom.id, + emulator=emulator, + ) + fs_asset_handler.write_file(file=saveFile, path=saves_path) # Scan or update save @@ -55,6 +74,7 @@ async def add_save( file_name=saveFile.filename, user=request.user, platform_fs_slug=rom.platform.fs_slug, + rom_id=rom_id, emulator=emulator, ) db_save = db_save_handler.get_save_by_filename( @@ -73,7 +93,7 @@ async def add_save( screenshotFile: UploadFile | None = data.get("screenshotFile", None) # type: ignore if screenshotFile and screenshotFile.filename: screenshots_path = fs_asset_handler.build_screenshots_file_path( - user=request.user, platform_fs_slug=rom.platform_slug + user=request.user, platform_fs_slug=rom.platform_slug, rom_id=rom.id ) fs_asset_handler.write_file(file=screenshotFile, path=screenshots_path) @@ -83,6 +103,7 @@ async def add_save( file_name=screenshotFile.filename, user=request.user, platform_fs_slug=rom.platform_slug, + rom_id=rom.id, ) db_screenshot = db_screenshot_handler.get_screenshot_by_filename( rom_id=rom.id, user_id=request.user.id, file_name=screenshotFile.filename @@ -95,9 +116,7 @@ async def add_save( else: scanned_screenshot.rom_id = rom.id scanned_screenshot.user_id = request.user.id - db_screenshot = db_screenshot_handler.add_screenshot( - screenshot=scanned_screenshot - ) + db_screenshot_handler.add_screenshot(screenshot=scanned_screenshot) # Set the last played time for the current user rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=request.user.id) @@ -155,6 +174,38 @@ async def update_save(request: Request, id: int) -> SaveSchema: db_save.id, {"file_size_bytes": saveFile.size} ) + screenshotFile: UploadFile | None = data.get("screenshotFile", None) # type: ignore + if screenshotFile and screenshotFile.filename: + screenshots_path = fs_asset_handler.build_screenshots_file_path( + user=request.user, + platform_fs_slug=db_save.rom.platform_slug, + rom_id=db_save.rom.id, + ) + + fs_asset_handler.write_file(file=screenshotFile, path=screenshots_path) + + # Scan or update screenshot + scanned_screenshot = scan_screenshot( + file_name=screenshotFile.filename, + user=request.user, + platform_fs_slug=db_save.rom.platform_slug, + rom_id=db_save.rom.id, + ) + db_screenshot = db_screenshot_handler.get_screenshot_by_filename( + rom_id=db_save.rom.id, + user_id=request.user.id, + file_name=screenshotFile.filename, + ) + if db_screenshot: + db_screenshot = db_screenshot_handler.update_screenshot( + db_screenshot.id, + {"file_size_bytes": scanned_screenshot.file_size_bytes}, + ) + else: + scanned_screenshot.rom_id = db_save.rom.id + scanned_screenshot.user_id = request.user.id + db_screenshot_handler.add_screenshot(screenshot=scanned_screenshot) + # Set the last played time for the current user rom_user = db_rom_handler.get_rom_user(db_save.rom_id, request.user.id) if not rom_user: @@ -186,13 +237,15 @@ async def delete_saves(request: Request) -> list[int]: db_save_handler.delete_save(save_id) - log.info(f"Deleting {save.file_name} from filesystem") + log.info( + f"Deleting save {hl(save.file_name)} [{save.rom.platform_slug}] from filesystem" + ) try: fs_asset_handler.remove_file( file_name=save.file_name, file_path=save.file_path ) except FileNotFoundError: - error = f"Save file {save.file_name} not found for platform {save.rom.platform_slug}" + error = f"Save file {hl(save.file_name)} not found for platform {hl(save.rom.platform_display_name, color=BLUE)}[{hl(save.rom.platform_slug)}]" log.error(error) if save.screenshot: @@ -204,7 +257,7 @@ async def delete_saves(request: Request) -> list[int]: file_path=save.screenshot.file_path, ) except FileNotFoundError: - error = f"Screenshot file {save.screenshot.file_name} not found for save {save.file_name}" + error = f"Screenshot file {hl(save.screenshot.file_name)} not found for save {hl(save.file_name)}[{hl(save.rom.platform_slug)}]" log.error(error) return save_ids diff --git a/backend/endpoints/screenshots.py b/backend/endpoints/screenshots.py index d35fa4a4e..c5a4f50c8 100644 --- a/backend/endpoints/screenshots.py +++ b/backend/endpoints/screenshots.py @@ -6,6 +6,8 @@ from handler.auth.constants import Scope from handler.database import db_rom_handler, db_screenshot_handler from handler.filesystem import fs_asset_handler from handler.scan_handler import scan_screenshot +from logger.formatter import BLUE +from logger.formatter import highlight as hl from logger.logger import log from utils.router import APIRouter @@ -27,10 +29,10 @@ async def add_screenshot( raise RomNotFoundInDatabaseException(rom_id) current_user = request.user - log.info(f"Uploading screenshots to {rom.name}") + log.info(f"Uploading screenshots to {hl(rom.name, color=BLUE)}") screenshots_path = fs_asset_handler.build_screenshots_file_path( - user=request.user, platform_fs_slug=rom.platform_slug + user=request.user, platform_fs_slug=rom.platform_slug, rom_id=rom.id ) if "screenshotFile" not in data: @@ -61,6 +63,7 @@ async def add_screenshot( file_name=screenshotFile.filename, user=request.user, platform_fs_slug=rom.platform_slug, + rom_id=rom.id, ) db_screenshot = db_screenshot_handler.get_screenshot_by_filename( rom_id=rom.id, user_id=current_user.id, file_name=screenshotFile.filename diff --git a/backend/endpoints/search.py b/backend/endpoints/search.py index 6dc15bfc0..c2fcf7651 100644 --- a/backend/endpoints/search.py +++ b/backend/endpoints/search.py @@ -18,6 +18,8 @@ from handler.metadata.moby_handler import MOBY_API_ENABLED, MobyGamesRom from handler.metadata.sgdb_handler import STEAMGRIDDB_API_ENABLED from handler.metadata.ss_handler import SS_API_ENABLED, SSRom from handler.scan_handler import _get_main_platform_igdb_id +from logger.formatter import BLUE, CYAN +from logger.formatter import highlight as hl from logger.logger import log from utils.router import APIRouter @@ -68,8 +70,12 @@ 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.fs_name}")) + log.info(f"Searching by {hl(search_by.lower(), color=CYAN)}:") + log.info( + emoji.emojize( + f":video_game: {hl(rom.platform_display_name, color=BLUE)} [{rom.platform_fs_slug}]: {hl(search_term)}[{rom.fs_name}]" + ) + ) igdb_matched_roms: list[IGDBRom] = [] moby_matched_roms: list[MobyGamesRom] = [] diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index d87525d84..ac71151cf 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -28,12 +28,13 @@ from handler.redis_handler import high_prio_queue, redis_client from handler.scan_handler import ( MetadataSource, ScanType, + fetch_ra_info, scan_firmware, scan_platform, scan_rom, ) from handler.socket_handler import socket_handler -from logger.formatter import LIGHTYELLOW, RED +from logger.formatter import BLUE, LIGHTYELLOW, RED from logger.formatter import highlight as hl from logger.logger import log from models.platform import Platform @@ -153,7 +154,12 @@ async def scan_platforms( roms_ids = [] if not metadata_sources: - metadata_sources = [MetadataSource.IGDB, MetadataSource.MOBY, MetadataSource.SS] + metadata_sources = [ + MetadataSource.IGDB, + MetadataSource.MOBY, + MetadataSource.SS, + MetadataSource.RA, + ] sm = _get_socket_manager() @@ -181,12 +187,14 @@ async def scan_platforms( if len(platform_list) == 0: log.warning( emoji.emojize( - f"{hl(':warning:', color=LIGHTYELLOW)} No platforms found, verify that the folder structure is right and the volume is mounted correctly. \ + f"{hl(':warning:', color=LIGHTYELLOW)} No platforms found, verify that the folder structure is right and the volume is mounted correctly. \ Check https://github.com/rommapp/romm?tab=readme-ov-file#folder-structure for more details." ) ) else: - log.info(f"Found {len(platform_list)} platforms in the file system") + log.info( + f"Found {hl(str(len(platform_list)))} platforms in the file system" + ) for platform_slug in platform_list: scan_stats += await _identify_platform( @@ -204,11 +212,11 @@ async def scan_platforms( if len(fs_platforms) > 0: purged_platforms = db_platform_handler.purge_platforms(fs_platforms) if len(purged_platforms) > 0: - log.info("Purging platforms not found in the filesystem:") + log.warning("Purging platforms not found in the filesystem:") for p in purged_platforms: - log.info(f" - {p.slug}") + log.warning(f" - {p.slug}") - log.info(emoji.emojize(":check_mark: Scan completed ")) + log.info(emoji.emojize(":check_mark: Scan completed ")) await sm.emit("scan:done", scan_stats.__dict__) except ScanStoppedException: await stop_scan() @@ -273,11 +281,11 @@ async def _identify_platform( if len(fs_firmware) == 0: log.warning( emoji.emojize( - f" {hl(':warning:', color=LIGHTYELLOW)} No firmware found, skipping firmware scan for this platform" + f"{hl(':warning:', color=LIGHTYELLOW)} No firmware found for {hl(platform.custom_name or platform.name, color=BLUE)}[{hl(platform.fs_slug)}]" ) ) else: - log.info(f" {len(fs_firmware)} firmware files found") + log.info(f"{hl(str(len(fs_firmware)))} firmware files found") for fs_fw in fs_firmware: scan_stats += await _identify_firmware( @@ -295,11 +303,11 @@ async def _identify_platform( if len(fs_roms) == 0: log.warning( emoji.emojize( - f" {hl(':warning:', color=LIGHTYELLOW)} No roms found, verify that the folder structure is correct" + f"{hl(':warning:', color=LIGHTYELLOW)} No roms found, verify that the folder structure is correct" ) ) else: - log.info(f" {len(fs_roms)} roms found in the file system") + log.info(f"{hl(str(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_fs_name( @@ -326,9 +334,9 @@ async def _identify_platform( platform.id, [rom["fs_name"] for rom in fs_roms] ) if len(purged_roms) > 0: - log.info("Purging roms not found in the filesystem:") + log.warning("Purging roms not found in the filesystem:") for r in purged_roms: - log.info(f" - {r.fs_name}") + log.warning(f" - {r.fs_name}") # Same protection for firmware if len(fs_firmware) > 0: @@ -336,9 +344,9 @@ async def _identify_platform( platform.id, [fw for fw in fs_firmware] ) if len(purged_firmware) > 0: - log.info("Purging firmware not found in the filesystem:") + log.warning("Purging firmware not found in the filesystem:") for f in purged_firmware: - log.info(f" - {f}") + log.warning(f" - {f}") return scan_stats @@ -368,22 +376,24 @@ async def _identify_firmware( return scan_stats -def _set_rom_hashes(rom_id: int): +async def _set_rom_hashes(rom_id: int) -> str: """Set the hashes for the given rom Args: rom_id (int): Rom id + Returns: + ra_hash (str): Calculated retroachievements hash """ rom = db_rom_handler.get_rom(rom_id) if not rom: - return + return "" try: - rom_hash, rom_file_hashes = fs_rom_handler.get_rom_hashes(rom) + rom_hash, rom_file_hashes = await fs_rom_handler.get_rom_hashes(rom) except zlib.error as e: # Set empty hashes if calculating them fails for corrupted files log.error( - f"Hashes of {rom.fs_name} couldn't be calculated: {hl(str(e), color=RED)}" + f"Hashes of {hl(rom.fs_name)} couldn't be calculated: {hl(str(e), color=RED)}" ) db_rom_handler.update_rom( rom_id, @@ -391,8 +401,10 @@ def _set_rom_hashes(rom_id: int): "crc_hash": "", "md5_hash": "", "sha1_hash": "", + "ra_hash": "", }, ) + return "" else: db_rom_handler.update_rom( rom_id, @@ -400,6 +412,7 @@ def _set_rom_hashes(rom_id: int): "crc_hash": rom_hash["crc_hash"], "md5_hash": rom_hash["md5_hash"], "sha1_hash": rom_hash["sha1_hash"], + "ra_hash": rom_hash["ra_hash"], }, ) for file_hash in rom_file_hashes: @@ -409,8 +422,10 @@ def _set_rom_hashes(rom_id: int): "crc_hash": file_hash["crc_hash"], "md5_hash": file_hash["md5_hash"], "sha1_hash": file_hash["sha1_hash"], + "ra_hash": rom_hash["ra_hash"], }, ) + return rom_hash["ra_hash"] async def _identify_rom( @@ -446,7 +461,9 @@ async def _identify_rom( scan_stats.scanned_roms += 1 scan_stats.added_roms += 1 if not rom else 0 - scan_stats.metadata_roms += 1 if scanned_rom.igdb_id or scanned_rom.moby_id else 0 + scan_stats.metadata_roms += ( + 1 if scanned_rom.igdb_id or scanned_rom.moby_id or scanned_rom.ss_id else 0 + ) _added_rom = db_rom_handler.add_rom(scanned_rom) @@ -469,17 +486,42 @@ async def _identify_rom( db_rom_handler.add_rom_file(new_rom_file) # Calculating hashes is expensive, so we only do it if necessary - if not rom or scan_type == ScanType.COMPLETE or scan_type == ScanType.HASHES: + if ( + not rom + or not rom.ra_id + or scan_type == ScanType.COMPLETE + or scan_type == ScanType.HASHES + or MetadataSource.RA in metadata_sources + ): # Skip hashing games for platforms that don't have a hash database if platform.slug not in NON_HASHABLE_PLATFORMS: - _set_rom_hashes(_added_rom.id) - - # Uncomment this to run scan in a background process - # low_prio_queue.enqueue( - # _set_rom_hashes, - # _added_rom.id, - # job_timeout=60 * 15, # Timeout (15 minutes) - # ) + ra_hash = await _set_rom_hashes(_added_rom.id) + if ra_hash: + ra_handler_rom = await fetch_ra_info( + platform=platform, + rom_id=_added_rom.id, + hash=ra_hash, + ) + _added_rom.ra_id = ra_handler_rom.get("ra_id", "") + _added_rom.ra_metadata = ra_handler_rom.get("ra_metadata", {}) + for a in _added_rom.ra_metadata.get("achievements", {}): + # Store both normal and locked version + badge_url_lock = a.get("badge_url_lock", None) + badge_path_lock = a.get("badge_path_lock", None) + if badge_url_lock and badge_path_lock: + await fs_resource_handler.store_badge( + badge_url_lock, badge_path_lock + ) + badge_url = a.get("badge_url", None) + badge_path = a.get("badge_path", None) + if badge_url and badge_path: + await fs_resource_handler.store_badge(badge_url, badge_path) + # Uncomment this to run scan in a background process + # 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: @@ -539,7 +581,7 @@ async def scan_handler(_sid: str, options: dict): options (dict): Socket options """ - log.info(emoji.emojize(":magnifying_glass_tilted_right: Scanning ")) + log.info(emoji.emojize(":magnifying_glass_tilted_right: Scanning")) platform_ids = options.get("platforms", []) scan_type = ScanType[options.get("type", "quick").upper()] diff --git a/backend/endpoints/states.py b/backend/endpoints/states.py index 352018ff3..9c04f3164 100644 --- a/backend/endpoints/states.py +++ b/backend/endpoints/states.py @@ -8,6 +8,8 @@ from handler.auth.constants import Scope from handler.database import db_rom_handler, db_screenshot_handler, db_state_handler from handler.filesystem import fs_asset_handler from handler.scan_handler import scan_screenshot, scan_state +from logger.formatter import BLUE +from logger.formatter import highlight as hl from logger.logger import log from utils.router import APIRouter @@ -32,7 +34,10 @@ async def add_state( log.info(f"Uploading state of {rom.name}") states_path = fs_asset_handler.build_states_file_path( - user=request.user, platform_fs_slug=rom.platform.fs_slug, emulator=emulator + user=request.user, + platform_fs_slug=rom.platform.fs_slug, + rom_id=rom_id, + emulator=emulator, ) if "stateFile" not in data: @@ -42,12 +47,26 @@ async def add_state( ) stateFile: UploadFile = data["stateFile"] # type: ignore + if not stateFile.filename: log.error("State file has no filename") raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="State file has no filename" ) + rom = db_rom_handler.get_rom(rom_id) + if not rom: + raise RomNotFoundInDatabaseException(rom_id) + + log.info(f"Uploading state {hl(stateFile.filename)} for {hl(rom.name, color=BLUE)}") + + states_path = fs_asset_handler.build_states_file_path( + user=request.user, + platform_fs_slug=rom.platform.fs_slug, + rom_id=rom.id, + emulator=emulator, + ) + fs_asset_handler.write_file(file=stateFile, path=states_path) # Scan or update state @@ -55,6 +74,7 @@ async def add_state( file_name=stateFile.filename, user=request.user, platform_fs_slug=rom.platform.fs_slug, + rom_id=rom_id, emulator=emulator, ) db_state = db_state_handler.get_state_by_filename( @@ -73,7 +93,7 @@ async def add_state( screenshotFile: UploadFile | None = data.get("screenshotFile", None) # type: ignore if screenshotFile and screenshotFile.filename: screenshots_path = fs_asset_handler.build_screenshots_file_path( - user=request.user, platform_fs_slug=rom.platform_slug + user=request.user, platform_fs_slug=rom.platform_slug, rom_id=rom.id ) fs_asset_handler.write_file(file=screenshotFile, path=screenshots_path) @@ -83,6 +103,7 @@ async def add_state( file_name=screenshotFile.filename, user=request.user, platform_fs_slug=rom.platform_slug, + rom_id=rom.id, ) db_screenshot = db_screenshot_handler.get_screenshot_by_filename( rom_id=rom.id, user_id=request.user.id, file_name=screenshotFile.filename @@ -155,6 +176,40 @@ async def update_state(request: Request, id: int) -> StateSchema: db_state.id, {"file_size_bytes": stateFile.size} ) + screenshotFile: UploadFile | None = data.get("screenshotFile", None) # type: ignore + if screenshotFile and screenshotFile.filename: + screenshots_path = fs_asset_handler.build_screenshots_file_path( + user=request.user, + platform_fs_slug=db_state.rom.platform_slug, + rom_id=db_state.rom.id, + ) + + fs_asset_handler.write_file(file=screenshotFile, path=screenshots_path) + + # Scan or update screenshot + scanned_screenshot = scan_screenshot( + file_name=screenshotFile.filename, + user=request.user, + platform_fs_slug=db_state.rom.platform_slug, + rom_id=db_state.rom.id, + ) + db_screenshot = db_screenshot_handler.get_screenshot_by_filename( + rom_id=db_state.rom.id, + user_id=request.user.id, + file_name=screenshotFile.filename, + ) + if db_screenshot: + db_screenshot = db_screenshot_handler.update_screenshot( + db_screenshot.id, + {"file_size_bytes": scanned_screenshot.file_size_bytes}, + ) + else: + scanned_screenshot.rom_id = db_state.rom.id + scanned_screenshot.user_id = request.user.id + db_screenshot = db_screenshot_handler.add_screenshot( + screenshot=scanned_screenshot + ) + # Set the last played time for the current user rom_user = db_rom_handler.get_rom_user(db_state.rom_id, request.user.id) if not rom_user: @@ -185,14 +240,16 @@ async def delete_states(request: Request) -> list[int]: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error) db_state_handler.delete_state(state_id) - log.info(f"Deleting {state.file_name} from filesystem") + log.info( + f"Deleting state {hl(state.file_name)} [{state.rom.platform_slug}] from filesystem" + ) try: fs_asset_handler.remove_file( file_name=state.file_name, file_path=state.file_path ) except FileNotFoundError: - error = f"State file {state.file_name} not found for platform {state.rom.platform_slug}" + error = f"State file {hl(state.file_name)} not found for platform {hl(state.rom.platform_display_name, color=BLUE)}[{hl(state.rom.platform_slug)}]" log.error(error) if state.screenshot: @@ -204,7 +261,7 @@ async def delete_states(request: Request) -> list[int]: file_path=state.screenshot.file_path, ) except FileNotFoundError: - error = f"Screenshot file {state.screenshot.file_name} not found for state {state.file_name}" + error = f"Screenshot file {hl(state.screenshot.file_name)} not found for state {hl(state.file_name)}[{hl(state.rom.platform_slug)}]" log.error(error) return state_ids diff --git a/backend/endpoints/stats.py b/backend/endpoints/stats.py index 7fbd358d7..d7a3dc8e9 100644 --- a/backend/endpoints/stats.py +++ b/backend/endpoints/stats.py @@ -22,5 +22,5 @@ def stats() -> StatsReturn: "SAVES": db_stats_handler.get_saves_count(), "STATES": db_stats_handler.get_states_count(), "SCREENSHOTS": db_stats_handler.get_screenshots_count(), - "FILESIZE": db_stats_handler.get_total_filesize(), + "TOTAL_FILESIZE_BYTES": db_stats_handler.get_total_filesize(), } diff --git a/backend/endpoints/user.py b/backend/endpoints/user.py index 560583cc1..f0c7902a5 100644 --- a/backend/endpoints/user.py +++ b/backend/endpoints/user.py @@ -7,12 +7,13 @@ from config import ASSETS_BASE_PATH from decorators.auth import protected_route from endpoints.forms.identity import UserForm from endpoints.responses import MessageResponse -from endpoints.responses.identity import UserSchema -from fastapi import Depends, HTTPException, Request, status +from endpoints.responses.identity import InviteLinkSchema, UserSchema +from fastapi import Body, Depends, HTTPException, Request, status from handler.auth import auth_handler from handler.auth.constants import Scope from handler.database import db_user_handler from handler.filesystem import fs_asset_handler +from handler.metadata import meta_ra_handler from logger.logger import log from models.user import Role, User from utils.router import APIRouter @@ -81,6 +82,95 @@ def add_user( return UserSchema.model_validate(db_user_handler.add_user(user)) +@protected_route( + router.post, + "/invite-link", + [], + status_code=status.HTTP_201_CREATED, +) +def create_invite_link(request: Request, role: str) -> InviteLinkSchema: + """Create an invite link for a user. + + Args: + request (Request): FastAPI Request object + role (str): The role of the user + + Returns: + InviteLinkSchema: Invite link + """ + + if ( + Scope.USERS_WRITE not in request.auth.scopes + and len(db_user_handler.get_admin_users()) > 0 + ): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Forbidden", + ) + + if role not in [r.value for r in Role]: + msg = f"Role {role} is not valid" + log.error(msg) + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=msg, + ) + + token = auth_handler.generate_invite_link_token(request.user, role=role) + return InviteLinkSchema.model_validate({"token": token}) + + +@router.post("/register", status_code=status.HTTP_201_CREATED) +def create_user_from_invite( + username: str = Body(..., embed=True), + email: str = Body(..., embed=True), + password: str = Body(..., embed=True), + token: str = Body(..., embed=True), +) -> UserSchema: + """Create user endpoint with invite link + + Args: + username (str): User username + email (str): User email + password (str): User password + token (str): Invite link token + + Returns: + UserSchema: Newly created user + """ + + jti, role = auth_handler.verify_invite_link_token(token) + + if db_user_handler.get_user_by_username(username): + msg = f"Username {username} already exists" + log.error(msg) + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=msg, + ) + + if email and db_user_handler.get_user_by_email(email): + msg = f"User with email {email} already exists" + log.error(msg) + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=msg, + ) + + user = User( + username=username.lower(), + hashed_password=auth_handler.get_password_hash(password), + email=email.lower() or None, + role=Role[role.upper()], + ) + + created_user = db_user_handler.add_user(user) + + auth_handler.invalidate_invite_link_token(jti) + + return UserSchema.model_validate(created_user) + + @protected_route(router.get, "", [Scope.USERS_READ]) def get_users(request: Request) -> list[UserSchema]: """Get all users endpoint @@ -193,6 +283,9 @@ async def update_user( if form_data.enabled is not None and request.user.id != id: cleaned_data["enabled"] = form_data.enabled # type: ignore[assignment] + if form_data.ra_username: + cleaned_data["ra_username"] = form_data.ra_username # type: ignore[assignment] + if form_data.avatar is not None: user_avatar_path = fs_asset_handler.build_avatar_path(user=db_user) # Extract the file extension from the uploaded file @@ -261,3 +354,17 @@ def delete_user(request: Request, id: int) -> MessageResponse: db_user_handler.delete_user(id) return {"msg": "User successfully deleted"} + + +@protected_route(router.post, "/{id}/ra/refresh", [Scope.ME_WRITE]) +async def refresh_retro_achievements(request: Request, id: int) -> MessageResponse: + user = db_user_handler.get_user(id) + user_progression = await meta_ra_handler.get_user_progression(user.ra_username) + db_user_handler.update_user( + id, + { + "ra_progression": user_progression, + }, + ) + + return {"msg": "RetroAchievements successfully refreshed"} diff --git a/backend/exceptions/endpoint_exceptions.py b/backend/exceptions/endpoint_exceptions.py index bd5d26113..ee8f75178 100644 --- a/backend/exceptions/endpoint_exceptions.py +++ b/backend/exceptions/endpoint_exceptions.py @@ -59,6 +59,14 @@ class CollectionAlreadyExistsException(Exception): return self.message +class RomNotFoundInRetroAchievementsException(Exception): + def __init__(self, id): + self.message = f"Rom with id '{id}' does not exist on RetroAchievements" + super().__init__(self.message) + log.critical(self.message) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=self.message) + + class SGDBInvalidAPIKeyException(Exception): def __init__(self): self.message = "Invalid SGDB API key" diff --git a/backend/exceptions/fs_exceptions.py b/backend/exceptions/fs_exceptions.py index 942c596d2..00b90b0b8 100644 --- a/backend/exceptions/fs_exceptions.py +++ b/backend/exceptions/fs_exceptions.py @@ -1,3 +1,6 @@ +from logger.formatter import BLUE +from logger.formatter import highlight as hl + folder_struct_msg = "Check RomM folder structure here: https://github.com/rommapp/romm?tab=readme-ov-file#folder-structure" @@ -30,7 +33,7 @@ class PlatformAlreadyExistsException(Exception): class RomsNotFoundException(Exception): def __init__(self, platform: str): - self.message = f"Roms not found for platform {platform}. {folder_struct_msg}" + self.message = f"Roms not found for platform {hl(platform, color=BLUE)}. {folder_struct_msg}" super().__init__(self.message) def __repr__(self): @@ -39,7 +42,7 @@ class RomsNotFoundException(Exception): class RomAlreadyExistsException(Exception): def __init__(self, rom_name: str): - self.message = f"Can't rename: {rom_name} already exists" + self.message = f"Can't rename: {hl(rom_name)} already exists" super().__init__(self.message) def __repr__(self): @@ -48,9 +51,7 @@ class RomAlreadyExistsException(Exception): class FirmwareNotFoundException(Exception): def __init__(self, platform: str): - self.message = ( - f"Firmware not found for platform {platform}. {folder_struct_msg}" - ) + self.message = f"Firmware not found for platform {hl(platform, color=BLUE)}. {folder_struct_msg}" super().__init__(self.message) def __repr__(self): @@ -59,7 +60,7 @@ class FirmwareNotFoundException(Exception): class FirmwareAlreadyExistsException(Exception): def __init__(self, firmware_name: str): - self.message = f"Can't rename: {firmware_name} already exists" + self.message = f"Can't rename: {hl(firmware_name)} already exists" super().__init__(self.message) def __repr__(self): diff --git a/backend/handler/auth/base_handler.py b/backend/handler/auth/base_handler.py index a7516cceb..7bab00990 100644 --- a/backend/handler/auth/base_handler.py +++ b/backend/handler/auth/base_handler.py @@ -1,15 +1,18 @@ import uuid from datetime import datetime, timedelta, timezone -from typing import Any +from typing import Any, Tuple -from config import OIDC_ENABLED, ROMM_AUTH_SECRET_KEY +from config import OIDC_ENABLED, ROMM_AUTH_SECRET_KEY, ROMM_BASE_URL from decorators.auth import oauth from exceptions.auth_exceptions import OAuthCredentialsException, UserDisabledException from fastapi import HTTPException, status -from handler.auth.constants import ALGORITHM, DEFAULT_OAUTH_TOKEN_EXPIRY +from handler.auth.constants import ALGORITHM, DEFAULT_OAUTH_TOKEN_EXPIRY, TokenPurpose +from handler.redis_handler import redis_client from joserfc import jwt from joserfc.errors import BadSignatureError from joserfc.jwk import OctKey +from logger.formatter import CYAN +from logger.formatter import highlight as hl from logger.logger import log from passlib.context import CryptContext from starlette.requests import HTTPConnection @@ -18,6 +21,8 @@ from starlette.requests import HTTPConnection class AuthHandler: def __init__(self) -> None: self.pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + self.reset_passwd_token_expires_in_minutes = 10 + self.invite_link_token_expires_in_minutes = 10 def verify_password(self, plain_password, hashed_password): return self.pwd_context.verify(plain_password, hashed_password) @@ -54,13 +59,173 @@ class AuthHandler: conn.session.clear() log.error( "User '%s' %s", - username, + hl(username, color=CYAN), "not found" if user is None else "not enabled", ) return None return user + def generate_password_reset_token(self, user: Any) -> None: + now = datetime.now(timezone.utc) + + jti = str(uuid.uuid4()) + + to_encode = { + "sub": user.username, + "email": user.email, + "type": TokenPurpose.RESET, + "iat": int(now.timestamp()), + "exp": int( + ( + now + timedelta(minutes=self.reset_passwd_token_expires_in_minutes) + ).timestamp() + ), + "jti": jti, + } + token = jwt.encode( + {"alg": ALGORITHM}, to_encode, OctKey.import_key(ROMM_AUTH_SECRET_KEY) + ) + log.info( + f"Reset password link requested for {hl(user.username, color=CYAN)}. Reset link: {hl(f'{ROMM_BASE_URL}/reset-password?token={token}')}" + ) + redis_client.setex( + f"reset-jti:{jti}", self.reset_passwd_token_expires_in_minutes * 60, "valid" + ) + + def verify_password_reset_token(self, token: str) -> Any: + """Verify the password reset token. + + Args: + token (str): The token to verify. + + Raises: + HTTPException: If the token is invalid or expired. + HTTPException: If the token is missing or malformed. + HTTPException: If the user is not found. + HTTPException: If the token is not for password reset. + """ + from handler.database import db_user_handler + + try: + payload = jwt.decode(token, ROMM_AUTH_SECRET_KEY, algorithms=[ALGORITHM]) + except (BadSignatureError, ValueError) as exc: + raise HTTPException(status_code=400, detail="Invalid token") from exc + + if payload.claims.get("type") != TokenPurpose.RESET: + raise HTTPException(status_code=400, detail="Invalid token purpose") + + username = payload.claims.get("sub") + jti = payload.claims.get("jti") + if not username or not jti: + raise HTTPException(status_code=400, detail="Invalid token payload") + + # Check JTI in Redis + redis_jti_key = f"reset-jti:{jti}" + if not redis_client.exists(redis_jti_key): + raise HTTPException( + status_code=400, detail="This token has already been used or is invalid" + ) + + # Delete it to enforce one-time use + redis_client.delete(redis_jti_key) + + user = db_user_handler.get_user_by_username(username) + if not user: + raise HTTPException(status_code=404, detail="User not found") + + now = datetime.now(timezone.utc).timestamp() + if now > payload.claims.get("exp"): + raise HTTPException(status_code=400, detail="Token has expired") + + return user + + def set_user_new_password(self, user: Any, new_password: str) -> None: + """ + Set the new password for the user. + Args: + user (Any): The user object. + new_password (str): The new password to set. + """ + from handler.database import db_user_handler + + db_user_handler.update_user( + user.id, {"hashed_password": self.get_password_hash(new_password)} + ) + + def generate_invite_link_token(self, user: Any, role: str) -> str: + """ + Generate an invite link token for the user. + Args: + user (Any): The user object. + role (str): The role of the user. + Returns: + str: The generated invite link token. + """ + now = datetime.now(timezone.utc) + + jti = str(uuid.uuid4()) + + to_encode = { + "sub": user.username, + "type": TokenPurpose.INVITE, + "role": role.upper(), + "iat": int(now.timestamp()), + "exp": int( + ( + now + timedelta(minutes=self.invite_link_token_expires_in_minutes) + ).timestamp() + ), + "jti": jti, + } + token = jwt.encode( + {"alg": ALGORITHM}, to_encode, OctKey.import_key(ROMM_AUTH_SECRET_KEY) + ) + invite_link = f"{ROMM_BASE_URL}/register?token={token}" + log.info( + f"Invite link created by {hl(user.username, color=CYAN)}: {hl(invite_link)}" + ) + redis_client.setex( + f"invite-jti:{jti}", self.invite_link_token_expires_in_minutes * 60, "valid" + ) + return token + + def verify_invite_link_token(self, token: str) -> Tuple[str, str]: + """ + Verify the invite link token. + Args: + token (str): The token to verify. + Returns: + str: The JTI (JWT ID) of the token. + """ + try: + payload = jwt.decode(token, OctKey.import_key(ROMM_AUTH_SECRET_KEY)) + except (BadSignatureError, ValueError) as exc: + raise HTTPException(status_code=400, detail="Invalid token") from exc + + if payload.claims.get("type") != TokenPurpose.INVITE: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Invalid token type.", + ) + + jti = payload.claims.get("jti") + role = payload.claims.get("role", "USER").upper() + if not jti or redis_client.get(f"invite-jti:{jti}") != b"valid": + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Invite token has already been used or is invalid.", + ) + return jti, role + + def invalidate_invite_link_token(self, jti: str) -> None: + """ + Invalidate the invite link token. + Args: + jti (str): The JTI (JWT ID) of the token to invalidate. + """ + redis_client.delete(f"invite-jti:{jti}") + class OAuthHandler: def __init__(self) -> None: @@ -148,18 +313,21 @@ class OpenIDHandler: user = db_user_handler.get_user_by_email(email) if user is None: - log.info("User with email '%s' not found, creating new user", email) - user = User( + log.info( + "User with email '%s' not found, creating new user", + hl(email, color=CYAN), + ) + new_user = User( username=preferred_username, hashed_password=str(uuid.uuid4()), email=email, enabled=True, role=Role.VIEWER, ) - db_user_handler.add_user(user) + user = db_user_handler.add_user(new_user) if not user.enabled: raise UserDisabledException - log.info("User successfully authenticated: %s", email) + log.info("User successfully authenticated: %s", hl(email, color=CYAN)) return user, userinfo diff --git a/backend/handler/auth/constants.py b/backend/handler/auth/constants.py index 7b4c8e9b9..a22681017 100644 --- a/backend/handler/auth/constants.py +++ b/backend/handler/auth/constants.py @@ -59,3 +59,8 @@ READ_SCOPES: Final = list(READ_SCOPES_MAP.keys()) WRITE_SCOPES: Final = READ_SCOPES + list(WRITE_SCOPES_MAP.keys()) EDIT_SCOPES: Final = WRITE_SCOPES + list(EDIT_SCOPES_MAP.keys()) FULL_SCOPES: Final = EDIT_SCOPES + list(FULL_SCOPES_MAP.keys()) + + +class TokenPurpose(enum.StrEnum): + INVITE = "invite" + RESET = "reset" diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index e8473ec6b..5881d09b5 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -5,6 +5,7 @@ from typing import List, Sequence, Tuple from config import ROMM_DB_DRIVER from decorators.database import begin_session from models.collection import Collection, VirtualCollection +from models.platform import Platform from models.rom import Rom, RomFile, RomMetadata, RomUser from sqlalchemy import ( Integer, @@ -26,6 +27,80 @@ from sqlalchemy.orm import InstrumentedAttribute, Query, Session, selectinload from .base_handler import DBBaseHandler +EJS_SUPPORTED_PLATFORMS = [ + "3do", + "amiga", + "amiga-cd32", + "arcade", + "neogeoaes", + "neogeomvs", + "atari2600", + "atari-2600-plus", + "atari5200", + "atari7800", + "c-plus-4", + "c64", + "cpet", + "commodore-64c", + "c128", + "commmodore-128", + "colecovision", + "jaguar", + "lynx", + "atari-lynx-mkii", + "neo-geo-pocket", + "neo-geo-pocket-color", + "nes", + "famicom", + "fds", + "game-televisison", + "new-style-nes", + "n64", + "ique-player", + "nds", + "nintendo-ds-lite", + "nintendo-dsi", + "nintendo-dsi-xl", + "gb", + "game-boy-pocket", + "game-boy-light", + "gba", + "game-boy-adavance-sp", + "game-boy-micro", + "gbc", + "pc-fx", + "ps", + "psp", + "segacd", + "sega32", + "gamegear", + "sms", + "sega-mark-iii", + "sega-game-box-9", + "sega-master-system-ii", + "master-system-super-compact", + "master-system-girl", + "genesis-slash-megadrive", + "sega-mega-drive-2-slash-genesis", + "sega-mega-jet", + "mega-pc", + "tera-drive", + "sega-nomad", + "saturn", + "snes", + "sfam", + "super-nintendo-original-european-version", + "super-famicom-shvc-001", + "super-famicom-jr-model-shvc-101", + "new-style-super-nes-model-sns-101", + "turbografx16--1", + "vic-20", + "virtualboy", + "wonderswan", + "swancrystal", + "wonderswan-color", +] + def with_details(func): @functools.wraps(func) @@ -144,6 +219,11 @@ class DBRomsHandler(DBBaseHandler): def filter_by_duplicates_only(self, query: Query): return query.filter(Rom.sibling_roms.any()) + def filter_by_playables_only(self, query: Query): + return query.join(Rom.platform).filter( + Platform.slug.in_(EJS_SUPPORTED_PLATFORMS) + ) + def filter_by_genre(self, query: Query, selected_genre: str): if ROMM_DB_DRIVER == "postgresql": return query.filter( @@ -215,8 +295,6 @@ class DBRomsHandler(DBBaseHandler): ) def filter_by_status(self, query: Query, selected_status: str): - query = query.join(RomUser) - status_filter = RomUser.status == selected_status if selected_status == "now_playing": status_filter = RomUser.now_playing.is_(True) @@ -270,6 +348,7 @@ class DBRomsHandler(DBBaseHandler): matched_only: bool = False, favourites_only: bool = False, duplicates_only: bool = False, + playables_only: bool = False, group_by_meta_id: bool = False, selected_genre: str | None = None, selected_franchise: str | None = None, @@ -308,6 +387,9 @@ class DBRomsHandler(DBBaseHandler): if duplicates_only: query = self.filter_by_duplicates_only(query) + if playables_only: + query = self.filter_by_playables_only(query) + if group_by_meta_id: def build_func(provider: str, column: InstrumentedAttribute): @@ -383,18 +465,24 @@ class DBRomsHandler(DBBaseHandler): if selected_age_rating: query = self.filter_by_age_rating(query, selected_age_rating) - if selected_status: - query = self.filter_by_status(query, selected_status) - if selected_region: query = self.filter_by_region(query, selected_region) if selected_language: query = self.filter_by_language(query, selected_language) + # The RomUser table is already joined if user_id is set + if selected_status and user_id: + query = self.filter_by_status(query, selected_status) + elif user_id: + query = query.filter( + or_(RomUser.hidden.is_(False), RomUser.hidden.is_(None)) + ) + return query @with_simple + @begin_session def get_roms_query( self, *, @@ -402,6 +490,7 @@ class DBRomsHandler(DBBaseHandler): order_dir: str = "asc", user_id: int | None = None, query: Query = None, + session: Session = None, ) -> Query[Rom]: if user_id: query = query.outerjoin( @@ -421,6 +510,19 @@ class DBRomsHandler(DBBaseHandler): else: order_attr = Rom.name + # Handle computed properties + if order_by == "fs_size_bytes": + subquery = ( + session.query( + RomFile.rom_id, + func.sum(RomFile.file_size_bytes).label("total_size"), + ) + .group_by(RomFile.rom_id) + .subquery() + ) + query = query.outerjoin(subquery, Rom.id == subquery.c.rom_id) + order_attr = func.coalesce(subquery.c.total_size, 0) + # Ignore case when the order attribute is a number if isinstance(order_attr.type, (String, Text)): # Remove any leading articles diff --git a/backend/handler/filesystem/assets_handler.py b/backend/handler/filesystem/assets_handler.py index 5de48cd12..30cdbbba2 100644 --- a/backend/handler/filesystem/assets_handler.py +++ b/backend/handler/filesystem/assets_handler.py @@ -26,7 +26,6 @@ class FSAssetsHandler(FSHandler): 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) with open(file_location, "wb") as f: @@ -43,25 +42,49 @@ class FSAssetsHandler(FSHandler): return os.path.join(self.user_folder_path(user), "profile") def _build_asset_file_path( - self, user: User, folder: str, platform_fs_slug, emulator: str | None = None + self, + user: User, + folder: str, + platform_fs_slug: str, + rom_id: int, + emulator: str | None = None, ): user_folder_path = self.user_folder_path(user) + assets_path = os.path.join( + user_folder_path, folder, platform_fs_slug, str(rom_id) + ) if emulator: - return os.path.join(user_folder_path, folder, platform_fs_slug, emulator) - return os.path.join(user_folder_path, folder, platform_fs_slug) + assets_path = os.path.join(assets_path, emulator) + return assets_path - # /users/557365723a31/saves/n64/mupen64plus + # /users/557365723a31/saves/n64/{rom.id}/mupen64plus/ def build_saves_file_path( - self, user: User, platform_fs_slug: str, emulator: str | None = None + self, + user: User, + platform_fs_slug: str, + rom_id: int, + emulator: str | None = None, ): - return self._build_asset_file_path(user, "saves", platform_fs_slug, emulator) + return self._build_asset_file_path( + user, "saves", platform_fs_slug, rom_id, emulator + ) - # /users/557365723a31/states/n64/mupen64plus + # /users/557365723a31/states/n64/{rom.id}/mupen64plus def build_states_file_path( - self, user: User, platform_fs_slug: str, emulator: str | None = None + self, + user: User, + platform_fs_slug: str, + rom_id: int, + emulator: str | None = None, ): - return self._build_asset_file_path(user, "states", platform_fs_slug, emulator) + return self._build_asset_file_path( + user, "states", platform_fs_slug, rom_id, emulator + ) - # /users/557365723a31/screenshots/n64 - def build_screenshots_file_path(self, user: User, platform_fs_slug: str): - return self._build_asset_file_path(user, "screenshots", platform_fs_slug) + # /users/557365723a31/screenshots/{rom.id}/n64 + def build_screenshots_file_path( + self, user: User, platform_fs_slug: str, rom_id: int + ): + return self._build_asset_file_path( + user, "screenshots", platform_fs_slug, rom_id + ) diff --git a/backend/handler/filesystem/firmware_handler.py b/backend/handler/filesystem/firmware_handler.py index 897366a82..a55f781be 100644 --- a/backend/handler/filesystem/firmware_handler.py +++ b/backend/handler/filesystem/firmware_handler.py @@ -90,7 +90,6 @@ class FSFirmwareHandler(FSHandler): return Path(path).mkdir(parents=True, exist_ok=True) - log.info(f" - Uploading {file.filename}") file_location = os.path.join(path, file.filename) with open(file_location, "wb") as f: diff --git a/backend/handler/filesystem/resources_handler.py b/backend/handler/filesystem/resources_handler.py index 243281e94..67b9a8a66 100644 --- a/backend/handler/filesystem/resources_handler.py +++ b/backend/handler/filesystem/resources_handler.py @@ -3,10 +3,12 @@ import shutil import httpx from anyio import Path, open_file from config import RESOURCES_BASE_PATH +from logger.formatter import BLUE +from logger.formatter import highlight as hl from logger.logger import log from models.collection import Collection from models.rom import Rom -from PIL import Image, ImageFile +from PIL import Image, ImageFile, UnidentifiedImageError from utils.context import ctx_httpx_client from .base_handler import CoverSize, FSHandler @@ -44,6 +46,22 @@ class FSResourcesHandler(FSHandler): small_img = cover.resize(small_size) small_img.save(save_path) + async def store_badge(self, url: str, file_path: str) -> None: + httpx_client = ctx_httpx_client.get() + try: + async with httpx_client.stream("GET", url, timeout=120) as response: + if response.status_code == 200: + await Path(f"{RESOURCES_BASE_PATH}/{file_path}").parent.mkdir( + parents=True, exist_ok=True + ) + async with await Path(f"{RESOURCES_BASE_PATH}/{file_path}").open( + "wb" + ) as f: + async for chunk in response.aiter_raw(): + await f.write(chunk) + except httpx.TransportError as exc: + log.error(f"Unable to fetch cover at {url}: {str(exc)}") + async def _store_cover( self, entity: Rom | Collection, url_cover: str, size: CoverSize ) -> None: @@ -68,11 +86,14 @@ class FSResourcesHandler(FSHandler): await f.write(chunk) except httpx.TransportError as exc: log.error(f"Unable to fetch cover at {url_cover}: {str(exc)}") - return None if size == CoverSize.SMALL: - with Image.open(cover_file) as img: - self.resize_cover_to_small(img, save_path=cover_file) + try: + with Image.open(cover_file) as img: + self.resize_cover_to_small(img, save_path=cover_file) + except UnidentifiedImageError as exc: + log.error(f"Unable to identify image {cover_file}: {str(exc)}") + return None @staticmethod async def _get_cover_path(entity: Rom | Collection, size: CoverSize) -> str: @@ -126,7 +147,7 @@ class FSResourcesHandler(FSHandler): shutil.rmtree(cover_path) except FileNotFoundError: log.warning( - f"Couldn't remove cover from '{entity.name or entity.id}' since '{cover_path}' doesn't exists." + f"Couldn't remove cover from '{hl(entity.name or entity.id, color=BLUE)}' since '{cover_path}' doesn't exists." ) return {"path_cover_s": "", "path_cover_l": ""} diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 8293e52c9..cb6fb1a92 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -14,9 +14,11 @@ from typing import Any, Final, Literal, TypedDict import magic import py7zr import zipfile_deflate64 # trunk-ignore(ruff/F401): Patches zipfile to support deflate64 compression +from adapters.services.rahasher import RAHasherService from config import LIBRARY_BASE_PATH from config.config_manager import config_manager as cm from exceptions.fs_exceptions import RomAlreadyExistsException, RomsNotFoundException +from handler.metadata.ra_handler import SLUG_TO_RA_ID from models.rom import Rom, RomFile, RomFileCategory from py7zr.exceptions import ( Bad7zFile, @@ -73,6 +75,7 @@ class FileHash(TypedDict): crc_hash: str md5_hash: str sha1_hash: str + ra_hash: str def is_compressed_file(file_path: str) -> bool: @@ -368,7 +371,7 @@ class FSRomsHandler(FSHandler): rom_sha1_h, ) - def get_rom_hashes(self, rom: Rom) -> tuple[FileHash, list[FileHash]]: + async def get_rom_hashes(self, rom: Rom) -> tuple[FileHash, list[FileHash]]: rom_crc_c = 0 rom_md5_h = hashlib.md5(usedforsecurity=False) rom_sha1_h = hashlib.sha1(usedforsecurity=False) @@ -395,9 +398,9 @@ class FSRomsHandler(FSHandler): if sha1_h.digest() != DEFAULT_SHA1_H_DIGEST else "" ), + ra_hash="", ) ) - return ( FileHash( id=rom.id, @@ -412,6 +415,14 @@ class FSRomsHandler(FSHandler): if rom_sha1_h.digest() != DEFAULT_SHA1_H_DIGEST else "" ), + ra_hash=( + await RAHasherService().calculate_hash( + SLUG_TO_RA_ID[rom.platform.slug]["id"], + f"{LIBRARY_BASE_PATH}/{rom.fs_path}/{rom.fs_name}", + ) + if rom.platform.slug in SLUG_TO_RA_ID.keys() + else "" + ), ), hashed_files, ) diff --git a/backend/handler/metadata/__init__.py b/backend/handler/metadata/__init__.py index 5f80c8557..46b23afb9 100644 --- a/backend/handler/metadata/__init__.py +++ b/backend/handler/metadata/__init__.py @@ -1,5 +1,6 @@ from .igdb_handler import IGDBHandler from .moby_handler import MobyGamesHandler +from .ra_handler import RAHandler from .sgdb_handler import SGDBBaseHandler from .ss_handler import SSHandler @@ -7,3 +8,4 @@ meta_igdb_handler = IGDBHandler() meta_moby_handler = MobyGamesHandler() meta_ss_handler = SSHandler() meta_sgdb_handler = SGDBBaseHandler() +meta_ra_handler = RAHandler() diff --git a/backend/handler/metadata/base_hander.py b/backend/handler/metadata/base_hander.py index afe17347b..b3c555882 100644 --- a/backend/handler/metadata/base_hander.py +++ b/backend/handler/metadata/base_hander.py @@ -206,6 +206,7 @@ class MetadataHandler: - "sspassword" - "devid" - "devpassword" + - "y" (RA API key) """ return { key: ( @@ -224,6 +225,7 @@ class MetadataHandler: "sspassword", "devid", "devpassword", + "y", } # Leave other keys unchanged else values[key] diff --git a/backend/handler/metadata/ra_handler.py b/backend/handler/metadata/ra_handler.py new file mode 100644 index 000000000..f69b480e5 --- /dev/null +++ b/backend/handler/metadata/ra_handler.py @@ -0,0 +1,411 @@ +import asyncio +import http +import json +import os +import time +from typing import Final, NotRequired, TypedDict + +import httpx +import yarl +from anyio import open_file +from config import ( + REFRESH_RETROACHIEVEMENTS_CACHE_DAYS, + RESOURCES_BASE_PATH, + RETROACHIEVEMENTS_API_KEY, +) +from fastapi import HTTPException, status +from logger.logger import log +from models.platform import Platform +from utils.context import ctx_httpx_client + +from .base_hander import MetadataHandler + +# Used to display the Retroachievements API status in the frontend +RA_API_ENABLED: Final = bool(RETROACHIEVEMENTS_API_KEY) + + +class RAGamesPlatform(TypedDict): + slug: str + ra_id: int | None + name: NotRequired[str] + + +class RAGameRomAchievement(TypedDict): + ra_id: int | None + title: str | None + description: str | None + points: int | None + num_awarded: int | None + num_awarded_hardcore: int | None + badge_id: str | None + badge_url_lock: str | None + badge_path_lock: str | None + badge_url: str | None + badge_path: str | None + display_order: int | None + type: str | None + + +class RAMetadata(TypedDict): + achievements: list[RAGameRomAchievement] + + +class RAGameRom(TypedDict): + ra_id: int | None + ra_metadata: NotRequired[RAMetadata] + + +class EarnedAchievement(TypedDict): + id: str + date: str + + +class RAUserGameProgression(TypedDict): + rom_ra_id: int | None + max_possible: int | None + num_awarded: int | None + num_awarded_hardcore: int | None + earned_achievements: list[EarnedAchievement] + + +class RAUserProgression(TypedDict): + count: int + total: int + results: list[RAUserGameProgression] + + +class RAHandler(MetadataHandler): + def __init__(self) -> None: + self.BASE_URL = "https://retroachievements.org/API" + self.search_endpoint = f"{self.BASE_URL}/API_GetGameList.php" + self.game_details_endpoint = f"{self.BASE_URL}/API_GetGameExtended.php" + self.user_complete_progression_endpoint = ( + f"{self.BASE_URL}/API_GetUserCompletionProgress.php" + ) + self.user_game_progression_endpoint = ( + f"{self.BASE_URL}/API_GetGameInfoAndUserProgress.php" + ) + self.HASHES_FILE_NAME = "ra_hashes.json" + + def _get_rom_base_path(self, platform_id: int, rom_id: int) -> str: + return os.path.join( + "roms", + str(platform_id), + str(rom_id), + "retroachievements", + ) + + def _get_hashes_file_path(self, platform_id: int) -> str: + return os.path.join( + RESOURCES_BASE_PATH, + "roms", + str(platform_id), + self.HASHES_FILE_NAME, + ) + + def _get_badges_path(self, platform_id: int, rom_id: int) -> str: + return os.path.join(self._get_rom_base_path(platform_id, rom_id), "badges") + + def _create_resources_path(self, platform_id: int, rom_id: int) -> None: + os.makedirs( + os.path.join( + RESOURCES_BASE_PATH, + self._get_rom_base_path(platform_id, rom_id), + ), + exist_ok=True, + ) + + def _exists_cache_file(self, platform_id: int) -> bool: + return os.path.exists(self._get_hashes_file_path(platform_id)) + + def _days_since_last_cache_file_update(self, platform_id: int) -> int: + file_path = self._get_hashes_file_path(platform_id) + return ( + 0 + if not os.path.exists(file_path) + else int((time.time() - os.path.getmtime(file_path)) / (24 * 3600)) + ) + + async def _request(self, url: str, request_timeout: int = 120) -> dict: + httpx_client = ctx_httpx_client.get() + authorized_url = yarl.URL(url) + masked_url = authorized_url.with_query( + self._mask_sensitive_values(dict(authorized_url.query)) + ) + log.debug( + "API request: URL=%s, Timeout=%s", + masked_url, + request_timeout, + ) + try: + res = await httpx_client.get(str(authorized_url), timeout=request_timeout) + res.raise_for_status() + return res.json() + except httpx.NetworkError as exc: + log.critical( + "Connection error: can't connect to RetroAchievements", exc_info=True + ) + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="Can't connect to RetroAchievements, check your internet connection", + ) from exc + except httpx.HTTPStatusError as err: + if err.response.status_code == http.HTTPStatus.TOO_MANY_REQUESTS: + # Retry after 2 seconds if rate limit hit + await asyncio.sleep(2) + else: + # Log the error and return an empty dict if the request fails with a different code + log.error(err) + return {} + except httpx.TimeoutException: + # Retry the request once if it times out + pass + + try: + log.debug( + "API request: URL=%s, Timeout=%s", + url, + request_timeout, + ) + res = await httpx_client.get(url, timeout=request_timeout) + res.raise_for_status() + except (httpx.HTTPStatusError, httpx.TimeoutException) as err: + if ( + isinstance(err, httpx.HTTPStatusError) + and err.response.status_code == http.HTTPStatus.UNAUTHORIZED + ): + # Sometimes Mobygames returns 401 even with a valid API key + return {} + + # Log the error and return an empty dict if the request fails with a different code + log.error(err) + return {} + + return res.json() + + async def _search_rom( + self, platform: Platform, rom_id: int, hash: str + ) -> dict | None: + + if not platform.ra_id: + return None + + self._create_resources_path(platform.id, rom_id) + + url = yarl.URL(self.search_endpoint).with_query( + i=[platform.ra_id], + f=["1"], # If 1, only return games that have achievements. Defaults to 0. + h=["1"], # If 1, also return supported hashes for games. Defaults to 0. + y=[RETROACHIEVEMENTS_API_KEY], + ) + + # Fetch all hashes for specific platform + if ( + REFRESH_RETROACHIEVEMENTS_CACHE_DAYS + <= self._days_since_last_cache_file_update(platform.id) + or not self._exists_cache_file(platform.id) + ): + # Write the roms result to a JSON file if older than REFRESH_RETROACHIEVEMENTS_CACHE_DAYS days + roms = await self._request(str(url)) + async with await open_file( + self._get_hashes_file_path(platform.id), + "w", + encoding="utf-8", + ) as json_file: + await json_file.write(json.dumps(roms, indent=4)) + else: + # Read the roms result from the JSON file + async with await open_file( + self._get_hashes_file_path(platform.id), + "r", + encoding="utf-8", + ) as json_file: + roms = json.loads(await json_file.read()) + + for rom in roms: + if hash in rom["Hashes"]: + return rom + + return None + + async def _get_rom_details(self, ra_id: int) -> dict: + url = yarl.URL(self.game_details_endpoint).with_query( + i=[ra_id], + y=[RETROACHIEVEMENTS_API_KEY], + ) + details = await self._request(str(url)) + return details + + def get_platform(self, slug: str) -> RAGamesPlatform: + platform = SLUG_TO_RA_ID.get(slug.lower(), None) + + if not platform: + return RAGamesPlatform(ra_id=None, slug=slug) + + return RAGamesPlatform( + ra_id=platform["id"], + slug=slug, + name=platform["name"], + ) + + async def get_rom(self, platform: Platform, rom_id: int, hash: str) -> RAGameRom: + if not platform.ra_id or not hash: + return RAGameRom(ra_id=None) + + rom = await self._search_rom(platform, rom_id, hash) + + if not rom: + return RAGameRom(ra_id=None) + + try: + rom_details = await self._get_rom_details(rom["ID"]) + return RAGameRom( + ra_id=rom["ID"], + ra_metadata=RAMetadata( + achievements=[ + RAGameRomAchievement( + ra_id=achievement.get("ID", None), + title=achievement.get("Title", ""), + description=achievement.get("Description", ""), + points=achievement.get("Points", None), + num_awarded=achievement.get("NumAwarded", None), + num_awarded_hardcore=achievement.get( + "NumAwardedHardcore", None + ), + badge_id=achievement.get("BadgeName", ""), + badge_url_lock=f"https://media.retroachievements.org/Badge/{achievement.get('BadgeName', '')}_lock.png", + badge_path_lock=f"{self._get_badges_path(platform.id, rom_id)}/{achievement.get('BadgeName', '')}_lock.png", + badge_url=f"https://media.retroachievements.org/Badge/{achievement.get('BadgeName', '')}.png", + badge_path=f"{self._get_badges_path(platform.id, rom_id)}/{achievement.get('BadgeName', '')}.png", + display_order=achievement.get("DisplayOrder", None), + type=achievement.get("type", ""), + ) + for achievement in rom_details.get("Achievements", {}).values() + ] + ), + ) + except KeyError: + return RAGameRom(ra_id=None) + + async def get_user_progression(self, username: str) -> RAUserProgression: + url = yarl.URL(self.user_complete_progression_endpoint).with_query( + u=[username], y=[RETROACHIEVEMENTS_API_KEY], c=[500] + ) + user_complete_progression = await self._request(str(url)) + roms_with_progression = user_complete_progression.get("Results", []) + for rom in roms_with_progression: + rom["EarnedAchievements"] = [] + if rom.get("GameID", None): + url = yarl.URL(self.user_game_progression_endpoint).with_query( + g=[rom["GameID"]], + u=[username], + y=[RETROACHIEVEMENTS_API_KEY], + ) + result = await self._request(str(url)) + for achievement in result.get("Achievements", {}).values(): + if "DateEarned" in achievement.keys(): + rom["EarnedAchievements"].append( + { + "id": achievement.get("BadgeName"), + "date": achievement["DateEarned"], + } + ) + return RAUserProgression( + count=user_complete_progression.get("Count", 0), + total=user_complete_progression.get("Total", 0), + results=[ + RAUserGameProgression( + rom_ra_id=rom.get("GameID", None), + max_possible=rom.get("MaxPossible", None), + num_awarded=rom.get("NumAwarded", None), + num_awarded_hardcore=rom.get("NumAwardedHardcore", None), + earned_achievements=rom.get("EarnedAchievements", []), + ) + for rom in roms_with_progression + ], + ) + + +class SlugToRAId(TypedDict): + id: int + name: str + + +SLUG_TO_RA_ID: dict[str, SlugToRAId] = { + "3do": {"id": 43, "name": "3DO"}, + "cpc": {"id": 37, "name": "Amstrad CPC"}, + "acpc": {"id": 37, "name": "Amstrad CPC"}, + "apple2": {"id": 38, "name": "Apple II"}, + "appleii": {"id": 38, "name": "Apple II"}, + "arcade": {"id": 27, "name": "Arcade"}, + "arcadia-2001": {"id": 73, "name": "Arcadia 2001"}, + "arduboy": {"id": 71, "name": "Arduboy"}, + "atari-2600": {"id": 25, "name": "Atari 2600"}, + "atari2600": {"id": 25, "name": "Atari 2600"}, # IGDB + "atari-7800": {"id": 51, "name": "Atari 7800"}, + "atari7800": {"id": 51, "name": "Atari 7800"}, # IGDB + "atari-jaguar-cd": {"id": 77, "name": "Atari Jaguar CD"}, + "colecovision": {"id": 44, "name": "ColecoVision"}, + "dreamcast": {"id": 40, "name": "Dreamcast"}, + "dc": {"id": 40, "name": "Dreamcast"}, # IGDB + "gameboy": {"id": 4, "name": "Game Boy"}, + "gb": {"id": 4, "name": "Game Boy"}, # IGDB + "gameboy-advance": {"id": 5, "name": "Game Boy Advance"}, + "gba": {"id": 5, "name": "Game Boy Advance"}, # IGDB + "gameboy-color": {"id": 6, "name": "Game Boy Color"}, + "gbc": {"id": 6, "name": "Game Boy Color"}, # IGDB + "game-gear": {"id": 15, "name": "Game Gear"}, + "gamegear": {"id": 15, "name": "Game Gear"}, # IGDB + "gamecube": {"id": 16, "name": "GameCube"}, + "ngc": {"id": 14, "name": "GameCube"}, # IGDB + "genesis": {"id": 1, "name": "Genesis/Mega Drive"}, + "genesis-slash-megadrive": {"id": 16, "name": "Genesis/Mega Drive"}, + "intellivision": {"id": 45, "name": "Intellivision"}, + "jaguar": {"id": 17, "name": "Jaguar"}, + "lynx": {"id": 13, "name": "Lynx"}, + "msx": {"id": 29, "name": "MSX"}, + "mega-duck-slash-cougar-boy": {"id": 69, "name": "Mega Duck/Cougar Boy"}, + "nes": {"id": 7, "name": "NES"}, + "famicom": {"id": 7, "name": "NES"}, + "neo-geo-cd": {"id": 56, "name": "Neo Geo CD"}, + "neo-geo-pocket": {"id": 14, "name": "Neo Geo Pocket"}, + "neo-geo-pocket-color": {"id": 14, "name": "Neo Geo Pocket Color"}, + "n64": {"id": 2, "name": "Nintendo 64"}, + "nintendo-ds": {"id": 18, "name": "Nintendo DS"}, + "nds": {"id": 18, "name": "Nintendo DS"}, # IGDB + "nintendo-dsi": {"id": 78, "name": "Nintendo DSi"}, + "odyssey-2": {"id": 23, "name": "Odyssey 2"}, + "pc-8000": {"id": 47, "name": "PC-8000"}, + "pc-8800-series": {"id": 47, "name": "PC-8800 Series"}, # IGDB + "pc-fx": {"id": 49, "name": "PC-FX"}, + "psp": {"id": 41, "name": "PSP"}, + "playstation": {"id": 12, "name": "PlayStation"}, + "ps": {"id": 12, "name": "PlayStation"}, # IGDB + "ps2": {"id": 21, "name": "PlayStation 2"}, + "pokemon-mini": {"id": 24, "name": "Pokémon Mini"}, + "saturn": {"id": 39, "name": "Sega Saturn"}, + "sega-32x": {"id": 10, "name": "SEGA 32X"}, + "sega32": {"id": 10, "name": "SEGA 32X"}, # IGDB + "sega-cd": {"id": 9, "name": "SEGA CD"}, + "segacd": {"id": 9, "name": "SEGA CD"}, # IGDB + "sega-master-system": {"id": 11, "name": "SEGA Master System"}, + "sms": {"id": 11, "name": "SEGA Master System"}, # IGDB + "sg-1000": {"id": 33, "name": "SG-1000"}, + "snes": {"id": 3, "name": "SNES"}, + "turbografx-cd": {"id": 76, "name": "TurboGrafx CD"}, + "turbografx-16-slash-pc-engine-cd": {"id": 76, "name": "TurboGrafx CD"}, + "turbo-grafx": {"id": 8, "name": "TurboGrafx-16"}, + "turbografx16--1": {"id": 8, "name": "TurboGrafx-16"}, # IGDB + "vectrex": {"id": 26, "name": "Vectrex"}, + "virtual-boy": {"id": 28, "name": "Virtual Boy"}, + "virtualboy": {"id": 28, "name": "Virtual Boy"}, + "watara-slash-quickshot-supervision": { + "id": 63, + "name": "Watara/QuickShot Supervision", + }, + "wonderswan": {"id": 53, "name": "WonderSwan"}, + "wonderswan-color": {"id": 53, "name": "WonderSwan Color"}, +} + +# Reverse lookup +RA_ID_TO_SLUG = {v["id"]: k for k, v in SLUG_TO_RA_ID.items()} diff --git a/backend/handler/redis_handler.py b/backend/handler/redis_handler.py index 7eb520f79..423e680dc 100644 --- a/backend/handler/redis_handler.py +++ b/backend/handler/redis_handler.py @@ -1,3 +1,4 @@ +import os import sys from enum import Enum @@ -28,10 +29,11 @@ def __get_sync_cache() -> Redis: return FakeRedis(version=7) - log.info(f"Connecting to sync redis in {sys.argv[0]}...") # A separate client that auto-decodes responses is needed client = Redis.from_url(str(REDIS_URL), decode_responses=True) - log.info(f"Redis sync connection established in {sys.argv[0]}!") + log.debug( + f"Sync redis/valkey connection established in {os.path.splitext(os.path.basename(sys.argv[0]))[0]}" + ) return client @@ -42,10 +44,11 @@ def __get_async_cache() -> AsyncRedis: return FakeAsyncRedis(version=7) - log.info(f"Connecting to async redis in {sys.argv[0]}...") # A separate client that auto-decodes responses is needed client = AsyncRedis.from_url(str(REDIS_URL), decode_responses=True) - log.info(f"Redis async connection established in {sys.argv[0]}!") + log.debug( + f"Async redis/valkey connection established in {os.path.splitext(os.path.basename(sys.argv[0]))[0]}" + ) return client diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 9385234ab..6dac46170 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -7,11 +7,17 @@ from config.config_manager import config_manager as cm from handler.database import db_platform_handler from handler.filesystem import fs_asset_handler, fs_firmware_handler, fs_rom_handler from handler.filesystem.roms_handler import FSRom -from handler.metadata import meta_igdb_handler, meta_moby_handler, meta_ss_handler +from handler.metadata import ( + meta_igdb_handler, + meta_moby_handler, + meta_ra_handler, + meta_ss_handler, +) from handler.metadata.igdb_handler import IGDBPlatform, IGDBRom from handler.metadata.moby_handler import MobyGamesPlatform, MobyGamesRom +from handler.metadata.ra_handler import RAGameRom, RAGamesPlatform from handler.metadata.ss_handler import SSPlatform, SSRom -from logger.formatter import BLUE +from logger.formatter import BLUE, LIGHTYELLOW from logger.formatter import highlight as hl from logger.logger import log from models.assets import Save, Screenshot, State @@ -20,6 +26,8 @@ from models.platform import Platform from models.rom import Rom from models.user import User +LOGGER_MODULE_NAME = {"module_name": "scan"} + class ScanType(Enum): NEW_PLATFORMS = "new_platforms" @@ -34,6 +42,20 @@ class MetadataSource: IGDB = "igdb" MOBY = "moby" SS = "ss" + RA = "ra" + + +async def fetch_ra_info( + platform: Platform, + rom_id: int, + hash: str, +) -> RAGameRom: + + return await meta_ra_handler.get_rom( + platform=platform, + rom_id=rom_id, + hash=hash, + ) async def _get_main_platform_igdb_id(platform: Platform): @@ -68,10 +90,13 @@ async def scan_platform( Platform object """ - log.info(f"· {hl(fs_slug)}") - if metadata_sources is None: - metadata_sources = [MetadataSource.IGDB, MetadataSource.MOBY, MetadataSource.SS] + metadata_sources = [ + MetadataSource.IGDB, + MetadataSource.MOBY, + MetadataSource.SS, + MetadataSource.RA, + ] platform_attrs: dict[str, Any] = {} platform_attrs["fs_slug"] = fs_slug @@ -83,7 +108,8 @@ async def scan_platform( # Sometimes users change the name of the folder, so we try to match it with the config if fs_slug not in fs_platforms: log.warning( - f" {fs_slug} not found in file system, trying to match via config..." + f"{hl(fs_slug)} not found in file system, trying to match via config", + extra=LOGGER_MODULE_NAME, ) if fs_slug in swapped_platform_bindings.keys(): platform = db_platform_handler.get_platform_by_fs_slug(fs_slug) @@ -103,7 +129,6 @@ async def scan_platform( platform_attrs["slug"] = fs_slug except (KeyError, TypeError, AttributeError): platform_attrs["slug"] = fs_slug - igdb_platform = ( (await meta_igdb_handler.get_platform(platform_attrs["slug"])) if MetadataSource.IGDB in metadata_sources @@ -120,9 +145,15 @@ async def scan_platform( else SSPlatform(ss_id=None, slug=platform_attrs["slug"]) ) + ra_platform = ( + meta_ra_handler.get_platform(platform_attrs["slug"]) + if MetadataSource.RA in metadata_sources + else RAGamesPlatform(ra_id=None, slug=platform_attrs["slug"]) + ) + platform_attrs["name"] = platform_attrs["slug"].replace("-", " ").title() platform_attrs.update( - {**moby_platform, **ss_platform, **igdb_platform} + {**ra_platform, **moby_platform, **ss_platform, **igdb_platform} ) # Reverse order if ( @@ -132,14 +163,16 @@ async def scan_platform( ): log.info( emoji.emojize( - f" Identified as {hl(platform_attrs['name'], color=BLUE)} :video_game:" - ) + f"Folder {hl(platform_attrs['slug'])}[{hl(fs_slug, color=LIGHTYELLOW)}] identified as {hl(platform_attrs['name'], color=BLUE)} :video_game:" + ), + extra={"module_name": "scan"}, ) else: log.warning( emoji.emojize( - f" Platform {platform_attrs['slug']} not identified :cross_mark:" - ) + f"Platform {hl(platform_attrs['slug'])} not identified :cross_mark:" + ), + extra=LOGGER_MODULE_NAME, ) return Platform(**platform_attrs) @@ -152,8 +185,6 @@ def scan_firmware( ) -> Firmware: firmware_path = fs_firmware_handler.get_firmware_fs_structure(platform.fs_slug) - log.info(f"\t · {file_name}") - # Set default properties firmware_attrs = { "id": firmware.id if firmware else None, @@ -198,16 +229,15 @@ async def scan_rom( metadata_sources: list[str] | None = None, ) -> Rom: if not metadata_sources: - metadata_sources = [MetadataSource.IGDB, MetadataSource.MOBY, MetadataSource.SS] + metadata_sources = [ + MetadataSource.IGDB, + MetadataSource.MOBY, + MetadataSource.SS, + MetadataSource.RA, + ] roms_path = fs_rom_handler.get_roms_fs_structure(platform.fs_slug) - 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.file_name}") - # Set default properties rom_attrs = { "id": rom.id if rom else None, @@ -228,6 +258,7 @@ async def scan_rom( "moby_id": rom.moby_id, "ss_id": rom.ss_id, "sgdb_id": rom.sgdb_id, + "ra_id": rom.ra_id, "name": rom.name, "slug": rom.slug, "summary": rom.summary, @@ -348,20 +379,28 @@ async def scan_rom( and not ss_handler_rom.get("ss_id") ): log.warning( - emoji.emojize( - f"\t Rom {rom_attrs['fs_name']} not identified :cross_mark:" - ) + emoji.emojize(f"{hl(rom_attrs['fs_name'])} not identified :cross_mark:"), + extra=LOGGER_MODULE_NAME, ) return Rom(**rom_attrs) - log.info(emoji.emojize(f"\t Identified as {rom_attrs['name']} :alien_monster:")) + log.info( + emoji.emojize( + f"{hl(rom_attrs['fs_name'])} identified as {hl(rom_attrs['name'], color=BLUE)} :alien_monster:" + ), + extra=LOGGER_MODULE_NAME, + ) + if fs_rom.get("multi", False): + for file in fs_rom["files"]: + log.info( + f"\t · {hl(file.file_name, color=LIGHTYELLOW)}", + extra=LOGGER_MODULE_NAME, + ) return Rom(**rom_attrs) def _scan_asset(file_name: str, path: str): - log.info(f"\t\t · {file_name}") - file_size = fs_asset_handler.get_asset_size(file_name=file_name, asset_path=path) return { @@ -375,19 +414,27 @@ def _scan_asset(file_name: str, path: str): def scan_save( - file_name: str, user: User, platform_fs_slug: str, emulator: str | None = None + file_name: str, + user: User, + platform_fs_slug: str, + rom_id: int, + emulator: str | None = None, ) -> Save: saves_path = fs_asset_handler.build_saves_file_path( - user=user, platform_fs_slug=platform_fs_slug, emulator=emulator + user=user, platform_fs_slug=platform_fs_slug, rom_id=rom_id, emulator=emulator ) return Save(**_scan_asset(file_name, saves_path)) def scan_state( - file_name: str, user: User, platform_fs_slug: str, emulator: str | None = None + file_name: str, + user: User, + platform_fs_slug: str, + rom_id: int, + emulator: str | None = None, ) -> State: states_path = fs_asset_handler.build_states_file_path( - user=user, platform_fs_slug=platform_fs_slug, emulator=emulator + user=user, platform_fs_slug=platform_fs_slug, rom_id=rom_id, emulator=emulator ) return State(**_scan_asset(file_name, states_path)) @@ -396,8 +443,9 @@ def scan_screenshot( file_name: str, user: User, platform_fs_slug: str, + rom_id: int, ) -> Screenshot: screenshots_path = fs_asset_handler.build_screenshots_file_path( - user=user, platform_fs_slug=platform_fs_slug + user=user, platform_fs_slug=platform_fs_slug, rom_id=rom_id ) return Screenshot(**_scan_asset(file_name, screenshots_path)) diff --git a/backend/handler/tests/conftest.py b/backend/handler/tests/conftest.py index 63133aeeb..23e630f8a 100644 --- a/backend/handler/tests/conftest.py +++ b/backend/handler/tests/conftest.py @@ -46,7 +46,7 @@ def platform(): @pytest.fixture -def rom(platform: Platform): +def rom(admin_user: User, platform: Platform): rom = Rom( platform_id=platform.id, name="test_rom", @@ -57,7 +57,11 @@ def rom(platform: Platform): fs_extension="zip", fs_path=f"{platform.slug}/roms", ) - return db_rom_handler.add_rom(rom) + rom = db_rom_handler.add_rom(rom) + + db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id) + + return rom @pytest.fixture diff --git a/backend/logger/formatter.py b/backend/logger/formatter.py index fee4e816a..6e3733700 100644 --- a/backend/logger/formatter.py +++ b/backend/logger/formatter.py @@ -1,14 +1,19 @@ import logging -import os +from pprint import pformat from colorama import Fore, Style, init from config import FORCE_COLOR, NO_COLOR RED = Fore.RED +LIGHTRED = Fore.LIGHTRED_EX GREEN = Fore.GREEN LIGHTYELLOW = Fore.LIGHTYELLOW_EX YELLOW = Fore.YELLOW BLUE = Fore.BLUE +CYAN = Fore.CYAN +LIGHTMAGENTA = Fore.LIGHTMAGENTA_EX +RESET = Fore.RESET +RESET_ALL = Style.RESET_ALL def should_strip_ansi() -> bool: @@ -18,9 +23,8 @@ def should_strip_ansi() -> bool: return False if NO_COLOR: return True - - # For other environments, strip colors if not a TTY - return not os.isatty(1) + # Default: do not strip (Docker will handle colors) + return False # Initialize Colorama once, considering different environments @@ -43,37 +47,40 @@ class Formatter(logging.Formatter): The formatted log record as a string. """ level = "%(levelname)s" - dots = f"{Fore.RESET}:" + dots = f"{RESET}:" identifier = ( - f"\t {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[{record.module.lower()}]" + f"\t {BLUE}[RomM]{LIGHTMAGENTA}[{record.module_name.lower()}]" if hasattr(record, "module_name") - else f"\t {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[%(module)s]" + else f"\t {BLUE}[RomM]{LIGHTMAGENTA}[%(module)s]" ) identifier_warning = ( - f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[{record.module.lower()}]" + f" {BLUE}[RomM]{LIGHTMAGENTA}[{record.module_name.lower()}]" if hasattr(record, "module_name") - else f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[%(module)s]" + else f" {BLUE}[RomM]{LIGHTMAGENTA}[%(module)s]" ) identifier_critical = ( - f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[{record.module.lower()}]" + f" {BLUE}[RomM]{LIGHTMAGENTA}[{record.module_name.lower()}]" if hasattr(record, "module_name") - else f" {Fore.BLUE}[RomM]{Fore.LIGHTMAGENTA_EX}[%(module)s]" + else f" {BLUE}[RomM]{LIGHTMAGENTA}[%(module)s]" ) - msg = f"{Style.RESET_ALL}%(message)s" - date = f"{Fore.CYAN}[%(asctime)s] " + msg = f"{RESET_ALL}%(message)s" + + message = pformat(record.msg) if hasattr(record, "pprint") else "%(message)s" + msg = f"{RESET_ALL}{message}" + date = f"{CYAN}[%(asctime)s] " formats = { - logging.DEBUG: f"{Fore.LIGHTMAGENTA_EX}{level}{dots}{identifier}{date}{msg}", - logging.INFO: f"{Fore.GREEN}{level}{dots}{identifier}{date}{msg}", - logging.WARNING: f"{Fore.YELLOW}{level}{dots}{identifier_warning}{date}{msg}", - logging.ERROR: f"{Fore.LIGHTRED_EX}{level}{dots}{identifier}{date}{msg}", - logging.CRITICAL: f"{Fore.RED}{level}{dots}{identifier_critical}{date}{msg}", + logging.DEBUG: f"{LIGHTMAGENTA}{level}{dots}{identifier}{date}{msg}", + logging.INFO: f"{GREEN}{level}{dots}{identifier}{date}{msg}", + logging.WARNING: f"{YELLOW}{level}{dots}{identifier_warning}{date}{msg}", + logging.ERROR: f"{LIGHTRED}{level}{dots}{identifier}{date}{msg}", + logging.CRITICAL: f"{RED}{level}{dots}{identifier_critical}{date}{msg}", } log_fmt = formats.get(record.levelno) formatter = logging.Formatter(fmt=log_fmt, datefmt="%Y-%m-%d %H:%M:%S") return formatter.format(record) -def highlight(msg: str = "", color=Fore.YELLOW) -> str: +def highlight(msg: str = "", color=YELLOW) -> str: """ Highlights the message to send to the fancylog. @@ -84,4 +91,4 @@ def highlight(msg: str = "", color=Fore.YELLOW) -> str: Returns: The highlighted message as a string. """ - return f"{color}{msg}{Style.RESET_ALL}" + return f"{color}{msg}{RESET_ALL}" diff --git a/backend/logger/logger.py b/backend/logger/logger.py index c14049f33..2e7f26b58 100644 --- a/backend/logger/logger.py +++ b/backend/logger/logger.py @@ -8,15 +8,28 @@ from logger.formatter import Formatter log = logging.getLogger("romm") log.setLevel(LOGLEVEL) -# Set up sqlachemy logger -# sql_log = logging.getLogger("sqlalchemy.engine") -# sql_log.setLevel(LOGLEVEL) - # Define stdout handler stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(Formatter()) log.addHandler(stdout_handler) -# sql_log.addHandler(stdout_handler) # Hush passlib warnings logging.getLogger("passlib").setLevel(logging.ERROR) + + +def unify_logger(logger: str) -> None: + """ + Unify the logger to use the same format and level as the main logger. + + Args: + logger (str): The name of the logger to unify. + """ + alembic_logger = logging.getLogger(logger) + alembic_logger.setLevel(log.level) + + if not alembic_logger.hasHandlers(): + for handler in log.handlers: + alembic_logger.addHandler(handler) + else: + for handler in alembic_logger.handlers: + handler.setFormatter(log.handlers[0].formatter) diff --git a/backend/models/platform.py b/backend/models/platform.py index ce08d4463..535bf9bf2 100644 --- a/backend/models/platform.py +++ b/backend/models/platform.py @@ -23,6 +23,7 @@ class Platform(BaseModel): sgdb_id: Mapped[int | None] moby_id: Mapped[int | None] ss_id: Mapped[int | None] + ra_id: Mapped[int | None] slug: Mapped[str] = mapped_column(String(length=100)) fs_slug: Mapped[str] = mapped_column(String(length=100)) name: Mapped[str] = mapped_column(String(length=400)) diff --git a/backend/models/rom.py b/backend/models/rom.py index 9263783bc..4c1670724 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -52,6 +52,7 @@ class RomFile(BaseModel): 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)) + ra_hash: Mapped[str | None] = mapped_column(String(100)) category: Mapped[RomFileCategory | None] = mapped_column( Enum(RomFileCategory), default=None ) @@ -115,11 +116,14 @@ class Rom(BaseModel): sgdb_id: Mapped[int | None] moby_id: Mapped[int | None] ss_id: Mapped[int | None] + ra_id: Mapped[int | None] __table_args__ = ( Index("idx_roms_igdb_id", "igdb_id"), Index("idx_roms_moby_id", "moby_id"), Index("idx_roms_ss_id", "ss_id"), + Index("idx_roms_ra_id", "ra_id"), + Index("idx_roms_sgdb_id", "sgdb_id"), ) fs_name: Mapped[str] = mapped_column(String(length=450)) @@ -140,6 +144,9 @@ class Rom(BaseModel): ss_metadata: Mapped[dict[str, Any] | None] = mapped_column( CustomJSON(), default=dict ) + ra_metadata: Mapped[dict[str, Any] | None] = mapped_column( + CustomJSON(), default=dict + ) path_cover_s: Mapped[str | None] = mapped_column(Text, default="") path_cover_l: Mapped[str | None] = mapped_column(Text, default="") @@ -165,6 +172,7 @@ class Rom(BaseModel): crc_hash: Mapped[str | None] = mapped_column(String(length=100)) md5_hash: Mapped[str | None] = mapped_column(String(length=100)) sha1_hash: Mapped[str | None] = mapped_column(String(length=100)) + ra_hash: Mapped[str | None] = mapped_column(String(length=100)) platform_id: Mapped[int] = mapped_column( ForeignKey("platforms.id", ondelete="CASCADE") @@ -232,7 +240,16 @@ class Rom(BaseModel): @cached_property def multi(self) -> bool: - return len(self.files) > 1 + # TODO: Improve multi game detection. This is a temporal fix to check if multi. + if len(self.files) > 1: + return True + if ( + self.files + and len(self.files) > 0 + and len(self.files[0].full_path.split("/")) > 3 + ): + return True + return False @cached_property def fs_size_bytes(self) -> int: @@ -274,9 +291,23 @@ class Rom(BaseModel): or [] ) + @property + def merged_ra_metadata(self) -> dict[str, list] | None: + if self.ra_metadata and "achievements" in self.ra_metadata: + for achievement in self.ra_metadata.get("achievements", []): + achievement["badge_path_lock"] = ( + f"{FRONTEND_RESOURCES_PATH}/{achievement['badge_path_lock']}" + ) + achievement["badge_path"] = ( + f"{FRONTEND_RESOURCES_PATH}/{achievement['badge_path']}" + ) + return self.ra_metadata + @property def is_unidentified(self) -> bool: - return not self.igdb_id and not self.moby_id and not self.ss_id + return ( + not self.igdb_id and not self.moby_id and not self.ss_id and not self.ra_id + ) @property def is_partially_identified(self) -> bool: @@ -284,7 +315,12 @@ class Rom(BaseModel): @property def is_fully_identified(self) -> bool: - return bool(self.igdb_id) and bool(self.moby_id) and bool(self.ss_id) + return ( + bool(self.igdb_id) + and bool(self.moby_id) + and bool(self.ss_id) + and bool(self.ra_id) + ) def has_m3u_file(self) -> bool: """ diff --git a/backend/models/user.py b/backend/models/user.py index 4c994989b..a367666e0 100644 --- a/backend/models/user.py +++ b/backend/models/user.py @@ -2,7 +2,7 @@ from __future__ import annotations import enum from datetime import datetime, timezone -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from config import KIOSK_MODE from handler.auth.constants import ( @@ -16,6 +16,7 @@ from models.base import BaseModel from sqlalchemy import TIMESTAMP, Enum, String from sqlalchemy.orm import Mapped, mapped_column, relationship from starlette.authentication import SimpleUser +from utils.database import CustomJSON if TYPE_CHECKING: from models.assets import Save, Screenshot, State @@ -45,6 +46,10 @@ class User(BaseModel, SimpleUser): avatar_path: Mapped[str] = mapped_column(String(length=255), default="") last_login: Mapped[datetime | None] = mapped_column(TIMESTAMP(timezone=True)) last_active: Mapped[datetime | None] = mapped_column(TIMESTAMP(timezone=True)) + ra_username: Mapped[str | None] = mapped_column(String(length=255), default="") + ra_progression: Mapped[dict[str, Any] | None] = mapped_column( + CustomJSON(), default=dict + ) saves: Mapped[list[Save]] = relationship(lazy="select", back_populates="user") states: Mapped[list[State]] = relationship(lazy="select", back_populates="user") diff --git a/backend/scheduler.py b/backend/scheduler.py index 2105c65ac..ec9385abd 100644 --- a/backend/scheduler.py +++ b/backend/scheduler.py @@ -1,22 +1,24 @@ import sentry_sdk -from config import SENTRY_DSN +from config import ( + ENABLE_SCHEDULED_RESCAN, + ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB, + SENTRY_DSN, +) from logger.logger import log from tasks.scan_library import scan_library_task from tasks.tasks import tasks_scheduler from tasks.update_switch_titledb import update_switch_titledb_task from utils import get_version -sentry_sdk.init( - dsn=SENTRY_DSN, - release="romm@" + get_version(), -) +sentry_sdk.init(dsn=SENTRY_DSN, release=f"romm@{get_version()}") if __name__ == "__main__": # Initialize the tasks - scan_library_task.init() - update_switch_titledb_task.init() - - log.info("Starting scheduler") - + if ENABLE_SCHEDULED_RESCAN: + log.info("Starting scheduled rescan") + scan_library_task.init() + if ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB: + log.info("Starting scheduled update switch titledb") + update_switch_titledb_task.init() # Start the scheduler tasks_scheduler.run() diff --git a/backend/watcher.py b/backend/watcher.py index df071a1cb..213345a2b 100644 --- a/backend/watcher.py +++ b/backend/watcher.py @@ -12,6 +12,8 @@ from config.config_manager import config_manager as cm from endpoints.sockets.scan import scan_platforms from handler.database import db_platform_handler from handler.scan_handler import ScanType +from logger.formatter import CYAN +from logger.formatter import highlight as hl from logger.logger import log from rq.job import Job from tasks.tasks import tasks_scheduler @@ -21,7 +23,7 @@ from watchdog.observers import Observer sentry_sdk.init( dsn=SENTRY_DSN, - release="romm@" + get_version(), + release=f"romm@{get_version()}", ) path = ( @@ -66,11 +68,11 @@ class EventHandler(FileSystemEventHandler): return if db_platform and db_platform.id in job.args[0]: - log.info(f"Scan already scheduled for {fs_slug}") + log.info(f"Scan already scheduled for {hl(fs_slug)}") return time_delta = timedelta(minutes=RESCAN_ON_FILESYSTEM_CHANGE_DELAY) - rescan_in_msg = f"rescanning in {RESCAN_ON_FILESYSTEM_CHANGE_DELAY} minutes." + rescan_in_msg = f"rescanning in {hl(str(RESCAN_ON_FILESYSTEM_CHANGE_DELAY), color=CYAN)} minutes." # Any change to a platform directory should trigger a full rescan if event.is_directory and event_src.count("/") == 1: @@ -78,7 +80,7 @@ class EventHandler(FileSystemEventHandler): tasks_scheduler.enqueue_in(time_delta, scan_platforms, []) elif db_platform: # Otherwise trigger a rescan for the specific platform - log.info(f"Change detected in {fs_slug} folder, {rescan_in_msg}") + log.info(f"Change detected in {hl(fs_slug)} folder, {rescan_in_msg}") tasks_scheduler.enqueue_in( time_delta, scan_platforms, @@ -93,7 +95,7 @@ if __name__ == "__main__": observer.schedule(EventHandler(), path, recursive=True) observer.start() - log.info(f"Watching {path} for changes") + log.info(f"Watching {hl(path)} for changes") try: while observer.is_alive(): diff --git a/backend/worker.py b/backend/worker.py index 73d2c66ce..2c58fbd87 100644 --- a/backend/worker.py +++ b/backend/worker.py @@ -1,18 +1,19 @@ import sentry_sdk from config import SENTRY_DSN from handler.redis_handler import redis_client +from logger.logger import unify_logger from rq import Queue, Worker from utils import get_version +unify_logger("rq.worker") + listen = ("high", "default", "low") sentry_sdk.init( dsn=SENTRY_DSN, - release="romm@" + get_version(), + release=f"romm@{get_version()}", ) - if __name__ == "__main__": - # Start the worker worker = Worker([Queue(name, connection=redis_client) for name in listen]) worker.work() diff --git a/docker-compose.yml b/docker-compose.yml index 845ff7a50..0f468a6af 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,9 +1,9 @@ # Please see the full example under examples/docker-compose.example.yml services: - romm-mariadb-dev: + romm-db-dev: image: mariadb:11.3.2 - container_name: romm-mariadb-dev + container_name: romm-db-dev restart: unless-stopped env_file: - .env @@ -13,7 +13,7 @@ services: - MARIADB_USER=$DB_USER - MARIADB_PASSWORD=$DB_PASSWD volumes: - - maria-db:/var/lib/mysql + - romm-db-dev:/var/lib/mysql ports: - $DB_PORT:3306 @@ -89,7 +89,7 @@ services: - romm-valkey-dev volumes: - maria-db: + romm-db-dev: postgres-db: authentik-media: authentik-templates: diff --git a/docker/Dockerfile b/docker/Dockerfile index e60efbdaa..fdae438e7 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -146,8 +146,8 @@ COPY --from=frontend-build /front/dist ${WEBSERVER_FOLDER} COPY ./frontend/assets ${WEBSERVER_FOLDER}/assets RUN mkdir -p ${WEBSERVER_FOLDER}/assets/romm && \ - ln -s /romm/resources ${WEBSERVER_FOLDER}/assets/romm/resources && \ - ln -s /romm/assets ${WEBSERVER_FOLDER}/assets/romm/assets + ln -sf /romm/resources ${WEBSERVER_FOLDER}/assets/romm/resources && \ + ln -sf /romm/assets ${WEBSERVER_FOLDER}/assets/romm/assets COPY ./backend /backend @@ -156,6 +156,7 @@ COPY ./docker/init_scripts/* / COPY ./docker/nginx/js/ /etc/nginx/js/ COPY ./docker/nginx/templates/ /etc/nginx/templates/ COPY ./docker/nginx/default.conf /etc/nginx/nginx.conf +COPY ./docker/gunicorn/logging.conf /etc/gunicorn/logging.conf # User permissions # - Create default user `romm` (1000) and group `romm` (1000). diff --git a/docker/build_local_image.sh b/docker/build_local_image.sh index 21805abd8..c7faf3cc4 100755 --- a/docker/build_local_image.sh +++ b/docker/build_local_image.sh @@ -2,4 +2,5 @@ branch_name="$(git symbolic-ref HEAD 2>/dev/null)" branch_name=${branch_name##refs/heads/} -docker build -t "rommapp/romm:local-${branch_name}" . --file ./docker/Dockerfile +branch_name=${branch_name//\//-} # Replace slashes with dashes +docker build -t "rommapp/romm-testing:local-${branch_name}" . --file ./docker/Dockerfile diff --git a/docker/gunicorn/logging.conf b/docker/gunicorn/logging.conf new file mode 100644 index 000000000..5429635ff --- /dev/null +++ b/docker/gunicorn/logging.conf @@ -0,0 +1,39 @@ +[loggers] +keys=root,gunicorn,error + +[handlers] +keys=console_gunicorn + +[formatters] +keys=gunicorn_format + +# Root logger — KEEP but minimal +[logger_root] +level=WARNING +handlers= + +# Gunicorn internal logger +[logger_gunicorn] +level=INFO +handlers=console_gunicorn +qualname=gunicorn +propagate=0 + +# Gunicorn error logger (optional) +[logger_error] +level=ERROR +handlers=console_gunicorn +qualname=gunicorn.error +propagate=0 + +# Handler for Gunicorn logs +[handler_console_gunicorn] +class=StreamHandler +formatter=gunicorn_format +args=(sys.stdout,) + +# Formatter for Gunicorn logs +[formatter_gunicorn_format] +format=INFO: [RomM][gunicorn][%(asctime)s] %(message)s +datefmt=%Y-%m-%d %H:%M:%S + diff --git a/docker/init_scripts/init b/docker/init_scripts/init index 2aaf0638f..2efa012d0 100755 --- a/docker/init_scripts/init +++ b/docker/init_scripts/init @@ -5,39 +5,74 @@ set -o nounset # treat unset variables as an error set -o pipefail # treat errors in pipes as fatal shopt -s inherit_errexit # inherit errexit +LOGLEVEL="${LOGLEVEL:="info"}" + # make it possible to disable the inotify watcher process -ENABLE_RESCAN_ON_FILESYSTEM_CHANGE="${ENABLE_RESCAN_ON_FILESYSTEM_CHANGE:="true"}" +ENABLE_RESCAN_ON_FILESYSTEM_CHANGE="${ENABLE_RESCAN_ON_FILESYSTEM_CHANGE:="false"}" +ENABLE_SCHEDULED_RESCAN="${ENABLE_SCHEDULED_RESCAN:="false"}" +ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB="${ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB:="false"}" -# Set INIT_DEBUG to false if not set by docker env -# (this env var is currently undocumented and usually just needed for development purposes) -INIT_DEBUG="${INIT_DEBUG:="false"}" +# if REDIS_HOST is set, we assume that an external redis is used +REDIS_HOST="${REDIS_HOST:=""}" + +# set DEFAULT_WEB_CONCURRENCY to 1 if not set by docker env to reduce resource usage +# (since backend is almost 100% async this won't block anything) +DEFAULT_WEB_CONCURRENCY=1 + +# logger colors +RED='\033[0;31m' +LIGHTMAGENTA='\033[0;95m' +GREEN='\033[0;32m' +YELLOW='\033[0;33m' +BLUE='\033[0;34m' +CYAN='\033[0;36m' +RESET='\033[0;00m' + +print_banner() { + info_log " _____ __ __ " + info_log ' | __ \ | \/ |' + info_log ' | |__) |___ _ __ ___ | \ / |' + info_log " | _ // _ \\| '_ \` _ \\| |\\/| |" + info_log ' | | \ \ (_) | | | | | | | | |' + info_log ' |_| \_\___/|_| |_| |_|_| |_|' + info_log "" + info_log "The beautiful, powerful, self-hosted Rom manager and player" + info_log "" +} -# print debug log output if enabled debug_log() { - if [[ ${INIT_DEBUG} == "true" ]]; then - echo "DEBUG: [init][$(date +"%Y-%m-%d %T")]" "${@}" || true + # print debug log output if enabled + if [[ ${LOGLEVEL} == "debug" ]]; then + echo -e "${LIGHTMAGENTA}DEBUG: ${BLUE}[RomM]${LIGHTMAGENTA}[init]${CYAN}[$(date +"%Y-%m-%d %T")]${RESET}" "${@}" || true fi } info_log() { - echo "INFO: [init][$(date +"%Y-%m-%d %T")]" "${@}" || true + echo -e "${GREEN}INFO: ${BLUE}[RomM]${LIGHTMAGENTA}[init]${CYAN}[$(date +"%Y-%m-%d %T")]${RESET}" "${@}" || true } warn_log() { - echo "WARNING: [init][$(date +"%Y-%m-%d %T")]" "${@}" || true + echo -e "${YELLOW}WARNING: ${BLUE}[RomM]${LIGHTMAGENTA}[init]${CYAN}[$(date +"%Y-%m-%d %T")]${RESET}" "${@}" || true } error_log() { - echo "ERROR: [init][$(date +"%Y-%m-%d %T")]" "${@}" || true + echo -e "${RED}ERROR: ${BLUE}[RomM]${LIGHTMAGENTA}[init]${CYAN}[$(date +"%Y-%m-%d %T")]${RESET}" "${@}" || true exit 1 } wait_for_gunicorn_socket() { - info_log "waiting for gunicorn socket file..." - while [[ ! -S /tmp/gunicorn.sock ]]; do - sleep 1 + debug_log "Waiting for gunicorn socket file..." + local retries=60 + while [[ ! -S /tmp/gunicorn.sock && retries -gt 0 ]]; do + sleep 0.5 + ((retries--)) done - info_log "gunicorn socket file found" + + if [[ -S /tmp/gunicorn.sock ]]; then + debug_log "Gunicorn socket file found" + else + error_log "Gunicorn socket file not found after waiting 30s" + fi } # function that runs or main process and creates a corresponding PID file, @@ -46,7 +81,7 @@ start_bin_gunicorn() { rm /tmp/gunicorn.sock -f # commands to start our main application and store its PID to check for crashes - info_log "starting gunicorn" + info_log "Starting backend" # TODO: Remove support for GUNICORN_WORKERS in future version. if [[ -n ${GUNICORN_WORKERS-} ]]; then @@ -55,14 +90,15 @@ start_bin_gunicorn() { fi gunicorn \ - --access-logfile - \ - --error-logfile - \ - --worker-class uvicorn.workers.UvicornWorker \ --bind=0.0.0.0:5000 \ --bind=unix:/tmp/gunicorn.sock \ --pid=/tmp/gunicorn.pid \ --forwarded-allow-ips="*" \ - --workers "${WEB_CONCURRENCY:-2}" \ + --worker-class uvicorn.workers.UvicornWorker \ + --workers "${WEB_CONCURRENCY:-${DEFAULT_WEB_CONCURRENCY:-1}}" \ + --error-logfile - \ + --error-logfile - \ + --log-config /etc/gunicorn/logging.conf \ main:app & } @@ -70,31 +106,68 @@ start_bin_gunicorn() { start_bin_nginx() { wait_for_gunicorn_socket - info_log "starting nginx" + info_log "Starting nginx" if [[ ${EUID} -ne 0 ]]; then nginx else # if container runs as root, drop permissions nginx -g 'user romm;' fi + + : "${ROMM_BASE_URL:=http://0.0.0.0:8080}" + info_log "🚀 RomM is now available at ${ROMM_BASE_URL}" } +# Commands to start valkey-server (handling PID creation internally) start_bin_valkey-server() { - info_log "starting valkey-server" - # Check if /usr/local/etc/valkey/valkey.conf exists and use it if so + info_log "Starting internal valkey" + if [[ -f /usr/local/etc/valkey/valkey.conf ]]; then - valkey-server /usr/local/etc/valkey/valkey.conf & + if [[ ${LOGLEVEL} == "debug" ]]; then + valkey-server /usr/local/etc/valkey/valkey.conf & + else + valkey-server /usr/local/etc/valkey/valkey.conf >/dev/null 2>&1 & + fi else - valkey-server --dir /redis-data & + if [[ ${LOGLEVEL} == "debug" ]]; then + valkey-server --dir /redis-data & + else + valkey-server --dir /redis-data >/dev/null 2>&1 & + fi fi + VALKEY_PID=$! echo "${VALKEY_PID}" >/tmp/valkey-server.pid + + local host="127.0.0.1" + local port="6379" + local max_retries=120 + local retry=0 + + debug_log "Waiting for internal valkey to be ready..." + + # Temporarily disable errexit for this part of the script + set +o errexit + + while ((retry < max_retries)); do + # Attempt to check if valkey TCP port is open + if (echo >/dev/tcp/"${host}"/"${port}") 2>/dev/null; then + debug_log "Internal valkey is ready and accepting connections" + set -o errexit # Re-enable errexit after success + return 0 + fi + + sleep 0.5 + ((retry++)) + done + + error_log "Internal valkey did not become ready after $((max_retries * 500))ms" } # function that runs our independent python scripts and creates corresponding PID files, start_python() { SCRIPT="${1}" - info_log "starting ${SCRIPT}.py" + info_log "Starting ${SCRIPT}" python3 "${SCRIPT}.py" & WATCHER_PID=$! echo "${WATCHER_PID}" >"/tmp/${SCRIPT}.pid" @@ -106,9 +179,7 @@ watchdog_process_pid() { if [[ -f "/tmp/${PROCESS}.pid" ]]; then # check if the pid we last wrote to our state file is actually active PID=$(cat "/tmp/${PROCESS}.pid") || true - if [[ -d "/proc/${PID}" ]]; then - debug_log "${PROCESS} still running, no need to start" - else + if [[ ! -d "/proc/${PID}" ]]; then if [[ ${TYPE} == "bin" ]]; then start_bin_"${PROCESS}" elif [[ ${TYPE} == "python" ]]; then @@ -116,6 +187,7 @@ watchdog_process_pid() { fi fi else + # start process if we dont have a corresponding PID file if [[ ${TYPE} == "bin" ]]; then start_bin_"${PROCESS}" elif [[ ${TYPE} == "python" ]]; then @@ -129,7 +201,7 @@ stop_process_pid() { if [[ -f "/tmp/${PROCESS}.pid" ]]; then PID=$(cat "/tmp/${PROCESS}.pid") || true if [[ -d "/proc/${PID}" ]]; then - info_log "stopping ${PROCESS}" + info_log "Stopping ${PROCESS}" kill "${PID}" || true # wait for process exit while [[ -e "/proc/${PID}" ]]; do sleep 0.1; done @@ -147,11 +219,11 @@ shutdown() { stop_process_pid valkey-server } +print_banner + # switch to backend directory cd /backend || { error_log "/backend directory doesn't seem to exist"; } -info_log "Starting up, please wait..." - # setup trap handler exited=0 trap 'exited=1 && shutdown' SIGINT SIGTERM EXIT @@ -159,45 +231,38 @@ trap 'exited=1 && shutdown' SIGINT SIGTERM EXIT # clear any leftover PID files rm /tmp/*.pid -f -# function definition done, lets start our main loop +# Start Valkey server if REDIS_HOST is not set (which would mean user is using an external Redis/Valkey) +if [[ -z ${REDIS_HOST} ]]; then + watchdog_process_pid bin valkey-server +else + warn_log "REDIS_HOST is set, not starting internal valkey-server" +fi + +# Run needed database migrations once at startup +info_log "Running database migrations" +if alembic upgrade head; then + info_log "Database migrations succeeded" +else + error_log "Failed to run database migrations" +fi + +# main loop while ! ((exited)); do - # Start Valkey server if we dont have a corresponding PID file - # and REDIS_HOST is not set (which would mean we're using an external Redis/Valkey) - if [[ -z ${REDIS_HOST:=""} ]]; then - watchdog_process_pid bin valkey-server - fi - - # Run needed database migrations on startup, - # but only if it was not successful since the last full docker container start - if [[ ${ALEMBIC_SUCCESS:="false"} == "false" ]]; then - if alembic upgrade head; then - debug_log "database schema migrations succeeded" - ALEMBIC_SUCCESS="true" - else - error_log "Something went horribly wrong with our database" - fi - else - debug_log "database schema already upgraded during current container lifecycle" - fi - - # Start gunicorn if we dont have a corresponding PID file watchdog_process_pid bin gunicorn - # Start nginx if we dont have a corresponding PID file - watchdog_process_pid bin nginx + watchdog_process_pid python worker - # only start the watcher.py if we actually want to use the rescan on fs change feature + # only start the scheduler if enabled + if [[ ${ENABLE_SCHEDULED_RESCAN} == "true" || ${ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB} == "true" ]]; then + watchdog_process_pid python scheduler + fi + + # only start the watcher if enabled if [[ ${ENABLE_RESCAN_ON_FILESYSTEM_CHANGE} == "true" ]]; then - # Start watcher if we dont have a corresponding PID file watchdog_process_pid python watcher fi - # Start background worker processes - debug_log "Starting worker and scheduler" - # Start worker if we dont have a corresponding PID file - watchdog_process_pid python worker - # Start scheduler if we dont have a corresponding PID file - watchdog_process_pid python scheduler + watchdog_process_pid bin nginx # check for died processes every 5 seconds sleep 5 diff --git a/docker/nginx/default.conf b/docker/nginx/default.conf index 4d487cd21..6ba62366c 100644 --- a/docker/nginx/default.conf +++ b/docker/nginx/default.conf @@ -42,13 +42,33 @@ http { ~T([0-9:]+)\+ $1; } - #INFO: [nginx][2023-11-14 09:20:29] 127.0.0.1 - -"GET / HTTP/1.1" 500 177 "-" "Mozilla/5.0 (X11; Linux x86_64)"rt=0.000 uct="-" uht="-" urt="-" - log_format romm_log 'INFO: [nginx][$date $time] $remote_addr - $remote_user ' - '"$request" $status $body_bytes_sent ' - '"$http_referer" "$http_user_agent" ' - 'rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"'; + # Map to extract the browser name (e.g., Chrome, Firefox, etc.) + map $http_user_agent $browser { + default "Unknown"; + "~Chrome/" "Chrome"; + "~Firefox/" "Firefox"; + "~Safari/" "Safari"; + "~Edge/" "Edge"; + "~Opera/" "Opera"; + } - access_log /dev/stdout romm_log; + # Map to extract the OS (e.g., Windows, MacOS, Linux) + map $http_user_agent $os { + default "Unknown"; + "~Windows NT" "Windows"; + "~Macintosh" "macOS"; + "~Linux" "Linux"; + "~Android" "Android"; + "~iPhone" "iOS"; + } + + #INFO: [nginx][2023-11-14 09:20:29] 127.0.0.1 - -"GET / HTTP/1.1" 500 177 "-" "Mozilla/5.0 (X11; Linux x86_64)"rt=0.000 uct="-" uht="-" urt="-" + log_format romm_logs 'INFO: [RomM][nginx][$date $time] ' + '$remote_addr | $http_x_forwarded_for | ' + '$request_method $request_uri $status | $body_bytes_sent | ' + '$browser $os | $request_time'; + + access_log /dev/stdout romm_logs; error_log /dev/stderr; gzip on; diff --git a/env.template b/env.template index 83a4baca6..4edbc74a5 100644 --- a/env.template +++ b/env.template @@ -1,6 +1,7 @@ ROMM_BASE_PATH=/path/to/romm_mock DEV_MODE=true KIOSK_MODE=false +VITE_ALLOWED_HOSTS=false # Gunicorn (optional) # Workers -> (2 × CPU cores) + 1 @@ -20,6 +21,9 @@ SCREENSCRAPER_PASSWORD= # SteamGridDB STEAMGRIDDB_API_KEY= +# RetroAchievements +RETROACHIEVEMENTS_API_KEY= + # Database config DB_HOST=127.0.0.1 DB_PORT=3306 diff --git a/examples/docker-compose.example.yml b/examples/docker-compose.example.yml index cd039b8b6..d2322fb1a 100644 --- a/examples/docker-compose.example.yml +++ b/examples/docker-compose.example.yml @@ -22,6 +22,7 @@ services: - STEAMGRIDDB_API_KEY= # https://docs.romm.app/latest/Getting-Started/Generate-API-Keys/#steamgriddb - SCREENSCRAPER_USER= # Use your ScreenScraper username and password - SCREENSCRAPER_PASSWORD= # https://docs.romm.app/latest/Getting-Started/Generate-API-Keys/#screenscraper + - RETROACHIEVEMENTS_API_KEY= # https://api-docs.retroachievements.org/#api-access volumes: - romm_resources:/romm/resources # Resources fetched from IGDB (covers, screenshots, etc.) - romm_redis_data:/redis-data # Cached data for background tasks diff --git a/frontend/assets/scrappers/ra.png b/frontend/assets/scrappers/ra.png new file mode 100644 index 000000000..551e514ad Binary files /dev/null and b/frontend/assets/scrappers/ra.png differ diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 65bfbb333..50d8a6a1b 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -12,6 +12,7 @@ "@mdi/font": "7.4.47", "axios": "^1.8.4", "cronstrue": "^2.57.0", + "date-fns": "^4.1.0", "js-cookie": "^3.0.5", "lodash": "^4.17.21", "md-editor-v3": "^5.5.0", @@ -43,7 +44,7 @@ "openapi-typescript-codegen": "^0.29.0", "typescript": "^5.7.3", "typescript-eslint": "^8.28.0", - "vite": "^6.2.6", + "vite": "^6.3.4", "vite-plugin-pwa": "^0.21.1", "vite-plugin-vuetify": "^2.0.4", "vue-tsc": "^2.2.8" @@ -2916,228 +2917,260 @@ } }, "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.34.2.tgz", - "integrity": "sha512-6Fyg9yQbwJR+ykVdT9sid1oc2ewejS6h4wzQltmJfSW53N60G/ah9pngXGANdy9/aaE/TcUFpWosdm7JXS1WTQ==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.40.1.tgz", + "integrity": "sha512-kxz0YeeCrRUHz3zyqvd7n+TVRlNyTifBsmnmNPtk3hQURUyG9eAB+usz6DAwagMusjx/zb3AjvDUvhFGDAexGw==", "cpu": [ "arm" ], + "license": "MIT", "optional": true, "os": [ "android" ] }, "node_modules/@rollup/rollup-android-arm64": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.34.2.tgz", - "integrity": "sha512-K5GfWe+vtQ3kyEbihrimM38UgX57UqHp+oME7X/EX9Im6suwZfa7Hsr8AtzbJvukTpwMGs+4s29YMSO3rwWtsw==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.40.1.tgz", + "integrity": "sha512-PPkxTOisoNC6TpnDKatjKkjRMsdaWIhyuMkA4UsBXT9WEZY4uHezBTjs6Vl4PbqQQeu6oION1w2voYZv9yquCw==", "cpu": [ "arm64" ], + "license": "MIT", "optional": true, "os": [ "android" ] }, "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.34.2.tgz", - "integrity": "sha512-PSN58XG/V/tzqDb9kDGutUruycgylMlUE59f40ny6QIRNsTEIZsrNQTJKUN2keMMSmlzgunMFqyaGLmly39sug==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.40.1.tgz", + "integrity": "sha512-VWXGISWFY18v/0JyNUy4A46KCFCb9NVsH+1100XP31lud+TzlezBbz24CYzbnA4x6w4hx+NYCXDfnvDVO6lcAA==", "cpu": [ "arm64" ], + "license": "MIT", "optional": true, "os": [ "darwin" ] }, "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.34.2.tgz", - "integrity": "sha512-gQhK788rQJm9pzmXyfBB84VHViDERhAhzGafw+E5mUpnGKuxZGkMVDa3wgDFKT6ukLC5V7QTifzsUKdNVxp5qQ==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.40.1.tgz", + "integrity": "sha512-nIwkXafAI1/QCS7pxSpv/ZtFW6TXcNUEHAIA9EIyw5OzxJZQ1YDrX+CL6JAIQgZ33CInl1R6mHet9Y/UZTg2Bw==", "cpu": [ "x64" ], + "license": "MIT", "optional": true, "os": [ "darwin" ] }, "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.34.2.tgz", - "integrity": "sha512-eiaHgQwGPpxLC3+zTAcdKl4VsBl3r0AiJOd1Um/ArEzAjN/dbPK1nROHrVkdnoE6p7Svvn04w3f/jEZSTVHunA==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.40.1.tgz", + "integrity": "sha512-BdrLJ2mHTrIYdaS2I99mriyJfGGenSaP+UwGi1kB9BLOCu9SR8ZpbkmmalKIALnRw24kM7qCN0IOm6L0S44iWw==", "cpu": [ "arm64" ], + "license": "MIT", "optional": true, "os": [ "freebsd" ] }, "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.34.2.tgz", - "integrity": "sha512-lhdiwQ+jf8pewYOTG4bag0Qd68Jn1v2gO1i0mTuiD+Qkt5vNfHVK/jrT7uVvycV8ZchlzXp5HDVmhpzjC6mh0g==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.40.1.tgz", + "integrity": "sha512-VXeo/puqvCG8JBPNZXZf5Dqq7BzElNJzHRRw3vjBE27WujdzuOPecDPc/+1DcdcTptNBep3861jNq0mYkT8Z6Q==", "cpu": [ "x64" ], + "license": "MIT", "optional": true, "os": [ "freebsd" ] }, "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.34.2.tgz", - "integrity": "sha512-lfqTpWjSvbgQP1vqGTXdv+/kxIznKXZlI109WkIFPbud41bjigjNmOAAKoazmRGx+k9e3rtIdbq2pQZPV1pMig==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.40.1.tgz", + "integrity": "sha512-ehSKrewwsESPt1TgSE/na9nIhWCosfGSFqv7vwEtjyAqZcvbGIg4JAcV7ZEh2tfj/IlfBeZjgOXm35iOOjadcg==", "cpu": [ "arm" ], + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.34.2.tgz", - "integrity": "sha512-RGjqULqIurqqv+NJTyuPgdZhka8ImMLB32YwUle2BPTDqDoXNgwFjdjQC59FbSk08z0IqlRJjrJ0AvDQ5W5lpw==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.40.1.tgz", + "integrity": "sha512-m39iO/aaurh5FVIu/F4/Zsl8xppd76S4qoID8E+dSRQvTyZTOI2gVk3T4oqzfq1PtcvOfAVlwLMK3KRQMaR8lg==", "cpu": [ "arm" ], + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.34.2.tgz", - "integrity": "sha512-ZvkPiheyXtXlFqHpsdgscx+tZ7hoR59vOettvArinEspq5fxSDSgfF+L5wqqJ9R4t+n53nyn0sKxeXlik7AY9Q==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.40.1.tgz", + "integrity": "sha512-Y+GHnGaku4aVLSgrT0uWe2o2Rq8te9hi+MwqGF9r9ORgXhmHK5Q71N757u0F8yU1OIwUIFy6YiJtKjtyktk5hg==", "cpu": [ "arm64" ], + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.34.2.tgz", - "integrity": "sha512-UlFk+E46TZEoxD9ufLKDBzfSG7Ki03fo6hsNRRRHF+KuvNZ5vd1RRVQm8YZlGsjcJG8R252XFK0xNPay+4WV7w==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.40.1.tgz", + "integrity": "sha512-jEwjn3jCA+tQGswK3aEWcD09/7M5wGwc6+flhva7dsQNRZZTe30vkalgIzV4tjkopsTS9Jd7Y1Bsj6a4lzz8gQ==", "cpu": [ "arm64" ], + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-linux-loongarch64-gnu": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.34.2.tgz", - "integrity": "sha512-hJhfsD9ykx59jZuuoQgYT1GEcNNi3RCoEmbo5OGfG8RlHOiVS7iVNev9rhLKh7UBYq409f4uEw0cclTXx8nh8Q==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.40.1.tgz", + "integrity": "sha512-ySyWikVhNzv+BV/IDCsrraOAZ3UaC8SZB67FZlqVwXwnFhPihOso9rPOxzZbjp81suB1O2Topw+6Ug3JNegejQ==", "cpu": [ "loong64" ], + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.34.2.tgz", - "integrity": "sha512-g/O5IpgtrQqPegvqopvmdCF9vneLE7eqYfdPWW8yjPS8f63DNam3U4ARL1PNNB64XHZDHKpvO2Giftf43puB8Q==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.40.1.tgz", + "integrity": "sha512-BvvA64QxZlh7WZWqDPPdt0GH4bznuL6uOO1pmgPnnv86rpUpc8ZxgZwcEgXvo02GRIZX1hQ0j0pAnhwkhwPqWg==", "cpu": [ "ppc64" ], + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.34.2.tgz", - "integrity": "sha512-bSQijDC96M6PuooOuXHpvXUYiIwsnDmqGU8+br2U7iPoykNi9JtMUpN7K6xml29e0evK0/g0D1qbAUzWZFHY5Q==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.40.1.tgz", + "integrity": "sha512-EQSP+8+1VuSulm9RKSMKitTav89fKbHymTf25n5+Yr6gAPZxYWpj3DzAsQqoaHAk9YX2lwEyAf9S4W8F4l3VBQ==", "cpu": [ "riscv64" ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.40.1.tgz", + "integrity": "sha512-n/vQ4xRZXKuIpqukkMXZt9RWdl+2zgGNx7Uda8NtmLJ06NL8jiHxUawbwC+hdSq1rrw/9CghCpEONor+l1e2gA==", + "cpu": [ + "riscv64" + ], + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.34.2.tgz", - "integrity": "sha512-49TtdeVAsdRuiUHXPrFVucaP4SivazetGUVH8CIxVsNsaPHV4PFkpLmH9LeqU/R4Nbgky9lzX5Xe1NrzLyraVA==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.40.1.tgz", + "integrity": "sha512-h8d28xzYb98fMQKUz0w2fMc1XuGzLLjdyxVIbhbil4ELfk5/orZlSTpF/xdI9C8K0I8lCkq+1En2RJsawZekkg==", "cpu": [ "s390x" ], + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.34.2.tgz", - "integrity": "sha512-j+jFdfOycLIQ7FWKka9Zd3qvsIyugg5LeZuHF6kFlXo6MSOc6R1w37YUVy8VpAKd81LMWGi5g9J25P09M0SSIw==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.40.1.tgz", + "integrity": "sha512-XiK5z70PEFEFqcNj3/zRSz/qX4bp4QIraTy9QjwJAb/Z8GM7kVUsD0Uk8maIPeTyPCP03ChdI+VVmJriKYbRHQ==", "cpu": [ "x64" ], + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.34.2.tgz", - "integrity": "sha512-aDPHyM/D2SpXfSNCVWCxyHmOqN9qb7SWkY1+vaXqMNMXslZYnwh9V/UCudl6psyG0v6Ukj7pXanIpfZwCOEMUg==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.40.1.tgz", + "integrity": "sha512-2BRORitq5rQ4Da9blVovzNCMaUlyKrzMSvkVR0D4qPuOy/+pMCrh1d7o01RATwVy+6Fa1WBw+da7QPeLWU/1mQ==", "cpu": [ "x64" ], + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.34.2.tgz", - "integrity": "sha512-LQRkCyUBnAo7r8dbEdtNU08EKLCJMgAk2oP5H3R7BnUlKLqgR3dUjrLBVirmc1RK6U6qhtDw29Dimeer8d5hzQ==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.40.1.tgz", + "integrity": "sha512-b2bcNm9Kbde03H+q+Jjw9tSfhYkzrDUf2d5MAd1bOJuVplXvFhWz7tRtWvD8/ORZi7qSCy0idW6tf2HgxSXQSg==", "cpu": [ "arm64" ], + "license": "MIT", "optional": true, "os": [ "win32" ] }, "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.34.2.tgz", - "integrity": "sha512-wt8OhpQUi6JuPFkm1wbVi1BByeag87LDFzeKSXzIdGcX4bMLqORTtKxLoCbV57BHYNSUSOKlSL4BYYUghainYA==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.40.1.tgz", + "integrity": "sha512-DfcogW8N7Zg7llVEfpqWMZcaErKfsj9VvmfSyRjCyo4BI3wPEfrzTtJkZG6gKP/Z92wFm6rz2aDO7/JfiR/whA==", "cpu": [ "ia32" ], + "license": "MIT", "optional": true, "os": [ "win32" ] }, "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.34.2.tgz", - "integrity": "sha512-rUrqINax0TvrPBXrFKg0YbQx18NpPN3NNrgmaao9xRNbTwek7lOXObhx8tQy8gelmQ/gLaGy1WptpU2eKJZImg==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.40.1.tgz", + "integrity": "sha512-ECyOuDeH3C1I8jH2MK1RtBJW+YPMvSfT0a5NN0nHfQYnDSJ6tUiZH3gzwVP5/Kfh/+Tt7tpWVF9LXNTnhTJ3kA==", "cpu": [ "x64" ], + "license": "MIT", "optional": true, "os": [ "win32" @@ -3181,10 +3214,11 @@ } }, "node_modules/@types/estree": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", - "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==", - "devOptional": true + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.7.tgz", + "integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==", + "devOptional": true, + "license": "MIT" }, "node_modules/@types/js-cookie": { "version": "3.0.6", @@ -4363,6 +4397,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/date-fns": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz", + "integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/kossnocorp" + } + }, "node_modules/de-indent": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/de-indent/-/de-indent-1.0.2.tgz", @@ -6244,9 +6288,10 @@ "dev": true }, "node_modules/lru-cache": { - "version": "11.0.2", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.0.2.tgz", - "integrity": "sha512-123qHRfJBmo2jXDbo/a5YOQrJoHF/GNQTLzQ5+IdK5pWpceK17yRc6ozlWd25FxvGKQbIUs91fDFkXmDHTKcyA==", + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.1.0.tgz", + "integrity": "sha512-QIXZUBJUx+2zHUdQujWejBkcD9+cs94tLn0+YL8UrCh+D5sCXZ4c7LaEH48pNwRY3MLDgqUFyhlCyjJPf1WP0A==", + "license": "ISC", "engines": { "node": "20 || >=22" } @@ -6255,6 +6300,7 @@ "version": "0.453.0", "resolved": "https://registry.npmjs.org/lucide-vue-next/-/lucide-vue-next-0.453.0.tgz", "integrity": "sha512-5zmv83vxAs9SVoe22veDBi8Dw0Fh2F+oTngWgKnKOkrZVbZjceXLQ3tescV2boB0zlaf9R2Sd9RuUP2766xvsQ==", + "license": "ISC", "peerDependencies": { "vue": ">=3.0.1" } @@ -7074,12 +7120,13 @@ "license": "MIT" }, "node_modules/rollup": { - "version": "4.34.2", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.34.2.tgz", - "integrity": "sha512-sBDUoxZEaqLu9QeNalL8v3jw6WjPku4wfZGyTU7l7m1oC+rpRihXc/n/H+4148ZkGz5Xli8CHMns//fFGKvpIQ==", + "version": "4.40.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.40.1.tgz", + "integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==", "devOptional": true, + "license": "MIT", "dependencies": { - "@types/estree": "1.0.6" + "@types/estree": "1.0.7" }, "bin": { "rollup": "dist/bin/rollup" @@ -7089,25 +7136,26 @@ "npm": ">=8.0.0" }, "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.34.2", - "@rollup/rollup-android-arm64": "4.34.2", - "@rollup/rollup-darwin-arm64": "4.34.2", - "@rollup/rollup-darwin-x64": "4.34.2", - "@rollup/rollup-freebsd-arm64": "4.34.2", - "@rollup/rollup-freebsd-x64": "4.34.2", - "@rollup/rollup-linux-arm-gnueabihf": "4.34.2", - "@rollup/rollup-linux-arm-musleabihf": "4.34.2", - "@rollup/rollup-linux-arm64-gnu": "4.34.2", - "@rollup/rollup-linux-arm64-musl": "4.34.2", - "@rollup/rollup-linux-loongarch64-gnu": "4.34.2", - "@rollup/rollup-linux-powerpc64le-gnu": "4.34.2", - "@rollup/rollup-linux-riscv64-gnu": "4.34.2", - "@rollup/rollup-linux-s390x-gnu": "4.34.2", - "@rollup/rollup-linux-x64-gnu": "4.34.2", - "@rollup/rollup-linux-x64-musl": "4.34.2", - "@rollup/rollup-win32-arm64-msvc": "4.34.2", - "@rollup/rollup-win32-ia32-msvc": "4.34.2", - "@rollup/rollup-win32-x64-msvc": "4.34.2", + "@rollup/rollup-android-arm-eabi": "4.40.1", + "@rollup/rollup-android-arm64": "4.40.1", + "@rollup/rollup-darwin-arm64": "4.40.1", + "@rollup/rollup-darwin-x64": "4.40.1", + "@rollup/rollup-freebsd-arm64": "4.40.1", + "@rollup/rollup-freebsd-x64": "4.40.1", + "@rollup/rollup-linux-arm-gnueabihf": "4.40.1", + "@rollup/rollup-linux-arm-musleabihf": "4.40.1", + "@rollup/rollup-linux-arm64-gnu": "4.40.1", + "@rollup/rollup-linux-arm64-musl": "4.40.1", + "@rollup/rollup-linux-loongarch64-gnu": "4.40.1", + "@rollup/rollup-linux-powerpc64le-gnu": "4.40.1", + "@rollup/rollup-linux-riscv64-gnu": "4.40.1", + "@rollup/rollup-linux-riscv64-musl": "4.40.1", + "@rollup/rollup-linux-s390x-gnu": "4.40.1", + "@rollup/rollup-linux-x64-gnu": "4.40.1", + "@rollup/rollup-linux-x64-musl": "4.40.1", + "@rollup/rollup-win32-arm64-msvc": "4.40.1", + "@rollup/rollup-win32-ia32-msvc": "4.40.1", + "@rollup/rollup-win32-x64-msvc": "4.40.1", "fsevents": "~2.3.2" } }, @@ -7714,23 +7762,28 @@ "devOptional": true }, "node_modules/tinyglobby": { - "version": "0.2.10", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.10.tgz", - "integrity": "sha512-Zc+8eJlFMvgatPZTl6A9L/yht8QqdmUNtURHaKZLmKBE12hNPSrqNkUp2cs3M/UKmNVVAMFQYSjYIVHDjW5zew==", - "dev": true, + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.13.tgz", + "integrity": "sha512-mEwzpUgrLySlveBwEVDMKk5B57bhLPYovRfPAXD5gA/98Opn0rCDj3GtLwFvCvH5RK9uPCExUROW5NjDwvqkxw==", + "devOptional": true, + "license": "MIT", "dependencies": { - "fdir": "^6.4.2", + "fdir": "^6.4.4", "picomatch": "^4.0.2" }, "engines": { "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" } }, "node_modules/tinyglobby/node_modules/fdir": { - "version": "6.4.3", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.3.tgz", - "integrity": "sha512-PMXmW2y1hDDfTSRc9gaXIuCCRpuoz3Kaz8cUelp3smouvfT632ozg2vrT6lJsHKKOF59YLbOGfAWGUcKEfRMQw==", - "dev": true, + "version": "6.4.4", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.4.tgz", + "integrity": "sha512-1NZP+GK4GfuAv3PqKvxQRDMjdSRZjnkq7KfhlNrCNNlZ0ygQFpebfrnfnq/W7fpUnAv9aGWmY1zKx7FYL3gwhg==", + "devOptional": true, + "license": "MIT", "peerDependencies": { "picomatch": "^3 || ^4" }, @@ -7744,7 +7797,8 @@ "version": "4.0.2", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz", "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", - "dev": true, + "devOptional": true, + "license": "MIT", "engines": { "node": ">=12" }, @@ -8081,15 +8135,18 @@ "dev": true }, "node_modules/vite": { - "version": "6.2.6", - "resolved": "https://registry.npmjs.org/vite/-/vite-6.2.6.tgz", - "integrity": "sha512-9xpjNl3kR4rVDZgPNdTL0/c6ao4km69a/2ihNQbcANz8RuCOK3hQBmLSJf3bRKVQjVMda+YvizNE8AwvogcPbw==", + "version": "6.3.4", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.3.4.tgz", + "integrity": "sha512-BiReIiMS2fyFqbqNT/Qqt4CVITDU9M9vE+DKcVAsB+ZV0wvTKd+3hMbkpxz1b+NmEDMegpVbisKiAZOnvO92Sw==", "devOptional": true, "license": "MIT", "dependencies": { "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", "postcss": "^8.5.3", - "rollup": "^4.30.1" + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" }, "bin": { "vite": "bin/vite.js" @@ -8201,6 +8258,34 @@ "vuetify": "^3.0.0" } }, + "node_modules/vite/node_modules/fdir": { + "version": "6.4.4", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.4.tgz", + "integrity": "sha512-1NZP+GK4GfuAv3PqKvxQRDMjdSRZjnkq7KfhlNrCNNlZ0ygQFpebfrnfnq/W7fpUnAv9aGWmY1zKx7FYL3gwhg==", + "devOptional": true, + "license": "MIT", + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/vite/node_modules/picomatch": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz", + "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/vscode-uri": { "version": "3.0.8", "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.0.8.tgz", diff --git a/frontend/package.json b/frontend/package.json index 4df6ead69..b2c3af0e7 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -30,6 +30,7 @@ "@mdi/font": "7.4.47", "axios": "^1.8.4", "cronstrue": "^2.57.0", + "date-fns": "^4.1.0", "js-cookie": "^3.0.5", "lodash": "^4.17.21", "md-editor-v3": "^5.5.0", @@ -61,7 +62,7 @@ "openapi-typescript-codegen": "^0.29.0", "typescript": "^5.7.3", "typescript-eslint": "^8.28.0", - "vite": "^6.2.6", + "vite": "^6.3.4", "vite-plugin-pwa": "^0.21.1", "vite-plugin-vuetify": "^2.0.4", "vue-tsc": "^2.2.8" diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index f355aee5b..76dc9a4be 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -6,6 +6,9 @@ export type { AddFirmwareResponse } from './models/AddFirmwareResponse'; export type { Body_add_collection_api_collections_post } from './models/Body_add_collection_api_collections_post'; export type { Body_add_firmware_api_firmware_post } from './models/Body_add_firmware_api_firmware_post'; +export type { Body_create_user_from_invite_api_users_register_post } from './models/Body_create_user_from_invite_api_users_register_post'; +export type { Body_request_password_reset_api_forgot_password_post } from './models/Body_request_password_reset_api_forgot_password_post'; +export type { Body_reset_password_api_reset_password_post } from './models/Body_reset_password_api_reset_password_post'; export type { Body_token_api_token_post } from './models/Body_token_api_token_post'; export type { Body_update_collection_api_collections__id__put } from './models/Body_update_collection_api_collections__id__put'; export type { Body_update_rom_api_roms__id__put } from './models/Body_update_rom_api_roms__id__put'; @@ -14,6 +17,7 @@ export type { CollectionSchema } from './models/CollectionSchema'; export type { ConfigResponse } from './models/ConfigResponse'; export type { CustomLimitOffsetPage_SimpleRomSchema_ } from './models/CustomLimitOffsetPage_SimpleRomSchema_'; export type { DetailedRomSchema } from './models/DetailedRomSchema'; +export type { EarnedAchievement } from './models/EarnedAchievement'; export type { EmulationDict } from './models/EmulationDict'; export type { FilesystemDict } from './models/FilesystemDict'; export type { FirmwareSchema } from './models/FirmwareSchema'; @@ -23,17 +27,22 @@ export type { HTTPValidationError } from './models/HTTPValidationError'; export type { IGDBAgeRating } from './models/IGDBAgeRating'; export type { IGDBMetadataPlatform } from './models/IGDBMetadataPlatform'; export type { IGDBRelatedGame } from './models/IGDBRelatedGame'; +export type { InviteLinkSchema } from './models/InviteLinkSchema'; export type { MessageResponse } from './models/MessageResponse'; export type { MetadataSourcesDict } from './models/MetadataSourcesDict'; export type { MobyMetadataPlatform } from './models/MobyMetadataPlatform'; export type { OIDCDict } from './models/OIDCDict'; export type { PlatformSchema } from './models/PlatformSchema'; +export type { RAGameRomAchievement } from './models/RAGameRomAchievement'; +export type { RAProgression } from './models/RAProgression'; +export type { RAUserGameProgression } from './models/RAUserGameProgression'; export type { Role } from './models/Role'; export type { RomFileCategory } from './models/RomFileCategory'; export type { RomFileSchema } from './models/RomFileSchema'; export type { RomIGDBMetadata } from './models/RomIGDBMetadata'; export type { RomMetadataSchema } from './models/RomMetadataSchema'; export type { RomMobyMetadata } from './models/RomMobyMetadata'; +export type { RomRAMetadata } from './models/RomRAMetadata'; export type { RomSSMetadata } from './models/RomSSMetadata'; export type { RomUserSchema } from './models/RomUserSchema'; export type { RomUserStatus } from './models/RomUserStatus'; diff --git a/frontend/src/__generated__/models/Body_create_user_from_invite_api_users_register_post.ts b/frontend/src/__generated__/models/Body_create_user_from_invite_api_users_register_post.ts new file mode 100644 index 000000000..801608c5c --- /dev/null +++ b/frontend/src/__generated__/models/Body_create_user_from_invite_api_users_register_post.ts @@ -0,0 +1,11 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +export type Body_create_user_from_invite_api_users_register_post = { + username: string; + email: string; + password: string; + token: string; +}; + diff --git a/frontend/src/__generated__/models/Body_request_password_reset_api_forgot_password_post.ts b/frontend/src/__generated__/models/Body_request_password_reset_api_forgot_password_post.ts new file mode 100644 index 000000000..0b3957b5a --- /dev/null +++ b/frontend/src/__generated__/models/Body_request_password_reset_api_forgot_password_post.ts @@ -0,0 +1,8 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +export type Body_request_password_reset_api_forgot_password_post = { + username: string; +}; + diff --git a/frontend/src/__generated__/models/Body_reset_password_api_reset_password_post.ts b/frontend/src/__generated__/models/Body_reset_password_api_reset_password_post.ts new file mode 100644 index 000000000..e261c4d61 --- /dev/null +++ b/frontend/src/__generated__/models/Body_reset_password_api_reset_password_post.ts @@ -0,0 +1,9 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +export type Body_reset_password_api_reset_password_post = { + token: string; + new_password: string; +}; + diff --git a/frontend/src/__generated__/models/DetailedRomSchema.ts b/frontend/src/__generated__/models/DetailedRomSchema.ts index 05829fbdf..0a31860b9 100644 --- a/frontend/src/__generated__/models/DetailedRomSchema.ts +++ b/frontend/src/__generated__/models/DetailedRomSchema.ts @@ -7,6 +7,7 @@ import type { RomFileSchema } from './RomFileSchema'; import type { RomIGDBMetadata } from './RomIGDBMetadata'; import type { RomMetadataSchema } from './RomMetadataSchema'; import type { RomMobyMetadata } from './RomMobyMetadata'; +import type { RomRAMetadata } from './RomRAMetadata'; import type { RomSSMetadata } from './RomSSMetadata'; import type { RomUserSchema } from './RomUserSchema'; import type { SaveSchema } from './SaveSchema'; @@ -20,6 +21,7 @@ export type DetailedRomSchema = { sgdb_id: (number | null); moby_id: (number | null); ss_id: (number | null); + ra_id: (number | null); platform_id: number; platform_slug: string; platform_fs_slug: string; @@ -60,6 +62,7 @@ export type DetailedRomSchema = { full_path: string; created_at: string; updated_at: string; + merged_ra_metadata: (RomRAMetadata | null); merged_screenshots: Array; siblings: Array; rom_user: RomUserSchema; diff --git a/frontend/src/__generated__/models/EarnedAchievement.ts b/frontend/src/__generated__/models/EarnedAchievement.ts new file mode 100644 index 000000000..740d5ecbe --- /dev/null +++ b/frontend/src/__generated__/models/EarnedAchievement.ts @@ -0,0 +1,9 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +export type EarnedAchievement = { + id: string; + date: string; +}; + diff --git a/frontend/src/__generated__/models/InviteLinkSchema.ts b/frontend/src/__generated__/models/InviteLinkSchema.ts new file mode 100644 index 000000000..c1106520a --- /dev/null +++ b/frontend/src/__generated__/models/InviteLinkSchema.ts @@ -0,0 +1,8 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +export type InviteLinkSchema = { + token: string; +}; + diff --git a/frontend/src/__generated__/models/MetadataSourcesDict.ts b/frontend/src/__generated__/models/MetadataSourcesDict.ts index 881d6fd15..9515ae62f 100644 --- a/frontend/src/__generated__/models/MetadataSourcesDict.ts +++ b/frontend/src/__generated__/models/MetadataSourcesDict.ts @@ -8,5 +8,6 @@ export type MetadataSourcesDict = { MOBY_API_ENABLED: boolean; SS_API_ENABLED: boolean; STEAMGRIDDB_ENABLED: boolean; + RA_ENABLED: boolean; }; diff --git a/frontend/src/__generated__/models/PlatformSchema.ts b/frontend/src/__generated__/models/PlatformSchema.ts index 8a4d180bb..86120701e 100644 --- a/frontend/src/__generated__/models/PlatformSchema.ts +++ b/frontend/src/__generated__/models/PlatformSchema.ts @@ -14,6 +14,7 @@ export type PlatformSchema = { sgdb_id?: (number | null); moby_id?: (number | null); ss_id?: (number | null); + ra_id?: (number | null); category?: (string | null); generation?: (number | null); family_name?: (string | null); diff --git a/frontend/src/__generated__/models/RAGameRomAchievement.ts b/frontend/src/__generated__/models/RAGameRomAchievement.ts new file mode 100644 index 000000000..a2f1b8717 --- /dev/null +++ b/frontend/src/__generated__/models/RAGameRomAchievement.ts @@ -0,0 +1,20 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +export type RAGameRomAchievement = { + ra_id: (number | null); + title: (string | null); + description: (string | null); + points: (number | null); + num_awarded: (number | null); + num_awarded_hardcore: (number | null); + badge_id: (string | null); + badge_url_lock: (string | null); + badge_path_lock: (string | null); + badge_url: (string | null); + badge_path: (string | null); + display_order: (number | null); + type: (string | null); +}; + diff --git a/frontend/src/__generated__/models/RAProgression.ts b/frontend/src/__generated__/models/RAProgression.ts new file mode 100644 index 000000000..18a18bbd2 --- /dev/null +++ b/frontend/src/__generated__/models/RAProgression.ts @@ -0,0 +1,11 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +import type { RAUserGameProgression } from './RAUserGameProgression'; +export type RAProgression = { + count?: number; + total?: number; + results?: Array; +}; + diff --git a/frontend/src/__generated__/models/RAUserGameProgression.ts b/frontend/src/__generated__/models/RAUserGameProgression.ts new file mode 100644 index 000000000..0d234ea50 --- /dev/null +++ b/frontend/src/__generated__/models/RAUserGameProgression.ts @@ -0,0 +1,13 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +import type { EarnedAchievement } from './EarnedAchievement'; +export type RAUserGameProgression = { + rom_ra_id: (number | null); + max_possible: (number | null); + num_awarded: (number | null); + num_awarded_hardcore: (number | null); + earned_achievements: Array; +}; + diff --git a/frontend/src/__generated__/models/RomRAMetadata.ts b/frontend/src/__generated__/models/RomRAMetadata.ts new file mode 100644 index 000000000..e85a45df7 --- /dev/null +++ b/frontend/src/__generated__/models/RomRAMetadata.ts @@ -0,0 +1,9 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +import type { RAGameRomAchievement } from './RAGameRomAchievement'; +export type RomRAMetadata = { + achievements?: Array; +}; + diff --git a/frontend/src/__generated__/models/SimpleRomSchema.ts b/frontend/src/__generated__/models/SimpleRomSchema.ts index bad3fcd36..da57242e9 100644 --- a/frontend/src/__generated__/models/SimpleRomSchema.ts +++ b/frontend/src/__generated__/models/SimpleRomSchema.ts @@ -15,6 +15,7 @@ export type SimpleRomSchema = { sgdb_id: (number | null); moby_id: (number | null); ss_id: (number | null); + ra_id: (number | null); platform_id: number; platform_slug: string; platform_fs_slug: string; diff --git a/frontend/src/__generated__/models/StatsReturn.ts b/frontend/src/__generated__/models/StatsReturn.ts index 323d7485d..260cddc69 100644 --- a/frontend/src/__generated__/models/StatsReturn.ts +++ b/frontend/src/__generated__/models/StatsReturn.ts @@ -8,6 +8,6 @@ export type StatsReturn = { SAVES: number; STATES: number; SCREENSHOTS: number; - FILESIZE: number; + TOTAL_FILESIZE_BYTES: number; }; diff --git a/frontend/src/__generated__/models/UserSchema.ts b/frontend/src/__generated__/models/UserSchema.ts index cb1585222..f5c8b1fb2 100644 --- a/frontend/src/__generated__/models/UserSchema.ts +++ b/frontend/src/__generated__/models/UserSchema.ts @@ -2,6 +2,7 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ +import type { RAProgression } from './RAProgression'; import type { Role } from './Role'; export type UserSchema = { id: number; @@ -13,6 +14,8 @@ export type UserSchema = { avatar_path: string; last_login: (string | null); last_active: (string | null); + ra_username?: (string | null); + ra_progression?: (RAProgression | null); created_at: string; updated_at: string; }; diff --git a/frontend/src/components/Details/ActionBar.vue b/frontend/src/components/Details/ActionBar.vue index ad2782659..2e1d085b2 100644 --- a/frontend/src/components/Details/ActionBar.vue +++ b/frontend/src/components/Details/ActionBar.vue @@ -79,6 +79,7 @@ async function copyDownloadLink(rom: DetailedRom) { fileIDs: downloadStore.fileIDsToDownload, }) " + :aria-label="`Download ${rom.name}`" > - + @@ -120,6 +126,7 @@ async function copyDownloadLink(rom: DetailedRom) { params: { rom: rom?.id }, }) " + :aria-label="`Play ${rom.name}`" > @@ -127,6 +134,7 @@ async function copyDownloadLink(rom: DetailedRom) { v-if="is3DSRom" class="flex-grow-1" @click="emitter?.emit('showQRCodeDialog', rom)" + :aria-label="`Show ${rom.name} QR code`" > @@ -139,7 +147,11 @@ async function copyDownloadLink(rom: DetailedRom) { location="bottom" > diff --git a/frontend/src/components/Details/GameData.vue b/frontend/src/components/Details/GameData.vue new file mode 100644 index 000000000..eefe616cd --- /dev/null +++ b/frontend/src/components/Details/GameData.vue @@ -0,0 +1,49 @@ + + diff --git a/frontend/src/components/Details/Info/FileInfo.vue b/frontend/src/components/Details/Info/FileInfo.vue index a82cfb510..476fa731f 100644 --- a/frontend/src/components/Details/Info/FileInfo.vue +++ b/frontend/src/components/Details/Info/FileInfo.vue @@ -153,7 +153,7 @@ watch( - + diff --git a/frontend/src/components/Details/Info/GameInfo.vue b/frontend/src/components/Details/Info/GameInfo.vue index 30cbd4334..3fcc1d2f7 100644 --- a/frontend/src/components/Details/Info/GameInfo.vue +++ b/frontend/src/components/Details/Info/GameInfo.vue @@ -129,7 +129,7 @@ function onFilterClick(filter: FilterType, value: string) { +import RetroAchievements from "@/components/Details/RetroAchievements.vue"; +import RSection from "@/components/common/RSection.vue"; import romApi from "@/services/api/rom"; import storeAuth from "@/stores/auth"; import type { DetailedRom } from "@/stores/roms"; @@ -14,9 +16,10 @@ import { storeToRefs } from "pinia"; // Props const { t } = useI18n(); const props = defineProps<{ rom: DetailedRom }>(); +const tab = ref<"status" | "ra" | "notes">("status"); const auth = storeAuth(); const theme = useTheme(); -const { mdAndUp, smAndDown } = useDisplay(); +const { mdAndUp, mdAndDown, smAndDown } = useDisplay(); const { scopes } = storeToRefs(auth); const editingNote = ref(false); const romUser = ref(props.rom.rom_user); @@ -66,259 +69,300 @@ watch( diff --git a/frontend/src/components/Details/Saves.vue b/frontend/src/components/Details/Saves.vue index a93091ea5..fff790fd6 100644 --- a/frontend/src/components/Details/Saves.vue +++ b/frontend/src/components/Details/Saves.vue @@ -1,13 +1,14 @@ diff --git a/frontend/src/components/Details/States.vue b/frontend/src/components/Details/States.vue index deac5df0f..dd5c99313 100644 --- a/frontend/src/components/Details/States.vue +++ b/frontend/src/components/Details/States.vue @@ -1,4 +1,5 @@ diff --git a/frontend/src/components/Details/Title.vue b/frontend/src/components/Details/Title.vue index ae42ea721..25a0c69fc 100644 --- a/frontend/src/components/Details/Title.vue +++ b/frontend/src/components/Details/Title.vue @@ -88,7 +88,7 @@ const hasReleaseDate = Number(props.rom.metadatum.first_release_date) > 0; 0; mdi-star + + + + + + {{ rom.ss_id }} + + {{ rom.ss_metadata?.ss_score }} + mdi-star + + @@ -128,20 +145,16 @@ const hasReleaseDate = Number(props.rom.metadatum.first_release_date) > 0; - - + + - {{ rom.ss_id }} - - {{ rom.ss_metadata?.ss_score }} - mdi-star + {{ rom.ra_id }} diff --git a/frontend/src/components/Gallery/AppBar/Base.vue b/frontend/src/components/Gallery/AppBar/Base.vue index b2c5545f8..51e1dd605 100644 --- a/frontend/src/components/Gallery/AppBar/Base.vue +++ b/frontend/src/components/Gallery/AppBar/Base.vue @@ -13,11 +13,13 @@ import { calculateMainLayoutWidth } from "@/utils"; // Props withDefaults( defineProps<{ + showPlayablesFilter?: boolean; showPlatformsFilter?: boolean; showFilterBar?: boolean; showSearchBar?: boolean; }>(), { + showPlayablesFilter: true, showPlatformsFilter: false, showFilterBar: false, showSearchBar: false, @@ -42,13 +44,14 @@ const { calculatedWidth } = calculateMainLayoutWidth(); diff --git a/frontend/src/components/Gallery/AppBar/Platform/Base.vue b/frontend/src/components/Gallery/AppBar/Platform/Base.vue index 3fd89632c..a6100681f 100644 --- a/frontend/src/components/Gallery/AppBar/Platform/Base.vue +++ b/frontend/src/components/Gallery/AppBar/Platform/Base.vue @@ -2,21 +2,18 @@ import BaseGalleryAppBar from "@/components/Gallery/AppBar/Base.vue"; import PlatformIcon from "@/components/common/Platform/Icon.vue"; import FirmwareBtn from "@/components/Gallery/AppBar/Platform/FirmwareBtn.vue"; +import SettingsBtn from "@/components/Gallery/AppBar/Platform/SettingsBtn.vue"; import FirmwareDrawer from "@/components/Gallery/AppBar/Platform/FirmwareDrawer.vue"; import PlatformInfoDrawer from "@/components/Gallery/AppBar/Platform/PlatformInfoDrawer.vue"; -import storeNavigation from "@/stores/navigation"; import storeRoms from "@/stores/roms"; import { storeToRefs } from "pinia"; -import { computed } from "vue"; // Props const romsStore = storeRoms(); const { currentPlatform } = storeToRefs(romsStore); -const navigationStore = storeNavigation(); -const { activePlatformInfoDrawer } = storeToRefs(navigationStore); + aria-label="Firmwares" + @click="galleryViewStore.switchActiveFirmwareDrawer()" + /> + + diff --git a/frontend/src/components/Gallery/AppBar/Platform/FirmwareDrawer.vue b/frontend/src/components/Gallery/AppBar/Platform/FirmwareDrawer.vue index c6b3595c7..eb8d45fc5 100644 --- a/frontend/src/components/Gallery/AppBar/Platform/FirmwareDrawer.vue +++ b/frontend/src/components/Gallery/AppBar/Platform/FirmwareDrawer.vue @@ -9,7 +9,7 @@ import type { Events } from "@/types/emitter"; import { formatBytes, calculateMainLayoutWidth } from "@/utils"; import type { Emitter } from "mitt"; import { storeToRefs } from "pinia"; -import { inject, ref } from "vue"; +import { inject, ref, computed } from "vue"; import { useDisplay } from "vuetify"; import { useI18n } from "vue-i18n"; @@ -33,6 +33,7 @@ const HEADERS = [ }, { title: "", align: "end", key: "actions", sortable: false }, ] as const; +const tabIndex = computed(() => (activeFirmwareDrawer.value ? 0 : -1)); // Functions function downloadSelectedFirmware() { @@ -64,6 +65,7 @@ function deleteSelectedFirmware() { :style="{ width: calculatedWidth, }" + tabindex="-1" > diff --git a/frontend/src/components/Gallery/AppBar/common/SelectingBtn.vue b/frontend/src/components/Gallery/AppBar/common/SelectingBtn.vue index b41833691..2619ca4aa 100644 --- a/frontend/src/components/Gallery/AppBar/common/SelectingBtn.vue +++ b/frontend/src/components/Gallery/AppBar/common/SelectingBtn.vue @@ -23,6 +23,7 @@ const romsStore = storeRoms(); v-bind="props" class="mr-0" icon="mdi-select-group" + aria-label="Multi select" @click="romsStore.setSelecting()" /> diff --git a/frontend/src/components/Home/Collections.vue b/frontend/src/components/Home/Collections.vue index 0f1d7a0ea..8a0047a8c 100644 --- a/frontend/src/components/Home/Collections.vue +++ b/frontend/src/components/Home/Collections.vue @@ -25,7 +25,11 @@ function toggleGridCollections() {