game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
gog_integration.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// gog_integration.cpp
4// ==============================================================================
5// Implementation of GOG.com integration
6// ==============================================================================
7
8#include "gog_integration.h"
9#include "logger.h"
10#include "shell_utils.h"
11
12#include <array>
13#include <atomic>
14#include <cstdio>
15#include <cstdlib>
16#include <fstream>
17#include <mutex>
18#include <nlohmann/json.hpp>
19#include <sstream>
20#include <sys/wait.h>
21#include <thread>
22#include <utility>
23
24using json = nlohmann::json;
25namespace fs = std::filesystem;
26
27// ==============================================================================
28// Helper Functions
29// ==============================================================================
30
32{
33 if (installSize < 1024)
34 return std::to_string(installSize) + " B";
35 if (installSize < 1024 * 1024)
36 return std::to_string(installSize / 1024) + " KB";
37 if (installSize < 1024LL * 1024 * 1024)
38 return std::to_string(installSize / (1024 * 1024)) + " MB";
39 return std::to_string(installSize / (1024LL * 1024 * 1024)) + " GB";
40}
41
43{
44 if (!isAuthenticated)
45 return true;
46 return std::chrono::system_clock::now() > tokenExpiry;
47}
48
49std::string GOGProgress::getStateStr() const
50{
51 switch (state)
52 {
53 case State::Starting:
54 return "Starting";
56 return "Downloading";
58 return "Verifying";
60 return "Installing";
62 return "Completed";
63 case State::Failed:
64 return "Failed";
66 return "Cancelled";
67 default:
68 return "Unknown";
69 }
70}
71
72// ==============================================================================
73// Implementation Details
74// ==============================================================================
75
77{
78 mutable std::mutex mutex;
79 std::atomic<bool> cancelFlag{false};
80
83
84 // Cached data
85 std::vector<GOGGameInfo> libraryCache;
86 std::chrono::system_clock::time_point libraryCacheTime;
87 bool libraryCacheValid = false;
88
89 // Settings
91
92 // Async-worker tracking. Every method that spawns a future captures
93 // `this`, so the destructor MUST wait for those workers to finish before
94 // `impl_` goes away — otherwise the worker UAFs on `impl_->cancelFlag`,
95 // `impl_->activeBackend`, etc. We hold a separate mutex from `mutex`
96 // so a worker that takes `mutex` mid-flight doesn't deadlock with the
97 // destructor's join. The vector stores `std::future<void>` (the worker's
98 // own completion handle); the caller-facing `std::future<bool>` is a
99 // separate object backed by a `std::promise`, so callers who drop their
100 // future don't strand the worker.
101 std::mutex futuresMutex;
102 std::vector<std::shared_ptr<std::future<void>>> activeFutures;
103
104 static constexpr int LIBRARY_CACHE_VALIDITY_SEC = 300;
105
107 {
108 const char* home = std::getenv("HOME");
109 if (home)
110 {
111 defaultInstallPath = fs::path(home) / "Games/GOG";
112 }
113 }
114
115 // Append a worker future and prune any that have already completed.
116 // Called from spawning code only; the destructor uses its own join path.
117 void storeFuture(std::shared_ptr<std::future<void>> f)
118 {
119 std::lock_guard<std::mutex> lock(futuresMutex);
120 activeFutures.erase(std::remove_if(activeFutures.begin(), activeFutures.end(),
121 [](const std::shared_ptr<std::future<void>>& fu)
122 {
123 return fu->wait_for(std::chrono::seconds(0)) ==
124 std::future_status::ready;
125 }),
126 activeFutures.end());
127 activeFutures.push_back(std::move(f));
128 }
129};
130
131// ==============================================================================
132// Constructor/Destructor
133// ==============================================================================
134
135GOGIntegration::GOGIntegration() : impl_(std::make_unique<Impl>())
136{
137 // Detect available backend
138 if (isHeroicAvailable())
139 {
140 impl_->activeBackend = GOGBackend::Heroic;
141 }
142 else if (isGogdlAvailable())
143 {
144 impl_->activeBackend = GOGBackend::GOGDL;
145 }
146 else
147 {
148 impl_->activeBackend = GOGBackend::Direct;
149 }
150}
151
153{
154 // 1. Signal cancellation so any cooperative worker will short-circuit.
155 impl_->cancelFlag.store(true);
156
157 // 2. Wait for every outstanding async worker to finish before `impl_`
158 // goes away. Move the vector out under the lock so workers that
159 // re-enter via callbacks (which may take futuresMutex via storeFuture)
160 // cannot deadlock with us.
161 std::vector<std::shared_ptr<std::future<void>>> pending;
162 {
163 std::lock_guard<std::mutex> lock(impl_->futuresMutex);
164 pending = std::move(impl_->activeFutures);
165 }
166 for (auto& f : pending)
167 {
168 if (f && f->valid())
169 {
170 f->wait();
171 }
172 }
173}
174
175// ==============================================================================
176// Availability Check
177// ==============================================================================
178
180{
182}
183
185{
186 return impl_->activeBackend;
187}
188
190{
191 // Check for Heroic config directory
192 const char* home = std::getenv("HOME");
193 if (!home)
194 return false;
195
196 fs::path heroicConfig = fs::path(home) / ".config/heroic";
197 fs::path heroicFlatpak = fs::path(home) / ".var/app/com.heroicgameslauncher.hgl/config/heroic";
198
199 return fs::exists(heroicConfig) || fs::exists(heroicFlatpak);
200}
201
203{
204 // Cache the `which gogdl` result for the lifetime of the process.
205 // The function is called from the constructor, setPreferredBackend,
206 // isAvailable, and the install dispatcher — running popen on every
207 // call adds visible latency to the UI thread when these are reached
208 // from a hot path. The user installing/uninstalling gogdl mid-session
209 // is rare; if it matters, restarting the launcher refreshes.
210 //
211 // Thread-safe via std::call_once (one-shot init regardless of which
212 // thread arrives first).
213 static std::atomic<bool> cached{false};
214 static std::once_flag onceFlag;
215 std::call_once(onceFlag,
216 []()
217 {
218 FILE* pipe = popen("which gogdl 2>/dev/null", "r");
219 if (!pipe)
220 return; // cached stays false
221 std::array<char, 256> buffer{};
222 std::string result;
223 if (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe) != nullptr)
224 {
225 result = buffer.data();
226 }
227 int pcStatus = pclose(pipe);
228 // gogdl is available only if `which` found it (exit 0) AND produced output.
229 if (pcStatus != -1 && WIFEXITED(pcStatus) && WEXITSTATUS(pcStatus) == 0 &&
230 !result.empty())
231 {
232 cached.store(true, std::memory_order_release);
233 }
234 });
235 return cached.load(std::memory_order_acquire);
236}
237
239{
240 impl_->preferredBackend = backend;
241
242 // Update active backend based on availability
243 if (backend == GOGBackend::Heroic && isHeroicAvailable())
244 {
245 impl_->activeBackend = GOGBackend::Heroic;
246 }
247 else if (backend == GOGBackend::GOGDL && isGogdlAvailable())
248 {
249 impl_->activeBackend = GOGBackend::GOGDL;
250 }
251 else if (isHeroicAvailable())
252 {
253 impl_->activeBackend = GOGBackend::Heroic;
254 }
255 else if (isGogdlAvailable())
256 {
257 impl_->activeBackend = GOGBackend::GOGDL;
258 }
259}
260
261// ==============================================================================
262// Heroic Config Path
263// ==============================================================================
264
265fs::path GOGIntegration::getHeroicConfigPath() const
266{
267 const char* home = std::getenv("HOME");
268 if (!home)
269 return {};
270
271 // Check flatpak first
272 fs::path flatpakPath = fs::path(home) / ".var/app/com.heroicgameslauncher.hgl/config/heroic";
273 if (fs::exists(flatpakPath))
274 {
275 return flatpakPath;
276 }
277
278 // Native install
279 fs::path nativePath = fs::path(home) / ".config/heroic";
280 if (fs::exists(nativePath))
281 {
282 return nativePath;
283 }
284
285 return {};
286}
287
288// ==============================================================================
289// Authentication
290// ==============================================================================
291
293{
294 GOGAuthStatus status;
295
296 if (impl_->activeBackend == GOGBackend::Heroic)
297 {
298 fs::path configPath = getHeroicConfigPath();
299 if (configPath.empty())
300 return status;
301
302 fs::path authFile = configPath / "gog_store/auth.json";
303 if (!fs::exists(authFile))
304 return status;
305
306 try
307 {
308 std::ifstream file(authFile);
309 json j = json::parse(file);
310
311 if (j.contains("access_token") && !j["access_token"].get<std::string>().empty())
312 {
313 status.isAuthenticated = true;
314 status.username = j.value("username", "");
315 status.userId = j.value("user_id", "");
316 }
317 }
318 catch (const std::exception& e)
319 {
320 Logger::error("[GOG] Failed to parse auth file: {}", e.what());
321 }
322 }
323
324 return status;
325}
326
331
333{
334 // For Heroic, direct user to open Heroic and log in
335 Logger::info("[GOG] Authentication requested - user should log in via Heroic Games Launcher");
336
337 if (callback)
338 {
339 callback(false, "Please log in to GOG through Heroic Games Launcher");
340 }
341}
342
344{
345 // Clear auth file for Heroic
346 fs::path configPath = getHeroicConfigPath();
347 if (!configPath.empty())
348 {
349 fs::path authFile = configPath / "gog_store/auth.json";
350 std::error_code ec;
351 fs::remove(authFile, ec);
352 }
353
354 {
355 std::lock_guard<std::mutex> lock(impl_->mutex);
356 impl_->libraryCacheValid = false;
357 }
358 Logger::info("[GOG] Logged out");
359}
360
361// ==============================================================================
362// Library Management - Heroic
363// ==============================================================================
364
365std::vector<GOGGameInfo> GOGIntegration::parseHeroicLibrary() const
366{
367 std::vector<GOGGameInfo> games;
368
369 fs::path configPath = getHeroicConfigPath();
370 if (configPath.empty())
371 return games;
372
373 fs::path libraryFile = configPath / "gog_store/library.json";
374 if (!fs::exists(libraryFile))
375 {
376 Logger::debug("[GOG] Heroic library file not found: {}", libraryFile.string());
377 return games;
378 }
379
380 try
381 {
382 std::ifstream file(libraryFile);
383 json j = json::parse(file);
384
385 if (!j.contains("games") || !j["games"].is_array())
386 {
387 return games;
388 }
389
390 for (const auto& item : j["games"])
391 {
392 GOGGameInfo game;
393 game.gameId = item.value("app_name", "");
394 game.title = item.value("title", "");
395
396 if (item.contains("art_square"))
397 {
398 game.coverUrl = item["art_square"].get<std::string>();
399 }
400 if (item.contains("art_cover"))
401 {
402 game.backgroundUrl = item["art_cover"].get<std::string>();
403 }
404
405 // Check platform availability
406 if (item.contains("is_linux_native"))
407 {
408 game.hasLinuxBuild = item["is_linux_native"].get<bool>();
409 }
410 game.hasWindowsBuild = true; // GOG games typically have Windows builds
411
412 if (item.contains("developer"))
413 {
414 game.developer = item["developer"].get<std::string>();
415 }
416 if (item.contains("publisher"))
417 {
418 game.publisher = item["publisher"].get<std::string>();
419 }
420
421 games.push_back(game);
422 }
423 }
424 catch (const std::exception& e)
425 {
426 Logger::error("[GOG] Failed to parse Heroic library: {}", e.what());
427 }
428
429 return games;
430}
431
432std::vector<GOGGameInfo> GOGIntegration::parseHeroicInstalled() const
433{
434 std::vector<GOGGameInfo> games;
435
436 fs::path configPath = getHeroicConfigPath();
437 if (configPath.empty())
438 return games;
439
440 fs::path installedFile = configPath / "gog_store/installed.json";
441 if (!fs::exists(installedFile))
442 {
443 return games;
444 }
445
446 try
447 {
448 std::ifstream file(installedFile);
449 json j = json::parse(file);
450
451 if (!j.is_object())
452 return games;
453
454 for (const auto& [gameId, info] : j.items())
455 {
456 GOGGameInfo game;
457 game.gameId = gameId;
458 game.isInstalled = true;
459
460 if (info.contains("install_path"))
461 {
462 game.installPath = info["install_path"].get<std::string>();
463 }
464 if (info.contains("install_size"))
465 {
466 game.installSize = info["install_size"].get<int64_t>();
467 }
468 if (info.contains("executable"))
469 {
470 game.executable = info["executable"].get<std::string>();
471 }
472 if (info.contains("version"))
473 {
474 game.version = info["version"].get<std::string>();
475 }
476 if (info.contains("title"))
477 {
478 game.title = info["title"].get<std::string>();
479 }
480
481 games.push_back(game);
482 }
483 }
484 catch (const std::exception& e)
485 {
486 Logger::error("[GOG] Failed to parse Heroic installed: {}", e.what());
487 }
488
489 return games;
490}
491
492// Internal: fetch Heroic library without holding mutex (blocking file I/O)
493std::vector<GOGGameInfo> GOGIntegration::fetchLibraryHeroicUnlocked()
494{
495 auto library = parseHeroicLibrary();
496 auto installed = parseHeroicInstalled();
497
498 // Merge installed info into library
499 for (auto& game : library)
500 {
501 for (const auto& inst : installed)
502 {
503 if (inst.gameId == game.gameId)
504 {
505 game.isInstalled = true;
506 game.installPath = inst.installPath;
507 game.installSize = inst.installSize;
508 game.executable = inst.executable;
509 game.version = inst.version;
510 break;
511 }
512 }
513 }
514
515 Logger::info("[GOG] Found {} games in Heroic library", library.size());
516 return library;
517}
518
519std::vector<GOGGameInfo> GOGIntegration::getLibraryHeroic(bool forceRefresh)
520{
521 // Check cache under lock
522 {
523 std::lock_guard<std::mutex> lock(impl_->mutex);
524 if (!forceRefresh && impl_->libraryCacheValid)
525 {
526 auto now = std::chrono::system_clock::now();
527 auto age =
528 std::chrono::duration_cast<std::chrono::seconds>(now - impl_->libraryCacheTime);
529 if (age.count() < Impl::LIBRARY_CACHE_VALIDITY_SEC)
530 return impl_->libraryCache;
531 }
532 }
533
534 // Do blocking I/O WITHOUT holding the mutex
535 auto library = fetchLibraryHeroicUnlocked();
536
537 // Store results under lock
538 {
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;
543 }
544
545 return library;
546}
547
548// ==============================================================================
549// Library Management - gogdl
550// ==============================================================================
551
552std::vector<GOGGameInfo> GOGIntegration::getLibraryGogdl(bool /*forceRefresh*/)
553{
554 std::vector<GOGGameInfo> games;
555
556 // Run gogdl list
557 FILE* pipe = popen("gogdl list --json 2>/dev/null", "r");
558 if (!pipe)
559 {
560 return games;
561 }
562
563 std::array<char, 4096> buffer;
564 std::string result;
565 constexpr size_t kMaxOutput = 16u * 1024 * 1024; // 16 MB
566 while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe) != nullptr)
567 {
568 result += buffer.data();
569 if (result.size() > kMaxOutput)
570 break;
571 }
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));
576
577 try
578 {
579 auto j = json::parse(result);
580
581 for (const auto& item : j)
582 {
583 GOGGameInfo game;
584 game.gameId = item.value("id", "");
585 game.title = item.value("title", "");
586 game.isInstalled = item.value("installed", false);
587
588 games.push_back(game);
589 }
590 }
591 catch (const json::exception& e)
592 {
593 Logger::error("[GOG] Failed to parse gogdl output: {}", e.what());
594 }
595
596 return games;
597}
598
599// ==============================================================================
600// Library Management
601// ==============================================================================
602
603std::vector<GOGGameInfo> GOGIntegration::getLibrary(bool forceRefresh)
604{
605 // Read backend WITHOUT holding the mutex (non-blocking field read)
606 // Cache checks and updates are handled inside each backend method with their own locks
607 GOGBackend backend;
608 {
609 std::lock_guard<std::mutex> lock(impl_->mutex);
610 backend = impl_->activeBackend;
611 }
612
613 if (backend == GOGBackend::Heroic)
614 return getLibraryHeroic(forceRefresh);
615 else if (backend == GOGBackend::GOGDL)
616 return getLibraryGogdl(forceRefresh);
617
618 return {};
619}
620
621std::vector<GOGGameInfo> GOGIntegration::getInstalledGames() const
622{
623 std::vector<GOGGameInfo> installed;
624
625 if (impl_->activeBackend == GOGBackend::Heroic)
626 {
627 return parseHeroicInstalled();
628 }
629
630 std::lock_guard<std::mutex> lock(impl_->mutex);
631 for (const auto& game : impl_->libraryCache)
632 {
633 if (game.isInstalled)
634 {
635 installed.push_back(game);
636 }
637 }
638
639 return installed;
640}
641
642std::optional<GOGGameInfo> GOGIntegration::getGameInfo(const std::string& gameId) const
643{
644 std::lock_guard<std::mutex> lock(impl_->mutex);
645 for (const auto& game : impl_->libraryCache)
646 {
647 if (game.gameId == gameId)
648 {
649 return game;
650 }
651 }
652
653 return std::nullopt;
654}
655
657{
658 Game game;
659 game.id = "gog_" + gogGame.gameId;
660 game.name = gogGame.title;
661 game.source = GameSource::GOG;
662
663 // Determine runner based on platform
664 if (gogGame.hasLinuxBuild)
665 {
667 }
668 else
669 {
671 }
672
673 if (gogGame.isInstalled)
674 {
675 game.installPath = gogGame.installPath.string();
676 game.runnerConfig.executablePath = (gogGame.installPath / gogGame.executable).string();
677 }
678
679 // Set cover art
680 if (!gogGame.coverUrl.empty())
681 {
683 }
684 if (!gogGame.backgroundUrl.empty())
685 {
687 }
688
689 // Set metadata
690 game.metadata.developer = gogGame.developer;
691 game.metadata.publisher = gogGame.publisher;
692 game.metadata.genres = gogGame.genres;
693
694 return game;
695}
696
698{
699 auto games = getLibrary(true);
700 Logger::info("[GOG] Synced {} games from GOG library", games.size());
701 return static_cast<int>(games.size());
702}
703
704// ==============================================================================
705// Installation
706// ==============================================================================
707
708bool GOGIntegration::installGameHeroic(const std::string& gameId,
709 const std::filesystem::path& /*path*/,
710 const ProgressCallback& /*cb*/)
711{
712 // Heroic installation is typically done through the Heroic GUI
713 // For CLI, we'd need to call heroic-cli or use their internal methods
714 Logger::info("[GOG] Install via Heroic requested for: {}", gameId);
715 return false; // Not implemented - user should use Heroic GUI
716}
717
718bool GOGIntegration::installGameGogdl(const std::string& gameId, const std::filesystem::path& path,
719 const ProgressCallback& callback)
720{
721 Logger::info("[GOG] Installing game via gogdl: {}", gameId);
722
723 impl_->cancelFlag.store(false);
724
725 std::string cmd = "gogdl download " + ShellUtils::escapeArg(gameId);
726 if (!path.empty())
727 {
728 cmd += " --path " + ShellUtils::escapeArg(path.string());
729 }
730 cmd += " 2>&1";
731
732 FILE* pipe = popen(cmd.c_str(), "r");
733 if (!pipe)
734 {
735 return false;
736 }
737
738 std::array<char, 1024> buffer;
739 while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe) != nullptr)
740 {
741 if (impl_->cancelFlag.load())
742 {
743 pclose(pipe);
744 return false;
745 }
746
747 if (callback)
748 {
749 GOGProgress progress;
751 progress.currentFile = buffer.data();
752 callback(progress);
753 }
754 }
755
756 int status = pclose(pipe);
757 return status != -1 && WIFEXITED(status) && WEXITSTATUS(status) == 0;
758}
759
760bool GOGIntegration::installGame(const std::string& gameId,
761 const std::filesystem::path& installPath,
762 const std::string& /*platform*/,
763 const ProgressCallback& progressCallback)
764{
765 if (impl_->activeBackend == GOGBackend::Heroic)
766 {
767 return installGameHeroic(gameId, installPath, progressCallback);
768 }
769 else if (impl_->activeBackend == GOGBackend::GOGDL)
770 {
771 return installGameGogdl(gameId, installPath, progressCallback);
772 }
773
774 return false;
775}
776
777std::future<bool> GOGIntegration::installGameAsync(const std::string& gameId,
778 const std::filesystem::path& installPath,
779 const std::string& platform,
780 const ProgressCallback& progressCallback)
781{
782 // Split the worker future from the caller-facing future so that callers
783 // who drop the returned future do NOT strand the worker (and the worker's
784 // captured `this` survives until the destructor joins it).
785 auto promise = std::make_shared<std::promise<bool>>();
786 auto callerFuture = promise->get_future();
787
788 auto workerFuture = std::make_shared<std::future<void>>(
789 std::async(std::launch::async,
790 [this, gameId, installPath, platform, progressCallback, promise]()
791 {
792 try
793 {
794 bool ok = installGame(gameId, installPath, platform, progressCallback);
795 promise->set_value(ok);
796 }
797 catch (...)
798 {
799 promise->set_exception(std::current_exception());
800 }
801 }));
802 impl_->storeFuture(std::move(workerFuture));
803 return callerFuture;
804}
805
806bool GOGIntegration::uninstallGame(const std::string& gameId)
807{
808 Logger::info("[GOG] Uninstalling game: {}", gameId);
809
810 auto gameInfo = getGameInfo(gameId);
811 if (!gameInfo || !gameInfo->isInstalled)
812 {
813 return false;
814 }
815
816 // Validate install path is within a trusted prefix before destructive removal
817 const std::string installPath = gameInfo->installPath;
818 if (installPath.empty())
819 {
820 Logger::error("[GOG] Uninstall refused: empty install path for game {}", gameId);
821 return false;
822 }
823 std::error_code ecCanon;
824 fs::path canonical = fs::weakly_canonical(installPath, ecCanon);
825 if (ecCanon)
826 {
827 Logger::error("[GOG] Uninstall refused: cannot canonicalize path '{}': {}", installPath,
828 ecCanon.message());
829 return false;
830 }
831 // Whitelist: path must be strictly inside $HOME (not equal to it)
832 // A blacklist of /proc /sys /dev is insufficient — use whitelist instead.
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()] == '/');
839 if (!isSafe)
840 {
841 Logger::error("[GOG] Uninstall refused: path '{}' is not inside home directory", canonStr);
842 return false;
843 }
844
845 // Remove installation directory
846 std::error_code ec;
847 fs::remove_all(canonical, ec);
848
849 if (ec)
850 {
851 Logger::error("[GOG] Failed to remove game directory: {}", ec.message());
852 return false;
853 }
854
855 {
856 std::lock_guard<std::mutex> lock(impl_->mutex);
857 impl_->libraryCacheValid = false;
858 }
859 return true;
860}
861
862bool GOGIntegration::updateGame(const std::string& gameId, const ProgressCallback& progressCallback)
863{
864 Logger::info("[GOG] Updating game: {}", gameId);
865
866 if (impl_->activeBackend == GOGBackend::GOGDL)
867 {
868 return installGameGogdl(gameId, {}, progressCallback);
869 }
870
871 return false;
872}
873
874bool GOGIntegration::hasUpdate(const std::string& /*gameId*/) const
875{
876 // Would need to query GOG API to check for updates
877 return false;
878}
879
880bool GOGIntegration::verifyGame(const std::string& gameId,
881 const ProgressCallback& /*progressCallback*/)
882{
883 Logger::info("[GOG] Verifying game: {}", gameId);
884 // GOG games typically include their own verification tools
885 return false;
886}
887
888bool GOGIntegration::importGame(const std::string& gameId,
889 const std::filesystem::path& existingPath)
890{
891 Logger::info("[GOG] Importing game {} from {}", gameId, existingPath.string());
892
893 if (!fs::exists(existingPath))
894 {
895 return false;
896 }
897
898 // For Heroic, we'd need to update the installed.json
899 // For now, just return success
900 {
901 std::lock_guard<std::mutex> lock(impl_->mutex);
902 impl_->libraryCacheValid = false;
903 }
904 return true;
905}
906
907// ==============================================================================
908// Cloud Saves
909// ==============================================================================
910
911bool GOGIntegration::downloadCloudSaves(const std::string& gameId)
912{
913 Logger::info("[GOG] Downloading cloud saves for: {}", gameId);
914 // GOG cloud saves are handled by Heroic
915 return false;
916}
917
918bool GOGIntegration::uploadCloudSaves(const std::string& gameId)
919{
920 Logger::info("[GOG] Uploading cloud saves for: {}", gameId);
921 return false;
922}
923
924bool GOGIntegration::syncCloudSaves(const std::string& gameId)
925{
926 Logger::info("[GOG] Syncing cloud saves for: {}", gameId);
927 return false;
928}
929
930// ==============================================================================
931// Launch
932// ==============================================================================
933
934bool GOGIntegration::launchGame(const std::string& gameId, bool /*useProton*/,
935 const std::string& /*protonVersion*/)
936{
937 Logger::info("[GOG] Launching game: {}", gameId);
938
939 auto gameInfo = getGameInfo(gameId);
940 if (!gameInfo || !gameInfo->isInstalled)
941 {
942 Logger::error("[GOG] Game not installed: {}", gameId);
943 return false;
944 }
945
946 fs::path execPath = gameInfo->installPath / gameInfo->executable;
947
948 // Containment check: ensure the resolved executable stays within installPath.
949 // Use separate error codes — sharing one variable causes the second call to
950 // clear the first call's error, masking a failed canonicalization.
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);
954 if (ec1 || ec2)
955 {
956 Logger::error("[GOG] Cannot verify executable containment, rejecting: {}",
957 execPath.string());
958 return false;
959 }
960 {
961 std::error_code ec;
962 auto rel = fs::relative(canonical, base, ec);
963 if (ec || rel.empty() || *rel.begin() == "..")
964 {
965 Logger::error("[GOG] Executable path escapes installPath: {}", execPath.string());
966 return false;
967 }
968 }
969
970 if (!fs::exists(execPath))
971 {
972 Logger::error("[GOG] Game executable not found: {}", execPath.string());
973 return false;
974 }
975
976 // Launch in background with &. The shell exits 0 immediately after spawning, so
977 // we check only for system() failure (-1 = fork failed), not the game's exit code.
978 std::string cmd = ShellUtils::escapeArg(execPath.string()) + " &";
979 int result = std::system(cmd.c_str());
980
981 if (result == -1)
982 {
983 Logger::error("[GOG] Failed to fork shell for game launch");
984 return false;
985 }
986 return true; // shell spawned the background process successfully
987}
988
989std::string GOGIntegration::getLaunchCommand(const std::string& gameId) const
990{
991 auto gameInfo = getGameInfo(gameId);
992 if (!gameInfo || !gameInfo->isInstalled)
993 {
994 return "";
995 }
996
997 return (gameInfo->installPath / gameInfo->executable).string();
998}
999
1000// ==============================================================================
1001// Configuration
1002// ==============================================================================
1003
1004void GOGIntegration::setDefaultInstallPath(const std::filesystem::path& path)
1005{
1006 std::lock_guard<std::mutex> lock(impl_->mutex);
1007 impl_->defaultInstallPath = path;
1008}
1009
1010std::filesystem::path GOGIntegration::getDefaultInstallPath() const
1011{
1012 std::lock_guard<std::mutex> lock(impl_->mutex);
1013 return impl_->defaultInstallPath;
1014}
1015
1017{
1018 impl_->cancelFlag.store(true);
1019}
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.
Definition game.h:767
GameMetadata metadata
Descriptive information and media.
Definition game.h:785
std::string installPath
Installation directory path.
Definition game.h:819
std::string name
Display name shown in UI.
Definition game.h:774
std::string id
Unique identifier (auto-generated or user-specified).
Definition game.h:773
GameRunner runner
Runner/compatibility layer to use (Native, Proton, Wine, etc.).
Definition game.h:777
GameRunnerConfig runnerConfig
How to launch and run the game.
Definition game.h:784
GameSource source
Where the game was acquired from (Steam, GOG, Local, etc.).
Definition game.h:775
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 escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
Definition shell_utils.h:65
@ GOG
GOG.com (DRM-free games).
Definition game.h:42
@ Native
Native Linux executable (no compatibility layer).
Definition game.h:82
@ Wine
Wine compatibility layer.
Definition game.h:83
nlohmann::json json
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::string username
std::string userId
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.
int64_t installSize
std::string gameId
GOG game ID (numeric string).
std::string publisher
std::string developer
std::string version
Installed version.
std::string getFormattedSize() const
std::string coverUrl
std::vector< std::string > genres
std::string title
Display title.
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
static constexpr int LIBRARY_CACHE_VALIDITY_SEC
std::string getStateStr() const
std::string currentFile
std::string verticalCover
Vertical cover art (library_600x900.jpg).
Definition game.h:497
std::string heroImage
Wide banner/hero image (library_hero.jpg).
Definition game.h:498
GameImagePaths imagePaths
Paths to all available image assets.
Definition game.h:562
std::string developer
Developer/studio name.
Definition game.h:568
std::string publisher
Publisher name.
Definition game.h:569
std::vector< std::string > genres
Game genres (RPG, FPS, Strategy, etc.).
Definition game.h:566
std::string executablePath
Full path to game executable.
Definition game.h:141