49std::string HLTBService::httpPost(
const std::string& url,
const std::string& body,
50 const std::string& contentType)
54 std::string command =
"curl -s -X POST";
56 command +=
" -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36'";
57 command +=
" -H 'Origin: https://howlongtobeat.com'";
58 command +=
" -H 'Referer: https://howlongtobeat.com'";
59 command +=
" --connect-timeout 10 --max-time 30 --max-redirs 10 --proto =https";
63 std::array<char, 8192> buffer;
66 std::unique_ptr<FILE, int (*)(FILE*)> pipe(popen(command.c_str(),
"r"), pclose);
73 constexpr size_t kMaxResponse = 16u * 1024 * 1024;
74 while (fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe.get()) !=
nullptr)
76 result += buffer.data();
77 if (result.size() > kMaxResponse)
79 Logger::warn(
"[HLTB] HTTP response too large, truncating");
87std::string HLTBService::urlEncode(
const std::string& str)
89 std::ostringstream encoded;
95 if (std::isalnum(
static_cast<unsigned char>(c)) || c ==
'-' || c ==
'_' || c ==
'.' ||
102 encoded << std::uppercase;
103 encoded << '%' << std::setw(2) << static_cast<int>(
static_cast<unsigned char>(c));
104 encoded << std::nouppercase;
108 return encoded.str();
115std::string HLTBService::normalizeTitle(
const std::string& title)
117 std::string normalized;
118 normalized.reserve(title.size());
123 char lower =
static_cast<char>(std::tolower(
static_cast<unsigned char>(c)));
126 if (std::isalnum(
static_cast<unsigned char>(lower)))
135double HLTBService::calculateSimilarity(
const std::string& a,
const std::string& b)
137 std::string normA = normalizeTitle(a);
138 std::string normB = normalizeTitle(b);
140 if (normA.empty() || normB.empty())
148 if (normA.find(normB) != std::string::npos || normB.find(normA) != std::string::npos)
151 double lenRatio =
static_cast<double>(std::min(normA.size(), normB.size())) /
152 static_cast<double>(std::max(normA.size(), normB.size()));
153 return 0.8 + (0.2 * lenRatio);
157 size_t len1 = normA.size();
158 size_t len2 = normB.size();
161 if (std::max(len1, len2) > 2 * std::min(len1, len2))
165 std::vector<std::vector<size_t>> dp(len1 + 1, std::vector<size_t>(len2 + 1));
167 for (
size_t i = 0; i <= len1; i++)
169 for (
size_t j = 0; j <= len2; j++)
172 for (
size_t i = 1; i <= len1; i++)
174 for (
size_t j = 1; j <= len2; j++)
176 size_t cost = (normA[i - 1] == normB[j - 1]) ? 0 : 1;
177 dp[i][j] = std::min({dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost});
181 size_t distance = dp[len1][len2];
182 size_t maxLen = std::max(len1, len2);
184 return 1.0 - (
static_cast<double>(distance) /
static_cast<double>(maxLen));
197 std::string searchKey =
"\"" + key +
"\"";
198 size_t pos =
json.find(searchKey);
199 if (pos == std::string::npos)
202 pos =
json.find(
':', pos);
203 if (pos == std::string::npos)
207 while (pos <
json.size() && std::isspace(
static_cast<unsigned char>(
json[pos])))
210 if (pos >=
json.size() ||
json[pos] !=
'"')
215 while (end <
json.size() &&
json[end] !=
'"')
217 if (
json[end] ==
'\\' && end + 1 <
json.size())
222 return json.substr(pos, end - pos);
227 std::string searchKey =
"\"" + key +
"\"";
228 size_t pos =
json.find(searchKey);
229 if (pos == std::string::npos)
232 pos =
json.find(
':', pos);
233 if (pos == std::string::npos)
237 while (pos <
json.size() && std::isspace(
static_cast<unsigned char>(
json[pos])))
242 return std::stod(
json.substr(pos));
258 std::vector<std::string> elements;
260 std::string searchKey =
"\"" + arrayKey +
"\"";
261 size_t pos =
json.find(searchKey);
262 if (pos == std::string::npos)
265 pos =
json.find(
'[', pos);
266 if (pos == std::string::npos)
271 bool inString =
false;
272 bool escaped =
false;
273 size_t elementStart = pos;
275 for (
size_t i = pos; i <
json.size(); i++)
301 else if ((c ==
',' || c ==
']') && braceCount == 0)
303 std::string element =
json.substr(elementStart, i - elementStart);
304 size_t first = element.find_first_not_of(
" \t\n\r");
305 size_t last = element.find_last_not_of(
" \t\n\r");
306 if (first != std::string::npos && last != std::string::npos)
308 element = element.substr(first, last - first + 1);
309 if (!element.empty() && element[0] ==
'{')
311 elements.push_back(element);
314 elementStart = i + 1;
317 if (c ==
']' && braceCount == 0)
330std::vector<HLTBSearchResult> HLTBService::parseSearchResponse(
const std::string&
json)
332 std::vector<HLTBSearchResult> results;
337 for (
const auto& gameJson : games)
339 HLTBSearchResult result;
358 if (result.
gameId > 0 && !result.
name.empty())
360 results.push_back(result);
369 HowLongToBeatInfo info;
396 std::string url =
"https://howlongtobeat.com/api/search";
399 std::ostringstream payload;
401 payload <<
"\"searchType\":\"games\",";
403 payload <<
"\"searchPage\":1,";
404 payload <<
"\"size\":" << std::max(1, std::min(50, maxResults)) <<
",";
405 payload <<
"\"searchOptions\":{";
406 payload <<
"\"games\":{";
407 payload <<
"\"userId\":0,";
408 payload <<
"\"platform\":\"\",";
409 payload <<
"\"sortCategory\":\"popular\",";
410 payload <<
"\"rangeCategory\":\"main\",";
411 payload <<
"\"rangeTime\":{\"min\":null,\"max\":null},";
412 payload <<
"\"gameplay\":{\"perspective\":\"\",\"flow\":\"\",\"genre\":\"\"},";
413 payload <<
"\"rangeYear\":{\"min\":\"\",\"max\":\"\"},";
414 payload <<
"\"modifier\":\"\"";
416 payload <<
"\"users\":{\"sortCategory\":\"postcount\"},";
417 payload <<
"\"filter\":\"\",";
418 payload <<
"\"sort\":0,";
419 payload <<
"\"randomizer\":0";
423 std::string response = httpPost(url, payload.str(),
"application/json");
425 if (response.empty())
427 Logger::warn(
"HLTB: Empty response for search '{}'", query);
431 auto results = parseSearchResponse(response);
432 Logger::debug(
"HLTB: Found {} results for '{}'", results.size(), query);
439 if (gameName.empty())
447 std::string cacheKey = normalizeTitle(gameName);
456 auto results =
search(gameName, 5);
460 Logger::warn(
"HLTB: No results found for '{}'", gameName);
467 double bestScore = 0.0;
468 size_t bestMatchIndex = results.size();
470 for (
size_t i = 0; i < results.size(); ++i)
472 results[i].similarity = calculateSimilarity(gameName, results[i].name);
473 if (results[i].similarity > bestScore)
475 bestScore = results[i].similarity;
481 if (bestMatchIndex >= results.size() || bestScore < 0.5)
483 Logger::warn(
"HLTB: No good match found for '{}' (best score: {:.2f})", gameName,
490 Logger::info(
"HLTB: Best match for '{}' is '{}' (score: {:.2f})", gameName,
491 results[bestMatchIndex].name, bestScore);
493 auto info = parseGameDetails(results[bestMatchIndex]);
512 Logger::warn(
"HLTB: Direct ID lookup not implemented for ID {}", hltbId);
525 auto future = std::make_shared<std::future<void>>(std::async(std::launch::async,
526 [gameName, callback]()
537 static std::mutex futuresMutex;
538 static std::vector<std::shared_ptr<std::future<void>>> activeFutures;
541 std::lock_guard<std::mutex> lock(futuresMutex);
544 activeFutures.erase(std::remove_if(activeFutures.begin(), activeFutures.end(),
545 [](
const std::shared_ptr<std::future<void>>& f)
547 return f->wait_for(std::chrono::milliseconds(0)) ==
548 std::future_status::ready;
550 activeFutures.end());
552 activeFutures.push_back(future);
559 auto future = std::make_shared<std::future<void>>(std::async(std::launch::async,
560 [query, callback, maxResults]()
563 search(query, maxResults);
570 static std::mutex futuresMutex;
571 static std::vector<std::shared_ptr<std::future<void>>> activeFutures;
574 std::lock_guard<std::mutex> lock(futuresMutex);
575 activeFutures.erase(std::remove_if(activeFutures.begin(), activeFutures.end(),
576 [](
const std::shared_ptr<std::future<void>>& f)
578 return f->wait_for(std::chrono::milliseconds(0)) ==
579 std::future_status::ready;
581 activeFutures.end());
582 activeFutures.push_back(future);
591 const std::function<
void(
int completed,
int total)>& progressCallback)
593 int total =
static_cast<int>(games.size());
596 for (
Game* game : games)
602 if (game->hltbInfo.found && !game->hltbInfo.isStale())
605 if (progressCallback)
606 progressCallback(completed, total);
614 game->hltbInfo = info;
618 if (progressCallback)
619 progressCallback(completed, total);
622 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Complete representation of a game in the library.
static void getGameInfoAsync(const std::string &gameName, const InfoCallback &callback)
Get game info asynchronously.
std::function< void(const HowLongToBeatInfo &)> InfoCallback
static HowLongToBeatInfo getGameInfoById(int hltbId)
Get time estimates by HLTB game ID.
static std::vector< HLTBSearchResult > search(const std::string &query, int maxResults=10)
Search for games on HLTB.
static void clearCache()
Clear the HLTB cache.
static void batchFetch(std::vector< Game * > &games, const std::function< void(int completed, int total)> &progressCallback=nullptr)
Fetch HLTB info for multiple games.
static HowLongToBeatInfo getGameInfo(const std::string &gameName)
Get time estimates for a game by name.
std::function< void(const std::vector< HLTBSearchResult > &)> SearchCallback
static LRUCache< std::string, HowLongToBeatInfo >::Stats getCacheStats()
Get cache statistics.
static void searchAsync(const std::string &query, const SearchCallback &callback, int maxResults=10)
Search asynchronously.
Thread-safe LRU cache with optional TTL support.
static void info(const std::string &message, Args &&... args)
Log info message (general information).
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
static std::string escapeJson(const std::string &str)
Escape a string for JSON.
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
static LRUCache< std::string, HowLongToBeatInfo > & hltbCache()
static constexpr int HLTB_CACHE_TTL_SECONDS
static constexpr size_t HLTB_CACHE_MAX_SIZE
std::string jsonGetString(const std::string &json, const std::string &key)
std::vector< std::string > jsonSplitArray(const std::string &json, const std::string &arrayKey)
int jsonGetInt(const std::string &json, const std::string &key)
double jsonGetNumber(const std::string &json, const std::string &key)
A single search result from HowLongToBeat.
std::string imageUrl
Cover image URL.
double completionist
100% completion time
std::string name
Game name on HLTB.
int releaseYear
Release year.
double allStyles
Average across all styles.
double mainStory
Main story time.
double mainExtras
Main + extras time.
Time-to-beat estimates from HowLongToBeat.com.
time_t lastUpdated
When this data was fetched.
double allStylesHours
Average across all playstyles.
double completionistHours
100% completion
int hltbId
HowLongToBeat game ID.
bool found
Whether a match was found.
std::string matchedName
Name matched on HLTB.
double mainPlusExtrasHours
Main + side content.
double mainStoryHours
Main story/campaign only.