mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 04:55:44 +00:00
fix(ea): ask for sign-in after a rejected refresh, upload saves reached through folder aliases
This commit is contained in:
1 parent
a113656196
commit
86190c62dc
4 files changed
+103
-11
No files matched your search
@@ -207,7 +207,7 @@ object CloudSaves {
|
||||
}
|
||||
|
||||
private fun signedIn(context: Context, store: Store): Boolean = when (store) {
|
||||
Store.EA -> EaAuth.load(context)?.userId?.isNotEmpty() == true
|
||||
Store.EA -> EaAuth.signedIn(context)
|
||||
else -> true
|
||||
}
|
||||
|
||||
@@ -344,6 +344,7 @@ object CloudSaves {
|
||||
val cloud = if (dir != null) transport(context, store, id, g.first) else null
|
||||
when {
|
||||
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 && localFiles(dir).keys.groupBy { it.lowercase() }.any { it.value.size > 1 } -> Result("failed", 0, 0, "case-collision")
|
||||
@@ -368,14 +369,20 @@ object CloudSaves {
|
||||
|
||||
private fun localFiles(dir: File): Map<String, File> {
|
||||
if (!dir.isDirectory) return emptyMap()
|
||||
val real = runCatching { dir.canonicalFile }.getOrNull() ?: return emptyMap()
|
||||
val root = real.path + File.separator
|
||||
val inside = { f: File -> runCatching { (f.canonicalPath + File.separator).startsWith(root) }.getOrDefault(false) }
|
||||
val enter = { d: File ->
|
||||
runCatching { d == dir || d.canonicalFile == File(real, d.relativeTo(dir).path) }.getOrDefault(false)
|
||||
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
|
||||
}
|
||||
}
|
||||
return dir.walkTopDown().onEnter(enter).filter { it.isFile && inside(it) }
|
||||
.associateBy { it.relativeTo(dir).path.replace(File.separatorChar, '/') }
|
||||
walk(dir, "", setOf(root))
|
||||
return found
|
||||
}
|
||||
|
||||
internal fun md5(f: File): String = md5(f.readBytes())
|
||||
|
||||
@@ -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 (reply.status == 400 || reply.status == 401 || reply.status == 403) 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
|
||||
|
||||
@@ -65,6 +65,23 @@ class CloudSavesTest {
|
||||
assertEquals("local", File(kept, "SaveData/slot.sav").readText())
|
||||
}
|
||||
|
||||
@Test fun aSaveReachedOnlyThroughAFolderAliasStillGoesUp() {
|
||||
val game = id; val dir = dir()
|
||||
File(dir, "Actual").mkdirs(); File(dir, "Actual/slot.sav").writeText("played")
|
||||
val link = runCatching { java.nio.file.Files.createSymbolicLink(File(dir, "SaveData").toPath(), File(dir, "Actual").toPath()) }
|
||||
org.junit.Assume.assumeTrue(link.isSuccess)
|
||||
java.nio.file.Files.createSymbolicLink(File(dir, "Actual/loop").toPath(), dir.toPath())
|
||||
val memory = Memory()
|
||||
val cloud = object : CloudTransport by memory {
|
||||
override fun wants(name: String) = name.startsWith("SaveData/")
|
||||
}
|
||||
CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false)
|
||||
val r = CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false)
|
||||
assertEquals("uploaded", r.reason)
|
||||
assertEquals(listOf("SaveData/slot.sav"), memory.puts)
|
||||
assertEquals("played", String(memory.files.getValue("SaveData/slot.sav").first))
|
||||
}
|
||||
|
||||
@Test fun aFileChangedOnBothSidesIsLeftForTheUser() {
|
||||
val game = id; val dir = dir()
|
||||
val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L }
|
||||
|
||||
@@ -415,6 +415,55 @@ class EaTest {
|
||||
assertNull(EaAuth.load(app))
|
||||
}
|
||||
|
||||
private fun tokenServer(status: String): java.net.ServerSocket {
|
||||
val server = java.net.ServerSocket(0)
|
||||
Thread {
|
||||
runCatching {
|
||||
server.accept().use { socket ->
|
||||
val input = socket.getInputStream()
|
||||
val head = StringBuilder()
|
||||
while (!head.endsWith("\r\n\r\n")) head.append(input.read().takeIf { it >= 0 }?.toChar() ?: break)
|
||||
val length = Regex("(?i)content-length: *(\\d+)").find(head)?.groupValues?.get(1)?.toInt() ?: 0
|
||||
repeat(length) { input.read() }
|
||||
val body = """{"error":"invalid_grant"}""".toByteArray()
|
||||
socket.getOutputStream().apply {
|
||||
write("HTTP/1.1 $status\r\nContent-Type: application/json\r\nContent-Length: ${body.size}\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
write(body)
|
||||
flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
}.apply { isDaemon = true; start() }
|
||||
return server
|
||||
}
|
||||
|
||||
@Test fun aRejectedRefreshAsksForSignInWhileAnUnreachableOneKeepsTheSessionForARetry() {
|
||||
val app = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val real = EaAuth.tokenUrl
|
||||
try {
|
||||
com.droiddeck.launcher.stores.StoreAccounts.write(app, Store.EA,
|
||||
JSONObject().put("access_token", "old").put("refresh_token", "r").put("expires_at", 1L).put("user_id", "1"))
|
||||
EaAuth.tokenUrl = "http://127.0.0.1:1/"
|
||||
assertNull(EaAuth.accessToken(app))
|
||||
assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn)
|
||||
tokenServer("503 Service Unavailable").use { server ->
|
||||
EaAuth.tokenUrl = "http://127.0.0.1:${server.localPort}/"
|
||||
assertNull(EaAuth.accessToken(app))
|
||||
}
|
||||
assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn)
|
||||
tokenServer("400 Bad Request").use { server ->
|
||||
EaAuth.tokenUrl = "http://127.0.0.1:${server.localPort}/"
|
||||
assertNull(EaAuth.accessToken(app))
|
||||
}
|
||||
assertFalse(CloudSaves.status(app, Store.EA, "x").signedIn)
|
||||
assertTrue(EaAuth.storeRefreshed(app, "new", 3600, "r2"))
|
||||
assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn)
|
||||
} finally {
|
||||
EaAuth.tokenUrl = real
|
||||
EaAuth.signOut(app)
|
||||
}
|
||||
}
|
||||
|
||||
private val heat = """<saveFileCriteria>
|
||||
<include order="0">%Documents%/Need for Speed Heat/SaveGame/savegame/</include>
|
||||
<include order="1">%Documents%/Need for Speed Heat/SaveGame/wraps/</include>
|
||||
|
||||
Reference in new issue
Block a user