Merge pull request #1515 from rommapp/romm-403

[ROMM-403] Import metadata from Launchbox database
This commit is contained in:
Georges-Antoine Assi
2025-06-13 12:01:27 -04:00
committed by GitHub
52 changed files with 1549 additions and 73 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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!"}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" standalone="yes"?>
<LaunchBox>
<File>
<Platform>3DO Interactive Multiplayer</Platform>
<FileName>20th Century Video Almanac (USA)</FileName>
<GameName>20th Century Video Almanac (USA)</GameName>
</File>
</LaunchBox>

View File

@@ -0,0 +1,41 @@
<?xml version="1.0" standalone="yes"?>
<LaunchBox>
<MameFile>
<FileName>wrlok_l3</FileName>
<Name>Warlok</Name>
<Status>preliminary</Status>
<Developer />
<Publisher>Williams</Publisher>
<Year>1982</Year>
<IsMechanical>true</IsMechanical>
<Version>(L-3)</Version>
<Region>North America</Region>
<IsBootleg>false</IsBootleg>
<IsPrototype>false</IsPrototype>
<IsHack>false</IsHack>
<IsMature>false</IsMature>
<IsQuiz>false</IsQuiz>
<IsFruit>false</IsFruit>
<IsCasino>false</IsCasino>
<IsRhythm>false</IsRhythm>
<IsTableTop>false</IsTableTop>
<IsPlayChoice>false</IsPlayChoice>
<IsMahjong>false</IsMahjong>
<IsNonArcade>false</IsNonArcade>
<Genre>Electromechanical / Pinball</Genre>
<PlayMode>Pinball</PlayMode>
<Language>English</Language>
<Source>pinball/s7.cpp</Source>
</MameFile>
<ControllerSupport>
<ControllerName>Generic Keypad</ControllerName>
<ControllerCategory>Keyboard</ControllerCategory>
<FileName>wrlok_l3</FileName>
<Required>true</Required>
</ControllerSupport>
<MameListItem>
<FileName>wrlok_l3</FileName>
<GameName>Warlok (L-3)</GameName>
<ListName>Williams Classics</ListName>
</MameListItem>
</LaunchBox>

View File

