game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
lutris_api_service.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// lutris_api_service.cpp
4// ==============================================================================
5// Lutris API client implementation
6// ==============================================================================
7
9#include "logger.h"
10#include "shell_utils.h"
11
12#include <array>
13#include <cctype>
14#include <cstdio>
15#include <future>
16#include <limits>
17#include <memory>
18#include <mutex>
19#include <regex>
20#include <sstream>
21#include <sys/wait.h>
22#include <vector>
23
24namespace
25{
26// Tracks async futures so they are not abandoned (detached threads are avoided).
27// Completed futures are pruned on each new async request.
28std::mutex g_futuresMutex;
29std::vector<std::shared_ptr<std::future<void>>> g_activeFutures;
30
31void storeFuture(std::shared_ptr<std::future<void>> f)
32{
33 std::lock_guard<std::mutex> lock(g_futuresMutex);
34 // Prune completed futures
35 g_activeFutures.erase(std::remove_if(g_activeFutures.begin(), g_activeFutures.end(),
36 [](const std::shared_ptr<std::future<void>>& fut)
37 {
38 return fut && fut->wait_for(std::chrono::seconds(0)) ==
39 std::future_status::ready;
40 }),
41 g_activeFutures.end());
42 g_activeFutures.push_back(std::move(f));
43}
44} // namespace
45
46namespace
47{
48
49// Hot-path regexes wrapped in function-local statics. parseInstallerScript
50// is called once per Lutris install attempt; rebuilding ~3 std::regex
51// objects per call dominates parse cost on installers with many `tasks:`
52// entries. The function-local-static form initializes on first use
53// (Meyer's singleton, thread-safe per [stmt.dcl]/4) so any malformed-
54// pattern std::regex_error propagates from the caller instead of an
55// uncatchable program-start crash (bugprone-throwing-static-initialization,
56// CERT ERR58-CPP). std::regex const-method calls are documented thread-
57// safe. Custom raw-string delimiter `RX(...)RX` avoids the )" sequence
58// inside the regex prematurely terminating the default `R"(...)"` form.
59const std::regex& kKvWildValueRegex()
60{
61 static const std::regex re{R"RX("([^"]+)"\s*:\s*("[^"]*"|[^,}\s]+))RX"};
62 return re;
63}
64const std::regex& kKvStringValueRegex()
65{
66 static const std::regex re{R"RX("([^"]+)"\s*:\s*"([^"]*)")RX"};
67 return re;
68}
69
70// Percent-encodes a string for use as a URL path segment or query value.
71std::string urlEncodeComponent(const std::string& s)
72{
73 std::string out;
74 out.reserve(s.size());
75 for (char raw : s)
76 {
77 auto c = static_cast<unsigned char>(raw);
78 if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')
79 out += static_cast<char>(c);
80 else
81 {
82 char hex[4];
83 std::snprintf(hex, sizeof(hex), "%%%02X", c);
84 out += hex;
85 }
86 }
87 return out;
88}
89} // namespace
90
91// ==============================================================================
92// Static Members
93// ==============================================================================
94// API_BASE is a `static constexpr const char*` declared in the header
95// (no out-of-line definition needed in C++17).
96std::map<std::string, LutrisAPIService::CacheEntry<std::vector<LutrisSearchResult>>>
97 LutrisAPIService::searchCache_;
98std::map<std::string, LutrisAPIService::CacheEntry<LutrisInstallerScript>>
99 LutrisAPIService::scriptCache_;
100std::mutex LutrisAPIService::cacheMutex_;
101
102// ==============================================================================
103// LutrisInstallerScript Methods
104// ==============================================================================
105
107{
108 uint64_t total = 0;
109 for (const auto& file : files)
110 {
111 if (!file.isManual)
112 {
113 total += file.size;
114 }
115 }
116 return total;
117}
118
120{
121 for (const auto& file : files)
122 {
123 if (file.isManual)
124 {
125 return true;
126 }
127 }
128 return false;
129}
130
131// ==============================================================================
132// Search Methods
133// ==============================================================================
134
135std::vector<LutrisSearchResult> LutrisAPIService::searchGames(const std::string& query,
136 int maxResults)
137{
138 // Check cache with TTL
139 {
140 std::lock_guard<std::mutex> lock(cacheMutex_);
141 auto it = searchCache_.find(query);
142 if (it != searchCache_.end() && !it->second.isExpired(SEARCH_CACHE_TTL))
143 {
144 Logger::debug("LutrisAPI: Returning cached search for '{}'", query);
145 return it->second.data;
146 }
147 // Remove expired entry if present
148 if (it != searchCache_.end())
149 {
150 Logger::debug("LutrisAPI: Cache expired for '{}'", query);
151 searchCache_.erase(it);
152 }
153 }
154
155 // URL encode query
156 std::string encodedQuery;
157 for (char c : query)
158 {
159 if (std::isalnum(static_cast<unsigned char>(c)) || c == '-' || c == '_' || c == '.')
160 {
161 encodedQuery += c;
162 }
163 else if (c == ' ')
164 {
165 encodedQuery += '+';
166 }
167 else
168 {
169 char hex[4];
170 std::snprintf(hex, sizeof(hex), "%%%02X", static_cast<unsigned char>(c));
171 encodedQuery += hex;
172 }
173 }
174
175 std::string url = std::string(API_BASE) + "/games?search=" + encodedQuery;
176 Logger::info("LutrisAPI: Searching for '{}'", query);
177
178 std::string response = httpGet(url);
179 if (response.empty())
180 {
181 Logger::error("LutrisAPI: Empty response from search");
182 return {};
183 }
184
185 auto results = parseSearchResults(response);
186
187 // Limit results
188 if (static_cast<int>(results.size()) > maxResults)
189 {
190 results.resize(static_cast<size_t>(maxResults));
191 }
192
193 // Cache results with timestamp
194 {
195 std::lock_guard<std::mutex> lock(cacheMutex_);
196 searchCache_[query] = {results, std::chrono::steady_clock::now()};
197 }
198
199 Logger::info("LutrisAPI: Found {} games for '{}'", results.size(), query);
200 return results;
201}
202
204 const std::string& query,
205 const std::function<void(const std::vector<LutrisSearchResult>&)>& callback, int maxResults)
206{
207 auto future = std::make_shared<std::future<void>>(std::async(std::launch::async,
208 [query, callback, maxResults]()
209 {
210 auto results = searchGames(
211 query, maxResults);
212 if (callback)
213 callback(results);
214 }));
215 storeFuture(std::move(future));
216}
217
219{
220 std::string url = std::string(API_BASE) + "/games?steamid=" + std::to_string(steamAppId);
221 Logger::info("LutrisAPI: Looking up Steam app {}", steamAppId);
222
223 std::string response = httpGet(url);
224 if (response.empty())
225 {
226 return {};
227 }
228
229 auto results = parseSearchResults(response);
230 if (results.empty())
231 {
232 return {};
233 }
234
235 return results[0];
236}
237
239{
240 std::string url = std::string(API_BASE) + "/games?gogid=" + std::to_string(gogId);
241 Logger::info("LutrisAPI: Looking up GOG game {}", gogId);
242
243 std::string response = httpGet(url);
244 if (response.empty())
245 {
246 return {};
247 }
248
249 auto results = parseSearchResults(response);
250 if (results.empty())
251 {
252 return {};
253 }
254
255 return results[0];
256}
257
258// ==============================================================================
259// Installer Methods
260// ==============================================================================
261
262std::vector<LutrisInstallerSummary> LutrisAPIService::getInstallers(const std::string& gameSlug)
263{
264 std::string url =
265 std::string(API_BASE) + "/installers?game_slug=" + urlEncodeComponent(gameSlug);
266 Logger::info("LutrisAPI: Fetching installers for '{}'", gameSlug);
267
268 std::string response = httpGet(url);
269 if (response.empty())
270 {
271 Logger::error("LutrisAPI: Empty response when fetching installers");
272 return {};
273 }
274
275 std::vector<LutrisInstallerSummary> installers;
276
277 // Find results array
278 size_t resultsStart = response.find("\"results\"");
279 if (resultsStart == std::string::npos)
280 {
281 return installers;
282 }
283
284 // Find the array
285 size_t arrayStart = response.find('[', resultsStart);
286 if (arrayStart == std::string::npos)
287 {
288 return installers;
289 }
290
291 // Extract the array
292 int bracketCount = 0;
293 size_t arrayEnd = arrayStart;
294 for (size_t i = arrayStart; i < response.size(); ++i)
295 {
296 if (response[i] == '[')
297 bracketCount++;
298 else if (response[i] == ']')
299 bracketCount--;
300 if (bracketCount == 0)
301 {
302 arrayEnd = i;
303 break;
304 }
305 }
306
307 std::string arrayJson = response.substr(arrayStart, arrayEnd - arrayStart + 1);
308 auto items = jsonSplitArray(arrayJson);
309
310 for (const auto& item : items)
311 {
312 LutrisInstallerSummary summary = parseInstallerSummary(item);
313 if (!summary.slug.empty())
314 {
315 installers.push_back(summary);
316 }
317 }
318
319 Logger::info("LutrisAPI: Found {} installers for '{}'", installers.size(), gameSlug);
320 return installers;
321}
322
324 const std::string& gameSlug,
325 const std::function<void(const std::vector<LutrisInstallerSummary>&)>& callback)
326{
327 auto future = std::make_shared<std::future<void>>(std::async(std::launch::async,
328 [gameSlug, callback]()
329 {
330 auto results =
331 getInstallers(gameSlug);
332 if (callback)
333 callback(results);
334 }));
335 storeFuture(std::move(future));
336}
337
339 const std::string& installerSlug)
340{
341 std::string cacheKey = gameSlug + "/" + installerSlug;
342
343 // Check cache with TTL
344 {
345 std::lock_guard<std::mutex> lock(cacheMutex_);
346 auto it = scriptCache_.find(cacheKey);
347 if (it != scriptCache_.end() && !it->second.isExpired(SCRIPT_CACHE_TTL))
348 {
349 Logger::debug("LutrisAPI: Returning cached script for '{}'", cacheKey);
350 return it->second.data;
351 }
352 // Remove expired entry if present
353 if (it != scriptCache_.end())
354 {
355 Logger::debug("LutrisAPI: Cache expired for script '{}'", cacheKey);
356 scriptCache_.erase(it);
357 }
358 }
359
360 // Fetch from game details which includes full installer info
361 std::string url = std::string(API_BASE) + "/games/" + urlEncodeComponent(gameSlug);
362 Logger::info("LutrisAPI: Fetching installer script for '{}/{}'", gameSlug, installerSlug);
363
364 std::string response = httpGet(url);
365 if (response.empty())
366 {
367 Logger::error("LutrisAPI: Empty response when fetching game details");
368 return {};
369 }
370
371 // Find the installers array
372 size_t installersStart = response.find("\"installers\"");
373 if (installersStart == std::string::npos)
374 {
375 Logger::error("LutrisAPI: No installers found in response");
376 return {};
377 }
378
379 // Find the array
380 size_t arrayStart = response.find('[', installersStart);
381 if (arrayStart == std::string::npos)
382 {
383 return {};
384 }
385
386 int bracketCount = 0;
387 size_t arrayEnd = arrayStart;
388 for (size_t i = arrayStart; i < response.size(); ++i)
389 {
390 if (response[i] == '[')
391 bracketCount++;
392 else if (response[i] == ']')
393 bracketCount--;
394 if (bracketCount == 0)
395 {
396 arrayEnd = i;
397 break;
398 }
399 }
400
401 std::string arrayJson = response.substr(arrayStart, arrayEnd - arrayStart + 1);
402 auto items = jsonSplitArray(arrayJson);
403
404 // Find the specific installer
405 for (const auto& item : items)
406 {
407 std::string slug = jsonGetString(item, "slug");
408 if (slug == installerSlug)
409 {
410 LutrisInstallerScript script = parseInstallerScript(item);
411 script.gameSlug = gameSlug;
412 script.gameName = jsonGetString(response, "name");
413
414 // Cache with timestamp
415 {
416 std::lock_guard<std::mutex> lock(cacheMutex_);
417 scriptCache_[cacheKey] = {script, std::chrono::steady_clock::now()};
418 }
419
420 return script;
421 }
422 }
423
424 Logger::error("LutrisAPI: Installer '{}' not found for game '{}'", installerSlug, gameSlug);
425 return {};
426}
427
429 const std::string& gameSlug, const std::string& installerSlug,
430 const std::function<void(const LutrisInstallerScript&)>& callback)
431{
432 auto future = std::make_shared<std::future<void>>(
433 std::async(std::launch::async,
434 [gameSlug, installerSlug, callback]()
435 {
436 auto result = getInstallerScript(gameSlug, installerSlug);
437 if (callback)
438 callback(result);
439 }));
440 storeFuture(std::move(future));
441}
442
443// ==============================================================================
444// Game Details
445// ==============================================================================
446
448{
449 std::string url = std::string(API_BASE) + "/games/" + urlEncodeComponent(gameSlug);
450 Logger::info("LutrisAPI: Fetching details for '{}'", gameSlug);
451
452 std::string response = httpGet(url);
453 if (response.empty())
454 {
455 return {};
456 }
457
458 return parseGameJson(response);
459}
460
461// ==============================================================================
462// Utilities
463// ==============================================================================
464
466{
467 std::string response = httpGet(std::string(API_BASE) + "/games?search=test");
468 return !response.empty() && response.find("results") != std::string::npos;
469}
470
472{
473 std::lock_guard<std::mutex> lock(cacheMutex_);
474 searchCache_.clear();
475 scriptCache_.clear();
476 Logger::info("LutrisAPI: Cache cleared");
477}
478
479// ==============================================================================
480// HTTP
481// ==============================================================================
482
483std::string LutrisAPIService::httpGet(const std::string& url)
484{
485 std::string command =
486 "curl -s -L --proto =https --connect-timeout 15 --max-time 60 --max-redirs 10 " +
487 ShellUtils::escapeArg(url) + " 2>/dev/null";
488
489 FILE* raw = popen(command.c_str(), "r");
490 if (!raw)
491 {
492 Logger::error("LutrisAPI: Failed to execute curl");
493 return "";
494 }
495
496 std::array<char, 8192> buffer;
497 std::string result;
498
499 constexpr size_t kMaxResponse = 16u * 1024 * 1024; // 16 MB
500 while (fgets(buffer.data(), static_cast<int>(buffer.size()), raw) != nullptr)
501 {
502 result += buffer.data();
503 if (result.size() > kMaxResponse)
504 {
505 Logger::warn("[LutrisAPI] HTTP response too large, truncating");
506 break;
507 }
508 }
509
510 int status = pclose(raw);
511 if (status == -1)
512 {
513 Logger::warn("LutrisAPI: pclose failed");
514 }
515 else if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
516 {
517 Logger::warn("LutrisAPI: curl exited with status {}", WEXITSTATUS(status));
518 }
519
520 return result;
521}
522
523// ==============================================================================
524// JSON Parsing Helpers
525// ==============================================================================
526
527std::string LutrisAPIService::jsonGetString(const std::string& json, const std::string& key)
528{
529 std::string searchKey = "\"" + key + "\"";
530 size_t pos = json.find(searchKey);
531 if (pos == std::string::npos)
532 return "";
533
534 pos = json.find(':', pos);
535 if (pos == std::string::npos)
536 return "";
537
538 pos++;
539 while (pos < json.size() && std::isspace(static_cast<unsigned char>(json[pos])))
540 pos++;
541
542 if (pos >= json.size())
543 return "";
544
545 // Check for null
546 if (json.substr(pos, 4) == "null")
547 return "";
548
549 if (json[pos] != '"')
550 return "";
551
552 pos++; // Skip opening quote
553 std::string result;
554
555 while (pos < json.size() && json[pos] != '"')
556 {
557 if (json[pos] == '\\' && pos + 1 < json.size())
558 {
559 pos++;
560 switch (json[pos])
561 {
562 case 'n':
563 result += '\n';
564 break;
565 case 't':
566 result += '\t';
567 break;
568 case 'r':
569 result += '\r';
570 break;
571 case '"':
572 result += '"';
573 break;
574 case '\\':
575 result += '\\';
576 break;
577 default:
578 result += json[pos];
579 break;
580 }
581 }
582 else
583 {
584 result += json[pos];
585 }
586 pos++;
587 }
588
589 return result;
590}
591
592int LutrisAPIService::jsonGetInt(const std::string& json, const std::string& key)
593{
594 std::string searchKey = "\"" + key + "\"";
595 size_t pos = json.find(searchKey);
596 if (pos == std::string::npos)
597 return 0;
598
599 pos = json.find(':', pos);
600 if (pos == std::string::npos)
601 return 0;
602
603 pos++;
604 while (pos < json.size() && std::isspace(static_cast<unsigned char>(json[pos])))
605 pos++;
606
607 if (pos >= json.size())
608 return 0;
609
610 // Check for null
611 if (json.substr(pos, 4) == "null")
612 return 0;
613
614 // Extract number. isdigit/tolower take int but std::isdigit requires
615 // the value be representable as unsigned char or EOF — `char` is
616 // signed-by-default on most ABIs, so a negative byte would be UB.
617 std::string numStr;
618 while (pos < json.size() &&
619 (std::isdigit(static_cast<unsigned char>(json[pos])) || json[pos] == '-'))
620 {
621 numStr += json[pos];
622 pos++;
623 }
624
625 try
626 {
627 // Lutris returns int64-sized fields like `installs` and `user_count`
628 // that already exceed INT_MAX in production data. Use stoll to avoid
629 // out_of_range exceptions silently turning into 0; clamp to int range
630 // for the int return type so downstream UI code's `int` assumption
631 // still holds. Loss of precision past 2^31 is acceptable for these
632 // cosmetic counters; what we want is to NOT silently return 0.
633 long long v = std::stoll(numStr);
634 if (v > std::numeric_limits<int>::max())
635 return std::numeric_limits<int>::max();
636 if (v < std::numeric_limits<int>::min())
637 return std::numeric_limits<int>::min();
638 return static_cast<int>(v);
639 }
640 catch (...)
641 {
642 return 0;
643 }
644}
645
646bool LutrisAPIService::jsonGetBool(const std::string& json, const std::string& key)
647{
648 std::string searchKey = "\"" + key + "\"";
649 size_t pos = json.find(searchKey);
650 if (pos == std::string::npos)
651 return false;
652
653 pos = json.find(':', pos);
654 if (pos == std::string::npos)
655 return false;
656
657 pos++;
658 while (pos < json.size() && std::isspace(static_cast<unsigned char>(json[pos])))
659 pos++;
660
661 return json.substr(pos, 4) == "true";
662}
663
664std::vector<std::string> LutrisAPIService::jsonGetArray(const std::string& json,
665 const std::string& key)
666{
667 std::vector<std::string> result;
668
669 std::string searchKey = "\"" + key + "\"";
670 size_t pos = json.find(searchKey);
671 if (pos == std::string::npos)
672 return result;
673
674 pos = json.find('[', pos);
675 if (pos == std::string::npos)
676 return result;
677
678 // Find matching ]
679 int bracketCount = 0;
680 size_t arrayEnd = pos;
681 for (size_t i = pos; i < json.size(); ++i)
682 {
683 if (json[i] == '[')
684 bracketCount++;
685 else if (json[i] == ']')
686 bracketCount--;
687 if (bracketCount == 0)
688 {
689 arrayEnd = i;
690 break;
691 }
692 }
693
694 std::string arrayJson = json.substr(pos, arrayEnd - pos + 1);
695 return jsonSplitArray(arrayJson);
696}
697
698std::vector<std::string> LutrisAPIService::jsonSplitArray(const std::string& arrayJson)
699{
700 std::vector<std::string> items;
701
702 if (arrayJson.empty() || arrayJson[0] != '[')
703 return items;
704
705 int depth = 0;
706 bool inString = false;
707 size_t itemStart = std::string::npos;
708
709 auto pushItem = [&](size_t end)
710 {
711 if (itemStart == std::string::npos)
712 return;
713 std::string item = arrayJson.substr(itemStart, end - itemStart);
714 size_t s = item.find_first_not_of(" \t\n\r");
715 size_t e = item.find_last_not_of(" \t\n\r");
716 if (s != std::string::npos)
717 items.push_back(item.substr(s, e - s + 1));
718 itemStart = std::string::npos;
719 };
720
721 for (size_t i = 1; i < arrayJson.size(); ++i)
722 {
723 char c = arrayJson[i];
724
725 if (c == '"')
726 {
727 // Count preceding backslashes: even count → quote is unescaped
728 size_t numBackslashes = 0;
729 size_t check = i;
730 while (check > 0 && arrayJson[check - 1] == '\\')
731 {
732 ++numBackslashes;
733 --check;
734 }
735 if (numBackslashes % 2 == 0)
736 {
737 if (!inString && depth == 0 && itemStart == std::string::npos)
738 itemStart = i; // start of a string element at top level
739 inString = !inString;
740 }
741 }
742 else if (!inString)
743 {
744 if (c == '{' || c == '[')
745 {
746 if (depth == 0 && itemStart == std::string::npos)
747 itemStart = i;
748 depth++;
749 }
750 else if (c == '}' || c == ']')
751 {
752 if (depth == 0)
753 {
754 // Closing bracket of the outer array — extract last element.
755 pushItem(i);
756 break;
757 }
758 depth--;
759 if (depth == 0)
760 {
761 // End of an object/array element — include the closing bracket.
762 pushItem(i + 1);
763 }
764 }
765 else if (depth == 0 && c == ',')
766 {
767 // Delimiter between elements — extract current element.
768 pushItem(i);
769 }
770 else if (depth == 0 && c != ' ' && c != '\t' && c != '\n' && c != '\r')
771 {
772 // Start of a scalar element (number, bool, null) at top level.
773 if (itemStart == std::string::npos)
774 itemStart = i;
775 }
776 }
777 }
778
779 return items;
780}
781
782// ==============================================================================
783// Response Parsers
784// ==============================================================================
785
786LutrisSearchResult LutrisAPIService::parseGameJson(const std::string& json)
787{
788 LutrisSearchResult result;
789
790 result.slug = jsonGetString(json, "slug");
791 result.name = jsonGetString(json, "name");
792 result.year = jsonGetInt(json, "year");
793 result.steamId = jsonGetInt(json, "steamid");
794 result.gogId = jsonGetInt(json, "gogid");
795 result.iconUrl = jsonGetString(json, "icon_url");
796 result.bannerUrl = jsonGetString(json, "banner_url");
797 result.coverUrl = jsonGetString(json, "coverart");
798 result.userCount = jsonGetInt(json, "user_count");
799
800 // Count installers if present
801 size_t installersPos = json.find("\"installers\"");
802 if (installersPos != std::string::npos)
803 {
804 // Count by finding objects in the array
805 size_t arrayStart = json.find('[', installersPos);
806 if (arrayStart != std::string::npos)
807 {
808 int bracketCount = 0;
809 size_t arrayEnd = arrayStart;
810 for (size_t i = arrayStart; i < json.size(); ++i)
811 {
812 if (json[i] == '[')
813 bracketCount++;
814 else if (json[i] == ']')
815 bracketCount--;
816 if (bracketCount == 0)
817 {
818 arrayEnd = i;
819 break;
820 }
821 }
822
823 std::string arrayJson = json.substr(arrayStart, arrayEnd - arrayStart + 1);
824 auto items = jsonSplitArray(arrayJson);
825 result.installerCount = static_cast<int>(items.size());
826
827 // Check installer types
828 for (const auto& item : items)
829 {
830 std::string runner = jsonGetString(item, "runner");
831 if (runner == "wine")
832 result.hasWineInstaller = true;
833 else if (runner == "steam")
834 result.hasSteamInstaller = true;
835 else if (runner == "linux")
836 result.hasLinuxInstaller = true;
837 }
838 }
839 }
840
841 return result;
842}
843
844std::vector<LutrisSearchResult> LutrisAPIService::parseSearchResults(const std::string& json)
845{
846 std::vector<LutrisSearchResult> results;
847
848 // Find results array
849 size_t resultsStart = json.find("\"results\"");
850 if (resultsStart == std::string::npos)
851 {
852 return results;
853 }
854
855 size_t arrayStart = json.find('[', resultsStart);
856 if (arrayStart == std::string::npos)
857 {
858 return results;
859 }
860
861 int bracketCount = 0;
862 size_t arrayEnd = arrayStart;
863 for (size_t i = arrayStart; i < json.size(); ++i)
864 {
865 if (json[i] == '[')
866 bracketCount++;
867 else if (json[i] == ']')
868 bracketCount--;
869 if (bracketCount == 0)
870 {
871 arrayEnd = i;
872 break;
873 }
874 }
875
876 std::string arrayJson = json.substr(arrayStart, arrayEnd - arrayStart + 1);
877 auto items = jsonSplitArray(arrayJson);
878
879 for (const auto& item : items)
880 {
881 LutrisSearchResult result = parseGameJson(item);
882 if (!result.slug.empty())
883 {
884 results.push_back(result);
885 }
886 }
887
888 return results;
889}
890
891LutrisInstallerSummary LutrisAPIService::parseInstallerSummary(const std::string& json)
892{
893 LutrisInstallerSummary summary;
894
895 summary.slug = jsonGetString(json, "slug");
896 summary.name = jsonGetString(json, "name");
897 summary.version = jsonGetString(json, "version");
898 summary.runner = jsonGetString(json, "runner");
899 summary.description = jsonGetString(json, "description");
900 summary.rating = jsonGetInt(json, "rating");
901 summary.isPublished = jsonGetBool(json, "published");
902 summary.createdAt = jsonGetString(json, "created_at");
903
904 // Download count might be in different fields
905 summary.downloadCount = jsonGetInt(json, "installs");
906 if (summary.downloadCount == 0)
907 {
908 summary.downloadCount = jsonGetInt(json, "download_count");
909 }
910
911 return summary;
912}
913
914LutrisInstallerScript LutrisAPIService::parseInstallerScript(const std::string& json)
915{
916 LutrisInstallerScript script;
917
918 // Basic info
919 script.installerSlug = jsonGetString(json, "slug");
920 script.installerName = jsonGetString(json, "name");
921 script.version = jsonGetString(json, "version");
922 script.runner = jsonGetString(json, "runner");
923 script.description = jsonGetString(json, "description");
924 script.notes = jsonGetString(json, "notes");
925 script.createdAt = jsonGetString(json, "created_at");
926 script.updatedAt = jsonGetString(json, "updated_at");
927 script.rating = jsonGetInt(json, "rating");
928 script.isPublished = jsonGetBool(json, "published");
929 script.isDraft = jsonGetBool(json, "draft");
930
931 // Store IDs
932 script.steamId = jsonGetInt(json, "steamid");
933 script.gogId = jsonGetInt(json, "gogid");
934 script.gogSlug = jsonGetString(json, "gogslug");
935 script.humbleId = jsonGetString(json, "humbleid");
936
937 // Find the script object within the installer
938 size_t scriptStart = json.find("\"script\"");
939 if (scriptStart != std::string::npos)
940 {
941 size_t objStart = json.find('{', scriptStart);
942 if (objStart != std::string::npos)
943 {
944 // Extract the script object
945 int braceCount = 0;
946 size_t objEnd = objStart;
947 for (size_t i = objStart; i < json.size(); ++i)
948 {
949 if (json[i] == '{')
950 braceCount++;
951 else if (json[i] == '}')
952 braceCount--;
953 if (braceCount == 0)
954 {
955 objEnd = i;
956 break;
957 }
958 }
959
960 std::string scriptObj = json.substr(objStart, objEnd - objStart + 1);
961
962 // Parse files
963 script.files = parseFiles(scriptObj);
964
965 // Parse steps (installer array)
966 script.steps = parseSteps(scriptObj);
967
968 // Parse game config
969 size_t gameStart = scriptObj.find("\"game\"");
970 if (gameStart != std::string::npos)
971 {
972 size_t gameObjStart = scriptObj.find('{', gameStart);
973 if (gameObjStart != std::string::npos)
974 {
975 int bc = 0;
976 size_t gameObjEnd = gameObjStart;
977 for (size_t i = gameObjStart; i < scriptObj.size(); ++i)
978 {
979 if (scriptObj[i] == '{')
980 bc++;
981 else if (scriptObj[i] == '}')
982 bc--;
983 if (bc == 0)
984 {
985 gameObjEnd = i;
986 break;
987 }
988 }
989
990 std::string gameObj =
991 scriptObj.substr(gameObjStart, gameObjEnd - gameObjStart + 1);
992 script.executable = jsonGetString(gameObj, "exe");
993 script.workingDir = jsonGetString(gameObj, "working_dir");
994 script.arguments = jsonGetString(gameObj, "args");
995 script.prefix = jsonGetString(gameObj, "prefix");
996 }
997 }
998
999 // Parse wine config
1000 script.wineConfig = parseWineConfig(scriptObj);
1001 }
1002 }
1003
1004 // Generate descriptions for steps
1005 for (auto& step : script.steps)
1006 {
1007 step.description = describeStep(step);
1008 }
1009
1010 return script;
1011}
1012
1013std::vector<LutrisInstallerFile> LutrisAPIService::parseFiles(const std::string& scriptJson)
1014{
1015 std::vector<LutrisInstallerFile> files;
1016
1017 // Files can be an array or object
1018 size_t filesStart = scriptJson.find("\"files\"");
1019 if (filesStart == std::string::npos)
1020 {
1021 return files;
1022 }
1023
1024 // Check if it's an array [ or object {
1025 size_t nextChar = scriptJson.find_first_not_of(" \t\n\r:", filesStart + 7);
1026 if (nextChar == std::string::npos)
1027 {
1028 return files;
1029 }
1030
1031 if (scriptJson[nextChar] == '[')
1032 {
1033 // Array of file objects
1034 auto fileItems = jsonGetArray(scriptJson, "files");
1035 for (const auto& item : fileItems)
1036 {
1037 LutrisInstallerFile file;
1038
1039 // Each item can be {"id": "url"} or {"id": {"url": "...", "filename": "..."}}
1040 // Try to find the first key
1041 size_t keyStart = item.find('"');
1042 if (keyStart == std::string::npos)
1043 continue;
1044
1045 size_t keyEnd = item.find('"', keyStart + 1);
1046 if (keyEnd == std::string::npos)
1047 continue;
1048
1049 file.id = item.substr(keyStart + 1, keyEnd - keyStart - 1);
1050
1051 // Check what's after the colon
1052 size_t colonPos = item.find(':', keyEnd);
1053 if (colonPos == std::string::npos)
1054 continue;
1055
1056 size_t valueStart = item.find_first_not_of(" \t\n\r", colonPos + 1);
1057 if (valueStart == std::string::npos)
1058 continue;
1059
1060 if (item[valueStart] == '"')
1061 {
1062 // Simple string URL
1063 file.url = jsonGetString(item, file.id);
1064 }
1065 else if (item[valueStart] == '{')
1066 {
1067 // Object with url, filename, etc.
1068 // Extract the nested object
1069 int bc = 0;
1070 size_t objEnd = valueStart;
1071 for (size_t i = valueStart; i < item.size(); ++i)
1072 {
1073 if (item[i] == '{')
1074 bc++;
1075 else if (item[i] == '}')
1076 bc--;
1077 if (bc == 0)
1078 {
1079 objEnd = i;
1080 break;
1081 }
1082 }
1083 std::string fileObj = item.substr(valueStart, objEnd - valueStart + 1);
1084 file.url = jsonGetString(fileObj, "url");
1085 file.filename = jsonGetString(fileObj, "filename");
1086 file.checksum = jsonGetString(fileObj, "checksum");
1087 }
1088
1089 // Check if manual file
1090 if (file.url.find("N/A") == 0 || file.url.empty())
1091 {
1092 file.isManual = true;
1093 }
1094
1095 // Set filename from URL if not specified
1096 if (file.filename.empty() && !file.url.empty() && !file.isManual)
1097 {
1098 size_t lastSlash = file.url.rfind('/');
1099 if (lastSlash != std::string::npos)
1100 {
1101 file.filename = file.url.substr(lastSlash + 1);
1102 // Remove query string
1103 size_t queryPos = file.filename.find('?');
1104 if (queryPos != std::string::npos)
1105 {
1106 file.filename = file.filename.substr(0, queryPos);
1107 }
1108 }
1109 }
1110
1111 files.push_back(file);
1112 }
1113 }
1114
1115 return files;
1116}
1117
1118std::vector<LutrisInstallStep> LutrisAPIService::parseSteps(const std::string& scriptJson)
1119{
1120 std::vector<LutrisInstallStep> steps;
1121
1122 // Steps are in the "installer" array
1123 size_t installerStart = scriptJson.find("\"installer\"");
1124 if (installerStart == std::string::npos)
1125 {
1126 return steps;
1127 }
1128
1129 size_t arrayStart = scriptJson.find('[', installerStart);
1130 if (arrayStart == std::string::npos)
1131 {
1132 return steps;
1133 }
1134
1135 int bracketCount = 0;
1136 size_t arrayEnd = arrayStart;
1137 for (size_t i = arrayStart; i < scriptJson.size(); ++i)
1138 {
1139 if (scriptJson[i] == '[')
1140 bracketCount++;
1141 else if (scriptJson[i] == ']')
1142 bracketCount--;
1143 if (bracketCount == 0)
1144 {
1145 arrayEnd = i;
1146 break;
1147 }
1148 }
1149
1150 std::string arrayJson = scriptJson.substr(arrayStart, arrayEnd - arrayStart + 1);
1151 auto stepItems = jsonSplitArray(arrayJson);
1152
1153 for (const auto& item : stepItems)
1154 {
1155 LutrisInstallStep step;
1156
1157 // Each step is an object with a single key (the task type)
1158 // e.g., {"extract": {"file": "$setup", "dst": "$GAMEDIR"}}
1159 // or {"task": {"name": "winetricks", "prefix": "$GAMEDIR"}}
1160
1161 // Find the first key
1162 size_t keyStart = item.find('"');
1163 if (keyStart == std::string::npos)
1164 continue;
1165
1166 size_t keyEnd = item.find('"', keyStart + 1);
1167 if (keyEnd == std::string::npos)
1168 continue;
1169
1170 step.task = item.substr(keyStart + 1, keyEnd - keyStart - 1);
1171
1172 // Find the value (could be object or string)
1173 size_t colonPos = item.find(':', keyEnd);
1174 if (colonPos == std::string::npos)
1175 continue;
1176
1177 size_t valueStart = item.find_first_not_of(" \t\n\r", colonPos + 1);
1178 if (valueStart == std::string::npos)
1179 continue;
1180
1181 if (item[valueStart] == '{')
1182 {
1183 // Extract parameters object
1184 int bc = 0;
1185 size_t objEnd = valueStart;
1186 for (size_t i = valueStart; i < item.size(); ++i)
1187 {
1188 if (item[i] == '{')
1189 bc++;
1190 else if (item[i] == '}')
1191 bc--;
1192 if (bc == 0)
1193 {
1194 objEnd = i;
1195 break;
1196 }
1197 }
1198
1199 std::string paramsObj = item.substr(valueStart, objEnd - valueStart + 1);
1200
1201 // Extract all key-value pairs from params (hoisted regex)
1202 std::sregex_iterator it(paramsObj.begin(), paramsObj.end(), kKvWildValueRegex());
1203 std::sregex_iterator end;
1204
1205 while (it != end)
1206 {
1207 std::string key = (*it)[1].str();
1208 std::string value = (*it)[2].str();
1209
1210 // Remove quotes from string values
1211 if (value.size() >= 2 && value[0] == '"' && value.back() == '"')
1212 {
1213 value = value.substr(1, value.size() - 2);
1214 }
1215
1216 step.params[key] = value;
1217 ++it;
1218 }
1219 }
1220 else if (item[valueStart] == '"')
1221 {
1222 // Simple string value
1223 size_t strEnd = item.find('"', valueStart + 1);
1224 if (strEnd != std::string::npos)
1225 {
1226 step.params["value"] = item.substr(valueStart + 1, strEnd - valueStart - 1);
1227 }
1228 }
1229
1230 steps.push_back(step);
1231 }
1232
1233 return steps;
1234}
1235
1236LutrisWineConfig LutrisAPIService::parseWineConfig(const std::string& json)
1237{
1238 LutrisWineConfig config;
1239
1240 // Wine config can be in a "wine" section
1241 size_t wineStart = json.find("\"wine\"");
1242 if (wineStart != std::string::npos)
1243 {
1244 size_t objStart = json.find('{', wineStart);
1245 if (objStart != std::string::npos)
1246 {
1247 int bc = 0;
1248 size_t objEnd = objStart;
1249 for (size_t i = objStart; i < json.size(); ++i)
1250 {
1251 if (json[i] == '{')
1252 bc++;
1253 else if (json[i] == '}')
1254 bc--;
1255 if (bc == 0)
1256 {
1257 objEnd = i;
1258 break;
1259 }
1260 }
1261
1262 std::string wineObj = json.substr(objStart, objEnd - objStart + 1);
1263 config.version = jsonGetString(wineObj, "version");
1264 config.dxvk = jsonGetBool(wineObj, "dxvk");
1265 config.vkd3d = jsonGetBool(wineObj, "vkd3d");
1266 config.esync = jsonGetBool(wineObj, "esync");
1267 config.fsync = jsonGetBool(wineObj, "fsync");
1268 config.battleye = jsonGetBool(wineObj, "battleye");
1269 config.eac = jsonGetBool(wineObj, "eac");
1270
1271 // Parse DLL overrides
1272 size_t overridesStart = wineObj.find("\"overrides\"");
1273 if (overridesStart != std::string::npos)
1274 {
1275 size_t ovObjStart = wineObj.find('{', overridesStart);
1276 if (ovObjStart != std::string::npos)
1277 {
1278 int obc = 0;
1279 size_t ovObjEnd = ovObjStart;
1280 for (size_t i = ovObjStart; i < wineObj.size(); ++i)
1281 {
1282 if (wineObj[i] == '{')
1283 obc++;
1284 else if (wineObj[i] == '}')
1285 obc--;
1286 if (obc == 0)
1287 {
1288 ovObjEnd = i;
1289 break;
1290 }
1291 }
1292
1293 std::string ovObj = wineObj.substr(ovObjStart, ovObjEnd - ovObjStart + 1);
1294 std::sregex_iterator it(ovObj.begin(), ovObj.end(), kKvStringValueRegex());
1295 std::sregex_iterator end;
1296
1297 while (it != end)
1298 {
1299 config.dllOverrides[(*it)[1].str()] = (*it)[2].str();
1300 ++it;
1301 }
1302 }
1303 }
1304 }
1305 }
1306
1307 // Check system section for environment variables
1308 size_t systemStart = json.find("\"system\"");
1309 if (systemStart != std::string::npos)
1310 {
1311 size_t objStart = json.find('{', systemStart);
1312 if (objStart != std::string::npos)
1313 {
1314 int bc = 0;
1315 size_t objEnd = objStart;
1316 for (size_t i = objStart; i < json.size(); ++i)
1317 {
1318 if (json[i] == '{')
1319 bc++;
1320 else if (json[i] == '}')
1321 bc--;
1322 if (bc == 0)
1323 {
1324 objEnd = i;
1325 break;
1326 }
1327 }
1328
1329 std::string sysObj = json.substr(objStart, objEnd - objStart + 1);
1330
1331 // Look for env section
1332 size_t envStart = sysObj.find("\"env\"");
1333 if (envStart != std::string::npos)
1334 {
1335 size_t envObjStart = sysObj.find('{', envStart);
1336 if (envObjStart != std::string::npos)
1337 {
1338 int ebc = 0;
1339 size_t envObjEnd = envObjStart;
1340 for (size_t i = envObjStart; i < sysObj.size(); ++i)
1341 {
1342 if (sysObj[i] == '{')
1343 ebc++;
1344 else if (sysObj[i] == '}')
1345 ebc--;
1346 if (ebc == 0)
1347 {
1348 envObjEnd = i;
1349 break;
1350 }
1351 }
1352
1353 std::string envObj = sysObj.substr(envObjStart, envObjEnd - envObjStart + 1);
1354 std::sregex_iterator it(envObj.begin(), envObj.end(), kKvStringValueRegex());
1355 std::sregex_iterator end;
1356
1357 while (it != end)
1358 {
1359 config.environment[(*it)[1].str()] = (*it)[2].str();
1360 ++it;
1361 }
1362 }
1363 }
1364 }
1365 }
1366
1367 // Also check for arch
1368 config.arch = jsonGetString(json, "arch");
1369 if (config.arch.empty())
1370 {
1371 config.arch = "win64"; // Default
1372 }
1373
1374 return config;
1375}
1376
1377// ==============================================================================
1378// Step Description Generator
1379// ==============================================================================
1380
1381std::string LutrisAPIService::describeStep(const LutrisInstallStep& step)
1382{
1383 std::ostringstream desc;
1384
1385 if (step.task == "extract")
1386 {
1387 std::string file = step.params.count("file") ? step.params.at("file") : "archive";
1388 std::string dst = step.params.count("dst") ? step.params.at("dst") : "destination";
1389 desc << "Extract " << file << " to " << dst;
1390 }
1391 else if (step.task == "copy" || step.task == "merge")
1392 {
1393 std::string src = step.params.count("src") ? step.params.at("src") : "files";
1394 std::string dst = step.params.count("dst") ? step.params.at("dst") : "destination";
1395 desc << "Copy " << src << " to " << dst;
1396 }
1397 else if (step.task == "move")
1398 {
1399 std::string src = step.params.count("src") ? step.params.at("src") : "files";
1400 std::string dst = step.params.count("dst") ? step.params.at("dst") : "destination";
1401 desc << "Move " << src << " to " << dst;
1402 }
1403 else if (step.task == "execute")
1404 {
1405 std::string file = step.params.count("file") ? step.params.at("file") : "program";
1406 desc << "Run " << file;
1407 if (step.params.count("args"))
1408 {
1409 desc << " with arguments";
1410 }
1411 }
1412 else if (step.task == "task")
1413 {
1414 std::string name = step.params.count("name") ? step.params.at("name") : "task";
1415 if (name == "winetricks")
1416 {
1417 std::string args = step.params.count("app") ? step.params.at("app") : "";
1418 if (args.empty())
1419 args = step.params.count("args") ? step.params.at("args") : "";
1420 desc << "Install Wine components: " << args;
1421 }
1422 else if (name == "create_prefix")
1423 {
1424 desc << "Create Wine prefix";
1425 }
1426 else if (name == "set_regedit")
1427 {
1428 desc << "Set Windows registry values";
1429 }
1430 else if (name == "winekill")
1431 {
1432 desc << "Stop Wine processes";
1433 }
1434 else
1435 {
1436 desc << "Run task: " << name;
1437 }
1438 }
1439 else if (step.task == "write_file")
1440 {
1441 std::string file = step.params.count("file") ? step.params.at("file") : "file";
1442 desc << "Write configuration to " << file;
1443 }
1444 else if (step.task == "write_json")
1445 {
1446 std::string file = step.params.count("file") ? step.params.at("file") : "file";
1447 desc << "Write JSON configuration to " << file;
1448 }
1449 else if (step.task == "write_config")
1450 {
1451 std::string file = step.params.count("file") ? step.params.at("file") : "file";
1452 desc << "Write INI configuration to " << file;
1453 }
1454 else if (step.task == "chmodx")
1455 {
1456 std::string file = step.params.count("file") ? step.params.at("file") : "file";
1457 desc << "Make " << file << " executable";
1458 }
1459 else if (step.task == "delete")
1460 {
1461 std::string file = step.params.count("file") ? step.params.at("file") : "files";
1462 desc << "Delete " << file;
1463 }
1464 else if (step.task == "rename")
1465 {
1466 std::string src = step.params.count("src") ? step.params.at("src") : "file";
1467 std::string dst = step.params.count("dst") ? step.params.at("dst") : "new name";
1468 desc << "Rename " << src << " to " << dst;
1469 }
1470 else if (step.task == "insert-disc")
1471 {
1472 desc << "Insert game disc";
1473 }
1474 else
1475 {
1476 desc << step.task;
1477 }
1478
1479 return desc.str();
1480}
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 LutrisSearchResult getGameDetails(const std::string &gameSlug)
Get detailed information about a game.
static void searchGamesAsync(const std::string &query, const std::function< void(const std::vector< LutrisSearchResult > &)> &callback, int maxResults=20)
Search for games asynchronously.
static LutrisSearchResult findBySteamId(int steamAppId)
Find a game by Steam App ID.
static void getInstallerScriptAsync(const std::string &gameSlug, const std::string &installerSlug, const std::function< void(const LutrisInstallerScript &)> &callback)
Get installer script asynchronously.
static void clearCache()
Clear cached data.
static void getInstallersAsync(const std::string &gameSlug, const std::function< void(const std::vector< LutrisInstallerSummary > &)> &callback)
Get available installers asynchronously.
static std::vector< LutrisInstallerSummary > getInstallers(const std::string &gameSlug)
Get available installers for a game.
static std::vector< LutrisSearchResult > searchGames(const std::string &query, int maxResults=20)
Search for games by name.
static LutrisInstallerScript getInstallerScript(const std::string &gameSlug, const std::string &installerSlug)
Get full installer script with all details.
static LutrisSearchResult findByGogId(int gogId)
Find a game by GOG ID.
static bool isApiAvailable()
Check if Lutris API is accessible.
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
Definition shell_utils.h:65
nlohmann::json json
void storeFuture(std::shared_ptr< std::future< void > > f)
std::string urlEncodeComponent(const std::string &s)
std::vector< std::shared_ptr< std::future< void > > > g_activeFutures
std::map< std::string, std::string > params
LutrisWineConfig wineConfig
std::vector< LutrisInstallerFile > files
uint64_t getTotalDownloadSize() const
std::vector< LutrisInstallStep > steps
std::map< std::string, std::string > dllOverrides
std::map< std::string, std::string > environment