fix(ea): sync at EA launch and exit, keep one rule snapshot, and check the cloud copy under the write lock

This commit is contained in:
Kurt Himebauch committed 2026-11-18 09:07:54 -05:00
1 parent 7d134ae459
commit 7d47c61e24
9 files changed
+100 -20

No files matched your search

@@ -190,13 +190,13 @@ object CloudSaves {
}
Store.EA -> {
val sidecar = StoreGameSidecar.read(folder)
val rules = eaRules(context, id)?.let(EaSaveRules::parse)
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)
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.UBISOFT, Store.ROCKSTAR -> null
}
@@ -354,9 +354,12 @@ object CloudSaves {
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.canonicalPath + File.separator }.getOrNull() ?: return emptyMap()
return dir.walkTopDown().filter { it.isFile && runCatching { it.canonicalPath.startsWith(root) }.getOrDefault(false) }
.associateBy { it.relativeTo(dir).path.replace(File.separatorChar, '/') }
}
internal fun md5(f: File): String = md5(f.readBytes())
@@ -428,7 +431,7 @@ object CloudSaves {
}
val after = remote(cloud) { it in send }
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)
}
}
@@ -28,6 +28,7 @@ class CloudPut(val modifiedMs: Long, val md5: String?)
interface CloudTransport {
fun wants(name: String): Boolean = true
fun committed(name: String): CloudFile? = null
fun list(): List<CloudFile>
fun details(file: CloudFile) {}
fun get(file: CloudFile): Pair<ByteArray, Long>
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.stores.ea
import android.util.Base64
import com.droiddeck.launcher.stores.CloudFile
import com.droiddeck.launcher.stores.CloudTransport
import java.io.File
import java.security.MessageDigest
import java.time.Instant
@@ -12,6 +13,7 @@ internal class EaCloud(
private val keys: List<String>,
private val base: String,
private val rules: EaSaveRules,
private 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)
@@ -23,16 +25,36 @@ internal class EaCloud(
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()
return manifest?.files.orEmpty().mapNotNull { e ->
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
CloudFile(path.substring(base.length), parseTime(e.modified), hex(e.md5), readLink = e.href)
CloudFile(localName(path.substring(base.length)), parseTime(e.modified), hex(e.md5), readLink = e.href)
}
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()
val pick = match.singleOrNull() ?: match.firstOrNull { it.name == part }
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> {
@@ -50,8 +72,15 @@ internal class EaCloud(
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 current = manifestUrl(body)?.let { fetchManifest(it) } ?: Manifest("{00000000-0000-0000-0000-000000000000}", emptyList(), emptyList())
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 now = current.files.firstOrNull { EaSaveRules.normalize(it.localName).equals(base + name, ignoreCase = true) }?.let { hex(it.md5) }
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)
@@ -68,6 +97,11 @@ internal class EaCloud(
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 }
}
}
@@ -149,7 +183,7 @@ internal class EaCloud(
Entry(attr(a, "size")?.toLongOrNull() ?: 0, attr(a, "href").orEmpty(), attr(a, "md5").orEmpty(),
attr(local.groupValues[1], "created").orEmpty(), attr(local.groupValues[1], "lastModified").orEmpty(), unescape(local.groupValues[2]))
}.toList()
return Manifest(lineage, files, SNAPSHOT.findAll(xml).map { it.groupValues[1] }.toList())
return Manifest(lineage, files, SNAPSHOT.findAll(xml).map { unescape(it.groupValues[1]) }.toList())
}
fun write(m: Manifest): String = buildString {
@@ -192,6 +226,6 @@ internal class EaCloud(
private fun escape(s: String) = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;")
private fun unescape(s: String) = s.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&apos;", "'").replace("&amp;", "&")
private fun unescape(s: String) = EaSaveRules.unescape(s)
}
}
@@ -133,7 +133,7 @@ internal class EaInstaller(
return StoreGameSidecar(
Store.EA, item.id, item.title, exe = exe, args = args,
installVersion = version.ifEmpty { manifest?.version.orEmpty() }, installedAt = System.currentTimeMillis(),
cover = cover, hero = item.imageUrl, extra = extra, cloud = !game?.cloudSaves.isNullOrBlank(), logo = item.logoUrl,
cover = cover, hero = item.imageUrl, extra = extra, cloud = false, logo = item.logoUrl,
)
}
}
@@ -43,10 +43,13 @@ internal class EaSaveRules(val includes: List<String>, val excludes: List<String
"localappdata" to "%LOCALAPPDATA%", "programdata" to "%PROGRAMDATA%", "userprofile" to "%USERPROFILE%",
)
fun normalize(path: String) = path.trim().replace('\\', '/')
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(xml).map { it.groupValues[1].lowercase() to normalize(unescape(it.groupValues[2])) }
val rules = RULE.findAll(COMMENT.replace(xml, "")).map { it.groupValues[1].lowercase() to normalize(unescape(it.groupValues[2]).trim()) }
.filter { it.second.isNotEmpty() }.toList()
val includes = rules.filter { it.first == "include" }.map { it.second }
if (includes.isEmpty()) return null
@@ -59,6 +62,15 @@ internal class EaSaveRules(val includes: List<String>, val excludes: List<String
return token + base.substring(variable.value.length)
}
private fun unescape(s: String) = s.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&apos;", "'").replace("&amp;", "&")
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)
}
}
}
}
@@ -1000,11 +1000,12 @@ 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 && st.folder != null
val pending = stringResource(R.string.cloud_pending)
val summary = when {
st == null || busy != null -> pending
!supported -> stringResource(R.string.cloud_none)
st.folder == null -> stringResource(if (st.reason == "not-signed-in") R.string.cloud_signed_out else 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)
@@ -64,6 +64,22 @@ class EaCloudTest {
assertEquals(m.lineage, again.lineage)
}
@Test fun commentedRulesAreIgnoredAndNamesKeepTheirSpaces() {
val rules = EaSaveRules.parse("""<saveFileCriteria>
<!-- <exclude order="0">%Documents%/Game/Config/</exclude> -->
<include order="1"> %Documents%/Game/ </include></saveFileCriteria>""")!!
assertEquals(listOf("%Documents%/Game/"), rules.includes)
assertTrue(rules.excludes.isEmpty())
assertTrue(rules.matches("%Documents%/Game/Config/a.ini"))
assertEquals("%Documents%/Game/slot.sav ", EaSaveRules.normalize("%Documents%\\Game\\slot.sav "))
}
@Test fun snapshotEntitiesAreDecodedOnceAndWrittenBackTheSame() {
val m = EaCloud.parse("""<manifest lineage="{1}"><snapshot>abc&#x2B;def</snapshot></manifest>""")
assertEquals(listOf("abc+def"), m.snapshots)
assertEquals(listOf("abc+def"), EaCloud.parse(EaCloud.write(m)).snapshots)
}
@Test fun cloudKeysFollowTheMultiplayerId() {
assertEquals(listOf("195133_195133"), EaCloud.keys("195133", "195133"))
assertEquals(listOf("52209", "52209_52209"), EaCloud.keys("52209", ""))
@@ -304,7 +304,6 @@ def exited(argv, code=0):
if found is not None and launch_dir and str(found[1].get("store")) == "ea":
ask(Path(launch_dir) / "stores", {"op": "ea-exited", "store": "ea", "id": str(found[1].get("id"))}, timeout=1.0)
log("ea %s exited" % found[1].get("id"))
return 0
if found is None or not launch_dir or not cloud_on(found[1]):
return 0
store, game = str(found[1].get("store")), str(found[1].get("id"))
@@ -1601,7 +1600,7 @@ def main(argv):
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
prefix_id = os.path.basename(compat_data) if compat_data else ""
launch_dir = os.environ.get("DD_LAUNCH_DIR", "")
if launch_dir and cloud_on(sidecar):
if launch_dir and cloud_on(sidecar) and store != "ea":
made = create_prefix(compat_data, os.environ.get("DD_STORE_PROTON", ""))
if made != "present":
log("cloud %s %s prefix=%s" % (store, game, made))
@@ -1670,11 +1669,10 @@ def main(argv):
log("epic prefix=%s %s" % (prefix_id or "?", provision_prefix(compat_data)))
if store == "ea":
prepare_ea(folder, sidecar, compat_data, launch_dir)
return STORE_GAME
if not cloud_on(sidecar):
if store in CLOUD_STORES:
log("cloud %s %s down result=skipped reason=off" % (store, game))
return 0
return STORE_GAME if store == "ea" else 0
if launch_dir:
answer = ask(Path(launch_dir) / "stores", {"op": "cloud-down", "store": store, "id": game}, timeout=CLOUD_TIMEOUT)
if answer is None:
+15
View File
@@ -225,6 +225,21 @@ class CloudHooks(unittest.TestCase):
self.assertEqual(store.CLOUD_TIMEOUT, asked[1][1])
self.assertEqual('cloud-up', asked[2][0]['op'])
def test_an_ea_game_with_cloud_saves_asks_after_its_preparation_and_exit(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='ea', ident='Origin.OFR.50.0002694')
bat = str(folder / '.droiddeck-launch.bat')
asked = []
with patch.dict(os.environ, {'DD_LAUNCH_DIR': str(Path(root) / 'session')}), patch.object(store, 'prepare_ea', side_effect=lambda *a: asked.append({'op': 'prepared'})), patch.object(store, 'create_prefix', side_effect=AssertionError('EA prepares its own prefix')), patch.object(store, 'ask', side_effect=lambda channel, request, timeout=5.0: asked.append(request) or {'result': 'ok'}):
self.assertEqual(store.STORE_GAME, store.main([bat]))
self.assertEqual(0, store.main(['--exited', bat]))
self.assertEqual(['prepared', 'cloud-down', 'ea-exited', 'cloud-up'], [r['op'] for r in asked])
sidecar = json.loads((folder / store.SIDECAR).read_text())
sidecar['cloud'] = False
(folder / store.SIDECAR).write_text(json.dumps(sidecar))
with patch.dict(os.environ, {'DD_LAUNCH_DIR': str(Path(root) / 'session')}), patch.object(store, 'prepare_ea'), patch.object(store, 'ask', side_effect=AssertionError('cloud saves are off')):
self.assertEqual(store.STORE_GAME, store.main([bat]))
def test_a_first_launch_creates_the_prefix_before_the_cloud_download(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='epic', ident='fa4240e5')