18#include <nlohmann/json.hpp>
24using json = nlohmann::json;
25namespace fs = std::filesystem;
38 return std::to_string(
installSize / (1024 * 1024)) +
" MB";
39 return std::to_string(
installSize / (1024LL * 1024 * 1024)) +
" GB";
46 return std::chrono::system_clock::now() >
tokenExpiry;
108 const char* home = std::getenv(
"HOME");
121 [](
const std::shared_ptr<std::future<void>>& fu)
123 return fu->wait_for(std::chrono::seconds(0)) ==
124 std::future_status::ready;
155 impl_->cancelFlag.store(
true);
161 std::vector<std::shared_ptr<std::future<void>>> pending;
163 std::lock_guard<std::mutex> lock(impl_->futuresMutex);
164 pending = std::move(impl_->activeFutures);
166 for (
auto& f : pending)
186 return impl_->activeBackend;
192 const char* home = std::getenv(
"HOME");
196 fs::path heroicConfig = fs::path(home) /
".config/heroic";
197 fs::path heroicFlatpak = fs::path(home) /
".var/app/com.heroicgameslauncher.hgl/config/heroic";
199 return fs::exists(heroicConfig) || fs::exists(heroicFlatpak);
213 static std::atomic<bool> cached{
false};
214 static std::once_flag onceFlag;
215 std::call_once(onceFlag,
218 FILE* pipe = popen(
"which gogdl 2>/dev/null",
"r");
221 std::array<char, 256> buffer{};
223 if (fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe) !=
nullptr)
225 result = buffer.data();
227 int pcStatus = pclose(pipe);
229 if (pcStatus != -1 && WIFEXITED(pcStatus) && WEXITSTATUS(pcStatus) == 0 &&
232 cached.store(
true, std::memory_order_release);
235 return cached.load(std::memory_order_acquire);
240 impl_->preferredBackend = backend;
265fs::path GOGIntegration::getHeroicConfigPath()
const
267 const char* home = std::getenv(
"HOME");
272 fs::path flatpakPath = fs::path(home) /
".var/app/com.heroicgameslauncher.hgl/config/heroic";
273 if (fs::exists(flatpakPath))
279 fs::path nativePath = fs::path(home) /
".config/heroic";
280 if (fs::exists(nativePath))
298 fs::path configPath = getHeroicConfigPath();
299 if (configPath.empty())
302 fs::path authFile = configPath /
"gog_store/auth.json";
303 if (!fs::exists(authFile))
308 std::ifstream file(authFile);
309 json j = json::parse(file);
311 if (j.contains(
"access_token") && !j[
"access_token"].get<std::string>().empty())
314 status.
username = j.value(
"username",
"");
315 status.
userId = j.value(
"user_id",
"");
318 catch (
const std::exception& e)
320 Logger::error(
"[GOG] Failed to parse auth file: {}", e.what());
335 Logger::info(
"[GOG] Authentication requested - user should log in via Heroic Games Launcher");
339 callback(
false,
"Please log in to GOG through Heroic Games Launcher");
346 fs::path configPath = getHeroicConfigPath();
347 if (!configPath.empty())
349 fs::path authFile = configPath /
"gog_store/auth.json";
351 fs::remove(authFile, ec);
355 std::lock_guard<std::mutex> lock(impl_->mutex);
356 impl_->libraryCacheValid =
false;
365std::vector<GOGGameInfo> GOGIntegration::parseHeroicLibrary()
const
367 std::vector<GOGGameInfo> games;
369 fs::path configPath = getHeroicConfigPath();
370 if (configPath.empty())
373 fs::path libraryFile = configPath /
"gog_store/library.json";
374 if (!fs::exists(libraryFile))
376 Logger::debug(
"[GOG] Heroic library file not found: {}", libraryFile.string());
382 std::ifstream file(libraryFile);
383 json j = json::parse(file);
385 if (!j.contains(
"games") || !j[
"games"].is_array())
390 for (
const auto& item : j[
"games"])
393 game.
gameId = item.value(
"app_name",
"");
394 game.
title = item.value(
"title",
"");
396 if (item.contains(
"art_square"))
398 game.
coverUrl = item[
"art_square"].get<std::string>();
400 if (item.contains(
"art_cover"))
406 if (item.contains(
"is_linux_native"))
412 if (item.contains(
"developer"))
414 game.
developer = item[
"developer"].get<std::string>();
416 if (item.contains(
"publisher"))
418 game.
publisher = item[
"publisher"].get<std::string>();
421 games.push_back(game);
424 catch (
const std::exception& e)
426 Logger::error(
"[GOG] Failed to parse Heroic library: {}", e.what());
432std::vector<GOGGameInfo> GOGIntegration::parseHeroicInstalled()
const
434 std::vector<GOGGameInfo> games;
436 fs::path configPath = getHeroicConfigPath();
437 if (configPath.empty())
440 fs::path installedFile = configPath /
"gog_store/installed.json";
441 if (!fs::exists(installedFile))
448 std::ifstream file(installedFile);
449 json j = json::parse(file);
454 for (
const auto& [gameId, info] : j.items())
460 if (info.contains(
"install_path"))
462 game.
installPath = info[
"install_path"].get<std::string>();
464 if (info.contains(
"install_size"))
466 game.
installSize = info[
"install_size"].get<int64_t>();
468 if (info.contains(
"executable"))
470 game.
executable = info[
"executable"].get<std::string>();
472 if (info.contains(
"version"))
474 game.
version = info[
"version"].get<std::string>();
476 if (info.contains(
"title"))
478 game.
title = info[
"title"].get<std::string>();
481 games.push_back(game);
484 catch (
const std::exception& e)
486 Logger::error(
"[GOG] Failed to parse Heroic installed: {}", e.what());
493std::vector<GOGGameInfo> GOGIntegration::fetchLibraryHeroicUnlocked()
495 auto library = parseHeroicLibrary();
496 auto installed = parseHeroicInstalled();
499 for (
auto& game : library)
501 for (
const auto& inst : installed)
503 if (inst.gameId == game.
gameId)
515 Logger::info(
"[GOG] Found {} games in Heroic library", library.size());
519std::vector<GOGGameInfo> GOGIntegration::getLibraryHeroic(
bool forceRefresh)
523 std::lock_guard<std::mutex> lock(impl_->mutex);
524 if (!forceRefresh && impl_->libraryCacheValid)
526 auto now = std::chrono::system_clock::now();
528 std::chrono::duration_cast<std::chrono::seconds>(now - impl_->libraryCacheTime);
530 return impl_->libraryCache;
535 auto library = fetchLibraryHeroicUnlocked();
539 std::lock_guard<std::mutex> lock(impl_->mutex);
540 impl_->libraryCache = library;
541 impl_->libraryCacheTime = std::chrono::system_clock::now();
542 impl_->libraryCacheValid =
true;
552std::vector<GOGGameInfo> GOGIntegration::getLibraryGogdl(
bool )
554 std::vector<GOGGameInfo> games;
557 FILE* pipe = popen(
"gogdl list --json 2>/dev/null",
"r");
563 std::array<char, 4096> buffer;
565 constexpr size_t kMaxOutput = 16u * 1024 * 1024;
566 while (fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe) !=
nullptr)
568 result += buffer.data();
569 if (result.size() > kMaxOutput)
572 int pcStatus = pclose(pipe);
573 if (pcStatus == -1 || (WIFEXITED(pcStatus) && WEXITSTATUS(pcStatus) != 0))
574 Logger::warn(
"[GOG] gogdl exited with non-zero status: {}",
575 pcStatus == -1 ? -1 : WEXITSTATUS(pcStatus));
579 auto j = json::parse(result);
581 for (
const auto& item : j)
584 game.
gameId = item.value(
"id",
"");
585 game.
title = item.value(
"title",
"");
588 games.push_back(game);
591 catch (
const json::exception& e)
593 Logger::error(
"[GOG] Failed to parse gogdl output: {}", e.what());
609 std::lock_guard<std::mutex> lock(impl_->mutex);
610 backend = impl_->activeBackend;
614 return getLibraryHeroic(forceRefresh);
616 return getLibraryGogdl(forceRefresh);
623 std::vector<GOGGameInfo> installed;
627 return parseHeroicInstalled();
630 std::lock_guard<std::mutex> lock(impl_->mutex);
631 for (
const auto& game : impl_->libraryCache)
635 installed.push_back(game);
644 std::lock_guard<std::mutex> lock(impl_->mutex);
645 for (
const auto& game : impl_->libraryCache)
647 if (game.
gameId == gameId)
700 Logger::info(
"[GOG] Synced {} games from GOG library", games.size());
701 return static_cast<int>(games.size());
708bool GOGIntegration::installGameHeroic(
const std::string& gameId,
709 const std::filesystem::path& ,
710 const ProgressCallback& )
714 Logger::info(
"[GOG] Install via Heroic requested for: {}", gameId);
718bool GOGIntegration::installGameGogdl(
const std::string& gameId,
const std::filesystem::path& path,
719 const ProgressCallback& callback)
721 Logger::info(
"[GOG] Installing game via gogdl: {}", gameId);
723 impl_->cancelFlag.store(
false);
732 FILE* pipe = popen(cmd.c_str(),
"r");
738 std::array<char, 1024> buffer;
739 while (fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe) !=
nullptr)
741 if (impl_->cancelFlag.load())
749 GOGProgress progress;
756 int status = pclose(pipe);
757 return status != -1 && WIFEXITED(status) && WEXITSTATUS(status) == 0;
761 const std::filesystem::path& installPath,
767 return installGameHeroic(gameId, installPath, progressCallback);
771 return installGameGogdl(gameId, installPath, progressCallback);
778 const std::filesystem::path& installPath,
785 auto promise = std::make_shared<std::promise<bool>>();
786 auto callerFuture = promise->get_future();
788 auto workerFuture = std::make_shared<std::future<void>>(
789 std::async(std::launch::async,
790 [
this, gameId, installPath,
platform, progressCallback, promise]()
795 promise->set_value(ok);
799 promise->set_exception(std::current_exception());
802 impl_->storeFuture(std::move(workerFuture));
811 if (!gameInfo || !gameInfo->isInstalled)
817 const std::string installPath = gameInfo->installPath;
818 if (installPath.empty())
820 Logger::error(
"[GOG] Uninstall refused: empty install path for game {}", gameId);
823 std::error_code ecCanon;
824 fs::path canonical = fs::weakly_canonical(installPath, ecCanon);
827 Logger::error(
"[GOG] Uninstall refused: cannot canonicalize path '{}': {}", installPath,
833 const std::string canonStr = canonical.string();
834 const char* homeEnv = std::getenv(
"HOME");
835 const std::string homeStr = (homeEnv && homeEnv[0] !=
'\0') ? fs::path(homeEnv).string() :
"";
836 bool isSafe = !homeStr.empty() && canonStr.size() > homeStr.size() &&
837 canonStr.compare(0, homeStr.size(), homeStr) == 0 &&
838 (homeStr.back() ==
'/' || canonStr[homeStr.size()] ==
'/');
841 Logger::error(
"[GOG] Uninstall refused: path '{}' is not inside home directory", canonStr);
847 fs::remove_all(canonical, ec);
851 Logger::error(
"[GOG] Failed to remove game directory: {}", ec.message());
856 std::lock_guard<std::mutex> lock(impl_->mutex);
857 impl_->libraryCacheValid =
false;
868 return installGameGogdl(gameId, {}, progressCallback);
889 const std::filesystem::path& existingPath)
891 Logger::info(
"[GOG] Importing game {} from {}", gameId, existingPath.string());
893 if (!fs::exists(existingPath))
901 std::lock_guard<std::mutex> lock(impl_->mutex);
902 impl_->libraryCacheValid =
false;
913 Logger::info(
"[GOG] Downloading cloud saves for: {}", gameId);
920 Logger::info(
"[GOG] Uploading cloud saves for: {}", gameId);
926 Logger::info(
"[GOG] Syncing cloud saves for: {}", gameId);
940 if (!gameInfo || !gameInfo->isInstalled)
946 fs::path execPath = gameInfo->installPath / gameInfo->executable;
951 std::error_code ec1, ec2;
952 fs::path canonical = fs::weakly_canonical(execPath, ec1);
953 fs::path base = fs::weakly_canonical(fs::path(gameInfo->installPath), ec2);
956 Logger::error(
"[GOG] Cannot verify executable containment, rejecting: {}",
962 auto rel = fs::relative(canonical, base, ec);
963 if (ec || rel.empty() || *rel.begin() ==
"..")
965 Logger::error(
"[GOG] Executable path escapes installPath: {}", execPath.string());
970 if (!fs::exists(execPath))
972 Logger::error(
"[GOG] Game executable not found: {}", execPath.string());
979 int result = std::system(cmd.c_str());
992 if (!gameInfo || !gameInfo->isInstalled)
997 return (gameInfo->installPath / gameInfo->executable).string();
1006 std::lock_guard<std::mutex> lock(impl_->mutex);
1007 impl_->defaultInstallPath = path;
1012 std::lock_guard<std::mutex> lock(impl_->mutex);
1013 return impl_->defaultInstallPath;
1018 impl_->cancelFlag.store(
true);
bool launchGame(const std::string &gameId, bool useProton=false, const std::string &protonVersion="")
Launch a game.
std::optional< GOGGameInfo > getGameInfo(const std::string &gameId) const
Get info for a specific game.
std::vector< GOGGameInfo > getLibrary(bool forceRefresh=false)
Get all games in GOG library.
bool syncCloudSaves(const std::string &gameId)
Sync cloud saves (bidirectional).
static bool isHeroicAvailable()
Check if Heroic Games Launcher is installed.
void cancelOperation()
Cancel ongoing operation.
GOGBackend getActiveBackend() const
Get which backend is being used.
bool uninstallGame(const std::string &gameId)
Uninstall a game.
bool verifyGame(const std::string &gameId, const ProgressCallback &progressCallback=nullptr)
Verify game files.
bool importGame(const std::string &gameId, const std::filesystem::path &existingPath)
Import existing game installation.
std::future< bool > installGameAsync(const std::string &gameId, const std::filesystem::path &installPath={}, const std::string &platform="", const ProgressCallback &progressCallback=nullptr)
Install a game asynchronously.
void setDefaultInstallPath(const std::filesystem::path &path)
Set default installation directory.
std::string getLaunchCommand(const std::string &gameId) const
Get launch command for a game.
bool hasUpdate(const std::string &gameId) const
Check if updates are available.
static bool isGogdlAvailable()
Check if gogdl CLI is installed.
bool isAvailable() const
Check if GOG integration is available.
void authenticate(const AuthCallback &callback=nullptr)
Start authentication flow.
Game toGame(const GOGGameInfo &gogGame) const
Convert GOG game to generic Game object.
bool updateGame(const std::string &gameId, const ProgressCallback &progressCallback=nullptr)
Update a game.
std::filesystem::path getDefaultInstallPath() const
Get default installation directory.
bool uploadCloudSaves(const std::string &gameId)
Upload local saves to cloud.
bool installGame(const std::string &gameId, const std::filesystem::path &installPath={}, const std::string &platform="", const ProgressCallback &progressCallback=nullptr)
Install a game.
std::vector< GOGGameInfo > getInstalledGames() const
Get all installed GOG games.
int syncLibrary()
Sync GOG library with game database.
bool isAuthenticated() const
Check if user is authenticated.
void setPreferredBackend(GOGBackend backend)
Set preferred backend.
GOGAuthStatus getAuthStatus() const
Get authentication status.
void logout()
Log out and clear credentials.
std::function< void(bool success, const std::string &message)> AuthCallback
std::function< void(const GOGProgress &)> ProgressCallback
bool downloadCloudSaves(const std::string &gameId)
Download cloud saves for a game.
Complete representation of a game in the library.
GameMetadata metadata
Descriptive information and media.
std::string installPath
Installation directory path.
std::string name
Display name shown in UI.
std::string id
Unique identifier (auto-generated or user-specified).
GameRunner runner
Runner/compatibility layer to use (Native, Proton, Wine, etc.).
GameRunnerConfig runnerConfig
How to launch and run the game.
GameSource source
Where the game was acquired from (Steam, GOG, Local, etc.).
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.
@ GOG
GOG.com (DRM-free games).
@ Native
Native Linux executable (no compatibility layer).
@ Wine
Wine compatibility layer.
GOGBackend
Backend to use for GOG operations.
@ GOGDL
gogdl CLI (lightweight)
@ Heroic
Heroic Games Launcher (full-featured).
@ Direct
Direct GOG API (limited).
GOG Galaxy authentication status.
bool isTokenExpired() const
std::chrono::system_clock::time_point tokenExpiry
Information about a GOG.com game.
std::string backgroundUrl
std::filesystem::path installPath
std::string executable
Main executable name.
std::string gameId
GOG game ID (numeric string).
std::string version
Installed version.
std::string getFormattedSize() const
std::vector< std::string > genres
std::string title
Display title.
GOGBackend preferredBackend
std::chrono::system_clock::time_point libraryCacheTime
std::vector< GOGGameInfo > libraryCache
void storeFuture(std::shared_ptr< std::future< void > > f)
std::atomic< bool > cancelFlag
std::vector< std::shared_ptr< std::future< void > > > activeFutures
fs::path defaultInstallPath
static constexpr int LIBRARY_CACHE_VALIDITY_SEC
std::string getStateStr() const
std::string verticalCover
Vertical cover art (library_600x900.jpg).
std::string heroImage
Wide banner/hero image (library_hero.jpg).
std::string executablePath
Full path to game executable.