game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
cloud_save_service.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// cloud_save_service.cpp
4// ==============================================================================
5// Cloud save synchronization service implementation
6// ==============================================================================
7
9#include "logger.h"
10
11#include <algorithm>
12#include <array>
13#include <cstdint>
14#include <cstdlib>
15#include <ctime>
16#include <fstream>
17#include <map>
18#include <mutex>
19#include <random>
20#include <string>
21#include <vector>
22
23// ==============================================================================
24// Helper Functions
25// ==============================================================================
26
27namespace
28{
29
30bool fileExists(const std::filesystem::path& path)
31{
32 std::error_code ec;
33 return std::filesystem::exists(path, ec);
34}
35
36bool createDirectories(const std::filesystem::path& path)
37{
38 std::error_code ec;
39 std::filesystem::create_directories(path, ec);
40 return !ec;
41}
42
43int64_t getFileSize(const std::filesystem::path& path)
44{
45 std::error_code ec;
46 auto size = std::filesystem::file_size(path, ec);
47 return ec ? 0 : static_cast<int64_t>(size);
48}
49
50std::chrono::system_clock::time_point getFileModTime(const std::filesystem::path& path)
51{
52 std::error_code ec;
53 auto ftime = std::filesystem::last_write_time(path, ec);
54 if (ec)
55 {
56 return std::chrono::system_clock::now();
57 }
58 // Convert file_time to system_clock
59 auto sctp = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
60 ftime - std::filesystem::file_time_type::clock::now() + std::chrono::system_clock::now());
61 return sctp;
62}
63
64std::string formatBytes(int64_t bytes)
65{
66 const char* units[] = {"B", "KB", "MB", "GB"};
67 int unitIndex = 0;
68 double size = static_cast<double>(bytes);
69
70 while (size >= 1024 && unitIndex < 3)
71 {
72 size /= 1024;
73 unitIndex++;
74 }
75
76 char buffer[64];
77 snprintf(buffer, sizeof(buffer), "%.1f %s", size, units[unitIndex]);
78 return buffer;
79}
80
81std::string formatTime(std::chrono::system_clock::time_point tp)
82{
83 auto time = std::chrono::system_clock::to_time_t(tp);
84 char buffer[64];
85 struct tm tm_buf;
86 localtime_r(&time, &tm_buf);
87 std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &tm_buf);
88 return buffer;
89}
90
91std::string generateUUID()
92{
93 std::random_device rd;
94 std::mt19937 gen(rd());
95 std::uniform_int_distribution<> dis(0, 15);
96 std::uniform_int_distribution<> dis2(8, 11);
97
98 std::stringstream ss;
99 ss << std::hex;
100
101 for (int i = 0; i < 8; i++)
102 ss << dis(gen);
103 ss << "-";
104 for (int i = 0; i < 4; i++)
105 ss << dis(gen);
106 ss << "-4";
107 for (int i = 0; i < 3; i++)
108 ss << dis(gen);
109 ss << "-";
110 ss << dis2(gen);
111 for (int i = 0; i < 3; i++)
112 ss << dis(gen);
113 ss << "-";
114 for (int i = 0; i < 12; i++)
115 ss << dis(gen);
116
117 return ss.str();
118}
119
120std::filesystem::path getDataDirectory()
121{
122 const char* home = std::getenv("HOME");
123 if (home)
124 {
125 return std::filesystem::path(home) / ".local" / "share" / "gamelauncher";
126 }
127 return {};
128}
129
130std::vector<std::filesystem::path> globFiles(const std::filesystem::path& root,
131 const std::string& pattern)
132{
133 std::vector<std::filesystem::path> result;
134 std::error_code ec;
135
136 if (!fileExists(root))
137 {
138 return result;
139 }
140
141 // Simple pattern matching - treat ** as recursive
142 bool recursive = pattern.find("**") != std::string::npos;
143
144 if (recursive)
145 {
146 // Canonicalize root to prevent path traversal via symlinks
147 auto canonicalRoot = std::filesystem::canonical(root, ec);
148 if (ec)
149 {
150 return result;
151 }
152
153 for (const auto& entry : std::filesystem::recursive_directory_iterator(root, ec))
154 {
155 if (entry.is_regular_file())
156 {
157 std::error_code ecPath;
158 auto canonicalPath = std::filesystem::canonical(entry.path(), ecPath);
159 auto canonicalStr = canonicalPath.string();
160 auto rootStr = canonicalRoot.string();
161 // Check containment: path must equal root or be directly under it
162 // (rootStr must be followed by '/' to avoid /home/alice matching /home/alice2)
163 bool contained =
164 !ecPath && canonicalStr.size() >= rootStr.size() &&
165 canonicalStr.compare(0, rootStr.size(), rootStr) == 0 &&
166 (canonicalStr.size() == rootStr.size() || canonicalStr[rootStr.size()] == '/');
167 if (contained)
168 {
169 result.push_back(entry.path());
170 }
171 }
172 }
173 }
174 else
175 {
176 for (const auto& entry : std::filesystem::directory_iterator(root, ec))
177 {
178 if (entry.is_regular_file())
179 {
180 // Check if matches pattern (simplified)
181 std::string filename = entry.path().filename().string();
182 if (pattern == "*" || pattern.empty())
183 {
184 result.push_back(entry.path());
185 }
186 else if (pattern.front() == '*')
187 {
188 std::string ext = pattern.substr(1);
189 if (filename.size() >= ext.size() &&
190 filename.substr(filename.size() - ext.size()) == ext)
191 {
192 result.push_back(entry.path());
193 }
194 }
195 }
196 }
197 }
198
199 return result;
200}
201
202} // namespace
203
204// ==============================================================================
205// SaveFile Methods
206// ==============================================================================
207
208std::string SaveFile::getFormattedSize() const
209{
210 return formatBytes(size);
211}
212
213std::string SaveFile::getFormattedTime() const
214{
215 return formatTime(modifiedTime);
216}
217
218// ==============================================================================
219// SaveSnapshot Methods
220// ==============================================================================
221
223{
224 return formatTime(timestamp);
225}
226
228{
229 return formatBytes(totalSize);
230}
231
232// ==============================================================================
233// SyncStatus Methods
234// ==============================================================================
235
236std::string SyncStatus::getStateStr() const
237{
238 switch (state)
239 {
240 case State::Idle:
241 return "Idle";
242 case State::Scanning:
243 return "Scanning";
244 case State::Comparing:
245 return "Comparing";
246 case State::Uploading:
247 return "Uploading";
249 return "Downloading";
250 case State::Resolving:
251 return "Resolving conflicts";
252 case State::Completed:
253 return "Completed";
254 case State::Failed:
255 return "Failed";
256 case State::Cancelled:
257 return "Cancelled";
258 default:
259 return "Unknown";
260 }
261}
262
263// ==============================================================================
264// Helper Function Implementations
265// ==============================================================================
266
267std::string cloudBackendName(CloudBackend backend)
268{
269 switch (backend)
270 {
272 return "Local Only";
274 return "Steam Cloud";
276 return "GOG Galaxy";
278 return "Custom";
279 default:
280 return "Unknown";
281 }
282}
283
284std::string syncDirectionName(SyncDirection direction)
285{
286 switch (direction)
287 {
289 return "Upload";
291 return "Download";
293 return "Bidirectional";
294 default:
295 return "Unknown";
296 }
297}
298
299// ==============================================================================
300// CloudSaveService Implementation
301// ==============================================================================
302
304{
305 std::filesystem::path backupDir;
306 std::filesystem::path customSyncDir;
307 std::vector<SaveLocation> saveLocations;
308 std::map<std::string, std::vector<SaveSnapshot>> snapshots;
311 std::atomic<bool> cancelRequested{false};
312 mutable std::mutex mutex;
313
315 {
316 backupDir = getDataDirectory() / "save_backups";
317 createDirectories(backupDir);
318 }
319};
320
321CloudSaveService::CloudSaveService() : impl_(std::make_unique<Impl>())
322{
323 loadSaveLocations();
324 loadSnapshots();
325}
326
328
329// ==============================================================================
330// Save Location Management
331// ==============================================================================
332
334{
335 std::lock_guard<std::mutex> lock(impl_->mutex);
336
337 // Check if already exists
338 for (const auto& loc : impl_->saveLocations)
339 {
340 if (loc.gameId == location.gameId)
341 {
342 return false;
343 }
344 }
345
346 impl_->saveLocations.push_back(location);
347 saveSaveLocations();
348 return true;
349}
350
352{
353 std::lock_guard<std::mutex> lock(impl_->mutex);
354
355 for (auto& loc : impl_->saveLocations)
356 {
357 if (loc.gameId == location.gameId)
358 {
359 loc = location;
360 saveSaveLocations();
361 return true;
362 }
363 }
364 return false;
365}
366
367bool CloudSaveService::removeSaveLocation(const std::string& gameId)
368{
369 std::lock_guard<std::mutex> lock(impl_->mutex);
370
371 auto it = std::remove_if(impl_->saveLocations.begin(), impl_->saveLocations.end(),
372 [&gameId](const SaveLocation& loc) { return loc.gameId == gameId; });
373
374 if (it != impl_->saveLocations.end())
375 {
376 impl_->saveLocations.erase(it, impl_->saveLocations.end());
377 saveSaveLocations();
378 return true;
379 }
380 return false;
381}
382
383std::vector<SaveLocation> CloudSaveService::getSaveLocations() const
384{
385 std::lock_guard<std::mutex> lock(impl_->mutex);
386 return impl_->saveLocations;
387}
388
389std::optional<SaveLocation> CloudSaveService::getSaveLocation(const std::string& gameId) const
390{
391 std::lock_guard<std::mutex> lock(impl_->mutex);
392
393 for (const auto& loc : impl_->saveLocations)
394 {
395 if (loc.gameId == gameId)
396 {
397 return loc;
398 }
399 }
400 return std::nullopt;
401}
402
403std::vector<SaveLocation>
404CloudSaveService::detectSaveLocation(const std::string& gameName,
405 const std::filesystem::path& prefixPath) const
406{
407 std::vector<SaveLocation> detected;
408
409 // Common Linux save locations
410 std::vector<std::filesystem::path> searchPaths;
411 const char* home = std::getenv("HOME");
412 if (home)
413 {
414 std::filesystem::path homePath(home);
415
416 // Standard Linux locations
417 searchPaths.push_back(homePath / ".local" / "share");
418 searchPaths.push_back(homePath / ".config");
419 searchPaths.push_back(homePath / "Games");
420 searchPaths.push_back(homePath / ".steam" / "steam" / "steamapps" / "compatdata");
421
422 // XDG data dirs
423 const char* xdgData = std::getenv("XDG_DATA_HOME");
424 if (xdgData)
425 {
426 searchPaths.push_back(std::filesystem::path(xdgData));
427 }
428
429 // Wine prefix locations
430 if (!prefixPath.empty())
431 {
432 searchPaths.push_back(prefixPath / "drive_c" / "users" / "steamuser" / "Saved Games");
433 searchPaths.push_back(prefixPath / "drive_c" / "users" / "steamuser" / "Documents");
434 searchPaths.push_back(prefixPath / "drive_c" / "users" / "steamuser" / "AppData" /
435 "Local");
436 searchPaths.push_back(prefixPath / "drive_c" / "users" / "steamuser" / "AppData" /
437 "Roaming");
438 }
439 }
440
441 // Simple name matching
442 std::string lowerName = gameName;
443 std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(),
444 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
445
446 // Remove common suffixes
447 std::vector<std::string> suffixes = {" game of the year", " goty", " edition", " remaster",
448 " remastered"};
449 for (const auto& suffix : suffixes)
450 {
451 if (lowerName.size() > suffix.size())
452 {
453 if (lowerName.substr(lowerName.size() - suffix.size()) == suffix)
454 {
455 lowerName = lowerName.substr(0, lowerName.size() - suffix.size());
456 }
457 }
458 }
459
460 for (const auto& searchPath : searchPaths)
461 {
462 if (!fileExists(searchPath))
463 continue;
464
465 std::error_code ec;
466 for (const auto& entry : std::filesystem::directory_iterator(searchPath, ec))
467 {
468 if (!entry.is_directory())
469 continue;
470
471 std::string dirName = entry.path().filename().string();
472 std::string lowerDir = dirName;
473 std::transform(lowerDir.begin(), lowerDir.end(), lowerDir.begin(),
474 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
475
476 // Check if directory name contains game name
477 if (lowerDir.find(lowerName) != std::string::npos)
478 {
479 SaveLocation loc;
480 loc.gameId = gameName; // Will be replaced with proper ID
481 loc.gameName = gameName;
482 loc.localPath = entry.path();
483 loc.pattern = "**/*";
484 loc.isWinePrefix = !prefixPath.empty();
485 loc.prefixPath = prefixPath;
486 detected.push_back(loc);
487 }
488 }
489 }
490
491 return detected;
492}
493
494// ==============================================================================
495// Local Backup (Snapshots)
496// ==============================================================================
497
498std::optional<std::string> CloudSaveService::createSnapshot(const std::string& gameId,
499 const std::string& description)
500{
501 auto location = getSaveLocation(gameId);
502 if (!location)
503 {
504 return std::nullopt;
505 }
506
507 // Scan current save files
508 auto files = scanSaveFiles(*location);
509 if (files.empty())
510 {
511 return std::nullopt;
512 }
513
514 // Create snapshot
515 SaveSnapshot snapshot;
516 snapshot.id = generateSnapshotId();
517 snapshot.gameId = gameId;
518 snapshot.gameName = location->gameName;
519 snapshot.timestamp = std::chrono::system_clock::now();
520 snapshot.description = description;
521 snapshot.isAutomatic = description.empty();
522
523 // Create snapshot directory
524 std::filesystem::path snapshotDir = impl_->backupDir / gameId / snapshot.id;
525 if (!createDirectories(snapshotDir))
526 {
527 return std::nullopt;
528 }
529
530 // Copy files
531 int64_t totalSize = 0;
532 for (const auto& file : files)
533 {
534 std::filesystem::path destPath = snapshotDir / file.relativePath;
535 createDirectories(destPath.parent_path());
536
537 std::error_code ec;
538 std::filesystem::copy_file(file.path, destPath,
539 std::filesystem::copy_options::overwrite_existing, ec);
540
541 if (!ec)
542 {
543 SaveFile snapshotFile = file;
544 snapshotFile.path = destPath;
545 snapshot.files.push_back(snapshotFile);
546 totalSize += file.size;
547 }
548 else
549 {
550 Logger::warn("[CloudSave] Snapshot {}: failed to copy {}: {}", snapshot.id,
551 file.relativePath, ec.message());
552 }
553 }
554
555 snapshot.totalSize = totalSize;
556
557 // Store snapshot
558 {
559 std::lock_guard<std::mutex> lock(impl_->mutex);
560 impl_->snapshots[gameId].push_back(snapshot);
561
562 // Prune old snapshots if needed (use while to handle cases where
563 // the list is already multiple entries over the limit)
564 while (impl_->maxSnapshotsPerGame > 0 &&
565 static_cast<int>(impl_->snapshots[gameId].size()) > impl_->maxSnapshotsPerGame)
566 {
567 impl_->snapshots[gameId].erase(impl_->snapshots[gameId].begin());
568 }
569 }
570
571 return snapshot.id;
572}
573
574std::future<std::optional<std::string>>
575CloudSaveService::createSnapshotAsync(const std::string& gameId, const std::string& description)
576{
577 return std::async(std::launch::async, [this, gameId, description]()
578 { return createSnapshot(gameId, description); });
579}
580
581std::vector<SaveSnapshot> CloudSaveService::getSnapshots(const std::string& gameId) const
582{
583 std::lock_guard<std::mutex> lock(impl_->mutex);
584
585 auto it = impl_->snapshots.find(gameId);
586 if (it != impl_->snapshots.end())
587 {
588 // Return in reverse order (newest first)
589 std::vector<SaveSnapshot> result = it->second;
590 std::reverse(result.begin(), result.end());
591 return result;
592 }
593 return {};
594}
595
596std::optional<SaveSnapshot> CloudSaveService::getSnapshot(const std::string& snapshotId) const
597{
598 std::lock_guard<std::mutex> lock(impl_->mutex);
599
600 for (const auto& [gameId, snapshots] : impl_->snapshots)
601 {
602 for (const auto& snapshot : snapshots)
603 {
604 if (snapshot.id == snapshotId)
605 {
606 return snapshot;
607 }
608 }
609 }
610 return std::nullopt;
611}
612
613bool CloudSaveService::restoreSnapshot(const std::string& snapshotId, bool backupCurrent)
614{
615 auto snapshot = getSnapshot(snapshotId);
616 if (!snapshot)
617 {
618 return false;
619 }
620
621 auto location = getSaveLocation(snapshot->gameId);
622 if (!location)
623 {
624 return false;
625 }
626
627 // Backup current saves first
628 if (backupCurrent)
629 {
630 createSnapshot(snapshot->gameId, "Auto-backup before restore");
631 }
632
633 // Restore files from snapshot
634 std::filesystem::path snapshotDir = impl_->backupDir / snapshot->gameId / snapshotId;
635 // Use separate error codes — sharing one variable causes the second call to
636 // clear the first call's error, masking a failed canonicalization.
637 std::error_code canonEc1, canonEc2;
638 std::filesystem::path canonDestBase =
639 std::filesystem::weakly_canonical(location->localPath, canonEc2);
640 if (canonEc2)
641 {
642 Logger::error("[CloudSave] Cannot canonicalize save location, aborting restore");
643 return false;
644 }
645
646 for (const auto& file : snapshot->files)
647 {
648 // Validate relative path to prevent directory traversal
649 std::filesystem::path relPath(file.relativePath);
650 for (const auto& component : relPath)
651 {
652 if (component == "..")
653 {
654 Logger::error("[CloudSave] Rejected snapshot path with traversal: {}",
655 file.relativePath);
656 return false;
657 }
658 }
659
660 std::filesystem::path srcPath = snapshotDir / relPath;
661 std::filesystem::path destPath = location->localPath / relPath;
662
663 // Reject symlinks in the snapshot to prevent reading outside the backup dir.
664 std::error_code ec;
665 if (std::filesystem::is_symlink(srcPath, ec))
666 {
667 Logger::error("[CloudSave] Rejected symlink in snapshot: {}", srcPath.string());
668 continue;
669 }
670
671 // Validate destination is within the save location using path component
672 // check. Treat a canonicalization failure as a rejection (fail closed):
673 // skipping the check on error would let an unresolved path through.
674 std::filesystem::path canonDest = std::filesystem::weakly_canonical(destPath, ec);
675 if (ec)
676 {
677 Logger::error("[CloudSave] Could not canonicalize snapshot dest, rejecting: {}",
678 file.relativePath);
679 return false;
680 }
681 std::filesystem::path rel = std::filesystem::relative(canonDest, canonDestBase, ec);
682 if (ec || rel.empty() || *rel.begin() == "..")
683 {
684 Logger::error("[CloudSave] Rejected snapshot path outside save dir: {}",
685 file.relativePath);
686 return false;
687 }
688
689 createDirectories(destPath.parent_path());
690
691 std::filesystem::copy_file(srcPath, destPath,
692 std::filesystem::copy_options::overwrite_existing, ec);
693
694 if (ec)
695 {
696 return false;
697 }
698 }
699
700 return true;
701}
702
703bool CloudSaveService::deleteSnapshot(const std::string& snapshotId)
704{
705 std::lock_guard<std::mutex> lock(impl_->mutex);
706
707 for (auto& [gameId, snapshots] : impl_->snapshots)
708 {
709 auto it = std::find_if(snapshots.begin(), snapshots.end(),
710 [&snapshotId](const SaveSnapshot& s) { return s.id == snapshotId; });
711
712 if (it != snapshots.end())
713 {
714 // Remove directory
715 std::filesystem::path snapshotDir = impl_->backupDir / gameId / snapshotId;
716 std::error_code ec;
717 std::filesystem::remove_all(snapshotDir, ec);
718
719 snapshots.erase(it);
720 return true;
721 }
722 }
723 return false;
724}
725
726int CloudSaveService::pruneSnapshots(const std::string& gameId, int keepCount)
727{
728 std::lock_guard<std::mutex> lock(impl_->mutex);
729
730 auto it = impl_->snapshots.find(gameId);
731 if (it == impl_->snapshots.end())
732 {
733 return 0;
734 }
735
736 auto& snapshots = it->second;
737 if (static_cast<int>(snapshots.size()) <= keepCount)
738 {
739 return 0;
740 }
741
742 int safeKeepCount = std::max(0, keepCount);
743 int deleteCount = static_cast<int>(snapshots.size()) - safeKeepCount;
744 if (deleteCount <= 0)
745 return 0;
746
747 // Sort by timestamp (oldest first)
748 std::sort(snapshots.begin(), snapshots.end(), [](const SaveSnapshot& a, const SaveSnapshot& b)
749 { return a.timestamp < b.timestamp; });
750
751 // Delete oldest
752 for (size_t i = 0; i < static_cast<size_t>(deleteCount) && i < snapshots.size(); ++i)
753 {
754 std::filesystem::path snapshotDir = impl_->backupDir / gameId / snapshots[i].id;
755 std::error_code ec;
756 std::filesystem::remove_all(snapshotDir, ec);
757 }
758
759 snapshots.erase(snapshots.begin(), snapshots.begin() + deleteCount);
760 return deleteCount;
761}
762
763// ==============================================================================
764// Cloud Sync
765// ==============================================================================
766
767bool CloudSaveService::syncSaves(const std::string& gameId, SyncDirection direction,
768 const ProgressCallback& progressCallback,
769 const ConflictCallback& conflictCallback)
770{
771 impl_->cancelRequested = false;
772
773 auto location = getSaveLocation(gameId);
774 if (!location)
775 {
776 if (progressCallback)
777 {
778 SyncStatus status;
780 status.errorMessage = "Save location not registered";
781 progressCallback(status);
782 }
783 return false;
784 }
785
786 // For now, sync to custom directory if configured
787 if (impl_->customSyncDir.empty())
788 {
789 if (progressCallback)
790 {
791 SyncStatus status;
793 status.errorMessage = "No cloud sync directory configured";
794 progressCallback(status);
795 }
796 return false;
797 }
798
799 SyncStatus status;
801 if (progressCallback)
802 progressCallback(status);
803
804 // Scan local files
805 auto localFiles = scanSaveFiles(*location);
806
808 if (progressCallback)
809 progressCallback(status);
810
811 // Scan remote files
812 std::filesystem::path remotePath = impl_->customSyncDir / gameId;
813 createDirectories(remotePath);
814
815 SaveLocation remoteLocation = *location;
816 remoteLocation.localPath = remotePath;
817 auto remoteFiles = scanSaveFiles(remoteLocation);
818
819 // Build file maps for comparison
820 std::map<std::string, SaveFile> localMap;
821 std::map<std::string, SaveFile> remoteMap;
822
823 for (const auto& f : localFiles)
824 localMap[f.relativePath] = f;
825 for (const auto& f : remoteFiles)
826 remoteMap[f.relativePath] = f;
827
828 // Determine what needs syncing
829 std::vector<SaveFile> toUpload;
830 std::vector<SaveFile> toDownload;
831 std::vector<SyncConflict> conflicts;
832
833 for (const auto& [path, localFile] : localMap)
834 {
835 auto remoteIt = remoteMap.find(path);
836 if (remoteIt == remoteMap.end())
837 {
838 // File only exists locally
839 if (direction == SyncDirection::Upload || direction == SyncDirection::Bidirectional)
840 {
841 toUpload.push_back(localFile);
842 }
843 }
844 else
845 {
846 // File exists in both - check for conflict
847 const auto& remoteFile = remoteIt->second;
848 if (localFile.checksum != remoteFile.checksum)
849 {
850 SyncConflict conflict;
851 conflict.filePath = path;
852 conflict.localFile = localFile;
853 conflict.remoteFile = remoteFile;
854
855 ConflictResolution resolution = impl_->defaultResolution;
856 if (conflictCallback)
857 {
858 resolution = conflictCallback(conflict);
859 }
860
861 switch (resolution)
862 {
864 toUpload.push_back(localFile);
865 break;
867 toDownload.push_back(remoteFile);
868 break;
870 if (localFile.modifiedTime > remoteFile.modifiedTime)
871 toUpload.push_back(localFile);
872 else
873 toDownload.push_back(remoteFile);
874 break;
876 toUpload.push_back(localFile);
877 // Backup the remote version locally before it gets overwritten
878 {
879 std::filesystem::path backupPath = localFile.path;
880 backupPath += ".conflict";
881 std::error_code backupEc;
882 std::filesystem::copy_file(
883 remoteFile.path, backupPath,
884 std::filesystem::copy_options::overwrite_existing, backupEc);
885 if (backupEc)
886 {
888 "[CloudSave] KeepBoth: failed to save remote backup for {}: {}",
889 remoteFile.relativePath, backupEc.message());
890 }
891 else
892 {
893 Logger::info("[CloudSave] KeepBoth: saved remote version to {}",
894 backupPath.string());
895 }
896 }
897 break;
899 conflicts.push_back(conflict);
900 break;
901 }
902 }
903 }
904 }
905
906 // Check remote-only files
907 for (const auto& [path, remoteFile] : remoteMap)
908 {
909 if (localMap.find(path) == localMap.end())
910 {
911 if (direction == SyncDirection::Download || direction == SyncDirection::Bidirectional)
912 {
913 toDownload.push_back(remoteFile);
914 }
915 }
916 }
917
918 // Perform sync
919 status.filesTotal = static_cast<int>(toUpload.size() + toDownload.size());
920
921 // Upload
922 if (direction == SyncDirection::Upload || direction == SyncDirection::Bidirectional)
923 {
925 for (const auto& file : toUpload)
926 {
927 if (impl_->cancelRequested)
928 {
930 if (progressCallback)
931 progressCallback(status);
932 return false;
933 }
934
935 std::filesystem::path destPath = remotePath / file.relativePath;
936 createDirectories(destPath.parent_path());
937
938 std::error_code ec;
939 std::filesystem::copy_file(file.path, destPath,
940 std::filesystem::copy_options::overwrite_existing, ec);
941
942 status.filesProcessed++;
943 status.bytesTransferred += file.size;
944 status.currentFile = file.relativePath;
945 status.percentComplete =
946 status.filesTotal > 0
947 ? static_cast<int>(static_cast<int64_t>(status.filesProcessed) * 100 /
948 status.filesTotal)
949 : 100;
950 if (progressCallback)
951 progressCallback(status);
952 }
953 }
954
955 // Download
956 if (direction == SyncDirection::Download || direction == SyncDirection::Bidirectional)
957 {
959 for (const auto& file : toDownload)
960 {
961 if (impl_->cancelRequested)
962 {
964 if (progressCallback)
965 progressCallback(status);
966 return false;
967 }
968
969 std::filesystem::path destPath = location->localPath / file.relativePath;
970 createDirectories(destPath.parent_path());
971
972 std::error_code ec;
973 std::filesystem::copy_file(file.path, destPath,
974 std::filesystem::copy_options::overwrite_existing, ec);
975
976 status.filesProcessed++;
977 status.bytesTransferred += file.size;
978 status.currentFile = file.relativePath;
979 status.percentComplete =
980 status.filesTotal > 0
981 ? static_cast<int>(static_cast<int64_t>(status.filesProcessed) * 100 /
982 status.filesTotal)
983 : 100;
984 if (progressCallback)
985 progressCallback(status);
986 }
987 }
988
990 status.percentComplete = 100;
991 if (progressCallback)
992 progressCallback(status);
993
994 return conflicts.empty();
995}
996
997std::future<bool> CloudSaveService::syncSavesAsync(const std::string& gameId,
998 SyncDirection direction,
999 const ProgressCallback& progressCallback,
1000 const ConflictCallback& conflictCallback)
1001{
1002 return std::async(std::launch::async,
1003 [this, gameId, direction, progressCallback, conflictCallback]()
1004 { return syncSaves(gameId, direction, progressCallback, conflictCallback); });
1005}
1006
1007bool CloudSaveService::needsSync(const std::string& gameId) const
1008{
1009 auto location = getSaveLocation(gameId);
1010 if (!location || impl_->customSyncDir.empty())
1011 {
1012 return false;
1013 }
1014
1015 auto localFiles = scanSaveFiles(*location);
1016
1017 SaveLocation remoteLocation = *location;
1018 remoteLocation.localPath = impl_->customSyncDir / gameId;
1019 auto remoteFiles = scanSaveFiles(remoteLocation);
1020
1021 // Quick comparison
1022 if (localFiles.size() != remoteFiles.size())
1023 {
1024 return true;
1025 }
1026
1027 std::map<std::string, std::string> localChecksums;
1028 for (const auto& f : localFiles)
1029 {
1030 localChecksums[f.relativePath] = f.checksum;
1031 }
1032
1033 for (const auto& f : remoteFiles)
1034 {
1035 auto it = localChecksums.find(f.relativePath);
1036 if (it == localChecksums.end() || it->second != f.checksum)
1037 {
1038 return true;
1039 }
1040 }
1041
1042 return false;
1043}
1044
1045std::vector<SyncConflict> CloudSaveService::getPendingConflicts(const std::string& /*gameId*/) const
1046{
1047 // Not implemented - conflicts are resolved during sync
1048 return {};
1049}
1050
1051bool CloudSaveService::resolveConflict(const std::string& /*gameId*/,
1052 const std::string& /*filePath*/,
1053 ConflictResolution /*resolution*/)
1054{
1055 // Not implemented - conflicts are resolved during sync
1056 return false;
1057}
1058
1059// ==============================================================================
1060// Auto-Sync
1061// ==============================================================================
1062
1063void CloudSaveService::setAutoSync(const std::string& gameId, bool enabled)
1064{
1065 std::lock_guard<std::mutex> lock(impl_->mutex);
1066
1067 for (auto& loc : impl_->saveLocations)
1068 {
1069 if (loc.gameId == gameId)
1070 {
1071 loc.autoSync = enabled;
1072 saveSaveLocations();
1073 return;
1074 }
1075 }
1076}
1077
1078void CloudSaveService::onGameLaunch(const std::string& gameId)
1079{
1080 auto location = getSaveLocation(gameId);
1081 if (location && location->autoSync)
1082 {
1084 }
1085}
1086
1087void CloudSaveService::onGameExit(const std::string& gameId)
1088{
1089 auto location = getSaveLocation(gameId);
1090 if (location && location->autoSync)
1091 {
1092 // Create snapshot before uploading
1093 createSnapshot(gameId, "Auto-backup on exit");
1095 }
1096}
1097
1098// ==============================================================================
1099// Configuration
1100// ==============================================================================
1101
1102void CloudSaveService::setBackupDirectory(const std::filesystem::path& path)
1103{
1104 std::lock_guard<std::mutex> lock(impl_->mutex);
1105 impl_->backupDir = path;
1106 createDirectories(path);
1107}
1108
1109std::filesystem::path CloudSaveService::getBackupDirectory() const
1110{
1111 return impl_->backupDir;
1112}
1113
1114void CloudSaveService::setCustomSyncDirectory(const std::filesystem::path& path)
1115{
1116 std::lock_guard<std::mutex> lock(impl_->mutex);
1117 impl_->customSyncDir = path;
1118}
1119
1121{
1122 // defaultResolution is read mid-sync at synchronizeSaves (around line
1123 // 856) under impl_->mutex. Writing without the lock is a data race
1124 // per the C++ memory model — torn reads or stale values are
1125 // technically possible. setCustomSyncDirectory above already takes
1126 // the lock; mirror the pattern here so all setters are consistent.
1127 std::lock_guard<std::mutex> lock(impl_->mutex);
1128 impl_->defaultResolution = resolution;
1129}
1130
1132{
1133 // Same rationale as setDefaultConflictResolution — read at
1134 // pruneOldSnapshots time under impl_->mutex.
1135 std::lock_guard<std::mutex> lock(impl_->mutex);
1136 impl_->maxSnapshotsPerGame = count;
1137}
1138
1140{
1141 impl_->cancelRequested = true;
1142}
1143
1144// ==============================================================================
1145// Statistics
1146// ==============================================================================
1147
1148int64_t CloudSaveService::getTotalBackupSize(const std::string& gameId) const
1149{
1150 std::lock_guard<std::mutex> lock(impl_->mutex);
1151
1152 auto it = impl_->snapshots.find(gameId);
1153 if (it == impl_->snapshots.end())
1154 {
1155 return 0;
1156 }
1157
1158 int64_t total = 0;
1159 for (const auto& snapshot : it->second)
1160 {
1161 total += snapshot.totalSize;
1162 }
1163 return total;
1164}
1165
1167{
1168 std::lock_guard<std::mutex> lock(impl_->mutex);
1169
1170 int64_t total = 0;
1171 for (const auto& [gameId, snapshots] : impl_->snapshots)
1172 {
1173 for (const auto& snapshot : snapshots)
1174 {
1175 total += snapshot.totalSize;
1176 }
1177 }
1178 return total;
1179}
1180
1181int CloudSaveService::getSnapshotCount(const std::string& gameId) const
1182{
1183 std::lock_guard<std::mutex> lock(impl_->mutex);
1184
1185 auto it = impl_->snapshots.find(gameId);
1186 if (it != impl_->snapshots.end())
1187 {
1188 return static_cast<int>(it->second.size());
1189 }
1190 return 0;
1191}
1192
1193// ==============================================================================
1194// Private Methods
1195// ==============================================================================
1196
1197std::vector<SaveFile> CloudSaveService::scanSaveFiles(const SaveLocation& location) const
1198{
1199 std::vector<SaveFile> files;
1200
1201 if (!fileExists(location.localPath))
1202 {
1203 return files;
1204 }
1205
1206 auto paths = globFiles(location.localPath, location.pattern);
1207
1208 for (const auto& path : paths)
1209 {
1210 SaveFile file;
1211 file.path = path;
1212 file.relativePath = std::filesystem::relative(path, location.localPath).string();
1213 file.size = getFileSize(path);
1214 file.modifiedTime = getFileModTime(path);
1215 file.checksum = calculateChecksum(path);
1216
1217 // Check exclusions
1218 bool excluded = false;
1219 for (const auto& exclude : location.excludePatterns)
1220 {
1221 if (file.relativePath.find(exclude) != std::string::npos)
1222 {
1223 excluded = true;
1224 break;
1225 }
1226 }
1227
1228 if (!excluded)
1229 {
1230 files.push_back(file);
1231 }
1232 }
1233
1234 return files;
1235}
1236
1237std::string CloudSaveService::calculateChecksum(const std::filesystem::path& path) const
1238{
1239 // FNV-1a 64-bit hash over file contents for reliable change detection
1240 std::ifstream file(path, std::ios::binary);
1241 if (!file)
1242 return "";
1243
1244 constexpr uint64_t fnvOffsetBasis = 14695981039346656037ULL;
1245 constexpr uint64_t fnvPrime = 1099511628211ULL;
1246 uint64_t hash = fnvOffsetBasis;
1247
1248 char buf[65536];
1249 while (file.read(buf, sizeof(buf)) || file.gcount() > 0)
1250 {
1251 for (std::streamsize i = 0; i < file.gcount(); ++i)
1252 {
1253 hash ^= static_cast<uint8_t>(buf[i]);
1254 hash *= fnvPrime;
1255 }
1256 }
1257
1258 char result[32];
1259 snprintf(result, sizeof(result), "%016llx", static_cast<unsigned long long>(hash));
1260 return result;
1261}
1262
1263bool CloudSaveService::copyFiles(const std::vector<SaveFile>& files,
1264 const std::filesystem::path& destDir,
1265 const ProgressCallback& callback)
1266{
1267 SyncStatus status;
1268 status.filesTotal = static_cast<int>(files.size());
1269
1270 for (const auto& file : files)
1271 {
1272 if (impl_->cancelRequested)
1273 {
1274 return false;
1275 }
1276
1277 std::filesystem::path destPath = destDir / file.relativePath;
1278 createDirectories(destPath.parent_path());
1279
1280 std::error_code ec;
1281 std::filesystem::copy_file(file.path, destPath,
1282 std::filesystem::copy_options::overwrite_existing, ec);
1283
1284 if (ec)
1285 {
1287 status.errorMessage = "Failed to copy: " + file.relativePath;
1288 if (callback)
1289 callback(status);
1290 return false;
1291 }
1292
1293 status.filesProcessed++;
1294 status.bytesTransferred += file.size;
1295 status.currentFile = file.relativePath;
1296 if (callback)
1297 callback(status);
1298 }
1299
1300 return true;
1301}
1302
1303std::string CloudSaveService::generateSnapshotId() const
1304{
1305 return generateUUID();
1306}
1307
1308void CloudSaveService::loadSaveLocations()
1309{
1310 std::filesystem::path configPath = getDataDirectory() / "save_locations.conf";
1311 if (!fileExists(configPath))
1312 {
1313 return;
1314 }
1315
1316 std::ifstream file(configPath);
1317 std::string line;
1318 SaveLocation current;
1319
1320 while (std::getline(file, line))
1321 {
1322 if (line.empty() || line[0] == '#')
1323 continue;
1324
1325 if (line[0] == '[')
1326 {
1327 // New section
1328 if (!current.gameId.empty())
1329 {
1330 impl_->saveLocations.push_back(current);
1331 }
1332 current = SaveLocation();
1333 current.gameId = line.substr(1, line.size() - 2);
1334 }
1335 else
1336 {
1337 auto eqPos = line.find('=');
1338 if (eqPos != std::string::npos)
1339 {
1340 std::string key = line.substr(0, eqPos);
1341 std::string value = line.substr(eqPos + 1);
1342
1343 if (key == "name")
1344 current.gameName = value;
1345 else if (key == "path")
1346 current.localPath = value;
1347 else if (key == "pattern")
1348 current.pattern = value;
1349 else if (key == "autoSync")
1350 current.autoSync = (value == "true");
1351 else if (key == "isWinePrefix")
1352 current.isWinePrefix = (value == "true");
1353 else if (key == "prefixPath")
1354 current.prefixPath = value;
1355 }
1356 }
1357 }
1358
1359 if (!current.gameId.empty())
1360 {
1361 impl_->saveLocations.push_back(current);
1362 }
1363}
1364
1365void CloudSaveService::saveSaveLocations() const
1366{
1367 std::filesystem::path configPath = getDataDirectory() / "save_locations.conf";
1368 std::filesystem::path tmpPath = std::filesystem::path(configPath.string() + ".tmp");
1369
1370 {
1371 std::ofstream file(tmpPath);
1372 if (!file)
1373 {
1374 Logger::error("[CloudSave] Failed to open tmp config for write: {}", tmpPath.string());
1375 return;
1376 }
1377
1378 for (const auto& loc : impl_->saveLocations)
1379 {
1380 file << "[" << loc.gameId << "]\n";
1381 file << "name=" << loc.gameName << "\n";
1382 file << "path=" << loc.localPath.string() << "\n";
1383 file << "pattern=" << loc.pattern << "\n";
1384 file << "autoSync=" << (loc.autoSync ? "true" : "false") << "\n";
1385 file << "isWinePrefix=" << (loc.isWinePrefix ? "true" : "false") << "\n";
1386 if (!loc.prefixPath.empty())
1387 {
1388 file << "prefixPath=" << loc.prefixPath.string() << "\n";
1389 }
1390 file << "\n";
1391 }
1392 }
1393
1394 std::error_code ec;
1395 std::filesystem::rename(tmpPath, configPath, ec);
1396 if (ec)
1397 {
1398 Logger::error("[CloudSave] Failed to atomically replace config: {}", ec.message());
1399 std::filesystem::remove(tmpPath, ec);
1400 }
1401}
1402
1403void CloudSaveService::loadSnapshots()
1404{
1405 if (!fileExists(impl_->backupDir))
1406 {
1407 return;
1408 }
1409
1410 std::error_code ec;
1411 for (const auto& gameDir : std::filesystem::directory_iterator(impl_->backupDir, ec))
1412 {
1413 if (!gameDir.is_directory())
1414 continue;
1415
1416 std::string gameId = gameDir.path().filename().string();
1417
1418 for (const auto& snapshotDir : std::filesystem::directory_iterator(gameDir.path(), ec))
1419 {
1420 if (!snapshotDir.is_directory())
1421 continue;
1422
1423 SaveSnapshot snapshot;
1424 snapshot.id = snapshotDir.path().filename().string();
1425 snapshot.gameId = gameId;
1426 snapshot.timestamp = getFileModTime(snapshotDir.path());
1427
1428 // Scan files in snapshot
1429 for (const auto& entry :
1430 std::filesystem::recursive_directory_iterator(snapshotDir.path(), ec))
1431 {
1432 if (entry.is_regular_file())
1433 {
1434 SaveFile file;
1435 file.path = entry.path();
1436 file.relativePath =
1437 std::filesystem::relative(entry.path(), snapshotDir.path()).string();
1438 file.size = getFileSize(entry.path());
1439 file.modifiedTime = getFileModTime(entry.path());
1440 snapshot.files.push_back(file);
1441 snapshot.totalSize += file.size;
1442 }
1443 }
1444
1445 impl_->snapshots[gameId].push_back(snapshot);
1446 }
1447
1448 // Sort by timestamp
1449 auto& snapshots = impl_->snapshots[gameId];
1450 std::sort(snapshots.begin(), snapshots.end(),
1451 [](const SaveSnapshot& a, const SaveSnapshot& b)
1452 { return a.timestamp < b.timestamp; });
1453 }
1454}
void setCustomSyncDirectory(const std::filesystem::path &path)
Set custom sync directory.
bool needsSync(const std::string &gameId) const
Check if sync is needed.
void setBackupDirectory(const std::filesystem::path &path)
Set the local backup directory.
std::function< void(const SyncStatus &)> ProgressCallback
bool resolveConflict(const std::string &gameId, const std::string &filePath, ConflictResolution resolution)
Resolve a conflict.
std::optional< std::string > createSnapshot(const std::string &gameId, const std::string &description="")
Create a snapshot of current saves.
std::vector< SaveSnapshot > getSnapshots(const std::string &gameId) const
List all snapshots for a game.
void setAutoSync(const std::string &gameId, bool enabled)
Enable auto-sync for a game.
void setMaxSnapshotsPerGame(int count)
Set maximum snapshots per game.
bool restoreSnapshot(const std::string &snapshotId, bool backupCurrent=true)
Restore saves from a snapshot.
int getSnapshotCount(const std::string &gameId) const
Get snapshot count for a game.
void onGameLaunch(const std::string &gameId)
Called when a game is about to launch.
void onGameExit(const std::string &gameId)
Called when a game exits.
bool updateSaveLocation(const SaveLocation &location)
Update an existing save location.
int64_t getTotalBackupSize() const
Get total backup size for all games.
std::vector< SyncConflict > getPendingConflicts(const std::string &gameId) const
Get pending conflicts.
bool deleteSnapshot(const std::string &snapshotId)
Delete a snapshot.
bool registerSaveLocation(const SaveLocation &location)
Register a game's save location.
void setDefaultConflictResolution(ConflictResolution resolution)
Set default conflict resolution.
std::future< bool > syncSavesAsync(const std::string &gameId, SyncDirection direction=SyncDirection::Bidirectional, const ProgressCallback &progressCallback=nullptr, const ConflictCallback &conflictCallback=nullptr)
Sync asynchronously.
std::vector< SaveLocation > getSaveLocations() const
Get all registered save locations.
void cancelOperation()
Cancel ongoing operation.
std::optional< SaveLocation > getSaveLocation(const std::string &gameId) const
Get save location for a specific game.
std::function< ConflictResolution(const SyncConflict &)> ConflictCallback
std::future< std::optional< std::string > > createSnapshotAsync(const std::string &gameId, const std::string &description="")
Create snapshot asynchronously.
std::optional< SaveSnapshot > getSnapshot(const std::string &snapshotId) const
Get a specific snapshot.
std::vector< SaveLocation > detectSaveLocation(const std::string &gameName, const std::filesystem::path &prefixPath={}) const
Detect save location for a game.
bool removeSaveLocation(const std::string &gameId)
Remove a save location registration.
bool syncSaves(const std::string &gameId, SyncDirection direction=SyncDirection::Bidirectional, const ProgressCallback &progressCallback=nullptr, const ConflictCallback &conflictCallback=nullptr)
Sync saves with cloud storage.
int pruneSnapshots(const std::string &gameId, int keepCount=10)
Delete old snapshots.
std::filesystem::path getBackupDirectory() const
Get the backup directory.
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
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
std::string syncDirectionName(SyncDirection direction)
Get human-readable sync direction name.
std::string cloudBackendName(CloudBackend backend)
Get human-readable backend name.
SyncDirection
Direction of sync operation.
@ Download
Cloud -> Local.
@ Upload
Local -> Cloud.
@ Bidirectional
Two-way sync.
ConflictResolution
How to resolve sync conflicts.
@ AskUser
Prompt user to choose.
@ UseRemote
Keep remote version.
@ UseNewest
Use whichever is newer.
@ KeepBoth
Keep both versions (create backup).
@ UseLocal
Keep local version.
CloudBackend
Supported cloud storage backends.
@ Steam
Steam Cloud.
@ None
Local backup only.
@ Custom
Custom sync location (e.g., Syncthing, Nextcloud).
@ GOG
GOG Galaxy Cloud.
std::chrono::system_clock::time_point getFileModTime(const std::filesystem::path &path)
int64_t getFileSize(const std::filesystem::path &path)
std::vector< std::filesystem::path > globFiles(const std::filesystem::path &root, const std::string &pattern)
std::string formatTime(std::chrono::system_clock::time_point tp)
bool createDirectories(const std::filesystem::path &path)
bool fileExists(const std::filesystem::path &path)
bool fileExists(const std::filesystem::path &path)
static std::string generateUUID()
std::map< std::string, std::vector< SaveSnapshot > > snapshots
std::vector< SaveLocation > saveLocations
std::filesystem::path backupDir
std::atomic< bool > cancelRequested
ConflictResolution defaultResolution
std::filesystem::path customSyncDir
Information about a specific save file.
std::string getFormattedSize() const
std::string getFormattedTime() const
std::chrono::system_clock::time_point modifiedTime
std::string relativePath
Path relative to save root.
int64_t size
File size in bytes.
std::string checksum
SHA-256 hash for comparison.
std::filesystem::path path
Full path to file.
Information about a game's save location.
bool autoSync
Auto-sync on launch/exit.
std::filesystem::path localPath
Local save directory.
std::filesystem::path prefixPath
Wine prefix path if applicable.
std::string gameName
Display name.
std::string pattern
File pattern (e.g., "*.sav", "**‍/*").
std::string gameId
Internal game ID.
std::vector< std::string > excludePatterns
Patterns to exclude.
bool isWinePrefix
Save is in a Wine prefix.
A complete snapshot of a game's saves at a point in time.
std::vector< SaveFile > files
Files in this snapshot.
std::string gameName
Game display name.
int64_t totalSize
Total size of all files.
std::string getFormattedTime() const
std::chrono::system_clock::time_point timestamp
std::string id
Unique snapshot ID.
std::string gameId
Game this belongs to.
std::string getFormattedSize() const
bool isAutomatic
True if auto-created.
std::string description
User-provided description.
Details about a sync conflict.
std::string filePath
Status of sync operation.
std::string errorMessage
int64_t bytesTransferred
std::string currentFile
std::string getStateStr() const