Files
Matt Kaatman d8d9fa7884 fix(igdb): let region_mode decide the localized title (#5785)
* fix(igdb): let region_mode decide the localized title

get_igdb_preferred_locale ignored scan.priority.region_mode, so a rom
tagged (Japan) always got IGDB's ja-JP localized title, even with
prefer_config and us first in scan.priority.region. Under prefer_config
the configured regions now come first and the rom's own tags are the
fallback, matching the ScreenScraper handler since #4413. The default
prefer_rom_tags ordering is unchanged.

Fixes #5784

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(igdb): fold the region_mode note into one docstring sentence

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: code-review

Log a missing IGDB locale at debug: under prefer_config every ROM asks
for the first config locale, so a missing one is routine, not a warning.
Pin SCAN_REGION_MODE in the multi-region locale test instead of relying
on MagicMock's auto attribute.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: simplify

Drop the IGDB-locale filter on the ROM's region codes; the final
lookup loop already skips codes IGDB has no locale for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: prose

Spell out the USA region in the prefer_config test docstring so it
does not read as the pronoun, untangle the fallback test docstring, and
finish the clipped Returns line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(metadata): share one region order across IGDB, ScreenScraper and LaunchBox

IGDB now tries every preferred locale in order, up to the first region
that uses the default title, instead of only the first. Under
prefer_config with [eu, jp], a (Japan) ROM whose game has no EU
localization gets the Japanese title again rather than the default.

preferred_region_codes in the filesystem base handler builds the region
order once. ScreenScraper, IGDB and LaunchBox all read it, so LaunchBox
artwork follows region_mode too, and uppercase config codes match the
ROM's tags for every provider.

European country codes map to IGDB's EU locale and ScreenScraper's ss
to the default title, so a (France) ROM no longer falls through to the
next configured region.

An unquoted no (Norway, Norwegian) in scan.priority.region or
scan.priority.language loads as false from YAML and crashed every IGDB
match. The config loader now turns it back into "no" and drops other
non-string entries with a warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(igdb): drop _string_codes and spell out the EU region codes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-11-26 20:11:48 -05:00

790 lines
24 KiB
Python

from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
from config.config_manager import MetadataMediaType
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 (
preferred_region_codes,
region_name_to_provider_shortcode,
)
from handler.metadata.ss_handler import get_preferred_media_types
from utils.database import safe_str_to_bool
from utils.html_text import html_to_text
from utils.urls import youtube_id_from_url
if TYPE_CHECKING:
from models.rom import Rom
from .types import (
LAUNCHBOX_IMAGES_DIR,
LAUNCHBOX_MANUALS_DIR,
LAUNCHBOX_VIDEOS_DIR,
LaunchboxImage,
LaunchboxMetadata,
LaunchboxRom,
LocalMediaContext,
MediaRequest,
)
from .utils import (
coalesce,
dedupe_words,
file_uri_for_local_path,
launchbox_region_to_shortcode,
parse_list,
parse_playmode,
parse_release_date,
sanitize_filename,
)
LAUNCHBOX_IMAGES_URL: str = "https://images.launchbox-app.com"
# 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",
)
@dataclass(frozen=True, slots=True)
class BoxArt:
media_type: MetadataMediaType
url_key: Literal["box2d_url", "box2d_back_url", "box2d_side_url", "box3d_url"]
path_key: Literal["box2d_path", "box2d_back_path", "box2d_side_path", "box3d_path"]
# LaunchBox image types in descending preference
image_types: tuple[str, ...]
# Stored under the same paths ScreenScraper uses, so a box face one provider
# lacks is filled by the other.
BOX_ART: tuple[BoxArt, ...] = (
BoxArt(
MetadataMediaType.BOX2D,
"box2d_url",
"box2d_path",
("Box - Front", "Box - Front - Reconstructed"),
),
BoxArt(
MetadataMediaType.BOX2D_BACK,
"box2d_back_url",
"box2d_back_path",
("Box - Back", "Box - Back - Reconstructed"),
),
BoxArt(
MetadataMediaType.BOX2D_SIDE,
"box2d_side_url",
"box2d_side_path",
("Box - Spine",),
),
BoxArt(MetadataMediaType.BOX3D, "box3d_url", "box3d_path", ("Box - 3D",)),
)
def rom_region_shortcodes(fs_name: str) -> tuple[str, ...]:
"""Provider region shortcodes to prefer for a ROM, most-preferred first.
Under "prefer_rom_tags" a ROM with no known region tag gets none, so the
listing order picks its artwork.
"""
region_names = fs_rom_handler.parse_tags(fs_name).regions if fs_name else []
if cm.get_config().SCAN_REGION_MODE != "prefer_config" and not any(
region_name_to_provider_shortcode(name) for name in region_names
):
return ()
return tuple(preferred_region_codes(region_names))
# 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.
RECOGNIZED_VIDEO_EXTENSIONS: tuple[str, ...] = (
".mp4",
".webm",
".avi",
".mkv",
".mov",
".wmv",
)
def local_media_req(
*,
platform_name: str | None,
fs_name: str,
local: dict[str, str] | None,
remote: dict[str, Any] | None,
remote_images: list[dict[str, Any]] | None,
remote_enabled: bool,
) -> MediaRequest:
title = ((local or {}).get("Title") or "").strip()
region_hint = ((local or {}).get("Region") or "").strip() or None
return MediaRequest(
platform_name,
fs_name,
title,
region_hint,
remote_images,
remote_enabled,
rom_region_shortcodes(fs_name),
)
def remote_media_req(
*,
remote: dict[str, Any] | None,
remote_images: list[dict[str, Any]] | None,
remote_enabled: bool,
platform_name: str | None = None,
fs_name: str = "",
) -> MediaRequest:
title = ((remote or {}).get("Name") or "").strip()
# Without a platform_name, _build_local_media_context bails and local
# Images/Manuals/Videos never get searched. Fall back to the platform
# recorded on the remote entry so remote-matched ROMs can still surface
# on-disk media.
if not platform_name and remote:
platform_name = (remote.get("Platform") or "").strip() or None
return MediaRequest(
platform_name,
fs_name,
title,
None,
remote_images,
remote_enabled,
rom_region_shortcodes(fs_name),
)
def _build_local_media_context(
req: MediaRequest,
base_dir: Path,
*,
include_region_hints: bool = True,
) -> LocalMediaContext | None:
if not req.platform_name:
return None
if not base_dir.exists():
return None
base = (base_dir / req.platform_name).resolve()
if not base.is_dir():
return None
stems: list[str] = []
if req.fs_name:
stems.append(Path(req.fs_name).stem)
if req.title:
stems.append(req.title)
out: list[str] = []
for s in stems:
clean = sanitize_filename(s)
if clean and clean not in out:
out.append(clean)
stems = out
if not stems:
return None
preferred_regions: list[str] = []
if include_region_hints and req.region_hint:
region_hint = req.region_hint.strip()
if region_hint:
preferred_regions.append(region_hint)
if "," in region_hint:
preferred_regions.extend(
[r.strip() for r in region_hint.split(",") if r.strip()]
)
return {
"base": base,
"stems": stems,
"preferred_regions": preferred_regions,
"region_shortcodes": req.region_shortcodes if include_region_hints else (),
}
def _find_local_media_candidates(
ctx: LocalMediaContext,
category_name: str,
*,
exts: tuple[str, ...] = (".png", ".jpg", ".jpeg", ".webp"),
indexed_preference: tuple[int, ...] | None = None,
indexed_only_preferred: bool = False,
) -> tuple[list[Path], str]:
category_dir = ctx["base"] / category_name
if not category_dir.is_dir():
return [], ""
search_dirs: list[Path] = []
for region in ctx["preferred_regions"]:
p = category_dir / region
if p.exists() and p.is_dir() and p not in search_dirs:
search_dirs.append(p)
region_dirs = sorted(
[p for p in category_dir.iterdir() if p.is_dir()],
key=lambda p: p.name.lower(),
)
# The ROM's own regions come next, e.g. "North America" for a "(USA)" ROM.
for code in ctx["region_shortcodes"]:
for p in region_dirs:
if p not in search_dirs and launchbox_region_to_shortcode(p.name) == code:
search_dirs.append(p)
for p in region_dirs:
if p not in search_dirs:
search_dirs.append(p)
if category_dir not in search_dirs:
search_dirs.append(category_dir)
if not search_dirs:
return [], ""
allowed_exts = {e.lower() for e in exts}
def _candidates(d: Path, stem: str) -> list[Path]:
if not stem:
return []
plain: Path | None = None
indexed: list[tuple[int, Path]] = []
prefix = f"{stem}-"
try:
for p in d.iterdir():
if not (p.is_file() and p.suffix.lower() in allowed_exts):
continue
stem_name = p.stem
if stem_name == stem:
plain = p
continue
if stem_name.startswith(prefix):
suffix = stem_name[len(prefix) :]
if suffix.isdigit():
indexed.append((int(suffix), p))
except OSError, PermissionError:
return []
if indexed:
indexed.sort(key=lambda t: (t[0], t[1].name.lower()))
if indexed_preference:
indexed_by_num: dict[int, Path] = {n: p for n, p in indexed}
preferred_hits = [
indexed_by_num[n] for n in indexed_preference if n in indexed_by_num
]
if preferred_hits:
return preferred_hits
if indexed_only_preferred:
return [plain] if plain else []
return [p for _, p in indexed]
return [plain] if plain else []
for d in search_dirs:
region = "" if d == category_dir else d.name
for stem in ctx["stems"]:
candidate_files = _candidates(d, stem)
if candidate_files:
return candidate_files, region
return [], ""
def _find_local_image(
ctx: LocalMediaContext, image_types: tuple[str, ...]
) -> tuple[str, str] | None:
"""URL and region folder of the first local image of the highest-priority type."""
for category in image_types:
candidate_files, region = _find_local_media_candidates(
ctx,
category,
indexed_preference=(1,),
indexed_only_preferred=True,
)
url = file_uri_for_local_path(candidate_files[0]) if candidate_files else None
if url:
return url, region
return None
def _select_remote_image(
remote_images: list[dict[str, Any]],
image_types: tuple[str, ...],
region_shortcodes: tuple[str, ...],
) -> dict[str, Any] | None:
"""Pick the best remote image: 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 image_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 _select_remote_cover(
remote_images: list[dict[str, Any]], region_shortcodes: tuple[str, ...]
) -> dict[str, Any] | None:
return _select_remote_image(remote_images, COVER_PRIORITY_TYPES, region_shortcodes)
def _get_box_art(req: MediaRequest) -> dict[BoxArt, str]:
"""Resolve the URL of each box face, a local image overriding the remote one.
The faces after the front prefer the front's region, so the box matches.
"""
urls: dict[BoxArt, str] = {}
ctx = _build_local_media_context(
req, LAUNCHBOX_IMAGES_DIR, include_region_hints=True
)
remote_images = req.remote_images if req.remote_enabled else None
region_shortcodes = req.region_shortcodes
for art in BOX_ART:
url: str | None = None
region: str | None = None
local = _find_local_image(ctx, art.image_types) if ctx is not None else None
if local:
url, region = local
elif remote_images:
image = _select_remote_image(
remote_images, art.image_types, region_shortcodes
)
if image:
url = f"{LAUNCHBOX_IMAGES_URL}/{image['FileName']}"
region = image.get("Region")
if not url:
continue
urls[art] = url
if art.media_type != MetadataMediaType.BOX2D or not region:
continue
code = launchbox_region_to_shortcode(region)
if code:
region_shortcodes = (code, *(c for c in region_shortcodes if c != code))
if ctx is not None:
ctx = LocalMediaContext(
base=ctx["base"],
stems=ctx["stems"],
preferred_regions=[
region,
*(r for r in ctx["preferred_regions"] if r != region),
],
region_shortcodes=region_shortcodes,
)
return urls
def _get_cover(req: MediaRequest) -> str | None:
cover: str | None = None
# Remote media (overridden by local if available)
if req.remote_enabled and req.remote_images:
best_cover = _select_remote_cover(req.remote_images, req.region_shortcodes)
if best_cover and best_cover.get("FileName"):
cover = f"{LAUNCHBOX_IMAGES_URL}/{best_cover.get('FileName')}"
ctx = _build_local_media_context(
req, LAUNCHBOX_IMAGES_DIR, include_region_hints=True
)
if ctx is not None:
local_cover = _find_local_image(ctx, COVER_PRIORITY_TYPES)
if local_cover:
cover = local_cover[0]
return cover
def _get_screenshots(req: MediaRequest) -> list[str]:
screenshots: list[str] = []
# Remote media (overridden by local if available)
if req.remote_enabled and req.remote_images:
screenshots = [
f"{LAUNCHBOX_IMAGES_URL}/{image.get('FileName')}"
for image in req.remote_images
if image.get("FileName") and "Screenshot" in image.get("Type", "")
]
ctx = _build_local_media_context(
req, LAUNCHBOX_IMAGES_DIR, include_region_hints=True
)
if ctx is not None:
local_screens: list[str] = []
seen: set[str] = set()
for dir_name in (
"Amazon Screenshot",
"Epic Games Screenshot",
"GOG Screenshot",
"Origin Screenshot",
"Screenshot - Game Title",
"Screenshot - Game Select",
"Screenshot - Gameplay",
"Screenshot - High Scores",
"Screenshot - Game Over",
"Steam Screenshot",
):
candidate_files, _region = _find_local_media_candidates(ctx, dir_name)
for p in candidate_files:
url = file_uri_for_local_path(p)
if url and url not in seen:
seen.add(url)
local_screens.append(url)
if local_screens:
screenshots = local_screens
return screenshots
def _get_manuals(req: MediaRequest) -> str | None:
manual: str | None = None
ctx = _build_local_media_context(
req, LAUNCHBOX_MANUALS_DIR, include_region_hints=False
)
if ctx is None:
return manual
pdfs: list[Path] = [
p for p in ctx["base"].iterdir() if p.is_file() and p.suffix.lower() == ".pdf"
]
if not pdfs:
return manual
def _key(p: Path) -> str:
return sanitize_filename(p.stem).lower()
pdfs_sorted = sorted(pdfs, key=lambda p: (len(p.name), p.name.lower()))
stems_lower = [s.lower() for s in ctx["stems"]]
for stem in stems_lower:
for p in pdfs_sorted:
if _key(p) == stem:
url = file_uri_for_local_path(p)
if url:
return url
for stem in stems_lower:
for p in pdfs_sorted:
if _key(p).startswith(stem):
url = file_uri_for_local_path(p)
if url:
return url
return manual
def _get_video(req: MediaRequest) -> str | None:
"""Resolve a local LaunchBox video for the given ROM.
LaunchBox stores videos flat under `Videos/<Platform>/<GameStem>.<ext>`
(no region or category subdirectories). Return a `launchbox-file://` URL
to the first match, or None.
"""
ctx = _build_local_media_context(
req, LAUNCHBOX_VIDEOS_DIR, include_region_hints=False
)
if ctx is None:
return None
for stem in ctx["stems"]:
for ext in RECOGNIZED_VIDEO_EXTENSIONS:
candidate = ctx["base"] / f"{stem}{ext}"
if candidate.is_file():
return file_uri_for_local_path(candidate)
return None
def _get_images(req: MediaRequest) -> list[LaunchboxImage]:
images: list[LaunchboxImage] = []
# Remote media (overridden by local if available)
if req.remote_enabled and req.remote_images:
images = [
LaunchboxImage(
{
"url": f"{LAUNCHBOX_IMAGES_URL}/{image['FileName']}",
"type": image.get("Type", ""),
"region": image.get("Region", ""),
}
)
for image in req.remote_images
if image.get("FileName")
]
ctx = _build_local_media_context(
req, LAUNCHBOX_IMAGES_DIR, include_region_hints=True
)
if ctx is not None:
local_images: list[LaunchboxImage] = []
for dir_name in (
"Advertisement Flyer - Back",
"Advertisement Flyer - Front",
"Box - Back",
"Box - Back - Reconstructed",
"Box - Full",
"Box - Spine",
"Cart - Front",
"Cart - 3D",
"Clear Logo",
"Fanart - Box - Back",
"Fanart - Background", # Later separate in new category for rom header
"Amazon Background", # Later separate in new category for rom header
"Epic Games Background", # Later separate in new category for rom header
"Origin Background", # Later separate in new category for rom header
"Uplay Background", # Later separate in new category for rom header
):
candidate_files, region = _find_local_media_candidates(ctx, dir_name)
for p in candidate_files:
url = file_uri_for_local_path(p)
if not url:
continue
local_images.append(
LaunchboxImage(
{
"url": url,
"type": dir_name,
"region": region,
}
)
)
if local_images:
images = local_images
seen_images: dict[str, LaunchboxImage] = {}
for img in images:
if img["url"] not in seen_images:
seen_images[img["url"]] = img
return list(seen_images.values())
def build_launchbox_metadata(
*,
local: dict[str, str] | None = None,
remote: dict[str, Any] | None = None,
images: list[LaunchboxImage],
) -> LaunchboxMetadata:
local_release_date = local.get("ReleaseDate") if local else None
remote_release_date = remote.get("ReleaseDate") if remote else None
release_date_raw = coalesce(local_release_date, remote_release_date)
first_release_date = parse_release_date(release_date_raw)
max_players_raw = coalesce(
local.get("MaxPlayers") if local else None,
remote.get("MaxPlayers") if remote else None,
)
try:
max_players = int(max_players_raw or 0)
except TypeError, ValueError:
max_players = 0
release_type = (
coalesce(
local.get("ReleaseType") if local else None,
remote.get("ReleaseType") if remote else None,
)
or ""
)
if local and coalesce(local.get("PlayMode")):
cooperative = parse_playmode(local.get("PlayMode"))
else:
cooperative = safe_str_to_bool(
(remote.get("Cooperative") if remote else None) or "false"
)
video_url = coalesce(
(local.get("VideoUrl") if local else None),
(remote.get("VideoURL") if remote else None),
)
community_rating_raw = coalesce(
local.get("CommunityStarRating") if local else None,
remote.get("CommunityRating") if remote else None,
)
try:
community_rating = float(community_rating_raw or 0.0)
except TypeError, ValueError:
community_rating = 0.0
community_rating_count_raw = coalesce(
local.get("CommunityStarRatingTotalVotes") if local else None,
remote.get("CommunityRatingCount") if remote else None,
)
try:
community_rating_count = int(community_rating_count_raw or 0)
except TypeError, ValueError:
community_rating_count = 0
wikipedia_url = (
coalesce(
local.get("WikipediaURL") if local else None,
remote.get("WikipediaURL") if remote else None,
)
or ""
)
esrb_raw = coalesce(
(local.get("Rating") if local else None),
(remote.get("ESRB") if remote else None),
)
esrb = (esrb_raw or "").split(" - ")[0].strip()
genres_raw = coalesce(
local.get("Genre") if local else None,
remote.get("Genres") if remote else None,
)
genres = parse_list(genres_raw)
publisher = coalesce(
local.get("Publisher") if local else None,
remote.get("Publisher") if remote else None,
)
developer = coalesce(
local.get("Developer") if local else None,
remote.get("Developer") if remote else None,
)
companies = dedupe_words([publisher, developer])
return LaunchboxMetadata(
{
"first_release_date": first_release_date,
"max_players": max_players,
"release_type": release_type,
"cooperative": cooperative,
"youtube_video_id": youtube_id_from_url(video_url) or "",
"community_rating": community_rating,
"community_rating_count": community_rating_count,
"wikipedia_url": wikipedia_url,
"esrb": esrb,
"genres": genres,
"companies": companies,
"publishers": dedupe_words([publisher]),
"developers": dedupe_words([developer]),
"images": images,
}
)
def populate_rom_specific_paths(
metadata: LaunchboxMetadata, rom: "Rom"
) -> LaunchboxMetadata:
"""Populate rom-specific media paths on a LaunchBox metadata dict.
Called after the Rom is known (in the scan pipeline) to compute the
destination path for the media the handler surfaced a URL for.
"""
preferred_media_types = get_preferred_media_types()
for art in BOX_ART:
if art.media_type in preferred_media_types and metadata.get(art.url_key):
base = fs_resource_handler.get_media_resources_path(
rom.platform_id, rom.id, art.media_type
)
metadata[art.path_key] = f"{base}/{art.media_type.value}.png"
if (
MetadataMediaType.VIDEO in preferred_media_types
and "video_url" in metadata
and metadata.get("video_url")
):
base = fs_resource_handler.get_media_resources_path(
rom.platform_id, rom.id, MetadataMediaType.VIDEO
)
ext = Path(metadata["video_url"]).suffix.lower()
if ext not in RECOGNIZED_VIDEO_EXTENSIONS:
ext = ".mp4"
metadata["video_path"] = f"{base}/video{ext}"
return metadata
def build_rom(
*,
local: dict[str, str] | None,
remote: dict[str, Any] | None,
launchbox_id: int | None,
media_req: MediaRequest | None = None,
) -> LaunchboxRom:
images: list[LaunchboxImage] = (
_get_images(media_req) if media_req is not None else []
)
url_cover: str | None = None
url_screenshots: list[str] = []
url_manual: str | None = None
video_url: str | None = None
box_art: dict[BoxArt, str] = {}
if media_req is not None:
box_art = _get_box_art(media_req)
url_cover = _get_cover(media_req)
url_screenshots = _get_screenshots(media_req)
url_manual = _get_manuals(media_req)
video_url = _get_video(media_req)
url_screenshots = url_screenshots or []
name = (
coalesce(
(local.get("Title") if local else None),
(remote.get("Name") if remote else None),
)
or ""
).strip()
summary = html_to_text(
coalesce(
(local.get("Notes") if local else None),
(remote.get("Overview") if remote else None),
)
)
launchbox_id = int(launchbox_id) if launchbox_id is not None else None
metadata = build_launchbox_metadata(
local=local,
remote=remote,
images=images,
)
for art, url in box_art.items():
metadata[art.url_key] = url
if video_url:
metadata["video_url"] = video_url
return LaunchboxRom(
launchbox_id=launchbox_id,
name=name,
summary=summary,
url_cover=url_cover or "",
url_screenshots=url_screenshots,
url_manual=url_manual or "",
launchbox_metadata=metadata,
)