Merge pull request #3709 from rommapp/posthog-code/fix-launchbox-cover-region

fix(launchbox): match remote cover art region to ROM region
This commit is contained in:
Georges-Antoine Assi
2026-07-09 13:42:32 -04:00
committed by GitHub
4 changed files with 177 additions and 22 deletions

View File

@@ -2,7 +2,9 @@ from pathlib import Path
from typing import TYPE_CHECKING
from config.config_manager import MetadataMediaType
from handler.filesystem import fs_resource_handler
from config.config_manager import config_manager as cm
from handler.filesystem import fs_resource_handler, fs_rom_handler
from handler.filesystem.base_handler import region_name_to_provider_shortcode
from handler.metadata.ss_handler import get_preferred_media_types
from utils.database import safe_str_to_bool
@@ -23,6 +25,7 @@ from .utils import (
coalesce,
dedupe_words,
file_uri_for_local_path,
launchbox_region_to_shortcode,
parse_list,
parse_playmode,
parse_release_date,
@@ -30,6 +33,47 @@ from .utils import (
sanitize_filename,
)
# Cover image types in descending preference. Region acts as a tiebreaker
# within a single type (see `_select_remote_cover`).
COVER_PRIORITY_TYPES: tuple[str, ...] = (
"Box - Front",
"Box - Front - Reconstructed",
"Fanart - Box - Front",
"Box - 3D",
"Amazon Poster",
"Epic Games Poster",
"GOG Poster",
"Steam Poster",
)
def rom_region_shortcodes(fs_name: str) -> tuple[str, ...]:
"""Provider region shortcodes to prefer for a ROM, most-preferred first.
Combines the regions tagged in the filename (reordered by the user's
SCAN_REGION_PRIORITY) with the configured priority list, so a ROM tagged
"(USA)" prefers its US cover even when another region sorts first.
"""
if not fs_name:
return ()
priority = cm.get_config().SCAN_REGION_PRIORITY
rom_codes: list[str] = []
for region_name in fs_rom_handler.parse_tags(fs_name).regions:
code = region_name_to_provider_shortcode(region_name)
if code and code not in rom_codes:
rom_codes.append(code)
rom_codes.sort(
key=lambda code: priority.index(code) if code in priority else len(priority)
)
if not rom_codes:
return ()
return tuple(dict.fromkeys(rom_codes + priority))
# Video container extensions recognized when probing for local LaunchBox media
# and when validating a metadata video URL's suffix. A tuple because the probe
# order is a preference order.
@@ -61,6 +105,7 @@ def local_media_req(
region_hint,
remote_images,
remote_enabled,
rom_region_shortcodes(fs_name),
)
@@ -86,6 +131,7 @@ def remote_media_req(
None,
remote_images,
remote_enabled,
rom_region_shortcodes(fs_name),
)
@@ -220,31 +266,39 @@ def _find_local_media_candidates(
return [], ""
def _select_remote_cover(
remote_images: list[dict], region_shortcodes: tuple[str, ...]
) -> dict | None:
"""Pick the best remote cover: highest-priority type, region as tiebreaker.
Within the best available image type, prefer the image whose region matches
the ROM (e.g. a "(USA)" ROM gets the North America box, not a random one).
"""
for image_type in COVER_PRIORITY_TYPES:
typed = [
image
for image in remote_images
if image.get("Type") == image_type and image.get("FileName")
]
if not typed:
continue
for code in region_shortcodes:
for image in typed:
if launchbox_region_to_shortcode(image.get("Region")) == code:
return image
return typed[0]
return None
def _get_cover(req: MediaRequest) -> str | None:
cover: str | None = None
cover_priority_types = (
"Box - Front",
"Box - Front - Reconstructed",
"Fanart - Box - Front",
"Box - 3D",
"Amazon Poster",
"Epic Games Poster",
"GOG Poster",
"Steam Poster",
)
# Remote media (overridden by local if available)
if req.remote_enabled and req.remote_images:
best_cover: dict | None = None
for image_type in cover_priority_types:
for image in req.remote_images:
if image.get("Type") == image_type and image.get("FileName"):
best_cover = image
break
if best_cover is not None:
break
best_cover = _select_remote_cover(req.remote_images, req.region_shortcodes)
if best_cover and best_cover.get("FileName"):
cover = f"https://images.launchbox-app.com/{best_cover.get('FileName')}"
@@ -252,7 +306,7 @@ def _get_cover(req: MediaRequest) -> str | None:
req, LAUNCHBOX_IMAGES_DIR, include_region_hints=True
)
if ctx is not None:
for category in cover_priority_types:
for category in COVER_PRIORITY_TYPES:
candidate_files, _region = _find_local_media_candidates(
ctx,
category,

View File

@@ -77,3 +77,6 @@ class MediaRequest:
region_hint: str | None
remote_images: list[dict] | None
remote_enabled: bool
# Provider region shortcodes (e.g. "us", "eu") ordered by preference, used
# to pick a region-matched remote cover. Derived from the ROM filename.
region_shortcodes: tuple[str, ...] = ()

View File

@@ -2,8 +2,34 @@ import re
from datetime import datetime
from pathlib import Path
from handler.filesystem.base_handler import region_name_to_provider_shortcode
from .types import LAUNCHBOX_LOCAL_DIR
# LaunchBox region names that don't map cleanly onto the shared REGIONS table
# (which ROM filename tags use). Keyed lowercase for case-insensitive lookup.
_LAUNCHBOX_REGION_OVERRIDES: dict[str, str] = {
"north america": "us",
"united states": "us",
"united kingdom": "uk",
"the netherlands": "nl",
}
def launchbox_region_to_shortcode(region_name: str | None) -> str | None:
"""Map a LaunchBox image Region name to a provider shortcode (e.g. "us").
LaunchBox labels the US region as "North America", so its names can't be
compared directly against ROM filename regions; normalize both sides to a
shortcode before matching.
"""
if not region_name:
return None
key = region_name.strip().lower()
if key in _LAUNCHBOX_REGION_OVERRIDES:
return _LAUNCHBOX_REGION_OVERRIDES[key]
return region_name_to_provider_shortcode(region_name.strip())
def sanitize_filename(stem: str) -> str:
s = (stem or "").strip()

View File

@@ -20,11 +20,14 @@ from defusedxml import ElementTree as ET
from handler.metadata.launchbox_handler.handler import LaunchboxHandler
from handler.metadata.launchbox_handler.local_source import LocalSource
from handler.metadata.launchbox_handler.media import (
_get_cover,
_get_video,
_select_remote_cover,
build_launchbox_metadata,
build_rom,
populate_rom_specific_paths,
remote_media_req,
rom_region_shortcodes,
)
from handler.metadata.launchbox_handler.platforms import get_platform
from handler.metadata.launchbox_handler.remote_source import RemoteSource
@@ -40,6 +43,7 @@ from handler.metadata.launchbox_handler.types import (
)
from handler.metadata.launchbox_handler.utils import (
coalesce,
launchbox_region_to_shortcode,
parse_playmode,
parse_release_date,
parse_videourl,
@@ -884,6 +888,74 @@ class TestRemoteMediaReq:
assert req.platform_name is None
class TestRegionAwareCover:
"""Regression tests for #3706: remote cover art should match the ROM region."""
def _image(self, file_name: str, region: str, type_: str = "Box - Front") -> dict:
return {"FileName": file_name, "Type": type_, "Region": region}
def _req(self, images: list[dict], shortcodes: tuple[str, ...]) -> MediaRequest:
return MediaRequest(
platform_name=None,
fs_name="",
title="",
region_hint=None,
remote_images=images,
remote_enabled=True,
region_shortcodes=shortcodes,
)
def test_launchbox_region_to_shortcode(self):
assert launchbox_region_to_shortcode("North America") == "us"
assert launchbox_region_to_shortcode("Europe") == "eu"
assert launchbox_region_to_shortcode("Japan") == "jp"
assert launchbox_region_to_shortcode("World") == "wor"
assert launchbox_region_to_shortcode("United Kingdom") == "uk"
assert launchbox_region_to_shortcode("") is None
assert launchbox_region_to_shortcode(None) is None
def test_select_prefers_region_match_within_type(self):
images = [
self._image("eu.png", "Europe"),
self._image("us.png", "North America"),
]
# USA rom must pick the North America box, not the first (EU) one.
best = _select_remote_cover(images, ("us", "eu"))
assert best is not None and best["FileName"] == "us.png"
def test_select_falls_back_to_first_without_region_info(self):
images = [
self._image("first.png", ""),
self._image("second.png", ""),
]
# With preferred regions present but no usable Region data on images,
# selection should fall back to the first image (preserves prior behavior).
best = _select_remote_cover(images, ("us",))
assert best is not None and best["FileName"] == "first.png"
def test_select_type_priority_beats_region(self):
images = [
self._image("us-3d.png", "North America", type_="Box - 3D"),
self._image("eu-front.png", "Europe", type_="Box - Front"),
]
# A same-region "Box - 3D" must not win over a higher-priority "Box - Front".
best = _select_remote_cover(images, ("us", "eu"))
assert best is not None and best["FileName"] == "eu-front.png"
def test_get_cover_uses_region_shortcodes(self):
# The 007: Nightfire (USA) scenario: two Box - Front covers, EU listed first.
images = [
self._image("nightfire-eu.png", "Europe"),
self._image("nightfire-us.png", "North America"),
]
cover = _get_cover(self._req(images, ("us", "wor", "eu")))
assert cover == "https://images.launchbox-app.com/nightfire-us.png"
def test_rom_region_shortcodes_from_filename(self):
codes = rom_region_shortcodes("007 - Nightfire (USA).chd")
assert codes[0] == "us"
class TestRemoteMatchLocalImages:
"""Regression test for bug where remote-matched roms skipped local image lookup.