@@ -0,0 +1,260 @@
<?xml version="1.0" standalone="yes"?>
<LaunchBox>
<Game>
<Name>Paper Mario</Name>
<ReleaseDate>2000-08-11T00:00:00-07:00</ReleaseDate>
<Overview>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.</Overview>
<MaxPlayers>1</MaxPlayers>
<ReleaseType>Released</ReleaseType>
<Cooperative>false</Cooperative>
<VideoURL>http://www.youtube.com/watch?v=WoGJd0k_FR8</VideoURL>
<DatabaseID>141</DatabaseID>
<CommunityRating>4.4416873449131513</CommunityRating>
<WikipediaURL>https://en.wikipedia.org/wiki/Paper_Mario_(video_game)</WikipediaURL>
<Platform>Nintendo 64</Platform>
<ESRB>E - Everyone</ESRB>
<CommunityRatingCount>403</CommunityRatingCount>
<Genres> Role-Playing</Genres>
<Developer>Intelligent Systems</Developer>
<Publisher>Nintendo</Publisher>
</Game>
<GameAlternateName>
<AlternateName>Mario Story</AlternateName>
<DatabaseID>141</DatabaseID>
<Region>Japan</Region>
</GameAlternateName>
<GameAlternateName>
<AlternateName>纸片马力欧</AlternateName>
<DatabaseID>141</DatabaseID>
<Region>China</Region>
</GameAlternateName>
<GameAlternateName>
<AlternateName>纸片马里奥</AlternateName>
<DatabaseID>141</DatabaseID>
<Region>China</Region>
</GameAlternateName>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>5e4587a1-8505-4fd2-ace1-87613df5f5d1.png</FileName>
<Type>Advertisement Flyer - Front</Type>
<Region>China</Region>
<CRC32>2072259539</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>16231fc3-bcb3-4dbc-bbe4-f0bc36b31081.jpg</FileName>
<Type>Advertisement Flyer - Front</Type>
<Region>North America</Region>
<CRC32>727411021</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>dfb30000-001e-432b-8e95-bd8e9fff3983.jpg</FileName>
<Type>Advertisement Flyer - Front</Type>
<Region>North America</Region>
<CRC32>583876627</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>c417920f-1edc-4af1-95a2-2f55fb777194.jpg</FileName>
<Type>Banner</Type>
<CRC32>959239531</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>e76b4339-482d-43e1-8ecb-4c6e1b442daa.jpg</FileName>
<Type>Banner</Type>
<CRC32>1545972692</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>c205963e-7349-4755-8dc3-d7439a32a5a3.PNG</FileName>
<Type>Box - 3D</Type>
<Region>Japan</Region>
<CRC32>3690696107</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>1748e1a1-a1aa-4726-b9e8-4c04da848d58.png</FileName>
<Type>Box - 3D</Type>
<Region>Europe</Region>
<CRC32>2680176444</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>c7ae433d-5e91-4da5-bb75-24b84b68e69c.png</FileName>
<Type>Box - 3D</Type>
<Region>North America</Region>
<CRC32>3778415585</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>0edddd5d-4175-423d-8418-9340c9eae803.jpg</FileName>
<Type>Box - Back</Type>
<Region>North America</Region>
<CRC32>4144827731</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>11a54e4a-6831-4f99-bff2-dc2e9c5bf779.jpg</FileName>
<Type>Box - Back</Type>
<Region>Japan</Region>
<CRC32>1527171011</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>10e9028c-3c48-44d1-9272-aac002e26c86.jpg</FileName>
<Type>Box - Back</Type>
<Region>Europe</Region>
<CRC32>1577175924</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>346c7be3-6533-4418-80a3-55c61f2abc11.jpg</FileName>
<Type>Box - Front</Type>
<Region>Europe</Region>
<CRC32>2640187913</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>856a0c08-0d44-4142-8315-8d0c72a679c5.jpg</FileName>
<Type>Box - Front</Type>
<Region>Japan</Region>
<CRC32>386642606</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>eb7eb36a-2a90-4100-aa6b-1c9736e38ae6.png</FileName>
<Type>Box - Front</Type>
<Region>North America</Region>
<CRC32>390632758</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>310332a4-41d3-4606-bdb1-fedd21f0ea79.jpg</FileName>
<Type>Box - Front</Type>
<Region>Australia</Region>
<CRC32>936530111</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>d5755b52-d75c-405d-98e7-20e54526bed3.jpg</FileName>
<Type>Box - Spine</Type>
<Region>North America</Region>
<CRC32>3913618231</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>8a47e006-a565-4906-8420-02e6de9a33ad.jpg</FileName>
<Type>Box - Spine</Type>
<Region>Japan</Region>
<CRC32>1761128152</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>90115c9c-48b9-4b79-b8ea-2033519d9923.png</FileName>
<Type>Cart - 3D</Type>
<Region>North America</Region>
<CRC32>3602298032</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>87d84d99-db78-4cbc-8450-fda0ffc3ce80.png</FileName>
<Type>Cart - Front</Type>
<Region>North America</Region>
<CRC32>22235904</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>1e0a96eb-a772-4003-9777-290ac0ea8356.png</FileName>
<Type>Clear Logo</Type>
<Region>World</Region>
<CRC32>2486841913</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>7fa59a62-99a9-4daa-a8b4-cf9681a73b55.png</FileName>
<Type>Clear Logo</Type>
<Region>China</Region>
<CRC32>1965202817</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>bde294fa-b2d8-46dd-83da-4dc72623d922.png</FileName>
<Type>Clear Logo</Type>
<Region>Japan</Region>
<CRC32>1297661257</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>fb6214d1-b0ba-4193-97d6-82128de00930.png</FileName>
<Type>Clear Logo</Type>
<Region>Japan</Region>
<CRC32>2974004483</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>87f88c4e-689d-4eef-958c-e65f957f4243.jpg</FileName>
<Type>Fanart - Background</Type>
<CRC32>3930859962</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>fa81cb25-99d9-4de8-9526-929c1b791f4e.jpg</FileName>
<Type>Fanart - Background</Type>
<CRC32>397167211</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>70b9b270-361c-4134-8590-19760800245f.png</FileName>
<Type>Fanart - Box - Front</Type>
<CRC32>1787674306</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>7cf2a436-9ba6-42a4-9fe7-b805d6da2ccf.png</FileName>
<Type>Screenshot - Game Title</Type>
<Region>China</Region>
<CRC32>765939706</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>af53b508-1585-4522-bb31-de6eb5c7f6e1.png</FileName>
<Type>Screenshot - Game Title</Type>
<Region>China</Region>
<CRC32>698006263</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>363e6708-2ec8-495a-be53-492e31d3d5f8.png</FileName>
<Type>Screenshot - Game Title</Type>
<Region>Japan</Region>
<CRC32>4083516316</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>561f42f1-9f37-4787-82b8-dd8156399c29.png</FileName>
<Type>Screenshot - Game Title</Type>
<Region>North America</Region>
<CRC32>2631830900</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>3f33ae92-6a49-4428-81b6-10ba85f4e027.png</FileName>
<Type>Screenshot - Gameplay</Type>
<CRC32>991180833</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>927204b2-64ee-4379-99a2-2a114c26f64b.png</FileName>
<Type>Screenshot - Gameplay</Type>
<CRC32>3132977303</CRC32>
</GameImage>
<GameImage>
<DatabaseID>141</DatabaseID>
<FileName>15f6304e-85be-4863-a65d-9a81f25e7707.png</FileName>
<Type>Screenshot - Gameplay</Type>
<Region>China</Region>
<CRC32>1122730830</CRC32>
</GameImage>
</LaunchBox>

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" standalone="yes"?>
<LaunchBox>
<Platform>
<Name>3DO Interactive Multiplayer</Name>
<Emulated>true</Emulated>
<ReleaseDate>1993-10-04T00:00:00-07:00</ReleaseDate>
<Developer>The 3DO Company</Developer>
<Manufacturer>Panasonic Corporation, Sanyo Electric Co., Ltd., GoldStar</Manufacturer>
<Cpu>32-bit RISC ARM60 @ 12.5 MHz</Cpu>
<Memory>2 MB main RAM and 1 MB video RAM</Memory>
<Graphics>3DO "CLIO" @ 25 MHz, 3DO "MADAM" @ 25 MHz</Graphics>
<Sound>16-bit Stereo, Dolby Surround</Sound>
<Display>320x240 and 640x480</Display>
<Media>CD-ROM</Media>
<MaxControllers>1 (up to 8 if daisy-chained)</MaxControllers>
<Notes>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.</Notes>
<Category>Consoles</Category>
<UseMameFiles>false</UseMameFiles>
</Platform>
</LaunchBox>

