25namespace fs = std::filesystem;
40 [](
const std::shared_ptr<std::future<void>>& fu)
42 return fu->wait_for(std::chrono::seconds(0)) ==
43 std::future_status::ready;
54std::string SteamGridDBService::apiKey_;
55std::mutex SteamGridDBService::apiKeyMutex_;
63 std::lock_guard<std::mutex> lock(apiKeyMutex_);
70 std::lock_guard<std::mutex> lock(apiKeyMutex_);
71 return !apiKey_.empty();
76 const char* home = std::getenv(
"HOME");
80 fs::path cacheDir = fs::path(home) /
".cache" /
"gamelauncher" /
"steamgriddb";
84 if (!fs::exists(cacheDir))
86 fs::create_directories(cacheDir);
89 catch (
const std::exception& e)
91 Logger::warn(
"SteamGridDB: Failed to create cache directory: {}", e.what());
95 return cacheDir.string();
102std::string SteamGridDBService::httpGet(
const std::string& url,
103 const std::map<std::string, std::string>& headers)
105 std::ostringstream cmd;
106 cmd <<
"curl -s -L --connect-timeout 10 --max-time 30 --max-redirs 10 ";
109 for (
const auto& [key, value] : headers)
116 std::array<char, 4096> buffer;
119 std::unique_ptr<FILE, int (*)(FILE*)> pipe(popen(cmd.str().c_str(),
"r"), pclose);
122 Logger::error(
"SteamGridDB: Failed to execute curl command");
126 constexpr size_t kMaxResponse = 16u * 1024 * 1024;
127 while (fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe.get()) !=
nullptr)
129 result += buffer.data();
130 if (result.size() > kMaxResponse)
132 Logger::warn(
"[SteamGridDB] HTTP response too large, truncating");
140bool SteamGridDBService::downloadFile(
const std::string& url,
const std::string& localPath)
143 if (url.compare(0, 8,
"https://") != 0 && url.compare(0, 7,
"http://") != 0)
145 Logger::warn(
"SteamGridDB: Rejected URL with disallowed scheme: {}", url);
150 "curl -s -L --proto =https,http --connect-timeout 10 --max-time 60 --max-redirs 10 -o " +
153 int rawStatus = std::system(cmd.c_str());
154 if (rawStatus == -1 || !WIFEXITED(rawStatus) || WEXITSTATUS(rawStatus) != 0)
156 Logger::warn(
"SteamGridDB: Failed to download file from {}", url);
161 if (!fs::exists(localPath) || fs::file_size(localPath) == 0)
163 Logger::warn(
"SteamGridDB: Downloaded file is empty or missing");
164 fs::remove(localPath);
171std::string SteamGridDBService::urlEncode(
const std::string& str)
173 std::ostringstream encoded;
179 if (std::isalnum(
static_cast<unsigned char>(c)) || c ==
'-' || c ==
'_' || c ==
'.' ||
186 encoded << std::uppercase;
187 encoded << '%' << std::setw(2) << static_cast<int>(
static_cast<unsigned char>(c));
188 encoded << std::nouppercase;
192 return encoded.str();
204 std::string searchKey =
"\"" + key +
"\"";
205 size_t pos =
json.find(searchKey);
206 if (pos == std::string::npos)
209 pos =
json.find(
':', pos);
210 if (pos == std::string::npos)
214 while (pos <
json.size() && std::isspace(
static_cast<unsigned char>(
json[pos])))
217 if (pos >=
json.size())
221 if (
json.substr(pos, 4) ==
"null")
224 if (
json[pos] !=
'"')
230 while (end <
json.size())
232 if (
json[end] ==
'"')
235 size_t numBackslashes = 0;
237 while (check > 0 &&
json[check - 1] ==
'\\')
242 if (numBackslashes % 2 == 0)
248 return json.substr(pos, end - pos);
253 std::string searchKey =
"\"" + key +
"\"";
254 size_t pos =
json.find(searchKey);
255 if (pos == std::string::npos)
258 pos =
json.find(
':', pos);
259 if (pos == std::string::npos)
263 while (pos <
json.size() && std::isspace(
static_cast<unsigned char>(
json[pos])))
268 return std::stoi(
json.substr(pos));
278 std::string searchKey =
"\"" + key +
"\"";
279 size_t pos =
json.find(searchKey);
280 if (pos == std::string::npos)
283 pos =
json.find(
':', pos);
284 if (pos == std::string::npos)
288 while (pos <
json.size() && std::isspace(
static_cast<unsigned char>(
json[pos])))
291 return json.substr(pos, 4) ==
"true";
296 std::vector<std::string> elements;
299 if (arrayKey.empty())
301 start =
json.find(
'[');
305 std::string searchKey =
"\"" + arrayKey +
"\"";
306 size_t keyPos =
json.find(searchKey);
307 if (keyPos == std::string::npos)
309 start =
json.find(
'[', keyPos);
312 if (start == std::string::npos)
317 bool inString =
false;
318 bool escaped =
false;
319 size_t elementStart = start;
321 for (
size_t i = start; i <
json.size(); i++)
347 else if ((c ==
',' || c ==
']') && braceCount == 0)
349 std::string element =
json.substr(elementStart, i - elementStart);
350 size_t first = element.find_first_not_of(
" \t\n\r");
351 size_t last = element.find_last_not_of(
" \t\n\r");
352 if (first != std::string::npos && last != std::string::npos)
354 element = element.substr(first, last - first + 1);
355 if (!element.empty() && element[0] ==
'{')
357 elements.push_back(element);
360 elementStart = i + 1;
363 if (c ==
']' && braceCount == 0)
376std::vector<SteamGridDBGame> SteamGridDBService::parseGamesJson(
const std::string&
json)
378 std::vector<SteamGridDBGame> games;
381 if (
json.find(
"\"success\":true") == std::string::npos &&
382 json.find(
"\"success\": true") == std::string::npos)
384 Logger::warn(
"SteamGridDB: API returned unsuccessful response");
389 for (
const auto& elem : elements)
391 SteamGridDBGame game;
399 size_t steamPos = elem.find(
"\"steam\"");
400 if (steamPos != std::string::npos)
402 size_t idPos = elem.find(
"\"id\"", steamPos);
403 if (idPos != std::string::npos && idPos < steamPos + 100)
411 games.push_back(game);
418std::vector<SteamGridDBImage> SteamGridDBService::parseImagesJson(
const std::string&
json)
420 std::vector<SteamGridDBImage> images;
422 if (
json.find(
"\"success\":true") == std::string::npos &&
423 json.find(
"\"success\": true") == std::string::npos)
429 for (
const auto& elem : elements)
431 SteamGridDBImage image;
442 if (image.
id > 0 && !image.
url.empty())
444 images.push_back(image);
449 std::sort(images.begin(), images.end(), [](
const SteamGridDBImage& a,
const SteamGridDBImage& b)
450 { return a.score > b.score; });
459std::string SteamGridDBService::sanitizeFilename(
const std::string& name)
464 if (std::isalnum(
static_cast<unsigned char>(c)) || c ==
'-' || c ==
'_' || c ==
' ')
468 else if (c ==
':' || c ==
'/' || c ==
'\\')
475 while (!safe.empty() && (safe.front() ==
' ' || safe.front() ==
'_'))
477 while (!safe.empty() && (safe.back() ==
' ' || safe.back() ==
'_'))
483std::string SteamGridDBService::getImageExtension(
const std::string& mime)
485 if (mime.find(
"png") != std::string::npos)
487 if (mime.find(
"jpeg") != std::string::npos || mime.find(
"jpg") != std::string::npos)
489 if (mime.find(
"webp") != std::string::npos)
505 std::string url =
"https://www.steamgriddb.com/api/v2/search/autocomplete/" + urlEncode(query);
507 std::map<std::string, std::string> headers;
509 std::lock_guard<std::mutex> lock(apiKeyMutex_);
510 if (!apiKey_.empty())
512 headers[
"Authorization"] =
"Bearer " + apiKey_;
516 std::string response = httpGet(url, headers);
517 if (response.empty())
519 Logger::warn(
"SteamGridDB: Empty response from search API");
523 auto games = parseGamesJson(response);
524 Logger::info(
"SteamGridDB: Found {} games matching '{}'", games.size(), query);
529 const std::string& query,
530 const std::function<
void(
const std::vector<SteamGridDBGame>&)>& callback)
532 auto future = std::make_shared<std::future<void>>(std::async(std::launch::async,
540 storeFuture(std::move(future));
548 Logger::info(
"SteamGridDB: Looking up Steam App ID {}", steamAppId);
551 "https://www.steamgriddb.com/api/v2/games/steam/" + std::to_string(steamAppId);
553 std::map<std::string, std::string> headers;
555 std::lock_guard<std::mutex> lock(apiKeyMutex_);
556 if (!apiKey_.empty())
558 headers[
"Authorization"] =
"Bearer " + apiKey_;
562 std::string response = httpGet(url, headers);
563 if (response.empty())
566 auto games = parseGamesJson(response);
569 games[0].steamAppId = steamAppId;
585 std::string url =
"https://www.steamgriddb.com/api/v2/grids/game/" + std::to_string(gameId) +
586 "?dimensions=600x900";
588 std::map<std::string, std::string> headers;
590 std::lock_guard<std::mutex> lock(apiKeyMutex_);
591 if (!apiKey_.empty())
593 headers[
"Authorization"] =
"Bearer " + apiKey_;
597 std::string response = httpGet(url, headers);
598 return parseImagesJson(response);
606 std::string url =
"https://www.steamgriddb.com/api/v2/heroes/game/" + std::to_string(gameId);
608 std::map<std::string, std::string> headers;
610 std::lock_guard<std::mutex> lock(apiKeyMutex_);
611 if (!apiKey_.empty())
613 headers[
"Authorization"] =
"Bearer " + apiKey_;
617 std::string response = httpGet(url, headers);
618 return parseImagesJson(response);
626 std::string url =
"https://www.steamgriddb.com/api/v2/logos/game/" + std::to_string(gameId);
628 std::map<std::string, std::string> headers;
630 std::lock_guard<std::mutex> lock(apiKeyMutex_);
631 if (!apiKey_.empty())
633 headers[
"Authorization"] =
"Bearer " + apiKey_;
637 std::string response = httpGet(url, headers);
638 return parseImagesJson(response);
646 std::string url =
"https://www.steamgriddb.com/api/v2/icons/game/" + std::to_string(gameId);
648 std::map<std::string, std::string> headers;
650 std::lock_guard<std::mutex> lock(apiKeyMutex_);
651 if (!apiKey_.empty())
653 headers[
"Authorization"] =
"Bearer " + apiKey_;
657 std::string response = httpGet(url, headers);
658 return parseImagesJson(response);
668 Logger::info(
"SteamGridDB: Fetching all images for game ID {}", gameId);
675 Logger::info(
"SteamGridDB: Found {} grids, {} heroes, {} logos, {} icons", set.
grids.size(),
686 const std::string& gameName)
688 if (image.
url.empty())
692 if (cacheDir.empty())
695 std::string safeName = sanitizeFilename(gameName);
696 std::string extension = getImageExtension(image.
mime);
697 std::string filename = safeName +
"_" + std::to_string(image.
id) + extension;
698 std::string localPath = cacheDir +
"/" + filename;
701 if (fs::exists(localPath) && fs::file_size(localPath) > 0)
703 Logger::debug(
"SteamGridDB: Using cached image: {}", localPath);
707 Logger::info(
"SteamGridDB: Downloading image for '{}' from {}", gameName, image.
url);
709 if (downloadFile(image.
url, localPath))
711 Logger::info(
"SteamGridDB: Downloaded image to {}", localPath);
720 if (gameName.empty())
727 Logger::debug(
"SteamGridDB: Using cached cover for '{}'", gameName);
731 Logger::info(
"SteamGridDB: Searching for cover art for '{}'", gameName);
737 Logger::warn(
"SteamGridDB: No games found matching '{}'", gameName);
742 int bestGameId = games[0].id;
743 std::string nameToMatch = gameName;
744 std::transform(nameToMatch.begin(), nameToMatch.end(), nameToMatch.begin(),
745 [](
unsigned char c) { return static_cast<char>(std::tolower(c)); });
747 for (
const auto& game : games)
749 std::string gameNameLower = game.
name;
750 std::transform(gameNameLower.begin(), gameNameLower.end(), gameNameLower.begin(),
751 [](
unsigned char c) { return static_cast<char>(std::tolower(c)); });
753 if (gameNameLower == nameToMatch)
755 bestGameId = game.
id;
764 Logger::warn(
"SteamGridDB: No cover images found for '{}'", gameName);
769 for (
const auto& cover : covers)
787 const std::string& gameName,
const std::function<
void(
const std::string&)>& callback)
790 std::make_shared<std::future<void>>(std::async(std::launch::async,
791 [gameName, callback]()
798 storeFuture(std::move(future));
804 if (cacheDir.empty())
807 std::string safeName = sanitizeFilename(gameName);
808 if (safeName.empty())
814 for (
const auto& entry : fs::directory_iterator(cacheDir))
816 if (!entry.is_regular_file())
819 std::string filename = entry.path().filename().string();
820 if (filename.find(safeName) == 0)
822 return entry.path().string();
841 if (cacheDir.empty())
846 for (
const auto& entry : fs::directory_iterator(cacheDir))
848 if (entry.is_regular_file())
850 fs::remove(entry.path());
855 catch (
const std::exception& e)
857 Logger::warn(
"SteamGridDB: Failed to clear cache: {}", e.what());
864 if (cacheDir.empty())
867 size_t totalSize = 0;
871 for (
const auto& entry : fs::directory_iterator(cacheDir))
873 if (entry.is_regular_file())
875 totalSize += entry.file_size();
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 escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
static std::vector< SteamGridDBGame > searchGames(const std::string &query)
Search for games by name.
static std::string downloadImage(const SteamGridDBImage &image, const std::string &gameName)
Download an image to local cache.
static std::string getCachedCover(const std::string &gameName)
Check if we have a cached cover for a game.
static std::vector< SteamGridDBImage > getGridImages(int gameId)
Get grid/cover images for a game.
static SteamGridDBGame getGameBySteamAppId(int steamAppId)
Get game info by Steam App ID.
static std::string downloadBestCover(const std::string &gameName)
Download best cover art for a game by name.
static void searchGamesAsync(const std::string &query, const std::function< void(const std::vector< SteamGridDBGame > &)> &callback)
Search for games by name asynchronously.
static void setApiKey(const std::string &key)
Set the API key for SteamGridDB.
static std::vector< SteamGridDBImage > getLogoImages(int gameId)
Get logo images for a game.
static bool hasApiKey()
Check if API key is configured.
static SteamGridDBImageSet getAllImages(int gameId)
Get all images for a game.
static void downloadBestCoverAsync(const std::string &gameName, const std::function< void(const std::string &)> &callback)
Download best cover art asynchronously.
static void clearCache()
Clear all cached images.
static size_t getCacheSize()
Get total size of cached images in bytes.
static std::string getCacheDirectory()
Get the cache directory for downloaded images.
static std::vector< SteamGridDBImage > getHeroImages(int gameId)
Get hero images for a game.
static std::vector< SteamGridDBImage > getIconImages(int gameId)
Get icon images for a game.
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)
int jsonGetInt(const std::string &json, const std::string &key)
std::vector< std::shared_ptr< std::future< void > > > activeFutures_
std::vector< std::string > jsonSplitArray(const std::string &json, const std::string &arrayKey="")
void storeFuture(std::shared_ptr< std::future< void > > f)
bool jsonGetBool(const std::string &json, const std::string &key)
std::string jsonGetString(const std::string &json, const std::string &key)
Search result from SteamGridDB.
int steamAppId
Steam App ID if linked (0 if not Steam).
int id
SteamGridDB game ID.
std::string releaseDate
Release date (YYYY-MM-DD).
std::string name
Game name.
bool verified
If game is verified on SteamGridDB.
Complete set of images for a game.
std::vector< SteamGridDBImage > icons
Icon images.
std::vector< SteamGridDBImage > heroes
Hero images (wide banners).
std::vector< SteamGridDBImage > logos
Logo images with transparency.
std::vector< SteamGridDBImage > grids
Cover art / grid images (600x900).
Image result from SteamGridDB.
int width
Image width in pixels.
std::string thumbUrl
URL for thumbnail.
std::string mime
MIME type (image/png, image/jpeg).
std::string url
URL to download image.
std::string style
Style: "alternate", "blurred", "white_logo", etc.
int score
Community score.
int height
Image height in pixels.
int id
Image ID on SteamGridDB.