Implement file tag matching for HLTB

This commit is contained in:
Georges-Antoine Assi
2025-09-17 11:07:08 -04:00
parent bdd80a8527
commit afc92e73ee

View File

@@ -1,4 +1,5 @@
import json
import re
from typing import Final, NotRequired, TypedDict
import httpx
@@ -12,6 +13,9 @@ from utils.context import ctx_httpx_client
from .base_handler import BaseRom, MetadataHandler
# Regex to detect HLTB ID tags in filenames like (hltb-12345)
HLTB_TAG_REGEX = re.compile(r"\(hltb-(\d+)\)", re.IGNORECASE)
class HLTBPlatform(TypedDict):
slug: str
@@ -174,6 +178,14 @@ class HowLongToBeatHandler(MetadataHandler):
def is_enabled(cls) -> bool:
return HLTB_API_ENABLED
@staticmethod
def extract_hltb_id_from_filename(fs_name: str) -> int | None:
"""Extract HLTB ID from filename tag like (hltb-12345)."""
match = HLTB_TAG_REGEX.search(fs_name)
if match:
return int(match.group(1))
return None
async def _request(self, url: str, payload: dict) -> dict:
"""
Sends a POST request to HowLongToBeat API.
@@ -340,8 +352,25 @@ class HowLongToBeatHandler(MetadataHandler):
if not HLTB_API_ENABLED:
return HLTBRom(hltb_id=None)
# Normalize the search term
search_term = fs_rom_handler.get_file_name_with_no_tags(fs_name)
# Check for HLTB ID tag in filename first
hltb_id_from_tag = self.extract_hltb_id_from_filename(fs_name)
if hltb_id_from_tag:
log.debug(f"Found HLTB ID tag in filename: {hltb_id_from_tag}")
rom_by_id = await self.get_rom_by_id(hltb_id_from_tag)
if rom_by_id["hltb_id"]:
log.debug(
f"Successfully matched ROM by HLTB ID tag: {fs_name} -> {hltb_id_from_tag}"
)
return rom_by_id
else:
log.warning(
f"HLTB ID tag found but no match: {fs_name} -> {hltb_id_from_tag}"
)
# We replace " - " with ": " to match HowLongToBeat's naming convention
search_term = fs_rom_handler.get_file_name_with_no_tags(fs_name).replace(
" - ", ": "
)
search_term = self.normalize_search_term(search_term, remove_punctuation=False)
# Search for games