View File

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

View File

@@ -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 <xml_file>")
sys.exit(1)
diagnose_xml(sys.argv[1])

View File

@@ -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'<a href="https://www.screenscraper.fr/systemeinfos.php?plateforme={platform["ss_id"]}" target="_blank" rel="noopener norefer">ScreenSaver.fr</a>'
if platform["ss_id"]
else " |"
),
(
f'<a href="https://gamesdb.launchbox-app.com/platforms/games/{platform["launchbox_id"]}" target="_blank" rel="noopener norefer">LaunchBox</a>'
if platform["launchbox_id"]
else " |"
),
)

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 146 B

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.6 KiB

After

Width:  |  Height:  |  Size: 140 KiB

View File

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

View File

@@ -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<string>;
languages: Array<string>;

View File

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

View File

@@ -9,5 +9,6 @@ export type MetadataSourcesDict = {
SS_API_ENABLED: boolean;
STEAMGRIDDB_API_ENABLED: boolean;
RA_API_ENABLED: boolean;
LAUNCHBOX_API_ENABLED: boolean;
};

View File

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

View File

@@ -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<string>;
developer?: string;
publisher?: string;
images?: Array<LaunchboxImage>;
};

View File

@@ -6,5 +6,6 @@ import type { TaskDict } from './TaskDict';
export type SchedulerDict = {
RESCAN: TaskDict;
SWITCH_TITLEDB: TaskDict;
LAUNCHBOX_METADATA: TaskDict;
};

View File

@@ -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<string>;
languages: Array<string>;

View File

@@ -90,7 +90,7 @@ const { allPlatforms } = storeToRefs(platformsStore);
</v-row>
<v-row
v-if="rom.igdb_id || rom.moby_id || rom.ss_id || rom.ra_id"
v-if="rom.is_identified"
class="text-white text-shadow mt-2"
:class="{ 'text-center': smAndDown }"
no-gutters
@@ -160,6 +160,22 @@ const { allPlatforms } = storeToRefs(platformsStore);
<span>{{ rom.ra_id }}</span>
</v-chip>
</a>
<div
v-if="rom.launchbox_id"
:class="{ 'ml-1': rom.igdb_id || rom.ss_id }"
>
<v-chip class="pl-0 mt-1" size="small">
<v-avatar class="mr-2" size="30" rounded="0">
<v-img src="/assets/scrappers/launchbox.png" />
</v-avatar>
<span>{{ rom.launchbox_id }}</span>
<v-divider class="mx-2 border-opacity-25" vertical />
<span>{{
rom.launchbox_metadata?.community_rating?.toFixed(2)
}}</span>
<v-icon class="ml-1">mdi-star</v-icon>
</v-chip>
</div>
</v-col>
</v-row>
</div>

View File

