game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
hltb_service.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// hltb_service.cpp
4// ==============================================================================
5// HowLongToBeat.com integration implementation
6// ==============================================================================
7
8#include "hltb_service.h"
9#include "logger.h"
10#include "shell_utils.h"
11
12#include <algorithm>
13#include <array>
14#include <cctype>
15#include <chrono>
16#include <cstdio>
17#include <cstring>
18#include <ctime>
19#include <future>
20#include <iomanip>
21#include <memory>
22#include <regex>
23#include <sstream>
24#include <thread>
25
26// ==============================================================================
27// Cache Configuration
28// ==============================================================================
29
30static constexpr size_t HLTB_CACHE_MAX_SIZE = 500;
31static constexpr int HLTB_CACHE_TTL_SECONDS = 2592000; // 30 days
32
33// Global cache (game name -> info). Wrapped in a Meyer's-singleton
34// accessor because LRUCache's allocating ctor isn't noexcept;
35// file-scope static would be bugprone-throwing-static-initialization /
36// CERT ERR58-CPP. Function-local static initializes on first call,
37// thread-safe per [stmt.dcl]/4.
44
45// ==============================================================================
46// HTTP Helpers
47// ==============================================================================
48
49std::string HLTBService::httpPost(const std::string& url, const std::string& body,
50 const std::string& contentType)
51{
52 // Build curl command with POST data
53 // HLTB requires specific headers to work
54 std::string command = "curl -s -X POST";
55 command += " -H " + ShellUtils::escapeArg("Content-Type: " + contentType);
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";
60 command += " -d " + ShellUtils::escapeArg(body);
61 command += " " + ShellUtils::escapeArg(url) + " 2>/dev/null";
62
63 std::array<char, 8192> buffer;
64 std::string result;
65
66 std::unique_ptr<FILE, int (*)(FILE*)> pipe(popen(command.c_str(), "r"), pclose);
67 if (!pipe)
68 {
69 Logger::error("HLTB: Failed to execute curl command");
70 return "";
71 }
72
73 constexpr size_t kMaxResponse = 16u * 1024 * 1024; // 16 MB
74 while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe.get()) != nullptr)
75 {
76 result += buffer.data();
77 if (result.size() > kMaxResponse)
78 {
79 Logger::warn("[HLTB] HTTP response too large, truncating");
80 break;
81 }
82 }
83
84 return result;
85}
86
87std::string HLTBService::urlEncode(const std::string& str)
88{
89 std::ostringstream encoded;
90 encoded.fill('0');
91 encoded << std::hex;
92
93 for (char c : str)
94 {
95 if (std::isalnum(static_cast<unsigned char>(c)) || c == '-' || c == '_' || c == '.' ||
96 c == '~')
97 {
98 encoded << c;
99 }
100 else
101 {
102 encoded << std::uppercase;
103 encoded << '%' << std::setw(2) << static_cast<int>(static_cast<unsigned char>(c));
104 encoded << std::nouppercase;
105 }
106 }
107
108 return encoded.str();
109}
110
111// ==============================================================================
112// Title Normalization & Fuzzy Matching
113// ==============================================================================
114
115std::string HLTBService::normalizeTitle(const std::string& title)
116{
117 std::string normalized;
118 normalized.reserve(title.size());
119
120 for (char c : title)
121 {
122 // Convert to lowercase
123 char lower = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
124
125 // Keep only alphanumeric characters
126 if (std::isalnum(static_cast<unsigned char>(lower)))
127 {
128 normalized += lower;
129 }
130 }
131
132 return normalized;
133}
134
135double HLTBService::calculateSimilarity(const std::string& a, const std::string& b)
136{
137 std::string normA = normalizeTitle(a);
138 std::string normB = normalizeTitle(b);
139
140 if (normA.empty() || normB.empty())
141 return 0.0;
142
143 // Exact match
144 if (normA == normB)
145 return 1.0;
146
147 // One contains the other
148 if (normA.find(normB) != std::string::npos || normB.find(normA) != std::string::npos)
149 {
150 // Score based on length ratio
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);
154 }
155
156 // Levenshtein distance-based similarity
157 size_t len1 = normA.size();
158 size_t len2 = normB.size();
159
160 // Quick rejection for very different lengths
161 if (std::max(len1, len2) > 2 * std::min(len1, len2))
162 return 0.0;
163
164 // Simple Levenshtein distance
165 std::vector<std::vector<size_t>> dp(len1 + 1, std::vector<size_t>(len2 + 1));
166
167 for (size_t i = 0; i <= len1; i++)
168 dp[i][0] = i;
169 for (size_t j = 0; j <= len2; j++)
170 dp[0][j] = j;
171
172 for (size_t i = 1; i <= len1; i++)
173 {
174 for (size_t j = 1; j <= len2; j++)
175 {
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});
178 }
179 }
180
181 size_t distance = dp[len1][len2];
182 size_t maxLen = std::max(len1, len2);
183
184 return 1.0 - (static_cast<double>(distance) / static_cast<double>(maxLen));
185}
186
187// ==============================================================================
188// JSON Parsing Helpers
189// ==============================================================================
190
191namespace
192{
193
194// Simple JSON value extraction
195std::string jsonGetString(const std::string& json, const std::string& key)
196{
197 std::string searchKey = "\"" + key + "\"";
198 size_t pos = json.find(searchKey);
199 if (pos == std::string::npos)
200 return "";
201
202 pos = json.find(':', pos);
203 if (pos == std::string::npos)
204 return "";
205
206 pos++;
207 while (pos < json.size() && std::isspace(static_cast<unsigned char>(json[pos])))
208 pos++;
209
210 if (pos >= json.size() || json[pos] != '"')
211 return "";
212
213 pos++;
214 size_t end = pos;
215 while (end < json.size() && json[end] != '"')
216 {
217 if (json[end] == '\\' && end + 1 < json.size())
218 end++;
219 end++;
220 }
221
222 return json.substr(pos, end - pos);
223}
224
225double jsonGetNumber(const std::string& json, const std::string& key)
226{
227 std::string searchKey = "\"" + key + "\"";
228 size_t pos = json.find(searchKey);
229 if (pos == std::string::npos)
230 return 0.0;
231
232 pos = json.find(':', pos);
233 if (pos == std::string::npos)
234 return 0.0;
235
236 pos++;
237 while (pos < json.size() && std::isspace(static_cast<unsigned char>(json[pos])))
238 pos++;
239
240 try
241 {
242 return std::stod(json.substr(pos));
243 }
244 catch (...)
245 {
246 return 0.0;
247 }
248}
249
250int jsonGetInt(const std::string& json, const std::string& key)
251{
252 return static_cast<int>(jsonGetNumber(json, key));
253}
254
255// Split JSON array into elements
256std::vector<std::string> jsonSplitArray(const std::string& json, const std::string& arrayKey)
257{
258 std::vector<std::string> elements;
259
260 std::string searchKey = "\"" + arrayKey + "\"";
261 size_t pos = json.find(searchKey);
262 if (pos == std::string::npos)
263 return elements;
264
265 pos = json.find('[', pos);
266 if (pos == std::string::npos)
267 return elements;
268
269 pos++;
270 int braceCount = 0;
271 bool inString = false;
272 bool escaped = false;
273 size_t elementStart = pos;
274
275 for (size_t i = pos; i < json.size(); i++)
276 {
277 char c = json[i];
278
279 // Track JSON string state so structural characters inside a quoted
280 // value (e.g. a note containing '}') are not miscounted (M4).
281 if (inString)
282 {
283 if (escaped)
284 escaped = false;
285 else if (c == '\\')
286 escaped = true;
287 else if (c == '"')
288 inString = false;
289 continue;
290 }
291 if (c == '"')
292 {
293 inString = true;
294 continue;
295 }
296
297 if (c == '{')
298 braceCount++;
299 else if (c == '}')
300 braceCount--;
301 else if ((c == ',' || c == ']') && braceCount == 0)
302 {
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)
307 {
308 element = element.substr(first, last - first + 1);
309 if (!element.empty() && element[0] == '{')
310 {
311 elements.push_back(element);
312 }
313 }
314 elementStart = i + 1;
315 }
316
317 if (c == ']' && braceCount == 0)
318 break;
319 }
320
321 return elements;
322}
323
324} // anonymous namespace
325
326// ==============================================================================
327// Search Response Parsing
328// ==============================================================================
329
330std::vector<HLTBSearchResult> HLTBService::parseSearchResponse(const std::string& json)
331{
332 std::vector<HLTBSearchResult> results;
333
334 // HLTB API returns: {"data": [...]}
335 auto games = jsonSplitArray(json, "data");
336
337 for (const auto& gameJson : games)
338 {
339 HLTBSearchResult result;
340
341 result.gameId = jsonGetInt(gameJson, "game_id");
342 result.name = jsonGetString(gameJson, "game_name");
343 result.imageUrl = jsonGetString(gameJson, "game_image");
344 result.releaseYear = jsonGetInt(gameJson, "release_world");
345
346 // Times are in seconds, convert to hours
347 double mainSec = jsonGetNumber(gameJson, "comp_main");
348 double extrasSec = jsonGetNumber(gameJson, "comp_plus");
349 double compSec = jsonGetNumber(gameJson, "comp_100");
350 double allSec = jsonGetNumber(gameJson, "comp_all");
351
352 // Convert seconds to hours (HLTB stores as seconds)
353 result.mainStory = mainSec / 3600.0;
354 result.mainExtras = extrasSec / 3600.0;
355 result.completionist = compSec / 3600.0;
356 result.allStyles = allSec / 3600.0;
357
358 if (result.gameId > 0 && !result.name.empty())
359 {
360 results.push_back(result);
361 }
362 }
363
364 return results;
365}
366
367HowLongToBeatInfo HLTBService::parseGameDetails(const HLTBSearchResult& result)
368{
369 HowLongToBeatInfo info;
370
371 info.hltbId = result.gameId;
372 info.matchedName = result.name;
373 info.mainStoryHours = result.mainStory;
374 info.mainPlusExtrasHours = result.mainExtras;
375 info.completionistHours = result.completionist;
376 info.allStylesHours = result.allStyles;
377 info.lastUpdated = std::time(nullptr);
378 info.found = true;
379
380 return info;
381}
382
383// ==============================================================================
384// Public API Implementation
385// ==============================================================================
386
387std::vector<HLTBSearchResult> HLTBService::search(const std::string& query, int maxResults)
388{
389 if (query.empty())
390 return {};
391
392 Logger::info("HLTB: Searching for '{}'", query);
393
394 // HLTB API endpoint and payload
395 // The API uses a specific JSON format for search
396 std::string url = "https://howlongtobeat.com/api/search";
397
398 // Build search payload (HLTB's specific format)
399 std::ostringstream payload;
400 payload << "{";
401 payload << "\"searchType\":\"games\",";
402 payload << "\"searchTerms\":[\"" << ShellUtils::escapeJson(query) << "\"],";
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\":\"\"";
415 payload << "},";
416 payload << "\"users\":{\"sortCategory\":\"postcount\"},";
417 payload << "\"filter\":\"\",";
418 payload << "\"sort\":0,";
419 payload << "\"randomizer\":0";
420 payload << "}";
421 payload << "}";
422
423 std::string response = httpPost(url, payload.str(), "application/json");
424
425 if (response.empty())
426 {
427 Logger::warn("HLTB: Empty response for search '{}'", query);
428 return {};
429 }
430
431 auto results = parseSearchResponse(response);
432 Logger::debug("HLTB: Found {} results for '{}'", results.size(), query);
433
434 return results;
435}
436
437HowLongToBeatInfo HLTBService::getGameInfo(const std::string& gameName)
438{
439 if (gameName.empty())
440 {
442 info.found = false;
443 return info;
444 }
445
446 // Check cache first
447 std::string cacheKey = normalizeTitle(gameName);
448 auto cached = hltbCache().get(cacheKey);
449 if (cached)
450 {
451 Logger::debug("HLTB: Cache hit for '{}'", gameName);
452 return *cached;
453 }
454
455 // Search HLTB
456 auto results = search(gameName, 5);
457
458 if (results.empty())
459 {
460 Logger::warn("HLTB: No results found for '{}'", gameName);
462 info.found = false;
463 return info;
464 }
465
466 // Find best match using fuzzy matching
467 double bestScore = 0.0;
468 size_t bestMatchIndex = results.size(); // invalid sentinel
469
470 for (size_t i = 0; i < results.size(); ++i)
471 {
472 results[i].similarity = calculateSimilarity(gameName, results[i].name);
473 if (results[i].similarity > bestScore)
474 {
475 bestScore = results[i].similarity;
476 bestMatchIndex = i;
477 }
478 }
479
480 // Require at least 50% similarity
481 if (bestMatchIndex >= results.size() || bestScore < 0.5)
482 {
483 Logger::warn("HLTB: No good match found for '{}' (best score: {:.2f})", gameName,
484 bestScore);
486 info.found = false;
487 return info;
488 }
489
490 Logger::info("HLTB: Best match for '{}' is '{}' (score: {:.2f})", gameName,
491 results[bestMatchIndex].name, bestScore);
492
493 auto info = parseGameDetails(results[bestMatchIndex]);
494
495 // Cache the result
496 hltbCache().put(cacheKey, info);
497
498 return info;
499}
500
502{
503 if (hltbId <= 0)
504 {
506 info.found = false;
507 return info;
508 }
509
510 // HLTB doesn't have a direct ID lookup API, so we'd need to fetch the game page
511 // For now, return not found - we primarily use name-based search
512 Logger::warn("HLTB: Direct ID lookup not implemented for ID {}", hltbId);
513
515 info.found = false;
516 return info;
517}
518
519// ==============================================================================
520// Async API Implementation
521// ==============================================================================
522
523void HLTBService::getGameInfoAsync(const std::string& gameName, const InfoCallback& callback)
524{
525 auto future = std::make_shared<std::future<void>>(std::async(std::launch::async,
526 [gameName, callback]()
527 {
528 auto info =
529 getGameInfo(gameName);
530 if (callback)
531 {
532 callback(info);
533 }
534 }));
535
536 // Store future to prevent premature destruction
537 static std::mutex futuresMutex;
538 static std::vector<std::shared_ptr<std::future<void>>> activeFutures;
539
540 {
541 std::lock_guard<std::mutex> lock(futuresMutex);
542
543 // Clean up completed futures
544 activeFutures.erase(std::remove_if(activeFutures.begin(), activeFutures.end(),
545 [](const std::shared_ptr<std::future<void>>& f)
546 {
547 return f->wait_for(std::chrono::milliseconds(0)) ==
548 std::future_status::ready;
549 }),
550 activeFutures.end());
551
552 activeFutures.push_back(future);
553 }
554}
555
556void HLTBService::searchAsync(const std::string& query, const SearchCallback& callback,
557 int maxResults)
558{
559 auto future = std::make_shared<std::future<void>>(std::async(std::launch::async,
560 [query, callback, maxResults]()
561 {
562 auto results =
563 search(query, maxResults);
564 if (callback)
565 {
566 callback(results);
567 }
568 }));
569
570 static std::mutex futuresMutex;
571 static std::vector<std::shared_ptr<std::future<void>>> activeFutures;
572
573 {
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)
577 {
578 return f->wait_for(std::chrono::milliseconds(0)) ==
579 std::future_status::ready;
580 }),
581 activeFutures.end());
582 activeFutures.push_back(future);
583 }
584}
585
586// ==============================================================================
587// Batch Operations
588// ==============================================================================
589
590void HLTBService::batchFetch(std::vector<Game*>& games,
591 const std::function<void(int completed, int total)>& progressCallback)
592{
593 int total = static_cast<int>(games.size());
594 int completed = 0;
595
596 for (Game* game : games)
597 {
598 if (!game)
599 continue;
600
601 // Skip if we already have fresh data
602 if (game->hltbInfo.found && !game->hltbInfo.isStale())
603 {
604 completed++;
605 if (progressCallback)
606 progressCallback(completed, total);
607 continue;
608 }
609
610 // Fetch HLTB info
611 auto info = getGameInfo(game->name);
612 if (info.found)
613 {
614 game->hltbInfo = info;
615 }
616
617 completed++;
618 if (progressCallback)
619 progressCallback(completed, total);
620
621 // Small delay to avoid rate limiting
622 std::this_thread::sleep_for(std::chrono::milliseconds(100));
623 }
624}
625
626// ==============================================================================
627// Cache Management
628// ==============================================================================
629
631{
632 hltbCache().clear();
633 Logger::info("HLTB: Cache cleared");
634}
635
Complete representation of a game in the library.
Definition game.h:767
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.
Definition lru_cache.h:44
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
Definition logger.h:100
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
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.
Definition shell_utils.h:65
nlohmann::json json
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.
int gameId
HLTB game ID.
double mainStory
Main story time.
double mainExtras
Main + extras time.
Time-to-beat estimates from HowLongToBeat.com.
Definition game.h:672
time_t lastUpdated
When this data was fetched.
Definition game.h:683
double allStylesHours
Average across all playstyles.
Definition game.h:680
double completionistHours
100% completion
Definition game.h:679
int hltbId
HowLongToBeat game ID.
Definition game.h:673
bool found
Whether a match was found.
Definition game.h:684
std::string matchedName
Name matched on HLTB.
Definition game.h:674
double mainPlusExtrasHours
Main + side content.
Definition game.h:678
double mainStoryHours
Main story/campaign only.
Definition game.h:677