romm icon indicating copy to clipboard operation
romm copied to clipboard

[Bug] Manually adding How Long to Beat id does not fetch metadata properly

Open J0R6IT0 opened this issue 10 months ago • 2 comments

RomM version 4.6.0-alpha.4

Describe the bug When manually adding a HLTB id for a game, metadata is never updated and the How Long to Beat tab is empty. All the other games matched during the scan process work properly.

To Reproduce Steps to reproduce the behavior:

  1. Find a game without a HLTB id associated.
  2. Manually add the id
  3. Apply changes, observe that metadata for HLTB is not fetched properly.

Expected behavior Just like IGDB or others, when manually adding an id, metadata should be fetched properly

Screenshots

Image

Server:

  • OS: Debian
  • Version: 12

Client:

  • Device: MacBook Pro M4
  • OS: macOS 26.2
  • Browser: Brave
  • Version 1.86

J0R6IT0 avatar Jan 20 '26 18:01 J0R6IT0

HLTB has no endpoint for fetching metadata by the ID, so this isn't possible at the moment.

gantoine avatar Jan 20 '26 20:01 gantoine

I made a Python script to test fetching HLTB data directly by ID, and it works fine on my machine:

import json
import requests
from bs4 import BeautifulSoup
from typing import Tuple, TypedDict
from typing_extensions import NotRequired


class GameHLTBData(TypedDict):
    main_story: NotRequired[int]
    main_story_count: NotRequired[int]
    main_plus_extra: NotRequired[int]
    main_plus_extra_count: NotRequired[int]
    completionist: NotRequired[int]
    completionist_count: NotRequired[int]
    all_styles: NotRequired[int]
    all_styles_count: NotRequired[int]
    release_year: NotRequired[int]
    review_score: NotRequired[int]
    review_count: NotRequired[int]
    popularity: NotRequired[int]
    completions: NotRequired[int]


def safe_int(value: any) -> int | None:
    if value is None or value == "":
        return None
    try:
        return int(value)
    except (ValueError, TypeError):
        return None


def fetch_raw_hltb_game(game_id: int | str) -> dict:
    """Extract the raw dictionary directly from __NEXT_DATA__ without transformations."""
    url = f"https://howlongtobeat.com/game?id={game_id}"
    headers = {
        "User-Agent": (
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/124.0.0.0 Safari/537.36"
        ),
        "Referer": "https://howlongtobeat.com/",
        "Accept-Language": "en-US,en;q=0.9",
    }

    response = requests.get(url, headers=headers)
    response.raise_for_status()

    soup = BeautifulSoup(response.text, "html.parser")
    script_tag = soup.find("script", id="__NEXT_DATA__")

    if not script_tag or not script_tag.string:
        raise ValueError(f"Could not find data for game ID {game_id}")

    data = json.loads(script_tag.string)
    games_list = (
        data.get("props", {})
        .get("pageProps", {})
        .get("game", {})
        .get("data", {})
        .get("game", [])
    )

    if not games_list:
        raise ValueError(f"No records found for game ID {game_id}")

    return games_list[0]


def fetch_hltb_game(game_id: int | str) -> Tuple[str, GameHLTBData]:
    """Map raw data to the final typed format."""
    raw = fetch_raw_hltb_game(game_id)

    # Get game name for verification
    game_name = raw.get("game_name", "Unknown")
    result: GameHLTBData = {}

    # Gameplay times (in seconds)
    if val := safe_int(raw.get("comp_main")):
        if val > 0:
            result["main_story"] = val
    if val := safe_int(raw.get("comp_main_count")):
        result["main_story_count"] = val

    if val := safe_int(raw.get("comp_plus")):
        if val > 0:
            result["main_plus_extra"] = val
    if val := safe_int(raw.get("comp_plus_count")):
        result["main_plus_extra_count"] = val

    if val := safe_int(raw.get("comp_100")):
        if val > 0:
            result["completionist"] = val
    if val := safe_int(raw.get("comp_100_count")):
        result["completionist_count"] = val

    if val := safe_int(raw.get("comp_all")):
        if val > 0:
            result["all_styles"] = val
    if val := safe_int(raw.get("comp_all_count")):
        result["all_styles_count"] = val

    # Release year
    if val := raw.get("release_world"):
        year_str = str(val).split("-")[0].strip()
        if year_str.isdigit():
            result["release_year"] = int(year_str)

    # Community metrics
    if val := safe_int(raw.get("review_score")):
        result["review_score"] = val
    if val := safe_int(raw.get("review_count")):
        result["review_count"] = val
    if val := safe_int(raw.get("profile_popular")):
        result["popularity"] = val

    # Total completions
    completions_val = raw.get("profile_completed") or raw.get("comp_count")
    if val := safe_int(completions_val):
        result["completions"] = val

    return game_name, result


if __name__ == "__main__":
    game_id_test = 7169

    # 1. Inspect raw data from HLTB
    print("=== RAW DATA FROM HLTB ===")
    raw_data = fetch_raw_hltb_game(game_id_test)
    print(json.dumps(raw_data, indent=2))

    print("\n" + "=" * 50 + "\n")

    # 2. Inspect final mapped JSON
    print("=== FINAL MAPPED JSON ===")
    name, game_json = fetch_hltb_game(game_id_test)
    print(f"Game: {name}")
    print(json.dumps(game_json, indent=2))

nevespt avatar Aug 16 '26 12:08 nevespt