@@ -304,11 +304,7 @@ watch(
</div>
</div>
<v-row
v-if="
currentPlatform.igdb_id ||
currentPlatform.moby_id ||
currentPlatform.ss_id
"
v-if="currentPlatform.is_identified"
class="text-white text-shadow mt-2 text-center"
no-gutters
>
@@ -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"
>
<v-chip tabindex="-1" class="pl-0 mt-1" size="small" @click.stop>
@@ -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"
>
<v-chip tabindex="-1" class="pl-0 mt-1" size="small" @click.stop>
@@ -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"
>
<v-chip tabindex="-1" class="pl-0 mt-1" size="small" @click.stop>
@@ -377,6 +366,19 @@ watch(
<span>{{ currentPlatform.ra_id }}</span>
</v-chip>
</a>
<a
v-if="currentPlatform.launchbox_id"
style="text-decoration: none; color: inherit"
target="_blank"
class="ml-1"
>
<v-chip class="pl-0 mt-1" size="small" @click.stop>
<v-avatar class="mr-2" size="25" rounded="1">
<v-img src="/assets/scrappers/launchbox.png" />
</v-avatar>
<span>{{ currentPlatform.launchbox_id }}</span>
</v-chip>
</a>
</v-col>
</v-row>
<v-card class="mt-4 bg-toplayer fill-width" elevation="0">

View File

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

View File

@@ -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() {
</v-row>
<v-row class="justify-space-between px-4 py-2 mt-1" no-gutters>
<v-btn
:disabled="noMetadataMatch"
:class="` ${noMetadataMatch ? '' : 'bg-toplayer text-romm-red'}`"
:disabled="rom.is_unidentified"
:class="` ${rom.is_unidentified ? '' : 'bg-toplayer text-romm-red'}`"
variant="flat"
@click="unmatchRom"
>

View File

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

View File

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

View File

@@ -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: [],

View File

@@ -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() {
>
<template #append-body>
<v-chip
v-if="!rom.igdb_id && !rom.moby_id && !rom.ss_id"
v-if="rom.is_unidentified"
color="red"
size="x-small"
label

16
poetry.lock generated
View File

@@ -1,4 +1,4 @@
# This file is automatically @generated by Poetry 2.1.3 and should not be changed by hand.
# This file is automatically @generated by Poetry 2.1.2 and should not be changed by hand.
[[package]]
name = "aiohappyeyeballs"
@@ -697,6 +697,18 @@ files = [
{file = "decorator-5.1.1.tar.gz", hash = "sha256:637996211036b6385ef91435e4fae22989472f9d571faba8927ba8253acbc330"},
]
[[package]]
name = "defusedxml"
version = "0.7.1"
description = "XML bomb protection for Python stdlib modules"
optional = false
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*"
groups = ["main"]
files = [
{file = "defusedxml-0.7.1-py2.py3-none-any.whl", hash = "sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61"},
{file = "defusedxml-0.7.1.tar.gz", hash = "sha256:1bb3032db185915b62d7c6209c5a8792be6a32ab2fedacc84e01b52c51aa3e69"},
]
[[package]]
name = "emoji"
version = "2.10.1"
@@ -4443,4 +4455,4 @@ test = ["fakeredis", "pytest", "pytest-asyncio", "pytest-env", "pytest-mock", "p
[metadata]
lock-version = "2.1"
python-versions = "^3.12"
content-hash = "d3b1b339e055745c1a0118769e94c55271bb04edc99bfa57be3b29387a71f8bb"
content-hash = "b2a8d562ee0d10d98fb31df079db168c57360de0df9507eeaacb3b0fd097331a"

View File

@@ -19,8 +19,10 @@ dependencies = [
"authlib ~= 1.3",
"certifi == 2024.07.04",
"colorama ~= 0.4",
"defusedxml ~= 0.7.1",
"emoji == 2.10.1",
"fastapi == 0.115.6",
"fastapi-pagination (>=0.12.34,<0.13.0)",
"gunicorn == 23.0.0",
"httpx ~= 0.27",
"itsdangerous ~= 2.1",
@@ -45,14 +47,13 @@ dependencies = [
"types-passlib ~= 1.7",
"types-pyyaml ~= 6.0",
"types-redis ~= 4.6",
"ua-parser (>=1.0.1,<2.0.0)",
"user-agents (>=2.2.0,<3.0.0)",
"uvicorn == 0.29.0",
"watchdog ~= 4.0",
"websockets == 12.0",
"yarl ~= 1.14",
"zipfile-deflate64 ~= 0.2",
"fastapi-pagination (>=0.12.34,<0.13.0)",
"ua-parser (>=1.0.1,<2.0.0)",
"user-agents (>=2.2.0,<3.0.0)",
]
[project.optional-dependencies]

View File

@@ -12,9 +12,7 @@ env =
ENABLE_RESCAN_ON_FILESYSTEM_CHANGE=true
ENABLE_SCHEDULED_RESCAN=true
ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB=true
RESCAN_ON_FILESYSTEM_CHANGE_DELAY=5
SCHEDULED_RESCAN_CRON=0 3 * * *
SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON=0 4 * * *
ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA=true
UPLOAD_TIMEOUT=20
LOGLEVEL=DEBUG
DEV_MODE=false