diff --git a/backend/alembic/versions/0036_screenscraper_platforms_id.py b/backend/alembic/versions/0036_screenscraper_platforms_id.py index e29fd71d3..1297ee3dd 100644 --- a/backend/alembic/versions/0036_screenscraper_platforms_id.py +++ b/backend/alembic/versions/0036_screenscraper_platforms_id.py @@ -8,7 +8,7 @@ Create Date: 2025-01-02 18:58:55.557123 import sqlalchemy as sa from alembic import op -from handler.metadata.ss_handler import SLUG_TO_SS_ID +from handler.metadata.ss_handler import SCREENSAVER_PLATFORM_LIST # revision identifiers, used by Alembic. revision = "0036_screenscraper_platforms_id" @@ -20,7 +20,7 @@ depends_on = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### connection = op.get_bind() - for slug, ss_id in SLUG_TO_SS_ID.items(): + for slug, ss_id in SCREENSAVER_PLATFORM_LIST.items(): connection.execute( sa.text("UPDATE platforms SET ss_id = :ss_id WHERE slug = :slug"), {"ss_id": ss_id["id"], "slug": slug}, diff --git a/backend/alembic/versions/0043_launchbox_id.py b/backend/alembic/versions/0043_launchbox_id.py new file mode 100644 index 000000000..46e37aaef --- /dev/null +++ b/backend/alembic/versions/0043_launchbox_id.py @@ -0,0 +1,55 @@ +"""empty message + +Revision ID: 0043_launchbox_id +Revises: 0042_add_missing_from_fs +Create Date: 2025-05-20 22:39:16.993191 + +""" + +import sqlalchemy as sa +from alembic import op +from sqlalchemy.dialects import postgresql +from utils.database import CustomJSON + +revision = "0043_launchbox_id" +down_revision = "0042_add_missing_from_fs" +branch_labels = None +depends_on = None + + +def upgrade() -> 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.add_column(sa.Column("launchbox_id", sa.Integer(), nullable=True)) + + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.add_column(sa.Column("launchbox_id", sa.Integer(), nullable=True)) + batch_op.add_column( + sa.Column( + "launchbox_metadata", + sa.JSON().with_variant( + postgresql.JSONB(astext_type=sa.Text()), "postgresql" + ), + nullable=True, + ) + ) + batch_op.create_index("idx_roms_launchbox_id", ["launchbox_id"], unique=False) + batch_op.create_index("idx_roms_ra_id", ["ra_id"], unique=False) + batch_op.create_index("idx_roms_sgdb_id", ["sgdb_id"], unique=False) + + +def downgrade() -> None: + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.drop_index("idx_roms_sgdb_id") + batch_op.drop_index("idx_roms_ra_id") + batch_op.drop_index("idx_roms_launchbox_id") + batch_op.drop_column("launchbox_metadata") + batch_op.drop_column("launchbox_id") + + with op.batch_alter_table("platforms", schema=None) as batch_op: + batch_op.drop_column("launchbox_id") + + with op.batch_alter_table("rom_user", schema=None) as batch_op: + batch_op.add_column(sa.Column("ra_metadata", CustomJSON(), nullable=True)) diff --git a/backend/config/__init__.py b/backend/config/__init__.py index f98f51f2d..10fa2d565 100644 --- a/backend/config/__init__.py +++ b/backend/config/__init__.py @@ -75,6 +75,11 @@ REFRESH_RETROACHIEVEMENTS_CACHE_DAYS: Final = int( # MOBYGAMES MOBYGAMES_API_KEY: Final = os.environ.get("MOBYGAMES_API_KEY", "").strip() +# LAUNCHBOX +LAUNCHBOX_API_ENABLED: Final = str_to_bool( + os.environ.get("LAUNCHBOX_API_ENABLED", "true") +) + # AUTH ROMM_AUTH_SECRET_KEY: Final = os.environ.get( "ROMM_AUTH_SECRET_KEY", secrets.token_hex(32) @@ -123,6 +128,13 @@ SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON: Final = os.environ.get( "SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON", "0 4 * * *", # At 4:00 AM every day ) +ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA: Final = str_to_bool( + os.environ.get("ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA", "false") +) +SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON: Final = os.environ.get( + "SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON", + "0 5 * * *", # At 5:00 AM every day +) # EMULATION DISABLE_EMULATOR_JS = str_to_bool(os.environ.get("DISABLE_EMULATOR_JS", "false")) diff --git a/backend/endpoints/heartbeat.py b/backend/endpoints/heartbeat.py index c6187cc25..454dfdc95 100644 --- a/backend/endpoints/heartbeat.py +++ b/backend/endpoints/heartbeat.py @@ -4,11 +4,14 @@ from config import ( DISABLE_USERPASS_LOGIN, ENABLE_RESCAN_ON_FILESYSTEM_CHANGE, ENABLE_SCHEDULED_RESCAN, + ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA, ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB, + LAUNCHBOX_API_ENABLED, OIDC_ENABLED, OIDC_PROVIDER, RESCAN_ON_FILESYSTEM_CHANGE_DELAY, SCHEDULED_RESCAN_CRON, + SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON, SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON, UPLOAD_TIMEOUT, ) @@ -45,12 +48,14 @@ def heartbeat() -> HeartbeatResponse: "ANY_SOURCE_ENABLED": IGDB_API_ENABLED or SS_API_ENABLED or MOBY_API_ENABLED - or RA_API_ENABLED, + or RA_API_ENABLED + or LAUNCHBOX_API_ENABLED, "IGDB_API_ENABLED": IGDB_API_ENABLED, "SS_API_ENABLED": SS_API_ENABLED, "MOBY_API_ENABLED": MOBY_API_ENABLED, "STEAMGRIDDB_API_ENABLED": STEAMGRIDDB_API_ENABLED, "RA_API_ENABLED": RA_API_ENABLED, + "LAUNCHBOX_API_ENABLED": LAUNCHBOX_API_ENABLED, }, "FILESYSTEM": { "FS_PLATFORMS": fs_platform_handler.get_platforms(), @@ -73,6 +78,12 @@ def heartbeat() -> HeartbeatResponse: "TITLE": "Scheduled Switch TitleDB update", "MESSAGE": "Updates the Nintendo Switch TitleDB file", }, + "LAUNCHBOX_METADATA": { + "ENABLED": ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA, + "CRON": SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON, + "TITLE": "Scheduled LaunchBox metadata update", + "MESSAGE": "Updates the LaunchBox metadata store", + }, }, "EMULATION": { "DISABLE_EMULATOR_JS": DISABLE_EMULATOR_JS, diff --git a/backend/endpoints/platform.py b/backend/endpoints/platform.py index 2e84f1773..315659e99 100644 --- a/backend/endpoints/platform.py +++ b/backend/endpoints/platform.py @@ -90,6 +90,8 @@ def get_supported_platforms(request: Request) -> list[PlatformSchema]: "created_at": now, "updated_at": now, "fs_size_bytes": 0, + "is_unidentified": False, + "is_identified": True, "missing_from_fs": False, } diff --git a/backend/endpoints/responses/heartbeat.py b/backend/endpoints/responses/heartbeat.py index 0bf5484e0..569ff6eb1 100644 --- a/backend/endpoints/responses/heartbeat.py +++ b/backend/endpoints/responses/heartbeat.py @@ -19,6 +19,7 @@ class TaskDict(WatcherDict): class SchedulerDict(TypedDict): RESCAN: TaskDict SWITCH_TITLEDB: TaskDict + LAUNCHBOX_METADATA: TaskDict class MetadataSourcesDict(TypedDict): @@ -28,6 +29,7 @@ class MetadataSourcesDict(TypedDict): SS_API_ENABLED: bool STEAMGRIDDB_API_ENABLED: bool RA_API_ENABLED: bool + LAUNCHBOX_API_ENABLED: bool class FilesystemDict(TypedDict): diff --git a/backend/endpoints/responses/platform.py b/backend/endpoints/responses/platform.py index 043ad5e83..8f0612d1a 100644 --- a/backend/endpoints/responses/platform.py +++ b/backend/endpoints/responses/platform.py @@ -17,6 +17,7 @@ class PlatformSchema(BaseModel): igdb_id: int | None = None sgdb_id: int | None = None moby_id: int | None = None + launchbox_id: int | None = None ss_id: int | None = None ra_id: int | None = None category: str | None = None @@ -31,6 +32,8 @@ class PlatformSchema(BaseModel): created_at: datetime updated_at: datetime fs_size_bytes: int + is_unidentified: bool + is_identified: bool missing_from_fs: bool diff --git a/backend/endpoints/responses/rom.py b/backend/endpoints/responses/rom.py index 5d9371f02..d62277cf9 100644 --- a/backend/endpoints/responses/rom.py +++ b/backend/endpoints/responses/rom.py @@ -8,6 +8,7 @@ from endpoints.responses.assets import SaveSchema, ScreenshotSchema, StateSchema from endpoints.responses.collection import CollectionSchema from fastapi import Request from handler.metadata.igdb_handler import IGDBMetadata +from handler.metadata.launchbox_handler import LaunchboxMetadata from handler.metadata.moby_handler import MobyMetadata from handler.metadata.ra_handler import RAMetadata from handler.metadata.ss_handler import SSMetadata @@ -38,6 +39,11 @@ RomRAMetadata = TypedDict( # type: ignore[misc] dict((k, NotRequired[v]) for k, v in get_type_hints(RAMetadata).items()), total=False, ) +RomLaunchboxMetadata = TypedDict( # type: ignore[misc] + "RomLaunchboxMetadata", + dict((k, NotRequired[v]) for k, v in get_type_hints(LaunchboxMetadata).items()), + total=False, +) def rom_user_schema_factory() -> RomUserSchema: @@ -173,6 +179,7 @@ class RomSchema(BaseModel): moby_id: int | None ss_id: int | None ra_id: int | None + launchbox_id: int | None platform_id: int platform_slug: str @@ -199,6 +206,7 @@ class RomSchema(BaseModel): igdb_metadata: RomIGDBMetadata | None moby_metadata: RomMobyMetadata | None ss_metadata: RomSSMetadata | None + launchbox_metadata: RomLaunchboxMetadata | None path_cover_small: str | None path_cover_large: str | None @@ -209,6 +217,7 @@ class RomSchema(BaseModel): url_manual: str | None is_unidentified: bool + is_identified: bool revision: str | None regions: list[str] diff --git a/backend/endpoints/rom.py b/backend/endpoints/rom.py index 90d58d459..83752590d 100644 --- a/backend/endpoints/rom.py +++ b/backend/endpoints/rom.py @@ -36,7 +36,12 @@ from handler.database import db_platform_handler, db_rom_handler 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 handler.metadata import ( + meta_igdb_handler, + meta_launchbox_handler, + meta_moby_handler, + meta_ss_handler, +) from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log @@ -192,7 +197,7 @@ def get_roms( playables_only (bool, optional): Filter only playable roms by emulatorjs. Defaults to False. DEPRECATED: use `playable` instead. ra_only (bool, optional): Filter only roms with Retroachievements compatibility. Defaults to False. missing_only (bool, optional): Filter only roms that are missing from the filesystem. Defaults to False. - group_by_meta_id (bool, optional): Group roms by igdb/moby/ssrf ID. Defaults to False. + group_by_meta_id (bool, optional): Group roms by igdb/moby/ssrf/launchbox ID. Defaults to False. selected_genre (str, optional): Filter by genre. Defaults to None. selected_franchise (str, optional): Filter by franchise. Defaults to None. selected_collection (str, optional): Filter by collection. Defaults to None. @@ -555,6 +560,7 @@ async def update_rom( "moby_id": None, "ss_id": None, "ra_id": None, + "launchbox_id": None, "name": rom.fs_name, "summary": "", "url_screenshots": [], @@ -568,6 +574,7 @@ async def update_rom( "moby_metadata": {}, "ss_metadata": {}, "ra_metadata": {}, + "launchbox_metadata": {}, "revision": "", }, ) @@ -582,6 +589,7 @@ async def update_rom( "igdb_id": data.get("igdb_id", rom.igdb_id), "moby_id": data.get("moby_id", rom.moby_id), "ss_id": data.get("ss_id", rom.ss_id), + "launchbox_id": data.get("launchbox_id", rom.launchbox_id), } if ( @@ -622,6 +630,20 @@ async def update_rom( ) cleaned_data.update({"path_screenshots": path_screenshots}) + if ( + cleaned_data.get("launchbox_id", "") + and int(cleaned_data.get("launchbox_id", "")) != rom.launchbox_id + ): + igdb_rom = await meta_launchbox_handler.get_rom_by_id( + cleaned_data["launchbox_id"] + ) + cleaned_data.update(igdb_rom) + path_screenshots = await fs_resource_handler.get_rom_screenshots( + rom=rom, + url_screenshots=cleaned_data.get("url_screenshots", []), + ) + cleaned_data.update({"path_screenshots": path_screenshots}) + cleaned_data.update( { "name": data.get("name", rom.name), @@ -814,7 +836,7 @@ async def delete_roms( raise RomNotFoundInDatabaseException(id) log.info( - f"Deleting {hl(str(rom.name), color=BLUE)} [{hl(rom.fs_name)}] from database" + f"Deleting {hl(str(rom.name or 'ROM'), color=BLUE)} [{hl(rom.fs_name)}] from database" ) db_rom_handler.delete_rom(id) @@ -822,7 +844,7 @@ async def delete_roms( rmtree(f"{RESOURCES_BASE_PATH}/{rom.fs_resources_path}") except FileNotFoundError: log.error( - f"Couldn't find resources to delete for {hl(str(rom.name), color=BLUE)}" + f"Couldn't find resources to delete for {hl(str(rom.name or 'ROM'), color=BLUE)}" ) if id in delete_from_fs: diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 5c3037884..c481a1b1c 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -205,7 +205,7 @@ def _should_scan_rom(scan_type: ScanType, rom: Rom | None, roms_ids: list[str]) rom and ( (scan_type == ScanType.UNIDENTIFIED and rom.is_unidentified) - or (scan_type == ScanType.PARTIAL and rom.is_partially_identified) + or (scan_type == ScanType.PARTIAL and rom.is_identified) or (rom.id in roms_ids) ) ) @@ -249,9 +249,7 @@ 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 or scanned_rom.ss_id else 0 - ) + scan_stats.metadata_roms += 1 if scanned_rom.is_identified else 0 _added_rom = db_rom_handler.add_rom(scanned_rom) @@ -383,12 +381,13 @@ async def _identify_platform( # Keep the existing ids if they exist on the platform scanned_platform.igdb_id = scanned_platform.igdb_id or platform.igdb_id scanned_platform.moby_id = scanned_platform.moby_id or platform.moby_id + scanned_platform.launchbox_id = ( + scanned_platform.launchbox_id or platform.launchbox_id + ) scan_stats.scanned_platforms += 1 scan_stats.added_platforms += 1 if not platform else 0 - scan_stats.metadata_platforms += ( - 1 if scanned_platform.igdb_id or scanned_platform.moby_id else 0 - ) + scan_stats.metadata_platforms += 1 if scanned_platform.is_identified else 0 platform = db_platform_handler.add_platform(scanned_platform) diff --git a/backend/endpoints/tasks.py b/backend/endpoints/tasks.py index 3d9373033..4d168b59e 100644 --- a/backend/endpoints/tasks.py +++ b/backend/endpoints/tasks.py @@ -2,6 +2,7 @@ from decorators.auth import protected_route from endpoints.responses import MessageResponse from fastapi import Request from handler.auth.constants import Scope +from tasks.update_launchbox_metadata import update_launchbox_metadata_task from tasks.update_switch_titledb import update_switch_titledb_task from utils.router import APIRouter @@ -22,12 +23,13 @@ async def run_tasks(request: Request) -> MessageResponse: """ await update_switch_titledb_task.run() + await update_launchbox_metadata_task.run() return {"msg": "All tasks ran successfully!"} @protected_route(router.post, "/{task}/run", [Scope.TASKS_RUN]) async def run_task(request: Request, task: str) -> MessageResponse: - """Run all tasks endpoint + """Run single tasks endpoint Args: request (Request): Fastapi Request object @@ -35,7 +37,10 @@ async def run_task(request: Request, task: str) -> MessageResponse: RunTasksResponse: Standard message response """ - tasks = {"switch_titledb": update_switch_titledb_task} + tasks = { + "switch_titledb": update_switch_titledb_task, + "launchbox_metadata": update_launchbox_metadata_task, + } await tasks[task].run() return {"msg": f"Task {task} run successfully!"} diff --git a/backend/endpoints/tests/test_heartbeat.py b/backend/endpoints/tests/test_heartbeat.py index d8ac46449..d1564d168 100644 --- a/backend/endpoints/tests/test_heartbeat.py +++ b/backend/endpoints/tests/test_heartbeat.py @@ -27,4 +27,12 @@ def test_heartbeat(client): heartbeat.get("SCHEDULER").get("SWITCH_TITLEDB").get("TITLE") == "Scheduled Switch TitleDB update" ) + assert heartbeat.get("SCHEDULER").get("LAUNCHBOX_METADATA").get("ENABLED") + assert ( + heartbeat.get("SCHEDULER").get("LAUNCHBOX_METADATA").get("CRON") == "0 5 * * *" + ) + assert ( + heartbeat.get("SCHEDULER").get("LAUNCHBOX_METADATA").get("TITLE") + == "Scheduled LaunchBox metadata update" + ) assert heartbeat.get("FRONTEND").get("UPLOAD_TIMEOUT") == 20 diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index 68a7eaef2..c3f5369ce 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -193,6 +193,7 @@ class DBRomsHandler(DBBaseHandler): Rom.igdb_id.isnot(None), Rom.moby_id.isnot(None), Rom.ss_id.isnot(None), + Rom.launchbox_id.isnot(None), ) if not value: predicate = not_(predicate) @@ -426,6 +427,9 @@ class DBRomsHandler(DBBaseHandler): Rom.igdb_id.isnot(None): build_func("igdb", Rom.igdb_id), Rom.moby_id.isnot(None): build_func("moby", Rom.moby_id), Rom.ss_id.isnot(None): build_func("ss", Rom.ss_id), + Rom.launchbox_id.isnot(None): build_func( + "launchbox", Rom.launchbox_id + ), }, else_=build_func("romm", Rom.id), ) diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 546861445..620e9de70 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -9,7 +9,7 @@ import tarfile import zipfile from collections.abc import Callable, Iterator from pathlib import Path -from typing import Any, Final, Literal, TypedDict +from typing import IO, Any, Final, Literal, TypedDict import magic import py7zr @@ -87,22 +87,23 @@ def is_compressed_file(file_path: str) -> bool: ) -def read_basic_file(file_path: Path) -> Iterator[bytes]: +def read_basic_file(file_path: os.PathLike[str]) -> Iterator[bytes]: with open(file_path, "rb") as f: while chunk := f.read(FILE_READ_CHUNK_SIZE): yield chunk -def read_zip_file(file_path: Path) -> Iterator[bytes]: +def read_zip_file(file: str | os.PathLike[str] | IO[bytes]) -> Iterator[bytes]: try: - with zipfile.ZipFile(file_path, "r") as z: + with zipfile.ZipFile(file, "r") as z: for file in z.namelist(): with z.open(file, "r") as f: while chunk := f.read(FILE_READ_CHUNK_SIZE): yield chunk except zipfile.BadZipFile: - for chunk in read_basic_file(file_path): - yield chunk + if isinstance(file, Path): + for chunk in read_basic_file(file): + yield chunk def read_tar_file( diff --git a/backend/handler/metadata/__init__.py b/backend/handler/metadata/__init__.py index 46b23afb9..26edf6420 100644 --- a/backend/handler/metadata/__init__.py +++ b/backend/handler/metadata/__init__.py @@ -1,4 +1,5 @@ from .igdb_handler import IGDBHandler +from .launchbox_handler import LaunchboxHandler from .moby_handler import MobyGamesHandler from .ra_handler import RAHandler from .sgdb_handler import SGDBBaseHandler @@ -9,3 +10,4 @@ meta_moby_handler = MobyGamesHandler() meta_ss_handler = SSHandler() meta_sgdb_handler = SGDBBaseHandler() meta_ra_handler = RAHandler() +meta_launchbox_handler = LaunchboxHandler() diff --git a/backend/handler/metadata/launchbox_handler.py b/backend/handler/metadata/launchbox_handler.py new file mode 100644 index 000000000..35616887e --- /dev/null +++ b/backend/handler/metadata/launchbox_handler.py @@ -0,0 +1,448 @@ +import json +from typing import NotRequired, TypedDict + +from config import LAUNCHBOX_API_ENABLED, str_to_bool +from handler.redis_handler import async_cache +from logger.logger import log +from tasks.update_launchbox_metadata import ( # LAUNCHBOX_MAME_KEY, + LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, + LAUNCHBOX_METADATA_DATABASE_ID_KEY, + LAUNCHBOX_METADATA_IMAGE_KEY, + LAUNCHBOX_METADATA_NAME_KEY, + update_launchbox_metadata_task, +) + +from .base_hander import MetadataHandler + + +class LaunchboxPlatform(TypedDict): + slug: str + launchbox_id: int | None + name: NotRequired[str] + + +class LaunchboxImage(TypedDict): + url: str + type: NotRequired[str] + region: NotRequired[str] + + +class LaunchboxMetadata(TypedDict): + release_date: NotRequired[str] + max_players: NotRequired[int] + release_type: NotRequired[str] + cooperative: NotRequired[bool] + video_url: NotRequired[str] + community_rating: NotRequired[float] + community_rating_count: NotRequired[int] + wikipedia_url: NotRequired[str] + esrb: NotRequired[str] + genres: NotRequired[list[str]] + developer: NotRequired[str] + publisher: NotRequired[str] + images: list[LaunchboxImage] + + +class LaunchboxRom(TypedDict): + launchbox_id: int | None + name: NotRequired[str] + summary: NotRequired[str] + url_cover: NotRequired[str] + url_screenshots: NotRequired[list[str]] + launchbox_metadata: NotRequired[LaunchboxMetadata] + + +def extract_metadata_from_launchbox_rom( + index_entry: dict, game_images: list[dict] | None +) -> LaunchboxMetadata: + return LaunchboxMetadata( + { + "release_date": index_entry.get("ReleaseDate", ""), + "max_players": int(index_entry.get("MaxPlayers") or 0), + "release_type": index_entry.get("ReleaseType", ""), + "cooperative": str_to_bool(index_entry.get("Cooperative") or "false"), + "video_url": index_entry.get("VideoURL") or "", + "community_rating": float(index_entry.get("CommunityRating") or 0.0), + "community_rating_count": int(index_entry.get("CommunityRatingCount") or 0), + "wikipedia_url": index_entry.get("WikipediaURL", ""), + "esrb": index_entry.get("ESRB", ""), + "genres": ( + index_entry["Genres"].split() if index_entry.get("Genres", None) else [] + ), + "developer": index_entry.get("Developer") or "", + "publisher": index_entry.get("Publisher") or "", + "images": [ + LaunchboxImage( + { + "url": f"https://images.launchbox-app.com/{image['FileName']}", + "type": image.get("Type", ""), + "region": image.get("Region", ""), + } + ) + for image in game_images or [] + ], + } + ) + + +class LaunchboxHandler(MetadataHandler): + async def _get_rom_from_metadata( + self, file_name: str, platform_slug: str + ) -> dict | None: + if not (await async_cache.exists(LAUNCHBOX_METADATA_NAME_KEY)): + log.warning("Fetching the Launchbox Metadata.xml file...") + await update_launchbox_metadata_task.run(force=True) + + if not (await async_cache.exists(LAUNCHBOX_METADATA_NAME_KEY)): + log.error("Could not fetch the Launchbox Metadata.xml file") + return None + + lb_platform = self.get_platform(platform_slug) + platform_name = lb_platform.get("name", None) + if not platform_name: + return None + + metadata_name_index_entry = await async_cache.hget( + LAUNCHBOX_METADATA_NAME_KEY, f"{file_name}:{platform_name}" + ) + + if metadata_name_index_entry: + return json.loads(metadata_name_index_entry) + + metadata_alternate_name_index_entry = await async_cache.hget( + LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, file_name + ) + + if not metadata_alternate_name_index_entry: + return None + + metadata_alternate_name_index_entry = json.loads( + metadata_alternate_name_index_entry + ) + database_id = metadata_alternate_name_index_entry["DatabaseID"] + metadata_database_index_entry = await async_cache.hget( + LAUNCHBOX_METADATA_DATABASE_ID_KEY, database_id + ) + + if not metadata_database_index_entry: + return None + + return json.loads(metadata_database_index_entry) + + async def _get_game_images(self, database_id: str) -> list[dict] | None: + metadata_image_index_entry = await async_cache.hget( + LAUNCHBOX_METADATA_IMAGE_KEY, database_id + ) + + if not metadata_image_index_entry: + return None + + return json.loads(metadata_image_index_entry) + + def _get_best_cover_image(self, game_images: list[dict]) -> dict | None: + """ + Get the best cover image from a list of game images based on priority order: + """ + # Define priority order + priority_types = [ + "Box - Front", + "Box - 3D", + "Fanart - Box - Front", + "Cart - Front", + "Cart - 3D", + ] + + for image_type in priority_types: + for image in game_images: + if image.get("Type") == image_type: + return image + + return None + + def _get_screenshots(self, game_images: list[dict]) -> list[str]: + screenshots: list[str] = [] + for image in game_images: + if "Screenshot" in image.get("Type", ""): + screenshots.append( + f"https://images.launchbox-app.com/{image.get('FileName')}" + ) + + return screenshots + + def get_platform(self, slug: str) -> LaunchboxPlatform: + platform = LAUNCHBOX_PLATFORM_LIST.get(slug, None) + + if not platform: + return LaunchboxPlatform(slug=slug, launchbox_id=None) + + return LaunchboxPlatform( + slug=slug, + launchbox_id=platform["id"], + name=platform["name"], + ) + + async def get_rom(self, fs_name: str, platform_slug: str) -> LaunchboxRom: + from handler.filesystem import fs_rom_handler + + if not LAUNCHBOX_API_ENABLED: + return LaunchboxRom(launchbox_id=None) + + search_term = fs_rom_handler.get_file_name_with_no_tags(fs_name) + fallback_rom = LaunchboxRom(launchbox_id=None) + + index_entry = await self._get_rom_from_metadata(search_term, platform_slug) + if not index_entry: + return fallback_rom + + url_cover = None + url_screenshots = [] + + game_images = await self._get_game_images(index_entry["DatabaseID"]) + if game_images: + best_cover = self._get_best_cover_image(game_images) + if best_cover: + url_cover = ( + f"https://images.launchbox-app.com/{best_cover.get("FileName")}" + ) + + url_screenshots = self._get_screenshots(game_images) + + rom = { + "launchbox_id": index_entry["DatabaseID"], + "name": index_entry["Name"], + "summary": index_entry.get("Overview", ""), + "url_cover": url_cover, + "url_screenshots": url_screenshots, + "launchbox_metadata": extract_metadata_from_launchbox_rom( + index_entry, game_images + ), + } + + return LaunchboxRom({k: v for k, v in rom.items() if v}) # type: ignore[misc] + + async def get_rom_by_id(self, database_id: int) -> LaunchboxRom: + if not LAUNCHBOX_API_ENABLED: + return LaunchboxRom(launchbox_id=None) + + metadata_database_index_entry = await async_cache.hget( + LAUNCHBOX_METADATA_DATABASE_ID_KEY, str(database_id) + ) + + if not metadata_database_index_entry: + return LaunchboxRom(launchbox_id=None) + + game_images = await self._get_game_images( + metadata_database_index_entry["DatabaseID"] + ) + + rom = { + "launchbox_id": database_id, + "name": metadata_database_index_entry["Name"], + "summary": metadata_database_index_entry.get("Overview", ""), + "launchbox_metadata": extract_metadata_from_launchbox_rom( + metadata_database_index_entry, + game_images, + ), + } + + return LaunchboxRom({k: v for k, v in rom.items() if v}) # type: ignore[misc] + + async def get_matched_rom_by_id(self, database_id: int) -> LaunchboxRom | None: + if not LAUNCHBOX_API_ENABLED: + return None + + return await self.get_rom_by_id(database_id) + + +class SlugToLaunchboxPlatformName(TypedDict): + id: int + name: str + + +LAUNCHBOX_PLATFORM_LIST: dict[str, SlugToLaunchboxPlatformName] = { + "3do": {"id": 1, "name": "3DO Interactive Multiplayer"}, + "apf": {"id": 68, "name": "APF Imagination Machine"}, + "pegasus": {"id": 174, "name": "Aamber Pegasus"}, + "acorn-archimedes": {"id": 74, "name": "Acorn Archimedes"}, + "atom": {"id": 107, "name": "Acorn Atom"}, + "acorn-electron": {"id": 65, "name": "Acorn Electron"}, + "acpc": {"id": 3, "name": "Amstrad CPC"}, + "gx4000": {"id": 109, "name": "Amstrad GX4000"}, + "android": {"id": 4, "name": "Android"}, + "bk-01": {"id": 175, "name": "Apogee BK-01"}, + "apple2": {"id": 111, "name": "Apple II"}, + "apple2gs": {"id": 112, "name": "Apple IIGS"}, + "mac": {"id": 16, "name": "Apple Mac OS"}, + "ios": {"id": 18, "name": "Apple iOS"}, + "arcade": {"id": 5, "name": "Arcade"}, + "atari2600": {"id": 6, "name": "Atari 2600"}, + "atari5200": {"id": 7, "name": "Atari 5200"}, + "atari7800": {"id": 8, "name": "Atari 7800"}, + "atari800": {"id": 102, "name": "Atari 800"}, + "jaguar": {"id": 9, "name": "Atari Jaguar"}, + "atari-jaguar-cd": {"id": 10, "name": "Atari Jaguar CD"}, + "lynx": {"id": 11, "name": "Atari Lynx"}, + "atari-st": {"id": 76, "name": "Atari ST"}, + "atari-xegs": {"id": 12, "name": "Atari XEGS"}, + "bbcmicro": {"id": 59, "name": "BBC Microcomputer System"}, + "astrocade": {"id": 77, "name": "Bally Astrocade"}, + "super-vision-8000": {"id": 223, "name": "Bandai Super Vision 8000"}, + "camputers-lynx": {"id": 61, "name": "Camputers Lynx"}, + "casio-loopy": {"id": 114, "name": "Casio Loopy"}, + "casio-pv-1000": {"id": 115, "name": "Casio PV-1000"}, + "colecoadam": {"id": 117, "name": "Coleco ADAM"}, + "colecovision": {"id": 13, "name": "ColecoVision"}, + "c128": {"id": 118, "name": "Commodore 128"}, + "c64": {"id": 14, "name": "Commodore 64"}, + "amiga": {"id": 2, "name": "Commodore Amiga"}, + "amiga-cd32": {"id": 119, "name": "Commodore Amiga CD32"}, + "commodore-cdtv": {"id": 120, "name": "Commodore CDTV"}, + "cpet": {"id": 180, "name": "Commodore PET"}, + "c-plus-4": {"id": 121, "name": "Commodore Plus 4"}, + "vic-20": {"id": 122, "name": "Commodore VIC-20"}, + "dragon-32-slash-64": {"id": 66, "name": "Dragon 32/64"}, + "colour-genie": {"id": 73, "name": "EACA EG2000 Colour Genie"}, + "bk": {"id": 131, "name": "Elektronika BK"}, + "arcadia-2001": {"id": 79, "name": "Emerson Arcadia 2001"}, + "enterprise": {"id": 72, "name": "Enterprise"}, + "adventure-vision": {"id": 67, "name": "Entex Adventure Vision"}, + "epoch-game-pocket-computer": {"id": 132, "name": "Epoch Game Pocket Computer"}, + "epoch-super-cassette-vision": {"id": 81, "name": "Epoch Super Cassette Vision"}, + "exelvision": {"id": 183, "name": "Exelvision EXL 100"}, + "exidy-sorcerer": {"id": 184, "name": "Exidy Sorcerer"}, + "fairchild-channel-f": {"id": 58, "name": "Fairchild Channel F"}, + "fm-towns": {"id": 124, "name": "Fujitsu FM Towns Marty"}, + "fm-7": {"id": 186, "name": "Fujitsu FM-7"}, + "gp32": {"id": 135, "name": "GamePark GP32"}, + "game-wave": {"id": 216, "name": "GameWave"}, + "vectrex": {"id": 125, "name": "GCE Vectrex"}, + "hartung": {"id": 136, "name": "Hartung Game Master"}, + "hrx": {"id": 187, "name": "Hector HRX"}, + "vc-4000": {"id": 137, "name": "Interton VC 4000"}, + "jupiter-ace": {"id": 70, "name": "Jupiter Ace"}, + "linux": {"id": 218, "name": "Linux"}, + "dos": {"id": 83, "name": "MS-DOS"}, + "mugen": {"id": 138, "name": "MUGEN"}, + "odyssey--1": {"id": 78, "name": "Magnavox Odyssey"}, + "odyssey-2-slash-videopac-g7000": {"id": 57, "name": "Magnavox Odyssey 2"}, + "alice-3290": {"id": 189, "name": "Matra and Hachette Alice"}, + "mattel-aquarius": {"id": 69, "name": "Mattel Aquarius"}, + "hyperscan": {"id": 171, "name": "Mattel HyperScan"}, + "intellivision": {"id": 15, "name": "Mattel Intellivision"}, + "mega-duck-slash-cougar-boy": {"id": 127, "name": "Mega Duck"}, + "mtx512": {"id": 60, "name": "Memotech MTX512"}, + "msx": {"id": 82, "name": "Microsoft MSX"}, + "msx2": {"id": 190, "name": "Microsoft MSX2"}, + "msx2plus": {"id": 191, "name": "Microsoft MSX2+"}, + "xbox": {"id": 18, "name": "Microsoft Xbox"}, + "xbox360": {"id": 19, "name": "Microsoft Xbox 360"}, + "xboxone": {"id": 20, "name": "Microsoft Xbox One"}, + "series-x": {"id": 222, "name": "Microsoft Xbox Series X/S"}, + "pc-8800-series": {"id": 192, "name": "NEC PC-8801"}, + "pc-9800-series": {"id": 193, "name": "NEC PC-9801"}, + "pc-fx": {"id": 161, "name": "NEC PC-FX"}, + "turbografx16--1": {"id": 54, "name": "NEC TurboGrafx-16"}, + "turbografx-16-slash-pc-engine-cd": {"id": 163, "name": "NEC TurboGrafx-CD"}, + "system-32": {"id": 93, "name": "Namco System 22"}, + "3ds": {"id": 24, "name": "Nintendo 3DS"}, + "n64": {"id": 25, "name": "Nintendo 64"}, + "64dd": {"id": 194, "name": "Nintendo 64DD"}, + "nds": {"id": 26, "name": "Nintendo DS"}, + "nes": {"id": 27, "name": "Nintendo Entertainment System"}, + "fds": {"id": 157, "name": "Nintendo Famicom Disk System"}, + "famicom": {"id": 157, "name": "Nintendo Famicom Disk System"}, + "g-and-w": {"id": 166, "name": "Nintendo Game & Watch"}, + "gb": {"id": 28, "name": "Nintendo Game Boy"}, + "gba": {"id": 29, "name": "Nintendo Game Boy Advance"}, + "gbc": {"id": 30, "name": "Nintendo Game Boy Color"}, + "ngc": {"id": 31, "name": "Nintendo GameCube"}, + "pokemon-mini": {"id": 195, "name": "Nintendo Pokemon Mini"}, + "satellaview": {"id": 168, "name": "Nintendo Satellaview"}, + "switch": {"id": 211, "name": "Nintendo Switch"}, + "switch2": {"id": 224, "name": "Nintendo Switch 2"}, + "virtualboy": {"id": 32, "name": "Nintendo Virtual Boy"}, + "wii": {"id": 33, "name": "Nintendo Wii"}, + "wiiu": {"id": 34, "name": "Nintendo Wii U"}, + "ngage": {"id": 213, "name": "Nokia N-Gage"}, + "nuon": {"id": 126, "name": "Nuon"}, + "openbor": {"id": 139, "name": "OpenBOR"}, + "atmos": {"id": 64, "name": "Oric Atmos"}, + "multivision": {"id": 197, "name": "Othello Multivision"}, + "ouya": {"id": 35, "name": "Ouya"}, + "supergrafx": {"id": 162, "name": "PC Engine SuperGrafx"}, + "pico": {"id": 220, "name": "PICO-8"}, + "philips-cd-i": {"id": 37, "name": "Philips CD-i"}, + "philips-vg-5000": {"id": 140, "name": "Philips VG 5000"}, + "videopac-g7400": {"id": 141, "name": "Philips Videopac+"}, + "pinball": {"id": 151, "name": "Pinball"}, + "rca-studio-ii": {"id": 142, "name": "RCA Studio II"}, + "sam-coupe": {"id": 71, "name": "SAM Coupé"}, + "neogeoaes": {"id": 23, "name": "SNK Neo Geo AES"}, + "neo-geo-cd": {"id": 167, "name": "SNK Neo Geo CD"}, + "neogeomvs": {"id": 210, "name": "SNK Neo Geo MVS"}, + "neo-geo-pocket": {"id": 21, "name": "SNK Neo Geo Pocket"}, + "neo-geo-pocket-color": {"id": 22, "name": "SNK Neo Geo Pocket Color"}, + "scummvm": {"id": 143, "name": "ScummVM"}, + "sega32": {"id": 38, "name": "Sega 32X"}, + "segacd": {"id": 39, "name": "Sega CD"}, + "segacd32": {"id": 173, "name": "Sega CD 32X"}, + "dc": {"id": 40, "name": "Sega Dreamcast"}, + "vmu": {"id": 144, "name": "Sega Dreamcast VMU"}, + "gamegear": {"id": 41, "name": "Sega Game Gear"}, + "genesis-slash-megadrive": {"id": 42, "name": "Sega Genesis"}, + "hikaru": {"id": 208, "name": "Sega Hikaru"}, + "sms": {"id": 43, "name": "Sega Master System"}, + "model1": {"id": 104, "name": "Sega Model 1"}, + "model2": {"id": 88, "name": "Sega Model 2"}, + "model3": {"id": 94, "name": "Sega Model 3"}, + "sega-pico": {"id": 105, "name": "Sega Pico"}, + "sc3000": {"id": 145, "name": "Sega SC-3000"}, + "sg1000": {"id": 80, "name": "Sega SG-1000"}, + "stv": {"id": 146, "name": "Sega ST-V"}, + "saturn": {"id": 45, "name": "Sega Saturn"}, + "system16": {"id": 97, "name": "Sega System 16"}, + "system32": {"id": 96, "name": "Sega System 32"}, + "sharp-mz-80b20002500": {"id": 205, "name": "Sharp MZ-2500"}, + "x1": {"id": 204, "name": "Sharp X1"}, + "sharp-x68000": {"id": 128, "name": "Sharp X68000"}, + "zxs": {"id": 46, "name": "Sinclair ZX Spectrum"}, + "sinclair-zx81": {"id": 147, "name": "Sinclair ZX-81"}, + "psp": {"id": 52, "name": "Sony PSP"}, + "psp-minis": {"id": 202, "name": "Sony PSP Minis"}, + "ps": {"id": 47, "name": "Sony Playstation"}, + "ps2": {"id": 48, "name": "Sony Playstation 2"}, + "ps3": {"id": 49, "name": "Sony Playstation 3"}, + "ps4--1": {"id": 50, "name": "Sony Playstation 4"}, + "ps5": {"id": 219, "name": "Sony Playstation 5"}, + "psvita": {"id": 51, "name": "Sony Playstation Vita"}, + "pocketstation": {"id": 203, "name": "Sony PocketStation"}, + "sord-m5": {"id": 148, "name": "Sord M5"}, + "spectravideo": {"id": 201, "name": "Spectravideo"}, + "snes": {"id": 53, "name": "Super Nintendo Entertainment System"}, + "sfam": {"id": 53, "name": "Super Famicom"}, + "trs-80-color-computer": {"id": 164, "name": "TRS-80 Color Computer"}, + "type-x": {"id": 169, "name": "Taito Type X"}, + "trs-80": {"id": 129, "name": "Tandy TRS-80"}, + "zod": {"id": 75, "name": "Tapwave Zodiac"}, + "ti-994a": {"id": 149, "name": "Texas Instruments TI 99/4A"}, + "game-dot-com": {"id": 63, "name": "Tiger Game.com"}, + "tomy-tutor": {"id": 200, "name": "Tomy Tutor"}, + "creativision": {"id": 152, "name": "VTech CreatiVision"}, + "socrates": {"id": 198, "name": "VTech Socrates"}, + "vsmile": {"id": 221, "name": "VTech V.Smile"}, + "06c": {"id": 199, "name": "Vector-06C"}, + "watara-slash-quickshot-supervision": {"id": 153, "name": "Watara Supervision"}, + "browser": {"id": 85, "name": "Web Browser"}, + "win": {"id": 84, "name": "Windows"}, + "win3x": {"id": 212, "name": "Windows 3.X"}, + "action-max": {"id": 154, "name": "WoW Action Max"}, + "wonderswan": {"id": 55, "name": "WonderSwan"}, + "wonderswan-color": {"id": 56, "name": "WonderSwan Color"}, + "xavixport": {"id": 170, "name": "XaviXPORT"}, + "zinc": {"id": 155, "name": "ZiNc"}, +} + +# Reverse lookup +LAUNCHBOX_PLATFORM_NAME_TO_SLUG = { + v["id"]: k for k, v in LAUNCHBOX_PLATFORM_LIST.items() +} diff --git a/backend/handler/metadata/moby_handler.py b/backend/handler/metadata/moby_handler.py index 9669c49c7..86eb6d6a5 100644 --- a/backend/handler/metadata/moby_handler.py +++ b/backend/handler/metadata/moby_handler.py @@ -178,7 +178,7 @@ class MobyGamesHandler(MetadataHandler): return pydash.get(exact_matches or roms, "[0]", None) def get_platform(self, slug: str) -> MobyGamesPlatform: - platform = SLUG_TO_MOBY_ID.get(slug, None) + platform = MOBYGAMES_PLATFORM_LIST.get(slug, None) if not platform: return MobyGamesPlatform(moby_id=None, slug=slug) @@ -357,7 +357,7 @@ class SlugToMobyId(TypedDict): name: str -SLUG_TO_MOBY_ID: dict[str, SlugToMobyId] = { +MOBYGAMES_PLATFORM_LIST: dict[str, SlugToMobyId] = { "1292-advanced-programmable-video-system": { "id": 253, "name": "1292 Advanced Programmable Video System", @@ -759,4 +759,4 @@ SLUG_TO_MOBY_ID: dict[str, SlugToMobyId] = { } # Reverse lookup -MOBY_ID_TO_SLUG = {v["id"]: k for k, v in SLUG_TO_MOBY_ID.items()} +MOBY_ID_TO_SLUG = {v["id"]: k for k, v in MOBYGAMES_PLATFORM_LIST.items()} diff --git a/backend/handler/metadata/ss_handler.py b/backend/handler/metadata/ss_handler.py index 9b28ae94b..c3226a105 100644 --- a/backend/handler/metadata/ss_handler.py +++ b/backend/handler/metadata/ss_handler.py @@ -331,7 +331,7 @@ class SSHandler(MetadataHandler): return pydash.get(roms, "[0]", None) def get_platform(self, slug: str) -> SSPlatform: - platform = SLUG_TO_SS_ID.get(slug, None) + platform = SCREENSAVER_PLATFORM_LIST.get(slug, None) if not platform: return SSPlatform(ss_id=None, slug=slug) @@ -675,7 +675,7 @@ class SlugToSSId(TypedDict): name: str -SLUG_TO_SS_ID: dict[str, SlugToSSId] = { +SCREENSAVER_PLATFORM_LIST: dict[str, SlugToSSId] = { "3do": {"id": 29, "name": "3DO"}, "amiga": {"id": 64, "name": "Amiga"}, "amiga-cd32": {"id": 134, "name": "Amiga CD"}, @@ -854,4 +854,4 @@ SLUG_TO_SS_ID: dict[str, SlugToSSId] = { } # Reverse lookup -SS_ID_TO_SLUG = {v["id"]: k for k, v in SLUG_TO_SS_ID.items()} +SS_ID_TO_SLUG = {v["id"]: k for k, v in SCREENSAVER_PLATFORM_LIST.items()} diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index a30f21a09..010259149 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -9,11 +9,13 @@ from handler.filesystem import fs_asset_handler, fs_firmware_handler, fs_rom_han from handler.filesystem.roms_handler import FSRom from handler.metadata import ( meta_igdb_handler, + meta_launchbox_handler, meta_moby_handler, meta_ra_handler, meta_ss_handler, ) from handler.metadata.igdb_handler import IGDBPlatform, IGDBRom +from handler.metadata.launchbox_handler import LaunchboxPlatform, LaunchboxRom from handler.metadata.moby_handler import MobyGamesPlatform, MobyGamesRom from handler.metadata.ra_handler import RAGameRom, RAGamesPlatform from handler.metadata.ss_handler import SSPlatform, SSRom @@ -43,6 +45,7 @@ class MetadataSource: MOBY = "moby" SS = "ss" RA = "ra" + LB = "lb" async def fetch_ra_info( @@ -143,16 +146,26 @@ async def scan_platform( if MetadataSource.SS in metadata_sources 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"]) ) + launchbox_platform = ( + meta_launchbox_handler.get_platform(platform_attrs["slug"]) + if MetadataSource.LB in metadata_sources + else LaunchboxPlatform(launchbox_id=None, slug=platform_attrs["slug"]) + ) platform_attrs["name"] = platform_attrs["slug"].replace("-", " ").title() platform_attrs.update( - {**ra_platform, **moby_platform, **ss_platform, **igdb_platform} + { + **launchbox_platform, + **ra_platform, + **moby_platform, + **ss_platform, + **igdb_platform, + } ) # Reverse order if ( @@ -160,6 +173,7 @@ async def scan_platform( or platform_attrs["moby_id"] or platform_attrs["ss_id"] or platform_attrs["ra_id"] + or platform_attrs["launchbox_id"] ): log.info( emoji.emojize( @@ -260,6 +274,7 @@ async def scan_rom( "ss_id": rom.ss_id, "sgdb_id": rom.sgdb_id, "ra_id": rom.ra_id, + "launchbox_id": rom.launchbox_id, "name": rom.name, "slug": rom.slug, "summary": rom.summary, @@ -356,9 +371,27 @@ async def scan_rom( return SSRom(ss_id=None) + async def fetch_launchbox_rom(platform_slug: str): + if MetadataSource.LB in metadata_sources and ( + not rom + or scan_type == ScanType.COMPLETE + or (scan_type == ScanType.PARTIAL and not rom.launchbox_id) + or (scan_type == ScanType.UNIDENTIFIED and not rom.launchbox_id) + ): + return await meta_launchbox_handler.get_rom( + rom_attrs["fs_name"], platform_slug + ) + + return LaunchboxRom(launchbox_id=None) + # Run both metadata fetches concurrently - igdb_handler_rom, moby_handler_rom, ss_handler_rom = await asyncio.gather( - fetch_igdb_rom(), fetch_moby_rom(), fetch_ss_rom() + igdb_handler_rom, moby_handler_rom, ss_handler_rom, launchbox_handler_rom = ( + await asyncio.gather( + fetch_igdb_rom(), + fetch_moby_rom(), + fetch_ss_rom(), + fetch_launchbox_rom(platform.slug), + ) ) if rom: @@ -369,15 +402,25 @@ async def scan_rom( rom_attrs.update({**ss_handler_rom}) if igdb_handler_rom.get("igdb_id"): rom_attrs.update({**igdb_handler_rom}) + if launchbox_handler_rom.get("launchbox_id"): + rom_attrs.update({**launchbox_handler_rom}) else: # Reversed to prioritize IGDB - rom_attrs.update({**moby_handler_rom, **ss_handler_rom, **igdb_handler_rom}) + rom_attrs.update( + { + **launchbox_handler_rom, + **moby_handler_rom, + **ss_handler_rom, + **igdb_handler_rom, + } + ) - # If not found in IGDB, MobyGames or Screenscraper + # If not found in any metadata source, we return the rom with the default values if ( not igdb_handler_rom.get("igdb_id") and not moby_handler_rom.get("moby_id") and not ss_handler_rom.get("ss_id") + and not launchbox_handler_rom.get("launchbox_id") ): log.warning( emoji.emojize(f"{hl(rom_attrs['fs_name'])} not identified :cross_mark:"), diff --git a/backend/models/platform.py b/backend/models/platform.py index 8ea861f0f..7ff97b8f5 100644 --- a/backend/models/platform.py +++ b/backend/models/platform.py @@ -24,6 +24,7 @@ class Platform(BaseModel): moby_id: Mapped[int | None] ss_id: Mapped[int | None] ra_id: Mapped[int | None] + launchbox_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)) @@ -52,6 +53,28 @@ class Platform(BaseModel): missing_from_fs: Mapped[bool] = mapped_column(default=False, nullable=False) + @property + def is_unidentified(self) -> bool: + return ( + not self.igdb_id + and not self.moby_id + and not self.ss_id + and not self.launchbox_id + ) + + @property + def is_identified(self) -> bool: + return not self.is_unidentified + + @property + def is_fully_identified(self) -> bool: + return ( + bool(self.igdb_id) + and bool(self.moby_id) + and bool(self.ss_id) + and bool(self.launchbox_id) + ) + @cached_property def fs_size_bytes(self) -> int: from handler.database import db_stats_handler diff --git a/backend/models/rom.py b/backend/models/rom.py index 8996c0dce..35cdd76c0 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -119,6 +119,7 @@ class Rom(BaseModel): moby_id: Mapped[int | None] ss_id: Mapped[int | None] ra_id: Mapped[int | None] + launchbox_id: Mapped[int | None] __table_args__ = ( Index("idx_roms_igdb_id", "igdb_id"), @@ -126,6 +127,7 @@ class Rom(BaseModel): Index("idx_roms_ss_id", "ss_id"), Index("idx_roms_ra_id", "ra_id"), Index("idx_roms_sgdb_id", "sgdb_id"), + Index("idx_roms_launchbox_id", "launchbox_id"), ) fs_name: Mapped[str] = mapped_column(String(length=450)) @@ -149,6 +151,9 @@ class Rom(BaseModel): ra_metadata: Mapped[dict[str, Any] | None] = mapped_column( CustomJSON(), default=dict ) + launchbox_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="") @@ -310,12 +315,16 @@ class Rom(BaseModel): @property def is_unidentified(self) -> bool: return ( - not self.igdb_id and not self.moby_id and not self.ss_id and not self.ra_id + not self.igdb_id + and not self.moby_id + and not self.ss_id + and not self.ra_id + and not self.launchbox_id ) @property - def is_partially_identified(self) -> bool: - return not self.is_unidentified and not self.is_fully_identified + def is_identified(self) -> bool: + return not self.is_unidentified @property def is_fully_identified(self) -> bool: @@ -324,6 +333,7 @@ class Rom(BaseModel): and bool(self.moby_id) and bool(self.ss_id) and bool(self.ra_id) + and bool(self.launchbox_id) ) def has_m3u_file(self) -> bool: diff --git a/backend/scheduler.py b/backend/scheduler.py index ec9385abd..137168173 100644 --- a/backend/scheduler.py +++ b/backend/scheduler.py @@ -1,24 +1,33 @@ import sentry_sdk from config import ( ENABLE_SCHEDULED_RESCAN, + ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA, 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_launchbox_metadata import update_launchbox_metadata_task from tasks.update_switch_titledb import update_switch_titledb_task from utils import get_version sentry_sdk.init(dsn=SENTRY_DSN, release=f"romm@{get_version()}") + if __name__ == "__main__": # Initialize the tasks 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() + + if ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA: + log.info("Starting scheduled update launchbox metadata") + update_launchbox_metadata_task.init() + # Start the scheduler tasks_scheduler.run() diff --git a/backend/tasks/fixtures/launchbox/files.xml b/backend/tasks/fixtures/launchbox/files.xml new file mode 100644 index 000000000..084152dc6 --- /dev/null +++ b/backend/tasks/fixtures/launchbox/files.xml @@ -0,0 +1,8 @@ + + + + 3DO Interactive Multiplayer + 20th Century Video Almanac (USA) + 20th Century Video Almanac (USA) + + diff --git a/backend/tasks/fixtures/launchbox/mame.xml b/backend/tasks/fixtures/launchbox/mame.xml new file mode 100644 index 000000000..896d25c59 --- /dev/null +++ b/backend/tasks/fixtures/launchbox/mame.xml @@ -0,0 +1,41 @@ + + + + wrlok_l3 + Warlok + preliminary + + Williams + 1982 + true + (L-3) + North America + false + false + false + false + false + false + false + false + false + false + false + false + Electromechanical / Pinball + Pinball + English + pinball/s7.cpp + + + Generic Keypad + Keyboard + wrlok_l3 + true + + + wrlok_l3 + Warlok (L-3) + Williams Classics + + diff --git a/backend/tasks/fixtures/launchbox/metadata.xml b/backend/tasks/fixtures/launchbox/metadata.xml new file mode 100644 index 000000000..118f399b4 --- /dev/null +++ b/backend/tasks/fixtures/launchbox/metadata.xml @@ -0,0 +1,260 @@ + + + + Paper Mario + 2000-08-11T00:00:00-07:00 + Mario pals around in an all-new action adventure! Mario's back in his first adventure since Super Mario 64, and this time, Bowser's bent on preventing a storybook ending. When Princess Peach is kidnapped, Mario plots to rescue the seven Star Spirits and rid the Mushroom Kingdom of Koopa's cruel cohorts. As he travels from the tropical jungles of Lavalava Island to the frosty heights of Shiver Mountain, he'll meet up with seven all-new companions... and he'll need help from each one or there'll be no happily ever after. + 1 + Released + false + http://www.youtube.com/watch?v=WoGJd0k_FR8 + 141 + 4.4416873449131513 + https://en.wikipedia.org/wiki/Paper_Mario_(video_game) + Nintendo 64 + E - Everyone + 403 + Role-Playing + Intelligent Systems + Nintendo + + + Mario Story + 141 + Japan + + + 纸片马力欧 + 141 + China + + + 纸片马里奥 + 141 + China + + + 141 + 5e4587a1-8505-4fd2-ace1-87613df5f5d1.png + Advertisement Flyer - Front + China + 2072259539 + + + 141 + 16231fc3-bcb3-4dbc-bbe4-f0bc36b31081.jpg + Advertisement Flyer - Front + North America + 727411021 + + + 141 + dfb30000-001e-432b-8e95-bd8e9fff3983.jpg + Advertisement Flyer - Front + North America + 583876627 + + + 141 + c417920f-1edc-4af1-95a2-2f55fb777194.jpg + Banner + 959239531 + + + 141 + e76b4339-482d-43e1-8ecb-4c6e1b442daa.jpg + Banner + 1545972692 + + + 141 + c205963e-7349-4755-8dc3-d7439a32a5a3.PNG + Box - 3D + Japan + 3690696107 + + + 141 + 1748e1a1-a1aa-4726-b9e8-4c04da848d58.png + Box - 3D + Europe + 2680176444 + + + 141 + c7ae433d-5e91-4da5-bb75-24b84b68e69c.png + Box - 3D + North America + 3778415585 + + + 141 + 0edddd5d-4175-423d-8418-9340c9eae803.jpg + Box - Back + North America + 4144827731 + + + 141 + 11a54e4a-6831-4f99-bff2-dc2e9c5bf779.jpg + Box - Back + Japan + 1527171011 + + + 141 + 10e9028c-3c48-44d1-9272-aac002e26c86.jpg + Box - Back + Europe + 1577175924 + + + 141 + 346c7be3-6533-4418-80a3-55c61f2abc11.jpg + Box - Front + Europe + 2640187913 + + + 141 + 856a0c08-0d44-4142-8315-8d0c72a679c5.jpg + Box - Front + Japan + 386642606 + + + 141 + eb7eb36a-2a90-4100-aa6b-1c9736e38ae6.png + Box - Front + North America + 390632758 + + + 141 + 310332a4-41d3-4606-bdb1-fedd21f0ea79.jpg + Box - Front + Australia + 936530111 + + + 141 + d5755b52-d75c-405d-98e7-20e54526bed3.jpg + Box - Spine + North America + 3913618231 + + + 141 + 8a47e006-a565-4906-8420-02e6de9a33ad.jpg + Box - Spine + Japan + 1761128152 + + + 141 + 90115c9c-48b9-4b79-b8ea-2033519d9923.png + Cart - 3D + North America + 3602298032 + + + 141 + 87d84d99-db78-4cbc-8450-fda0ffc3ce80.png + Cart - Front + North America + 22235904 + + + 141 + 1e0a96eb-a772-4003-9777-290ac0ea8356.png + Clear Logo + World + 2486841913 + + + 141 + 7fa59a62-99a9-4daa-a8b4-cf9681a73b55.png + Clear Logo + China + 1965202817 + + + 141 + bde294fa-b2d8-46dd-83da-4dc72623d922.png + Clear Logo + Japan + 1297661257 + + + 141 + fb6214d1-b0ba-4193-97d6-82128de00930.png + Clear Logo + Japan + 2974004483 + + + 141 + 87f88c4e-689d-4eef-958c-e65f957f4243.jpg + Fanart - Background + 3930859962 + + + 141 + fa81cb25-99d9-4de8-9526-929c1b791f4e.jpg + Fanart - Background + 397167211 + + + 141 + 70b9b270-361c-4134-8590-19760800245f.png + Fanart - Box - Front + 1787674306 + + + 141 + 7cf2a436-9ba6-42a4-9fe7-b805d6da2ccf.png + Screenshot - Game Title + China + 765939706 + + + 141 + af53b508-1585-4522-bb31-de6eb5c7f6e1.png + Screenshot - Game Title + China + 698006263 + + + 141 + 363e6708-2ec8-495a-be53-492e31d3d5f8.png + Screenshot - Game Title + Japan + 4083516316 + + + 141 + 561f42f1-9f37-4787-82b8-dd8156399c29.png + Screenshot - Game Title + North America + 2631830900 + + + 141 + 3f33ae92-6a49-4428-81b6-10ba85f4e027.png + Screenshot - Gameplay + 991180833 + + + 141 + 927204b2-64ee-4379-99a2-2a114c26f64b.png + Screenshot - Gameplay + 3132977303 + + + 141 + 15f6304e-85be-4863-a65d-9a81f25e7707.png + Screenshot - Gameplay + China + 1122730830 + + diff --git a/backend/tasks/fixtures/launchbox/platforms.xml b/backend/tasks/fixtures/launchbox/platforms.xml new file mode 100644 index 000000000..4db7fafa1 --- /dev/null +++ b/backend/tasks/fixtures/launchbox/platforms.xml @@ -0,0 +1,20 @@ + + + + 3DO Interactive Multiplayer + true + 1993-10-04T00:00:00-07:00 + The 3DO Company + Panasonic Corporation, Sanyo Electric Co., Ltd., GoldStar + 32-bit RISC ARM60 @ 12.5 MHz + 2 MB main RAM and 1 MB video RAM + 3DO "CLIO" @ 25 MHz, 3DO "MADAM" @ 25 MHz + 16-bit Stereo, Dolby Surround + 320x240 and 640x480 + CD-ROM + 1 (up to 8 if daisy-chained) + The 3DO Interactive Multiplayer (often called simply 3DO) is a video game console originally produced by Panasonic in 1993. Further renditions of the hardware were released in 1994 by Sanyo and Goldstar. The consoles were manufactured according to specifications created by The 3DO Company, and were originally designed by Dave Needle and RJ Mical of New Technology Group. The system was conceived by entrepreneur and Electronic Arts founder Trip Hawkins. + Consoles + false + + diff --git a/backend/tasks/update_launchbox_metadata.py b/backend/tasks/update_launchbox_metadata.py new file mode 100644 index 000000000..9a54e5624 --- /dev/null +++ b/backend/tasks/update_launchbox_metadata.py @@ -0,0 +1,231 @@ +import json +import zipfile +from io import BytesIO +from typing import Final + +from config import ( + ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA, + LAUNCHBOX_API_ENABLED, + SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON, +) +from defusedxml import ElementTree as ET +from handler.redis_handler import async_cache +from logger.logger import log +from tasks.tasks import RemoteFilePullTask +from utils.context import initialize_context + +LAUNCHBOX_PLATFORMS_KEY: Final = "romm:launchbox_platforms" +LAUNCHBOX_METADATA_DATABASE_ID_KEY: Final = "romm:launchbox_metadata_database_id" +LAUNCHBOX_METADATA_NAME_KEY: Final = "romm:launchbox_metadata_name" +LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY: Final = "romm:launchbox_metadata_alternate_name" +LAUNCHBOX_METADATA_IMAGE_KEY: Final = "romm:launchbox_metadata_image" +LAUNCHBOX_MAME_KEY: Final = "romm:launchbox_mame" +LAUNCHBOX_FILES_KEY: Final = "romm:launchbox_files" + + +class UpdateLaunchboxMetadataTask(RemoteFilePullTask): + def __init__(self): + super().__init__( + func="tasks.update_launchbox_metadata.update_launchbox_metadata_task.run", + description="launchbox metadata update", + enabled=ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA, + cron_string=SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON, + url="https://gamesdb.launchbox-app.com/Metadata.zip", + ) + + @initialize_context() + async def run(self, force: bool = False) -> None: + if not LAUNCHBOX_API_ENABLED: + log.warning("Launchbox API is not enabled, skipping metadata update") + return + + content = await super().run(force) + if content is None: + return + + try: + zip_file_bytes = BytesIO(content) + with zipfile.ZipFile(zip_file_bytes) as z: + for file in z.namelist(): + if file == "Platforms.xml": + with z.open(file, "r") as f: + async with async_cache.pipeline() as pipe: + ctx = ET.iterparse(f, events=("end",)) + + for _, elem in ctx: + if elem.tag == "Platform": + name_elem = elem.find("Name") + if name_elem is not None and name_elem.text: + await pipe.hset( + LAUNCHBOX_PLATFORMS_KEY, + mapping={ + name_elem.text: json.dumps( + { + child.tag: child.text + for child in elem + } + ) + }, + ) + + elem.clear() + await pipe.execute() + + elif file == "Metadata.xml": + with z.open(file, "r") as f: + async with async_cache.pipeline() as pipe: + ctx = ET.iterparse(f, events=("end",)) + + current_game_image_db_id = None + current_game_images = [] + + for _, elem in ctx: + if elem.tag == "Game": + id_elem = elem.find("DatabaseID") + if id_elem is not None and id_elem.text: + await pipe.hset( + LAUNCHBOX_METADATA_DATABASE_ID_KEY, + mapping={ + id_elem.text: json.dumps( + { + child.tag: child.text + for child in elem + } + ) + }, + ) + + name_elem = elem.find("Name") + platform_elem = elem.find("Platform") + if ( + name_elem is not None + and name_elem.text + and platform_elem is not None + and platform_elem.text + ): + # Use a unique combination of name and platform as the key + await pipe.hset( + LAUNCHBOX_METADATA_NAME_KEY, + mapping={ + f"{name_elem.text}:{platform_elem.text}": json.dumps( + { + child.tag: child.text + for child in elem + } + ) + }, + ) + elem.clear() + + elif elem.tag == "GameAlternateName": + alternate_name_elem = elem.find("AlternateName") + if ( + alternate_name_elem is not None + and alternate_name_elem.text + ): + await pipe.hset( + LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, + mapping={ + alternate_name_elem.text: json.dumps( + { + child.tag: child.text + for child in elem + } + ) + }, + ) + + elem.clear() + + elif elem.tag == "GameImage": + id_elem = elem.find("DatabaseID") + if id_elem is not None and id_elem.text: + image_id = str(id_elem.text) + + if ( + current_game_image_db_id is not None + and image_id != current_game_image_db_id + ): + # Store the previous game's images + await pipe.hset( + LAUNCHBOX_METADATA_IMAGE_KEY, + mapping={ + current_game_image_db_id: json.dumps( + current_game_images + ) + }, + ) + current_game_images = [] + + current_game_image_db_id = image_id + current_game_images.append( + { + child.tag: child.text + for child in elem + } + ) + elem.clear() + await pipe.execute() + + elif file == "Mame.xml": + with z.open(file, "r") as f: + async with async_cache.pipeline() as pipe: + ctx = ET.iterparse(f, events=("end",)) + + for _, elem in ctx: + if elem.tag == "MameFile": + filename_elem = elem.find("FileName") + if ( + filename_elem is not None + and filename_elem.text + ): + await pipe.hset( + LAUNCHBOX_MAME_KEY, + mapping={ + filename_elem.text: json.dumps( + { + child.tag: child.text + for child in elem + } + ) + }, + ) + + elem.clear() + await pipe.execute() + + elif file == "Files.xml": + with z.open(file, "r") as f: + async with async_cache.pipeline() as pipe: + ctx = ET.iterparse(f, events=("end",)) + + for _, elem in ctx: + if elem.tag == "File": + filename_elem = elem.find("FileName") + if ( + filename_elem is not None + and filename_elem.text + ): + await pipe.hset( + LAUNCHBOX_FILES_KEY, + mapping={ + filename_elem.text: json.dumps( + { + child.tag: child.text + for child in elem + } + ) + }, + ) + + elem.clear() + await pipe.execute() + + except zipfile.BadZipFile: + log.error("Bad zip file in launchbox metadata update") + return + + log.info("Scheduled launchbox metadata update completed!") + + +update_launchbox_metadata_task = UpdateLaunchboxMetadataTask() diff --git a/backend/tools/xml_diagnostics.py b/backend/tools/xml_diagnostics.py new file mode 100644 index 000000000..57b366588 --- /dev/null +++ b/backend/tools/xml_diagnostics.py @@ -0,0 +1,84 @@ +import sys +from xml.sax.handler import ContentHandler # nosec + +from defusedxml import ElementTree as ET +from defusedxml.sax import make_parser + + +class DiagnosticHandler(ContentHandler): + def __init__(self): + super().__init__() + self.line_number = 0 + self.column_number = 0 + + def setDocumentLocator(self, locator): + self.locator = locator + + def characters(self, content): + # Check for invalid XML characters + for char in content: + if ord(char) >= 0xFFFE or (ord(char) <= 0x1F and char not in "\n\r\t"): + print( + f"Found invalid character '0x{ord(char):04x}' at line {self.locator.getLineNumber()}, column {self.locator.getColumnNumber()}" + ) + + +def diagnose_xml(filename): + print(f"Analyzing {filename}...") + + # First, try to read the file in chunks to find encoding issues + try: + with open(filename, "rb") as f: + chunk_size = 8192 + chunk_number = 0 + while True: + chunk = f.read(chunk_size) + if not chunk: + break + try: + chunk.decode("utf-8") + except UnicodeDecodeError as e: + byte_pos = chunk_number * chunk_size + e.start + print(f"Found invalid UTF-8 sequence at byte position {byte_pos}") + print(f"Problematic bytes: {chunk[e.start:e.end].decode('utf-8')}") + chunk_number += 1 + except Exception as e: + print(f"Error reading file: {e}") + return + + # Then try SAX parsing for detailed error reporting + parser = make_parser() + handler = DiagnosticHandler() + parser.setContentHandler(handler) + + try: + parser.parse(filename) + except Exception as e: + print(f"SAX parsing error: {e}") + + # Finally try ElementTree parsing + try: + ET.parse(filename) + except ET.ParseError as e: + print(f"ElementTree parsing error: {e}") + + # Try to get context around the error + try: + with open(filename, "r", encoding="utf-8") as f: + lines = f.readlines() + line_num = e.position[0] + start = max(0, line_num - 2) + end = min(len(lines), line_num + 3) + print("\nContext around error:") + for i in range(start, end): + prefix = "-> " if i + 1 == line_num else " " + print(f"{prefix}{i+1}: {lines[i].rstrip()}") + except Exception as context_error: + print(f"Could not get context: {context_error}") + + +if __name__ == "__main__": + if len(sys.argv) != 2: + print("Usage: python script.py ") + sys.exit(1) + diagnose_xml(sys.argv[1]) diff --git a/backend/utils/generate_supported_platforms.py b/backend/utils/generate_supported_platforms.py index e66b6d80c..fdf637fe7 100644 --- a/backend/utils/generate_supported_platforms.py +++ b/backend/utils/generate_supported_platforms.py @@ -2,7 +2,9 @@ from typing import TypedDict from handler.metadata.igdb_handler import IGDB_PLATFORM_LIST -from handler.metadata.moby_handler import SLUG_TO_MOBY_ID +from handler.metadata.launchbox_handler import LAUNCHBOX_PLATFORM_LIST +from handler.metadata.moby_handler import MOBYGAMES_PLATFORM_LIST +from handler.metadata.ss_handler import SCREENSAVER_PLATFORM_LIST IGDB_SLUG_TO_MOBY_SLUG = { "bbcmicro": "bbc-micro", @@ -75,25 +77,42 @@ class SupportedPlatform(TypedDict): name: str igdb_slug: str | None moby_slug: str | None + ss_id: int | None + launchbox_id: int | None if __name__ == "__main__": supported_platforms: dict[str, SupportedPlatform] = {} matched_moby_slugs: list[str] = [] + matched_ss_ids: list[int] = [] + matched_launchbox_ids: list[int] = [] for plt in IGDB_PLATFORM_LIST: - moby_slug = plt["slug"] if plt["slug"] in SLUG_TO_MOBY_ID else None + moby_slug = plt["slug"] if plt["slug"] in MOBYGAMES_PLATFORM_LIST else None moby_slug = IGDB_SLUG_TO_MOBY_SLUG.get(plt["slug"], moby_slug) + + ss_platform = SCREENSAVER_PLATFORM_LIST.get(plt["slug"]) + ss_id = ss_platform["id"] if ss_platform else None + + launchbox_platform = LAUNCHBOX_PLATFORM_LIST.get(plt["slug"]) + launchbox_id = launchbox_platform["id"] if launchbox_platform else None + supported_platforms[plt["name"]] = { "name": plt["name"], "igdb_slug": plt["slug"], "moby_slug": moby_slug, + "ss_id": ss_id, + "launchbox_id": launchbox_id, } if moby_slug: matched_moby_slugs.append(moby_slug) + if ss_id: + matched_ss_ids.append(ss_id) + if launchbox_id: + matched_launchbox_ids.append(launchbox_id) # Now go over the moby ids - for slug, pltf in SLUG_TO_MOBY_ID.items(): + for slug, pltf in MOBYGAMES_PLATFORM_LIST.items(): if ( pltf["name"] not in supported_platforms and pltf["name"].lower() not in supported_platforms @@ -103,6 +122,37 @@ if __name__ == "__main__": "name": pltf["name"], "igdb_slug": None, "moby_slug": slug, + "ss_id": None, + "launchbox_id": None, + } + + # And the remaining metadata sources + for _slug, pltf in SCREENSAVER_PLATFORM_LIST.items(): + if ( + pltf["name"] not in supported_platforms + and pltf["name"].lower() not in supported_platforms + and pltf["id"] not in matched_ss_ids + ): + supported_platforms[pltf["name"]] = { + "name": pltf["name"], + "igdb_slug": None, + "moby_slug": None, + "ss_id": pltf["id"], + "launchbox_id": None, + } + + for _slug, pltf in LAUNCHBOX_PLATFORM_LIST.items(): + if ( + pltf["name"] not in supported_platforms + and pltf["name"].lower() not in supported_platforms + and pltf["id"] not in matched_launchbox_ids + ): + supported_platforms[pltf["name"]] = { + "name": pltf["name"], + "igdb_slug": None, + "moby_slug": None, + "ss_id": None, + "launchbox_id": pltf["id"], } # Sort platforms by key @@ -112,7 +162,7 @@ if __name__ == "__main__": "Below is a list of all supported platforms/systems/consoles and their respective folder names. **The folder name is case-sensitive and must be used exactly as it appears in the list below.**" ) print("\n") - print("|Platform Name|Folder Name|IGDB|Mobygames|") + print("|Platform Name|Folder Name|IGDB|Mobygames|ScreenSaver.fr|LaunchBox|") print("|---|---|---|---|") for platform in supported_platforms.values(): @@ -129,4 +179,14 @@ if __name__ == "__main__": if platform["moby_slug"] else " |" ), + ( + f'ScreenSaver.fr' + if platform["ss_id"] + else " |" + ), + ( + f'LaunchBox' + if platform["launchbox_id"] + else " |" + ), ) diff --git a/env.template b/env.template index 4edbc74a5..d42418400 100644 --- a/env.template +++ b/env.template @@ -24,6 +24,9 @@ STEAMGRIDDB_API_KEY= # RetroAchievements RETROACHIEVEMENTS_API_KEY= +# LaunchBox +LAUNCHBOX_API_ENABLED= + # Database config DB_HOST=127.0.0.1 DB_PORT=3306 @@ -69,6 +72,8 @@ ENABLE_SCHEDULED_RESCAN=true SCHEDULED_RESCAN_CRON=0 3 * * * ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB=true SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON=0 4 * * * +ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA=true +SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON= 0 5 * * * # In-browser emulation DISABLE_EMULATOR_JS=false diff --git a/frontend/assets/scrappers/launchbox.png b/frontend/assets/scrappers/launchbox.png new file mode 100644 index 000000000..ea673d641 Binary files /dev/null and b/frontend/assets/scrappers/launchbox.png differ diff --git a/frontend/assets/scrappers/sgdb.png b/frontend/assets/scrappers/sgdb.png index 3a2899dd2..21d61c346 100644 Binary files a/frontend/assets/scrappers/sgdb.png and b/frontend/assets/scrappers/sgdb.png differ diff --git a/frontend/assets/scrappers/ss.png b/frontend/assets/scrappers/ss.png index 0faf0fe0a..2969af86c 100644 Binary files a/frontend/assets/scrappers/ss.png and b/frontend/assets/scrappers/ss.png differ diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index 76dc9a4be..75da79bcd 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -28,6 +28,7 @@ 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 { LaunchboxImage } from './models/LaunchboxImage'; export type { MessageResponse } from './models/MessageResponse'; export type { MetadataSourcesDict } from './models/MetadataSourcesDict'; export type { MobyMetadataPlatform } from './models/MobyMetadataPlatform'; @@ -40,6 +41,7 @@ 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 { RomLaunchboxMetadata } from './models/RomLaunchboxMetadata'; export type { RomMetadataSchema } from './models/RomMetadataSchema'; export type { RomMobyMetadata } from './models/RomMobyMetadata'; export type { RomRAMetadata } from './models/RomRAMetadata'; diff --git a/frontend/src/__generated__/models/DetailedRomSchema.ts b/frontend/src/__generated__/models/DetailedRomSchema.ts index 94dd82c85..6ab019d1e 100644 --- a/frontend/src/__generated__/models/DetailedRomSchema.ts +++ b/frontend/src/__generated__/models/DetailedRomSchema.ts @@ -5,6 +5,7 @@ import type { CollectionSchema } from './CollectionSchema'; import type { RomFileSchema } from './RomFileSchema'; import type { RomIGDBMetadata } from './RomIGDBMetadata'; +import type { RomLaunchboxMetadata } from './RomLaunchboxMetadata'; import type { RomMetadataSchema } from './RomMetadataSchema'; import type { RomMobyMetadata } from './RomMobyMetadata'; import type { RomRAMetadata } from './RomRAMetadata'; @@ -22,6 +23,7 @@ export type DetailedRomSchema = { moby_id: (number | null); ss_id: (number | null); ra_id: (number | null); + launchbox_id: (number | null); platform_id: number; platform_slug: string; platform_fs_slug: string; @@ -43,6 +45,7 @@ export type DetailedRomSchema = { igdb_metadata: (RomIGDBMetadata | null); moby_metadata: (RomMobyMetadata | null); ss_metadata: (RomSSMetadata | null); + launchbox_metadata: (RomLaunchboxMetadata | null); path_cover_small: (string | null); path_cover_large: (string | null); url_cover: (string | null); @@ -50,6 +53,7 @@ export type DetailedRomSchema = { path_manual: (string | null); url_manual: (string | null); is_unidentified: boolean; + is_identified: boolean; revision: (string | null); regions: Array; languages: Array; diff --git a/frontend/src/__generated__/models/LaunchboxImage.ts b/frontend/src/__generated__/models/LaunchboxImage.ts new file mode 100644 index 000000000..b900b92fc --- /dev/null +++ b/frontend/src/__generated__/models/LaunchboxImage.ts @@ -0,0 +1,10 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +export type LaunchboxImage = { + url: string; + type?: string; + region?: string; +}; + diff --git a/frontend/src/__generated__/models/MetadataSourcesDict.ts b/frontend/src/__generated__/models/MetadataSourcesDict.ts index b97358344..262353745 100644 --- a/frontend/src/__generated__/models/MetadataSourcesDict.ts +++ b/frontend/src/__generated__/models/MetadataSourcesDict.ts @@ -9,5 +9,6 @@ export type MetadataSourcesDict = { SS_API_ENABLED: boolean; STEAMGRIDDB_API_ENABLED: boolean; RA_API_ENABLED: boolean; + LAUNCHBOX_API_ENABLED: boolean; }; diff --git a/frontend/src/__generated__/models/PlatformSchema.ts b/frontend/src/__generated__/models/PlatformSchema.ts index 7aa650dd7..434d7e039 100644 --- a/frontend/src/__generated__/models/PlatformSchema.ts +++ b/frontend/src/__generated__/models/PlatformSchema.ts @@ -13,6 +13,7 @@ export type PlatformSchema = { igdb_id?: (number | null); sgdb_id?: (number | null); moby_id?: (number | null); + launchbox_id?: (number | null); ss_id?: (number | null); ra_id?: (number | null); category?: (string | null); @@ -27,6 +28,8 @@ export type PlatformSchema = { created_at: string; updated_at: string; fs_size_bytes: number; + is_unidentified: boolean; + is_identified: boolean; missing_from_fs: boolean; readonly display_name: string; }; diff --git a/frontend/src/__generated__/models/RomLaunchboxMetadata.ts b/frontend/src/__generated__/models/RomLaunchboxMetadata.ts new file mode 100644 index 000000000..1c84057bb --- /dev/null +++ b/frontend/src/__generated__/models/RomLaunchboxMetadata.ts @@ -0,0 +1,21 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +import type { LaunchboxImage } from './LaunchboxImage'; +export type RomLaunchboxMetadata = { + release_date?: string; + max_players?: number; + release_type?: string; + cooperative?: boolean; + video_url?: string; + community_rating?: number; + community_rating_count?: number; + wikipedia_url?: string; + esrb?: string; + genres?: Array; + developer?: string; + publisher?: string; + images?: Array; +}; + diff --git a/frontend/src/__generated__/models/SchedulerDict.ts b/frontend/src/__generated__/models/SchedulerDict.ts index a4a41c7f9..edee58592 100644 --- a/frontend/src/__generated__/models/SchedulerDict.ts +++ b/frontend/src/__generated__/models/SchedulerDict.ts @@ -6,5 +6,6 @@ import type { TaskDict } from './TaskDict'; export type SchedulerDict = { RESCAN: TaskDict; SWITCH_TITLEDB: TaskDict; + LAUNCHBOX_METADATA: TaskDict; }; diff --git a/frontend/src/__generated__/models/SimpleRomSchema.ts b/frontend/src/__generated__/models/SimpleRomSchema.ts index 7089667b6..63e1f27cf 100644 --- a/frontend/src/__generated__/models/SimpleRomSchema.ts +++ b/frontend/src/__generated__/models/SimpleRomSchema.ts @@ -4,6 +4,7 @@ /* eslint-disable */ import type { RomFileSchema } from './RomFileSchema'; import type { RomIGDBMetadata } from './RomIGDBMetadata'; +import type { RomLaunchboxMetadata } from './RomLaunchboxMetadata'; import type { RomMetadataSchema } from './RomMetadataSchema'; import type { RomMobyMetadata } from './RomMobyMetadata'; import type { RomSSMetadata } from './RomSSMetadata'; @@ -16,6 +17,7 @@ export type SimpleRomSchema = { moby_id: (number | null); ss_id: (number | null); ra_id: (number | null); + launchbox_id: (number | null); platform_id: number; platform_slug: string; platform_fs_slug: string; @@ -37,6 +39,7 @@ export type SimpleRomSchema = { igdb_metadata: (RomIGDBMetadata | null); moby_metadata: (RomMobyMetadata | null); ss_metadata: (RomSSMetadata | null); + launchbox_metadata: (RomLaunchboxMetadata | null); path_cover_small: (string | null); path_cover_large: (string | null); url_cover: (string | null); @@ -44,6 +47,7 @@ export type SimpleRomSchema = { path_manual: (string | null); url_manual: (string | null); is_unidentified: boolean; + is_identified: boolean; revision: (string | null); regions: Array; languages: Array; diff --git a/frontend/src/components/Details/Title.vue b/frontend/src/components/Details/Title.vue index d47c54e4d..7d10f687f 100644 --- a/frontend/src/components/Details/Title.vue +++ b/frontend/src/components/Details/Title.vue @@ -90,7 +90,7 @@ const { allPlatforms } = storeToRefs(platformsStore); {{ rom.ra_id }} +
+ + + + + {{ rom.launchbox_id }} + + {{ + rom.launchbox_metadata?.community_rating?.toFixed(2) + }} + mdi-star + +
diff --git a/frontend/src/components/Gallery/AppBar/Platform/PlatformInfoDrawer.vue b/frontend/src/components/Gallery/AppBar/Platform/PlatformInfoDrawer.vue index 2ae254766..118869971 100644 --- a/frontend/src/components/Gallery/AppBar/Platform/PlatformInfoDrawer.vue +++ b/frontend/src/components/Gallery/AppBar/Platform/PlatformInfoDrawer.vue @@ -304,11 +304,7 @@ watch( @@ -332,9 +328,7 @@ watch( style="text-decoration: none; color: inherit" :href="`https://www.screenscraper.fr/systemeinfos.php?plateforme=${currentPlatform.ss_id}`" target="_blank" - :class="{ - 'ml-1': currentPlatform.igdb_id || currentPlatform.moby_id, - }" + class="ml-1" :tabindex="tabIndex" > @@ -348,7 +342,7 @@ watch( v-if="currentPlatform.moby_id" style="text-decoration: none; color: inherit" target="_blank" - :class="{ 'ml-1': currentPlatform.igdb_id }" + class="ml-1" :tabindex="tabIndex" > @@ -362,12 +356,7 @@ watch( v-if="currentPlatform.ra_id" style="text-decoration: none; color: inherit" target="_blank" - :class="{ - 'ml-1': - currentPlatform.igdb_id || - currentPlatform.ss_id || - currentPlatform.moby_id, - }" + class="ml-1" :tabindex="tabIndex" > @@ -377,6 +366,19 @@ watch( {{ currentPlatform.ra_id }} + + + + + + {{ currentPlatform.launchbox_id }} + + diff --git a/frontend/src/components/Settings/Administration/Tasks.vue b/frontend/src/components/Settings/Administration/Tasks.vue index dc2a8e680..9c139df99 100644 --- a/frontend/src/components/Settings/Administration/Tasks.vue +++ b/frontend/src/components/Settings/Administration/Tasks.vue @@ -44,6 +44,19 @@ const tasks = computed(() => [ : "mdi-clock-remove-outline", enabled: heartbeatStore.value.SCHEDULER.SWITCH_TITLEDB.ENABLED, }, + { + title: heartbeatStore.value.SCHEDULER.LAUNCHBOX_METADATA.TITLE, + description: + heartbeatStore.value.SCHEDULER.LAUNCHBOX_METADATA.MESSAGE + + " " + + convertCronExperssion( + heartbeatStore.value.SCHEDULER.LAUNCHBOX_METADATA.CRON, + ), + icon: heartbeatStore.value.SCHEDULER.LAUNCHBOX_METADATA.ENABLED + ? "mdi-clock-check-outline" + : "mdi-clock-remove-outline", + enabled: heartbeatStore.value.SCHEDULER.LAUNCHBOX_METADATA.ENABLED, + }, ]); // Functions diff --git a/frontend/src/components/common/Game/Dialog/EditRom.vue b/frontend/src/components/common/Game/Dialog/EditRom.vue index f6d0155fb..c2c1fefec 100644 --- a/frontend/src/components/common/Game/Dialog/EditRom.vue +++ b/frontend/src/components/common/Game/Dialog/EditRom.vue @@ -80,10 +80,6 @@ async function removeArtwork() { removeCover.value = true; } -const noMetadataMatch = computed(() => { - return !rom.value?.igdb_id && !rom.value?.moby_id && !rom.value?.ss_id; -}); - async function handleRomUpdate( options: { rom: UpdateRom; @@ -371,8 +367,8 @@ function closeDialog() { diff --git a/frontend/src/components/common/Game/RAvatar.vue b/frontend/src/components/common/Game/RAvatar.vue index 78102538c..5a2162587 100644 --- a/frontend/src/components/common/Game/RAvatar.vue +++ b/frontend/src/components/common/Game/RAvatar.vue @@ -8,7 +8,7 @@ const props = withDefaults(defineProps<{ rom: SimpleRom; size?: number }>(), { }); const fallbackCoverImage = computed(() => - props.rom.igdb_id || props.rom.moby_id + props.rom.is_identified ? getMissingCoverImage(props.rom.name || props.rom.fs_name) : getUnmatchedCoverImage(props.rom.name || props.rom.fs_name), ); diff --git a/frontend/src/services/api/rom.ts b/frontend/src/services/api/rom.ts index ddd6ab477..2de0cc90b 100644 --- a/frontend/src/services/api/rom.ts +++ b/frontend/src/services/api/rom.ts @@ -212,6 +212,8 @@ async function updateRom({ if (rom.igdb_id) formData.append("igdb_id", rom.igdb_id.toString()); if (rom.moby_id) formData.append("moby_id", rom.moby_id.toString()); if (rom.ss_id) formData.append("ss_id", rom.ss_id.toString()); + if (rom.launchbox_id) + formData.append("launchbox_id", rom.launchbox_id.toString()); formData.append("name", rom.name || ""); formData.append("fs_name", rom.fs_name); formData.append("summary", rom.summary || ""); diff --git a/frontend/src/stores/heartbeat.ts b/frontend/src/stores/heartbeat.ts index 54d15e7d9..04784c074 100644 --- a/frontend/src/stores/heartbeat.ts +++ b/frontend/src/stores/heartbeat.ts @@ -27,6 +27,12 @@ const defaultHeartbeat: Heartbeat = { MESSAGE: "", CRON: "", }, + LAUNCHBOX_METADATA: { + ENABLED: false, + TITLE: "", + MESSAGE: "", + CRON: "", + }, }, METADATA_SOURCES: { ANY_SOURCE_ENABLED: false, @@ -35,6 +41,7 @@ const defaultHeartbeat: Heartbeat = { MOBY_API_ENABLED: false, RA_API_ENABLED: false, STEAMGRIDDB_API_ENABLED: false, + LAUNCHBOX_API_ENABLED: false, }, FILESYSTEM: { FS_PLATFORMS: [], diff --git a/frontend/src/views/Scan.vue b/frontend/src/views/Scan.vue index 9a4d17527..a8c1fab5f 100644 --- a/frontend/src/views/Scan.vue +++ b/frontend/src/views/Scan.vue @@ -47,6 +47,12 @@ const metadataOptions = computed(() => [ logo_path: "/assets/scrappers/ra.png", disabled: !heartbeat.value.METADATA_SOURCES?.RA_API_ENABLED, }, + { + name: "Launchbox", + value: "lb", + logo_path: "/assets/scrappers/launchbox.png", + disabled: !heartbeat.value.METADATA_SOURCES?.LAUNCHBOX_API_ENABLED, + }, ]); // Use the computed metadataOptions to filter out disabled sources const metadataSources = ref(metadataOptions.value.filter((s) => !s.disabled)); @@ -364,7 +370,7 @@ async function stopScan() { >