Merge branch 'master' into romm-1984

This commit is contained in:
zurdi
2025-06-16 09:19:59 +00:00
80 changed files with 2238 additions and 454 deletions

View File

@@ -31,8 +31,10 @@ sudo apt install libmariadb3 libmariadb-dev libpq-dev pipx
# Build and configure RAHasher (optional)
# IMPORTANT! This is only required to calculate RA hashes. This is needed only if RA API is going to be enabled
git clone --recursive --branch 1.8.0 --depth 1 https://github.com/RetroAchievements/RALibretro.git
git clone --recursive https://github.com/RetroAchievements/RALibretro.git
cd ./RALibretro
git checkout 1.8.0
git submodule update --init --recursive
sed -i '22a #include <ctime>' ./src/Util.h
make HAVE_CHD=1 -f ./Makefile.RAHasher
cp ./bin64/RAHasher /usr/bin/RAHasher
@@ -53,14 +55,14 @@ Then create the virtual environment
```sh
# Fix disable parallel installation stuck: $> poetry config experimental.new-installer false
# Fix Loading macOS/linux stuck: $> export PYTHON_KEYRING_BACKEND=keyring.backends.null.Keyring
poetry sync
poetry sync --all-extras
```
If you are on Arch Linux or another Arch-based distro, you need to run the command as follows:
```sh
# https://bbs.archlinux.org/viewtopic.php?id=296542
CFLAGS="-Wno-error=incompatible-pointer-types" poetry sync
CFLAGS="-Wno-error=incompatible-pointer-types" poetry sync --all-extras
```
#### - Spin up mariadb in docker

View File

@@ -1,7 +1,6 @@
import asyncio
import re
from handler.metadata.ra_handler import RA_ID_TO_SLUG
from logger.formatter import LIGHTMAGENTA
from logger.formatter import highlight as hl
from logger.logger import log
@@ -97,6 +96,8 @@ class RAHasherService:
"""Service to calculate RetroAchievements hashes using RAHasher."""
async def calculate_hash(self, platform_id: int, file_path: str) -> str:
from handler.metadata.ra_handler import RA_ID_TO_SLUG
log.debug(
f"Executing {hl('RAHasher', color=LIGHTMAGENTA)} for platform: {hl(RA_ID_TO_SLUG[platform_id])} - file: {hl(file_path.split('/')[-1])}"
)

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

