Files
romm/backend/handler/metadata/upc_handler.py
Georges-Antoine Assi 08901ca3a9 cleanup: reuse, simplify and trim the physical-games feature
Backend:

- Drop the post-scan re-assert of is_physical/upc/fs_path in
  create_physical_rom; scan_rom already forwards them in rom_attrs. The test
  fake was written to drop those fields to exercise the dead path, so it now
  matches the real scan_rom contract.
- Extract build_hashless_fs_rom() and use it from both the physical endpoint
  and the scan socket, which built the same FSRom literal by hand.
- Return added_rom instead of re-fetching it; add_rom is already decorated
  with @with_details, so get_rom repeated the whole eager-load fan-out.
- Pair invalidate_filter_values_cache() with refresh_affected_smart_collections(),
  as every other rom-mutating endpoint does.
- Reword the 409 detail: build_physical_fs_name uniquifies the name, so an
  IntegrityError can only mean a concurrent add.
- upc_handler: inline the single-use base_url and hoist the minimum title
  length to a module constant.

Frontend:

- Load BarcodeScannerDialog lazily. GlobalDialogs is mounted on every page, so
  the static import chain put ZXing (~438 KB) in the eager layout chunk. The
  scanner's watcher now runs immediate/post so it still starts when mounted
  behind a v-if.
- Guard the scanner against a teardown that races the decodeFromConstraints
  await; closing during the permission prompt left the camera on and the
  decode loop running.
- Render the UPC scan trigger through RTextField's append-inner adornment
  instead of a hand-built flex row.
- Type the createPhysicalRom payload with the generated PhysicalRomCreateForm
  and drop the metadataSources argument, which had no caller.
- Declare @zxing/library directly; it was imported but resolved transitively.
- Drop two write-only refs, scope the reader local to startCamera, and trim
  comments that restate the code.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 20:47:56 -04:00

77 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import re
from typing import Final
from config import UPC_LOOKUP_API_KEY, UPC_LOOKUP_BASE_URL, UPC_LOOKUP_ENABLED
from logger.logger import log
from utils import get_version
from utils.context import ctx_httpx_client
from .base_handler import MetadataHandler
# Retail suffixes/noise commonly present in UPC-database product titles that hurt
# name matching against game-metadata providers (e.g. "Sonic - Nintendo Switch").
_TITLE_NOISE_RE = re.compile(
r"\s*[-–(]?\s*(video ?game|nintendo switch|playstation \d?|"
r"xbox(?: one| series [sx])?|pc|ntsc|pal|region free|brand new|sealed)\b.*$",
re.IGNORECASE,
)
# Shorter than this and the "title" is a stray code, not a name worth matching.
_MIN_TITLE_LENGTH: Final = 2
class UPCHandler(MetadataHandler):
"""Resolve a UPC/EAN/barcode to a product title via an external lookup service.
This does not attach provider IDs; the resolved title is fed into the normal
name-based scan so the existing providers do the actual game matching.
"""
def __init__(self) -> None:
self.lookup_url = f"{UPC_LOOKUP_BASE_URL.rstrip('/')}/lookup"
@classmethod
def is_enabled(cls) -> bool:
return UPC_LOOKUP_ENABLED
def _clean_title(self, title: str) -> str:
cleaned = _TITLE_NOISE_RE.sub("", title).strip(" -–:")
return cleaned or title.strip()
async def resolve_upc_to_title(self, upc: str) -> str | None:
"""Return the best product title for a UPC, or None if unresolved."""
if not self.is_enabled():
log.warning("UPC lookup is disabled; cannot resolve barcode %s", upc)
return None
upc = upc.strip()
if not upc:
return None
headers = {"User-Agent": f"RomM/{get_version()}"}
if UPC_LOOKUP_API_KEY:
headers["user_key"] = UPC_LOOKUP_API_KEY
httpx_client = ctx_httpx_client.get()
try:
response = await httpx_client.get(
self.lookup_url,
params={"upc": upc},
headers=headers,
timeout=10,
)
response.raise_for_status()
data = response.json()
except Exception as e:
log.warning("Failed to resolve UPC %s: %s", upc, e)
return None
items = data.get("items") or []
for item in items:
title = (item.get("title") or "").strip()
if len(title) >= _MIN_TITLE_LENGTH:
return self._clean_title(title)
return None