mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-20 13:26:02 +00:00
feat(ea, ubisoft): cloud saves and a kept Ubisoft Denuvo token (#2824)
* feat(ubisoft): keep Denuvo game tokens per account and product until the game invalidates them * feat(ubisoft): sync cloud saves through Ubisoft's cloud save service * fix(xbox): turning cloud saves off passes the offline mode the game save runtime reads * fix(ubisoft): Ubisoft games list their shared prefix, so they get a saves and cloud tab * feat(ea): sync cloud saves through EA's cloud sync service * fix(ea): sync at EA launch and exit, keep one rule snapshot, and check the cloud copy under the write lock * fix(ubisoft): exact slot versions, scoped save export, and a Denuvo cache bound to its account * fix(ea): fresh rules per sync, checksums required, backup before restore, and sign-in shown on the saves tab * fix(ubisoft): launch-time sync on the shared prefix, saves scoped to the game, and Denuvo bound to each launch's account * fix(ea): back up only the saves a restore replaces, refuse truncated manifests, and need a master title id * fix(ubisoft): treat a slot whose bytes changed since the last sync as a conflict before uploading over it * fix(ea): one resolved save folder per sync, refuse case collisions, and walk each folder once * fix(ubisoft): sync only identified slots, keep live saves and backups safe, and tie a pending eviction to its account * fix(cloud): a forced download fetches every saved conflict and keeps the ones it could not write * test(ea): keep the cloud save cases in EaTest * fix(ubisoft): report only written slots, keep drift conflicts, read whole headers, and never rename a named eviction * fix(ea): keep real save folders in the inventory, back up any restored file, refuse duplicate or malformed cloud listings * fix(cloud): commit Ubisoft slots one at a time and stop on a newer cloud write, name skipped and blocked slots, keep unsent conflicts * fix(ubisoft): acknowledge an invalidation only once its marker is published and never serve a kept token after it * fix(cloud): a cloud request the launcher cannot write still starts the game and keeps the exit upload * fix(cloud): scope Ubisoft sync state to the account and product, compare alike slots, keep committed progress, and name partial slots * fix(ea): ask for sign-in after a rejected refresh, upload saves reached through folder aliases * fix(cloud): a launch that stops waiting for the cloud download claims it back, so no save is written once the game starts * fix(ubisoft): name the account in an invalidation marker and never hold the token lock across a pipe write * fix(ea): only invalid_grant asks for sign-in again, and case collisions count only among synced saves * test(epic): let the launcher's ask doubles take the claim flag * fix(ea): apply save rules in their order, match bare patterns inside the save folder, and resolve LocalLow and install folders * fix(ubisoft): stamp a fresh identifier into a new save that has none, so it can sync * fix(ubisoft): answer a burn ticket request as unavailable instead of leaving the game waiting * fix(cloud): read EA manifests with the XML parser, clear conflicts whose sides match, and bound the claim and stall tests
This commit is contained in:
1 parent
6ed281f78d
commit
123c431b8e
31 files changed
+1999
-132
No files matched your search
@@ -1513,7 +1513,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
onComponents = { focusContent -> openComponents(focusContent) },
|
||||
onGameComponents = { game -> openComponents(gameKey = game.profileKey) },
|
||||
onComponentsTab = { tab -> openComponents(focusContent = true, tab = tab) },
|
||||
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } },
|
||||
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(this@FrontEndActivity, sg) } },
|
||||
onAddonImport = { sg, target -> importAddons(sg.name, target) },
|
||||
onAddonDelete = { target, name ->
|
||||
saveAction(getString(R.string.main_addons_deleting, name)) {
|
||||
@@ -1521,7 +1521,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
getString(R.string.main_addons_deleted, name)
|
||||
}
|
||||
},
|
||||
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } },
|
||||
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(this@FrontEndActivity, sg) } },
|
||||
onPerformance = { refreshCores(); showComponents = false; showMapping = false; showPerformance = true },
|
||||
performancePanel = { PerformanceHost(embedded = true) },
|
||||
onRoms = { showRoms = true },
|
||||
|
||||
@@ -293,6 +293,7 @@ object Library {
|
||||
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
|
||||
hero = art.hero ?: art.header, lastPlayed = maxOf(lastPlayed, recordedPlay(context, g.gameId)), gameFiles = g.folder,
|
||||
protonPrefix = if (g.source == com.droiddeck.launcher.stores.Store.BATTLENET.id) File(com.droiddeck.launcher.runtime.BattleNet.prefix(context), "pfx").takeIf { it.isDirectory }
|
||||
else if (g.source == com.droiddeck.launcher.stores.Store.UBISOFT.id) File(com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.prefix(context), "pfx").takeIf { it.isDirectory }
|
||||
else protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
|
||||
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
|
||||
source = g.source, storeId = g.storeId,
|
||||
|
||||
@@ -25,7 +25,7 @@ object GameSaves {
|
||||
fun label(context: Context): String = context.getString(R.string.saves_layout_zip, app)
|
||||
}
|
||||
|
||||
data class Game(val game: Library.SteamGame, val prefix: File?, val saves: List<SaveDir>) {
|
||||
data class Game(val game: Library.SteamGame, val prefix: File?, val saves: List<SaveDir>, val root: String? = null) {
|
||||
val launched get() = prefix?.let { File(it, "drive_c").isDirectory } == true
|
||||
}
|
||||
|
||||
@@ -36,7 +36,28 @@ object GameSaves {
|
||||
fun savesDir(): File = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck/Saves")
|
||||
private fun backupsDir(): File = File(savesDir(), "backups")
|
||||
|
||||
fun game(game: Library.SteamGame): Game = Game(game, game.protonPrefix, game.protonPrefix?.let { locate(it, game) } ?: emptyList())
|
||||
fun game(context: Context, game: Library.SteamGame): Game {
|
||||
val root = if (ubisoft(game)) ubisoftRoot(context, game) else null
|
||||
val saves = game.protonPrefix?.let { prefix -> if (ubisoft(game)) root?.let { ubisoftSaves(prefix, it) }.orEmpty() else locate(prefix, game) }.orEmpty()
|
||||
return Game(game, game.protonPrefix, saves, root)
|
||||
}
|
||||
|
||||
fun saves(context: Context, prefix: File, game: Library.SteamGame): List<SaveDir> =
|
||||
if (ubisoft(game)) ubisoftRoot(context, game)?.let { ubisoftSaves(prefix, it) }.orEmpty() else locate(prefix, game)
|
||||
|
||||
private fun ubisoftRoot(context: Context, game: Library.SteamGame): String? {
|
||||
val product = game.gameFiles?.let { com.droiddeck.launcher.stores.StoreGameSidecar.read(it) }?.extra?.get("productId")?.toLongOrNull() ?: return null
|
||||
val user = com.droiddeck.launcher.stores.ubisoft.UbisoftAuth.load(context)?.userId
|
||||
if (user.isNullOrEmpty() || user.contains('/') || user.contains("..")) return null
|
||||
return "Saved Games/Ubisoft/$user/$product"
|
||||
}
|
||||
|
||||
private fun ubisoft(game: Library.SteamGame) = game.source == com.droiddeck.launcher.stores.Store.UBISOFT.id
|
||||
|
||||
private fun ubisoftSaves(prefix: File, rel: String): List<SaveDir> {
|
||||
val files = File(profile(prefix), rel).walkTopDown().filter { it.isFile }.toList()
|
||||
return if (files.isEmpty()) emptyList() else listOf(SaveDir(rel, files.size, files.sumOf { it.length() }))
|
||||
}
|
||||
|
||||
|
||||
private val SAVE_ROOTS = listOf("Documents/My Games", "Saved Games", "AppData/Roaming", "Documents", "AppData/Local", "AppData/LocalLow")
|
||||
@@ -109,9 +130,11 @@ object GameSaves {
|
||||
|
||||
fun export(context: Context, game: Game, layout: Layout, dir: File): Pair<File, Int> {
|
||||
val prefix = game.prefix ?: error(context.getString(R.string.saves_not_launched, game.game.name))
|
||||
val roots = game.saves.map { it.relPath }
|
||||
if (roots.isEmpty() && ubisoft(game.game)) error(context.getString(R.string.saves_none_found, game.game.name))
|
||||
dir.mkdirs()
|
||||
val out = File(dir, "${safe(game.game.name)}_${stamp()}.zip")
|
||||
val count = zipProfile(profile(prefix), game.saves.map { it.relPath }.ifEmpty { null }, layout, out)
|
||||
val count = zipProfile(profile(prefix), roots.ifEmpty { null }, layout, out)
|
||||
if (count == 0) { out.delete(); error(context.getString(R.string.saves_none_found, game.game.name)) }
|
||||
return out to count
|
||||
}
|
||||
@@ -142,12 +165,21 @@ object GameSaves {
|
||||
if (!driveC.isDirectory) error(context.getString(R.string.saves_not_launched, game.game.name))
|
||||
if (!looksLikeSaveZip(zip)) error(context.getString(R.string.saves_not_save_zip, zip.name))
|
||||
|
||||
val scoped = if (ubisoft(game.game)) game.root ?: error(context.getString(R.string.saves_none_found, game.game.name)) else null
|
||||
if (scoped != null) {
|
||||
val base = File(profile(prefix), scoped).canonicalFile
|
||||
val eligible = ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis ->
|
||||
generateSequence { zis.nextEntry }.any { e -> !e.isDirectory && remap(e.name)?.let { File(driveC, it).canonicalFile.path.startsWith(base.path + File.separator) } == true }
|
||||
}
|
||||
if (!eligible) error(context.getString(R.string.saves_not_save_zip, zip.name))
|
||||
}
|
||||
backupsDir().mkdirs()
|
||||
val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}.zip")
|
||||
val backedUp = zipProfile(profile(prefix), null, Layout.GAMEHUB, backup)
|
||||
val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}_${System.currentTimeMillis()}.zip")
|
||||
val backedUp = if (scoped != null && File(profile(prefix), scoped).walkTopDown().none { it.isFile }) 0
|
||||
else zipProfile(profile(prefix), scoped?.let(::listOf), Layout.GAMEHUB, backup)
|
||||
if (backedUp == 0) backup.delete()
|
||||
|
||||
val base = driveC.canonicalFile
|
||||
val base = (if (scoped != null) File(profile(prefix), scoped) else driveC).canonicalFile
|
||||
var written = 0
|
||||
ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis ->
|
||||
var e = zis.nextEntry
|
||||
|
||||
@@ -1484,6 +1484,8 @@ object SessionPrefs {
|
||||
(id and 0xFFFFFFFFL) to key.removePrefix("addedAppId:")
|
||||
}.toMap()
|
||||
|
||||
fun storeGameFolder(context: Context, key: String): String? = prefs(context).getString("storeFolder:$key", null)
|
||||
|
||||
fun followStoreGame(context: Context, key: String, folderPath: String, gone: (String) -> Boolean) = synchronized(addedGameLock) {
|
||||
val p = prefs(context)
|
||||
val previous = p.getString("storeFolder:$key", null)
|
||||
|
||||
@@ -5,11 +5,20 @@ import android.content.SharedPreferences
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.stores.ea.EaAuth
|
||||
import com.droiddeck.launcher.stores.ea.EaCloud
|
||||
import com.droiddeck.launcher.stores.ea.EaLibrary
|
||||
import com.droiddeck.launcher.stores.ea.EaPrefs
|
||||
import com.droiddeck.launcher.stores.ea.EaSaveRules
|
||||
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 com.droiddeck.launcher.stores.ubisoft.UbisoftAuth
|
||||
import com.droiddeck.launcher.stores.ubisoft.UbisoftCloud
|
||||
import com.droiddeck.launcher.stores.ubisoft.UbisoftCloudTransport
|
||||
import com.droiddeck.launcher.stores.ubisoft.UbisoftConnect
|
||||
import java.io.File
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
@@ -32,19 +41,27 @@ object CloudSaves {
|
||||
if (detail.isNotEmpty()) " detail=\"$detail\"" else ""
|
||||
}
|
||||
|
||||
class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String, val conflicts: List<String> = emptyList())
|
||||
class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String, val conflicts: List<String> = emptyList(), val signedIn: Boolean = true)
|
||||
|
||||
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 }
|
||||
}
|
||||
private fun game(context: Context, store: Store, id: String): Pair<File, StoreGameSidecar>? {
|
||||
fun match(f: File) = StoreGameSidecar.read(f)?.takeIf { it.store == store && it.id == id && it.isInstalled }?.let { f to it }
|
||||
return StoreInstallRoot.gameFolders(context).firstNotNullOfOrNull(::match)
|
||||
?: if (store != Store.UBISOFT) null
|
||||
else com.droiddeck.launcher.session.SessionPrefs.storeGameFolder(context, "${store.id}:$id")?.let { match(File(it)) }
|
||||
}
|
||||
|
||||
fun supports(store: Store?): Boolean = store == Store.GOG || store == Store.EPIC || store == Store.EA || store == Store.UBISOFT
|
||||
|
||||
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)
|
||||
private fun prefs(context: Context, store: Store) = when (store) {
|
||||
Store.GOG -> GogPrefs.get(context)
|
||||
Store.EA -> EaPrefs.get(context)
|
||||
else -> EpicPrefs.get(context)
|
||||
}
|
||||
|
||||
fun lastSync(context: Context, store: Store, id: String): Long = prefs(context, store).getLong("cloud_sync_$id", 0L)
|
||||
|
||||
@@ -52,6 +69,7 @@ object CloudSaves {
|
||||
|
||||
|
||||
private const val TEMPLATE_NONE = "none"
|
||||
private const val UBISOFT_TEMPLATE = "ubisoft"
|
||||
internal const val TEMPLATE_NONE_TTL_MS = 24 * 60 * 60 * 1000L
|
||||
|
||||
internal fun noneTemplateIsCurrent(storedAtMs: Long, nowMs: Long) =
|
||||
@@ -64,6 +82,10 @@ object CloudSaves {
|
||||
|
||||
fun template(context: Context, store: Store, id: String, folder: File, sidecar: StoreGameSidecar): String? {
|
||||
val p = prefs(context, store)
|
||||
if (store == Store.EA) eaRules(context, id)?.let { fresh ->
|
||||
if (fresh.isEmpty()) rememberNoCloud(p, id) else p.edit().putString("cloud_template_$id", fresh).remove("cloud_template_at_$id").apply()
|
||||
return fresh
|
||||
}
|
||||
var retryNone = false
|
||||
if (p.contains("cloud_template_$id")) {
|
||||
val cached = p.getString("cloud_template_$id", "") ?: ""
|
||||
@@ -89,7 +111,9 @@ object CloudSaves {
|
||||
val item = sidecar.extra["catalogItemId"].orEmpty()
|
||||
if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder")
|
||||
}
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> ""
|
||||
Store.UBISOFT -> UBISOFT_TEMPLATE
|
||||
Store.EA -> eaRules(context, id) ?: return null
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR -> ""
|
||||
} ?: return null
|
||||
p.edit()
|
||||
.putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE })
|
||||
@@ -146,18 +170,25 @@ object CloudSaves {
|
||||
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"
|
||||
if (store == Store.UBISOFT) {
|
||||
val user = UbisoftAuth.load(context)?.userId?.takeIf { it.isNotEmpty() } ?: return null to "not-signed-in"
|
||||
val product = sidecar.extra["productId"]?.toLongOrNull() ?: return null to "unresolved"
|
||||
return File(UbisoftConnect.prefix(context), "pfx/drive_c/users/steamuser/Saved Games/Ubisoft/$user/$product") to "ok"
|
||||
}
|
||||
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, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> null
|
||||
Store.EA -> if (sidecar.extra["masterTitleId"].isNullOrEmpty()) null
|
||||
else EaSaveRules.parse(template)?.base()?.let(EaSaveRules::template)?.let { CloudSavePaths.gog(it, pfx, folder) }
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> 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, conflicts(context, store, id))
|
||||
return Status(reason != "no-cloud-saves" && reason != "not-installed", dir, lastSync(context, store, id), reason, conflicts(context, store, id, dir), signedIn(context, store))
|
||||
}
|
||||
|
||||
|
||||
@@ -175,7 +206,33 @@ object CloudSaves {
|
||||
val account = EpicCredentialStore.load(context)?.accountId.orEmpty()
|
||||
if (token == null || account.isEmpty()) null else EpicCloud(account, id, token)
|
||||
}
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> null
|
||||
Store.UBISOFT -> {
|
||||
val session = UbisoftAuth.current(context)
|
||||
val product = StoreGameSidecar.read(folder)?.extra?.get("productId")?.toLongOrNull()
|
||||
if (session == null || product == null) null else UbisoftCloudTransport(UbisoftCloud(session, product), session.userId)
|
||||
}
|
||||
Store.EA -> {
|
||||
val sidecar = StoreGameSidecar.read(folder)
|
||||
val rules = sidecar?.let { template(context, store, id, folder, it) }?.let(EaSaveRules::parse)
|
||||
val base = rules?.base()
|
||||
val token = EaAuth.accessToken(context)
|
||||
val uid = EaAuth.load(context)?.userId.orEmpty()
|
||||
val master = sidecar?.extra?.get("masterTitleId").orEmpty()
|
||||
if (rules == null || base == null || token == null || uid.isEmpty() || master.isEmpty()) null
|
||||
else EaCloud(token, uid, EaCloud.keys(master, sidecar?.extra?.get("multiplayerId").orEmpty()), base, rules, saveFolder(context, store, id).first)
|
||||
}
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR -> null
|
||||
}
|
||||
|
||||
private fun signedIn(context: Context, store: Store): Boolean = when (store) {
|
||||
Store.EA -> EaAuth.signedIn(context)
|
||||
else -> true
|
||||
}
|
||||
|
||||
private fun eaRules(context: Context, id: String): String? {
|
||||
val games = EaLibrary.cached(context)
|
||||
if (games.isEmpty()) return null
|
||||
return games.firstOrNull { it.offerId == id }?.cloudSaves.orEmpty()
|
||||
}
|
||||
|
||||
private fun gogScopedToken(context: Context, id: String, clientId: String): String? {
|
||||
@@ -184,11 +241,15 @@ object CloudSaves {
|
||||
}
|
||||
|
||||
|
||||
private fun baseline(context: Context, store: Store, id: String): Map<String, CloudPlan.Entry>? =
|
||||
CloudPlan.fromJson(prefs(context, store).getString("cloud_baseline_$id", null))
|
||||
/** Ubisoft saves belong to an account and product, so their sync state is kept per save folder. */
|
||||
internal fun scope(store: Store, id: String, dir: File): String =
|
||||
if (store == Store.UBISOFT) "$id:${dir.parentFile?.name.orEmpty()}:${dir.name}" else id
|
||||
|
||||
private fun saveBaseline(context: Context, store: Store, id: String, b: Map<String, CloudPlan.Entry>) =
|
||||
prefs(context, store).edit().putString("cloud_baseline_$id", CloudPlan.toJson(b)).apply()
|
||||
internal fun baseline(context: Context, store: Store, key: String): Map<String, CloudPlan.Entry>? =
|
||||
CloudPlan.fromJson(prefs(context, store).getString("cloud_baseline_$key", null))
|
||||
|
||||
private fun saveBaseline(context: Context, store: Store, key: String, b: Map<String, CloudPlan.Entry>) =
|
||||
prefs(context, store).edit().putString("cloud_baseline_$key", CloudPlan.toJson(b)).apply()
|
||||
|
||||
internal class Migration(val baseline: Map<String, CloudPlan.Entry>, val moved: Int, val cleaned: Int, val failed: Int)
|
||||
|
||||
@@ -260,30 +321,45 @@ object CloudSaves {
|
||||
if (result == null || result.failed == 0) p.edit().putInt("cloud_layout_$id", CLOUD_LAYOUT).apply()
|
||||
}
|
||||
|
||||
fun conflicts(context: Context, store: Store, id: String): List<String> =
|
||||
prefs(context, store).getString("cloud_conflicts_$id", "").orEmpty().split('\n').filter { it.isNotEmpty() }
|
||||
fun conflicts(context: Context, store: Store, id: String, dir: File? = null): List<String> =
|
||||
if (store == Store.UBISOFT && dir == null) emptyList() else savedConflicts(context, store, dir?.let { scope(store, id, it) } ?: id)
|
||||
|
||||
private fun saveConflicts(context: Context, store: Store, id: String, names: Collection<String>) =
|
||||
prefs(context, store).edit().putString("cloud_conflicts_$id", names.joinToString("\n")).apply()
|
||||
private fun savedConflicts(context: Context, store: Store, key: String): List<String> =
|
||||
prefs(context, store).getString("cloud_conflicts_$key", "").orEmpty().split('\n').filter { it.isNotEmpty() }
|
||||
|
||||
fun download(context: Context, store: Store, id: String, force: Boolean = false): Result =
|
||||
sync(context, store, id, "down") { dir, cloud -> downWith(context, store, id, dir, cloud, force) }
|
||||
private fun saveConflicts(context: Context, store: Store, key: String, names: Collection<String>) =
|
||||
prefs(context, store).edit().putString("cloud_conflicts_$key", names.joinToString("\n")).apply()
|
||||
|
||||
private fun alike(cloud: CloudTransport, conflicts: List<String>, local: Map<String, CloudPlan.Local>, remote: Map<String, CloudFile>): List<String> =
|
||||
if (cloud.contentDigests) emptyList()
|
||||
else conflicts.filter { name ->
|
||||
val r = remote[name] ?: return@filter false
|
||||
val l = local[name] ?: return@filter false
|
||||
runCatching { md5(cloud.get(r).first) }.getOrNull()?.equals(l.md5, ignoreCase = true) == true
|
||||
}
|
||||
|
||||
private fun settled(plan: CloudPlan.Plan, alike: List<String>): CloudPlan.Plan =
|
||||
if (alike.isEmpty()) plan else CloudPlan.Plan(plan.transfer, plan.conflicts - alike.toSet(), plan.same + alike, plan.refused)
|
||||
|
||||
fun download(context: Context, store: Store, id: String, force: Boolean = false, claim: () -> Boolean = { true }): Result =
|
||||
sync(context, store, id, "down") { dir, cloud -> downWith(context, store, id, dir, cloud, force, claim) }
|
||||
|
||||
fun upload(context: Context, store: Store, id: String, force: Boolean = false): Result =
|
||||
sync(context, store, id, "up") { dir, cloud -> upWith(context, store, id, dir, cloud, force) }
|
||||
|
||||
fun downloadOrDefer(context: Context, store: Store, id: String): Result =
|
||||
downloadOrDefer(context, store, id, Executor { Thread(it, "cloud-deferred").start() })
|
||||
fun downloadOrDefer(context: Context, store: Store, id: String, claim: () -> Boolean): Result =
|
||||
downloadOrDefer(context, store, id, Executor { Thread(it, "cloud-deferred").start() }, claim)
|
||||
|
||||
internal fun downloadOrDefer(context: Context, store: Store, id: String, executor: Executor): Result {
|
||||
internal fun downloadOrDefer(context: Context, store: Store, id: String, executor: Executor, claim: () -> Boolean = { true }): Result {
|
||||
val app = context.applicationContext
|
||||
val g = game(app, store, id) ?: return done(store, id, "down", Result("skipped", 0, 0, "not-installed"))
|
||||
if (!g.second.cloud) return done(store, id, "down", Result("skipped", 0, 0, "off"))
|
||||
if (prefix(app, g.first)?.let { CloudSavePaths.profile(it).isDirectory } == true) return download(app, store, id)
|
||||
val ready = { (if (store == Store.UBISOFT) File(UbisoftConnect.prefix(app), "pfx") else prefix(app, g.first))?.let { CloudSavePaths.profile(it).isDirectory } == true }
|
||||
if (ready()) return download(app, store, id, claim = claim)
|
||||
executor.execute {
|
||||
val end = System.currentTimeMillis() + PREFIX_WAIT_MS
|
||||
while (System.currentTimeMillis() < end) {
|
||||
if (prefix(app, g.first)?.let { CloudSavePaths.profile(it).isDirectory } == true) { download(app, store, id); return@execute }
|
||||
if (ready()) { download(app, store, id); return@execute }
|
||||
Thread.sleep(2000)
|
||||
}
|
||||
done(store, id, "down", Result("skipped", 0, 0, "no-prefix"))
|
||||
@@ -304,8 +380,12 @@ object CloudSaves {
|
||||
if (dir != null && store == Store.GOG) migrateGogNested(context, id, g.first, dir)
|
||||
val cloud = if (dir != null) transport(context, store, id, g.first) else null
|
||||
when {
|
||||
cloud is UbisoftCloudTransport && dir?.parentFile?.name != cloud.user -> Result("skipped", 0, 0, "account-changed")
|
||||
dir == null -> Result("skipped", 0, 0, reason)
|
||||
cloud == null && store == Store.EA && signedIn(context, store) -> Result("failed", 0, 0, "sign-in-unreachable")
|
||||
cloud == null -> Result("skipped", 0, 0, "not-signed-in")
|
||||
cloud is EaCloud && cloud.localDir?.canonicalPath != dir.canonicalPath -> Result("skipped", 0, 0, "rules-changed")
|
||||
cloud is EaCloud && caseCollision(localFiles(dir).keys, cloud::wants) -> Result("failed", 0, 0, "case-collision")
|
||||
else -> body(dir, cloud).also { if (it.result == "ok") markSynced(context, store, id) }
|
||||
}
|
||||
}
|
||||
@@ -319,15 +399,32 @@ object CloudSaves {
|
||||
return done(store, id, way, result)
|
||||
}
|
||||
|
||||
internal fun caseCollision(names: Collection<String>, wants: (String) -> Boolean): Boolean =
|
||||
names.filter(wants).groupBy { it.lowercase() }.any { it.value.size > 1 }
|
||||
|
||||
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 localFiles(dir: File): Map<String, File> {
|
||||
if (!dir.isDirectory) return emptyMap()
|
||||
val root = runCatching { dir.toPath().toRealPath() }.getOrNull() ?: return emptyMap()
|
||||
val found = LinkedHashMap<String, File>()
|
||||
fun walk(d: File, prefix: String, ancestry: Set<java.nio.file.Path>) {
|
||||
for (child in d.listFiles().orEmpty()) {
|
||||
val real = runCatching { child.toPath().toRealPath() }.getOrNull() ?: continue
|
||||
if (!real.startsWith(root)) continue
|
||||
val name = prefix + child.name
|
||||
if (child.isDirectory) {
|
||||
if (real !in ancestry) walk(child, "$name/", ancestry + real)
|
||||
} else if (child.isFile) found[name] = child
|
||||
}
|
||||
}
|
||||
walk(dir, "", setOf(root))
|
||||
return found
|
||||
}
|
||||
|
||||
internal fun md5(f: File): String = md5(f.readBytes())
|
||||
|
||||
@@ -341,46 +438,85 @@ object CloudSaves {
|
||||
return files.associateBy { it.name }
|
||||
}
|
||||
|
||||
internal fun downWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean): Result {
|
||||
val files = localFiles(dir)
|
||||
internal fun downWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean, claim: () -> Boolean = { true }): Result {
|
||||
val files = localFiles(dir).filterKeys(cloud::wants)
|
||||
val remote = remote(cloud) { it in files }
|
||||
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
|
||||
val base = baseline(context, store, id)
|
||||
val plan = CloudPlan.down(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
|
||||
val take = if (force) plan.transfer + plan.conflicts else plan.transfer
|
||||
if (take.isNotEmpty() && files.isNotEmpty()) backup(context, store, id, dir, "local")
|
||||
val key = scope(store, id, dir)
|
||||
val base = baseline(context, store, key)
|
||||
val planned = CloudPlan.down(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
|
||||
val alike = alike(cloud, planned.conflicts, local, remote)
|
||||
val plan = settled(planned, alike)
|
||||
val saved = savedConflicts(context, store, key).filter { it in remote && it !in alike && it !in plan.same }
|
||||
val take = if (force) (plan.transfer + plan.conflicts + saved).distinct() else plan.transfer
|
||||
val next = HashMap(base.orEmpty())
|
||||
var bytes = 0L
|
||||
val written = HashSet<String>()
|
||||
val changed = ArrayList<String>()
|
||||
val blocked = ArrayList<String>()
|
||||
val fetched = LinkedHashMap<String, Pair<CloudFile, Pair<ByteArray, Long>>>()
|
||||
for (name in take) {
|
||||
val f = remote[name] ?: continue
|
||||
val (data, modified) = cloud.get(f)
|
||||
if (!File(dir, name).canonicalPath.startsWith(dir.canonicalPath + File.separator)) { blocked += name; continue }
|
||||
fetched[name] = f to cloud.get(f)
|
||||
}
|
||||
if (fetched.isNotEmpty() && !claim()) return Result("skipped", 0, 0, "launch-moved-on")
|
||||
val replaced = fetched.keys.mapNotNull { name -> files[name] ?: File(dir, name).takeIf { it.isFile } }
|
||||
if (!backupReplaced(context, store, id, dir, replaced)) return Result("failed", 0, 0, "backup-failed")
|
||||
for ((name, got) in fetched) {
|
||||
val (f, content) = got
|
||||
val (data, modified) = content
|
||||
val dest = File(dir, name)
|
||||
if (!dest.canonicalPath.startsWith(dir.canonicalPath + File.separator)) continue
|
||||
if ((if (dest.isFile) md5(dest) else null) != local[name]?.md5) { changed += name; continue }
|
||||
dest.parentFile?.mkdirs()
|
||||
dest.writeBytes(data)
|
||||
if (modified > 0) dest.setLastModified(modified)
|
||||
bytes += data.size
|
||||
written += name
|
||||
next[name] = CloudPlan.Entry(md5(data), f.md5, if (modified > 0) modified else f.modifiedMs)
|
||||
}
|
||||
for (name in plan.same) remote[name]?.let { r -> next[name] = CloudPlan.Entry(local.getValue(name).md5, r.md5, r.modifiedMs) }
|
||||
saveBaseline(context, store, id, next)
|
||||
val left = if (force) emptyList() else plan.conflicts
|
||||
saveConflicts(context, store, id, left)
|
||||
return Result("ok", take.size, bytes, if (take.isEmpty()) "up-to-date" else "downloaded", left.size)
|
||||
saveBaseline(context, store, key, next)
|
||||
val left = (if (force) take.filter { it !in written } else plan.conflicts + saved.filter { it !in written } + changed)
|
||||
.filter { it !in blocked }.distinct()
|
||||
saveConflicts(context, store, key, left)
|
||||
val reason = when {
|
||||
take.isEmpty() -> "up-to-date"
|
||||
changed.isNotEmpty() -> "changed-locally"
|
||||
blocked.isNotEmpty() -> "blocked-path"
|
||||
else -> "downloaded"
|
||||
}
|
||||
val detail = listOfNotNull(
|
||||
changed.takeIf { it.isNotEmpty() }?.joinToString(prefix = "changed locally: "),
|
||||
blocked.takeIf { it.isNotEmpty() }?.joinToString(prefix = "outside the save folder: "),
|
||||
).joinToString("; ")
|
||||
return Result(if (written.size < take.size) "partial" else "ok", written.size, bytes, reason, left.size, detail)
|
||||
}
|
||||
|
||||
internal fun upWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean): Result {
|
||||
val base = baseline(context, store, id) ?: return Result("skipped", 0, 0, "no-baseline")
|
||||
val files = localFiles(dir)
|
||||
val key = scope(store, id, dir)
|
||||
val base = baseline(context, store, key) ?: return Result("skipped", 0, 0, "no-baseline")
|
||||
val files = localFiles(dir).filterKeys(cloud::wants).let { all -> if (cloud is UbisoftCloudTransport) all.filterValues(::markUbisoftSave) else all }
|
||||
if (files.isEmpty()) return Result("skipped", 0, 0, "nothing-local")
|
||||
val remote = remote(cloud) { it in files }
|
||||
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
|
||||
val plan = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
|
||||
val send = CloudPlan.upSend(plan, force, cloud is GogCloud, files.keys)
|
||||
val planned = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
|
||||
val alike = alike(cloud, planned.conflicts, local, remote)
|
||||
val plan = settled(planned, alike)
|
||||
val saved = savedConflicts(context, store, key).filter { it !in alike && it !in plan.same }
|
||||
var send = CloudPlan.upSend(plan, force, cloud is GogCloud, files.keys)
|
||||
val next = HashMap(base)
|
||||
for (name in plan.same) remote[name]?.let { r -> next[name] = CloudPlan.Entry(local.getValue(name).md5, r.md5, r.modifiedMs) }
|
||||
var drifted = emptyList<String>()
|
||||
var raced = emptyList<String>()
|
||||
if (send.isNotEmpty()) {
|
||||
val copies = backupCloud(context, store, id, cloud, send.mapNotNull { remote[it] })
|
||||
if (cloud is UbisoftCloudTransport && !force) {
|
||||
drifted = send.filter { name -> val synced = base[name]?.localMd5; synced != null && copies[name]?.let { it != synced } == true }
|
||||
send = send - drifted.toSet()
|
||||
}
|
||||
}
|
||||
if (send.isNotEmpty()) {
|
||||
backupCloud(context, store, id, cloud, send.mapNotNull { remote[it] })
|
||||
val stamped = HashMap<String, Long>()
|
||||
val sentMd5 = HashMap<String, String>()
|
||||
if (cloud is GogCloud) {
|
||||
@@ -394,19 +530,40 @@ object CloudSaves {
|
||||
} else {
|
||||
val data = send.associateWith { files.getValue(it).readBytes() }
|
||||
for ((name, bytes) in data) sentMd5[name] = md5(bytes)
|
||||
stamped += cloud.put(data, send.associateWith { files.getValue(it).lastModified() })
|
||||
stamped += try {
|
||||
cloud.put(data, send.associateWith { files.getValue(it).lastModified() })
|
||||
} catch (e: CloudChanged) {
|
||||
raced = e.unsent
|
||||
e.sent
|
||||
} catch (e: Exception) {
|
||||
val kept = send.mapNotNull { name -> cloud.committed(name)?.let { name to it } }
|
||||
if (kept.isNotEmpty()) {
|
||||
for ((name, r) in kept) next[name] = CloudPlan.Entry(sentMd5.getValue(name), r.md5, r.modifiedMs)
|
||||
saveBaseline(context, store, key, next)
|
||||
saveConflicts(context, store, key, saved - kept.map { it.first }.toSet())
|
||||
}
|
||||
throw e
|
||||
}
|
||||
send = send.filter { it in stamped }
|
||||
for ((name, t) in stamped) if (t > 0) files[name]?.setLastModified(t)
|
||||
}
|
||||
val after = remote(cloud) { it in send }
|
||||
val after = if (send.all { cloud.committed(it) != null }) emptyMap() else remote(cloud) { it in send && cloud.committed(it) == null }
|
||||
for (name in send) {
|
||||
val r = after[name]
|
||||
val r = cloud.committed(name) ?: after[name]
|
||||
next[name] = CloudPlan.Entry(sentMd5.getValue(name), r?.md5, r?.modifiedMs ?: stamped[name] ?: -1L)
|
||||
}
|
||||
}
|
||||
saveBaseline(context, store, id, next)
|
||||
val left = if (force) emptyList() else plan.conflicts
|
||||
saveConflicts(context, store, id, left)
|
||||
return Result("ok", send.size, send.sumOf { files.getValue(it).length() }, if (send.isEmpty()) "up-to-date" else "uploaded", left.size)
|
||||
saveBaseline(context, store, key, next)
|
||||
val left = (if (force) (plan.conflicts + saved).filter { it !in send } + raced
|
||||
else plan.conflicts + drifted + raced + saved.filter { it !in send && it in files }).distinct()
|
||||
saveConflicts(context, store, key, left)
|
||||
val reason = when {
|
||||
raced.isNotEmpty() -> "changed-in-cloud"
|
||||
send.isEmpty() -> "up-to-date"
|
||||
else -> "uploaded"
|
||||
}
|
||||
return Result(if (raced.isEmpty()) "ok" else "partial", send.size, send.sumOf { files.getValue(it).length() }, reason, left.size,
|
||||
if (raced.isEmpty()) "" else raced.joinToString(prefix = "changed in the cloud: "))
|
||||
}
|
||||
|
||||
|
||||
@@ -441,23 +598,59 @@ object CloudSaves {
|
||||
private fun backupRoot(context: Context, store: Store, id: String) =
|
||||
File(context.filesDir, "stores/cloud-backups/${store.id}-${id.replace(Regex("[^A-Za-z0-9._-]"), "_")}")
|
||||
|
||||
private fun backup(context: Context, store: Store, id: String, dir: File, kind: String) {
|
||||
val root = backupRoot(context, store, id)
|
||||
runCatching { dir.copyRecursively(File(root, "$kind-${System.currentTimeMillis()}"), overwrite = true) }
|
||||
prune(root, kind)
|
||||
private fun markUbisoftSave(file: File): Boolean {
|
||||
val head = ByteArray(40)
|
||||
var filled = 0
|
||||
file.inputStream().use { input ->
|
||||
while (filled < head.size) {
|
||||
val n = input.read(head, filled, head.size - filled)
|
||||
if (n < 0) break
|
||||
filled += n
|
||||
}
|
||||
}
|
||||
if (filled < head.size) return false
|
||||
if (UbisoftCloud.mark(head) != null) return true
|
||||
if (head.copyOfRange(8, 40).any { it != 0.toByte() }) return false
|
||||
java.io.RandomAccessFile(file, "rw").use { it.seek(8); it.write(UbisoftCloud.freshMark().toByteArray(Charsets.ISO_8859_1)) }
|
||||
return true
|
||||
}
|
||||
|
||||
private fun backupCloud(context: Context, store: Store, id: String, cloud: CloudTransport, files: List<CloudFile>) {
|
||||
if (files.isEmpty()) return
|
||||
private fun backupCloud(context: Context, store: Store, id: String, cloud: CloudTransport, files: List<CloudFile>): Map<String, String> {
|
||||
if (files.isEmpty()) return emptyMap()
|
||||
val root = backupRoot(context, store, id)
|
||||
val target = File(root, "cloud-${System.currentTimeMillis()}")
|
||||
val copies = HashMap<String, String>()
|
||||
for (f in files) {
|
||||
val dest = File(target, f.name)
|
||||
if (!dest.canonicalPath.startsWith(target.canonicalPath + File.separator)) continue
|
||||
dest.parentFile?.mkdirs()
|
||||
dest.writeBytes(cloud.get(f).first)
|
||||
val data = cloud.get(f).first
|
||||
dest.writeBytes(data)
|
||||
copies[f.name] = md5(data)
|
||||
}
|
||||
prune(root, "cloud")
|
||||
return copies
|
||||
}
|
||||
|
||||
private fun backupReplaced(context: Context, store: Store, id: String, dir: File, replaced: List<File>): Boolean {
|
||||
if (replaced.isEmpty()) return true
|
||||
val base = runCatching { dir.canonicalPath + File.separator }.getOrNull() ?: return false
|
||||
val root = backupRoot(context, store, id)
|
||||
val stamp = "${System.currentTimeMillis()}-${java.util.UUID.randomUUID().toString().take(8)}"
|
||||
val staging = File(root, "staging-$stamp")
|
||||
val copied = runCatching {
|
||||
for (f in replaced) {
|
||||
check(f.canonicalPath.startsWith(base))
|
||||
f.copyTo(File(staging, f.relativeTo(dir).path), overwrite = true)
|
||||
}
|
||||
check(staging.renameTo(File(root, "local-$stamp")))
|
||||
}.isSuccess
|
||||
if (!copied) {
|
||||
staging.deleteRecursively()
|
||||
return false
|
||||
}
|
||||
prune(root, "local")
|
||||
return true
|
||||
}
|
||||
|
||||
private fun prune(root: File, kind: String) {
|
||||
|
||||
@@ -27,6 +27,10 @@ class CloudFile(val name: String, var modifiedMs: Long, var md5: String? = null,
|
||||
class CloudPut(val modifiedMs: Long, val md5: String?)
|
||||
|
||||
interface CloudTransport {
|
||||
/** False when [CloudFile.md5] is a version the service assigns rather than a digest of the content. */
|
||||
val contentDigests: Boolean get() = true
|
||||
fun committed(name: String): CloudFile? = null
|
||||
fun wants(name: String): Boolean = true
|
||||
fun list(): List<CloudFile>
|
||||
fun details(file: CloudFile) {}
|
||||
fun get(file: CloudFile): Pair<ByteArray, Long>
|
||||
@@ -182,6 +186,8 @@ internal fun isoDate(s: String?): Long {
|
||||
|
||||
class NoCloudSaves : Exception("no cloud saves")
|
||||
|
||||
class CloudChanged(val sent: Map<String, Long>, val unsent: List<String>) : Exception("cloud saves changed since they were read")
|
||||
|
||||
internal fun splitGogName(name: String): Pair<String?, String> {
|
||||
val slash = name.indexOf('/')
|
||||
return if (slash <= 0 || slash == name.length - 1) null to name
|
||||
|
||||
@@ -46,11 +46,18 @@ object StoreLaunchRequests {
|
||||
}
|
||||
|
||||
private fun answer(app: Context, file: File) {
|
||||
val resp = File(dir(app), "resp").apply { mkdirs() }
|
||||
val rid = file.name.removeSuffix(".json")
|
||||
val taken = File(resp, "$rid.taken")
|
||||
val writing = File(resp, "$rid.writing")
|
||||
if (!file.renameTo(taken)) return
|
||||
val request = try {
|
||||
JSONObject(file.readText()).also { file.delete() }
|
||||
JSONObject(taken.readText())
|
||||
} catch (e: Exception) {
|
||||
taken.delete()
|
||||
return
|
||||
}
|
||||
val claim = { taken.renameTo(writing) }
|
||||
val reply = when (request.optString("op")) {
|
||||
"xbox-released" -> {
|
||||
com.droiddeck.launcher.stores.xbox.XboxRuntime.released(request.optString("lease"))
|
||||
@@ -108,7 +115,7 @@ object StoreLaunchRequests {
|
||||
else {
|
||||
lastLaunched = store to id
|
||||
CloudSaves.markDirty(app, store, id)
|
||||
CloudSaves.downloadOrDefer(app, store, id).let { JSONObject().put("ok", it.ok).put("result", it.result).put("files", it.files).put("reason", it.reason) }
|
||||
CloudSaves.downloadOrDefer(app, store, id, claim).let { JSONObject().put("ok", it.ok).put("result", it.result).put("files", it.files).put("reason", it.reason) }
|
||||
}
|
||||
}
|
||||
"cloud-up" -> {
|
||||
@@ -167,12 +174,14 @@ object StoreLaunchRequests {
|
||||
else -> JSONObject().put("ok", false).put("reason", "unknown-op")
|
||||
}
|
||||
try {
|
||||
val resp = File(dir(app), "resp").apply { mkdirs() }
|
||||
val tmp = File(resp, file.name + ".tmp")
|
||||
tmp.writeText(reply.toString())
|
||||
tmp.renameTo(File(resp, file.name))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not answer ${file.name}: ${e.message}")
|
||||
} finally {
|
||||
taken.delete()
|
||||
writing.delete()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ object EaAuth {
|
||||
const val CLIENT_ID = "JUNO_PC_CLIENT"
|
||||
private const val CLIENT_SECRET = "4mRLtYMb6vq9qglomWEaT4ChxsXWcyqbQpuBNfMPOYOiDmYYQmjuaBsF2Zp0RyVeWkfqhE9TuGgAw7te"
|
||||
const val AUTH_URL = "https://accounts.ea.com/connect/auth"
|
||||
private const val TOKEN_URL = "https://accounts.ea.com/connect/token"
|
||||
internal var tokenUrl = "https://accounts.ea.com/connect/token"
|
||||
const val REDIRECT = "qrc:///html/login_successful.html"
|
||||
private const val REFRESH_MARGIN_MS = 5 * 60 * 1000L
|
||||
private val refreshLock = Any()
|
||||
@@ -41,8 +41,11 @@ object EaAuth {
|
||||
val personaId: String,
|
||||
val displayName: String,
|
||||
val eaId: String,
|
||||
val rejected: Boolean = false,
|
||||
)
|
||||
|
||||
private class Rejected(message: String) : IllegalStateException(message)
|
||||
|
||||
class Pending(val url: String, val verifier: String)
|
||||
|
||||
internal fun fromJson(o: JSONObject): Account? {
|
||||
@@ -55,6 +58,7 @@ object EaAuth {
|
||||
personaId = o.optString("persona_id"),
|
||||
displayName = o.optString("display_name"),
|
||||
eaId = o.optString("ea_id"),
|
||||
rejected = o.optBoolean("refresh_rejected"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -122,14 +126,15 @@ object EaAuth {
|
||||
|
||||
private fun tokenCall(values: List<Pair<String, String>>): JSONObject {
|
||||
val reply = EaHttp.request(
|
||||
TOKEN_URL, "POST",
|
||||
tokenUrl, "POST",
|
||||
mapOf("Content-Type" to "application/x-www-form-urlencoded"),
|
||||
EaHttp.form(values + listOf("client_id" to CLIENT_ID, "client_secret" to CLIENT_SECRET)).toByteArray(),
|
||||
follow = false,
|
||||
)
|
||||
val json = runCatching { JSONObject(reply.text) }.getOrNull()
|
||||
if (!reply.ok || json == null || json.optString("access_token").isEmpty()) {
|
||||
throw IllegalStateException("EA token request failed (${reply.status}): ${json?.optString("error_description")?.ifEmpty { json.optString("error") } ?: ""}")
|
||||
val message = "EA token request failed (${reply.status}): ${json?.optString("error_description")?.ifEmpty { json.optString("error") } ?: ""}"
|
||||
throw if (json?.optString("error") == "invalid_grant") Rejected(message) else IllegalStateException(message)
|
||||
}
|
||||
return json
|
||||
}
|
||||
@@ -162,6 +167,7 @@ object EaAuth {
|
||||
tokenCall(listOf("grant_type" to "refresh_token", "refresh_token" to a.refreshToken))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "refresh: ${e.message}")
|
||||
if (e is Rejected) markRejected(context, a.refreshToken)
|
||||
return null
|
||||
}
|
||||
val access = token.getString("access_token")
|
||||
@@ -176,11 +182,24 @@ object EaAuth {
|
||||
val record = StoreAccounts.read(app, Store.EA) ?: return false
|
||||
record.put("access_token", access).put("expires_at", System.currentTimeMillis() + expiresIn * 1000)
|
||||
refresh.takeIf { it.isNotEmpty() }?.let { record.put("refresh_token", it) }
|
||||
record.remove("refresh_rejected")
|
||||
player?.let { record.put("user_id", it.userId).put("persona_id", it.personaId).put("display_name", it.displayName).put("ea_id", it.eaId) }
|
||||
StoreAccounts.write(app, Store.EA, record)
|
||||
true
|
||||
}
|
||||
|
||||
private fun markRejected(context: Context, refresh: String) = synchronized(refreshLock) {
|
||||
val app = context.applicationContext
|
||||
val record = StoreAccounts.read(app, Store.EA) ?: return@synchronized
|
||||
if (record.optString("refresh_token") != refresh) return@synchronized
|
||||
StoreAccounts.write(app, Store.EA, record.put("refresh_rejected", true))
|
||||
}
|
||||
|
||||
fun signedIn(context: Context): Boolean {
|
||||
val a = load(context) ?: return false
|
||||
return a.userId.isNotEmpty() && !(a.rejected && a.expiresAt <= System.currentTimeMillis())
|
||||
}
|
||||
|
||||
fun accessToken(context: Context): String? {
|
||||
val current = load(context) ?: return null
|
||||
if (fresh(current)) return current.accessToken
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
package com.droiddeck.launcher.stores.ea
|
||||
|
||||
import android.util.Base64
|
||||
import android.util.Xml
|
||||
import com.droiddeck.launcher.stores.CloudFile
|
||||
import com.droiddeck.launcher.stores.CloudTransport
|
||||
import java.io.File
|
||||
import java.io.StringReader
|
||||
import java.security.MessageDigest
|
||||
import java.time.Instant
|
||||
import org.xmlpull.v1.XmlPullParser
|
||||
|
||||
internal class EaCloud(
|
||||
private val token: String,
|
||||
private val uid: String,
|
||||
private val keys: List<String>,
|
||||
private val base: String,
|
||||
private val rules: EaSaveRules,
|
||||
val localDir: File? = null,
|
||||
) : CloudTransport {
|
||||
class Entry(val size: Long, val href: String, val md5: String, val created: String, val modified: String, val localName: String)
|
||||
|
||||
class Manifest(val lineage: String, val files: List<Entry>, val snapshots: List<String>)
|
||||
|
||||
private class Signed(val url: String, val headers: Map<String, String>)
|
||||
|
||||
private class Request(val verb: String, val resource: String, val md5: String? = null, val type: String? = null)
|
||||
|
||||
private var key: String? = null
|
||||
private var found = false
|
||||
private var listed: Map<String, String?>? = null
|
||||
private val committed = HashMap<String, CloudFile>()
|
||||
|
||||
override fun wants(name: String): Boolean = rules.matches(base + name)
|
||||
|
||||
override fun committed(name: String): CloudFile? = committed[name]
|
||||
|
||||
override fun list(): List<CloudFile> {
|
||||
val manifest = pick()
|
||||
val files = manifest?.files.orEmpty().mapNotNull { e ->
|
||||
val path = EaSaveRules.normalize(e.localName)
|
||||
if (!path.startsWith(base, ignoreCase = true) || !rules.matches(path)) return@mapNotNull null
|
||||
val md5 = hex(e.md5) ?: error("EA listed ${path.substring(base.length)} without a valid checksum")
|
||||
CloudFile(localName(path.substring(base.length)), parseTime(e.modified), md5, readLink = e.href)
|
||||
}
|
||||
val twins = files.groupBy { it.name.lowercase() }.values.firstOrNull { it.size > 1 }
|
||||
check(twins == null) { "EA lists more than one save named ${twins!!.first().name} in different cases" }
|
||||
listed = files.associate { it.name.lowercase() to it.md5 }
|
||||
return files
|
||||
}
|
||||
|
||||
private fun localName(name: String): String {
|
||||
var dir = localDir ?: return name
|
||||
val parts = name.split('/')
|
||||
val out = ArrayList<String>()
|
||||
for (part in parts) {
|
||||
val match = dir.listFiles()?.filter { it.name.equals(part, ignoreCase = true) }.orEmpty()
|
||||
check(match.size <= 1) { "The save folder holds more than one file named $part in different cases" }
|
||||
val pick = match.singleOrNull()
|
||||
if (pick == null) return (out + parts.drop(out.size)).joinToString("/")
|
||||
out += pick.name
|
||||
dir = pick
|
||||
}
|
||||
return out.joinToString("/")
|
||||
}
|
||||
|
||||
override fun get(file: CloudFile): Pair<ByteArray, Long> {
|
||||
val href = file.readLink ?: error("EA has no data for ${file.name}")
|
||||
return locked("read", key ?: keys.first()) { lock, _ ->
|
||||
val signed = authorize(lock, listOf(Request("GET", href))).single()
|
||||
val reply = EaHttp.request(signed.url, headers = signed.headers)
|
||||
check(reply.ok) { "EA cloud save download answered ${reply.status}" }
|
||||
val want = file.md5 ?: error("EA listed ${file.name} without a valid checksum")
|
||||
check(hex(b64(md5(reply.body))) == want) { "EA cloud save ${file.name} failed its checksum" }
|
||||
reply.body to file.modifiedMs
|
||||
}
|
||||
}
|
||||
|
||||
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> {
|
||||
if (key == null) pick()
|
||||
check(found || keys.size == 1) { "EA has no cloud save record for this game yet; play it once in the EA app" }
|
||||
val target = key ?: keys.first()
|
||||
val seen = listed
|
||||
return locked("write", target) { lock, body ->
|
||||
val locked = manifestUrl(body)?.let { fetchManifest(it) }
|
||||
check(locked != null || !found) { "EA's cloud save record disappeared" }
|
||||
val current = locked ?: Manifest("{00000000-0000-0000-0000-000000000000}", emptyList(), emptyList())
|
||||
if (seen != null) for (name in files.keys) {
|
||||
val entry = current.files.firstOrNull { EaSaveRules.normalize(it.localName).equals(base + name, ignoreCase = true) }
|
||||
val now = entry?.let { hex(it.md5) ?: error("EA lists $name without a valid checksum") }
|
||||
check(now == seen[name.lowercase()]) { "EA's cloud saves changed since they were read" }
|
||||
}
|
||||
val now = System.currentTimeMillis()
|
||||
val added = files.map { (name, data) ->
|
||||
val sum = md5(data)
|
||||
val stamp = stamp(modifiedMs[name]?.takeIf { it > 0 } ?: now)
|
||||
val old = current.files.firstOrNull { EaSaveRules.normalize(it.localName).equals(base + name, ignoreCase = true) }
|
||||
Entry(data.size.toLong(), "content/${data.size}-${hexOf(sum)}", b64(sum), old?.created ?: stamp, stamp, base + name) to data
|
||||
}
|
||||
val names = added.map { it.first.localName.lowercase() }.toSet()
|
||||
val next = Manifest(current.lineage, current.files.filter { EaSaveRules.normalize(it.localName).lowercase() !in names } + added.map { it.first }, current.snapshots)
|
||||
val xml = write(next).toByteArray()
|
||||
val xmlMd5 = b64(md5(xml))
|
||||
val requests = added.map { Request("PUT", it.first.href, it.first.md5, "application/octet-stream") } + Request("PUT", "manifest.xml", xmlMd5, "text/xml")
|
||||
val signed = authorize(lock, requests)
|
||||
for ((i, pair) in added.withIndex()) upload(signed[i], pair.second)
|
||||
upload(signed.last(), xml)
|
||||
found = true
|
||||
for ((entry, _) in added) {
|
||||
val name = entry.localName.substring(base.length)
|
||||
committed[name] = CloudFile(name, parseTime(entry.modified), hex(entry.md5), readLink = entry.href)
|
||||
}
|
||||
listed = null
|
||||
files.mapValues { (name, _) -> modifiedMs[name]?.takeIf { it > 0 } ?: now }
|
||||
}
|
||||
}
|
||||
|
||||
private fun pick(): Manifest? {
|
||||
for (candidate in keys) {
|
||||
val manifest = locked("read", candidate, missing = { null }) { _, body -> manifestUrl(body)?.let { fetchManifest(it) } }
|
||||
if (manifest != null) {
|
||||
key = candidate
|
||||
found = true
|
||||
return manifest
|
||||
}
|
||||
}
|
||||
key = keys.first()
|
||||
found = false
|
||||
return null
|
||||
}
|
||||
|
||||
private fun upload(signed: Signed, data: ByteArray) {
|
||||
val reply = EaHttp.request(signed.url, "PUT", signed.headers, data)
|
||||
check(reply.ok) { "EA cloud save upload answered ${reply.status}" }
|
||||
}
|
||||
|
||||
private fun fetchManifest(url: String): Manifest? {
|
||||
val reply = EaHttp.request(url)
|
||||
if (reply.status == 404) return null
|
||||
check(reply.ok) { "EA cloud save manifest answered ${reply.status}" }
|
||||
return parse(reply.text)
|
||||
}
|
||||
|
||||
private fun <T> locked(kind: String, key: String, missing: (() -> T)? = null, body: (String, String) -> T): T {
|
||||
val reply = EaHttp.request("$HOST/lock/$kind/$uid/$key", "POST", mapOf(AUTH to token, "Content-Type" to "application/xml"), ByteArray(0))
|
||||
if (reply.status == 404 && missing != null) return missing()
|
||||
check(reply.ok) { "EA cloud saves answered ${reply.status}" }
|
||||
val lock = reply.header(LOCK) ?: error("EA did not grant a cloud save lock")
|
||||
try {
|
||||
return body(lock, reply.text)
|
||||
} finally {
|
||||
runCatching { EaHttp.request("$HOST/lock/delete/$uid", "DELETE", mapOf(AUTH to token, LOCK to lock)) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun authorize(lock: String, requests: List<Request>): List<Signed> {
|
||||
val body = buildString {
|
||||
append("<requests>")
|
||||
for ((i, r) in requests.withIndex()) {
|
||||
append("<request id=\"").append(i).append("\"><verb>").append(r.verb).append("</verb><resource>").append(escape(r.resource)).append("</resource>")
|
||||
r.md5?.let { append("<md5>").append(it).append("</md5>") }
|
||||
r.type?.let { append("<content-type>").append(it).append("</content-type>") }
|
||||
append("</request>")
|
||||
}
|
||||
append("</requests>")
|
||||
}
|
||||
val reply = EaHttp.request("$HOST/lock/authorize/$uid", "PUT", mapOf(AUTH to token, LOCK to lock, "Content-Type" to "application/xml"), body.toByteArray())
|
||||
check(reply.ok) { "EA cloud saves refused the transfer (${reply.status})" }
|
||||
return signedRequests(reply.text, requests.size)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val HOST = "https://cloudsync.juno.ea.com"
|
||||
private const val AUTH = "X-Origin-AuthToken"
|
||||
private const val LOCK = "X-Origin-Sync-Lock"
|
||||
private val REQUEST = Regex("<request\\b[^>]*\\bid=\"(\\d+)\"[^>]*>(.*?)</request>", RegexOption.DOT_MATCHES_ALL)
|
||||
private val HEADER = Regex("<header\\b([^>]*)/?>")
|
||||
|
||||
fun keys(masterTitleId: String, multiplayerId: String): List<String> =
|
||||
if (multiplayerId.isNotEmpty()) listOf("${masterTitleId}_$multiplayerId") else listOf(masterTitleId, "${masterTitleId}_$masterTitleId")
|
||||
|
||||
fun manifestUrl(lockBody: String): String? = Regex("<manifest>([^<]+)</manifest>").find(lockBody)?.groupValues?.get(1)?.let(::unescape)
|
||||
|
||||
fun parse(xml: String): Manifest {
|
||||
val p = Xml.newPullParser().apply { setInput(StringReader(xml)) }
|
||||
var root: String? = null
|
||||
var lineage: String? = null
|
||||
var depth = 0
|
||||
var closed = false
|
||||
val files = ArrayList<Entry>()
|
||||
val snapshots = ArrayList<String>()
|
||||
var file: Array<String>? = null
|
||||
var local: Entry? = null
|
||||
runCatching {
|
||||
while (p.next() != XmlPullParser.END_DOCUMENT) when (p.eventType) {
|
||||
XmlPullParser.START_TAG -> {
|
||||
depth++
|
||||
val at = { name: String -> p.getAttributeValue(null, name).orEmpty() }
|
||||
when {
|
||||
root == null -> { root = p.name; lineage = p.getAttributeValue(null, "lineage") }
|
||||
depth == 2 && p.name == "file" -> { file = arrayOf(at("size"), at("href"), at("md5")); local = null }
|
||||
depth == 3 && p.name == "localName" && file != null -> {
|
||||
val f = file!!
|
||||
val created = at("created")
|
||||
val modified = at("lastModified")
|
||||
local = Entry(f[0].toLongOrNull() ?: 0, f[1], f[2], created, modified, p.nextText())
|
||||
depth--
|
||||
}
|
||||
depth == 2 && p.name == "snapshot" -> { snapshots += p.nextText(); depth-- }
|
||||
}
|
||||
}
|
||||
XmlPullParser.END_TAG -> {
|
||||
if (depth == 2 && p.name == "file") { local?.let(files::add); file = null }
|
||||
depth--
|
||||
if (depth == 0) closed = true
|
||||
}
|
||||
}
|
||||
}.onFailure { error("EA sent an incomplete cloud save manifest") }
|
||||
check(root == "manifest" && depth == 0 && closed) { "EA sent an incomplete cloud save manifest" }
|
||||
return Manifest(lineage ?: "{00000000-0000-0000-0000-000000000000}", files, snapshots)
|
||||
}
|
||||
|
||||
fun write(m: Manifest): String = buildString {
|
||||
append("<manifest xmlns=\"http://origin.com/cloudsaves/manifest\" lineage=\"").append(escape(m.lineage)).append("\">\n")
|
||||
for (f in m.files) {
|
||||
append(" <file size=\"").append(f.size).append("\" href=\"").append(escape(f.href)).append("\" md5=\"").append(escape(f.md5)).append("\">\n")
|
||||
append(" <localName created=\"").append(escape(f.created)).append("\" lastModified=\"").append(escape(f.modified)).append("\">")
|
||||
append(escape(f.localName)).append("</localName>\n </file>\n")
|
||||
}
|
||||
for (s in m.snapshots) append(" <snapshot>").append(escape(s)).append("</snapshot>\n")
|
||||
append("</manifest>\n")
|
||||
}
|
||||
|
||||
private fun signedRequests(xml: String, count: Int): List<Signed> {
|
||||
val byId = REQUEST.findAll(xml).associate { m ->
|
||||
val inner = m.groupValues[2]
|
||||
val url = Regex("<url>([^<]+)</url>").find(inner)?.groupValues?.get(1)?.let(::unescape) ?: error("EA sent no transfer URL")
|
||||
val headers = HEADER.findAll(inner).mapNotNull { h ->
|
||||
val k = attr(h.groupValues[1], "key") ?: return@mapNotNull null
|
||||
k to (attr(h.groupValues[1], "value") ?: "")
|
||||
}.toMap()
|
||||
m.groupValues[1].toInt() to Signed(url, headers)
|
||||
}
|
||||
return (0 until count).map { byId[it] ?: error("EA signed ${byId.size} of $count cloud save transfers") }
|
||||
}
|
||||
|
||||
fun stamp(ms: Long): String = Instant.ofEpochMilli(ms / 1000 * 1000).toString() + "Z"
|
||||
|
||||
fun parseTime(s: String): Long = runCatching { Instant.parse(s.trimEnd('Z') + "Z").toEpochMilli() }.getOrDefault(-1L)
|
||||
|
||||
private fun attr(attrs: String, name: String): String? = Regex("\\b$name=\"([^\"]*)\"").find(attrs)?.groupValues?.get(1)?.let(::unescape)
|
||||
|
||||
private fun md5(data: ByteArray) = MessageDigest.getInstance("MD5").digest(data)
|
||||
|
||||
private fun b64(sum: ByteArray) = Base64.encodeToString(sum, Base64.NO_WRAP)
|
||||
|
||||
private fun hexOf(sum: ByteArray) = sum.joinToString("") { "%02x".format(it) }
|
||||
|
||||
fun hex(b64: String): String? = runCatching { hexOf(Base64.decode(b64, Base64.DEFAULT)) }.getOrNull()?.takeIf { it.length == 32 }
|
||||
|
||||
private fun escape(s: String) = s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """)
|
||||
|
||||
private fun unescape(s: String) = EaSaveRules.unescape(s)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.droiddeck.launcher.stores.ea
|
||||
|
||||
internal class EaSaveRules(private val rules: List<Pair<Boolean, String>>) {
|
||||
val includes get() = rules.filter { it.first }.map { it.second }
|
||||
val excludes get() = rules.filterNot { it.first }.map { it.second }
|
||||
|
||||
fun base(): String? {
|
||||
val dirs = includes.filterNot(::bare).map { pattern ->
|
||||
val wild = pattern.indexOfFirst { it == '*' || it == '?' }
|
||||
val fixed = if (wild < 0) pattern else pattern.substring(0, wild)
|
||||
if (fixed.endsWith('/')) fixed else fixed.substringBeforeLast('/', "") + "/"
|
||||
}
|
||||
val parts = dirs.map { it.trimEnd('/').split('/') }
|
||||
if (parts.isEmpty()) return null
|
||||
val common = ArrayList<String>()
|
||||
for (i in parts.minOf { it.size }.let { 0 until it }) {
|
||||
val seg = parts[0][i]
|
||||
if (parts.all { it[i].equals(seg, ignoreCase = true) }) common += seg else break
|
||||
}
|
||||
if (common.isEmpty() || !VARIABLE.matches(common[0])) return null
|
||||
return common.joinToString("/") + "/"
|
||||
}
|
||||
|
||||
fun matches(path: String): Boolean {
|
||||
val p = normalize(path)
|
||||
val inside = base()?.let { p.startsWith(it, ignoreCase = true) } ?: false
|
||||
return rules.firstOrNull { (_, pattern) -> if (bare(pattern)) inside && hit(pattern, p.substringAfterLast('/')) else hit(pattern, p) }?.first ?: false
|
||||
}
|
||||
|
||||
private fun bare(pattern: String) = !pattern.startsWith('%') && '/' !in pattern
|
||||
|
||||
private fun hit(pattern: String, path: String): Boolean = when {
|
||||
pattern.endsWith('/') -> path.startsWith(pattern, ignoreCase = true)
|
||||
pattern.any { it == '*' || it == '?' } -> glob(pattern).matches(path)
|
||||
else -> path.equals(pattern, ignoreCase = true)
|
||||
}
|
||||
|
||||
private fun glob(pattern: String): Regex = Regex(
|
||||
pattern.split('*').joinToString("[^/]*") { part -> part.split('?').joinToString("[^/]") { Regex.escape(it) } },
|
||||
RegexOption.IGNORE_CASE,
|
||||
)
|
||||
|
||||
companion object {
|
||||
private val VARIABLE = Regex("%[A-Za-z]+%")
|
||||
private val RULE = Regex("<(include|exclude)\\b([^>]*)>([^<]*)</\\1>", RegexOption.IGNORE_CASE)
|
||||
private val ORDER = Regex("\\border\\s*=\\s*[\"']?(\\d+)")
|
||||
private val TOKENS = mapOf(
|
||||
"documents" to "%DOCUMENTS%", "savedgames" to "%SAVED_GAMES%", "appdata" to "%APPDATA%",
|
||||
"localappdata" to "%LOCALAPPDATA%", "programdata" to "%PROGRAMDATA%", "userprofile" to "%USERPROFILE%",
|
||||
"locallowappdata" to "%APPLICATION_DATA_LOCAL_LOW%", "installdir" to "%INSTALL%",
|
||||
)
|
||||
|
||||
private val COMMENT = Regex("<!--.*?-->", RegexOption.DOT_MATCHES_ALL)
|
||||
private val ENTITY = Regex("&(#x[0-9a-fA-F]+|#[0-9]+|lt|gt|quot|apos|amp);")
|
||||
|
||||
fun normalize(path: String) = path.replace('\\', '/')
|
||||
|
||||
fun parse(xml: String): EaSaveRules? {
|
||||
val rules = RULE.findAll(COMMENT.replace(xml, "")).mapIndexed { index, rule ->
|
||||
val order = ORDER.find(rule.groupValues[2])?.groupValues?.get(1)?.toIntOrNull() ?: index
|
||||
Triple(order, rule.groupValues[1].equals("include", true), normalize(unescape(rule.groupValues[3]).trim()))
|
||||
}.filter { it.third.isNotEmpty() }.sortedBy { it.first }.map { it.second to it.third }.toList()
|
||||
if (rules.none { it.first }) return null
|
||||
return EaSaveRules(rules)
|
||||
}
|
||||
|
||||
fun template(base: String): String? {
|
||||
val variable = VARIABLE.find(base)?.takeIf { it.range.first == 0 } ?: return null
|
||||
val token = TOKENS[variable.value.trim('%').lowercase()] ?: return null
|
||||
return token + base.substring(variable.value.length)
|
||||
}
|
||||
|
||||
fun unescape(s: String): String = ENTITY.replace(s) { m ->
|
||||
when (val e = m.groupValues[1]) {
|
||||
"lt" -> "<"
|
||||
"gt" -> ">"
|
||||
"quot" -> "\""
|
||||
"apos" -> "'"
|
||||
"amp" -> "&"
|
||||
else -> runCatching { String(Character.toChars(if (e.startsWith("#x")) e.substring(2).toInt(16) else e.substring(1).toInt())) }.getOrDefault(m.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,23 +15,44 @@ object UbisoftActivation {
|
||||
private const val POLL_MS = 250L
|
||||
private const val IDLE_MS = 60_000L
|
||||
private val watching = HashMap<Long, Long>()
|
||||
private val owners = HashMap<Long, String>()
|
||||
|
||||
private const val INVALIDATE = "denuvo-invalidate"
|
||||
|
||||
fun bridge(context: Context, product: Long) = File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/ubisoft/bridge-$product")
|
||||
|
||||
/** Starts answering the product's activations; stale requests are cleared before this returns. */
|
||||
fun watch(app: Context, product: Long) {
|
||||
fun watch(app: Context, product: Long, owner: String?) {
|
||||
val dir = bridge(app, product)
|
||||
synchronized(watching) {
|
||||
val running = watching.containsKey(product)
|
||||
watching[product] = System.currentTimeMillis()
|
||||
if (owner.isNullOrEmpty()) owners.remove(product) else owners[product] = owner
|
||||
if (running) return
|
||||
dir.mkdirs()
|
||||
dir.listFiles()?.forEach { it.delete() }
|
||||
dir.listFiles()?.forEach { if (it.name != INVALIDATE) it.delete() }
|
||||
}
|
||||
Thread({
|
||||
var idleSince = 0L
|
||||
while (true) {
|
||||
runCatching { dir.listFiles { f -> f.name.startsWith("denuvo-") && f.name.endsWith(".req") }?.forEach { answer(app, product, it) } }
|
||||
runCatching {
|
||||
val marker = File(dir, INVALIDATE)
|
||||
val (owner, requests) = synchronized(watching) {
|
||||
owners[product] to dir.listFiles { f -> f.name.startsWith("denuvo-") && f.name.endsWith(".req") }.orEmpty()
|
||||
}
|
||||
if (marker.exists()) {
|
||||
val named = runCatching { marker.readText().trim() }.getOrNull()?.takeIf { it.isNotEmpty() }
|
||||
val issuer = named ?: owner
|
||||
if (invalidate(app, product, issuer)) marker.delete()
|
||||
else if (named == null && issuer != null) runCatching {
|
||||
val part = File(dir, "$INVALIDATE.part")
|
||||
part.writeText(issuer)
|
||||
check(part.renameTo(marker))
|
||||
}
|
||||
}
|
||||
val pending = marker.exists()
|
||||
requests.forEach { answer(app, product, it, owner, pending) }
|
||||
}
|
||||
.onFailure { StoresState.logLine("Ubisoft: activation for $product: ${it.javaClass.simpleName}") }
|
||||
val now = System.currentTimeMillis()
|
||||
if (SessionState.running) idleSince = 0L
|
||||
@@ -44,18 +65,31 @@ object UbisoftActivation {
|
||||
}, "ubisoft-activation-$product").start()
|
||||
}
|
||||
|
||||
private fun answer(app: Context, product: Long, request: File) {
|
||||
private fun answer(app: Context, product: Long, request: File, owner: String?, pending: Boolean) {
|
||||
val challenge = runCatching { request.readBytes() }.getOrNull() ?: return
|
||||
request.delete()
|
||||
val reply = File(request.parentFile, request.name.removeSuffix(".req") + ".rsp")
|
||||
val token = activate(app, product, challenge)
|
||||
val reply = File(request.parentFile, request.name.removeSuffix(".req").removeSuffix(".cache") + ".rsp")
|
||||
val token = activate(app, product, challenge, owner, cached = request.name.endsWith(".cache.req") && !pending)
|
||||
val part = File(reply.path + ".part")
|
||||
part.writeBytes(token ?: ByteArray(0))
|
||||
part.renameTo(reply)
|
||||
}
|
||||
|
||||
private fun activate(app: Context, product: Long, challenge: ByteArray): ByteArray? {
|
||||
private fun invalidate(app: Context, product: Long, owner: String?): Boolean {
|
||||
val user = owner ?: return false
|
||||
val gone = TokenCache(cacheDir(app)).drop(user, product)
|
||||
if (gone) StoresState.logLine("Ubisoft: activation for $product: kept game token dropped")
|
||||
return gone
|
||||
}
|
||||
|
||||
private fun activate(app: Context, product: Long, challenge: ByteArray, owner: String?, cached: Boolean): ByteArray? {
|
||||
val s = UbisoftAuth.current(app) ?: return null.also { StoresState.logLine("Ubisoft: activation for $product: signed out") }
|
||||
if (owner == null || s.userId != owner) return null.also { StoresState.logLine("Ubisoft: activation for $product: the signed-in account changed") }
|
||||
val cache = TokenCache(cacheDir(app))
|
||||
if (cached) cache.get(s.userId, product)?.let {
|
||||
StoresState.logLine("Ubisoft: activation for $product: kept ${it.size} B game token")
|
||||
return it
|
||||
}
|
||||
val answer = UbisoftNative.call("denuvo", JSONObject().put("ticket", s.ticket).put("sessionId", s.sessionId)
|
||||
.put("productId", product).put("challenge", hex(challenge)))
|
||||
answer?.optString("error")?.takeIf { it.isNotEmpty() }?.let {
|
||||
@@ -64,9 +98,28 @@ object UbisoftActivation {
|
||||
}
|
||||
val token = answer?.optString("token")?.takeIf { it.isNotEmpty() }?.let(::unhex)
|
||||
StoresState.logLine("Ubisoft: activation for $product: ${token?.size ?: 0} B game token")
|
||||
if (token != null && !cache.put(s.userId, product, token)) StoresState.logLine("Ubisoft: activation for $product: game token not kept")
|
||||
return token
|
||||
}
|
||||
|
||||
private fun cacheDir(app: Context) = File(app.filesDir, "ubisoft/denuvo")
|
||||
|
||||
internal class TokenCache(private val dir: File) {
|
||||
private fun file(user: String, product: Long) = File(dir, "${user.filter { it.isLetterOrDigit() || it == '-' }}-$product.token")
|
||||
|
||||
fun get(user: String, product: Long): ByteArray? = runCatching { file(user, product).readBytes() }.getOrNull()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
fun put(user: String, product: Long, token: ByteArray): Boolean = runCatching {
|
||||
dir.mkdirs()
|
||||
val target = file(user, product)
|
||||
val part = File(target.path + ".part")
|
||||
part.writeBytes(token)
|
||||
check(part.renameTo(target))
|
||||
}.isSuccess
|
||||
|
||||
fun drop(user: String, product: Long): Boolean = file(user, product).let { it.delete() || !it.exists() }
|
||||
}
|
||||
|
||||
internal fun hex(b: ByteArray): String = b.joinToString("") { "%02x".format(it) }
|
||||
|
||||
internal fun unhex(s: String): ByteArray? =
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
package com.droiddeck.launcher.stores.ubisoft
|
||||
|
||||
import android.os.Build
|
||||
import android.util.Base64
|
||||
import com.droiddeck.launcher.stores.CloudChanged
|
||||
import com.droiddeck.launcher.stores.CloudFile
|
||||
import com.droiddeck.launcher.stores.CloudTransport
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.MessageDigest
|
||||
import java.time.Instant
|
||||
import java.util.zip.Deflater
|
||||
import java.util.zip.Inflater
|
||||
|
||||
internal interface UbisoftSlots {
|
||||
fun entity(): UbisoftCloud.Entity?
|
||||
fun upload(slot: String, data: ByteArray)
|
||||
fun update(entity: UbisoftCloud.Entity, slots: JSONArray)
|
||||
fun download(slot: String): ByteArray?
|
||||
}
|
||||
|
||||
internal class UbisoftCloud(private val session: UbisoftAuth.Session, val product: Long) : UbisoftSlots {
|
||||
class Slot(val id: Int, val filename: String, val hash: String, val size: Long, val modifiedMs: Long)
|
||||
|
||||
class Entity(val json: JSONObject) {
|
||||
val id: String get() = json.optString("entityId")
|
||||
val revision: Int get() = json.optInt("revision")
|
||||
val slots: List<Slot> get() {
|
||||
val list = json.optJSONObject("obj")?.optJSONArray("slots") ?: JSONArray()
|
||||
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.map {
|
||||
Slot(it.optInt("id"), it.optString("filename"), it.optString("hash"), it.optLong("size"), UbisoftAuth.parseTime(it.optString("lastModified")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val authorization get() = "ubi_v1 t=${session.ticket}"
|
||||
|
||||
override fun entity(): Entity? {
|
||||
val url = "https://public-ubiservices.ubi.com/v1/profiles/${session.profileId}/entities?name=${entityName(product)}"
|
||||
val reply = UbisoftAuth.request(url, authorization = authorization, sessionId = session.sessionId)
|
||||
check(reply.ok) { "Ubisoft cloud saves answered ${reply.status}" }
|
||||
val list = JSONObject(reply.body).optJSONArray("entities") ?: return null
|
||||
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.firstOrNull { it.optString("name") == entityName(product) }?.let(::Entity)
|
||||
}
|
||||
|
||||
override fun upload(slot: String, data: ByteArray) {
|
||||
val packed = deflate(data)
|
||||
val md5 = Base64.encodeToString(MessageDigest.getInstance("MD5").digest(packed), Base64.NO_WRAP)
|
||||
val signed = signed("put", JSONArray().put(JSONObject().put("name", slot).put("size", packed.size).put("md5", md5))).single()
|
||||
val c = URL(signed.getString("url")).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 15_000
|
||||
c.readTimeout = 60_000
|
||||
c.requestMethod = "PUT"
|
||||
c.doOutput = true
|
||||
c.setFixedLengthStreamingMode(packed.size)
|
||||
c.setRequestProperty("Content-MD5", md5)
|
||||
try {
|
||||
c.outputStream.use { it.write(packed) }
|
||||
check(c.responseCode in 200..299) { "Ubisoft cloud save upload answered ${c.responseCode}" }
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
override fun update(entity: Entity, slots: JSONArray) {
|
||||
val obj = JSONObject(entity.json.optJSONObject("obj")?.toString() ?: "{}")
|
||||
.put("slots", slots).put("timestamp", (System.currentTimeMillis() / 1000).toString()).put("pc_name", Build.MODEL ?: "Android")
|
||||
val body = JSONObject().put("revision", entity.revision).put("name", entity.json.optString("name")).put("type", "cloudSave")
|
||||
.put("spaceId", entity.json.optString("spaceId")).put("tags", entity.json.optJSONArray("tags") ?: JSONArray()).put("obj", obj)
|
||||
val reply = UbisoftAuth.request("https://public-ubiservices.ubi.com/v1/profiles/entities/${entity.id}", "PUT",
|
||||
authorization, session.sessionId, body.toString())
|
||||
check(reply.ok) { "Ubisoft cloud save record answered ${reply.status}" }
|
||||
}
|
||||
|
||||
override fun download(slot: String): ByteArray? {
|
||||
val signed = signed("get", JSONArray().put(JSONObject().put("name", slot))).single()
|
||||
val c = URL(signed.getString("url")).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 15_000
|
||||
c.readTimeout = 60_000
|
||||
return try {
|
||||
when (c.responseCode) {
|
||||
404 -> null
|
||||
in 200..299 -> c.inputStream.use(::inflate)
|
||||
else -> error("Ubisoft cloud save download answered ${c.responseCode}")
|
||||
}
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun signed(method: String, items: JSONArray): List<JSONObject> {
|
||||
val answer = UbisoftNative.call("cloud-urls", JSONObject().put("ticket", session.ticket).put("sessionId", session.sessionId)
|
||||
.put("productId", product).put("method", method).put("items", items)) ?: error("Ubisoft cloud saves are unavailable")
|
||||
answer.optString("error").takeIf { it.isNotEmpty() }?.let { error(it) }
|
||||
val requests = answer.getJSONArray("requests")
|
||||
return (0 until requests.length()).map { requests.getJSONObject(it) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val MAX_SAVE = 256L * 1024 * 1024
|
||||
|
||||
fun entityName(product: Long) = "upcCloudSaveUplayId_$product"
|
||||
|
||||
private val MARK = Regex("[0-9a-f]{32}")
|
||||
|
||||
internal fun freshMark(): String = java.util.UUID.randomUUID().toString().replace("-", "")
|
||||
|
||||
internal fun mark(save: ByteArray): String? =
|
||||
if (save.size < 40) null else String(save, 8, 32, Charsets.ISO_8859_1).takeIf { MARK.matches(it) }
|
||||
|
||||
internal fun deflate(data: ByteArray): ByteArray {
|
||||
val deflater = Deflater(Deflater.BEST_COMPRESSION)
|
||||
deflater.setInput(data)
|
||||
deflater.finish()
|
||||
val out = ByteArrayOutputStream(data.size / 2 + 64)
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
try {
|
||||
while (!deflater.finished()) out.write(buffer, 0, deflater.deflate(buffer))
|
||||
} finally {
|
||||
deflater.end()
|
||||
}
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
internal fun inflate(data: ByteArray): ByteArray = inflate(data.inputStream())
|
||||
|
||||
internal fun inflate(input: java.io.InputStream): ByteArray {
|
||||
val inflater = Inflater()
|
||||
val out = ByteArrayOutputStream(64 * 1024)
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
val chunk = ByteArray(64 * 1024)
|
||||
try {
|
||||
while (!inflater.finished()) {
|
||||
if (inflater.needsInput()) {
|
||||
val read = input.read(chunk)
|
||||
if (read < 0) error("Ubisoft cloud save is truncated")
|
||||
inflater.setInput(chunk, 0, read)
|
||||
continue
|
||||
}
|
||||
if (inflater.needsDictionary()) error("Ubisoft cloud save is truncated")
|
||||
val n = inflater.inflate(buffer)
|
||||
check(out.size().toLong() + n <= MAX_SAVE) { "Ubisoft cloud save is too large" }
|
||||
out.write(buffer, 0, n)
|
||||
}
|
||||
} finally {
|
||||
inflater.end()
|
||||
}
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
internal fun version(slot: Slot): String = "${slot.size}:${slot.modifiedMs}:${slot.hash}"
|
||||
}
|
||||
}
|
||||
|
||||
internal class UbisoftCloudTransport(private val cloud: UbisoftSlots, val user: String) : CloudTransport {
|
||||
private var listed: UbisoftCloud.Entity? = null
|
||||
private val committed = HashMap<String, CloudFile>()
|
||||
|
||||
override val contentDigests: Boolean get() = false
|
||||
|
||||
override fun committed(name: String): CloudFile? = committed[name]
|
||||
|
||||
override fun wants(name: String): Boolean = name.endsWith(SUFFIX) && !name.contains('/')
|
||||
|
||||
override fun list(): List<CloudFile> {
|
||||
val entity = cloud.entity()
|
||||
listed = entity
|
||||
return entity?.slots.orEmpty().map { CloudFile(it.filename + SUFFIX, it.modifiedMs, UbisoftCloud.version(it)) }
|
||||
}
|
||||
|
||||
override fun get(file: CloudFile): Pair<ByteArray, Long> {
|
||||
val data = cloud.download(file.name.removeSuffix(SUFFIX)) ?: error("Ubisoft has no data for ${file.name}")
|
||||
return data to file.modifiedMs
|
||||
}
|
||||
|
||||
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> {
|
||||
var expected = listed ?: cloud.entity() ?: error("Ubisoft has no cloud save record for this game yet; play it once in Ubisoft Connect")
|
||||
val marks = files.mapValues { (name, data) ->
|
||||
check(name.endsWith(SUFFIX) && !name.contains('/')) { "$name is not a Ubisoft save slot" }
|
||||
UbisoftCloud.mark(data) ?: error("$name has no save identifier for Ubisoft Connect")
|
||||
}
|
||||
val sent = LinkedHashMap<String, Long>()
|
||||
try {
|
||||
for ((name, data) in files) {
|
||||
val slot = name.removeSuffix(SUFFIX)
|
||||
val live = cloud.entity() ?: error("Ubisoft's cloud save record disappeared")
|
||||
if (live.revision != expected.revision) throw CloudChanged(sent, files.keys.filter { it !in sent })
|
||||
val now = System.currentTimeMillis()
|
||||
cloud.upload(slot, data)
|
||||
val slots = JSONArray(live.json.optJSONObject("obj")?.optJSONArray("slots")?.toString() ?: "[]")
|
||||
val entry = (0 until slots.length()).map { slots.getJSONObject(it) }.firstOrNull { it.optString("filename") == slot }
|
||||
?: JSONObject().put("filename", slot).also { if (slot.toIntOrNull() != null) it.put("id", slot.toInt()); slots.put(it) }
|
||||
entry.put("hash", marks.getValue(name)).put("size", data.size).put("lastModified", Instant.ofEpochMilli(now).toString())
|
||||
cloud.update(live, slots)
|
||||
val after = cloud.entity()
|
||||
val mine = after?.let { committedSlot(live, it, slot, marks.getValue(name), data.size.toLong()) }
|
||||
?: throw CloudChanged(sent, files.keys.filter { it !in sent })
|
||||
sent[name] = now
|
||||
committed[name] = CloudFile(name, mine.modifiedMs, UbisoftCloud.version(mine))
|
||||
expected = after
|
||||
}
|
||||
} finally {
|
||||
listed = null
|
||||
}
|
||||
return sent
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val SUFFIX = ".save"
|
||||
|
||||
internal fun committedSlot(before: UbisoftCloud.Entity, after: UbisoftCloud.Entity, filename: String, hash: String, size: Long): UbisoftCloud.Slot? {
|
||||
fun others(e: UbisoftCloud.Entity) = e.slots.filter { it.filename != filename }.associate { it.filename to UbisoftCloud.version(it) }
|
||||
if (others(before) != others(after)) return null
|
||||
return after.slots.firstOrNull { it.filename == filename && it.hash == hash && it.size == size }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,7 @@ object UbisoftLaunch {
|
||||
}
|
||||
} ?: cached
|
||||
setup?.let { StoresState.logLine("Ubisoft: setup for $product: ${it.toString().take(1500)}") }
|
||||
UbisoftActivation.watch(app, product)
|
||||
UbisoftActivation.watch(app, product, s.userId)
|
||||
return JSONObject().put("ok", true)
|
||||
.put("productId", product)
|
||||
.put("ticket", native.optString("ticket"))
|
||||
|
||||
@@ -82,6 +82,12 @@ internal fun cloudMessage(context: android.content.Context, r: com.droiddeck.lau
|
||||
r.files == 0 -> context.getString(R.string.cloud_up_to_date)
|
||||
else -> context.getString(R.string.cloud_done, r.files)
|
||||
}
|
||||
"partial" -> when {
|
||||
r.conflicts > 0 && r.detail.isNotEmpty() -> context.getString(R.string.cloud_conflict_files_detail, r.conflicts, r.detail)
|
||||
r.conflicts > 0 -> context.getString(R.string.cloud_conflict_files, r.conflicts)
|
||||
r.detail.isNotEmpty() -> context.getString(R.string.cloud_partial, r.detail)
|
||||
else -> context.getString(R.string.cloud_not_synced)
|
||||
}
|
||||
"skipped" -> context.getString(when (r.reason) {
|
||||
"not-signed-in" -> R.string.cloud_signed_out
|
||||
"no-cloud-saves" -> R.string.cloud_none
|
||||
|
||||
@@ -258,7 +258,7 @@ internal fun GameDetail(
|
||||
stringResource(R.string.game_tab_achievements_count, stringResource(R.string.achievements_title), achievementState.done, list.size)
|
||||
} ?: stringResource(R.string.achievements_title)
|
||||
GameTab.LAUNCH -> stringResource(R.string.game_tab_launch)
|
||||
GameTab.SAVES -> stringResource(if (Store.byId(source).let { it == Store.GOG || it == Store.EPIC }) R.string.game_tab_saves_cloud else R.string.games_saves)
|
||||
GameTab.SAVES -> stringResource(if (CloudSaves.supports(Store.byId(source))) R.string.game_tab_saves_cloud else R.string.games_saves)
|
||||
GameTab.ADDONS -> stringResource(R.string.game_tab_addons)
|
||||
GameTab.INSTALL -> stringResource(R.string.game_tab_install)
|
||||
}
|
||||
@@ -892,8 +892,10 @@ private fun ShortcutFields(game: Library.SteamGame, folder: File) {
|
||||
|
||||
@Composable
|
||||
private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
|
||||
val saves by produceState<List<GameSaves.SaveDir>?>(null, g.gameId) {
|
||||
value = withContext(Dispatchers.IO) { runCatching { GameSaves.locate(prefix, g) }.getOrDefault(emptyList()) }
|
||||
val context = LocalContext.current.applicationContext
|
||||
var synced by remember(g.gameId) { mutableStateOf(0) }
|
||||
val saves by produceState<List<GameSaves.SaveDir>?>(null, g.gameId, synced) {
|
||||
value = withContext(Dispatchers.IO) { runCatching { GameSaves.saves(context, prefix, g) }.getOrDefault(emptyList()) }
|
||||
}
|
||||
val found = saves
|
||||
val summary = when {
|
||||
@@ -911,9 +913,9 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(summary, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 6.dp).readable().padding(4.dp))
|
||||
if (Store.byId(g.source).let { it == Store.GOG || it == Store.EPIC }) {
|
||||
if (CloudSaves.supports(Store.byId(g.source))) {
|
||||
SectionLabel(stringResource(R.string.store_cloud_saves))
|
||||
CloudRows(g)
|
||||
CloudRows(g) { synced++ }
|
||||
SectionLabel(stringResource(R.string.games_saves))
|
||||
}
|
||||
MenuItem(stringResource(R.string.games_import_saves), checked = false) { a.onSaveImport(g) }
|
||||
@@ -969,14 +971,16 @@ private fun AddonRow(name: String, target: WowAddons.Target, a: FrontEndActions)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CloudRows(g: Library.SteamGame) {
|
||||
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON && it != Store.EA } ?: return
|
||||
private fun CloudRows(g: Library.SteamGame, onSynced: () -> Unit = {}) {
|
||||
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON } ?: return
|
||||
val id = g.storeId ?: return
|
||||
val context = LocalContext.current.applicationContext
|
||||
var busy by remember(g.gameId) { mutableStateOf<String?>(null) }
|
||||
var tick by remember(g.gameId) { mutableStateOf(0) }
|
||||
var refreshing by remember(g.gameId) { mutableStateOf(false) }
|
||||
val status by produceState<CloudSaves.Status?>(null, g.gameId, tick) {
|
||||
value = withContext(Dispatchers.IO) { runCatching { CloudSaves.status(context, store, id) }.getOrNull() }
|
||||
refreshing = false
|
||||
}
|
||||
val folder = g.gameFiles
|
||||
var enabled by remember(g.gameId) { mutableStateOf(folder?.let { StoreGameSidecar.read(it)?.cloud } ?: true) }
|
||||
@@ -988,7 +992,7 @@ private fun CloudRows(g: Library.SteamGame) {
|
||||
busy = if (up) "up" else "down"
|
||||
Thread({
|
||||
val r = if (up) CloudSaves.upload(context, store, id, force) else CloudSaves.download(context, store, id, force)
|
||||
StoresState.post { busy = null; tick++; android.widget.Toast.makeText(context, cloudMessage(context, r), android.widget.Toast.LENGTH_SHORT).show() }
|
||||
StoresState.post { refreshing = true; busy = null; tick++; onSynced(); android.widget.Toast.makeText(context, cloudMessage(context, r), android.widget.Toast.LENGTH_SHORT).show() }
|
||||
}, "cloud-manual").start()
|
||||
}
|
||||
MenuItem(stringResource(R.string.store_cloud_saves), checked = enabled && supported, enabled = supported,
|
||||
@@ -1000,11 +1004,13 @@ private fun CloudRows(g: Library.SteamGame) {
|
||||
StoresState.post { enabled = written?.cloud ?: enabled }
|
||||
}, "cloud-switch").start()
|
||||
}
|
||||
val ready = st != null && supported && enabled && busy == null
|
||||
val ready = st != null && supported && enabled && busy == null && !refreshing && st.folder != null && st.signedIn
|
||||
val pending = stringResource(R.string.cloud_pending)
|
||||
val summary = when {
|
||||
st == null || busy != null -> pending
|
||||
!supported -> stringResource(R.string.cloud_none)
|
||||
!st.signedIn || st.reason == "not-signed-in" -> stringResource(R.string.cloud_signed_out)
|
||||
st.folder == null -> stringResource(R.string.cloud_not_synced)
|
||||
conflict -> stringResource(R.string.cloud_conflict_files, st.conflicts.size)
|
||||
st.lastSync > 0 -> stringResource(R.string.cloud_last_sync, android.text.format.DateUtils.getRelativeTimeSpanString(st.lastSync).toString())
|
||||
else -> stringResource(R.string.cloud_never)
|
||||
|
||||
Reference in new issue
Block a user