@@ -59,6 +59,9 @@ IGDB_CLIENT_SECRET: Final = os.environ.get(
"IGDB_CLIENT_SECRET", os.environ.get("CLIENT_SECRET", "")
).strip()
# MOBYGAMES
MOBYGAMES_API_KEY: Final = os.environ.get("MOBYGAMES_API_KEY", "").strip()
# SCREENSCRAPER
SCREENSCRAPER_USER: Final = os.environ.get("SCREENSCRAPER_USER", "")
SCREENSCRAPER_PASSWORD: Final = os.environ.get("SCREENSCRAPER_PASSWORD", "")
@@ -72,8 +75,15 @@ REFRESH_RETROACHIEVEMENTS_CACHE_DAYS: Final = int(
os.environ.get("REFRESH_RETROACHIEVEMENTS_CACHE_DAYS", 30)
)
# MOBYGAMES
MOBYGAMES_API_KEY: Final = os.environ.get("MOBYGAMES_API_KEY", "").strip()
# LAUNCHBOX
LAUNCHBOX_API_ENABLED: Final = str_to_bool(
os.environ.get("LAUNCHBOX_API_ENABLED", "false")
)
# PLAYMATCH
PLAYMATCH_API_ENABLED: Final = str_to_bool(
os.environ.get("PLAYMATCH_API_ENABLED", "false")
)
# AUTH
ROMM_AUTH_SECRET_KEY: Final = os.environ.get(
@@ -123,6 +133,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,15 @@ 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,
PLAYMATCH_API_ENABLED,
RESCAN_ON_FILESYSTEM_CHANGE_DELAY,
SCHEDULED_RESCAN_CRON,
SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON,
SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON,
UPLOAD_TIMEOUT,
)
@@ -45,12 +49,17 @@ 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
or PLAYMATCH_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,
# Platmatch requires use of the IGDB API
"PLAYMATCH_API_ENABLED": PLAYMATCH_API_ENABLED and IGDB_API_ENABLED,
},
"FILESYSTEM": {
"FS_PLATFORMS": fs_platform_handler.get_platforms(),
@@ -73,6 +82,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,8 @@ class MetadataSourcesDict(TypedDict):
SS_API_ENABLED: bool
STEAMGRIDDB_API_ENABLED: bool
RA_API_ENABLED: bool
LAUNCHBOX_API_ENABLED: bool
PLAYMATCH_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

@@ -1,6 +1,5 @@
from __future__ import annotations
import zlib
from dataclasses import dataclass
from itertools import batched
from typing import Any, Final
@@ -26,15 +25,13 @@ from handler.filesystem import (
from handler.filesystem.roms_handler import FSRom
from handler.redis_handler import high_prio_queue, redis_client
from handler.scan_handler import (
MetadataSource,
ScanType,
fetch_ra_info,
scan_firmware,
scan_platform,
scan_rom,
)
from handler.socket_handler import socket_handler
from logger.formatter import BLUE, LIGHTYELLOW, RED
from logger.formatter import BLUE, LIGHTYELLOW
from logger.formatter import highlight as hl
from logger.logger import log
from models.platform import Platform
@@ -45,37 +42,6 @@ from sqlalchemy.inspection import inspect
from utils.context import initialize_context
STOP_SCAN_FLAG: Final = "scan:stop"
NON_HASHABLE_PLATFORMS = frozenset(
(
"amazon-alexa",
"amazon-fire-tv",
"android",
"gear-vr",
"ios",
"ipad",
"linux",
"mac",
"meta-quest-2",
"meta-quest-3",
"oculus-go",
"oculus-quest",
"oculus-rift",
"pc",
"ps3",
"ps4",
"ps4--1",
"ps5",
"psvr",
"psvr2",
"series-x",
"switch",
"wiiu",
"win",
"xbox-360",
"xbox360",
"xboxone",
)
)
@dataclass
@@ -135,58 +101,6 @@ async def _identify_firmware(
return scan_stats
async def _set_rom_hashes(rom_id: int) -> str:
"""Set the hashes for the given rom
Args:
rom_id (int): Rom id
Returns:
ra_hash (str): Calculated retroachievements hash
"""
rom = db_rom_handler.get_rom(rom_id)
if not rom:
return ""
try:
rom_hash, rom_file_hashes = await fs_rom_handler.get_rom_hashes(rom)
except zlib.error as e:
# Set empty hashes if calculating them fails for corrupted files
log.error(
f"Hashes of {hl(rom.fs_name)} couldn't be calculated: {hl(str(e), color=RED)}"
)
db_rom_handler.update_rom(
rom_id,
{
"crc_hash": "",
"md5_hash": "",
"sha1_hash": "",
"ra_hash": "",
},
)
return ""
else:
db_rom_handler.update_rom(
rom_id,
{
"crc_hash": rom_hash["crc_hash"],
"md5_hash": rom_hash["md5_hash"],
"sha1_hash": rom_hash["sha1_hash"],
"ra_hash": rom_hash["ra_hash"],
},
)
for file_hash in rom_file_hashes:
db_rom_handler.update_rom_file(
file_hash["id"],
{
"crc_hash": file_hash["crc_hash"],
"md5_hash": file_hash["md5_hash"],
"sha1_hash": file_hash["sha1_hash"],
"ra_hash": rom_hash["ra_hash"],
},
)
return rom_hash["ra_hash"]
def _should_scan_rom(scan_type: ScanType, rom: Rom | None, roms_ids: list[str]) -> bool:
"""Decide if a rom should be scanned or not
@@ -205,13 +119,19 @@ 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)
)
)
)
# There's an order of operations here that is important:
# 1. Read the list of roms from the filesystem
# 2. Check if ROM should be scanned based on the scan type
# 3. Create a new ROM entry if it doesn't exist
# 4. Build the ROM files and calculate the hashes
# 4. Scan the ROM and update its metadata
async def _identify_rom(
platform: Platform,
fs_rom: FSRom,
@@ -239,24 +159,56 @@ async def _identify_rom(
return scan_stats
# Create the entry early so we have the ID
newly_added: bool = rom is None
if not rom:
rom = db_rom_handler.add_rom(
Rom(
multi=fs_rom["multi"],
fs_name=fs_rom["fs_name"],
platform_id=platform.id,
name=fs_rom["fs_name"],
url_cover="",
url_manual="",
url_screenshots=[],
)
)
# Silly checks to make the type checker happy
if not rom:
return scan_stats
# Build rom files object before scanning
rom_files, rom_crc_c, rom_md5_h, rom_sha1_h, rom_ra_h = (
await fs_rom_handler.get_rom_files(rom)
)
fs_rom.update(
{
"files": rom_files,
"crc_hash": rom_crc_c,
"md5_hash": rom_md5_h,
"sha1_hash": rom_sha1_h,
"ra_hash": rom_ra_h,
}
)
scanned_rom = await scan_rom(
platform=platform,
fs_rom=fs_rom,
scan_type=scan_type,
platform=platform,
rom=rom,
fs_rom=fs_rom,
metadata_sources=metadata_sources,
newly_added=newly_added,
)
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)
# Delete the existing rom files in the DB
db_rom_handler.missing_rom_files(_added_rom.id)
db_rom_handler.purge_rom_files(_added_rom.id)
# Create each file entry for the rom
new_rom_files = [
@@ -267,49 +219,34 @@ async def _identify_rom(
file_size_bytes=file.file_size_bytes,
last_modified=file.last_modified,
category=file.category,
crc_hash=file.crc_hash,
md5_hash=file.md5_hash,
sha1_hash=file.sha1_hash,
ra_hash=file.ra_hash,
)
for file in fs_rom["files"]
for file in rom_files
]
for new_rom_file in new_rom_files:
db_rom_handler.add_rom_file(new_rom_file)
# Calculating hashes is expensive, so we only do it if necessary
if (
not rom
or not rom.ra_id
or scan_type == ScanType.COMPLETE
or scan_type == ScanType.HASHES
or MetadataSource.RA in metadata_sources
):
# Skip hashing games for platforms that don't have a hash database
if platform.slug not in NON_HASHABLE_PLATFORMS:
ra_hash = await _set_rom_hashes(_added_rom.id)
if ra_hash:
ra_handler_rom = await fetch_ra_info(
platform=platform,
rom_id=_added_rom.id,
hash=ra_hash,
)
_added_rom.ra_id = ra_handler_rom.get("ra_id", None)
ra_metadata = ra_handler_rom.get("ra_metadata", None)
if ra_metadata:
_added_rom.ra_metadata = dict(ra_metadata)
for a in ra_metadata.get("achievements", {}):
# Store both normal and locked version
badge_url_lock = a.get("badge_url_lock", None)
badge_path_lock = a.get("badge_path_lock", None)
if badge_url_lock and badge_path_lock:
await fs_resource_handler.store_badge(
badge_url_lock, badge_path_lock
)
badge_url = a.get("badge_url", None)
badge_path = a.get("badge_path", None)
if badge_url and badge_path:
await fs_resource_handler.store_badge(badge_url, badge_path)
if _added_rom.ra_metadata:
fs_resource_handler.create_ra_resources_path(platform.id, _added_rom.id)
# Return early if we're only scanning for hashes
if scan_type == ScanType.HASHES:
return scan_stats
# Store the achievements badges
for ach in _added_rom.ra_metadata.get("achievements", []):
# Store both normal and locked version
badge_url_lock = ach.get("badge_url_lock", None)
badge_path_lock = ach.get("badge_path_lock", None)
if badge_url_lock and badge_path_lock:
badge_path_lock = f"{fs_resource_handler.get_ra_badges_path(platform.id, _added_rom.id)}/{badge_path_lock}"
await fs_resource_handler.store_ra_badge(
badge_url_lock, badge_path_lock
)
badge_url = ach.get("badge_url", None)
badge_path = ach.get("badge_path", None)
if badge_url and badge_path:
badge_path = f"{fs_resource_handler.get_ra_badges_path(platform.id, _added_rom.id)}/{badge_path}"
await fs_resource_handler.store_ra_badge(badge_url, badge_path)
path_cover_s, path_cover_l = await fs_resource_handler.get_cover(
entity=_added_rom,
@@ -383,12 +320,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)
@@ -423,7 +361,7 @@ async def _identify_platform(
# Scanning roms
try:
fs_roms = fs_rom_handler.get_roms(platform.fs_slug)
fs_roms = await fs_rom_handler.get_roms(platform)
except RomsNotFoundException as e:
log.error(e)
return scan_stats
@@ -492,16 +430,13 @@ async def scan_platforms(
if not roms_ids:
roms_ids = []
if not metadata_sources:
metadata_sources = [
MetadataSource.IGDB,
MetadataSource.MOBY,
MetadataSource.SS,
MetadataSource.RA,
]
sm = _get_socket_manager()
if not metadata_sources:
log.error("No metadata sources provided")
await sm.emit("scan:done_ko", "No metadata sources provided")
return
try:
fs_platforms: list[str] = fs_platform_handler.get_platforms()
except FolderStructureNotMatchException as e:
@@ -564,7 +499,7 @@ async def scan_platforms(
raise e
@socket_handler.socket_server.on("scan")
@socket_handler.socket_server.on("scan") # type: ignore
async def scan_handler(_sid: str, options: dict):
"""Scan socket endpoint
@@ -597,7 +532,7 @@ async def scan_handler(_sid: str, options: dict):
)
@socket_handler.socket_server.on("scan:stop")
@socket_handler.socket_server.on("scan:stop") # type: ignore
async def stop_scan_handler(_sid: str):
"""Stop scan socket endpoint"""

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),
)
@@ -783,16 +787,15 @@ class DBRomsHandler(DBBaseHandler):
return session.query(RomFile).filter_by(id=id).one()
@begin_session
def missing_rom_files(
def purge_rom_files(
self, rom_id: int, session: Session = None
) -> Sequence[RomFile]:
missing_rom_files = (
purged_rom_files = (
session.scalars(select(RomFile).filter_by(rom_id=rom_id)).unique().all()
)
session.execute(
update(RomFile)
delete(RomFile)
.where(RomFile.rom_id == rom_id)
.values(**{"missing_from_fs": True})
.execution_options(synchronize_session="evaluate")
)
return missing_rom_files
return purged_rom_files

View File

@@ -1,3 +1,4 @@
import os
import shutil
import httpx
@@ -46,22 +47,6 @@ class FSResourcesHandler(FSHandler):
small_img = cover.resize(small_size)
small_img.save(save_path)
async def store_badge(self, url: str, file_path: str) -> None:
httpx_client = ctx_httpx_client.get()
try:
async with httpx_client.stream("GET", url, timeout=120) as response:
if response.status_code == 200:
await Path(f"{RESOURCES_BASE_PATH}/{file_path}").parent.mkdir(
parents=True, exist_ok=True
)
async with await Path(f"{RESOURCES_BASE_PATH}/{file_path}").open(
"wb"
) as f:
async for chunk in response.aiter_raw():
await f.write(chunk)
except httpx.TransportError as exc:
log.error(f"Unable to fetch cover at {url}: {str(exc)}")
async def _store_cover(
self, entity: Rom | Collection, url_cover: str, size: CoverSize
) -> None:
@@ -273,3 +258,39 @@ class FSResourcesHandler(FSHandler):
path_manual = (await self._get_manual_path(rom)) if manual_exists else ""
return path_manual
async def store_ra_badge(self, url: str, file_path: str) -> None:
httpx_client = ctx_httpx_client.get()
try:
async with httpx_client.stream("GET", url, timeout=120) as response:
if response.status_code == 200:
await Path(f"{RESOURCES_BASE_PATH}/{file_path}").parent.mkdir(
parents=True, exist_ok=True
)
async with await Path(f"{RESOURCES_BASE_PATH}/{file_path}").open(
"wb"
) as f:
async for chunk in response.aiter_raw():
await f.write(chunk)
except httpx.TransportError as exc:
log.error(f"Unable to fetch cover at {url}: {str(exc)}")
def get_ra_base_path(self, platform_id: int, rom_id: int) -> str:
return os.path.join(
"roms",
str(platform_id),
str(rom_id),
"retroachievements",
)
def get_ra_badges_path(self, platform_id: int, rom_id: int) -> str:
return os.path.join(self.get_ra_base_path(platform_id, rom_id), "badges")
def create_ra_resources_path(self, platform_id: int, rom_id: int) -> None:
os.makedirs(
os.path.join(
RESOURCES_BASE_PATH,
self.get_ra_base_path(platform_id, rom_id),
),
exist_ok=True,
)

View File

@@ -7,9 +7,10 @@ import re
import shutil
import tarfile
import zipfile
import zlib
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
@@ -18,7 +19,7 @@ from adapters.services.rahasher import RAHasherService
from config import LIBRARY_BASE_PATH
from config.config_manager import config_manager as cm
from exceptions.fs_exceptions import RomAlreadyExistsException, RomsNotFoundException
from handler.metadata.ra_handler import SLUG_TO_RA_ID
from models.platform import Platform
from models.rom import Rom, RomFile, RomFileCategory
from py7zr.exceptions import (
Bad7zFile,
@@ -61,6 +62,38 @@ COMPRESSED_FILE_EXTENSIONS = frozenset(
)
)
NON_HASHABLE_PLATFORMS = frozenset(
(
"amazon-alexa",
"amazon-fire-tv",
"android",
"gear-vr",
"ios",
"ipad",
"linux",
"mac",
"meta-quest-2",
"meta-quest-3",
"oculus-go",
"oculus-quest",
"oculus-rift",
"pc",
"ps3",
"ps4",
"ps4--1",
"ps5",
"psvr",
"psvr2",
"series-x",
"switch",
"wiiu",
"win",
"xbox-360",
"xbox360",
"xboxone",
)
)
FILE_READ_CHUNK_SIZE = 1024 * 8
@@ -68,16 +101,18 @@ class FSRom(TypedDict):
multi: bool
fs_name: str
files: list[RomFile]
class FileHash(TypedDict):
id: int
crc_hash: str
md5_hash: str
sha1_hash: str
ra_hash: str
class FileHash(TypedDict):
crc_hash: str
md5_hash: str
sha1_hash: str
def is_compressed_file(file_path: str) -> bool:
mime = magic.Magic(mime=True)
file_type = mime.from_file(file_path)
@@ -87,22 +122,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(
@@ -251,7 +287,9 @@ class FSRomsHandler(FSHandler):
return [f for f in roms if f not in filtered_files]
def _build_rom_file(self, rom_path: Path, file_name: str) -> RomFile:
def _build_rom_file(
self, rom_path: Path, file_name: str, file_hash: FileHash
) -> RomFile:
# Absolute path to roms
abs_file_path = Path(LIBRARY_BASE_PATH, rom_path, file_name)
@@ -271,17 +309,40 @@ class FSRomsHandler(FSHandler):
file_size_bytes=os.stat(abs_file_path).st_size,
last_modified=os.path.getmtime(abs_file_path),
category=matching_category,
crc_hash=file_hash["crc_hash"],
md5_hash=file_hash["md5_hash"],
sha1_hash=file_hash["sha1_hash"],
)
def get_rom_files(self, rom: str, roms_path: str) -> list[RomFile]:
abs_fs_path = f"{LIBRARY_BASE_PATH}/{roms_path}" # Absolute path to roms
async def get_rom_files(self, rom: Rom) -> tuple[list[RomFile], str, str, str, str]:
from handler.metadata.ra_handler import SLUG_TO_RA_ID
rel_roms_path = self.get_roms_fs_structure(
rom.platform.fs_slug
) # Relative path to roms
abs_fs_path = f"{LIBRARY_BASE_PATH}/{rel_roms_path}" # Absolute path to roms
rom_files: list[RomFile] = []
# Skip hashing games for platforms that don't have a hash database
hashable_platform = rom.platform_slug not in NON_HASHABLE_PLATFORMS
excluded_file_names = cm.get_config().EXCLUDED_MULTI_PARTS_FILES
excluded_file_exts = cm.get_config().EXCLUDED_MULTI_PARTS_EXT
rom_crc_c = 0
rom_md5_h = hashlib.md5(usedforsecurity=False)
rom_sha1_h = hashlib.sha1(usedforsecurity=False)
rom_ra_h = ""
# Check if rom is a multi-part rom
if os.path.isdir(f"{abs_fs_path}/{rom}"):
# Calculate the RA hash if the platform has a slug that matches a known RA slug
if rom.platform_slug in SLUG_TO_RA_ID.keys():
rom_ra_h = await RAHasherService().calculate_hash(
SLUG_TO_RA_ID[rom.platform_slug]["id"],
f"{abs_fs_path}/{rom.fs_name}/*",
)
for f_path, file_name in iter_files(f"{abs_fs_path}/{rom}", recursive=True):
# Check if file is excluded
ext = self.parse_file_extension(file_name)
@@ -294,15 +355,102 @@ class FSRomsHandler(FSHandler):
):
continue
if hashable_platform:
try:
crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h = (
self._calculate_rom_hashes(
Path(f_path, file_name),
rom_crc_c,
rom_md5_h,
rom_sha1_h,
)
)
except zlib.error:
crc_c = 0
md5_h = hashlib.md5(usedforsecurity=False)
sha1_h = hashlib.sha1(usedforsecurity=False)
file_hash = FileHash(
crc_hash=crc32_to_hex(crc_c) if crc_c != DEFAULT_CRC_C else "",
md5_hash=(
md5_h.hexdigest()
if md5_h.digest() != DEFAULT_MD5_H_DIGEST
else ""
),
sha1_hash=(
sha1_h.hexdigest()
if sha1_h.digest() != DEFAULT_SHA1_H_DIGEST
else ""
),
)
else:
file_hash = FileHash(
crc_hash="",
md5_hash="",
sha1_hash="",
)
rom_files.append(
self._build_rom_file(
f_path.relative_to(LIBRARY_BASE_PATH), file_name
f_path.relative_to(LIBRARY_BASE_PATH),
file_name,
file_hash,
)
)
else:
rom_files.append(self._build_rom_file(Path(roms_path), rom))
elif hashable_platform:
try:
crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h = (
self._calculate_rom_hashes(
Path(abs_fs_path, rom.fs_name), rom_crc_c, rom_md5_h, rom_sha1_h
)
)
except zlib.error:
crc_c = 0
md5_h = hashlib.md5(usedforsecurity=False)
sha1_h = hashlib.sha1(usedforsecurity=False)
return rom_files
# Calculate the RA hash if the platform has a slug that matches a known RA slug
if rom.platform_slug in SLUG_TO_RA_ID.keys():
rom_ra_h = await RAHasherService().calculate_hash(
SLUG_TO_RA_ID[rom.platform_slug]["id"],
f"{abs_fs_path}/{rom.fs_name}",
)
file_hash = FileHash(
crc_hash=crc32_to_hex(crc_c) if crc_c != DEFAULT_CRC_C else "",
md5_hash=(
md5_h.hexdigest() if md5_h.digest() != DEFAULT_MD5_H_DIGEST else ""
),
sha1_hash=(
sha1_h.hexdigest()
if sha1_h.digest() != DEFAULT_SHA1_H_DIGEST
else ""
),
)
rom_files.append(
self._build_rom_file(Path(rel_roms_path), rom.fs_name, file_hash)
)
else:
file_hash = FileHash(
crc_hash="",
md5_hash="",
sha1_hash="",
)
rom_files.append(
self._build_rom_file(Path(rel_roms_path), rom.fs_name, file_hash)
)
return (
rom_files,
crc32_to_hex(rom_crc_c) if rom_crc_c != DEFAULT_CRC_C else "",
rom_md5_h.hexdigest() if rom_md5_h.digest() != DEFAULT_MD5_H_DIGEST else "",
(
rom_sha1_h.hexdigest()
if rom_sha1_h.digest() != DEFAULT_SHA1_H_DIGEST
else ""
),
rom_ra_h,
)
def _calculate_rom_hashes(
self,
@@ -371,63 +519,7 @@ class FSRomsHandler(FSHandler):
rom_sha1_h,
)
async def get_rom_hashes(self, rom: Rom) -> tuple[FileHash, list[FileHash]]:
rom_crc_c = 0
rom_md5_h = hashlib.md5(usedforsecurity=False)
rom_sha1_h = hashlib.sha1(usedforsecurity=False)
files = rom.files
hashed_files = []
for file in files:
path = Path(LIBRARY_BASE_PATH, file.file_path, file.file_name)
crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h = (
self._calculate_rom_hashes(path, rom_crc_c, rom_md5_h, rom_sha1_h)
)
hashed_files.append(
FileHash(
id=file.id,
crc_hash=crc32_to_hex(crc_c) if crc_c != DEFAULT_CRC_C else "",
md5_hash=(
md5_h.hexdigest()
if md5_h.digest() != DEFAULT_MD5_H_DIGEST
else ""
),
sha1_hash=(
sha1_h.hexdigest()
if sha1_h.digest() != DEFAULT_SHA1_H_DIGEST
else ""
),
ra_hash="",
)
)
return (
FileHash(
id=rom.id,
crc_hash=crc32_to_hex(rom_crc_c) if rom_crc_c != DEFAULT_CRC_C else "",
md5_hash=(
rom_md5_h.hexdigest()
if rom_md5_h.digest() != DEFAULT_MD5_H_DIGEST
else ""
),
sha1_hash=(
rom_sha1_h.hexdigest()
if rom_sha1_h.digest() != DEFAULT_SHA1_H_DIGEST
else ""
),
ra_hash=(
await RAHasherService().calculate_hash(
SLUG_TO_RA_ID[rom.platform.slug]["id"],
f"{LIBRARY_BASE_PATH}/{rom.fs_path}/{rom.fs_name}{'/*' if rom.multi else ''}",
)
if rom.platform.slug in SLUG_TO_RA_ID.keys()
else ""
),
),
hashed_files,
)
def get_roms(self, platform_fs_slug: str) -> list[FSRom]:
async def get_roms(self, platform: Platform) -> list[FSRom]:
"""Gets all filesystem roms for a platform
Args:
@@ -436,19 +528,19 @@ class FSRomsHandler(FSHandler):
list with all the filesystem roms for a platform found in the LIBRARY_BASE_PATH
"""
rel_roms_path = self.get_roms_fs_structure(
platform_fs_slug
platform.fs_slug
) # Relative path to roms
abs_fs_path = f"{LIBRARY_BASE_PATH}/{rel_roms_path}" # Absolute path to roms
try:
fs_single_roms = [f for _, f in iter_files(abs_fs_path)]
except IndexError as exc:
raise RomsNotFoundException(platform_fs_slug) from exc
raise RomsNotFoundException(platform.fs_slug) from exc
try:
fs_multi_roms = [d for _, d in iter_directories(abs_fs_path)]
except IndexError as exc:
raise RomsNotFoundException(platform_fs_slug) from exc
raise RomsNotFoundException(platform.fs_slug) from exc
fs_roms: list[dict] = [
{"multi": False, "fs_name": rom}
@@ -463,7 +555,11 @@ class FSRomsHandler(FSHandler):
FSRom(
multi=rom["multi"],
fs_name=rom["fs_name"],
files=self.get_rom_files(rom["fs_name"], rel_roms_path),
files=[],
crc_hash="",
md5_hash="",
sha1_hash="",
ra_hash="",
)
for rom in fs_roms
],

View File

@@ -27,9 +27,9 @@ def test_get_roms_fs_structure():
assert roms_structure == "n64/roms"
def test_get_roms():
async def test_get_roms():
platform = Platform(name="Nintendo 64", slug="n64", fs_slug="n64")
roms = fs_rom_handler.get_roms(platform_fs_slug=platform.fs_slug)
roms = await fs_rom_handler.get_roms(platform)
assert len(roms) == 2
assert roms[0]["fs_name"] == "Paper Mario (USA).z64"

View File

@@ -1,5 +1,7 @@
from .igdb_handler import IGDBHandler
from .launchbox_handler import LaunchboxHandler
from .moby_handler import MobyGamesHandler
from .pm_handler import PlaymatchHandler
from .ra_handler import RAHandler
from .sgdb_handler import SGDBBaseHandler
from .ss_handler import SSHandler
@@ -9,3 +11,5 @@ meta_moby_handler = MobyGamesHandler()
meta_ss_handler = SSHandler()
meta_sgdb_handler = SGDBBaseHandler()
meta_ra_handler = RAHandler()
meta_pm_handler = PlaymatchHandler()
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

@@ -0,0 +1,157 @@
from enum import Enum
from typing import NotRequired, TypedDict
import httpx
import yarl
from config import PLAYMATCH_API_ENABLED
from fastapi import HTTPException, status
from logger.logger import log
from models.rom import RomFile
from utils import get_version
from utils.context import ctx_httpx_client
class PlaymatchProvider(str, Enum):
"""
Enum for Playmatch Providers.
"""
IGDB = "IGDB"
class GameMatchType(str, Enum):
"""
Enum for Game Match Types.
"""
SHA256 = "SHA256"
SHA1 = "SHA1"
MD5 = "MD5"
FileNameAndSize = "FileNameAndSize"
NoMatch = "NoMatch"
class PlaymatchExternalMetadata(TypedDict):
automaticMatchReason: NotRequired[str]
comment: NotRequired[str]
failedMatchReason: NotRequired[str]
manualMatchType: NotRequired[str]
matchType: NotRequired[str]
providerId: NotRequired[str]
providerName: NotRequired[str]
class PlaymatchRomMatch(TypedDict):
provider: PlaymatchProvider
provider_game_id: int
game_match_type: GameMatchType
class PlaymatchHandler:
"""
Handler for [Playmatch](https://github.com/RetroRealm/playmatch), a service for matching Roms by Hashes.
"""
def __init__(self):
self.base_url = "https://playmatch.retrorealm.dev/api"
async def lookup_rom(self, rom_file: RomFile) -> list[PlaymatchRomMatch]:
"""
Identify a ROM file using Playmatch API.
:param file_name: The name of the ROM file.
:param file_size: The size of the ROM file in bytes.
:param md5: The MD5 hash of the ROM file, if available.
:param sha1: The SHA1 hash of the ROM file, if available.
:return: The IGDB provider ID if a match is found, otherwise None.
:raises HTTPException: If the request fails or the service is unavailable.
"""
if not PLAYMATCH_API_ENABLED:
return []
url = f"{self.base_url}/identify/ids"
try:
response = await self._request(
url,
{
"fileName": rom_file.file_name,
"fileSize": rom_file.file_size_bytes,
"md5": rom_file.md5_hash,
"sha1": rom_file.sha1_hash,
},
)
except httpx.HTTPStatusError:
# We silently fail if the service is unavailable as this should not block the rest of RomM.
return []
game_match_type = response.get("gameMatchType", None)
if game_match_type == GameMatchType.NoMatch:
log.debug("No match found for the provided ROM file.")
return []
externalMetadata = response.get("externalMetadata", [])
if len(externalMetadata) == 0:
log.debug("No external metadata found for the matched ROM file.")
return []
rom_matches: list[PlaymatchRomMatch] = []
for metadata in externalMetadata:
provider_name = metadata.get("providerName", None)
provider_game_id = metadata.get("providerId", None)
if provider_name == PlaymatchProvider.IGDB and provider_game_id is not None:
log.debug("Found IGDB match with IGDB ID: %s", provider_game_id)
rom_matches.append(
PlaymatchRomMatch(
provider=PlaymatchProvider.IGDB,
provider_game_id=int(provider_game_id),
game_match_type=GameMatchType(game_match_type),
)
)
return rom_matches
async def _request(self, url: str, query: dict, timeout=60) -> dict:
"""
Sends a Request to Playmatch API.
:param url: The API endpoint URL.
:param query: A dictionary containing the query parameters.
:param timeout: The timeout for the request in seconds.
:return: A dictionary with the json result.
:raises HTTPException: If the request fails or the service is unavailable.
"""
httpx_client = ctx_httpx_client.get()
filtered_query = {
key: value
for key, value in query.items()
if value is not None and value != "" # drop None and ""
}
url_with_query = yarl.URL(url).update_query(**filtered_query)
log.debug(
"API request: URL=%s, Timeout=%s",
url_with_query,
timeout,
)
headers = {
"user-agent": "RomM/" + get_version() + " (https://github.com/rommapp/romm)"
}
try:
res = await httpx_client.get(
str(url_with_query), headers=headers, timeout=timeout
)
res.raise_for_status()
return res.json()
except httpx.HTTPStatusError as e:
log.warning("Connection error: can't connect to Playmatch", exc_info=True)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Can't connect to Playmatch, check your internet connection",
) from e

