Stores: GOG and Epic cloud saves

Ported from Bannerlator's cloud-save managers. Before every launch the
cloud copy comes down where it is newer: droiddeck-store-launch asks the
app and waits up to 15 s. For a store game with cloud saves it tells the
compat tool so, and the tool waits for Proton instead of exec'ing it,
then asks for the upload without waiting. Newest wins per file, with an
MD5 check so a file the game only touched is not sent again; a download
first copies the folder to the app's storage (last three kept).

The save folder is GOG's remote-config location template (by the game's
Galaxy client id) or Epic's CloudSaveFolder catalog attribute, expanded
inside the game's Proton prefix or install folder by CloudSavePaths,
which refuses a path that leaves its boundary. GOG uploads with a token
issued to the game's own client (its secret is kept at install from now
on), Epic with signed write links. The GOG and Epic cards get a Cloud
saves switch kept in the sidecar; Manage saves shows the last sync with
Upload and Download, or No cloud saves.
This commit is contained in:
The412Banner committed 2026-10-09 05:39:40 -04:00
1 parent 935b70c585
commit 1580e3ee64
17 files changed
+853 -41

No files matched your search

@@ -0,0 +1,84 @@
/*
* Cloud-save folder resolution for GOG and Epic games, after Bannerlator's GogCloudSavePaths and
* EpicCloudSavePaths (device-proven there, August 2026): a store's save-location template expanded
* against the game's Proton prefix and its install folder.
*/
package com.droiddeck.launcher.stores
import java.io.File
/**
* Where a store keeps a game's saves on Windows, made concrete inside this game's Proton prefix.
*
* GOG gives a template per game in its public remote-config (`cloudStorage.locations[].location`):
* a leading `<?TOKEN?>` (or `%TOKEN%`) and a path, e.g. ELDERBORN's
* `<?APPLICATION_DATA_LOCAL_LOW?>/Hyperstrange/ELDERBORN`. Epic gives `CloudSaveFolder` in the
* game's catalog attributes: a leading `{Token}`, with `{EpicId}` / `{AppName}` inside, e.g.
* `{AppData}/Game/Saved/SaveGames`. Profile tokens map under the prefix's Wine user
* (`drive_c/users/steamuser`), the install tokens to the game's folder. The path is walked against
* what is on disk case-insensitively; a result outside its boundary is refused, never guessed.
*/
object CloudSavePaths {
/** The Wine user every prefix has (Proton's). */
fun profile(prefix: File): File = File(prefix, "drive_c/users/steamuser")
/** Expands a GOG location template; null for an unknown token or an escape. */
fun gog(template: String, prefix: File, install: File): File? {
val norm = template.replace('\\', '/').trim().trimStart('/')
val match = Regex("^(<\\?[^?>]+\\?>|%[^%]+%)").find(norm) ?: return null
val token = match.groupValues[1].trim('<', '>', '?', '%').uppercase()
val profile = profile(prefix)
val (base, boundary) = when (token) {
"INSTALL" -> install to install
"SAVED_GAMES" -> File(profile, "Saved Games") to profile
"DOCUMENTS" -> File(profile, "Documents") to profile
"APPLICATION_DATA_LOCAL", "LOCALAPPDATA" -> File(profile, "AppData/Local") to profile
"APPLICATION_DATA_LOCAL_LOW" -> File(profile, "AppData/LocalLow") to profile
"APPLICATION_DATA_ROAMING", "APPDATA" -> File(profile, "AppData/Roaming") to profile
"USERPROFILE" -> profile to profile
"PROGRAMDATA" -> File(prefix, "drive_c/ProgramData").let { it to it }
else -> return null
}
return walk(base, boundary, norm.substring(match.value.length), fuzzy = false)
}
/** Expands an Epic CloudSaveFolder; null for an unknown token or an escape. */
fun epic(template: String, prefix: File, install: File, accountId: String, appName: String): File? {
val norm = template.replace('\\', '/').trim().trimStart('/')
val match = Regex("^\\{([^}]+)\\}").find(norm) ?: return null
val profile = profile(prefix)
val (base, boundary) = when (match.groupValues[1].lowercase()) {
"installdir" -> install to install
"userprofile" -> profile to profile
"userdir" -> File(profile, "Documents") to profile
"usersavedgames" -> File(profile, "Saved Games") to profile
"appdata", "localappdata" -> File(profile, "AppData/Local") to profile
"roamingappdata" -> File(profile, "AppData/Roaming") to profile
else -> return null
}
val rest = norm.substring(match.value.length)
.replace("{epicid}", accountId, ignoreCase = true)
.replace("{appname}", appName, ignoreCase = true)
return walk(base, boundary, rest, fuzzy = true)
}
/**
* Each segment matched against the folder's entries case-insensitively (and, for Epic, by letters
* and digits alone when that names exactly one), else taken as written - a download creates it.
*/
private fun walk(base: File, boundary: File, rest: String, fuzzy: Boolean): File? {
var dir = base
for (seg in rest.trimStart('/').split('/').filter { it.isNotEmpty() && it != "." }) {
if (seg == "..") { dir = dir.parentFile ?: return null; continue }
val kids = dir.listFiles()
val existing = kids?.firstOrNull { it.name.equals(seg, ignoreCase = true) }
?: if (fuzzy) kids?.filter { squash(it.name) == squash(seg) && squash(seg).isNotEmpty() }?.singleOrNull() else null
dir = existing ?: File(dir, seg)
}
val bound = runCatching { boundary.canonicalPath }.getOrNull() ?: return null
val dest = runCatching { dir.canonicalPath }.getOrNull() ?: return null
return if (dest == bound || dest.startsWith(bound + File.separator)) dir else null
}
private fun squash(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
}
@@ -0,0 +1,262 @@
package com.droiddeck.launcher.stores
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.epic.EpicApiClient
import com.droiddeck.launcher.stores.epic.EpicCredentialStore
import com.droiddeck.launcher.stores.epic.EpicPrefs
import com.droiddeck.launcher.stores.gog.GogAuth
import com.droiddeck.launcher.stores.gog.GogPrefs
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import java.security.MessageDigest
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import org.json.JSONObject
/**
* GOG and Epic cloud saves for an installed store game: before a launch the cloud copy is brought
* down where it is newer, after the game exits what changed goes up - newest wins, file by file.
* Before a download overwrites anything, the folder is copied to the app's storage (the last
* [BACKUPS] per game). Both launch paths reach it: the compat tool's request from
* droiddeck-store-launch ([StoreLaunchRequests]) for every launch, and the Games tab's Manage saves.
*
* The save folder: GOG's remote-config location template (by the game's Galaxy client id) or
* Epic's CloudSaveFolder catalog attribute, cached per game, made concrete by [CloudSavePaths]
* inside the game's Proton prefix. A game whose store gives none has no cloud saves.
*/
object CloudSaves {
private const val TAG = "CloudSaves"
private const val BACKUPS = 3
private const val PARALLEL = 6
/** What a sync did, for the log and the Manage saves row. */
class Result(val ok: Boolean, val files: Int, val bytes: Long, val reason: String) {
val line: String get() = "files=$files bytes=$bytes result=${if (ok) "ok" else reason}"
}
/** A game's cloud state for the Manage saves row. */
class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String)
private fun game(context: Context, store: Store, id: String): Pair<File, StoreGameSidecar>? =
StoreInstallRoot.gameFolders(context).firstNotNullOfOrNull { f ->
StoreGameSidecar.read(f)?.takeIf { it.store == store && it.id == id && it.isInstalled }?.let { f to it }
}
/** The game's prefix: compatdata/<its shortcut appid>/pfx, wherever that library is. */
fun prefix(context: Context, folder: File): File? {
val appId = AddedGames.scan(context).firstOrNull { it.folder.absolutePath == folder.absolutePath }?.appId ?: return null
return Library.protonPrefix(context, appId and 0xFFFFFFFFL)
}
private fun prefs(context: Context, store: Store) = if (store == Store.GOG) GogPrefs.get(context) else EpicPrefs.get(context)
fun lastSync(context: Context, store: Store, id: String): Long = prefs(context, store).getLong("cloud_sync_$id", 0L)
private fun markSynced(context: Context, store: Store, id: String) = prefs(context, store).edit().putLong("cloud_sync_$id", System.currentTimeMillis()).apply()
// ---- the save folder ------------------------------------------------------------------------
/** The store's template for this game: cached, else fetched; "" when the store gives none, null when it could not be asked. */
fun template(context: Context, store: Store, id: String, folder: File, sidecar: StoreGameSidecar): String? {
val p = prefs(context, store)
if (p.contains("cloud_template_$id")) return p.getString("cloud_template_$id", "")
val fetched = when (store) {
Store.GOG -> gogTemplate(context, id, folder)
Store.EPIC -> {
val token = EpicCredentialStore.getValidAccessToken(context) ?: return null
val ns = sidecar.extra["namespace"].orEmpty()
val item = sidecar.extra["catalogItemId"].orEmpty()
if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder")
}
Store.AMAZON -> ""
} ?: return null
p.edit().putString("cloud_template_$id", fetched).apply()
Log.i(TAG, "cloud ${store.id} $id template ${if (fetched.isEmpty()) "none" else "found"}")
return fetched
}
private fun gogClientId(context: Context, id: String, folder: File): String? =
GogPrefs.get(context).getString("client_id_$id", null)?.ifEmpty { null }
?: runCatching { JSONObject(File(folder, "goggame-$id.info").readText()).optString("clientId").ifEmpty { null } }.getOrNull()
/** GOG's public remote-config: `content.Windows.cloudStorage.locations`, the one named "saves" first. */
private fun gogTemplate(context: Context, id: String, folder: File): String? {
val clientId = gogClientId(context, id, folder) ?: return ""
return try {
val c = URL("https://remote-config.gog.com/components/galaxy_client/clients/$clientId?component_version=2.0.45").openConnection() as HttpURLConnection
c.connectTimeout = 15_000; c.readTimeout = 15_000
c.setRequestProperty("User-Agent", "GOG Galaxy")
if (c.responseCode !in 200..299) { c.disconnect(); return null }
val cloud = JSONObject(c.inputStream.bufferedReader().readText()).optJSONObject("content")?.optJSONObject("Windows")?.optJSONObject("cloudStorage")
c.disconnect()
if (cloud?.optBoolean("enabled", false) != true) return ""
val locations = cloud.optJSONArray("locations") ?: return ""
val all = (0 until locations.length()).mapNotNull { locations.optJSONObject(it) }
(all.firstOrNull { it.optString("name").equals("saves", true) } ?: all.firstOrNull())?.optString("location").orEmpty()
} catch (e: Exception) {
Log.w(TAG, "gog remote-config: ${e.javaClass.simpleName}")
null
}
}
/** The concrete save folder in the prefix, or null with why. */
private fun saveFolder(context: Context, store: Store, id: String): Pair<File?, String> {
val (folder, sidecar) = game(context, store, id) ?: return null to "not-installed"
val template = template(context, store, id, folder, sidecar) ?: return null to "store-unreachable"
if (template.isEmpty()) return null to "no-cloud-saves"
val pfx = prefix(context, folder) ?: return null to "no-prefix"
val dir = when (store) {
Store.GOG -> CloudSavePaths.gog(template, pfx, folder)
Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id)
Store.AMAZON -> null
}
return dir to (if (dir == null) "unresolved" else "ok")
}
fun status(context: Context, store: Store, id: String): Status {
val (dir, reason) = saveFolder(context, store, id)
return Status(reason != "no-cloud-saves" && reason != "not-installed", dir, lastSync(context, store, id), reason)
}
// ---- transport ------------------------------------------------------------------------------
private fun transport(context: Context, store: Store, id: String, folder: File): CloudTransport? = when (store) {
Store.GOG -> {
val account = StoreAccounts.read(context, Store.GOG)
val userId = account?.optString("user_id").orEmpty()
val galaxy = GogAuth.validToken(context)
val clientId = gogClientId(context, id, folder)
if (userId.isEmpty() || galaxy == null || clientId == null) null
else GogCloud(userId, clientId, gogScopedToken(context, id, clientId, account?.optString("refresh_token").orEmpty()) ?: galaxy)
}
Store.EPIC -> {
val token = EpicCredentialStore.getValidAccessToken(context)
val account = EpicCredentialStore.load(context)?.accountId.orEmpty()
if (token == null || account.isEmpty()) null else EpicCloud(account, id, token)
}
Store.AMAZON -> null
}
/** GOG cloud storage wants a token issued to the game's own client: the Galaxy refresh token, exchanged with the game's id and secret. */
private fun gogScopedToken(context: Context, id: String, clientId: String, refresh: String): String? {
val secret = GogPrefs.get(context).getString("client_secret_$id", null)?.ifEmpty { null } ?: return null
if (refresh.isEmpty()) return null
return try {
val enc = { s: String -> java.net.URLEncoder.encode(s, "UTF-8") }
val c = URL("https://auth.gog.com/token?client_id=${enc(clientId)}&client_secret=${enc(secret)}&grant_type=refresh_token&refresh_token=${enc(refresh)}").openConnection() as HttpURLConnection
c.connectTimeout = 15_000; c.readTimeout = 15_000
c.setRequestProperty("User-Agent", "GOG Galaxy")
if (c.responseCode != 200) { c.disconnect(); return null }
JSONObject(c.inputStream.bufferedReader().readText()).optString("access_token").ifEmpty { null }.also { c.disconnect() }
} catch (e: Exception) { null }
}
// ---- sync -----------------------------------------------------------------------------------
/** Cloud → device where the cloud copy is newer. Blocking. */
fun download(context: Context, store: Store, id: String): Result = run(context, store, id, "down") { dir, cloud -> pull(context, store, id, dir, cloud) }
/** Device → cloud where the local copy is newer. Blocking. */
fun upload(context: Context, store: Store, id: String): Result = run(context, store, id, "up") { dir, cloud -> push(dir, cloud) }
private fun run(context: Context, store: Store, id: String, way: String, body: (File, CloudTransport) -> Result): Result {
val result = try {
val (folder, sidecar) = game(context, store, id) ?: return done(store, id, way, Result(false, 0, 0, "not-installed"))
if (!sidecar.cloud) return done(store, id, way, Result(true, 0, 0, "off"))
val (dir, reason) = saveFolder(context, store, id)
if (dir == null) Result(reason == "no-cloud-saves", 0, 0, reason)
else {
val cloud = transport(context, store, id, folder) ?: return done(store, id, way, Result(false, 0, 0, "signed-out"))
body(dir, cloud).also { if (it.ok) markSynced(context, store, id) }
}
} catch (e: NoCloudSaves) {
prefs(context, store).edit().putString("cloud_template_$id", "").apply()
Result(true, 0, 0, "no-cloud-saves")
} catch (e: Exception) {
Result(false, 0, 0, e.javaClass.simpleName)
}
return done(store, id, way, result)
}
private fun done(store: Store, id: String, way: String, r: Result): Result {
Log.i(TAG, "cloud ${store.id} $id $way ${r.line}")
StoresState.logLine("cloud ${store.id} $id $way ${r.line}")
return r
}
private fun localFiles(dir: File): Map<String, File> =
if (!dir.isDirectory) emptyMap()
else dir.walkTopDown().filter { it.isFile }.associateBy { it.relativeTo(dir).path.replace(File.separatorChar, '/') }
private fun md5(f: File): String? = runCatching {
val md = MessageDigest.getInstance("MD5")
f.inputStream().use { input -> val buf = ByteArray(8192); while (true) { val n = input.read(buf); if (n < 0) break; md.update(buf, 0, n) } }
md.digest().joinToString("") { "%02x".format(it) }
}.getOrNull()
private fun pull(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport): Result {
val remote = cloud.list()
if (remote.isEmpty()) return Result(true, 0, 0, "empty")
val local = localFiles(dir)
val pool = Executors.newFixedThreadPool(PARALLEL, com.droiddeck.launcher.stores.download.DownloadQueue.workerFactory("cloud"))
val wanted = java.util.concurrent.ConcurrentLinkedQueue<CloudFile>()
for (f in remote) pool.execute {
val mine = local[f.name]
if (mine == null) { wanted.add(f); return@execute }
cloud.details(f)
if (f.md5 != null && f.md5.equals(md5(mine), ignoreCase = true)) return@execute
if (f.modifiedMs > mine.lastModified()) wanted.add(f)
}
pool.shutdown(); pool.awaitTermination(2, TimeUnit.MINUTES)
if (wanted.isEmpty()) return Result(true, 0, 0, "up-to-date")
backup(context, store, id, dir)
var bytes = 0L
for (f in wanted) {
val (data, modified) = cloud.get(f)
val dest = File(dir, f.name)
if (!dest.canonicalPath.startsWith(dir.canonicalPath + File.separator)) continue
dest.parentFile?.mkdirs()
dest.writeBytes(data)
if (modified > 0) dest.setLastModified(modified)
bytes += data.size
}
return Result(true, wanted.size, bytes, "ok")
}
private fun push(dir: File, cloud: CloudTransport): Result {
val local = localFiles(dir)
if (local.isEmpty()) return Result(true, 0, 0, "nothing-local")
val remote = cloud.list().associateBy { it.name }
val pool = Executors.newFixedThreadPool(PARALLEL, com.droiddeck.launcher.stores.download.DownloadQueue.workerFactory("cloud"))
val changed = java.util.concurrent.ConcurrentHashMap<String, File>()
for ((name, file) in local) pool.execute {
val r = remote[name]
if (r == null) { changed[name] = file; return@execute }
cloud.details(r)
if (r.md5 != null && r.md5.equals(md5(file), ignoreCase = true)) {
// Same bytes, touched by the game: line the time up so the next sync skips it cheaply.
if (r.modifiedMs > 0) file.setLastModified(r.modifiedMs)
return@execute
}
if (r.modifiedMs < 0 || file.lastModified() > r.modifiedMs) changed[name] = file
}
pool.shutdown(); pool.awaitTermination(2, TimeUnit.MINUTES)
if (changed.isEmpty()) return Result(true, 0, 0, "up-to-date")
val data = changed.mapValues { it.value.readBytes() }
val stamped = cloud.put(data)
for ((name, t) in stamped) if (t > 0) changed[name]?.setLastModified(t)
return Result(true, stamped.size, data.values.sumOf { it.size.toLong() }, "ok")
}
/** The folder as it is, copied before a download changes it; the last [BACKUPS] are kept. */
private fun backup(context: Context, store: Store, id: String, dir: File) {
if (!dir.isDirectory || dir.listFiles().isNullOrEmpty()) return
val root = File(context.filesDir, "stores/cloud-backups/${store.id}-${id.replace(Regex("[^A-Za-z0-9._-]"), "_")}")
runCatching { dir.copyRecursively(File(root, System.currentTimeMillis().toString()), overwrite = true) }
root.listFiles()?.sortedByDescending { it.name }?.drop(BACKUPS)?.forEach { it.deleteRecursively() }
}
}
@@ -0,0 +1,191 @@
/*
* The two stores' cloud-save services, after Bannerlator's GogCloudSaveManager and
* EpicCloudSaveManager (device-proven there, August 2026): GOG's cloudstorage (one object per
* file, Last-Modified and an MD5 ETag on a HEAD) and Epic's savesync data storage (a listing with
* lastModified and signed read links; signed write links asked for per upload).
*/
package com.droiddeck.launcher.stores
import java.io.ByteArrayOutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone
import org.json.JSONArray
import org.json.JSONObject
/** One file in a game's cloud: its key (a path with '/'), when it was written (-1 unknown) and its MD5 when known. */
class CloudFile(val name: String, var modifiedMs: Long, var md5: String? = null, val readLink: String? = null)
/** A store's cloud for one game. Every call is blocking network. */
interface CloudTransport {
fun list(): List<CloudFile>
/** Fills in [CloudFile.modifiedMs] / [CloudFile.md5] where the listing left them out. */
fun details(file: CloudFile) {}
/** The file's bytes and its cloud time (-1 unknown). */
fun get(file: CloudFile): Pair<ByteArray, Long>
/** Writes [files] (key → bytes); the cloud times assigned, where the service says (-1 unknown). */
fun put(files: Map<String, ByteArray>): Map<String, Long>
}
private const val TIMEOUT = 30_000
private fun open(url: String, method: String, token: String?, ua: String): HttpURLConnection =
(URL(url).openConnection() as HttpURLConnection).apply {
requestMethod = method
connectTimeout = TIMEOUT
readTimeout = TIMEOUT
setRequestProperty("User-Agent", ua)
if (token != null) setRequestProperty("Authorization", "Bearer $token")
}
private fun HttpURLConnection.body(): ByteArray = inputStream.use { input ->
ByteArrayOutputStream().also { input.copyTo(it) }.toByteArray()
}
private fun httpDate(s: String?): Long = try {
SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US).apply { timeZone = TimeZone.getTimeZone("GMT") }.parse(s!!.trim())?.time ?: -1L
} catch (e: Exception) { -1L }
internal fun isoDate(s: String?): Long {
if (s == null || s.length < 19) return -1L
return try {
java.util.Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply {
clear()
set(s.substring(0, 4).toInt(), s.substring(5, 7).toInt() - 1, s.substring(8, 10).toInt(),
s.substring(11, 13).toInt(), s.substring(14, 16).toInt(), s.substring(17, 19).toInt())
}.timeInMillis
} catch (e: Exception) { -1L }
}
/** Thrown when the store says the game has no cloud saves for this client. */
class NoCloudSaves : Exception("no cloud saves")
/** GOG cloudstorage: `/v1/<userId>/<clientId>[/<key>]`. */
class GogCloud(private val userId: String, private val clientId: String, private val token: String) : CloudTransport {
private val base = "https://cloudstorage.gog.com/v1/$userId/$clientId"
private val ua = "GOG Galaxy"
/** A path segment: '+' from a space is wrong in a path (it stores a second, '+'-named copy). */
private fun key(name: String) = URLEncoder.encode(name, "UTF-8").replace("+", "%20")
override fun list(): List<CloudFile> {
val c = open(base, "GET", token, ua)
val code = c.responseCode
if (code == 404) { c.disconnect(); return emptyList() }
if (code !in 200..299) {
val err = runCatching { c.errorStream?.readBytes()?.decodeToString().orEmpty() }.getOrDefault("")
c.disconnect()
if ("not_enabled_for_client" in err || "disabled" in err) throw NoCloudSaves()
throw java.io.IOException("GOG cloud list HTTP $code")
}
val text = c.body().decodeToString().trim()
c.disconnect()
if (text.isEmpty() || text == "[]") return emptyList()
// A plain newline-separated list of keys (checked on device); a JSON array is read too.
if (text.startsWith("[")) {
val a = JSONArray(text)
return (0 until a.length()).mapNotNull { a.optJSONObject(it) }.mapNotNull { o ->
val n = o.optString("name").ifEmpty { return@mapNotNull null }
val lm = o.optLong("last_modified", 0L)
CloudFile(n, if (lm > 1_000_000_000_000L) lm else if (lm > 0) lm * 1000 else -1L)
}
}
return text.lines().map { it.trim() }.filter { it.isNotEmpty() }.map { CloudFile(it, -1L) }
}
override fun details(file: CloudFile) {
if (file.modifiedMs > 0 && file.md5 != null) return
val c = open("$base/${key(file.name)}", "HEAD", token, ua)
if (c.responseCode in 200..299) {
httpDate(c.getHeaderField("Last-Modified")).takeIf { it > 0 }?.let { file.modifiedMs = it }
c.getHeaderField("ETag")?.replace("\"", "")?.trim()?.ifEmpty { null }?.let { file.md5 = it }
}
c.disconnect()
}
override fun get(file: CloudFile): Pair<ByteArray, Long> {
val c = open("$base/${key(file.name)}", "GET", token, ua)
if (c.responseCode !in 200..299) { val code = c.responseCode; c.disconnect(); throw java.io.IOException("GOG cloud get HTTP $code") }
val modified = httpDate(c.getHeaderField("Last-Modified"))
return c.body().also { c.disconnect() } to modified
}
override fun put(files: Map<String, ByteArray>): Map<String, Long> = files.mapValues { (name, data) ->
val c = open("$base/${key(name)}", "PUT", token, ua)
c.doOutput = true
c.setRequestProperty("Content-Type", "application/octet-stream")
c.setFixedLengthStreamingMode(data.size)
c.outputStream.use { it.write(data) }
val code = c.responseCode
c.disconnect()
if (code !in 200..299) throw java.io.IOException("GOG cloud put HTTP $code")
// The server stamps the object itself; that time, so the next sync sees the two as equal.
CloudFile(name, -1L).also { details(it) }.modifiedMs
}
}
/** Epic savesync: `/api/v1/access/egstore/savesync/<accountId>/<appName>/`. */
class EpicCloud(private val accountId: String, private val appName: String, private val token: String) : CloudTransport {
private val base = "https://datastorage-public-service-liveegs.live.use1a.on.epicgames.com/api/v1/access/egstore/savesync/$accountId/$appName/"
private val ua = "EpicGamesLauncher/15.17.1-22692490"
override fun list(): List<CloudFile> {
val c = open(base, "GET", token, ua)
val code = c.responseCode
if (code == 404) { c.disconnect(); return emptyList() }
if (code !in 200..299) { c.disconnect(); throw java.io.IOException("Epic cloud list HTTP $code") }
val root = JSONObject(c.body().decodeToString().ifEmpty { "{}" })
c.disconnect()
val files = root.optJSONObject("files") ?: return emptyList()
return files.keys().asSequence().mapNotNull { k ->
val e = files.optJSONObject(k) ?: return@mapNotNull null
CloudFile(strip(k), isoDate(e.optString("lastModified", null)), e.optString("hash", "").ifEmpty { null }, e.optString("readLink", "").ifEmpty { null })
}.toList()
}
/** The listing names a file `<...>/<appName>/<key>`; the key is what is under the save folder. */
private fun strip(key: String): String {
val marker = "/$appName/"
val i = key.indexOf(marker)
if (i >= 0) return key.substring(i + marker.length)
return key.removePrefix("$appName/")
}
override fun get(file: CloudFile): Pair<ByteArray, Long> {
val link = file.readLink ?: throw java.io.IOException("Epic cloud: no read link")
val c = open(link, "GET", null, ua)
if (c.responseCode !in 200..299) { val code = c.responseCode; c.disconnect(); throw java.io.IOException("Epic cloud get HTTP $code") }
return c.body().also { c.disconnect() } to file.modifiedMs
}
override fun put(files: Map<String, ByteArray>): Map<String, Long> {
if (files.isEmpty()) return emptyMap()
val c = open(base, "POST", token, ua)
c.doOutput = true
c.setRequestProperty("Content-Type", "application/json")
val req = JSONObject().put("files", JSONArray(files.keys.toList())).toString().toByteArray()
c.outputStream.use { it.write(req) }
if (c.responseCode !in 200..299) { val code = c.responseCode; c.disconnect(); throw java.io.IOException("Epic cloud write links HTTP $code") }
val links = JSONObject(c.body().decodeToString()).optJSONObject("files") ?: JSONObject()
c.disconnect()
val out = HashMap<String, Long>()
for (k in links.keys()) {
val link = links.optJSONObject(k)?.optString("writeLink", "")?.ifEmpty { null } ?: continue
val name = strip(k)
val data = files[name] ?: files[k] ?: continue
val p = open(link, "PUT", null, ua)
p.doOutput = true
p.setRequestProperty("Content-Type", "application/octet-stream")
p.setFixedLengthStreamingMode(data.size)
p.outputStream.use { it.write(data) }
val code = p.responseCode
p.disconnect()
if (code !in 200..299) throw java.io.IOException("Epic cloud put HTTP $code")
out[name] = -1L
}
return out
}
}
@@ -40,6 +40,8 @@ class StoreGameSidecar(
val state: String = STATE_INSTALLED,
/** An Epic game's launch choices (the Games tab's Epic card); both launch paths read them from here. */
val epic: EpicOptions = EpicOptions(),
/** GOG / Epic cloud saves for this game: down before a launch, up after it (the game card's switch). */
val cloud: Boolean = true,
) {
val isInstalled: Boolean get() = state == STATE_INSTALLED
@@ -50,8 +52,8 @@ class StoreGameSidecar(
exe: String = this.exe, launcher: String? = this.launcher, args: List<String> = this.args,
env: Map<String, String> = this.env, installVersion: String = this.installVersion,
installedAt: Long = this.installedAt, cover: String? = this.cover, hero: String? = this.hero,
extra: Map<String, String> = this.extra, state: String = this.state, epic: EpicOptions = this.epic,
) = StoreGameSidecar(store, id, title, exe, launcher, args, env, installVersion, installedAt, cover, hero, extra, state, epic)
extra: Map<String, String> = this.extra, state: String = this.state, epic: EpicOptions = this.epic, cloud: Boolean = this.cloud,
) = StoreGameSidecar(store, id, title, exe, launcher, args, env, installVersion, installedAt, cover, hero, extra, state, epic, cloud)
fun toJson(): JSONObject = JSONObject().apply {
put("version", VERSION)
@@ -61,6 +63,7 @@ class StoreGameSidecar(
if (exe.isNotEmpty()) put("exe", exe)
if (state != STATE_INSTALLED) put("state", state)
if (store == Store.EPIC) put("epic", JSONObject().put("eos", epic.eos).put("offline", epic.offline))
if (store != Store.AMAZON) put("cloud", cloud)
if (!launcher.isNullOrEmpty()) put("launcher", launcher)
if (args.isNotEmpty()) put("args", JSONArray(args))
if (env.isNotEmpty()) put("env", JSONObject(env as Map<*, *>))
@@ -99,6 +102,13 @@ class StoreGameSidecar(
return read(folder)?.takeIf { it.epic == next.epic }
}
/** As [updateEpic], for the cloud-saves switch. */
fun updateCloud(folder: File, on: Boolean): StoreGameSidecar? {
val current = read(folder) ?: return null
current.copy(cloud = on).write(folder)
return read(folder)?.takeIf { it.cloud == on }
}
/** The sidecar in [folder], or null when there is none or it cannot be read. */
fun read(folder: File): StoreGameSidecar? {
val f = file(folder)
@@ -135,6 +145,7 @@ class StoreGameSidecar(
state = state,
// An "overlay" (or "v") field from an earlier build is read past: there is no overlay.
epic = o.optJSONObject("epic")?.let { e -> EpicOptions(eos = e.optBoolean("eos", true), offline = e.optBoolean("offline", false)) } ?: EpicOptions(),
cloud = o.optBoolean("cloud", true),
)
}
@@ -43,8 +43,8 @@ object StoreInstalls {
val app = context.applicationContext
onStep?.invoke(0, STEPS)
// The user's launch choices survive an update or a repair.
val kept = StoreGameSidecar.read(folder)?.epic ?: sidecar.epic
val finished = StoreLaunch.writeLauncher(folder, sidecar.copy(state = StoreGameSidecar.STATE_INSTALLED, epic = kept))
val before = StoreGameSidecar.read(folder)
val finished = StoreLaunch.writeLauncher(folder, sidecar.copy(state = StoreGameSidecar.STATE_INSTALLED, epic = before?.epic ?: sidecar.epic, cloud = before?.cloud ?: sidecar.cloud))
finished.write(folder)
if (StoreGameSidecar.read(folder)?.isInstalled != true) throw java.io.IOException("the install record could not be written in ${folder.name}")
onStep?.invoke(1, STEPS)
@@ -63,6 +63,20 @@ object StoreLaunchRequests {
JSONObject().put("ok", true).put("code", code.written).put("reason", code.reason)
}
}
// Cloud saves: down before Proton starts (the wrapper waits a bounded time), up after the
// game exits (answered at once; the upload runs on without holding Steam).
"cloud-down" -> {
val store = Store.byId(request.optString("store"))
val id = request.optString("id")
if (store == null || id.isEmpty()) JSONObject().put("ok", false).put("reason", "no-game")
else CloudSaves.download(app, store, id).let { JSONObject().put("ok", it.ok).put("files", it.files).put("reason", it.reason) }
}
"cloud-up" -> {
val store = Store.byId(request.optString("store"))
val id = request.optString("id")
if (store != null && id.isNotEmpty()) Thread({ CloudSaves.upload(app, store, id) }, "cloud-up").start()
JSONObject().put("ok", true)
}
// A browser a game opens inside the session (an EOS device sign-in, a store page):
// http(s) only, handed to Android's browser.
"open-url" -> {
@@ -149,6 +149,11 @@ public final class EpicApiClient {
/** `customAttributes.AdditionalCommandLine.value` for the game, "" when it has none, null when the call failed. */
public static String getAdditionalCommandLine(String accessToken, String namespace, String catalogItemId) {
return getCustomAttribute(accessToken, namespace, catalogItemId, "AdditionalCommandLine");
}
/** `customAttributes.<name>.value` for the game (CloudSaveFolder, AdditionalCommandLine), "" when it has none, null when the call failed. */
public static String getCustomAttribute(String accessToken, String namespace, String catalogItemId, String name) {
try {
String url = CATALOG_BASE + "/" + namespace + "/bulk/items?id=" + catalogItemId + "&country=US";
String resp = getWithLegendaryUA(url, accessToken);
@@ -159,10 +164,10 @@ public final class EpicApiClient {
if (item == null) return "";
JSONObject attrs = item.optJSONObject("customAttributes");
if (attrs == null) return "";
JSONObject attr = attrs.optJSONObject("AdditionalCommandLine");
JSONObject attr = attrs.optJSONObject(name);
return attr == null ? "" : attr.optString("value", "");
} catch (Exception e) {
Log.w(TAG, "additional command line: " + e.getClass().getSimpleName());
Log.w(TAG, "catalog attribute " + name + ": " + e.getClass().getSimpleName());
return null;
}
}
@@ -258,6 +258,9 @@ public final class GogDownloadManager {
deleteCounted(new File(installPath, ".gog_chunks"), cb);
String clientId = manifest.optString("clientId", null);
if (clientId != null && !clientId.isEmpty()) GogPrefs.get(ctx).edit().putString("client_id_" + game.gameId, clientId).apply();
// The game's own client secret: cloud saves need a token issued to the game's client.
String clientSecret = manifest.optString("clientSecret", null);
if (clientSecret != null && !clientSecret.isEmpty()) GogPrefs.get(ctx).edit().putString("client_secret_" + game.gameId, clientSecret).apply();
out.result = new Result(pickExe(installPath, tempExe, game.title), gm.buildId, planned);
return out;
} catch (Exception e) {
@@ -213,6 +213,43 @@ private fun ManageSaves(g: Library.SteamGame, prefix: java.io.File, a: FrontEndA
open = false; a.onBrowseFiles(java.io.File(prefix, "drive_c/users/steamuser/" + d.relPath))
}
}
CloudRows(g, open)
}
}
}
/**
* A GOG or Epic game's cloud saves in Manage saves: when it last synced, and Upload / Download
* (newest wins, file by file), or "No cloud saves" when the store keeps none for it.
*/
@Composable
private fun CloudRows(g: Library.SteamGame, open: Boolean) {
val store = com.droiddeck.launcher.stores.Store.byId(g.source)?.takeIf { it != com.droiddeck.launcher.stores.Store.AMAZON } ?: return
val id = g.storeId ?: return
val context = androidx.compose.ui.platform.LocalContext.current.applicationContext
var busy by remember(g.gameId) { androidx.compose.runtime.mutableStateOf<String?>(null) }
var tick by remember(g.gameId) { androidx.compose.runtime.mutableStateOf(0) }
val status by androidx.compose.runtime.produceState<com.droiddeck.launcher.stores.CloudSaves.Status?>(null, g.gameId, open, tick) {
if (open) value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
runCatching { com.droiddeck.launcher.stores.CloudSaves.status(context, store, id) }.getOrNull()
}
}
val st = status
when {
st == null -> MenuItem(stringResource(R.string.cloud_checking), checked = false, enabled = false) {}
!st.supported -> MenuItem(stringResource(R.string.cloud_none), checked = false, enabled = false) {}
else -> {
val last = if (st.lastSync > 0) stringResource(R.string.cloud_last_sync, android.text.format.DateUtils.getRelativeTimeSpanString(st.lastSync).toString()) else stringResource(R.string.cloud_never)
fun sync(up: Boolean) {
if (busy != null) return
busy = if (up) "up" else "down"
Thread({
val r = if (up) com.droiddeck.launcher.stores.CloudSaves.upload(context, store, id) else com.droiddeck.launcher.stores.CloudSaves.download(context, store, id)
com.droiddeck.launcher.stores.StoresState.post { busy = null; tick++; android.widget.Toast.makeText(context, if (r.ok) context.getString(R.string.cloud_done, r.files) else r.reason, android.widget.Toast.LENGTH_SHORT).show() }
}, "cloud-manual").start()
}
MenuItem(stringResource(R.string.cloud_upload), checked = false, enabled = busy == null, detail = if (busy == "up") stringResource(R.string.cloud_checking) else last) { sync(true) }
MenuItem(stringResource(R.string.cloud_download), checked = false, enabled = busy == null, detail = if (busy == "down") stringResource(R.string.cloud_checking) else null) { sync(false) }
}
}
}
@@ -477,9 +477,10 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
// An Epic game's own launch choices, kept in its sidecar so a launch from the Steam client
// honours them too (droiddeck-store-launch reads the same file).
if (game?.source == com.droiddeck.launcher.stores.Store.EPIC.id && game.gameFiles != null) add { m ->
val cardStore = com.droiddeck.launcher.stores.Store.byId(game?.source.orEmpty())?.takeIf { it != com.droiddeck.launcher.stores.Store.AMAZON }
if (cardStore != null && game?.gameFiles != null) add { m ->
Box(m) {
EpicLaunchCard(host, game.gameFiles!!)
StoreLaunchCard(host, game.gameFiles!!, cardStore)
}
}
if (wincompKey != null) add { m ->
@@ -510,14 +511,25 @@ private const val EPIC_RESOLVE_URL = "https://www.epicgames.com/id/login?redirec
/** The Epic card: the sign-in and offline switches, read from and written to the game's sidecar, and Resolve Epic sign-in. */
@Composable
private fun EpicLaunchCard(host: MenuHost, folder: java.io.File) {
private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.droiddeck.launcher.stores.Store) {
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
var sidecar by remember(folder) { mutableStateOf(com.droiddeck.launcher.stores.StoreGameSidecar.read(folder)) }
val options = sidecar?.epic ?: com.droiddeck.launcher.stores.EpicOptions()
val cloud = sidecar?.cloud ?: true
val epic = store == com.droiddeck.launcher.stores.Store.EPIC
val key = "store-" + store.id
val value = buildList {
if (options.offline) add(stringResource(R.string.epic_card_offline))
else if (options.eos) add(stringResource(R.string.epic_card_eos))
if (epic && options.offline) add(stringResource(R.string.epic_card_offline))
else if (epic && options.eos) add(stringResource(R.string.epic_card_eos))
if (cloud) add(stringResource(R.string.store_card_cloud))
}.ifEmpty { listOf(stringResource(R.string.epic_card_none)) }.joinToString(" · ")
fun setCloud(on: Boolean) {
Thread({
val written = runCatching { com.droiddeck.launcher.stores.StoreGameSidecar.updateCloud(folder, on) }.getOrNull()
android.util.Log.i("StoreLaunchCard", "cloud saves ${folder.name} " + (written?.cloud?.toString() ?: "not saved"))
com.droiddeck.launcher.stores.StoresState.post { sidecar = written ?: com.droiddeck.launcher.stores.StoreGameSidecar.read(folder) }
}, "store-options").start()
}
// Each switch goes straight to the sidecar on disk - both launch paths read it there - and the
// card shows what was read back, so a write that did not take is never shown as done.
fun set(change: (com.droiddeck.launcher.stores.EpicOptions) -> com.droiddeck.launcher.stores.EpicOptions) {
@@ -529,12 +541,16 @@ private fun EpicLaunchCard(host: MenuHost, folder: java.io.File) {
com.droiddeck.launcher.stores.StoresState.post { sidecar = written ?: com.droiddeck.launcher.stores.StoreGameSidecar.read(folder) }
}, "epic-options").start()
}
SettingCard(stringResource(R.string.epic_card_title), value, "card:epic", Modifier.fillMaxSize()) {
host.open = if (host.open == "epic") null else "epic"
SettingCard(store.shortLabel, value, "card:$key", Modifier.fillMaxSize()) {
host.open = if (host.open == key) null else key
}
AnchoredMenu(host.open == "epic", onDismiss = { if (host.open == "epic") host.open = null }, title = stringResource(R.string.epic_card_title)) { first ->
MenuItem(stringResource(R.string.epic_eos), checked = options.eos, focusRequester = first) { set { it.copy(eos = !it.eos) } }
MenuItem(stringResource(R.string.epic_offline), checked = options.offline) { set { it.copy(offline = !it.offline) } }
AnchoredMenu(host.open == key, onDismiss = { if (host.open == key) host.open = null }, title = store.shortLabel) { first ->
if (epic) {
MenuItem(stringResource(R.string.epic_eos), checked = options.eos, focusRequester = first) { set { it.copy(eos = !it.eos) } }
MenuItem(stringResource(R.string.epic_offline), checked = options.offline) { set { it.copy(offline = !it.offline) } }
}
MenuItem(stringResource(R.string.store_cloud_saves), checked = cloud, focusRequester = if (epic) null else first) { setCloud(!cloud) }
if (epic) {
// Epic asks some accounts to accept something once (privacy policy, EULA) before a game may
// sign in - EOS's "corrective action". Signing in on Epic's site shows it.
MenuItem(stringResource(R.string.epic_resolve), checked = false) {
@@ -543,6 +559,7 @@ private fun EpicLaunchCard(host: MenuHost, folder: java.io.File) {
appContext.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(EPIC_RESOLVE_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
}
}
}
}
}
+9
View File
@@ -2019,6 +2019,15 @@
<string name="epic_eos">Epic sign-in (EOS)</string>
<string name="epic_offline">Launch offline</string>
<string name="epic_resolve">Resolve Epic sign-in</string>
<string name="store_card_cloud">Cloud</string>
<string name="store_cloud_saves">Cloud saves</string>
<string name="cloud_upload">Upload to cloud</string>
<string name="cloud_download">Download from cloud</string>
<string name="cloud_none">No cloud saves</string>
<string name="cloud_checking">Checking cloud…</string>
<string name="cloud_last_sync">Last sync %1$s</string>
<string name="cloud_never">Not synced yet</string>
<string name="cloud_done">%1$d files</string>
<string name="stores_eyebrow_installed">installed</string>
<string name="stores_eyebrow_library">in your library</string>
<string name="stores_eyebrow_store">store</string>
@@ -0,0 +1,52 @@
package com.droiddeck.launcher.stores
import java.io.File
import java.nio.file.Files
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
/** A store's save-location template, made concrete inside the game's prefix (Bannerlator's cases). */
class CloudSavePathsTest {
private val root = Files.createTempDirectory("cloud").toFile()
private val prefix = File(root, "compatdata/3785150007/pfx").apply { mkdirs() }
private val install = File(root, "Games/Stores/GOG/ELDERBORN").apply { mkdirs() }
private val profile = File(prefix, "drive_c/users/steamuser")
@Test fun gogElderbornLivesInLocalLow() {
val dir = CloudSavePaths.gog("<?APPLICATION_DATA_LOCAL_LOW?>/Hyperstrange/ELDERBORN", prefix, install)
assertEquals(File(profile, "AppData/LocalLow/Hyperstrange/ELDERBORN").path, dir!!.path)
}
@Test fun gogTokensAndEnvironmentStyle() {
assertEquals(File(profile, "Saved Games/X").path, CloudSavePaths.gog("<?SAVED_GAMES?>/X", prefix, install)!!.path)
assertEquals(File(profile, "Documents/My Games/Y").path, CloudSavePaths.gog("<?DOCUMENTS?>\\My Games\\Y", prefix, install)!!.path)
assertEquals(File(profile, "AppData/Roaming/Z").path, CloudSavePaths.gog("%APPDATA%/Z", prefix, install)!!.path)
assertEquals(File(install, "saves").path, CloudSavePaths.gog("<?INSTALL?>/saves", prefix, install)!!.path)
assertNull(CloudSavePaths.gog("<?SOMETHING_ELSE?>/x", prefix, install))
assertNull(CloudSavePaths.gog("no/token", prefix, install))
}
@Test fun aPathThatLeavesItsBoundaryIsRefused() {
assertNull(CloudSavePaths.gog("<?SAVED_GAMES?>/../../../../outside", prefix, install))
assertNull(CloudSavePaths.epic("{InstallDir}/../other", prefix, install, "acc", "app"))
}
@Test fun anExistingFolderIsMatchedWhateverItsCase() {
File(profile, "AppData/LocalLow/hyperstrange/elderborn").mkdirs()
val dir = CloudSavePaths.gog("<?APPLICATION_DATA_LOCAL_LOW?>/Hyperstrange/ELDERBORN", prefix, install)
assertEquals(File(profile, "AppData/LocalLow/hyperstrange/elderborn").path, dir!!.path)
}
@Test fun epicTokensAndPlaceholders() {
assertEquals(File(profile, "AppData/Local/Metalstorm/Saved/SaveGames").path,
CloudSavePaths.epic("{AppData}/Metalstorm/Saved/SaveGames", prefix, install, "acc", "app")!!.path)
assertEquals(File(profile, "Saved Games/Studio/acc/app").path,
CloudSavePaths.epic("{UserSavedGames}/Studio/{EpicId}/{AppName}", prefix, install, "acc", "app")!!.path)
assertEquals(File(profile, "Documents/G").path, CloudSavePaths.epic("{UserDir}/G", prefix, install, "acc", "app")!!.path)
assertNull(CloudSavePaths.epic("{Nope}/G", prefix, install, "acc", "app"))
// Epic's folder names are matched by letters and digits alone when that names exactly one.
File(profile, "AppData/Local/My-Game").mkdirs()
assertEquals(File(profile, "AppData/Local/My-Game").path, CloudSavePaths.epic("{AppData}/MyGame", prefix, install, "acc", "app")!!.path)
}
}