game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
legendary_integration.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// legendary_integration.cpp
4// ==============================================================================
5// Implementation of Legendary/Epic Games integration
6// ==============================================================================
7
9#include "logger.h"
10#include "shell_utils.h"
11
12#include <algorithm>
13#include <array>
14#include <atomic>
15#include <cerrno>
16#include <chrono>
17#include <cstdio>
18#include <cstdlib>
19#include <cstring>
20#include <fcntl.h>
21#include <fstream>
22#include <future>
23#include <mutex>
24#include <nlohmann/json.hpp>
25#include <regex>
26#include <sstream>
27#include <sys/wait.h>
28#include <thread>
29#include <unistd.h>
30#include <utility>
31#include <vector>
32
33using json = nlohmann::json;
34namespace fs = std::filesystem;
35
36namespace
37{
38// Escape a string for safe use within double quotes in a shell command
39std::string shellEscape(const std::string& arg)
40{
41 std::string escaped;
42 escaped.reserve(arg.size() + 10);
43 for (char c : arg)
44 {
45 // Note: '!' is NOT escaped — history expansion is disabled in non-interactive
46 // (script/popen) shells, and \! inside double-quotes produces a literal \!
47 // rather than !, corrupting the argument.
48 if (c == '"' || c == '\\' || c == '$' || c == '`' || c == '\n' || c == '\r')
49 {
50 escaped += '\\';
51 }
52 escaped += c;
53 }
54 return escaped;
55}
56} // anonymous namespace
57
58// ==============================================================================
59// Helper Functions
60// ==============================================================================
61
63{
64 if (installSize < 1024)
65 return std::to_string(installSize) + " B";
66 if (installSize < 1024 * 1024)
67 return std::to_string(installSize / 1024) + " KB";
68 if (installSize < 1024LL * 1024 * 1024)
69 return std::to_string(installSize / (1024 * 1024)) + " MB";
70 return std::to_string(installSize / (1024LL * 1024 * 1024)) + " GB";
71}
72
74{
75 if (downloadSize < 1024)
76 return std::to_string(downloadSize) + " B";
77 if (downloadSize < 1024 * 1024)
78 return std::to_string(downloadSize / 1024) + " KB";
79 if (downloadSize < 1024LL * 1024 * 1024)
80 return std::to_string(downloadSize / (1024 * 1024)) + " MB";
81 return std::to_string(downloadSize / (1024LL * 1024 * 1024)) + " GB";
82}
83
85{
86 if (!isAuthenticated)
87 return true;
88 return std::chrono::system_clock::now() > tokenExpiry;
89}
90
92{
93 switch (state)
94 {
95 case State::Starting:
96 return "Starting";
98 return "Downloading";
100 return "Verifying";
102 return "Installing";
104 return "Extracting";
105 case State::Completed:
106 return "Completed";
107 case State::Failed:
108 return "Failed";
109 case State::Cancelled:
110 return "Cancelled";
111 default:
112 return "Unknown";
113 }
114}
115
116// ==============================================================================
117// Implementation Details
118// ==============================================================================
119
121{
122 mutable std::mutex mutex;
123 std::atomic<bool> cancelFlag{false};
124
125 // In-flight installGameAsync workers, joined in ~LegendaryIntegration so
126 // their lambdas — which capture `this` and call member functions — cannot
127 // outlive the object (BUG-4 use-after-free). Guarded by futuresMutex.
128 std::mutex futuresMutex;
129 std::vector<std::future<void>> activeInstalls;
130
131 // Cached data
132 std::vector<EpicGameInfo> libraryCache;
133 std::vector<EpicGameInfo> installedCache;
134 std::chrono::system_clock::time_point libraryCacheTime;
135 bool libraryCacheValid = false;
136
137 // Settings
139 int maxWorkers = 8;
140 bool autoSyncSaves = false;
141
142 // Auth info
144
145 static constexpr int LIBRARY_CACHE_VALIDITY_SEC = 300; // 5 minutes
146
148 {
149 const char* home = std::getenv("HOME");
150 if (home)
151 {
152 defaultInstallPath = fs::path(home) / "Games/Epic";
153 }
154 }
155};
156
157// ==============================================================================
158// Constructor/Destructor
159// ==============================================================================
160
162{
163 // Check auth status on init
164 if (isAvailable())
165 {
166 impl_->authStatus = getAuthStatus();
167 }
168}
169
171{
172 // Signal cancellation first so runLegendaryInteractive aborts promptly,
173 // then join any in-flight installGameAsync workers before destruction —
174 // their lambdas capture `this`, so they must not outlive the object.
175 impl_->cancelFlag.store(true);
176 std::vector<std::future<void>> pending;
177 {
178 std::lock_guard<std::mutex> lock(impl_->futuresMutex);
179 pending = std::move(impl_->activeInstalls);
180 }
181 for (auto& f : pending)
182 {
183 if (f.valid())
184 f.wait();
185 }
186}
187
188// ==============================================================================
189// Availability Check
190// ==============================================================================
191
193{
194 return !getLegendaryPath().empty();
195}
196
198{
199 if (!isAvailable())
200 {
201 return "";
202 }
203
204 // Run legendary --version
205 FILE* pipe = popen("legendary --version 2>&1", "r");
206 if (!pipe)
207 {
208 return "";
209 }
210
211 std::array<char, 256> buffer;
212 std::string result;
213 while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe) != nullptr)
214 {
215 result += buffer.data();
216 }
217 pclose(pipe);
218
219 // Parse version from output (e.g., "legendary version 0.20.33")
220 std::regex versionRegex(R"(version\s+(\S+))");
221 std::smatch match;
222 if (std::regex_search(result, match, versionRegex))
223 {
224 return match[1].str();
225 }
226
227 return result;
228}
229
231{
232 // Check common locations
233 const char* homeEnv = std::getenv("HOME");
234 std::vector<fs::path> paths = {"/usr/bin/legendary", "/usr/local/bin/legendary",
235 fs::path(homeEnv ? homeEnv : "") / ".local/bin/legendary"};
236
237 for (const auto& path : paths)
238 {
239 if (fs::exists(path))
240 {
241 return path;
242 }
243 }
244
245 // Check PATH
246 FILE* pipe = popen("which legendary 2>/dev/null", "r");
247 if (pipe)
248 {
249 std::array<char, 256> buffer;
250 std::string result;
251 if (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe) != nullptr)
252 {
253 result = buffer.data();
254 // Trim newline
255 if (!result.empty() && result.back() == '\n')
256 {
257 result.pop_back();
258 }
259 }
260 pclose(pipe);
261
262 if (!result.empty() && fs::exists(result))
263 {
264 return result;
265 }
266 }
267
268 return {};
269}
270
271// ==============================================================================
272// Helper to run legendary commands
273// ==============================================================================
274
275std::string LegendaryIntegration::runLegendary(const std::vector<std::string>& args,
276 int timeoutSec) const
277{
278 std::string cmd = "legendary";
279 for (const auto& arg : args)
280 {
281 cmd += " \"" + shellEscape(arg) + "\"";
282 }
283 cmd += " 2>&1";
284
285 // Use timeout if available
286 if (timeoutSec > 0)
287 {
288 cmd = "timeout " + std::to_string(timeoutSec) + " " + cmd;
289 }
290
291 FILE* pipe = popen(cmd.c_str(), "r");
292 if (!pipe)
293 {
294 Logger::error("[Legendary] Failed to run command: {}", cmd);
295 return "";
296 }
297
298 std::array<char, 4096> buffer;
299 std::string result;
300 constexpr size_t kMaxOutput = 16u * 1024 * 1024; // 16 MB
301 while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe) != nullptr)
302 {
303 result += buffer.data();
304 if (result.size() > kMaxOutput)
305 break;
306 }
307
308 int status = pclose(pipe);
309 if (status == -1)
310 {
311 Logger::warn("[Legendary] pclose failed for command");
312 }
313 else if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
314 {
315 Logger::debug("[Legendary] Command exited with code {}", WEXITSTATUS(status));
316 }
317 else if (WIFSIGNALED(status))
318 {
319 Logger::debug("[Legendary] Command killed by signal {}", WTERMSIG(status));
320 }
321
322 return result;
323}
324
325bool LegendaryIntegration::runLegendaryInteractive(const std::vector<std::string>& args,
326 const ProgressCallback& callback,
327 std::atomic<bool>& cancelled)
328{
329 std::string cmd = "legendary";
330 for (const auto& arg : args)
331 {
332 cmd += " \"" + shellEscape(arg) + "\"";
333 }
334 cmd += " 2>&1";
335
336 FILE* pipe = popen(cmd.c_str(), "r");
337 if (!pipe)
338 {
339 Logger::error("[Legendary] Failed to run command: {}", cmd);
340 return false;
341 }
342
343 std::array<char, 1024> buffer;
344 std::regex progressRegex(R"(\‍[DL Progress\‍]\s+(\d+\.\d+)%)");
345 std::regex speedRegex(R"((\d+\.\d+)\s*MiB/s)");
346
347 while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe) != nullptr)
348 {
349 if (cancelled.load())
350 {
351 pclose(pipe);
352 return false;
353 }
354
355 std::string line = buffer.data();
356
357 if (callback)
358 {
359 LegendaryProgress progress;
361
362 // Parse progress percentage
363 std::smatch match;
364 if (std::regex_search(line, match, progressRegex))
365 {
366 try
367 {
368 progress.percentComplete = static_cast<int>(std::stof(match[1].str()));
369 }
370 catch (...)
371 {
372 }
373 }
374
375 // Parse download speed
376 if (std::regex_search(line, match, speedRegex))
377 {
378 try
379 {
380 progress.downloadSpeed = std::stof(match[1].str());
381 }
382 catch (...)
383 {
384 }
385 }
386
387 progress.currentFile = line;
388 callback(progress);
389 }
390 }
391
392 int status = pclose(pipe);
393 // pclose() returns the raw waitpid() status word, not the exit code directly.
394 return WIFEXITED(status) && WEXITSTATUS(status) == 0;
395}
396
397// ==============================================================================
398// Authentication
399// ==============================================================================
400
402{
403 EpicAuthStatus status;
404
405 std::string output = runLegendary({"status", "--json"});
406
407 try
408 {
409 auto j = json::parse(output);
410
411 if (j.contains("account"))
412 {
413 status.isAuthenticated = true;
414 status.accountId = j["account"].value("id", "");
415 status.displayName = j["account"].value("name", "");
416 }
417 }
418 catch (const json::exception& e)
419 {
420 // Try simpler check
421 if (output.find("Logged in as") != std::string::npos)
422 {
423 status.isAuthenticated = true;
424 // Parse display name from output
425 std::regex nameRegex(R"(Logged in as: (.+))");
426 std::smatch match;
427 if (std::regex_search(output, match, nameRegex))
428 {
429 status.displayName = match[1].str();
430 }
431 }
432 }
433
434 return status;
435}
436
441
443{
444 // Capture impl_ by value (shared_ptr copy) so the thread safely extends
445 // the lifetime of the implementation data beyond 'this'.
446 auto implCopy = impl_;
447 std::thread(
448 [implCopy, callback]()
449 {
450 // Run legendary outside any lock; may block up to 5 minutes.
451 // Use popen directly rather than 'this' member functions since
452 // the LegendaryIntegration object may have been destroyed.
453 FILE* pipe = popen("legendary auth 2>&1", "r");
454 std::string output;
455 if (pipe)
456 {
457 char buf[256];
458 while (fgets(buf, sizeof(buf), pipe))
459 output += buf;
460 pclose(pipe);
461 }
462
463 bool success = output.find("Successfully logged in") != std::string::npos ||
464 output.find("Logged in as") != std::string::npos;
465
466 if (success)
467 {
468 // Fetch updated status via a minimal popen (no 'this' needed).
469 EpicAuthStatus status;
470 FILE* statusPipe = popen("legendary status --json 2>/dev/null", "r");
471 if (statusPipe)
472 {
473 std::string statusOut;
474 char buf[256];
475 while (fgets(buf, sizeof(buf), statusPipe))
476 statusOut += buf;
477 pclose(statusPipe);
478 // Parse JSON properly to populate accountId and displayName,
479 // matching the logic in getAuthStatus().
480 try
481 {
482 auto j = json::parse(statusOut);
483 if (j.contains("account"))
484 {
485 status.isAuthenticated = true;
486 status.accountId = j["account"].value("id", "");
487 status.displayName = j["account"].value("name", "");
488 }
489 }
490 catch (const json::exception&)
491 {
492 status.isAuthenticated =
493 statusOut.find("\"logged_in\": true") != std::string::npos ||
494 statusOut.find("\"logged_in\":true") != std::string::npos;
495 }
496 }
497 std::lock_guard<std::mutex> lock(implCopy->mutex);
498 implCopy->authStatus = status;
499 }
500
501 if (callback)
502 {
503 callback(success, success ? "Authentication successful" : output);
504 }
505 })
506 .detach();
507}
508
509void LegendaryIntegration::authenticateWithCode(const std::string& authCode,
510 const AuthCallback& callback)
511{
512 auto implCopy = impl_;
513 std::thread(
514 [implCopy, authCode, callback]()
515 {
516 std::string cmd = "legendary auth --code " + ShellUtils::escapeArg(authCode) + " 2>&1";
517 FILE* pipe = popen(cmd.c_str(), "r");
518 std::string output;
519 if (pipe)
520 {
521 char buf[256];
522 while (fgets(buf, sizeof(buf), pipe))
523 output += buf;
524 pclose(pipe);
525 }
526
527 bool success = output.find("Successfully logged in") != std::string::npos;
528
529 if (success)
530 {
531 EpicAuthStatus status;
532 FILE* statusPipe = popen("legendary status --json 2>/dev/null", "r");
533 if (statusPipe)
534 {
535 std::string statusOut;
536 char buf[256];
537 while (fgets(buf, sizeof(buf), statusPipe))
538 statusOut += buf;
539 pclose(statusPipe);
540 // Parse JSON properly to populate accountId and displayName.
541 try
542 {
543 auto j = json::parse(statusOut);
544 if (j.contains("account"))
545 {
546 status.isAuthenticated = true;
547 status.accountId = j["account"].value("id", "");
548 status.displayName = j["account"].value("name", "");
549 }
550 }
551 catch (const json::exception&)
552 {
553 status.isAuthenticated =
554 statusOut.find("\"logged_in\": true") != std::string::npos ||
555 statusOut.find("\"logged_in\":true") != std::string::npos;
556 }
557 }
558 std::lock_guard<std::mutex> lock(implCopy->mutex);
559 implCopy->authStatus = status;
560 }
561
562 if (callback)
563 {
564 callback(success, success ? "Authentication successful" : output);
565 }
566 })
567 .detach();
568}
569
571{
572 runLegendary({"auth", "--delete"});
573 impl_->authStatus = EpicAuthStatus{};
574 impl_->libraryCacheValid = false;
575 Logger::info("[Legendary] Logged out");
576}
577
578// ==============================================================================
579// Library Management
580// ==============================================================================
581
582void LegendaryIntegration::parseLibraryOutput(const std::string& output)
583{
584 impl_->libraryCache.clear();
585
586 // Parse JSON output from `legendary list --json`
587 try
588 {
589 auto j = json::parse(output);
590
591 for (const auto& item : j)
592 {
593 EpicGameInfo game;
594 game.appName = item.value("app_name", "");
595 game.appTitle = item.value("app_title", item.value("title", ""));
596 game.developer = item.value("developer", "");
597 game.publisher = item.value("publisher", "");
598 game.isDLC = item.value("is_dlc", false);
599
600 if (item.contains("asset_infos"))
601 {
602 // Parse platform info
603 for (const auto& [platform, info] : item["asset_infos"].items())
604 {
605 game.platforms.push_back(platform);
606 }
607 }
608
609 if (item.contains("metadata"))
610 {
611 auto& meta = item["metadata"];
612 if (meta.contains("keyImages"))
613 {
614 for (const auto& img : meta["keyImages"])
615 {
616 std::string type = img.value("type", "");
617 std::string url = img.value("url", "");
618 if (type == "OfferImageWide" || type == "DieselGameBox")
619 {
620 game.coverUrl = url;
621 }
622 else if (type == "Thumbnail")
623 {
624 game.thumbnailUrl = url;
625 }
626 }
627 }
628 }
629
630 impl_->libraryCache.push_back(game);
631 }
632 }
633 catch (const json::exception& e)
634 {
635 Logger::error("[Legendary] Failed to parse library JSON: {}", e.what());
636
637 // Fallback: parse text output
638 std::istringstream iss(output);
639 std::string line;
640 while (std::getline(iss, line))
641 {
642 // Parse lines like "* App Name (app_name)"
643 std::regex gameRegex(R"(\*\s+(.+?)\s+\‍(([^)]+)\))");
644 std::smatch match;
645 if (std::regex_search(line, match, gameRegex))
646 {
647 EpicGameInfo game;
648 game.appTitle = match[1].str();
649 game.appName = match[2].str();
650 impl_->libraryCache.push_back(game);
651 }
652 }
653 }
654}
655
656void LegendaryIntegration::parseInstalledOutput(const std::string& output)
657{
658 impl_->installedCache.clear();
659
660 try
661 {
662 auto j = json::parse(output);
663
664 for (const auto& item : j)
665 {
666 EpicGameInfo game;
667 game.appName = item.value("app_name", "");
668 game.appTitle = item.value("title", "");
669 game.version = item.value("version", "");
670 game.isInstalled = true;
671
672 if (item.contains("install_path"))
673 {
674 game.installPath = item["install_path"].get<std::string>();
675 }
676
677 if (item.contains("install_size"))
678 {
679 game.installSize = item["install_size"].get<int64_t>();
680 }
681
682 game.supportsCloudSaves =
683 item.contains("cloud_save_folder") && !item["cloud_save_folder"].is_null();
684
685 impl_->installedCache.push_back(game);
686 }
687 }
688 catch (const json::exception& e)
689 {
690 Logger::error("[Legendary] Failed to parse installed JSON: {}", e.what());
691 }
692}
693
694std::vector<EpicGameInfo> LegendaryIntegration::getLibrary(bool forceRefresh)
695{
696 // Check cache under lock — fast path.
697 {
698 std::lock_guard<std::mutex> lock(impl_->mutex);
699 auto now = std::chrono::system_clock::now();
700 auto age = std::chrono::duration_cast<std::chrono::seconds>(now - impl_->libraryCacheTime);
701 if (!forceRefresh && impl_->libraryCacheValid &&
703 {
704 return impl_->libraryCache;
705 }
706 }
707
708 // Run the blocking legendary command WITHOUT holding the mutex.
709 // This can take up to 60 seconds; holding the mutex that entire time
710 // would deadlock any concurrent call to setDefaultInstallPath, logout, etc.
711 Logger::info("[Legendary] Refreshing game library");
712 auto now = std::chrono::system_clock::now();
713 std::string output = runLegendary({"list", "--json"}, 60);
714
715 // Commit results under lock.
716 {
717 std::lock_guard<std::mutex> lock(impl_->mutex);
718 parseLibraryOutput(output);
719 impl_->libraryCacheTime = now;
720 impl_->libraryCacheValid = true;
721 Logger::info("[Legendary] Found {} games in library", impl_->libraryCache.size());
722 return impl_->libraryCache;
723 }
724}
725
726std::vector<EpicGameInfo> LegendaryIntegration::getInstalledGames() const
727{
728 std::string output = runLegendary({"list-installed", "--json"});
729
730 std::vector<EpicGameInfo> games;
731
732 try
733 {
734 auto j = json::parse(output);
735
736 for (const auto& item : j)
737 {
738 EpicGameInfo game;
739 game.appName = item.value("app_name", "");
740 game.appTitle = item.value("title", "");
741 game.version = item.value("version", "");
742 game.isInstalled = true;
743
744 if (item.contains("install_path"))
745 {
746 game.installPath = item["install_path"].get<std::string>();
747 }
748
749 if (item.contains("install_size"))
750 {
751 game.installSize = item["install_size"].get<int64_t>();
752 }
753
754 games.push_back(game);
755 }
756 }
757 catch (const json::exception& e)
758 {
759 Logger::error("[Legendary] Failed to parse installed list: {}", e.what());
760 }
761
762 return games;
763}
764
765std::optional<EpicGameInfo> LegendaryIntegration::getGameInfo(const std::string& appName) const
766{
767 std::string output = runLegendary({"info", appName, "--json"});
768
769 try
770 {
771 auto j = json::parse(output);
772
773 EpicGameInfo game;
774 game.appName = j["game"].value("app_name", appName);
775 game.appTitle = j["game"].value("title", "");
776 game.developer = j["game"].value("developer", "");
777 game.version = j["game"].value("version", "");
778
779 if (j.contains("install"))
780 {
781 game.isInstalled = true;
782 game.installPath = j["install"].value("install_path", "");
783 game.installSize = j["install"].value("install_size", 0);
784 }
785
786 if (j.contains("manifest"))
787 {
788 game.downloadSize = j["manifest"].value("download_size", 0);
789 }
790
791 return game;
792 }
793 catch (const json::exception& e)
794 {
795 Logger::error("[Legendary] Failed to parse game info: {}", e.what());
796 return std::nullopt;
797 }
798}
799
801{
802 Game game;
803 game.id = "epic_" + epicGame.appName;
804 game.name = epicGame.appTitle;
806 game.runner = GameRunner::Wine; // Epic games need Wine/Proton
807
808 if (epicGame.isInstalled)
809 {
810 game.installPath = epicGame.installPath.string();
811 }
812
813 // Set executable path to actual install path, with app name for launch resolution
814 if (epicGame.isInstalled && !epicGame.installPath.empty())
815 {
816 game.runnerConfig.executablePath = epicGame.installPath.string();
817 }
818 else
819 {
820 game.runnerConfig.executablePath = "legendary launch " + epicGame.appName;
821 }
822
823 // Set cover art if available
824 if (!epicGame.coverUrl.empty())
825 {
827 }
828
829 return game;
830}
831
833{
834 auto games = getLibrary(true);
835 Logger::info("[Legendary] Synced {} games from Epic library", games.size());
836 return static_cast<int>(games.size());
837}
838
839// ==============================================================================
840// Installation
841// ==============================================================================
842
843bool LegendaryIntegration::installGame(const std::string& appName, const fs::path& installPath,
844 const ProgressCallback& progressCallback)
845{
846 Logger::info("[Legendary] Installing game: {}", appName);
847
848 impl_->cancelFlag.store(false);
849
850 std::vector<std::string> args = {"install", appName};
851
852 if (!installPath.empty())
853 {
854 args.push_back("--base-path");
855 args.push_back(installPath.string());
856 }
857
858 args.push_back("-y"); // Auto-confirm
859
860 if (progressCallback)
861 {
862 LegendaryProgress progress;
864 progressCallback(progress);
865 }
866
867 bool success = runLegendaryInteractive(args, progressCallback, impl_->cancelFlag);
868
869 if (progressCallback)
870 {
871 LegendaryProgress progress;
872 progress.state =
874 progress.percentComplete = success ? 100 : 0;
875 progressCallback(progress);
876 }
877
878 return success;
879}
880
881std::future<bool> LegendaryIntegration::installGameAsync(const std::string& appName,
882 const fs::path& installPath,
883 const ProgressCallback& progressCallback)
884{
885 // Hand the caller a future backed by a promise, and keep the worker's own
886 // future internally so ~LegendaryIntegration can join it (the lambda
887 // captures `this`). Without this, destroying the integration mid-install
888 // is a use-after-free (BUG-4).
889 auto prom = std::make_shared<std::promise<bool>>();
890 std::future<bool> caller = prom->get_future();
891
892 std::lock_guard<std::mutex> lock(impl_->futuresMutex);
893 impl_->activeInstalls.erase(
894 std::remove_if(impl_->activeInstalls.begin(), impl_->activeInstalls.end(),
895 [](const std::future<void>& f)
896 {
897 return !f.valid() ||
898 f.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
899 }),
900 impl_->activeInstalls.end());
901 impl_->activeInstalls.push_back(
902 std::async(std::launch::async,
903 [this, appName, installPath, progressCallback, prom]()
904 {
905 try
906 {
907 prom->set_value(installGame(appName, installPath, progressCallback));
908 }
909 catch (...)
910 {
911 try
912 {
913 prom->set_exception(std::current_exception());
914 }
915 catch (...)
916 {
917 // set_exception can throw if the promise is already
918 // satisfied; nothing more we can do.
919 }
920 }
921 }));
922 return caller;
923}
924
925bool LegendaryIntegration::updateGame(const std::string& appName,
926 const ProgressCallback& progressCallback)
927{
928 Logger::info("[Legendary] Updating game: {}", appName);
929
930 impl_->cancelFlag.store(false);
931
932 std::vector<std::string> args = {"update", appName, "-y"};
933
934 return runLegendaryInteractive(args, progressCallback, impl_->cancelFlag);
935}
936
937bool LegendaryIntegration::uninstallGame(const std::string& appName, bool keepFiles)
938{
939 Logger::info("[Legendary] Uninstalling game: {}", appName);
940
941 std::vector<std::string> args = {"uninstall", appName, "-y"};
942 if (keepFiles)
943 {
944 args.push_back("--keep-files");
945 }
946
947 std::string output = runLegendary(args);
948 return output.find("Uninstalled") != std::string::npos ||
949 output.find("Game has been removed") != std::string::npos;
950}
951
952bool LegendaryIntegration::verifyGame(const std::string& appName,
953 const ProgressCallback& progressCallback)
954{
955 Logger::info("[Legendary] Verifying game: {}", appName);
956
957 impl_->cancelFlag.store(false);
958
959 std::vector<std::string> args = {"verify", appName};
960
961 return runLegendaryInteractive(args, progressCallback, impl_->cancelFlag);
962}
963
964bool LegendaryIntegration::repairGame(const std::string& appName,
965 const ProgressCallback& progressCallback)
966{
967 Logger::info("[Legendary] Repairing game: {}", appName);
968
969 impl_->cancelFlag.store(false);
970
971 std::vector<std::string> args = {"repair", appName, "-y"};
972
973 return runLegendaryInteractive(args, progressCallback, impl_->cancelFlag);
974}
975
976bool LegendaryIntegration::moveGame(const std::string& appName, const fs::path& newPath,
977 const ProgressCallback& progressCallback)
978{
979 Logger::info("[Legendary] Moving game {} to {}", appName, newPath.string());
980
981 impl_->cancelFlag.store(false);
982
983 std::vector<std::string> args = {"move", appName, newPath.string()};
984
985 return runLegendaryInteractive(args, progressCallback, impl_->cancelFlag);
986}
987
988bool LegendaryIntegration::importGame(const std::string& appName, const fs::path& existingPath)
989{
990 Logger::info("[Legendary] Importing game {} from {}", appName, existingPath.string());
991
992 std::vector<std::string> args = {"import", appName, existingPath.string()};
993
994 std::string output = runLegendary(args);
995 return output.find("Successfully imported") != std::string::npos;
996}
997
998// ==============================================================================
999// DLC Management
1000// ==============================================================================
1001
1002std::vector<EpicGameInfo> LegendaryIntegration::getAvailableDLC(const std::string& appName)
1003{
1004 std::vector<EpicGameInfo> dlcs;
1005
1006 auto library = getLibrary();
1007 for (const auto& game : library)
1008 {
1009 if (game.isDLC && game.baseGameAppName == appName)
1010 {
1011 dlcs.push_back(game);
1012 }
1013 }
1014
1015 return dlcs;
1016}
1017
1018bool LegendaryIntegration::installDLC(const std::string& dlcAppName,
1019 const ProgressCallback& progressCallback)
1020{
1021 return installGame(dlcAppName, {}, progressCallback);
1022}
1023
1024// ==============================================================================
1025// Cloud Saves
1026// ==============================================================================
1027
1029{
1030 EpicCloudSaveInfo info;
1031 info.appName = appName;
1032
1033 // Probe legendary for save state. The textual output is intentionally
1034 // discarded here - the call is what we want (forces a sync-saves
1035 // status refresh without uploading/downloading); the parsed result is
1036 // a future enhancement (see TODO below). Cast to void to silence
1037 // bugprone-unused-local-non-trivial-variable.
1038 (void)runLegendary({"sync-saves", appName, "--skip-upload", "--skip-download"});
1039
1040 // TODO: parse stdout for cloud-save metadata (timestamps, sync state).
1041
1042 return info;
1043}
1044
1045bool LegendaryIntegration::downloadCloudSaves(const std::string& appName, bool force)
1046{
1047 Logger::info("[Legendary] Downloading cloud saves for: {}", appName);
1048
1049 std::vector<std::string> args = {"sync-saves", appName, "--skip-upload"};
1050 if (force)
1051 {
1052 args.push_back("--force-download");
1053 }
1054
1055 std::string output = runLegendary(args);
1056 return output.find("Successfully") != std::string::npos ||
1057 output.find("No cloud saves") != std::string::npos;
1058}
1059
1060bool LegendaryIntegration::uploadCloudSaves(const std::string& appName, bool force)
1061{
1062 Logger::info("[Legendary] Uploading cloud saves for: {}", appName);
1063
1064 std::vector<std::string> args = {"sync-saves", appName, "--skip-download"};
1065 if (force)
1066 {
1067 args.push_back("--force-upload");
1068 }
1069
1070 std::string output = runLegendary(args);
1071 return output.find("Successfully") != std::string::npos;
1072}
1073
1074bool LegendaryIntegration::syncCloudSaves(const std::string& appName)
1075{
1076 Logger::info("[Legendary] Syncing cloud saves for: {}", appName);
1077
1078 std::string output = runLegendary({"sync-saves", appName});
1079 return output.find("Successfully") != std::string::npos ||
1080 output.find("No cloud saves") != std::string::npos;
1081}
1082
1083// ==============================================================================
1084// Launch
1085// ==============================================================================
1086
1087bool LegendaryIntegration::launchGame(const std::string& appName,
1088 const std::vector<std::string>& additionalArgs, bool offline,
1089 pid_t* outPid)
1090{
1091 Logger::info("[Legendary] Launching game: {}", appName);
1092
1093 const std::string legendaryPath = getLegendaryPath().string();
1094 if (legendaryPath.empty() || !std::filesystem::exists(legendaryPath))
1095 {
1096 Logger::error("[Legendary] legendary binary not found");
1097 return false;
1098 }
1099
1100 std::vector<std::string> args = {legendaryPath, "launch", appName};
1101 if (offline)
1102 {
1103 args.push_back("--offline");
1104 }
1105 for (const auto& arg : additionalArgs)
1106 {
1107 args.push_back(arg);
1108 }
1109
1110 // Build a null-terminated argv for execvp. The strings must outlive the
1111 // execvp call; they're owned by `args` above which stays alive until
1112 // this function returns in the parent, and execvp replaces the address
1113 // space in the child so it doesn't matter there.
1114 std::vector<char*> argv;
1115 argv.reserve(args.size() + 1);
1116 for (auto& a : args)
1117 {
1118 argv.push_back(const_cast<char*>(a.c_str()));
1119 }
1120 argv.push_back(nullptr);
1121
1122 pid_t pid = fork();
1123 if (pid < 0)
1124 {
1125 Logger::error("[Legendary] fork() failed for {}: {}", appName, std::strerror(errno));
1126 return false;
1127 }
1128
1129 if (pid == 0)
1130 {
1131 // Child: redirect stdout/stderr so legendary's output doesn't
1132 // interleave with ours, then exec. Only async-signal-safe code here.
1133 const int devnull = ::open("/dev/null", O_WRONLY);
1134 if (devnull >= 0)
1135 {
1136 ::dup2(devnull, STDOUT_FILENO);
1137 ::dup2(devnull, STDERR_FILENO);
1138 if (devnull > STDERR_FILENO)
1139 ::close(devnull);
1140 }
1141 execvp(argv[0], argv.data());
1142 // execvp only returns on error
1143 _exit(127);
1144 }
1145
1146 // Parent: hand the PID back to the caller (if they want it) and return.
1147 // legendary itself stays attached to the game until the game exits, so
1148 // the caller can waitpid(pid, ..., 0) if they want blocking semantics, or
1149 // poll with WNOHANG for a non-blocking status check.
1150 Logger::info("[Legendary] Spawned legendary pid={} for {}", pid, appName);
1151 if (outPid)
1152 *outPid = pid;
1153 return true;
1154}
1155
1156std::string LegendaryIntegration::getLaunchCommand(const std::string& appName,
1157 const std::vector<std::string>& additionalArgs,
1158 bool offline) const
1159{
1160 std::string cmd = "legendary launch \"" + shellEscape(appName) + "\"";
1161
1162 if (offline)
1163 {
1164 cmd += " --offline";
1165 }
1166
1167 for (const auto& arg : additionalArgs)
1168 {
1169 cmd += " \"" + shellEscape(arg) + "\"";
1170 }
1171
1172 return cmd;
1173}
1174
1175// ==============================================================================
1176// Configuration
1177// ==============================================================================
1178
1180{
1181 std::lock_guard<std::mutex> lock(impl_->mutex);
1182 impl_->defaultInstallPath = path;
1183}
1184
1186{
1187 std::lock_guard<std::mutex> lock(impl_->mutex);
1188 return impl_->defaultInstallPath;
1189}
1190
1192{
1193 std::lock_guard<std::mutex> lock(impl_->mutex);
1194 impl_->maxWorkers = workers;
1195}
1196
1198{
1199 std::lock_guard<std::mutex> lock(impl_->mutex);
1200 impl_->autoSyncSaves = enabled;
1201}
1202
1204{
1205 impl_->cancelFlag.store(true);
1206}
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
std::vector< EpicGameInfo > getInstalledGames() const
Get all installed games.
bool syncCloudSaves(const std::string &appName)
Sync saves (download if newer, upload if local is newer).
std::filesystem::path getDefaultInstallPath() const
Get default installation directory.
std::vector< EpicGameInfo > getLibrary(bool forceRefresh=false)
Get all games in Epic library.
bool installGame(const std::string &appName, const std::filesystem::path &installPath={}, const ProgressCallback &progressCallback=nullptr)
Install a game.
bool moveGame(const std::string &appName, const std::filesystem::path &newPath, const ProgressCallback &progressCallback=nullptr)
Move game to different location.
void authenticate(const AuthCallback &callback=nullptr)
Start authentication flow.
std::optional< EpicGameInfo > getGameInfo(const std::string &appName) const
Get info for a specific game.
std::function< void(bool success, const std::string &message)> AuthCallback
std::vector< EpicGameInfo > getAvailableDLC(const std::string &appName)
Get available DLC for a game.
static bool isAvailable()
Check if Legendary CLI is installed.
void cancelOperation()
Cancel ongoing operation.
bool launchGame(const std::string &appName, const std::vector< std::string > &additionalArgs={}, bool offline=false, pid_t *outPid=nullptr)
Launch a game.
std::future< bool > installGameAsync(const std::string &appName, const std::filesystem::path &installPath={}, const ProgressCallback &progressCallback=nullptr)
Install a game asynchronously.
bool installDLC(const std::string &dlcAppName, const ProgressCallback &progressCallback=nullptr)
Install DLC for a game.
bool uploadCloudSaves(const std::string &appName, bool force=false)
Upload local saves to cloud.
EpicAuthStatus getAuthStatus() const
Check authentication status.
void setAutoSyncSaves(bool enabled)
Enable/disable automatic cloud save sync.
EpicCloudSaveInfo getCloudSaveStatus(const std::string &appName) const
Get cloud save status for a game.
bool repairGame(const std::string &appName, const ProgressCallback &progressCallback=nullptr)
Repair game (verify and redownload corrupt files).
bool updateGame(const std::string &appName, const ProgressCallback &progressCallback=nullptr)
Update a game.
bool importGame(const std::string &appName, const std::filesystem::path &existingPath)
Import an existing game installation.
bool uninstallGame(const std::string &appName, bool keepFiles=false)
Uninstall a game.
std::function< void(const LegendaryProgress &)> ProgressCallback
std::string getLaunchCommand(const std::string &appName, const std::vector< std::string > &additionalArgs={}, bool offline=false) const
Get launch command for a game.
void setDefaultInstallPath(const std::filesystem::path &path)
Set default installation directory.
bool downloadCloudSaves(const std::string &appName, bool force=false)
Download cloud saves for a game.
static std::string getVersion()
Get Legendary version.
bool isAuthenticated() const
Check if user is authenticated.
bool verifyGame(const std::string &appName, const ProgressCallback &progressCallback=nullptr)
Verify game files.
Game toGame(const EpicGameInfo &epicGame) const
Convert Epic game to generic Game object.
static std::filesystem::path getLegendaryPath()
Get path to Legendary executable.
int syncLibrary()
Sync Epic library with game database.
void logout()
Log out and clear credentials.
void authenticateWithCode(const std::string &authCode, const AuthCallback &callback=nullptr)
Start authentication with authorization code.
void setMaxWorkers(int workers)
Set maximum download workers.
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
@ Epic
Epic Games Store.
Definition game.h:43
@ Wine
Wine compatibility layer.
Definition game.h:83
nlohmann::json json
std::string shellEscape(const std::string &arg)
Epic Games authentication status.
std::chrono::system_clock::time_point tokenExpiry
Information about cloud saves for an Epic game.
Information about an Epic Games Store game.
std::string appName
Internal app identifier.
std::string publisher
Publisher name.
std::string developer
Developer name.
int64_t installSize
Installed size in bytes.
std::string appTitle
Display title.
std::string getFormattedDownloadSize() const
std::string baseGameAppName
Parent game if this is DLC.
std::string thumbnailUrl
Thumbnail URL.
std::vector< std::string > platforms
Available platforms (Windows, Mac).
std::string coverUrl
Cover image URL.
std::string getFormattedInstallSize() const
std::filesystem::path installPath
std::string version
Installed/available version.
int64_t downloadSize
Download size in bytes.
std::string verticalCover
Vertical cover art (library_600x900.jpg).
Definition game.h:497
GameImagePaths imagePaths
Paths to all available image assets.
Definition game.h:562
std::string executablePath
Full path to game executable.
Definition game.h:141
std::vector< EpicGameInfo > libraryCache
static constexpr int LIBRARY_CACHE_VALIDITY_SEC
std::vector< std::future< void > > activeInstalls
std::vector< EpicGameInfo > installedCache
std::chrono::system_clock::time_point libraryCacheTime
Progress information for Legendary operations.
std::string getStateStr() const