View File

@@ -16,8 +16,9 @@ from config import (
RETROACHIEVEMENTS_API_KEY,
)
from fastapi import HTTPException, status
from handler.filesystem import fs_resource_handler
from logger.logger import log
from models.platform import Platform
from models.rom import Rom
from utils.context import ctx_httpx_client
from .base_hander import MetadataHandler
@@ -81,14 +82,6 @@ class RAHandler(MetadataHandler):
self.ra_service = RetroAchievementsService()
self.HASHES_FILE_NAME = "ra_hashes.json"
def _get_rom_base_path(self, platform_id: int, rom_id: int) -> str:
return os.path.join(
"roms",
str(platform_id),
str(rom_id),
"retroachievements",
)
def _get_hashes_file_path(self, platform_id: int) -> str:
return os.path.join(
RESOURCES_BASE_PATH,
@@ -97,18 +90,6 @@ class RAHandler(MetadataHandler):
self.HASHES_FILE_NAME,
)
def _get_badges_path(self, platform_id: int, rom_id: int) -> str:
return os.path.join(self._get_rom_base_path(platform_id, rom_id), "badges")
def _create_resources_path(self, platform_id: int, rom_id: int) -> None:
os.makedirs(
os.path.join(
RESOURCES_BASE_PATH,
self._get_rom_base_path(platform_id, rom_id),
),
exist_ok=True,
)
def _exists_cache_file(self, platform_id: int) -> bool:
return os.path.exists(self._get_hashes_file_path(platform_id))
@@ -177,30 +158,25 @@ class RAHandler(MetadataHandler):
return res.json()
async def _search_rom(
self, platform: Platform, rom_id: int, hash: str
) -> RAGameListItem | None:
if not platform.ra_id:
async def _search_rom(self, rom: Rom, ra_hash: str) -> RAGameListItem | None:
if not rom.platform.ra_id:
return None
self._create_resources_path(platform.id, rom_id)
# Fetch all hashes for specific platform
roms: list[RAGameListItem]
if (
REFRESH_RETROACHIEVEMENTS_CACHE_DAYS
<= self._days_since_last_cache_file_update(platform.id)
or not self._exists_cache_file(platform.id)
<= self._days_since_last_cache_file_update(rom.platform.id)
or not self._exists_cache_file(rom.platform.id)
):
# Write the roms result to a JSON file if older than REFRESH_RETROACHIEVEMENTS_CACHE_DAYS days
roms = await self.ra_service.get_game_list(
system_id=platform.ra_id,
system_id=rom.platform.ra_id,
only_games_with_achievements=True,
include_hashes=True,
)
async with await open_file(
self._get_hashes_file_path(platform.id),
self._get_hashes_file_path(rom.platform.id),
"w",
encoding="utf-8",
) as json_file:
@@ -208,15 +184,15 @@ class RAHandler(MetadataHandler):
else:
# Read the roms result from the JSON file
async with await open_file(
self._get_hashes_file_path(platform.id),
self._get_hashes_file_path(rom.platform.id),
"r",
encoding="utf-8",
) as json_file:
roms = json.loads(await json_file.read())
for rom in roms:
if hash in rom.get("Hashes", ()):
return rom
for r in roms:
if ra_hash in r.get("Hashes", ()):
return r
return None
@@ -232,19 +208,21 @@ class RAHandler(MetadataHandler):
name=platform["name"],
)
async def get_rom(self, platform: Platform, rom_id: int, hash: str) -> RAGameRom:
if not platform.ra_id or not hash:
async def get_rom(self, rom: Rom, ra_hash: str) -> RAGameRom:
if not rom.platform.ra_id or not ra_hash:
return RAGameRom(ra_id=None)
rom = await self._search_rom(platform, rom_id, hash)
ra_game_list_item = await self._search_rom(rom, ra_hash)
if not rom:
if not ra_game_list_item:
return RAGameRom(ra_id=None)
try:
rom_details = await self.ra_service.get_game_extended_details(rom["ID"])
rom_details = await self.ra_service.get_game_extended_details(
ra_game_list_item["ID"]
)
return RAGameRom(
ra_id=rom["ID"],
ra_id=ra_game_list_item["ID"],
ra_metadata=RAMetadata(
achievements=[
RAGameRomAchievement(
@@ -258,9 +236,9 @@ class RAHandler(MetadataHandler):
),
badge_id=achievement.get("BadgeName", ""),
badge_url_lock=f"https://media.retroachievements.org/Badge/{achievement.get('BadgeName', '')}_lock.png",
badge_path_lock=f"{self._get_badges_path(platform.id, rom_id)}/{achievement.get('BadgeName', '')}_lock.png",
badge_path_lock=f"{fs_resource_handler.get_ra_badges_path(rom.platform.id, rom.id)}/{achievement.get('BadgeName', '')}",
badge_url=f"https://media.retroachievements.org/Badge/{achievement.get('BadgeName', '')}.png",
badge_path=f"{self._get_badges_path(platform.id, rom_id)}/{achievement.get('BadgeName', '')}.png",
badge_path=f"{fs_resource_handler.get_ra_badges_path(rom.platform.id, rom.id)}/{achievement.get('BadgeName', '')}.png",
display_order=achievement.get("DisplayOrder", None),
type=achievement.get("type", ""),
)

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,12 +9,16 @@ 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_pm_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.pm_handler import PlaymatchProvider
from handler.metadata.ra_handler import RAGameRom, RAGamesPlatform
from handler.metadata.ss_handler import SSPlatform, SSRom
from logger.formatter import BLUE, LIGHTYELLOW
@@ -39,22 +43,12 @@ class ScanType(Enum):
class MetadataSource:
IGDB = "igdb"
MOBY = "moby"
SS = "ss"
RA = "ra"
async def fetch_ra_info(
platform: Platform,
rom_id: int,
hash: str,
) -> RAGameRom:
return await meta_ra_handler.get_rom(
platform=platform,
rom_id=rom_id,
hash=hash,
)
IGDB = "igdb" # IGDB
MOBY = "moby" # MobyGames
SS = "ss" # Screenscraper
RA = "ra" # RetroAchivements
LB = "lb" # Launchbox
PM = "pm" # Playmatch
async def _get_main_platform_igdb_id(platform: Platform):
@@ -95,6 +89,8 @@ async def scan_platform(
MetadataSource.MOBY,
MetadataSource.SS,
MetadataSource.RA,
MetadataSource.LB,
MetadataSource.PM,
]
platform_attrs: dict[str, Any] = {}
@@ -143,16 +139,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 +166,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(
@@ -223,21 +230,16 @@ def scan_firmware(
async def scan_rom(
platform: Platform,
fs_rom: FSRom,
scan_type: ScanType,
rom: Rom | None = None,
metadata_sources: list[str] | None = None,
platform: Platform,
rom: Rom,
fs_rom: FSRom,
metadata_sources: list[str],
newly_added: bool,
) -> Rom:
if not metadata_sources:
metadata_sources = [
MetadataSource.IGDB,
MetadataSource.MOBY,
MetadataSource.SS,
MetadataSource.RA,
]
roms_path = fs_rom_handler.get_roms_fs_structure(platform.fs_slug)
log.error("No metadata sources provided")
raise ValueError("No metadata sources provided")
# Set default properties
rom_attrs = {
@@ -246,13 +248,17 @@ async def scan_rom(
"fs_name": fs_rom["fs_name"],
"platform_id": platform.id,
"name": fs_rom["fs_name"],
"crc_hash": fs_rom["crc_hash"],
"md5_hash": fs_rom["md5_hash"],
"sha1_hash": fs_rom["sha1_hash"],
"ra_hash": fs_rom["ra_hash"],
"url_cover": "",
"url_manual": "",
"url_screenshots": [],
}
# Update properties from existing rom if not a complete rescan
if rom and scan_type != ScanType.COMPLETE:
if not newly_added and scan_type != ScanType.COMPLETE:
rom_attrs.update(
{
"igdb_id": rom.igdb_id,
@@ -260,6 +266,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,
@@ -277,10 +284,11 @@ async def scan_rom(
# Update properties that don't require metadata
filesize = sum([file.file_size_bytes for file in fs_rom["files"]])
regs, rev, langs, other_tags = fs_rom_handler.parse_tags(rom_attrs["fs_name"])
roms_path = fs_rom_handler.get_roms_fs_structure(platform.fs_slug)
rom_attrs.update(
{
"fs_path": roms_path,
"fs_name": rom_attrs["fs_name"],
"fs_name_no_tags": fs_rom_handler.get_file_name_with_no_tags(
rom_attrs["fs_name"]
),
@@ -296,20 +304,12 @@ async def scan_rom(
}
)
# Set empty hashes when we plan to recalculate them
if not rom or scan_type == ScanType.COMPLETE or scan_type == ScanType.HASHES:
rom_attrs.update({"crc_hash": "", "md5_hash": "", "sha1_hash": ""})
# If no metadata scan is required
if scan_type == ScanType.HASHES:
return Rom(**rom_attrs)
async def fetch_igdb_rom():
async def fetch_igdb_rom() -> IGDBRom:
if (
MetadataSource.IGDB in metadata_sources
and platform.igdb_id
and (
not rom
newly_added
or scan_type == ScanType.COMPLETE
or (scan_type == ScanType.PARTIAL and not rom.igdb_id)
or (scan_type == ScanType.UNIDENTIFIED and not rom.igdb_id)
@@ -322,12 +322,12 @@ async def scan_rom(
return IGDBRom(igdb_id=None)
async def fetch_moby_rom():
async def fetch_moby_rom() -> MobyGamesRom:
if (
MetadataSource.MOBY in metadata_sources
and platform.moby_id
and (
not rom
newly_added
or scan_type == ScanType.COMPLETE
or (scan_type == ScanType.PARTIAL and not rom.moby_id)
or (scan_type == ScanType.UNIDENTIFIED and not rom.moby_id)
@@ -339,12 +339,12 @@ async def scan_rom(
return MobyGamesRom(moby_id=None)
async def fetch_ss_rom():
async def fetch_ss_rom() -> SSRom:
if (
MetadataSource.SS in metadata_sources
and platform.ss_id
and (
not rom
newly_added
or scan_type == ScanType.COMPLETE
or (scan_type == ScanType.PARTIAL and not rom.ss_id)
or (scan_type == ScanType.UNIDENTIFIED and not rom.ss_id)
@@ -356,28 +356,112 @@ async def scan_rom(
return SSRom(ss_id=None)
async def fetch_launchbox_rom(platform_slug: str) -> LaunchboxRom:
if MetadataSource.LB in metadata_sources and (
newly_added
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)
async def fetch_ra_rom() -> RAGameRom:
if (
MetadataSource.RA in metadata_sources
and platform.ra_id
and (
newly_added
or scan_type == ScanType.COMPLETE
or scan_type == ScanType.HASHES
or (scan_type == ScanType.PARTIAL and not rom.ra_id)
or (scan_type == ScanType.UNIDENTIFIED and not rom.ra_id)
)
):
return await meta_ra_handler.get_rom(rom=rom, ra_hash=rom_attrs["ra_hash"])
return RAGameRom(ra_id=None)
# Playmatch currectly only supports IGDB IDs
async def fetch_playmatch_rom() -> IGDBRom:
if (
MetadataSource.PM in metadata_sources
and MetadataSource.IGDB in metadata_sources
and platform.igdb_id
and (
newly_added
or scan_type == ScanType.COMPLETE
or (scan_type == ScanType.PARTIAL and not rom.igdb_id)
or (scan_type == ScanType.UNIDENTIFIED and not rom.igdb_id)
)
):
rom_file = fs_rom["files"][0]
pm_matches = await meta_pm_handler.lookup_rom(rom_file)
for pm_match in pm_matches:
if pm_match["provider"] != PlaymatchProvider.IGDB:
continue
pm_igdbid = pm_match.get("provider_game_id")
if pm_igdbid is None:
continue
# Log the successful identification
log.debug(
emoji.emojize(
f"{hl(rom_attrs['fs_name'])} identified by Playmatch as "
f"{hl(str(pm_igdbid), color=BLUE)} :alien_monster:"
),
extra=LOGGER_MODULE_NAME,
)
# Return the ROM data from IGDB
return await meta_igdb_handler.get_rom_by_id(pm_igdbid)
return IGDBRom(igdb_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,
ra_handler_rom,
launchbox_handler_rom,
playmatch_handler_rom,
) = await asyncio.gather(
fetch_igdb_rom(),
fetch_moby_rom(),
fetch_ss_rom(),
fetch_ra_rom(),
fetch_launchbox_rom(platform.slug),
fetch_playmatch_rom(),
)
if rom:
# Only update fields if match is found
if moby_handler_rom.get("moby_id"):
rom_attrs.update({**moby_handler_rom})
if ss_handler_rom.get("ss_id"):
rom_attrs.update({**ss_handler_rom})
if igdb_handler_rom.get("igdb_id"):
rom_attrs.update({**igdb_handler_rom})
else:
# Reversed to prioritize IGDB
rom_attrs.update({**moby_handler_rom, **ss_handler_rom, **igdb_handler_rom})
# Only update fields if match is found
if playmatch_handler_rom.get("igdb_id"):
rom_attrs.update({**playmatch_handler_rom})
if ra_handler_rom.get("ra_id"):
rom_attrs.update({**ra_handler_rom})
if moby_handler_rom.get("moby_id"):
rom_attrs.update({**moby_handler_rom})
if launchbox_handler_rom.get("launchbox_id"):
rom_attrs.update({**launchbox_handler_rom})
if ss_handler_rom.get("ss_id"):
rom_attrs.update({**ss_handler_rom})
if igdb_handler_rom.get("igdb_id"):
rom_attrs.update({**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 ra_handler_rom.get("ra_id")
and not launchbox_handler_rom.get("launchbox_id")
and not playmatch_handler_rom.get("igdb_id")
):
log.warning(
emoji.emojize(f"{hl(rom_attrs['fs_name'])} not identified :cross_mark:"),
@@ -391,7 +475,7 @@ async def scan_rom(
),
extra=LOGGER_MODULE_NAME,
)
if fs_rom.get("multi", False):
if rom.multi:
for file in fs_rom["files"]:
log.info(
f"\t · {hl(file.file_name, color=LIGHTYELLOW)}",

View File

@@ -1,5 +1,5 @@
import pytest
from handler.scan_handler import ScanType, scan_platform, scan_rom
from handler.scan_handler import MetadataSource, ScanType, scan_platform, scan_rom
from models.platform import Platform
from models.rom import Rom, RomFile
from utils.context import initialize_context
@@ -28,21 +28,38 @@ async def test_scan_platform():
@pytest.mark.vcr
async def test_scan_rom():
platform = Platform(fs_slug="n64", igdb_id=4)
rom = Rom(
fs_name="Paper Mario (USA).z64",
name="Paper Mario",
igdb_id=3340,
fs_size_bytes=1024,
tags=[],
multi=False,
)
async with initialize_context():
files = [
RomFile(
file_name="Paper Mario (USA).z64",
file_path="n64/Paper Mario (USA)",
file_size_bytes=1024,
last_modified=1620000000,
)
]
rom = await scan_rom(
platform,
{"fs_name": "Paper Mario (USA).z64", "multi": False, "files": files},
ScanType.QUICK,
platform=platform,
scan_type=ScanType.QUICK,
rom=rom,
fs_rom={
"fs_name": "Paper Mario (USA).z64",
"multi": False,
"files": [
RomFile(
file_name="Paper Mario (USA).z64",
file_path="n64/Paper Mario (USA)",
file_size_bytes=1024,
last_modified=1620000000,
)
],
"crc_hash": "",
"md5_hash": "",
"sha1_hash": "",
"ra_hash": "",
},
metadata_sources=[MetadataSource.IGDB],
newly_added=True,
)
assert type(rom) is Rom

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="")
@@ -244,7 +249,7 @@ class Rom(BaseModel):
@cached_property
def multi(self) -> bool:
# TODO: Improve multi game detection. This is a temporal fix to check if multi.
# TODO: Improve multi game detection as this is a very basic check
if len(self.files) > 1:
return True
if (
@@ -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

@@ -58,27 +58,24 @@ FROM backend-build AS backend-dev-build
RUN poetry install --no-ansi --no-cache --all-extras
FROM alpine:${ALPINE_VERSION} AS rahasher-build
# TODO: Upgrade Alpine to the same version as the other stages, when RAHasher is updated to workAdd commentMore actions
# with it (seems like Alpine 3.18's g++ v12 is the latest version that works with RAHasher,
# while g++ v13 fails to compile it).
FROM alpine:3.18 AS rahasher-build
RUN apk add --no-cache \
g++ \
git \
make
linux-headers \
make \
zlib-dev
# TODO: Move to a tagged release of `RALibretro`, once a version newer than 1.8.0 is released.
ARG RALIBRETRO_SHA=304ed205f11dd0bb22c01afe11d1ffabf176facc
# TODO: Remove `sed` command adding "ctime", when RAHasher can be compiled without it.
# TODO: Remove `sed` command adding "unistd.h", when RAHasher can be compiled without it.
# Related pull request: https://github.com/madler/zlib/pull/1022
RUN git clone --recursive https://github.com/RetroAchievements/RALibretro.git && \
ARG RALIBRETRO_VERSION=1.8.0
# TODO: Remove `sed` command when RAHasher can be compiled without it.
RUN git clone --recursive --branch "${RALIBRETRO_VERSION}" --depth 1 https://github.com/RetroAchievements/RALibretro.git && \
cd ./RALibretro && \
git checkout "${RALIBRETRO_SHA}" && \
git submodule update --init --recursive && \
sed -i '22a #include <ctime>' ./src/Util.h && \
sed -i '6a #include <unistd.h>' \
./src/libchdr/deps/zlib-1.3.1/gzlib.c \
./src/libchdr/deps/zlib-1.3.1/gzread.c \
./src/libchdr/deps/zlib-1.3.1/gzwrite.c && \
make HAVE_CHD=1 -f ./Makefile.RAHasher

View File

@@ -24,6 +24,12 @@ STEAMGRIDDB_API_KEY=
# RetroAchievements
RETROACHIEVEMENTS_API_KEY=
# Playmatch
PLAYMATCH_API_ENABLED=
# LaunchBox
LAUNCHBOX_API_ENABLED=
# Database config
DB_HOST=127.0.0.1
DB_PORT=3306
@@ -69,6 +75,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: 7.4 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 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,7 @@ export type MetadataSourcesDict = {
SS_API_ENABLED: boolean;
STEAMGRIDDB_API_ENABLED: boolean;
RA_API_ENABLED: boolean;
LAUNCHBOX_API_ENABLED: boolean;
PLAYMATCH_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,12 +90,12 @@ 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
>
<v-col cols="12">
<v-col>
<a
v-if="rom.igdb_id"
style="text-decoration: none; color: inherit"
@@ -160,6 +160,24 @@ const { allPlatforms } = storeToRefs(platformsStore);
<span>{{ rom.ra_id }}</span>
</v-chip>
</a>
<v-chip
v-if="rom.launchbox_id"
:class="{
'ml-1': rom.igdb_id || rom.ss_id || rom.moby_id || rom.ra_id,
}"
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>
</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

@@ -48,7 +48,7 @@ const computedAspectRatio = computed(() => {
return parseFloat(ratio.toString());
});
const missingCoverImage = computed(() =>
getMissingCoverImage(rom.value?.name || rom.value?.fs_name || ""),
getMissingCoverImage(rom.value?.name || rom.value?.fs_name || "")
);
// Functions
@@ -81,17 +81,13 @@ 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;
removeCover?: boolean;
unmatch?: boolean;
},
successMessage: string,
successMessage: string
) {
show.value = false;
emitter?.emit("showLoadingDialog", { loading: true, scrim: true });
@@ -133,7 +129,7 @@ async function uploadManuals() {
})
.then((responses: PromiseSettledResult<unknown>[]) => {
const successfulUploads = responses.filter(
(d) => d.status == "fulfilled",
(d) => d.status == "fulfilled"
);
const failedUploads = responses.filter((d) => d.status == "rejected");
@@ -174,7 +170,7 @@ async function unmatchRom() {
if (!rom.value) return;
await handleRomUpdate(
{ rom: rom.value, unmatch: true },
"Rom unmatched successfully",
"Rom unmatched successfully"
);
}
@@ -190,7 +186,7 @@ async function updateRom() {
await handleRomUpdate(
{ rom: rom.value, removeCover: removeCover.value },
"Rom updated successfully!",
"Rom updated successfully!"
);
}
@@ -346,9 +342,9 @@ function closeDialog() {
</div>
<v-row class="justify-space-between mt-4" no-gutters>
<v-btn
:disabled="noMetadataMatch"
:disabled="rom.is_unidentified"
:class="` ${
noMetadataMatch ? '' : 'bg-toplayer text-romm-red'
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

@@ -3,6 +3,7 @@
"api-key-missing": "Fehlender oder ungültiger API-Key",
"complete-rescan": "Vollständiger Scan",
"complete-rescan-desc": "Kompletter Neu-Scan aller Plattformen und Dateien (am langsamsten)",
"disabled-by-admin": "Vom Administrator deaktiviert",
"hashes": "Hashes neu berechnen",
"hashes-desc": "Berechne Hashes für alle Dateien neu",
"manage-library": "Bibliothek verwalten",

View File

@@ -3,6 +3,7 @@
"api-key-missing": "API key missing or invalid",
"complete-rescan": "Complete rescan",
"complete-rescan-desc": "Total rescan of all platforms and files (slowest)",
"disabled-by-admin": "Disabled by the administrator",
"hashes": "Recalculate hashes",
"hashes-desc": "Recalculates hashes for all files",
"manage-library": "Manage library",

View File

@@ -3,6 +3,7 @@
"api-key-missing": "API key missing or invalid",
"complete-rescan": "Complete rescan",
"complete-rescan-desc": "Total rescan of all platforms and files (slowest)",
"disabled-by-admin": "Disabled by the administrator",
"hashes": "Recalculate hashes",
"hashes-desc": "Recalculates hashes for all files",
"manage-library": "Manage library",

View File

@@ -3,6 +3,7 @@
"api-key-missing": "API key inválida o no configurada",
"complete-rescan": "Escaneo completo",
"complete-rescan-desc": "Escaneo completo de todos los ficheros y plataformas (más lento)",
"disabled-by-admin": "Deshabilitado por el administrador",
"hashes": "Recalcular hashes",
"hashes-desc": "Recalcula los hashes de todos los ficheros",
"manage-library": "Gestionar biblioteca",

View File

@@ -3,6 +3,7 @@
"api-key-missing": "Clé API invalide ou non configurée",
"complete-rescan": "Scan complet",
"complete-rescan-desc": "Scan complet de tous les fichiers et plateformes (plus lent)",
"disabled-by-admin": "Désactivé par l'administrateur",
"hashes": "Recalculer les hachages",
"hashes-desc": "Recalculer les hachages de tous les fichiers",
"manage-library": "Gérer la bibliothèque",

View File

@@ -3,6 +3,7 @@
"api-key-missing": "Chiave API mancante o non valida",
"complete-rescan": "Scansione completa",
"complete-rescan-desc": "Scansiona nuovamente tutte le piattaforme e i file (più lento)",
"disabled-by-admin": "Disabilitato dall'amministratore",
"hashes": "Ricalcola hash",
"hashes-desc": "Ricalcola gli hash per tutti i file",
"manage-library": "Gestisci libreria",

View File

@@ -3,6 +3,7 @@
"api-key-missing": "API keyが見つからないか誤っています",
"complete-rescan": "完全再スキャン",
"complete-rescan-desc": "全てのプラットフォームとファイルを再スキャン (最遅)",
"disabled-by-admin": "管理者によって無効化されています",
"hashes": "ハッシュ値の再計算",
"hashes-desc": "全ファイルのハッシュ値を再計算します",
"manage-library": "ライブラリを編集",

View File

@@ -3,6 +3,7 @@
"api-key-missing": "API 키가 없거나 올바르지 않습니다",
"complete-rescan": "모두 재스캔",
"complete-rescan-desc": "모든 플랫폼과 파일 재스캔 (가장 느림)",
"disabled-by-admin": "관리자에 의해 비활성화됨",
"hashes": "해시",
"hashes-desc": "해시로만 스캔",
"manage-library": "라이브러리 관리",

View File

@@ -3,6 +3,7 @@
"api-key-missing": "Chave API ausente ou inválida",
"complete-rescan": "Reescanear completamente",
"complete-rescan-desc": "Reescanear totalmente todas as plataformas e arquivos (mais lento)",
"disabled-by-admin": "Desativado pelo administrador",
"hashes": "Recalcular hashes",
"hashes-desc": "Recalcular hashes para todos os arquivos",
"manage-library": "Gerenciar biblioteca",

View File

@@ -3,6 +3,7 @@
"api-key-missing": "Cheie API invalidă sau neconfigurată",
"complete-rescan": "Scanare completă",
"complete-rescan-desc": "Scanare completă a tuturor fișierelor și platformelor (mai lent)",
"disabled-by-admin": "Dezactivat de administrator",
"hashes": "Recalculează hash-urile",
"hashes-desc": "Recalculează hash-urile tuturor fișierelor",
"manage-library": "Gestionează biblioteca",

View File

@@ -3,6 +3,7 @@
"api-key-missing": "API ключ отсутствует или недействителен",
"complete-rescan": "Полное пересканирование",
"complete-rescan-desc": "Полное пересканирование всех платформ и файлов (самое медленное)",
"disabled-by-admin": "Отключено администратором",
"hashes": "Пересчитать хеши",
"hashes-desc": "Пересчитать хеши для всех файлов",
"manage-library": "Управление библиотекой",

View File

@@ -3,6 +3,7 @@
"api-key-missing": "接口密钥丢失或无效",
"complete-rescan": "完成重新扫描",
"complete-rescan-desc": "重新扫描所有平台与文件(最慢)",
"disabled-by-admin": "已被管理员禁用",
"hashes": "哈希",
"hashes-desc": "仅扫描哈希匹配的游戏",
"manage-library": "管理游戏库",

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,8 @@ const defaultHeartbeat: Heartbeat = {
MOBY_API_ENABLED: false,
RA_API_ENABLED: false,
STEAMGRIDDB_API_ENABLED: false,
LAUNCHBOX_API_ENABLED: false,
PLAYMATCH_API_ENABLED: false,
},
FILESYSTEM: {
FS_PLATFORMS: [],

View File

@@ -361,6 +361,7 @@ const _EJS_CORES_MAP = {
"commmodore-128": ["vice_x128"],
colecovision: ["gearcoleco"],
doom: ["prboom"],
dos: ["dosbox_pure"],
jaguar: ["virtualjaguar"],
lynx: ["handy"],
"atari-lynx-mkii": ["handy"],

View File

@@ -27,34 +27,69 @@ const metadataOptions = computed(() => [
name: "IGDB",
value: "igdb",
logo_path: "/assets/scrappers/igdb.png",
disabled: !heartbeat.value.METADATA_SOURCES?.IGDB_API_ENABLED,
disabled: !heartbeat.value.METADATA_SOURCES?.IGDB_API_ENABLED
? t("scan.api-key-missing")
: "",
},
{
name: "Mobygames",
value: "moby",
logo_path: "/assets/scrappers/moby.png",
disabled: !heartbeat.value.METADATA_SOURCES?.MOBY_API_ENABLED,
disabled: !heartbeat.value.METADATA_SOURCES?.MOBY_API_ENABLED
? t("scan.api-key-missing")
: "",
},
{
name: "Screenscraper",
value: "ss",
logo_path: "/assets/scrappers/ss.png",
disabled: !heartbeat.value.METADATA_SOURCES?.SS_API_ENABLED,
disabled: !heartbeat.value.METADATA_SOURCES?.SS_API_ENABLED
? t("scan.api-key-missing")
: "",
},
{
name: "RetroAchievements",
value: "ra",
logo_path: "/assets/scrappers/ra.png",
disabled: !heartbeat.value.METADATA_SOURCES?.RA_API_ENABLED,
disabled: !heartbeat.value.METADATA_SOURCES?.RA_API_ENABLED
? t("scan.api-key-missing")
: "",
},
{
name: "Launchbox",
value: "lb",
logo_path: "/assets/scrappers/launchbox.png",
disabled: !heartbeat.value.METADATA_SOURCES?.LAUNCHBOX_API_ENABLED
? t("scan.disabled-by-admin")
: "",
},
{
name: "Playmatch",
value: "pm",
logo_path: "/assets/scrappers/playmatch.png",
disabled: !heartbeat.value.METADATA_SOURCES?.PLAYMATCH_API_ENABLED
? t("scan.disabled-by-admin")
: "",
},
]);
// Use the computed metadataOptions to filter out disabled sources
const metadataSources = ref(metadataOptions.value.filter((s) => !s.disabled));
// Since metadataOptions is now a computed property, it will automatically update.
// Therefore, we only need to watch metadataOptions for changes.
watch(metadataOptions, (newOptions) => {
metadataSources.value = newOptions.filter((option) => !option.disabled);
});
watch(metadataSources, (newSources) => {
const igdbEnabled = newSources.some((s) => s.value === "igdb");
if (igdbEnabled) return;
const playmatchEnabled = newSources.some((s) => s.value === "pm");
if (playmatchEnabled) {
// If IGDB is disabled, Playmatch should also be disabled
metadataSources.value = metadataSources.value.filter(
(s) => s.value !== "pm",
);
}
});
// Adding each new scanned platform to panelIndex to be open by default
watch(
@@ -211,8 +246,8 @@ async function stopScan() {
<v-list-item
v-bind="props"
:title="item.raw.name"
:subtitle="item.raw.disabled ? t('scan.api-key-missing') : ''"
:disabled="item.raw.disabled"
:subtitle="item.raw.disabled"
:disabled="Boolean(item.raw.disabled)"
>
<template #prepend>
<v-avatar size="25" rounded="1">
@@ -364,7 +399,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