24#include <nlohmann/json.hpp>
33using json = nlohmann::json;
34namespace fs = std::filesystem;
42 escaped.reserve(arg.size() + 10);
48 if (c ==
'"' || c ==
'\\' || c ==
'$' || c ==
'`' || c ==
'\n' || c ==
'\r')
69 return std::to_string(
installSize / (1024 * 1024)) +
" MB";
70 return std::to_string(
installSize / (1024LL * 1024 * 1024)) +
" GB";
80 return std::to_string(
downloadSize / (1024 * 1024)) +
" MB";
81 return std::to_string(
downloadSize / (1024LL * 1024 * 1024)) +
" GB";
88 return std::chrono::system_clock::now() >
tokenExpiry;
149 const char* home = std::getenv(
"HOME");
175 impl_->cancelFlag.store(
true);
176 std::vector<std::future<void>> pending;
178 std::lock_guard<std::mutex> lock(impl_->futuresMutex);
179 pending = std::move(impl_->activeInstalls);
181 for (
auto& f : pending)
205 FILE* pipe = popen(
"legendary --version 2>&1",
"r");
211 std::array<char, 256> buffer;
213 while (fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe) !=
nullptr)
215 result += buffer.data();
220 std::regex versionRegex(R
"(version\s+(\S+))");
222 if (std::regex_search(result, match, versionRegex))
224 return match[1].str();
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"};
237 for (
const auto& path : paths)
239 if (fs::exists(path))
246 FILE* pipe = popen(
"which legendary 2>/dev/null",
"r");
249 std::array<char, 256> buffer;
251 if (fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe) !=
nullptr)
253 result = buffer.data();
255 if (!result.empty() && result.back() ==
'\n')
262 if (!result.empty() && fs::exists(result))
275std::string LegendaryIntegration::runLegendary(
const std::vector<std::string>& args,
276 int timeoutSec)
const
278 std::string cmd =
"legendary";
279 for (
const auto& arg : args)
281 cmd +=
" \"" + shellEscape(arg) +
"\"";
288 cmd =
"timeout " + std::to_string(timeoutSec) +
" " + cmd;
291 FILE* pipe = popen(cmd.c_str(),
"r");
298 std::array<char, 4096> buffer;
300 constexpr size_t kMaxOutput = 16u * 1024 * 1024;
301 while (fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe) !=
nullptr)
303 result += buffer.data();
304 if (result.size() > kMaxOutput)
308 int status = pclose(pipe);
313 else if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
315 Logger::debug(
"[Legendary] Command exited with code {}", WEXITSTATUS(status));
317 else if (WIFSIGNALED(status))
319 Logger::debug(
"[Legendary] Command killed by signal {}", WTERMSIG(status));
325bool LegendaryIntegration::runLegendaryInteractive(
const std::vector<std::string>& args,
326 const ProgressCallback& callback,
327 std::atomic<bool>& cancelled)
329 std::string cmd =
"legendary";
330 for (
const auto& arg : args)
336 FILE* pipe = popen(cmd.c_str(),
"r");
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)");
347 while (fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe) !=
nullptr)
349 if (cancelled.load())
355 std::string line = buffer.data();
359 LegendaryProgress progress;
364 if (std::regex_search(line, match, progressRegex))
368 progress.
percentComplete =
static_cast<int>(std::stof(match[1].str()));
376 if (std::regex_search(line, match, speedRegex))
392 int status = pclose(pipe);
394 return WIFEXITED(status) && WEXITSTATUS(status) == 0;
405 std::string output = runLegendary({
"status",
"--json"});
409 auto j = json::parse(output);
411 if (j.contains(
"account"))
414 status.
accountId = j[
"account"].value(
"id",
"");
415 status.
displayName = j[
"account"].value(
"name",
"");
418 catch (
const json::exception& e)
421 if (output.find(
"Logged in as") != std::string::npos)
425 std::regex nameRegex(R
"(Logged in as: (.+))");
427 if (std::regex_search(output, match, nameRegex))
446 auto implCopy = impl_;
448 [implCopy, callback]()
453 FILE* pipe = popen(
"legendary auth 2>&1",
"r");
458 while (fgets(buf,
sizeof(buf), pipe))
463 bool success = output.find(
"Successfully logged in") != std::string::npos ||
464 output.find(
"Logged in as") != std::string::npos;
470 FILE* statusPipe = popen(
"legendary status --json 2>/dev/null",
"r");
473 std::string statusOut;
475 while (fgets(buf,
sizeof(buf), statusPipe))
482 auto j = json::parse(statusOut);
483 if (j.contains(
"account"))
486 status.
accountId = j[
"account"].value(
"id",
"");
487 status.
displayName = j[
"account"].value(
"name",
"");
490 catch (
const json::exception&)
493 statusOut.find(
"\"logged_in\": true") != std::string::npos ||
494 statusOut.find(
"\"logged_in\":true") != std::string::npos;
497 std::lock_guard<std::mutex> lock(implCopy->mutex);
498 implCopy->authStatus = status;
503 callback(success, success ?
"Authentication successful" : output);
512 auto implCopy = impl_;
514 [implCopy, authCode, callback]()
517 FILE* pipe = popen(cmd.c_str(),
"r");
522 while (fgets(buf,
sizeof(buf), pipe))
527 bool success = output.find(
"Successfully logged in") != std::string::npos;
532 FILE* statusPipe = popen(
"legendary status --json 2>/dev/null",
"r");
535 std::string statusOut;
537 while (fgets(buf,
sizeof(buf), statusPipe))
543 auto j = json::parse(statusOut);
544 if (j.contains(
"account"))
547 status.
accountId = j[
"account"].value(
"id",
"");
548 status.
displayName = j[
"account"].value(
"name",
"");
551 catch (
const json::exception&)
554 statusOut.find(
"\"logged_in\": true") != std::string::npos ||
555 statusOut.find(
"\"logged_in\":true") != std::string::npos;
558 std::lock_guard<std::mutex> lock(implCopy->mutex);
559 implCopy->authStatus = status;
564 callback(success, success ?
"Authentication successful" : output);
572 runLegendary({
"auth",
"--delete"});
574 impl_->libraryCacheValid =
false;
582void LegendaryIntegration::parseLibraryOutput(
const std::string& output)
584 impl_->libraryCache.clear();
589 auto j = json::parse(output);
591 for (
const auto& item : j)
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);
600 if (item.contains(
"asset_infos"))
603 for (
const auto& [
platform, info] : item[
"asset_infos"].items())
609 if (item.contains(
"metadata"))
611 auto& meta = item[
"metadata"];
612 if (meta.contains(
"keyImages"))
614 for (
const auto& img : meta[
"keyImages"])
616 std::string type = img.value(
"type",
"");
617 std::string url = img.value(
"url",
"");
618 if (type ==
"OfferImageWide" || type ==
"DieselGameBox")
622 else if (type ==
"Thumbnail")
630 impl_->libraryCache.push_back(game);
633 catch (
const json::exception& e)
635 Logger::error(
"[Legendary] Failed to parse library JSON: {}", e.what());
638 std::istringstream iss(output);
640 while (std::getline(iss, line))
643 std::regex gameRegex(R
"(\*\s+(.+?)\s+\(([^)]+)\))");
645 if (std::regex_search(line, match, gameRegex))
650 impl_->libraryCache.push_back(game);
656void LegendaryIntegration::parseInstalledOutput(
const std::string& output)
658 impl_->installedCache.clear();
662 auto j = json::parse(output);
664 for (
const auto& item : j)
667 game.
appName = item.value(
"app_name",
"");
668 game.
appTitle = item.value(
"title",
"");
669 game.
version = item.value(
"version",
"");
672 if (item.contains(
"install_path"))
674 game.
installPath = item[
"install_path"].get<std::string>();
677 if (item.contains(
"install_size"))
679 game.
installSize = item[
"install_size"].get<int64_t>();
683 item.contains(
"cloud_save_folder") && !item[
"cloud_save_folder"].is_null();
685 impl_->installedCache.push_back(game);
688 catch (
const json::exception& e)
690 Logger::error(
"[Legendary] Failed to parse installed JSON: {}", e.what());
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 &&
704 return impl_->libraryCache;
712 auto now = std::chrono::system_clock::now();
713 std::string output = runLegendary({
"list",
"--json"}, 60);
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;
728 std::string output = runLegendary({
"list-installed",
"--json"});
730 std::vector<EpicGameInfo> games;
734 auto j = json::parse(output);
736 for (
const auto& item : j)
739 game.
appName = item.value(
"app_name",
"");
740 game.
appTitle = item.value(
"title",
"");
741 game.
version = item.value(
"version",
"");
744 if (item.contains(
"install_path"))
746 game.
installPath = item[
"install_path"].get<std::string>();
749 if (item.contains(
"install_size"))
751 game.
installSize = item[
"install_size"].get<int64_t>();
754 games.push_back(game);
757 catch (
const json::exception& e)
759 Logger::error(
"[Legendary] Failed to parse installed list: {}", e.what());
767 std::string output = runLegendary({
"info", appName,
"--json"});
771 auto j = json::parse(output);
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",
"");
779 if (j.contains(
"install"))
782 game.
installPath = j[
"install"].value(
"install_path",
"");
783 game.
installSize = j[
"install"].value(
"install_size", 0);
786 if (j.contains(
"manifest"))
788 game.
downloadSize = j[
"manifest"].value(
"download_size", 0);
793 catch (
const json::exception& e)
795 Logger::error(
"[Legendary] Failed to parse game info: {}", e.what());
835 Logger::info(
"[Legendary] Synced {} games from Epic library", games.size());
836 return static_cast<int>(games.size());
846 Logger::info(
"[Legendary] Installing game: {}", appName);
848 impl_->cancelFlag.store(
false);
850 std::vector<std::string> args = {
"install", appName};
852 if (!installPath.empty())
854 args.push_back(
"--base-path");
855 args.push_back(installPath.string());
858 args.push_back(
"-y");
860 if (progressCallback)
864 progressCallback(progress);
867 bool success = runLegendaryInteractive(args, progressCallback, impl_->cancelFlag);
869 if (progressCallback)
875 progressCallback(progress);
882 const fs::path& installPath,
889 auto prom = std::make_shared<std::promise<bool>>();
890 std::future<bool> caller = prom->get_future();
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)
898 f.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
900 impl_->activeInstalls.end());
901 impl_->activeInstalls.push_back(
902 std::async(std::launch::async,
903 [
this, appName, installPath, progressCallback, prom]()
907 prom->set_value(
installGame(appName, installPath, progressCallback));
913 prom->set_exception(std::current_exception());
930 impl_->cancelFlag.store(
false);
932 std::vector<std::string> args = {
"update", appName,
"-y"};
934 return runLegendaryInteractive(args, progressCallback, impl_->cancelFlag);
939 Logger::info(
"[Legendary] Uninstalling game: {}", appName);
941 std::vector<std::string> args = {
"uninstall", appName,
"-y"};
944 args.push_back(
"--keep-files");
947 std::string output = runLegendary(args);
948 return output.find(
"Uninstalled") != std::string::npos ||
949 output.find(
"Game has been removed") != std::string::npos;
955 Logger::info(
"[Legendary] Verifying game: {}", appName);
957 impl_->cancelFlag.store(
false);
959 std::vector<std::string> args = {
"verify", appName};
961 return runLegendaryInteractive(args, progressCallback, impl_->cancelFlag);
967 Logger::info(
"[Legendary] Repairing game: {}", appName);
969 impl_->cancelFlag.store(
false);
971 std::vector<std::string> args = {
"repair", appName,
"-y"};
973 return runLegendaryInteractive(args, progressCallback, impl_->cancelFlag);
979 Logger::info(
"[Legendary] Moving game {} to {}", appName, newPath.string());
981 impl_->cancelFlag.store(
false);
983 std::vector<std::string> args = {
"move", appName, newPath.string()};
985 return runLegendaryInteractive(args, progressCallback, impl_->cancelFlag);
990 Logger::info(
"[Legendary] Importing game {} from {}", appName, existingPath.string());
992 std::vector<std::string> args = {
"import", appName, existingPath.string()};
994 std::string output = runLegendary(args);
995 return output.find(
"Successfully imported") != std::string::npos;
1004 std::vector<EpicGameInfo> dlcs;
1007 for (
const auto& game : library)
1011 dlcs.push_back(game);
1021 return installGame(dlcAppName, {}, progressCallback);
1038 (void)runLegendary({
"sync-saves", appName,
"--skip-upload",
"--skip-download"});
1047 Logger::info(
"[Legendary] Downloading cloud saves for: {}", appName);
1049 std::vector<std::string> args = {
"sync-saves", appName,
"--skip-upload"};
1052 args.push_back(
"--force-download");
1055 std::string output = runLegendary(args);
1056 return output.find(
"Successfully") != std::string::npos ||
1057 output.find(
"No cloud saves") != std::string::npos;
1062 Logger::info(
"[Legendary] Uploading cloud saves for: {}", appName);
1064 std::vector<std::string> args = {
"sync-saves", appName,
"--skip-download"};
1067 args.push_back(
"--force-upload");
1070 std::string output = runLegendary(args);
1071 return output.find(
"Successfully") != std::string::npos;
1076 Logger::info(
"[Legendary] Syncing cloud saves for: {}", appName);
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;
1088 const std::vector<std::string>& additionalArgs,
bool offline,
1091 Logger::info(
"[Legendary] Launching game: {}", appName);
1094 if (legendaryPath.empty() || !std::filesystem::exists(legendaryPath))
1100 std::vector<std::string> args = {legendaryPath,
"launch", appName};
1103 args.push_back(
"--offline");
1105 for (
const auto& arg : additionalArgs)
1107 args.push_back(arg);
1114 std::vector<char*> argv;
1115 argv.reserve(args.size() + 1);
1116 for (
auto& a : args)
1118 argv.push_back(
const_cast<char*
>(a.c_str()));
1120 argv.push_back(
nullptr);
1125 Logger::error(
"[Legendary] fork() failed for {}: {}", appName, std::strerror(errno));
1133 const int devnull = ::open(
"/dev/null", O_WRONLY);
1136 ::dup2(devnull, STDOUT_FILENO);
1137 ::dup2(devnull, STDERR_FILENO);
1138 if (devnull > STDERR_FILENO)
1141 execvp(argv[0], argv.data());
1150 Logger::info(
"[Legendary] Spawned legendary pid={} for {}", pid, appName);
1157 const std::vector<std::string>& additionalArgs,
1160 std::string cmd =
"legendary launch \"" + shellEscape(appName) +
"\"";
1164 cmd +=
" --offline";
1167 for (
const auto& arg : additionalArgs)
1169 cmd +=
" \"" + shellEscape(arg) +
"\"";
1181 std::lock_guard<std::mutex> lock(impl_->mutex);
1182 impl_->defaultInstallPath = path;
1187 std::lock_guard<std::mutex> lock(impl_->mutex);
1188 return impl_->defaultInstallPath;
1193 std::lock_guard<std::mutex> lock(impl_->mutex);
1194 impl_->maxWorkers = workers;
1199 std::lock_guard<std::mutex> lock(impl_->mutex);
1200 impl_->autoSyncSaves = enabled;
1205 impl_->cancelFlag.store(
true);
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.).
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).
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.
@ Wine
Wine compatibility layer.
std::string shellEscape(const std::string &arg)
Epic Games authentication status.
bool isTokenExpired() const
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).
std::string executablePath
Full path to game executable.
fs::path defaultInstallPath
std::atomic< bool > cancelFlag
std::vector< EpicGameInfo > libraryCache
EpicAuthStatus authStatus
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