mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 12:28:40 +00:00
feat: EA store with sign-in, library, native downloads, updates and launch without the EA app (#2259)
* docs: research and plan for EA and Ubisoft stores * feat(ea): EA store with sign-in, library, native downloads, updates and launch without the EA app * perf(ea): fetch large archive records as parallel ranges * fix(ea): register game display names * fix(ea): license legacy EA Core games and harden the LSX endpoint * fix(ea): run legacy Origin SDK games with a stand-in Origin process * fix(ea): trust only the prepared game on LSX and stop stale library syncs * fix(ea): close LSX sessions on stop and drop clients that never hand-shake * fix(ea): require every hashed field before licensing or caching a probe * fix(ea): trust one LSX session per launch * fix(ea): serialize the library cache write with sign-out and rerun a skipped sync * fix(ea): hand off library sync requests under one lock * fix(ea): clear the sign-in before invalidating the library * fix(ea): serialize sign-out with token refresh and with the library cache * fix(ea): LSX trusts only verified peers, new launch closes old sessions, exit stops its own game * fix(ea): LSX hides profile and presence from unverified peers * fix(ea): LSX handshake has a fixed deadline and untrusted sessions yield their slot * fix(ea): LSX never registers a client after its listener was stopped * fix(ea): LSX evicts each untrusted session at most once * fix(ea): LSX admission and eviction share one lock and keep the cap * fix(ea): LSX trust promotion excludes eviction * fix(ea): LSX launch generation guards restarts and drops results after shutdown * fix(ea): LSX publishes launch state under the admission lock and tags accepts by generation * fix(ea): LSX restarts rebind its listener and promotion checks the launch generation * fix(ea): record why EA refuses a game licence in the store log * chore(ea): log owned offers and the full licence refusal * chore(ea): log the account's entitlements when no game licence is granted * chore(ea): log legacy entitlements when no game licence is granted * chore(ea): log only the refused game's own entitlements * fix(ea): skip trial launchers flagged 1 and license games whose LSX peer Android cannot name
This commit is contained in:
1 parent
9bf638a3c4
commit
d8ed02f2cf
46 files changed
+5284
-7
No files matched your search
@@ -61,6 +61,8 @@ class App : Application() {
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
|
||||
com.droiddeck.launcher.sync.Syncthing.init(this)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
|
||||
com.droiddeck.launcher.stores.ea.EaBackend.app = this
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ea.EaBackend)
|
||||
}
|
||||
|
||||
private fun prefetchAddonPacks() {
|
||||
|
||||
@@ -87,7 +87,7 @@ 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.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA -> ""
|
||||
} ?: return null
|
||||
p.edit()
|
||||
.putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE })
|
||||
@@ -148,7 +148,7 @@ object CloudSaves {
|
||||
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 -> null
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA -> null
|
||||
}
|
||||
return dir to (if (dir == null) "unresolved" else "ok")
|
||||
}
|
||||
@@ -173,7 +173,7 @@ 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 -> null
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA -> null
|
||||
}
|
||||
|
||||
private fun gogScopedToken(context: Context, id: String, clientId: String): String? {
|
||||
|
||||
@@ -13,11 +13,13 @@ internal object LoginFlows {
|
||||
Store.EPIC -> epicFlow()
|
||||
Store.AMAZON -> amazonFlow()
|
||||
Store.GAMEJOLT -> gameJoltFlow(browserUserAgent)
|
||||
Store.EA -> eaFlow(browserUserAgent)
|
||||
Store.ITCH, Store.XBOX, Store.BATTLENET -> null
|
||||
}
|
||||
|
||||
@Volatile var epicFlow: () -> StoreLoginActivity.Flow? = { null }
|
||||
@Volatile var amazonFlow: () -> StoreLoginActivity.Flow? = { null }
|
||||
@Volatile var eaFlow: (String) -> StoreLoginActivity.Flow? = { null }
|
||||
@Volatile var gameJoltFlow: (String) -> StoreLoginActivity.Flow? = { null }
|
||||
|
||||
private class GogFlow(private val state: String, override val userAgent: String) : StoreLoginActivity.Flow {
|
||||
|
||||
@@ -7,7 +7,8 @@ enum class Store(val id: String, val label: String, val shortLabel: String) {
|
||||
XBOX("xbox", "Xbox", "Xbox"),
|
||||
ITCH("itch", "Itch.io", "Itch.io"),
|
||||
GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt"),
|
||||
BATTLENET("battlenet", "Battle.net", "Battle.net");
|
||||
BATTLENET("battlenet", "Battle.net", "Battle.net"),
|
||||
EA("ea", "EA", "EA");
|
||||
|
||||
val folder: String get() = if (this == ITCH) "itch" else shortLabel
|
||||
|
||||
|
||||
@@ -11,9 +11,12 @@ object StoreLaunch {
|
||||
const val LAUNCHER = ".droiddeck-launch.bat"
|
||||
const val EPIC_CODE = ".droiddeck-epic-code"
|
||||
const val EPIC_ARGS = ".droiddeck-epic-args"
|
||||
const val EA_ENV = ".droiddeck-ea-env"
|
||||
/** A sleeping stand-in that the launch hook installs; older EA SDKs require a running Origin process. */
|
||||
const val EA_ORIGIN = "C:\\Program Files (x86)\\Origin\\Origin.exe"
|
||||
|
||||
fun writeLauncher(folder: File, sidecar: StoreGameSidecar): StoreGameSidecar {
|
||||
val needs = sidecar.args.isNotEmpty() || sidecar.env.isNotEmpty() || sidecar.store == Store.EPIC
|
||||
val needs = sidecar.args.isNotEmpty() || sidecar.env.isNotEmpty() || sidecar.store == Store.EPIC || sidecar.store == Store.EA
|
||||
val file = File(folder, LAUNCHER)
|
||||
if (!needs) { file.delete(); return sidecar.copy(launcher = null) }
|
||||
file.writeText(launcherText(sidecar))
|
||||
@@ -49,6 +52,14 @@ object StoreLaunch {
|
||||
lines += "del \"%~dp0$EPIC_ARGS\""
|
||||
lines += "if exist \"%~dp0$EPIC_CODE\" del \"%~dp0$EPIC_CODE\""
|
||||
lines += "set \"$CLIENT_VAR=\" & \"%~dp0$exe\" %$CLIENT_VAR%"
|
||||
} else if (sidecar.store == Store.EA) {
|
||||
lines += "if not exist \"%~dp0$EA_ENV\" goto run"
|
||||
lines += "for /f \"usebackq tokens=1,* delims==\" %%a in (\"%~dp0$EA_ENV\") do set \"%%a=%%b\""
|
||||
lines += "del \"%~dp0$EA_ENV\""
|
||||
lines += ":run"
|
||||
lines += "if exist \"$EA_ORIGIN\" start \"\" \"$EA_ORIGIN\""
|
||||
lines += run
|
||||
lines += "taskkill /f /im Origin.exe >nul 2>&1"
|
||||
} else {
|
||||
lines += run
|
||||
}
|
||||
|
||||
@@ -38,6 +38,7 @@ object StoreLaunchRequests {
|
||||
|
||||
fun stop() {
|
||||
com.droiddeck.launcher.stores.xbox.XboxRuntime.stop()
|
||||
com.droiddeck.launcher.stores.ea.EaLsx.stop()
|
||||
synchronized(lock) {
|
||||
observer?.stopWatching()
|
||||
observer = null
|
||||
@@ -58,6 +59,12 @@ object StoreLaunchRequests {
|
||||
"xbox-renew" -> JSONObject().put("ok", com.droiddeck.launcher.stores.xbox.XboxRuntime.renew(app, request.optString("id"), request.optString("lease")))
|
||||
"xbox-prepare" -> runCatching { com.droiddeck.launcher.stores.xbox.XboxRuntime.prepare(app, request.getString("id")) }
|
||||
.getOrElse { JSONObject().put("ok", false).put("reason", "Xbox account service is unavailable. Sign in again and retry.") }
|
||||
"ea-prepare" -> runCatching { lastLaunched = Store.EA to request.optString("id"); com.droiddeck.launcher.stores.ea.EaLaunch.prepare(app, request) }
|
||||
.getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) }
|
||||
"ea-exited" -> {
|
||||
com.droiddeck.launcher.stores.ea.EaLsx.stop(request.optString("id"))
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
"gog-achievements" -> runCatching { com.droiddeck.launcher.stores.gog.GogComet.prepare(app, request.optString("id")) }
|
||||
.getOrElse { JSONObject().put("ok", false).put("ready", false).put("reason", "service-unavailable") }
|
||||
"epic-code" -> {
|
||||
|
||||
@@ -55,6 +55,7 @@ object StoreSizes {
|
||||
Store.EPIC -> EpicPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
|
||||
Store.AMAZON -> AmazonPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
|
||||
Store.ITCH, Store.GAMEJOLT -> {}
|
||||
Store.EA -> com.droiddeck.launcher.stores.ea.EaPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
|
||||
Store.GOG, Store.XBOX, Store.BATTLENET -> {}
|
||||
}
|
||||
}
|
||||
@@ -111,6 +112,7 @@ object StoreSizes {
|
||||
val bytes = AmazonApiClient.getBytes(AmazonApiClient.appendPath(spec.downloadUrl, "manifest.proto"), token) ?: return 0L
|
||||
AmazonManifest.parse(bytes).totalInstallSize
|
||||
}
|
||||
Store.EA -> com.droiddeck.launcher.stores.ea.EaSizes.size(context, item)
|
||||
Store.GOG, Store.XBOX, Store.BATTLENET -> 0L
|
||||
Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchLibrary.size(context, item)
|
||||
Store.GAMEJOLT -> com.droiddeck.launcher.stores.gamejolt.GameJoltBuilds.size(context, item)
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
package com.droiddeck.launcher.stores.ea
|
||||
|
||||
import android.net.Uri
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
class EaApiException(val status: Int, message: String) : Exception(message)
|
||||
|
||||
object EaApi {
|
||||
private const val GRAPHQL = "https://service-aggregation-layer.juno.ea.com/graphql"
|
||||
private const val LOCALE = "DEFAULT"
|
||||
|
||||
class Player(val userId: String, val personaId: String, val displayName: String, val eaId: String)
|
||||
|
||||
class OwnedProduct(
|
||||
val offerId: String,
|
||||
val productId: String,
|
||||
val name: String,
|
||||
val slug: String,
|
||||
val baseSlug: String,
|
||||
val gameType: String,
|
||||
val downloadable: Boolean,
|
||||
val trial: Boolean,
|
||||
val ownership: List<String>,
|
||||
)
|
||||
|
||||
class Offer(
|
||||
val offerId: String,
|
||||
val contentId: String,
|
||||
val displayName: String,
|
||||
val displayType: String,
|
||||
val downloadable: Boolean,
|
||||
val executePathOverride: String,
|
||||
val installCheckOverride: String,
|
||||
val executeParameters: String,
|
||||
val multiplayerId: String,
|
||||
val masterTitleId: String,
|
||||
val gameVersion: String,
|
||||
val cloudSaves: String,
|
||||
val locales: List<String>,
|
||||
)
|
||||
|
||||
class Images(val tall: String?, val wide: String?, val logo: String?)
|
||||
|
||||
class Build(val buildId: String, val gameVersion: String, val liveDate: String)
|
||||
|
||||
private val queries = HashMap<String, String>()
|
||||
|
||||
internal fun query(name: String): String = synchronized(queries) {
|
||||
queries.getOrPut(name) {
|
||||
val stream = EaApi::class.java.getResourceAsStream("/ea/graphql/$name.gql") ?: throw IllegalStateException("missing query $name")
|
||||
stream.use { it.readBytes().toString(Charsets.UTF_8) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun persisted(name: String): String =
|
||||
JSONObject().put("persistedQuery", JSONObject().put("version", 1).put("sha256Hash", EaCrypto.hex(EaCrypto.sha256(query(name).toByteArray())))).toString()
|
||||
|
||||
internal fun call(token: String, name: String, variables: JSONObject): JSONObject {
|
||||
val headers = mapOf("Authorization" to "Bearer $token", "Accept" to "application/json")
|
||||
val get = Uri.parse(GRAPHQL).buildUpon()
|
||||
.appendQueryParameter("extensions", persisted(name))
|
||||
.appendQueryParameter("operationName", name)
|
||||
.appendQueryParameter("variables", variables.toString())
|
||||
.build().toString()
|
||||
var reply = EaHttp.request(get, headers = headers)
|
||||
var json = runCatching { JSONObject(reply.text) }.getOrNull()
|
||||
if (!reply.ok || json == null || json.has("errors")) {
|
||||
val body = JSONObject()
|
||||
.put("extensions", JSONObject(persisted(name)))
|
||||
.put("variables", variables)
|
||||
.put("operationName", name)
|
||||
.put("query", query(name))
|
||||
reply = EaHttp.request(GRAPHQL, "POST", headers + ("Content-Type" to "application/json"), body.toString().toByteArray())
|
||||
json = runCatching { JSONObject(reply.text) }.getOrNull()
|
||||
}
|
||||
if (reply.status == 401) throw EaApiException(401, "EA refused the session")
|
||||
if (json == null) throw EaApiException(reply.status, "EA gave no answer to $name (${reply.status})")
|
||||
json.optJSONArray("errors")?.optJSONObject(0)?.let { throw EaApiException(reply.status, "$name: ${it.optString("message")}") }
|
||||
return json.optJSONObject("data") ?: throw EaApiException(reply.status, "$name returned no data")
|
||||
}
|
||||
|
||||
fun player(token: String): Player {
|
||||
val me = call(token, "GetUserPlayer", JSONObject()).optJSONObject("me") ?: throw EaApiException(0, "no player")
|
||||
val p = me.optJSONObject("player")
|
||||
return Player(
|
||||
userId = me.optString("pd"),
|
||||
personaId = p?.optString("psd").orEmpty(),
|
||||
displayName = p?.optString("displayName").orEmpty(),
|
||||
eaId = p?.optString("uniqueName").orEmpty().ifEmpty { p?.optString("displayName").orEmpty() },
|
||||
)
|
||||
}
|
||||
|
||||
internal fun parseOwned(page: JSONObject): Pair<List<OwnedProduct>, String?> {
|
||||
val owned = page.optJSONObject("me")?.optJSONObject("ownedGameProducts") ?: return emptyList<OwnedProduct>() to null
|
||||
val items = owned.optJSONArray("items") ?: JSONArray()
|
||||
val list = (0 until items.length()).mapNotNull { items.optJSONObject(it) }.mapNotNull { o ->
|
||||
val product = o.optJSONObject("product") ?: return@mapNotNull null
|
||||
val base = product.optJSONObject("baseItem")
|
||||
val user = product.optJSONObject("gameProductUser")
|
||||
val methods = user?.optJSONArray("ownershipMethods")
|
||||
OwnedProduct(
|
||||
offerId = o.optString("originOfferId").ifEmpty { return@mapNotNull null },
|
||||
productId = product.optString("id"),
|
||||
name = (base?.optString("title")?.takeIf { it.isNotBlank() } ?: product.optString("name")).replace("\n", " ").trim(),
|
||||
slug = product.optString("gameSlug"),
|
||||
baseSlug = base?.optString("baseGameSlug").orEmpty().takeIf { it != "null" }.orEmpty(),
|
||||
gameType = base?.optString("gameType").orEmpty(),
|
||||
downloadable = product.optBoolean("downloadable", true),
|
||||
trial = product.optJSONObject("trialDetails")?.optString("trialType").orEmpty().let { it.isNotEmpty() && it != "null" },
|
||||
ownership = (0 until (methods?.length() ?: 0)).map { methods!!.optString(it) },
|
||||
)
|
||||
}
|
||||
val next = owned.optString("next").takeIf { it.isNotBlank() && it != "null" }
|
||||
return list to next
|
||||
}
|
||||
|
||||
fun owned(token: String): List<OwnedProduct> {
|
||||
val out = ArrayList<OwnedProduct>()
|
||||
var next: String? = "0"
|
||||
var guard = 0
|
||||
while (next != null && guard++ < 50) {
|
||||
val variables = JSONObject()
|
||||
.put("isMac", false)
|
||||
.put("limit", 100)
|
||||
.put("next", next)
|
||||
.put("type", JSONArray().put("DIGITAL_FULL_GAME").put("PACKAGED_FULL_GAME"))
|
||||
.put("storefronts", JSONArray().put("EA"))
|
||||
.put("platforms", JSONArray().put("PC"))
|
||||
val (items, after) = parseOwned(call(token, "getPreloadedOwnedGames", variables))
|
||||
out += items
|
||||
next = after?.takeIf { it != next && items.isNotEmpty() }
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
internal fun parseOffers(data: JSONObject): List<Offer> {
|
||||
val arr = data.optJSONArray("legacyOffers") ?: return emptyList()
|
||||
return (0 until arr.length()).mapNotNull { arr.optJSONObject(it) }.mapNotNull { o ->
|
||||
val downloads = o.optJSONArray("downloads")
|
||||
val version = (0 until (downloads?.length() ?: 0)).mapNotNull { downloads!!.optJSONObject(it) }
|
||||
.firstOrNull { it.optString("downloadType").equals("LIVE", true) }?.optString("gameVersion")
|
||||
?: downloads?.optJSONObject(0)?.optString("gameVersion")
|
||||
val locales = o.optJSONArray("softwareLocales")
|
||||
fun s(k: String) = o.optString(k).takeIf { it != "null" }.orEmpty()
|
||||
Offer(
|
||||
offerId = s("offerId").ifEmpty { return@mapNotNull null },
|
||||
contentId = s("contentId"),
|
||||
displayName = s("displayName"),
|
||||
displayType = s("displayType"),
|
||||
downloadable = o.optBoolean("isDownloadable", true),
|
||||
executePathOverride = s("executePathOverride"),
|
||||
installCheckOverride = s("installCheckOverride"),
|
||||
executeParameters = s("executeParameters"),
|
||||
multiplayerId = s("multiplayerId"),
|
||||
masterTitleId = s("primaryMasterTitleId"),
|
||||
gameVersion = version.orEmpty().takeIf { it != "null" }.orEmpty(),
|
||||
cloudSaves = s("cloudSaveConfigurationOverride"),
|
||||
locales = (0 until (locales?.length() ?: 0)).map { locales!!.optString(it) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun offers(token: String, ids: List<String>): List<Offer> = ids.distinct().chunked(50).flatMap { chunk ->
|
||||
parseOffers(call(token, "getLegacyCatalogDefs", JSONObject().put("offerIds", JSONArray(chunk))))
|
||||
}
|
||||
|
||||
private fun path(o: JSONObject?, vararg keys: String): String? {
|
||||
var cur = o ?: return null
|
||||
for (k in keys.dropLast(1)) cur = cur.optJSONObject(k) ?: return null
|
||||
return cur.optString(keys.last()).takeIf { it.startsWith("http") }
|
||||
}
|
||||
|
||||
internal fun parseImages(data: JSONObject): Images {
|
||||
val game = data.optJSONObject("game")
|
||||
val key = game?.optJSONObject("keyArt")
|
||||
val pack = game?.optJSONObject("packArt")
|
||||
return Images(
|
||||
tall = path(pack, "aspect9x16Image", "path") ?: path(key, "aspect9x16Image", "path"),
|
||||
wide = path(key, "aspect16x9Image", "path") ?: path(key, "largestImage", "path") ?: path(pack, "aspect2x1Image", "path"),
|
||||
logo = path(game, "primaryLogo", "largestImage", "path") ?: path(game, "primaryLogo", "path"),
|
||||
)
|
||||
}
|
||||
|
||||
fun images(token: String, slug: String): Images =
|
||||
parseImages(call(token, "GameImages", JSONObject().put("gameSlug", slug).put("locale", LOCALE)))
|
||||
|
||||
fun downloadUrl(token: String, offerId: String, buildId: String? = null): String {
|
||||
val data = call(token, "downloadUrl", JSONObject().put("offerId", offerId).put("buildId", buildId.orEmpty()))
|
||||
return data.optJSONObject("downloadUrl")?.optString("url").orEmpty().ifEmpty { throw EaApiException(0, "EA gave no download link") }
|
||||
}
|
||||
|
||||
fun builds(token: String, offerId: String): List<Build> {
|
||||
val arr = call(token, "availableBuilds", JSONObject().put("offerId", offerId)).optJSONArray("availableBuilds") ?: return emptyList()
|
||||
return (0 until arr.length()).mapNotNull { arr.optJSONObject(it) }.map {
|
||||
Build(it.optString("buildId"), it.optString("gameVersion").takeIf { v -> v != "null" }.orEmpty(), it.optString("buildLiveDate"))
|
||||
}
|
||||
}
|
||||
|
||||
fun legacyEntitlements(token: String): List<JSONObject> {
|
||||
val out = ArrayList<JSONObject>()
|
||||
var next: String? = "0"
|
||||
var guard = 0
|
||||
while (next != null && guard++ < 50) {
|
||||
val variables = JSONObject().put("limit", 100).put("next", next).put("storeFronts", JSONArray().put("EA"))
|
||||
val page = call(token, "getLegacyEntitlements", variables).optJSONObject("me")?.optJSONObject("legacyEntitlements") ?: break
|
||||
val items = page.optJSONArray("items") ?: JSONArray()
|
||||
for (i in 0 until items.length()) items.optJSONObject(i)?.let(out::add)
|
||||
next = page.optString("next").takeIf { it.isNotBlank() && it != "null" && it != next && items.length() > 0 }
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
fun entitlements(token: String, group: String): JSONArray {
|
||||
val variables = JSONObject()
|
||||
.put("productIds", JSONArray())
|
||||
.put("includeChildGroups", false)
|
||||
.put("groupNames", JSONArray().put(group))
|
||||
.put("entitlementTag", "")
|
||||
.put("pageSize", 100)
|
||||
.put("pageNumber", 1)
|
||||
return call(token, "sdkEntitlements", variables).optJSONObject("me")?.optJSONObject("sdkEntitlements")?.optJSONArray("entitlements") ?: JSONArray()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package com.droiddeck.launcher.stores.ea
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreAccounts
|
||||
import org.json.JSONObject
|
||||
import java.security.SecureRandom
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.TimeZone
|
||||
|
||||
object EaAuth {
|
||||
private const val TAG = "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"
|
||||
const val REDIRECT = "qrc:///html/login_successful.html"
|
||||
private const val REFRESH_MARGIN_MS = 5 * 60 * 1000L
|
||||
private val refreshLock = Any()
|
||||
private val random = SecureRandom()
|
||||
|
||||
private val PC_SIGN_KEYS = mapOf(
|
||||
"v1" to "ISa3dpGOc8wW7Adn4auACSQmaccrOyR2".toByteArray(),
|
||||
"v2" to "nt5FfJbdPzNcl2pkC3zgjO43Knvscxft".toByteArray(),
|
||||
)
|
||||
|
||||
val OPAQUE_SCOPES = listOf(
|
||||
"basic.commerce.cartv2", "service.atom", "dp.client.default", "signin", "social_recommendation_user",
|
||||
"basic.optin.write", "basic.commerce.cartv2.write", "basic.billing", "external.social_information_ups_admin",
|
||||
)
|
||||
|
||||
class Account(
|
||||
val accessToken: String,
|
||||
val refreshToken: String,
|
||||
val expiresAt: Long,
|
||||
val userId: String,
|
||||
val personaId: String,
|
||||
val displayName: String,
|
||||
val eaId: String,
|
||||
)
|
||||
|
||||
class Pending(val url: String, val verifier: String)
|
||||
|
||||
internal fun fromJson(o: JSONObject): Account? {
|
||||
val access = o.optString("access_token").ifEmpty { return null }
|
||||
return Account(
|
||||
accessToken = access,
|
||||
refreshToken = o.optString("refresh_token"),
|
||||
expiresAt = o.optLong("expires_at"),
|
||||
userId = o.optString("user_id"),
|
||||
personaId = o.optString("persona_id"),
|
||||
displayName = o.optString("display_name"),
|
||||
eaId = o.optString("ea_id"),
|
||||
)
|
||||
}
|
||||
|
||||
fun load(context: Context): Account? = StoreAccounts.read(context.applicationContext, Store.EA)?.let(::fromJson)
|
||||
|
||||
private fun deviceId(context: Context): String {
|
||||
val prefs = EaPrefs.get(context)
|
||||
prefs.getString("device", null)?.let { return it }
|
||||
val made = EaCrypto.hex(ByteArray(16).also(random::nextBytes))
|
||||
prefs.edit().putString("device", made).apply()
|
||||
return made
|
||||
}
|
||||
|
||||
internal fun pcSign(device: String, now: Date = Date(), version: String = if (random.nextBoolean()) "v1" else "v2"): String {
|
||||
val stamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }.format(now)
|
||||
val mid = EaCrypto.fnv1a(("DroidDeck" + device.uppercase() + "DroidDeck").toByteArray()).toString()
|
||||
val json = "{\"av\":\"v1\",\"bsn\":\"None\",\"gid\":0,\"hsn\":\"None\",\"mid\":\"$mid\",\"msn\":\"${device.uppercase()}\",\"sv\":\"$version\",\"ts\":\"$stamp\"}"
|
||||
val payload = EaCrypto.base64Url(json.toByteArray())
|
||||
val signature = EaCrypto.base64Url(EaCrypto.hmacSha256(PC_SIGN_KEYS.getValue(version), payload.toByteArray()))
|
||||
return "$payload.$signature"
|
||||
}
|
||||
|
||||
internal fun authUrl(
|
||||
device: String,
|
||||
responseType: String,
|
||||
challenge: String? = null,
|
||||
accessToken: String? = null,
|
||||
clientId: String = CLIENT_ID,
|
||||
scopes: List<String> = emptyList(),
|
||||
tokenFormat: String? = null,
|
||||
expiresIn: Int? = null,
|
||||
): String {
|
||||
val b = Uri.parse(AUTH_URL).buildUpon()
|
||||
.appendQueryParameter("client_id", clientId)
|
||||
.appendQueryParameter("sbiod_enabled", "false")
|
||||
.appendQueryParameter("response_type", responseType)
|
||||
.appendQueryParameter("locale", "en_US")
|
||||
.appendQueryParameter("pc_sign", pcSign(device))
|
||||
.appendQueryParameter("nonce", random.nextInt().toString())
|
||||
if (scopes.isNotEmpty()) b.appendQueryParameter("scope", scopes.joinToString(" "))
|
||||
if (challenge != null) {
|
||||
b.appendQueryParameter("code_challenge_method", "S256")
|
||||
b.appendQueryParameter("code_challenge", challenge)
|
||||
}
|
||||
if (accessToken != null) b.appendQueryParameter("access_token", accessToken)
|
||||
if (tokenFormat != null) b.appendQueryParameter("token_format", tokenFormat)
|
||||
if (expiresIn != null) b.appendQueryParameter("expires_in", expiresIn.toString())
|
||||
return b.build().toString()
|
||||
}
|
||||
|
||||
fun begin(context: Context): Pending {
|
||||
val verifier = EaCrypto.base64Url(ByteArray(32).also(random::nextBytes))
|
||||
val challenge = EaCrypto.base64Url(EaCrypto.sha256(verifier.toByteArray()))
|
||||
return Pending(authUrl(deviceId(context), "code", challenge = challenge), verifier)
|
||||
}
|
||||
|
||||
/** Pulls one parameter out of the redirect EA sends to its desktop client's local page. */
|
||||
internal fun redirectValue(location: String, name: String): String? {
|
||||
val normal = location.replace("qrc:///html", "http://127.0.0.1").replace("qrc:/html", "http://127.0.0.1")
|
||||
val uri = Uri.parse(normal)
|
||||
uri.getQueryParameter(name)?.let { return it }
|
||||
val fragment = uri.encodedFragment ?: return null
|
||||
return Uri.parse("http://x/?$fragment").getQueryParameter(name)
|
||||
}
|
||||
|
||||
private fun tokenCall(values: List<Pair<String, String>>): JSONObject {
|
||||
val reply = EaHttp.request(
|
||||
TOKEN_URL, "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") } ?: ""}")
|
||||
}
|
||||
return json
|
||||
}
|
||||
|
||||
fun exchange(context: Context, code: String, verifier: String) {
|
||||
val token = tokenCall(
|
||||
listOf(
|
||||
"grant_type" to "authorization_code", "code" to code, "code_verifier" to verifier,
|
||||
"redirect_uri" to REDIRECT, "token_format" to "JWS",
|
||||
),
|
||||
)
|
||||
val access = token.getString("access_token")
|
||||
val player = runCatching { EaApi.player(access) }.onFailure { Log.w(TAG, "player: ${it.message}") }.getOrNull()
|
||||
val record = JSONObject()
|
||||
.put("access_token", access)
|
||||
.put("refresh_token", token.optString("refresh_token"))
|
||||
.put("expires_at", System.currentTimeMillis() + token.optLong("expires_in", 3600) * 1000)
|
||||
.put("user_id", player?.userId.orEmpty())
|
||||
.put("persona_id", player?.personaId.orEmpty())
|
||||
.put("display_name", player?.displayName.orEmpty())
|
||||
.put("ea_id", player?.eaId.orEmpty())
|
||||
StoreAccounts.write(context.applicationContext, Store.EA, record)
|
||||
}
|
||||
|
||||
private fun fresh(a: Account) = a.expiresAt - System.currentTimeMillis() > REFRESH_MARGIN_MS || a.refreshToken.isEmpty()
|
||||
|
||||
private fun refreshLocked(context: Context, a: Account): String? {
|
||||
if (a.refreshToken.isEmpty()) return null
|
||||
val token = try {
|
||||
tokenCall(listOf("grant_type" to "refresh_token", "refresh_token" to a.refreshToken))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "refresh: ${e.message}")
|
||||
return null
|
||||
}
|
||||
val access = token.getString("access_token")
|
||||
val player = if (load(context)?.userId.isNullOrEmpty()) runCatching { EaApi.player(access) }.getOrNull() else null
|
||||
return access.takeIf { storeRefreshed(context, access, token.optLong("expires_in", 3600), token.optString("refresh_token"), player) }
|
||||
}
|
||||
|
||||
/** Writes a refreshed token into the saved sign-in, unless sign-out removed it meanwhile. */
|
||||
internal fun storeRefreshed(context: Context, access: String, expiresIn: Long, refresh: String, player: EaApi.Player? = null): Boolean =
|
||||
synchronized(refreshLock) {
|
||||
val app = context.applicationContext
|
||||
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) }
|
||||
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
|
||||
}
|
||||
|
||||
fun accessToken(context: Context): String? {
|
||||
val current = load(context) ?: return null
|
||||
if (fresh(current)) return current.accessToken
|
||||
synchronized(refreshLock) {
|
||||
val again = load(context) ?: return null
|
||||
if (fresh(again)) return again.accessToken
|
||||
return refreshLocked(context, again) ?: again.accessToken.takeIf { again.expiresAt > System.currentTimeMillis() }
|
||||
}
|
||||
}
|
||||
|
||||
fun refreshNow(context: Context, stale: String?): String? = synchronized(refreshLock) {
|
||||
val current = load(context) ?: return null
|
||||
if (stale != null && current.accessToken != stale) return current.accessToken
|
||||
refreshLocked(context, current)
|
||||
}
|
||||
|
||||
/** Asks EA to mint a code or token for another client from the signed-in session, as the EA app does for games. */
|
||||
fun mint(
|
||||
context: Context,
|
||||
clientId: String,
|
||||
responseType: String,
|
||||
scopes: List<String> = emptyList(),
|
||||
tokenFormat: String? = null,
|
||||
expiresIn: Int? = null,
|
||||
): String? {
|
||||
val access = accessToken(context) ?: return null
|
||||
val url = authUrl(deviceId(context), responseType, accessToken = access, clientId = clientId, scopes = scopes, tokenFormat = tokenFormat, expiresIn = expiresIn)
|
||||
val reply = runCatching { EaHttp.request(url, follow = false) }.getOrElse {
|
||||
Log.w(TAG, "mint $clientId: ${it.javaClass.simpleName}")
|
||||
return null
|
||||
}
|
||||
val location = reply.header("Location") ?: run {
|
||||
Log.w(TAG, "mint $clientId: no redirect (${reply.status})")
|
||||
return null
|
||||
}
|
||||
if (location.startsWith("https://signin.ea.com")) {
|
||||
Log.w(TAG, "mint $clientId: the session needs a new sign-in")
|
||||
return null
|
||||
}
|
||||
return redirectValue(location, if (responseType == "token") "access_token" else responseType)
|
||||
}
|
||||
|
||||
/** Waits for any refresh in progress, so it cannot write the sign-in back afterwards. */
|
||||
fun signOut(context: Context) {
|
||||
synchronized(refreshLock) { StoreAccounts.clear(context.applicationContext, Store.EA) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.droiddeck.launcher.stores.ea
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.util.Log
|
||||
import android.webkit.WebView
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.LoginFlows
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreBackend
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreLoginActivity
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.WebCookies
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
|
||||
object EaBackend : StoreBackend {
|
||||
override val store: Store = Store.EA
|
||||
|
||||
@Volatile internal var app: Context? = null
|
||||
|
||||
init {
|
||||
LoginFlows.eaFlow = { ua -> app?.let { EaLogin(EaAuth.begin(it), ua) } }
|
||||
}
|
||||
|
||||
override fun signIn(context: Context) {
|
||||
app = context.applicationContext
|
||||
context.startActivity(
|
||||
Intent(context, StoreLoginActivity::class.java)
|
||||
.putExtra(StoreLoginActivity.EXTRA_STORE, store.id)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
}
|
||||
|
||||
override fun signOut(context: Context) {
|
||||
val app = context.applicationContext
|
||||
EaAuth.signOut(app)
|
||||
EaLibrary.reset(app)
|
||||
EaUpdates.available.clear()
|
||||
runCatching { WebCookies.expire(EaLogin.SIGN_IN_URLS, ".ea.com", listOf("/")) {} }
|
||||
}
|
||||
|
||||
override fun syncLibrary(context: Context, force: Boolean) {
|
||||
val app = context.applicationContext
|
||||
this.app = app
|
||||
Thread({ EaLibrary.sync(app, force) }, "ea-sync").start()
|
||||
}
|
||||
|
||||
override fun loadShelves(context: Context, force: Boolean) {}
|
||||
|
||||
override fun install(context: Context, item: CatalogItem, root: java.io.File) {
|
||||
val app = context.applicationContext
|
||||
if (!EaNative.ready()) {
|
||||
StoresState.logLine(EaNative.ENGINE_MISSING)
|
||||
StoresState.post { StoresState.problems[store] = EaNative.ENGINE_MISSING }
|
||||
return
|
||||
}
|
||||
val folder = StoreInstallRoot.folderFor(app, store, item.id, item.title, root)
|
||||
val entry = DownloadEntry(store, item.id, item.title, cover = item.tallImageUrl ?: item.imageUrl, bytesTotal = item.sizeBytes, location = StoreInstallRoot.labelFor(app, folder))
|
||||
DownloadQueue.enqueue(app, entry) { EaInstaller(app, item, folder) }
|
||||
}
|
||||
|
||||
override fun uninstall(context: Context, game: InstalledStoreGame) {}
|
||||
}
|
||||
|
||||
internal class EaLogin(private val pending: EaAuth.Pending, override val userAgent: String) : StoreLoginActivity.Flow {
|
||||
override val startUrl: String get() = pending.url
|
||||
|
||||
override fun isRedirect(url: String): Boolean = url.startsWith("qrc:", ignoreCase = true)
|
||||
|
||||
override fun forgetSignIn(done: () -> Unit) {
|
||||
runCatching { WebCookies.expire(SIGN_IN_URLS, ".ea.com", listOf("/")) { done() } }.onFailure { done() }
|
||||
}
|
||||
|
||||
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? {
|
||||
val code = EaAuth.redirectValue(url, "code") ?: return activity.getString(R.string.stores_login_error_verification)
|
||||
return try {
|
||||
EaAuth.exchange(activity, code, pending.verifier)
|
||||
null
|
||||
} catch (e: Exception) {
|
||||
Log.w("EaLogin", "sign-in failed: ${e.message}")
|
||||
activity.getString(R.string.stores_login_error_generic)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
val SIGN_IN_URLS = listOf("https://accounts.ea.com", "https://signin.ea.com", "https://www.ea.com")
|
||||
}
|
||||
}
|
||||
|
||||
object EaUpdates {
|
||||
val available = mutableStateMapOf<String, String>()
|
||||
private val checked = java.util.concurrent.ConcurrentHashMap<String, Long>()
|
||||
private const val RECHECK_MS = 30 * 60 * 1000L
|
||||
|
||||
fun check(context: Context, game: InstalledStoreGame, force: Boolean = false) {
|
||||
val app = context.applicationContext
|
||||
val id = game.sidecar.id
|
||||
val now = System.currentTimeMillis()
|
||||
if (!force && now - (checked[id] ?: 0L) < RECHECK_MS) return
|
||||
checked[id] = now
|
||||
Thread({
|
||||
val token = EaAuth.accessToken(app)
|
||||
val offer = token?.let { runCatching { EaApi.offers(it, listOf(id)) }.getOrNull() }?.firstOrNull()
|
||||
if (offer == null) {
|
||||
checked.remove(id)
|
||||
return@Thread
|
||||
}
|
||||
val live = offer.gameVersion
|
||||
val installed = game.sidecar.installVersion
|
||||
StoresState.post {
|
||||
if (live.isNotEmpty() && installed.isNotEmpty() && live != installed) available[game.key] = live else available.remove(game.key)
|
||||
}
|
||||
}, "ea-update-check").start()
|
||||
}
|
||||
|
||||
fun start(context: Context, game: InstalledStoreGame) {
|
||||
val app = context.applicationContext
|
||||
val root = game.folder.parentFile?.parentFile ?: return
|
||||
val known = EaLibrary.game(app, game.sidecar.id)
|
||||
val item = known?.let { EaLibrary.toCatalogItem(app, it) } ?: CatalogItem(
|
||||
Store.EA, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover, owned = true, extra = game.sidecar.extra,
|
||||
)
|
||||
available.remove(game.key)
|
||||
StoresState.install(app, item, root)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.droiddeck.launcher.stores.ea
|
||||
|
||||
import java.security.MessageDigest
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneOffset
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.Mac
|
||||
import javax.crypto.spec.IvParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
internal object EaCrypto {
|
||||
val LSX_DEFAULT_KEY = ByteArray(16) { it.toByte() }
|
||||
|
||||
private val OOA_KEY = intArrayOf(65, 50, 114, 45, 208, 130, 239, 176, 220, 100, 87, 197, 118, 104, 202, 9)
|
||||
.map { it.toByte() }.toByteArray()
|
||||
|
||||
private const val PRIME_10K = 104729L
|
||||
private const val PRIME_20K = 224737L
|
||||
private const val PRIME_30K = 350377L
|
||||
|
||||
fun ecbEncrypt(data: ByteArray, key: ByteArray): ByteArray =
|
||||
Cipher.getInstance("AES/ECB/PKCS5Padding").run { init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES")); doFinal(data) }
|
||||
|
||||
fun ecbDecrypt(data: ByteArray, key: ByteArray): ByteArray =
|
||||
Cipher.getInstance("AES/ECB/PKCS5Padding").run { init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES")); doFinal(data) }
|
||||
|
||||
fun licenseEncrypt(data: ByteArray): ByteArray =
|
||||
Cipher.getInstance("AES/CBC/PKCS5Padding").run { init(Cipher.ENCRYPT_MODE, SecretKeySpec(OOA_KEY, "AES"), IvParameterSpec(ByteArray(16))); doFinal(data) }
|
||||
|
||||
fun licenseDecrypt(data: ByteArray): ByteArray =
|
||||
Cipher.getInstance("AES/CBC/PKCS5Padding").run { init(Cipher.DECRYPT_MODE, SecretKeySpec(OOA_KEY, "AES"), IvParameterSpec(ByteArray(16))); doFinal(data) }
|
||||
|
||||
fun hex(bytes: ByteArray): String = bytes.joinToString("") { "%02x".format(it.toInt() and 0xFF) }
|
||||
|
||||
fun unhex(text: String): ByteArray {
|
||||
val digits = text.lowercase().filter { it in '0'..'9' || it in 'a'..'f' }
|
||||
if (digits.length % 2 != 0) return ByteArray(0)
|
||||
return ByteArray(digits.length / 2) { i -> digits.substring(i * 2, i * 2 + 2).toInt(16).toByte() }
|
||||
}
|
||||
|
||||
/** The session key both sides derive after the LSX challenge, from a seed the game picks. */
|
||||
fun lsxKey(seed: Int): ByteArray {
|
||||
if (seed == 0) return LSX_DEFAULT_KEY.copyOf()
|
||||
var state = 7L
|
||||
fun next(): Int {
|
||||
state = (state * 214013L + 2531011L) and 0xFFFFFFFFL
|
||||
return ((state ushr 16) and 0xFFFF).toInt()
|
||||
}
|
||||
val start = (next().toLong() + seed) and 0xFFFFFFFFL
|
||||
state = start
|
||||
return ByteArray(16) { next().toByte() }
|
||||
}
|
||||
|
||||
fun challengeAnswer(key: String): String = hex(ecbEncrypt(key.toByteArray(Charsets.US_ASCII), LSX_DEFAULT_KEY))
|
||||
|
||||
fun challengeSeed(version: String, answer: String): Int? = when (version) {
|
||||
"2" -> 0
|
||||
"3" -> (answer[0].code shl 8) or answer[1].code
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** EA's launch handshake code, which changes every UTC day. */
|
||||
fun rtpCode(day: LocalDate = LocalDate.now(ZoneOffset.UTC)): Long {
|
||||
val time = ((PRIME_10K * day.year) xor (day.monthValue * PRIME_20K) xor (day.dayOfMonth * PRIME_30K)) and 0xFFFFFFFFL
|
||||
return (time xor ((time shl 16) and 0xFFFFFFFFL) xor (time ushr 16)) and 0xFFFFFFFFL
|
||||
}
|
||||
|
||||
fun sha256(data: ByteArray): ByteArray = MessageDigest.getInstance("SHA-256").digest(data)
|
||||
|
||||
fun sha1(data: ByteArray): ByteArray = MessageDigest.getInstance("SHA-1").digest(data)
|
||||
|
||||
fun hmacSha256(key: ByteArray, data: ByteArray): ByteArray =
|
||||
Mac.getInstance("HmacSHA256").run { init(SecretKeySpec(key, "HmacSHA256")); doFinal(data) }
|
||||
|
||||
fun fnv1a(data: ByteArray): ULong {
|
||||
var hash = 0xcbf29ce484222325UL
|
||||
for (b in data) hash = (hash xor (b.toUByte().toULong())) * 0x100000001b3UL
|
||||
return hash
|
||||
}
|
||||
|
||||
fun base64Url(data: ByteArray): String =
|
||||
java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(data)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.droiddeck.launcher.stores.ea
|
||||
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
|
||||
internal class EaReply(val status: Int, val body: ByteArray, val headers: Map<String, List<String>>) {
|
||||
val ok: Boolean get() = status in 200..299
|
||||
val text: String get() = body.toString(Charsets.UTF_8)
|
||||
fun header(name: String): String? = headers.entries.firstOrNull { it.key.equals(name, ignoreCase = true) }?.value?.firstOrNull()
|
||||
}
|
||||
|
||||
internal object EaHttp {
|
||||
const val USER_AGENT = "Mozilla/5.0 EA Desktop/13.735.2.6250"
|
||||
private const val TIMEOUT = 30_000
|
||||
|
||||
fun form(values: List<Pair<String, String>>): String =
|
||||
values.joinToString("&") { (k, v) -> URLEncoder.encode(k, "UTF-8") + "=" + URLEncoder.encode(v, "UTF-8") }
|
||||
|
||||
fun request(
|
||||
url: String,
|
||||
method: String = "GET",
|
||||
headers: Map<String, String> = emptyMap(),
|
||||
body: ByteArray? = null,
|
||||
follow: Boolean = true,
|
||||
): EaReply {
|
||||
val c = URL(url).openConnection() as HttpURLConnection
|
||||
try {
|
||||
c.requestMethod = method
|
||||
c.connectTimeout = TIMEOUT
|
||||
c.readTimeout = TIMEOUT
|
||||
c.instanceFollowRedirects = follow
|
||||
c.setRequestProperty("User-Agent", USER_AGENT)
|
||||
for ((k, v) in headers) c.setRequestProperty(k, v)
|
||||
if (body != null) {
|
||||
c.doOutput = true
|
||||
c.outputStream.use { it.write(body) }
|
||||
}
|
||||
val status = c.responseCode
|
||||
val stream = if (status >= 400) c.errorStream else c.inputStream
|
||||
val bytes = stream?.use { it.readBytes() } ?: ByteArray(0)
|
||||
return EaReply(status, bytes, c.headerFields.filterKeys { it != null })
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package com.droiddeck.launcher.stores.ea
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreExe
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.amazon.AmazonNative
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import com.droiddeck.launcher.stores.download.StoreDownloadTier
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
internal class EaInstaller(
|
||||
private val app: Context,
|
||||
private val item: CatalogItem,
|
||||
private val folder: File,
|
||||
) : DownloadQueue.DownloadJob {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
handle.stage(DownloadStage.MANIFEST, app.getString(R.string.stores_sync_sign_in))
|
||||
var token = EaAuth.accessToken(app) ?: throw IllegalStateException("Not signed in to EA")
|
||||
val url = try {
|
||||
EaApi.downloadUrl(token, item.id)
|
||||
} catch (e: EaApiException) {
|
||||
if (e.status != 401) throw IllegalStateException(e.message)
|
||||
token = EaAuth.refreshNow(app, token) ?: throw IllegalStateException("The EA sign-in has expired")
|
||||
EaApi.downloadUrl(token, item.id)
|
||||
}
|
||||
val game = EaLibrary.game(app, item.id)
|
||||
val version = runCatching { EaApi.offers(token, listOf(item.id)).firstOrNull()?.gameVersion }.getOrNull().orEmpty()
|
||||
.ifEmpty { game?.version.orEmpty() }
|
||||
val cover = item.tallImageUrl ?: item.imageUrl
|
||||
StoreInstalls.begin(folder, Store.EA, item.id, item.title, cover, item.imageUrl)
|
||||
if (cancelled.get()) return null
|
||||
|
||||
val tier = StoreDownloadTier.current(app)
|
||||
handle.log("ea: \"${item.title}\" tier=${tier.id} window=${tier.networkWindow}")
|
||||
val request = JSONObject()
|
||||
.put("url", url)
|
||||
.put("gameDir", folder.absolutePath)
|
||||
.put("maxWorkers", tier.networkWindow.coerceIn(1, 64))
|
||||
.put("processWorkers", tier.processWorkers)
|
||||
.put("caBundle", "")
|
||||
val shown = AtomicLong(-1)
|
||||
val downloading = AtomicBoolean(false)
|
||||
val listener = object : AmazonNative.InstallListener {
|
||||
override fun onStatus(text: String) { handle.stage(DownloadStage.MANIFEST, text) }
|
||||
override fun onCheck(doneBytes: Long, totalBytes: Long, files: Int, filesTotal: Int) {
|
||||
handle.stage(DownloadStage.MANIFEST, "Checking files…")
|
||||
handle.stageProgress(doneBytes, totalBytes, files, filesTotal, bytes = true)
|
||||
}
|
||||
override fun onSizes(pendingBytes: Long, totalBytes: Long) { handle.diskSize(totalBytes) }
|
||||
override fun onProgress(done: Long, total: Long, files: Int, filesTotal: Int) {
|
||||
if (downloading.compareAndSet(false, true)) handle.stage(DownloadStage.DOWNLOAD)
|
||||
while (true) {
|
||||
val before = shown.get()
|
||||
if (done < before) return
|
||||
if (shown.compareAndSet(before, done)) break
|
||||
}
|
||||
handle.progress(done, total, "Downloading ($files/$filesTotal files)")
|
||||
}
|
||||
override fun onLog(line: String) { handle.log("ea: $line") }
|
||||
override fun beforeReplace(): Boolean = try {
|
||||
StoreInstalls.markUpdating(folder)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
handle.log("ea: the install record could not be switched to updating (${e.javaClass.simpleName})")
|
||||
false
|
||||
}
|
||||
override fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String) = Unit
|
||||
}
|
||||
val outcome = EaNative.install(request, listener, cancelled)
|
||||
if (outcome.cancelled || cancelled.get() && !outcome.success) return null
|
||||
if (!outcome.success) throw IllegalStateException(outcome.error.ifEmpty { "The EA install failed" })
|
||||
val result = outcome.result ?: JSONObject()
|
||||
result.optLong("totalBytes").takeIf { it > 0 }?.let { EaPrefs.get(app).edit().putLong("size_${item.id}", it).apply() }
|
||||
|
||||
handle.stage(DownloadStage.INSTALL, app.getString(R.string.stores_registering))
|
||||
val sidecar = sidecarFor(app, item, folder, game, version, cover) { handle.log("ea: $it") }
|
||||
StoreInstalls.complete(app, folder, sidecar, onStep = { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) })
|
||||
return folder.path
|
||||
}
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
if (deleteFiles) StoreInstalls.discard(app, folder, emptyList())
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun locale(context: Context, available: List<String>): String {
|
||||
val wanted = StoreLanguage.localeFor(null, context)
|
||||
val exact = "${wanted.language}_${wanted.country}"
|
||||
return available.firstOrNull { it.equals(exact, true) }
|
||||
?: available.firstOrNull { it.substringBefore('_').equals(wanted.language, true) }
|
||||
?: available.firstOrNull { it.equals("en_US", true) }
|
||||
?: "en_US"
|
||||
}
|
||||
|
||||
internal fun sidecarFor(app: Context, item: CatalogItem, folder: File, game: EaGame?, version: String, cover: String?, log: (String) -> Unit): StoreGameSidecar {
|
||||
val manifest = EaManifest.read(folder)
|
||||
if (manifest == null) log("no installerdata.xml in ${folder.name}")
|
||||
val launcher = manifest?.launcher()
|
||||
val candidates = listOfNotNull(launcher?.path, game?.executePath?.takeIf { it.isNotEmpty() })
|
||||
var exe = candidates.firstNotNullOfOrNull { EaPaths.relativeOnDisk(folder, EaPaths.relative(it)) }.orEmpty()
|
||||
if (exe.isEmpty()) exe = StoreExe.pick(folder, null, item.title)
|
||||
if (exe.isEmpty()) { log("no exe found; pick one in Steam settings › Added games"); exe = "game.exe" } else log("exe=$exe")
|
||||
val args = EaPaths.splitArgs(listOf(game?.parameters.orEmpty(), launcher?.parameters.orEmpty()).filter { it.isNotBlank() }.joinToString(" "))
|
||||
val keys = JSONArray()
|
||||
listOfNotNull(game?.installCheck, game?.executePath, launcher?.path).mapNotNull { EaPaths.registered(it) }
|
||||
.distinctBy { it.key.lowercase() + "|" + it.value.lowercase() }
|
||||
.forEach { keys.put(JSONArray().put(it.key).put(it.value)) }
|
||||
val extra = linkedMapOf(
|
||||
"contentId" to (game?.contentId ?: item.extra["contentId"].orEmpty()),
|
||||
"slug" to (game?.slug ?: item.extra["slug"].orEmpty()),
|
||||
"multiplayerId" to game?.multiplayerId.orEmpty(),
|
||||
"masterTitleId" to game?.masterTitleId.orEmpty(),
|
||||
"locale" to locale(app, game?.locales.orEmpty()),
|
||||
"registry" to keys.toString(),
|
||||
"touchup" to manifest?.touchupPath.orEmpty().replace('\\', '/').trimStart('/'),
|
||||
"touchupArgs" to manifest?.touchupParameters.orEmpty(),
|
||||
"contentIds" to manifest?.contentIds.orEmpty().joinToString(","),
|
||||
"displayName" to manifest?.title(locale(app, game?.locales.orEmpty())).orEmpty(),
|
||||
).filterValues { it.isNotEmpty() }
|
||||
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 = false, logo = item.logoUrl,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.droiddeck.launcher.stores.ea
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Base64
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
|
||||
object EaLaunch {
|
||||
private const val TAG = "EaLaunch"
|
||||
const val ENV_FILE = ".droiddeck-ea-env"
|
||||
|
||||
private fun installed(context: Context, id: String): Pair<File, StoreGameSidecar>? =
|
||||
StoreInstallRoot.gameFolders(context).firstNotNullOfOrNull { f ->
|
||||
StoreGameSidecar.read(f)?.takeIf { it.store == Store.EA && it.id == id && it.isInstalled }?.let { f to it }
|
||||
}
|
||||
|
||||
internal fun environment(
|
||||
offerId: String,
|
||||
contentId: String,
|
||||
locale: String,
|
||||
generic: String,
|
||||
access: String,
|
||||
opaque: String,
|
||||
account: EaAuth.Account,
|
||||
session: String = UUID.randomUUID().toString(),
|
||||
): LinkedHashMap<String, String> = linkedMapOf(
|
||||
"EAAuthCode" to "unavailable",
|
||||
"EAEgsProxyIpcPort" to "0",
|
||||
"EAEntitlementSource" to "EA",
|
||||
"EAExternalSource" to "EA",
|
||||
"EAFreeTrialGame" to "false",
|
||||
"EAGameLocale" to locale,
|
||||
"EAGenericAuthToken" to generic,
|
||||
"EALaunchCode" to "unavailable",
|
||||
"EALaunchOwner" to "EA",
|
||||
"EALaunchEAID" to account.eaId.ifEmpty { account.displayName },
|
||||
"EALaunchEnv" to "production",
|
||||
"EALaunchOfflineMode" to "false",
|
||||
"EALsxPort" to EaLsx.PORT.toString(),
|
||||
"EARtPLaunchCode" to EaCrypto.rtpCode().toString(),
|
||||
"EASecureLaunchTokenTemp" to account.userId,
|
||||
"EASteamProxyIpcPort" to "0",
|
||||
"OriginSessionKey" to session,
|
||||
"ContentId" to contentId,
|
||||
"EAOnErrorExitRetCode" to "1",
|
||||
"EAConnectionId" to offerId,
|
||||
"EALicenseToken" to offerId,
|
||||
"EALaunchUserAuthToken" to opaque,
|
||||
"EAAccessTokenJWS" to access,
|
||||
)
|
||||
|
||||
/** Adds what installs made before the manifest's content ids and title were recorded are missing. */
|
||||
internal fun backfill(folder: File, sidecar: StoreGameSidecar): StoreGameSidecar {
|
||||
if (sidecar.extra.containsKey("contentIds") || sidecar.extra.containsKey("displayName")) return sidecar
|
||||
val manifest = EaManifest.read(folder) ?: return sidecar
|
||||
val locale = sidecar.extra["locale"].orEmpty().ifEmpty { "en_US" }
|
||||
val added = mapOf(
|
||||
"contentIds" to manifest.contentIds.joinToString(","),
|
||||
"displayName" to manifest.title(locale).orEmpty(),
|
||||
).filterValues { it.isNotEmpty() }
|
||||
if (added.isEmpty()) return sidecar
|
||||
val updated = sidecar.copy(extra = sidecar.extra + added)
|
||||
runCatching { updated.write(folder) }.onFailure { Log.w(TAG, "sidecar: ${it.javaClass.simpleName}") }
|
||||
return updated
|
||||
}
|
||||
|
||||
/** Answers the guest's request right before an EA game starts: session, licence and the LSX endpoint. */
|
||||
fun prepare(context: Context, request: JSONObject): JSONObject {
|
||||
val app = context.applicationContext
|
||||
val id = request.optString("id")
|
||||
val reply = JSONObject().put("ok", false)
|
||||
val (folder, recorded) = installed(app, id) ?: return reply.put("reason", "not-installed")
|
||||
val sidecar = backfill(folder, recorded)
|
||||
runCatching { com.droiddeck.launcher.stores.StoreLaunch.refreshLauncher(folder, sidecar) }
|
||||
File(folder, ENV_FILE).delete()
|
||||
val account = EaAuth.load(app) ?: return reply.put("reason", "signed-out")
|
||||
val access = EaAuth.accessToken(app) ?: return reply.put("reason", "sign-in-expired")
|
||||
val contentId = sidecar.extra["contentId"].orEmpty()
|
||||
val locale = sidecar.extra["locale"].orEmpty().ifEmpty { "en_US" }
|
||||
val core = EaOoa.coreDir(folder, sidecar.exe)
|
||||
val hashVersion = core?.let(EaOoa::activationVersion) ?: 1
|
||||
val hardware = request.optJSONObject("hardware")?.let(EaOoa.Hardware::fromJson)?.takeIf { it.complete(hashVersion) }
|
||||
val legacy = EaOoa.legacyCore(core)
|
||||
|
||||
val lifetime = if (legacy) 14400 else 550
|
||||
val opaque = EaAuth.mint(app, EaAuth.CLIENT_ID, "token", EaAuth.OPAQUE_SCOPES, "OPAQUE", lifetime).orEmpty()
|
||||
val known = (sidecar.extra["contentIds"].orEmpty().split(',') + sidecar.extra["multiplayerId"].orEmpty()).map { it.trim() }.filter { it.isNotEmpty() }.toSet()
|
||||
val lsx = EaLsx.start(app, EaLsx.Game(id, contentId, sidecar.title, sidecar.installVersion, locale, hardware, hashVersion, opaque,
|
||||
System.currentTimeMillis() + (lifetime - 30) * 1000L, known))
|
||||
val env = environment(id, contentId, locale, if (legacy && opaque.isNotEmpty()) opaque else access, access, opaque, EaAuth.load(app) ?: account)
|
||||
val tmp = File(folder, "$ENV_FILE.tmp")
|
||||
tmp.writeText(env.entries.joinToString("\r\n", postfix = "\r\n") { "${it.key}=${it.value}" })
|
||||
tmp.renameTo(File(folder, ENV_FILE))
|
||||
|
||||
val licenses = JSONArray()
|
||||
val notes = ArrayList<String>()
|
||||
if (core != null) {
|
||||
val ids = (listOf(contentId) + sidecar.extra["contentIds"].orEmpty().split(',')).map { it.trim() }.filter { it.isNotEmpty() }.distinct()
|
||||
if (hardware == null) notes += "no-hardware" else {
|
||||
val hash = EaOoa.machineHash(hardware, hashVersion)
|
||||
for (content in ids) {
|
||||
notes += try {
|
||||
for ((path, data) in EaOoa.files(core, EaOoa.request(access, content, hash))) {
|
||||
licenses.put(JSONObject().put("path", path).put("data", Base64.encodeToString(data, Base64.NO_WRAP)))
|
||||
}
|
||||
"$content:ok"
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "licence $content for $id: ${e.message}")
|
||||
com.droiddeck.launcher.stores.StoresState.logLine("ea licence $content for $id v$hashVersion legacy=$legacy: ${e.message}")
|
||||
"$content:refused"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (core != null && notes.isNotEmpty() && notes.none { it.endsWith(":ok") }) runCatching {
|
||||
val rows = EaApi.legacyEntitlements(access).filter { it.optString("productId") == id }
|
||||
val types = rows.joinToString(",") { it.optString("entitlementType") + "/" + it.optString("entitlementTag") + "/" + it.optString("status") }
|
||||
com.droiddeck.launcher.stores.StoresState.logLine("ea $id has no licence; entitlements: ${types.ifEmpty { "none" }}")
|
||||
}
|
||||
val licenseNote = if (core == null) "none-needed" else "v$hashVersion " + notes.joinToString(",")
|
||||
Log.i(TAG, "prepared $id lsx=$lsx legacy=$legacy opaque=${opaque.isNotEmpty()} licence=$licenseNote")
|
||||
return reply.put("ok", true).put("lsx", lsx).put("license", licenseNote).put("licenses", licenses)
|
||||
}
|
||||
}
|
||||
|
||||
object EaSizes {
|
||||
fun size(context: Context, item: com.droiddeck.launcher.stores.CatalogItem): Long {
|
||||
val token = EaAuth.accessToken(context) ?: return 0L
|
||||
val url = runCatching { EaApi.downloadUrl(token, item.id) }.getOrNull() ?: return 0L
|
||||
return EaNative.call("zip.size", JSONObject().put("url", url))?.optLong("totalBytes") ?: 0L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package com.droiddeck.launcher.stores.ea
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
import com.droiddeck.launcher.stores.StoreShelves
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.mergeItems
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
object EaPrefs {
|
||||
const val FILE = "stores.ea"
|
||||
fun get(context: Context): SharedPreferences = context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)
|
||||
}
|
||||
|
||||
data class EaGame(
|
||||
val offerId: String,
|
||||
val contentId: String,
|
||||
val title: String,
|
||||
val slug: String,
|
||||
val tall: String = "",
|
||||
val wide: String = "",
|
||||
val logo: String = "",
|
||||
val version: String = "",
|
||||
val executePath: String = "",
|
||||
val installCheck: String = "",
|
||||
val parameters: String = "",
|
||||
val multiplayerId: String = "",
|
||||
val masterTitleId: String = "",
|
||||
val cloudSaves: String = "",
|
||||
val locales: List<String> = emptyList(),
|
||||
) {
|
||||
fun toJson(): JSONObject = JSONObject()
|
||||
.put("offerId", offerId).put("contentId", contentId).put("title", title).put("slug", slug)
|
||||
.put("tall", tall).put("wide", wide).put("logo", logo).put("version", version)
|
||||
.put("executePath", executePath).put("installCheck", installCheck).put("parameters", parameters)
|
||||
.put("multiplayerId", multiplayerId).put("masterTitleId", masterTitleId).put("cloudSaves", cloudSaves)
|
||||
.put("locales", JSONArray(locales))
|
||||
|
||||
companion object {
|
||||
fun fromJson(o: JSONObject): EaGame? {
|
||||
val locales = o.optJSONArray("locales")
|
||||
return EaGame(
|
||||
offerId = o.optString("offerId").ifEmpty { return null },
|
||||
contentId = o.optString("contentId"),
|
||||
title = o.optString("title"),
|
||||
slug = o.optString("slug"),
|
||||
tall = o.optString("tall"),
|
||||
wide = o.optString("wide"),
|
||||
logo = o.optString("logo"),
|
||||
version = o.optString("version"),
|
||||
executePath = o.optString("executePath"),
|
||||
installCheck = o.optString("installCheck"),
|
||||
parameters = o.optString("parameters"),
|
||||
multiplayerId = o.optString("multiplayerId"),
|
||||
masterTitleId = o.optString("masterTitleId"),
|
||||
cloudSaves = o.optString("cloudSaves"),
|
||||
locales = (0 until (locales?.length() ?: 0)).map { locales!!.optString(it) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
object EaLibrary {
|
||||
private const val KEY_CACHE = "library_cache"
|
||||
private const val KEY_SYNCED_AT = "library_synced_at"
|
||||
private const val THROTTLE_MS = 6 * 60 * 60 * 1000L
|
||||
private const val ART_TTL_MS = 7 * 24 * 60 * 60 * 1000L
|
||||
private const val ART_THREADS = 4
|
||||
const val STORE_URL = "https://www.ea.com/ea-app/library"
|
||||
private val gate = SyncGate()
|
||||
private val generation = java.util.concurrent.atomic.AtomicInteger()
|
||||
|
||||
/** Drops the cache and makes any sync already running drop its results, in one step. */
|
||||
fun reset(context: Context) {
|
||||
synchronized(cacheLock) {
|
||||
generation.incrementAndGet()
|
||||
EaPrefs.get(context).edit().remove(KEY_CACHE).remove(KEY_SYNCED_AT).commit()
|
||||
}
|
||||
}
|
||||
|
||||
internal fun snapshot(app: Context): Pair<Int, List<EaGame>> = synchronized(cacheLock) { generation.get() to cached(app) }
|
||||
|
||||
internal fun storeCache(app: Context, games: List<EaGame>, gen: Int): Boolean = synchronized(cacheLock) {
|
||||
gen == generation.get() &&
|
||||
EaPrefs.get(app).edit().putString(KEY_CACHE, JSONArray(games.map { it.toJson() }).toString()).putLong(KEY_SYNCED_AT, System.currentTimeMillis()).commit()
|
||||
}
|
||||
|
||||
private val cacheLock = Any()
|
||||
private val store = Store.EA
|
||||
|
||||
fun cached(context: Context): List<EaGame> {
|
||||
val text = EaPrefs.get(context).getString(KEY_CACHE, null) ?: return emptyList()
|
||||
val arr = runCatching { JSONArray(text) }.getOrNull() ?: return emptyList()
|
||||
return (0 until arr.length()).mapNotNull { arr.optJSONObject(it)?.let(EaGame::fromJson) }
|
||||
}
|
||||
|
||||
fun game(context: Context, offerId: String): EaGame? = cached(context).firstOrNull { it.offerId == offerId }
|
||||
|
||||
|
||||
fun toCatalogItem(context: Context, g: EaGame): CatalogItem {
|
||||
val prefs = EaPrefs.get(context)
|
||||
val tall = g.tall.ifEmpty { prefs.getString("poster_${g.offerId}", null).orEmpty() }
|
||||
return CatalogItem(
|
||||
store = store,
|
||||
id = g.offerId,
|
||||
title = g.title.ifBlank { g.slug },
|
||||
imageUrl = g.wide.ifEmpty { tall }.ifEmpty { null },
|
||||
tallImageUrl = tall.ifEmpty { g.wide }.ifEmpty { null },
|
||||
publisher = "Electronic Arts",
|
||||
owned = true,
|
||||
sizeBytes = prefs.getLong("size_${g.offerId}", 0L),
|
||||
storeUrl = STORE_URL,
|
||||
extra = mapOf("contentId" to g.contentId, "slug" to g.slug, "version" to g.version),
|
||||
logoUrl = g.logo.ifEmpty { null },
|
||||
)
|
||||
}
|
||||
|
||||
/** One entry per game: owned editions of the same base game collapse onto the base offer. */
|
||||
internal fun pick(owned: List<EaApi.OwnedProduct>, offers: Map<String, EaApi.Offer>): List<Pair<EaApi.OwnedProduct, EaApi.Offer>> {
|
||||
val usable = owned.filter { o ->
|
||||
val offer = offers[o.offerId] ?: return@filter false
|
||||
!o.trial && o.downloadable && offer.downloadable &&
|
||||
(offer.displayType.isEmpty() || offer.displayType.equals("FullGame", true)) &&
|
||||
(o.gameType.isEmpty() || o.gameType.equals("BASE_GAME", true))
|
||||
}
|
||||
return usable.groupBy { it.baseSlug.ifEmpty { it.slug }.ifEmpty { it.offerId } }.values.map { group ->
|
||||
val chosen = group.firstOrNull { it.baseSlug.isEmpty() } ?: group.first()
|
||||
chosen to offers.getValue(chosen.offerId)
|
||||
}.sortedBy { it.first.name.lowercase() }
|
||||
}
|
||||
|
||||
private fun art(app: Context, token: String, slugs: Collection<String>, gen: Int): Map<String, EaApi.Images> {
|
||||
val prefs = EaPrefs.get(app)
|
||||
val now = System.currentTimeMillis()
|
||||
val out = java.util.concurrent.ConcurrentHashMap<String, EaApi.Images>()
|
||||
val pool = Executors.newFixedThreadPool(ART_THREADS)
|
||||
try {
|
||||
for (slug in slugs.filter { it.isNotEmpty() }) {
|
||||
if (gen != generation.get()) break
|
||||
val cached = prefs.getString("art_$slug", null)?.let { runCatching { JSONObject(it) }.getOrNull() }
|
||||
if (cached != null && now - cached.optLong("at") < ART_TTL_MS) {
|
||||
out[slug] = EaApi.Images(cached.optString("tall").ifEmpty { null }, cached.optString("wide").ifEmpty { null }, cached.optString("logo").ifEmpty { null })
|
||||
continue
|
||||
}
|
||||
pool.execute {
|
||||
if (gen != generation.get()) return@execute
|
||||
val images = runCatching { EaApi.images(token, slug) }.getOrNull() ?: return@execute
|
||||
out[slug] = images
|
||||
prefs.edit().putString(
|
||||
"art_$slug",
|
||||
JSONObject().put("at", now).put("tall", images.tall.orEmpty()).put("wide", images.wide.orEmpty()).put("logo", images.logo.orEmpty()).toString(),
|
||||
).apply()
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
pool.shutdown()
|
||||
pool.awaitTermination(2, TimeUnit.MINUTES)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun posters(app: Context, games: List<EaGame>, gen: Int) {
|
||||
val prefs = EaPrefs.get(app)
|
||||
val todo = games.filter { it.tall.isEmpty() && !prefs.contains("poster_${it.offerId}") }.take(40)
|
||||
if (todo.isEmpty()) return
|
||||
val pool = Executors.newFixedThreadPool(ART_THREADS)
|
||||
try {
|
||||
for (g in todo) pool.execute {
|
||||
if (gen != generation.get()) return@execute
|
||||
prefs.edit().putString("poster_${g.offerId}", runCatching { StoreNet.sgdbPoster(g.title) }.getOrDefault("")).apply()
|
||||
}
|
||||
} finally {
|
||||
pool.shutdown()
|
||||
pool.awaitTermination(5, TimeUnit.MINUTES)
|
||||
}
|
||||
}
|
||||
|
||||
private fun publish(app: Context, games: List<EaGame>, gen: Int = generation.get()) {
|
||||
if (gen != generation.get()) return
|
||||
val items = games.map { toCatalogItem(app, it) }
|
||||
StoresState.post {
|
||||
if (gen != generation.get()) return@post
|
||||
StoresState.library[store] = mergeItems(StoresState.library[store], items)
|
||||
val installed = StoresState.installed.filter { it.sidecar.store == store }.map { it.sidecar.id }.toSet()
|
||||
StoresState.shelves[store] = StoreShelves(trending = items.filterNot { it.id in installed }, art = StoresState.shelves[store]?.art.orEmpty())
|
||||
}
|
||||
}
|
||||
|
||||
private inline fun <T> withToken(app: Context, token: String, call: (String) -> T): T = try {
|
||||
call(token)
|
||||
} catch (e: EaApiException) {
|
||||
if (e.status != 401) throw e
|
||||
call(EaAuth.refreshNow(app, token) ?: throw e)
|
||||
}
|
||||
|
||||
fun sync(context: Context, force: Boolean) {
|
||||
if (!gate.enter()) return
|
||||
var forced = force
|
||||
do {
|
||||
runCatching { syncOnce(context.applicationContext, forced) }
|
||||
forced = true
|
||||
} while (gate.leave())
|
||||
}
|
||||
|
||||
private fun syncOnce(app: Context, force: Boolean) {
|
||||
val (gen, cache) = snapshot(app)
|
||||
val prefs = EaPrefs.get(app)
|
||||
val quiet = cache.isNotEmpty() && !force
|
||||
fun status(id: Int) { if (!quiet) StoresState.post { StoresState.status[store] = app.getString(id) } }
|
||||
fun problem(text: String?) {
|
||||
StoresState.post {
|
||||
StoresState.status.remove(store)
|
||||
if (text == null) StoresState.problems.remove(store) else StoresState.problems[store] = text
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (cache.isNotEmpty()) publish(app, cache, gen)
|
||||
if (!force && cache.isNotEmpty() && System.currentTimeMillis() - prefs.getLong(KEY_SYNCED_AT, 0L) in 0 until THROTTLE_MS) {
|
||||
return problem(null)
|
||||
}
|
||||
status(R.string.stores_sync_sign_in)
|
||||
val token = EaAuth.accessToken(app) ?: return problem(StoresState.notSignedInLine(store))
|
||||
status(R.string.stores_sync_game_list)
|
||||
val owned = withToken(app, token) { EaApi.owned(it) }
|
||||
val offers = withToken(app, token) { EaApi.offers(it, owned.map { o -> o.offerId }) }.associateBy { it.offerId }
|
||||
val picked = pick(owned, offers)
|
||||
StoresState.logLine("ea: ${owned.size} owned products, ${picked.size} games")
|
||||
for ((o, offer) in picked) StoresState.logLine(
|
||||
"ea: owned ${o.offerId} content=${offer.contentId} master=${offer.masterTitleId} mp=${offer.multiplayerId} via=${o.ownership.joinToString("+")} type=${o.gameType}")
|
||||
if (picked.isEmpty()) return problem(if (cache.isEmpty()) app.getString(R.string.stores_sync_no_games, store.label) else null)
|
||||
if (gen != generation.get()) return
|
||||
status(R.string.stores_sync_cover_art)
|
||||
val images = art(app, token, picked.map { it.first.slug }, gen)
|
||||
val games = picked.map { (o, offer) ->
|
||||
val img = images[o.slug]
|
||||
EaGame(
|
||||
offerId = o.offerId, contentId = offer.contentId, title = o.name.ifBlank { offer.displayName }, slug = o.slug,
|
||||
tall = img?.tall.orEmpty(), wide = img?.wide.orEmpty(), logo = img?.logo.orEmpty(), version = offer.gameVersion,
|
||||
executePath = offer.executePathOverride, installCheck = offer.installCheckOverride, parameters = offer.executeParameters,
|
||||
multiplayerId = offer.multiplayerId, masterTitleId = offer.masterTitleId, cloudSaves = offer.cloudSaves, locales = offer.locales,
|
||||
)
|
||||
}
|
||||
if (!storeCache(app, games, gen)) return
|
||||
posters(app, games, gen)
|
||||
if (gen != generation.get()) return
|
||||
publish(app, games, gen)
|
||||
problem(null)
|
||||
} catch (e: EaApiException) {
|
||||
StoresState.logLine("ea: library sync failed: ${e.message}")
|
||||
if (e.status == 401) StoresState.markSignInExpired(store)
|
||||
problem(if (cache.isEmpty()) e.message else null)
|
||||
} catch (e: Exception) {
|
||||
StoresState.logLine("ea: library sync failed: ${e.javaClass.simpleName} ${e.message.orEmpty()}")
|
||||
problem(if (cache.isEmpty()) e.message ?: app.getString(R.string.stores_sync_failed) else null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One sync at a time; a request made meanwhile makes the running one go round again rather than being lost. */
|
||||
internal class SyncGate {
|
||||
private var busy = false
|
||||
private var again = false
|
||||
|
||||
/** True when the caller should run; false when a running sync will pick the request up. */
|
||||
@Synchronized
|
||||
fun enter(): Boolean {
|
||||
if (busy) {
|
||||
again = true
|
||||
return false
|
||||
}
|
||||
busy = true
|
||||
return true
|
||||
}
|
||||
|
||||
/** True when another round was requested while running; the caller stays the runner. */
|
||||
@Synchronized
|
||||
fun leave(): Boolean {
|
||||
if (again) {
|
||||
again = false
|
||||
return true
|
||||
}
|
||||
busy = false
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
package com.droiddeck.launcher.stores.ea
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import org.xmlpull.v1.XmlPullParser
|
||||
import org.xmlpull.v1.XmlPullParserFactory
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.OutputStream
|
||||
import java.io.StringReader
|
||||
import java.net.InetAddress
|
||||
import java.net.ServerSocket
|
||||
import java.net.Socket
|
||||
import java.time.LocalDateTime
|
||||
import java.time.ZoneOffset
|
||||
import java.time.format.DateTimeFormatter
|
||||
|
||||
/**
|
||||
* The local SDK endpoint EA games talk to in place of the EA app (LSX: XML over TCP, AES after a
|
||||
* challenge). It answers for the one game DroidDeck last prepared.
|
||||
*/
|
||||
object EaLsx {
|
||||
private const val TAG = "EaLsx"
|
||||
const val PORT = 3216
|
||||
private const val SENDER = "EALS"
|
||||
private const val CHALLENGE_KEY = "cacf897a20b6d612ad0c05e011df52bb"
|
||||
private const val CHALLENGE_VERSION = "10,5,30,15625"
|
||||
private const val LANGUAGES = "ar_SA,de_DE,en_US,es_ES,es_MX,fr_FR,it_IT,ja_JP,ko_KR,pl_PL,pt_BR,ru_RU,zh_CN,zh_TW"
|
||||
|
||||
private val SERVICES = listOf(
|
||||
"EbisuSDK" to "SDK", "EbisuSDK" to "PROFILE", "XMPP" to "PRESENCE", "XMPP" to "FRIENDS", "Commerce" to "COMMERCE",
|
||||
"EbisuSDK" to "RECENTPLAYER", "EbisuSDK" to "IGO", "EbisuSDK" to "MISC", "EALS" to "LOGIN", "EbisuSDK" to "UTILITY",
|
||||
"XMPP" to "XMPP", "XMPP" to "CHAT", "EbisuSDK" to "IGO_EVENT", "EALS" to "EALS_EVENTS", "EbisuSDK" to "LOGIN_EVENT",
|
||||
"XMPP" to "INVITE_EVENT", "EbisuSDK" to "PROFILE_EVENT", "XMPP" to "PRESENCE_EVENT", "XMPP" to "FRIENDS_EVENT",
|
||||
"Commerce" to "COMMERCE_EVENT", "XMPP" to "CHAT_EVENT", "EbisuSDK" to "DOWNLOAD_EVENT", "EbisuSDK" to "PERMISSION",
|
||||
"EbisuSDK" to "RESOURCES", "EbisuSDK" to "BLOCKED_USERS", "EbisuSDK" to "BLOCKED_USER_EVENT", "EbisuSDK" to "GET_USERID",
|
||||
"EbisuSDK" to "ONLINE_STATUS_EVENT", "EbisuSDK" to "ACHIEVEMENT", "EbisuSDK" to "ACHIEVEMENT_EVENT",
|
||||
"EbisuSDK" to "BROADCAST_EVENT", "PI" to "PROGRESSIVE_INSTALLATION", "PI" to "PROGRESSIVE_INSTALLATION_EVENT",
|
||||
"EbisuSDK" to "CONTENT",
|
||||
)
|
||||
|
||||
class Game(
|
||||
val offerId: String,
|
||||
val contentId: String,
|
||||
val title: String,
|
||||
val version: String,
|
||||
val locale: String,
|
||||
val hardware: EaOoa.Hardware?,
|
||||
val hashVersion: Int,
|
||||
val token: String = "",
|
||||
val tokenExpiresAt: Long = 0L,
|
||||
val contentIds: Set<String> = emptySet(),
|
||||
) {
|
||||
val validToken: String? get() = token.takeIf { it.isNotEmpty() && System.currentTimeMillis() < tokenExpiresAt }
|
||||
}
|
||||
|
||||
/** The parts of a request a reply depends on. */
|
||||
class Message(val recipient: String, val id: String, val name: String, val attrs: Map<String, String>, val children: List<Pair<String, String>>)
|
||||
|
||||
interface Account {
|
||||
val userId: String
|
||||
val personaId: String
|
||||
val persona: String
|
||||
fun authCode(clientId: String, scope: String?): String?
|
||||
fun license(contentId: String, requestTicket: String, ticketEngine: String): String?
|
||||
fun entitlements(group: String): List<Map<String, String>>
|
||||
fun token(): String?
|
||||
}
|
||||
|
||||
@Volatile var game: Game? = null
|
||||
@Volatile private var account: Account? = null
|
||||
/** The one session of the current launch that may act for the account. */
|
||||
/** Bumped whenever the launch changes; a connection accepted under an older one is not admitted. */
|
||||
@Volatile internal var generation = 0
|
||||
private val holder = java.util.concurrent.atomic.AtomicReference<Any?>(null)
|
||||
private var server: ServerSocket? = null
|
||||
private val lock = Any()
|
||||
private const val MAX_CLIENTS = 8
|
||||
private val WHITESPACE = Regex("[ \t]+")
|
||||
|
||||
fun start(context: Context, game: Game): Boolean {
|
||||
synchronized(lock) {
|
||||
closeSessions()
|
||||
this.game = game
|
||||
account = AppAccount(context.applicationContext)
|
||||
runCatching { server?.close() }
|
||||
return try {
|
||||
val socket = ServerSocket().apply {
|
||||
reuseAddress = true
|
||||
bind(java.net.InetSocketAddress(InetAddress.getByName("127.0.0.1"), PORT), 8)
|
||||
}
|
||||
server = socket
|
||||
Thread({ accept(socket) }, "ea-lsx").apply { isDaemon = true }.start()
|
||||
Log.i(TAG, "listening on $PORT")
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not listen on $PORT: ${e.javaClass.simpleName}")
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Ends the endpoint; with [offerId], only if it still serves that game, so a late exit cannot stop a newer launch. */
|
||||
fun stop(offerId: String? = null) {
|
||||
synchronized(lock) {
|
||||
if (offerId != null && game?.offerId != offerId) return
|
||||
runCatching { server?.close() }
|
||||
server = null
|
||||
game = null
|
||||
account = null
|
||||
closeSessions()
|
||||
}
|
||||
}
|
||||
|
||||
private fun closeSessions() {
|
||||
generation++
|
||||
holder.set(null)
|
||||
synchronized(sessions) { sessions.forEach { it.trusted = false } }
|
||||
for (socket in open) runCatching { socket.close() }
|
||||
open.clear()
|
||||
}
|
||||
|
||||
private val open = java.util.Collections.newSetFromMap(java.util.concurrent.ConcurrentHashMap<Socket, Boolean>())
|
||||
private const val HANDSHAKE_TIMEOUT_MS = 15_000
|
||||
private const val UNTRUSTED_IDLE_MS = 10 * 60 * 1000
|
||||
|
||||
private fun accept(socket: ServerSocket) {
|
||||
while (!socket.isClosed) {
|
||||
val client = runCatching { socket.accept() }.getOrNull() ?: continue
|
||||
val (owner, unreadable) = ownerUid(client)
|
||||
val verified = owner?.let { it == android.os.Process.myUid() }
|
||||
if (verified == false) {
|
||||
Log.w(TAG, "refused a connection from another app")
|
||||
runCatching { client.close() }
|
||||
continue
|
||||
}
|
||||
if (unreadable != null) note("peer cannot be identified: $unreadable")
|
||||
val session = runCatching { Session(client, client.getOutputStream(), verified == true, unreadable != null) }.getOrNull()
|
||||
val live = session != null && synchronized(lock) { server === socket && admit(session).also { if (it) open += client } }
|
||||
if (!live) {
|
||||
runCatching { client.close() }
|
||||
continue
|
||||
}
|
||||
Thread({ try { serve(client, session!!) } finally { synchronized(sessions) { sessions -= session!! }; open -= client } }, "ea-lsx-client").apply { isDaemon = true }.start()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The uid owning the connecting socket, or null where SELinux hides /proc/net. The guest runs
|
||||
* under this app's uid, so any other uid is another app; an unknown owner never gets credentials.
|
||||
*/
|
||||
/** The connecting socket's uid, or why Android hid socket ownership from this app (some builds deny /proc/net). */
|
||||
private fun ownerUid(client: Socket): Pair<Int?, String?> {
|
||||
val port = client.port
|
||||
var denied: String? = null
|
||||
var read = false
|
||||
for (path in listOf("/proc/net/tcp6", "/proc/net/tcp")) {
|
||||
val lines = runCatching { java.io.File(path).readLines() }.onFailure { denied = "$path ${it.javaClass.simpleName}" }.getOrNull() ?: continue
|
||||
read = true
|
||||
owner(lines, port)?.let { return it to null }
|
||||
}
|
||||
return null to if (read) null else denied ?: "no socket table"
|
||||
}
|
||||
|
||||
internal fun owner(lines: List<String>, port: Int): Int? = lines.drop(1).firstNotNullOfOrNull { line ->
|
||||
val f = line.trim().split(WHITESPACE)
|
||||
val local = f.getOrNull(1)?.substringAfterLast(':')?.toIntOrNull(16)
|
||||
val remote = f.getOrNull(2)?.substringAfterLast(':')?.toIntOrNull(16)
|
||||
if (local == port && remote == PORT) f.getOrNull(7)?.toIntOrNull() else null
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds [session] unless the cap is reached by sessions that cannot be replaced; otherwise the
|
||||
* oldest session that never claimed the prepared game (then the oldest untrusted one) makes room.
|
||||
* Counting and eviction share one lock, so the live total never passes the cap.
|
||||
*/
|
||||
internal fun admit(session: Session): Boolean = synchronized(sessions) {
|
||||
if (sessions.count { !it.evicted } >= MAX_CLIENTS) {
|
||||
val candidates = sessions.filter { !it.trusted && !it.evicted }
|
||||
val victim = candidates.firstOrNull { !it.claimed } ?: candidates.firstOrNull() ?: return false
|
||||
victim.evicted = true
|
||||
runCatching { victim.socket.close() }
|
||||
}
|
||||
sessions += session
|
||||
true
|
||||
}
|
||||
|
||||
internal val sessions = LinkedHashSet<Session>()
|
||||
|
||||
/** Trust and eviction exclude each other: an evicted session never becomes trusted, a trusted one is never evicted. */
|
||||
internal fun promote(session: Session, matches: Boolean) {
|
||||
synchronized(sessions) { session.trusted = matches && !session.evicted && session.born == generation && holder.compareAndSet(null, session) }
|
||||
}
|
||||
|
||||
internal class Session(val socket: Socket, val output: OutputStream, val verified: Boolean, val unverifiable: Boolean = false) {
|
||||
val born = generation
|
||||
val connectedAt = System.currentTimeMillis()
|
||||
@Volatile var evicted = false
|
||||
@Volatile var claimed = false
|
||||
var key: ByteArray? = null
|
||||
@Volatile var trusted = false
|
||||
var pending: ByteArray? = null
|
||||
|
||||
/** A peer Android names as another app never gets account data; one Android cannot name is judged by its claim alone. */
|
||||
val mayTrust get() = (verified || unverifiable) && claimed
|
||||
|
||||
@Synchronized
|
||||
fun send(xml: String) {
|
||||
val key = this.key
|
||||
val text = if (key == null) xml else EaCrypto.hex(EaCrypto.ecbEncrypt(xml.toByteArray(), key))
|
||||
output.write(text.toByteArray())
|
||||
output.write(0)
|
||||
output.flush()
|
||||
}
|
||||
}
|
||||
|
||||
private fun note(line: String) = com.droiddeck.launcher.stores.StoresState.logLine("ea lsx: $line")
|
||||
|
||||
private fun serve(client: Socket, session: Session) {
|
||||
client.tcpNoDelay = true
|
||||
client.soTimeout = HANDSHAKE_TIMEOUT_MS
|
||||
val seen = LinkedHashSet<String>()
|
||||
var why = "closed by the game"
|
||||
note("game connected")
|
||||
try {
|
||||
session.send("<LSX><Event sender=\"$SENDER\"><Challenge build=\"release\" key=\"$CHALLENGE_KEY\" version=\"$CHALLENGE_VERSION\"/></Event></LSX>")
|
||||
val input = client.getInputStream()
|
||||
val pending = ByteArrayOutputStream()
|
||||
val chunk = ByteArray(16 * 1024)
|
||||
while (true) {
|
||||
if (session.key == null) {
|
||||
val left = session.connectedAt + HANDSHAKE_TIMEOUT_MS - System.currentTimeMillis()
|
||||
if (left <= 0) throw java.net.SocketTimeoutException()
|
||||
client.soTimeout = left.toInt()
|
||||
}
|
||||
val n = input.read(chunk)
|
||||
if (n < 0) break
|
||||
pending.write(chunk, 0, n)
|
||||
for (frame in frames(pending, session.key)) {
|
||||
for (one in Regex("<LSX>.*?</LSX>", RegexOption.DOT_MATCHES_ALL).findAll(frame)) {
|
||||
val message = parse(one.value) ?: continue
|
||||
if (seen.add(message.name)) note("request ${message.name}")
|
||||
val reply = runCatching { answer(session, message) }
|
||||
.onFailure { note("${message.name} failed: ${it.javaClass.simpleName}") }.getOrNull()
|
||||
if (reply != null) session.send("<LSX><Response sender=\"${esc(message.recipient)}\" id=\"${esc(message.id)}\">$reply</Response></LSX>")
|
||||
session.pending?.let { session.key = it; session.pending = null }
|
||||
if (session.key != null) {
|
||||
val idle = if (session.trusted) 0 else UNTRUSTED_IDLE_MS
|
||||
if (client.soTimeout != idle) client.soTimeout = idle
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pending.size() > 4 * 1024 * 1024) { why = "message too large"; break }
|
||||
}
|
||||
} catch (e: java.net.SocketTimeoutException) {
|
||||
why = "no trusted handshake in time"
|
||||
} catch (e: Exception) {
|
||||
why = e.javaClass.simpleName
|
||||
} finally {
|
||||
holder.compareAndSet(session, null)
|
||||
note("game disconnected ($why)")
|
||||
runCatching { client.close() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete messages in what has arrived so far. Messages normally end in a NUL; one that does
|
||||
* not counts once it holds a whole `<LSX>` element, plain or decrypted.
|
||||
*/
|
||||
private fun frames(pending: ByteArrayOutputStream, key: ByteArray?): List<String> {
|
||||
val bytes = pending.toByteArray()
|
||||
val out = ArrayList<String>()
|
||||
var start = 0
|
||||
for (i in bytes.indices) {
|
||||
if (bytes[i].toInt() != 0) continue
|
||||
if (i > start) decode(String(bytes, start, i - start, Charsets.UTF_8), key)?.let(out::add)
|
||||
start = i + 1
|
||||
}
|
||||
var rest = String(bytes, start, bytes.size - start, Charsets.UTF_8)
|
||||
if (rest.isNotBlank()) decode(rest, key)?.takeIf { it.contains("</LSX>") }?.let { out += it; rest = "" }
|
||||
pending.reset()
|
||||
pending.write(rest.toByteArray(Charsets.UTF_8))
|
||||
return out
|
||||
}
|
||||
|
||||
private fun decode(frame: String, key: ByteArray?): String? {
|
||||
val text = frame.trim()
|
||||
if (text.isEmpty()) return null
|
||||
if (text.startsWith("<")) return text
|
||||
val k = key ?: return null
|
||||
return runCatching { String(EaCrypto.ecbDecrypt(EaCrypto.unhex(text), k)) }.getOrNull()
|
||||
}
|
||||
|
||||
internal fun parse(xml: String): Message? = runCatching {
|
||||
val parser = XmlPullParserFactory.newInstance().newPullParser()
|
||||
parser.setInput(StringReader(xml))
|
||||
var recipient = ""
|
||||
var id = ""
|
||||
var name = ""
|
||||
val attrs = HashMap<String, String>()
|
||||
val children = ArrayList<Pair<String, String>>()
|
||||
var depth = 0
|
||||
var child = ""
|
||||
while (parser.eventType != XmlPullParser.END_DOCUMENT) {
|
||||
when (parser.eventType) {
|
||||
XmlPullParser.START_TAG -> {
|
||||
depth++
|
||||
when (depth) {
|
||||
2 -> if (parser.name == "Request") {
|
||||
recipient = parser.getAttributeValue(null, "recipient").orEmpty()
|
||||
id = parser.getAttributeValue(null, "id").orEmpty()
|
||||
} else return@runCatching null
|
||||
3 -> {
|
||||
name = parser.name
|
||||
for (i in 0 until parser.attributeCount) attrs[parser.getAttributeName(i)] = parser.getAttributeValue(i)
|
||||
}
|
||||
4 -> child = parser.name
|
||||
}
|
||||
}
|
||||
XmlPullParser.TEXT -> if (depth == 4) children += child to parser.text.trim()
|
||||
XmlPullParser.END_TAG -> depth--
|
||||
}
|
||||
parser.next()
|
||||
}
|
||||
if (name.isEmpty()) null else Message(recipient, id, name, attrs, children)
|
||||
}.getOrNull()
|
||||
|
||||
private fun esc(s: String) = s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """)
|
||||
|
||||
private fun tag(name: String, vararg attrs: Pair<String, Any?>, body: String? = null): String {
|
||||
val a = attrs.filter { it.second != null }.joinToString("") { " ${it.first}=\"${esc(it.second.toString())}\"" }
|
||||
return if (body == null) "<$name$a/>" else "<$name$a>$body</$name>"
|
||||
}
|
||||
|
||||
private fun now() = LocalDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"))
|
||||
|
||||
private fun answer(session: Session, m: Message): String? {
|
||||
val g = game
|
||||
val who = account
|
||||
val person = who?.takeIf { session.trusted }
|
||||
val locale = g?.locale ?: "en_US"
|
||||
return when (m.name) {
|
||||
"ChallengeResponse" -> {
|
||||
val answer = EaCrypto.challengeAnswer(m.attrs["key"].orEmpty())
|
||||
val version = m.attrs["version"].orEmpty()
|
||||
val seed = EaCrypto.challengeSeed(version, answer) ?: 0
|
||||
val content = m.children.firstOrNull { it.first == "ContentId" }?.second.orEmpty()
|
||||
session.claimed = g != null && content.isNotEmpty() && (content == g.contentId || content == g.offerId || content in g.contentIds)
|
||||
val matches = session.mayTrust
|
||||
promote(session, matches)
|
||||
note("challenge version '$version' content '$content' ${when { session.trusted -> "matches the prepared game"; matches -> "matches, but another session holds this launch"; !session.verified && !session.unverifiable -> "comes from an unverified peer"; else -> "does not match the prepared game" }}")
|
||||
session.pending = EaCrypto.lsxKey(seed)
|
||||
Log.i(TAG, "game connected: ${m.children.firstOrNull { it.first == "Title" }?.second.orEmpty()}")
|
||||
tag("ChallengeAccepted", "response" to answer)
|
||||
}
|
||||
"GetConfig" -> tag("GetConfigResponse", body = SERVICES.joinToString("") { tag("Service", "Name" to it.first, "Facility" to it.second) })
|
||||
"GetProfile" -> tag(
|
||||
"GetProfileResponse",
|
||||
"Persona" to person?.persona.orEmpty(), "SubscriberLevel" to 0, "CommerceCurrency" to "USD", "IsTrialSubscriber" to false,
|
||||
"Country" to "US", "UserId" to person?.userId.orEmpty(), "GeoCountry" to "US", "AvatarId" to "", "IsSubscriber" to false,
|
||||
"IsSteamSubscriber" to false, "PersonaId" to person?.personaId.orEmpty(), "IsUnderAge" to false, "UserIndex" to 0,
|
||||
)
|
||||
"GetSetting" -> tag("GetSettingResponse", "Setting" to when (m.attrs["SettingId"]) {
|
||||
"ENVIRONMENT" -> "production"
|
||||
"LANGUAGE" -> locale
|
||||
else -> "false"
|
||||
})
|
||||
"GetGameInfo" -> tag("GetGameInfoResponse", "GameInfo" to when (m.attrs["GameInfoId"]) {
|
||||
"FREETRIAL" -> "false"
|
||||
"LANGUAGES" -> LANGUAGES
|
||||
"INSTALLED_LANGUAGE" -> locale
|
||||
"INSTALLED_VERSION", "AVAILABLE_VERSION" -> g?.version.orEmpty()
|
||||
else -> ""
|
||||
})
|
||||
"GetAllGameInfo" -> tag(
|
||||
"GetAllGameInfoResponse",
|
||||
"FullGamePurchased" to true, "FullGameReleased" to true, "InstalledVersion" to (g?.version ?: "0"), "MaxGroupSize" to 16,
|
||||
"Languages" to LANGUAGES, "Expiration" to "0000-00-00T00:00:00", "UpToDate" to true, "HasExpiration" to false,
|
||||
"EntitlementSource" to "EA", "AvailableVersion" to (g?.version ?: "0"), "DisplayName" to g?.title.orEmpty(),
|
||||
"FreeTrial" to false, "InstalledLanguage" to locale, "FullGameReleaseDate" to "2000-01-01T00:00:00", "SystemTime" to now(),
|
||||
)
|
||||
"GetInternetConnectedState" -> tag("InternetConnectedState", "connected" to 1)
|
||||
"IsProgressiveInstallationAvailable" -> tag("IsProgressiveInstallationAvailableResponse", "ItemId" to m.attrs["ItemId"].orEmpty(), "Available" to false)
|
||||
"AreChunksInstalled" -> tag(
|
||||
"AreChunksInstalledResponse", "ItemId" to m.attrs["ItemId"].orEmpty(), "Installed" to true,
|
||||
body = m.children.joinToString("") { tag(it.first, body = esc(it.second)) },
|
||||
)
|
||||
"GetAuthCode" -> tag("AuthCode", "value" to (who?.takeIf { session.trusted }?.authCode(m.attrs["ClientId"].orEmpty(), m.attrs["Scope"])?.takeIf { session.trusted } ?: "invalid"))
|
||||
"GetAuthToken" -> tag("AuthToken", "value" to if (!session.trusted) "" else (g?.validToken ?: who?.token().orEmpty()))
|
||||
"RequestLicense" -> {
|
||||
val token = who?.takeIf { session.trusted }?.license(g?.contentId.orEmpty(), m.attrs["RequestTicket"].orEmpty(), m.attrs["TicketEngine"].orEmpty())?.takeIf { session.trusted }.orEmpty()
|
||||
tag("RequestLicenseResponse", "License" to token)
|
||||
}
|
||||
"QueryEntitlements" -> {
|
||||
val group = m.attrs["Group"].orEmpty()
|
||||
val rows = who?.takeIf { session.trusted }?.entitlements(group).orEmpty()
|
||||
tag("QueryEntitlementsResponse", body = rows.joinToString("") { e ->
|
||||
tag(
|
||||
"Entitlement",
|
||||
"LastModifiedDate" to "0000-00-00T00:00:00", "EntitlementId" to e["id"], "UseCount" to (e["useCount"] ?: "0"),
|
||||
"Version" to (e["version"] ?: "0"), "ItemId" to e["productId"], "ResourceId" to "", "GrantDate" to e["grantDate"],
|
||||
"Group" to group, "EntitlementTag" to e["entitlementTag"], "Type" to e["entitlementType"],
|
||||
"Expiration" to (e["terminationDate"]?.takeIf { it.isNotEmpty() && it != "null" } ?: "0000-00-00T00:00:00"), "Source" to "",
|
||||
)
|
||||
})
|
||||
}
|
||||
"GetPresence" -> tag("GetPresenceResponse", "UserId" to person?.userId.orEmpty(), "Presence" to "INGAME")
|
||||
"QueryPresence" -> tag("QueryPresenceResponse", body = "")
|
||||
"QueryFriends" -> tag("QueryFriendsResponse", body = "")
|
||||
"GetBlockList" -> tag("GetBlockListResponse", "Return" to "Success", body = "")
|
||||
"QueryOffers" -> tag("QueryOffersResponse", body = "")
|
||||
"QueryImage" -> tag("QueryImageResponse", "Result" to 0, body = "")
|
||||
"GetVoipStatus" -> tag("GetVoipStatusResponse", "Available" to false, "Active" to false)
|
||||
"ShowIGOWindow", "SetDownloaderUtilization" -> null
|
||||
else -> tag("ErrorSuccess", "Code" to 0, "Description" to "")
|
||||
}
|
||||
}
|
||||
|
||||
private class AppAccount(private val app: Context) : Account {
|
||||
private val saved get() = EaAuth.load(app)
|
||||
override val userId: String get() = saved?.userId.orEmpty()
|
||||
override val personaId: String get() = saved?.personaId.orEmpty()
|
||||
override val persona: String get() = saved?.eaId?.ifEmpty { null } ?: saved?.displayName.orEmpty()
|
||||
|
||||
override fun authCode(clientId: String, scope: String?): String? =
|
||||
EaAuth.mint(app, clientId, "code", scopes = scope?.split(' ')?.filter { it.isNotBlank() }.orEmpty())
|
||||
|
||||
override fun license(contentId: String, requestTicket: String, ticketEngine: String): String? {
|
||||
val g = game ?: return null
|
||||
val hw = g.hardware ?: return null
|
||||
val token = EaAuth.accessToken(app) ?: return null
|
||||
return runCatching {
|
||||
EaOoa.request(token, contentId, EaOoa.machineHash(hw, g.hashVersion), requestTicket.ifEmpty { null }, ticketEngine.ifEmpty { null }).gameToken
|
||||
}.onFailure { Log.w(TAG, "licence: ${it.message}") }.getOrNull()
|
||||
}
|
||||
|
||||
override fun token(): String? = EaAuth.mint(app, EaAuth.CLIENT_ID, "token", EaAuth.OPAQUE_SCOPES, "OPAQUE", 14400)
|
||||
|
||||
override fun entitlements(group: String): List<Map<String, String>> {
|
||||
val token = EaAuth.accessToken(app) ?: return emptyList()
|
||||
val arr = runCatching { EaApi.entitlements(token, group) }.getOrNull() ?: return emptyList()
|
||||
return (0 until arr.length()).mapNotNull { arr.optJSONObject(it) }.map { o ->
|
||||
o.keys().asSequence().associateWith { k -> o.optString(k) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.droiddeck.launcher.stores.ea
|
||||
|
||||
import org.xmlpull.v1.XmlPullParser
|
||||
import org.xmlpull.v1.XmlPullParserFactory
|
||||
import java.io.File
|
||||
import java.io.StringReader
|
||||
|
||||
/** What `__Installer/installerdata.xml` in an EA build says about running and finishing the install. */
|
||||
class EaManifest(
|
||||
val version: String,
|
||||
val launchers: List<Launcher>,
|
||||
val touchupPath: String,
|
||||
val touchupParameters: String,
|
||||
val contentIds: List<String> = emptyList(),
|
||||
val titles: Map<String, String> = emptyMap(),
|
||||
) {
|
||||
fun title(locale: String): String? = titles[locale] ?: titles["en_US"] ?: titles.values.firstOrNull()
|
||||
|
||||
class Launcher(val path: String, val parameters: String, val trial: Boolean)
|
||||
|
||||
fun launcher(): Launcher? = launchers.firstOrNull { !it.trial } ?: launchers.firstOrNull()
|
||||
|
||||
companion object {
|
||||
const val RELATIVE = "__Installer/installerdata.xml"
|
||||
|
||||
fun decode(bytes: ByteArray): String {
|
||||
val utf16 = bytes.size >= 2 && ((bytes[0] == 0xFF.toByte() && bytes[1] == 0xFE.toByte()) || (bytes[0] == 0xFE.toByte() && bytes[1] == 0xFF.toByte()))
|
||||
val text = if (utf16) String(bytes, Charsets.UTF_16) else String(bytes, Charsets.UTF_8)
|
||||
return text.trimStart('')
|
||||
}
|
||||
|
||||
fun read(folder: File): EaManifest? {
|
||||
val file = File(folder, RELATIVE).takeIf { it.isFile } ?: EaPaths.find(folder, RELATIVE) ?: return null
|
||||
return runCatching { parse(decode(file.readBytes())) }.getOrNull()
|
||||
}
|
||||
|
||||
fun parse(xml: String): EaManifest {
|
||||
val parser = XmlPullParserFactory.newInstance().newPullParser()
|
||||
parser.setInput(StringReader(xml.replace(Regex("^<\\?xml[^>]*\\?>"), "")))
|
||||
val stack = ArrayList<String>()
|
||||
var version = ""
|
||||
val launchers = ArrayList<Launcher>()
|
||||
var touchupPath = ""
|
||||
var touchupParams = ""
|
||||
var path = ""
|
||||
var params = ""
|
||||
var trial = false
|
||||
val contentIds = ArrayList<String>()
|
||||
val titles = LinkedHashMap<String, String>()
|
||||
var locale = ""
|
||||
while (parser.eventType != XmlPullParser.END_DOCUMENT) {
|
||||
when (parser.eventType) {
|
||||
XmlPullParser.START_TAG -> {
|
||||
val name = parser.name
|
||||
stack += name
|
||||
if (name.equals("gameVersion", true)) {
|
||||
version = parser.getAttributeValue(null, "version") ?: version
|
||||
}
|
||||
if (name.equals("launcher", true)) { path = ""; params = ""; trial = false }
|
||||
if (name.equals("localeInfo", true)) locale = parser.getAttributeValue(null, "locale").orEmpty()
|
||||
}
|
||||
XmlPullParser.TEXT -> {
|
||||
val text = parser.text.trim()
|
||||
val tag = stack.lastOrNull().orEmpty()
|
||||
val parent = stack.getOrNull(stack.size - 2).orEmpty()
|
||||
if (text.isNotEmpty()) when {
|
||||
parent.equals("launcher", true) && tag.equals("filePath", true) -> path = text
|
||||
parent.equals("launcher", true) && tag.equals("parameters", true) -> params = text
|
||||
parent.equals("launcher", true) && tag.equals("trial", true) -> trial = text.equals("true", true) || text == "1"
|
||||
(parent.equals("touchup", true) || parent.equals("executable", true)) && tag.equals("filePath", true) -> touchupPath = text
|
||||
(parent.equals("touchup", true) || parent.equals("executable", true)) && tag.equals("parameters", true) -> touchupParams = text
|
||||
parent.equals("contentIDs", true) && tag.equals("contentID", true) -> contentIds += text
|
||||
parent.equals("localeInfo", true) && tag.equals("title", true) && locale.isNotEmpty() -> titles[locale] = text
|
||||
}
|
||||
}
|
||||
XmlPullParser.END_TAG -> {
|
||||
if (parser.name.equals("launcher", true) && path.isNotEmpty()) launchers += Launcher(path, params, trial)
|
||||
stack.removeLastOrNull()
|
||||
}
|
||||
}
|
||||
parser.next()
|
||||
}
|
||||
return EaManifest(version, launchers, touchupPath, touchupParams, contentIds, titles)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
object EaPaths {
|
||||
private val KEY = Regex("^\\[([^\\]]+)\\](.*)$")
|
||||
|
||||
/** `[HKEY_LOCAL_MACHINE\SOFTWARE\Publisher\Game\Install Dir]bin\game.exe` splits into the registry key, value and relative path. */
|
||||
class Registered(val key: String, val value: String, val rest: String)
|
||||
|
||||
fun registered(path: String): Registered? {
|
||||
val m = KEY.find(path.trim()) ?: return null
|
||||
val full = m.groupValues[1]
|
||||
val cut = full.lastIndexOf('\\').takeIf { it > 0 } ?: return null
|
||||
return Registered(full.substring(0, cut), full.substring(cut + 1), m.groupValues[2])
|
||||
}
|
||||
|
||||
fun relative(path: String): String {
|
||||
val rest = registered(path)?.rest ?: path.replace("{installLocation}", "", ignoreCase = true)
|
||||
return rest.replace('\\', '/').trimStart('/').split('/').filter { it.isNotEmpty() && it != "." }.joinToString("/")
|
||||
}
|
||||
|
||||
/** The real file for a path the manifest may spell in a different case. */
|
||||
fun find(folder: File, relative: String): File? {
|
||||
var cur = folder
|
||||
for (part in relative.replace('\\', '/').split('/').filter { it.isNotEmpty() }) {
|
||||
val names = cur.listFiles() ?: return null
|
||||
cur = names.firstOrNull { it.name == part } ?: names.firstOrNull { it.name.equals(part, true) } ?: return null
|
||||
}
|
||||
return cur.takeIf { it.exists() && it != folder }
|
||||
}
|
||||
|
||||
fun relativeOnDisk(folder: File, relative: String): String? =
|
||||
find(folder, relative)?.relativeTo(folder)?.path?.replace(File.separatorChar, '/')
|
||||
|
||||
fun splitArgs(text: String): List<String> {
|
||||
val out = ArrayList<String>()
|
||||
val cur = StringBuilder()
|
||||
var quoted = false
|
||||
var any = false
|
||||
for (c in text) {
|
||||
when {
|
||||
c == '"' -> { quoted = !quoted; any = true }
|
||||
c.isWhitespace() && !quoted -> { if (any || cur.isNotEmpty()) out += cur.toString(); cur.clear(); any = false }
|
||||
else -> cur.append(c)
|
||||
}
|
||||
}
|
||||
if (any || cur.isNotEmpty()) out += cur.toString()
|
||||
return out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.droiddeck.launcher.stores.ea
|
||||
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.stores.StoresNative
|
||||
import com.droiddeck.launcher.stores.amazon.AmazonNative
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
object EaNative {
|
||||
private const val TAG = "EaNative"
|
||||
const val ENGINE_MISSING = "EA: the store engine is not available"
|
||||
|
||||
fun ready(): Boolean = StoresNative.ensureLoaded()
|
||||
|
||||
fun call(op: String, request: JSONObject): JSONObject? {
|
||||
if (!ready()) return null
|
||||
val text = try { nativeCall(op, request.toString()) } catch (t: Throwable) {
|
||||
Log.w(TAG, "$op: ${t.javaClass.simpleName}")
|
||||
null
|
||||
} ?: return null
|
||||
return runCatching { JSONObject(text) }.getOrNull()
|
||||
}
|
||||
|
||||
fun install(request: JSONObject, events: AmazonNative.InstallListener, cancelled: AtomicBoolean): AmazonNative.InstallOutcome {
|
||||
if (!ready()) return AmazonNative.InstallOutcome(false, false, ENGINE_MISSING, null)
|
||||
val done = CountDownLatch(1)
|
||||
val holder = arrayOfNulls<AmazonNative.InstallOutcome>(1)
|
||||
val bridge = object : AmazonNative.InstallListener by events {
|
||||
override fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String) {
|
||||
holder[0] = AmazonNative.InstallOutcome(success, cancelled, error, result.takeIf { it.isNotEmpty() }?.let { runCatching { JSONObject(it) }.getOrNull() })
|
||||
done.countDown()
|
||||
}
|
||||
}
|
||||
val handle = try { nativeInstall(request.toString(), bridge) } catch (t: Throwable) {
|
||||
return AmazonNative.InstallOutcome(false, false, "The EA install could not start: ${t.javaClass.simpleName}", null)
|
||||
}
|
||||
if (handle == 0L) return holder[0] ?: AmazonNative.InstallOutcome(false, false, "The EA install could not start", null)
|
||||
try {
|
||||
var forwarded = false
|
||||
while (true) {
|
||||
val finished = try { done.await(250, TimeUnit.MILLISECONDS) } catch (e: InterruptedException) { cancelled.set(true); false }
|
||||
if (finished) break
|
||||
if (!forwarded && cancelled.get()) { nativeCancel(handle); forwarded = true }
|
||||
}
|
||||
} finally {
|
||||
nativeRelease(handle)
|
||||
}
|
||||
return holder[0] ?: AmazonNative.InstallOutcome(false, false, "The EA install ended without a result", null)
|
||||
}
|
||||
|
||||
@JvmStatic private external fun nativeCall(op: String, request: String): String?
|
||||
@JvmStatic private external fun nativeInstall(request: String, listener: AmazonNative.InstallListener): Long
|
||||
@JvmStatic private external fun nativeCancel(handle: Long)
|
||||
@JvmStatic private external fun nativeRelease(handle: Long)
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package com.droiddeck.launcher.stores.ea
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.xmlpull.v1.XmlPullParser
|
||||
import org.xmlpull.v1.XmlPullParserFactory
|
||||
import java.io.File
|
||||
import java.io.StringReader
|
||||
import java.net.URLEncoder
|
||||
import java.security.SecureRandom
|
||||
|
||||
/** Origin Online Activation: the per-machine licence an EA game's activation layer checks before it runs. */
|
||||
object EaOoa {
|
||||
private const val LICENSES = "https://proxy.novafusion.ea.com/licenses"
|
||||
const val LICENSE_DIR = "ProgramData/Electronic Arts/EA Services/License"
|
||||
private const val SIGNATURE_SLOT = 65
|
||||
|
||||
/**
|
||||
* What the game sees of the machine inside its Wine prefix: firmware and OS values from Wine's
|
||||
* WMI, CPU values from CPUID executed as x86 code, since an emulated game sees the emulator's
|
||||
* CPUID rather than the host CPU WMI describes.
|
||||
*/
|
||||
class Hardware(
|
||||
val boardManufacturer: String,
|
||||
val boardSerial: String,
|
||||
val biosManufacturer: String,
|
||||
val biosSerial: String,
|
||||
val osInstallDate: String,
|
||||
val osSerial: String,
|
||||
val volumeSerial: String,
|
||||
val gpuPnpId: String,
|
||||
val cpuVendor: String,
|
||||
val cpuEdx: String,
|
||||
val cpuEax: String,
|
||||
val cpuEcx: String,
|
||||
val brand: String,
|
||||
val hostname: String,
|
||||
) {
|
||||
/** Whether the probe reported everything the hash of this activation version is built from. */
|
||||
fun complete(version: Int): Boolean {
|
||||
val needed = arrayListOf(boardManufacturer, biosManufacturer)
|
||||
when {
|
||||
version <= 1 -> needed += listOf(hostname, osInstallDate, osSerial)
|
||||
version == 2 -> needed += listOf(osInstallDate, osSerial, volumeSerial, cpuVendor, cpuEdx, cpuEcx)
|
||||
version == 3 -> needed += listOf(volumeSerial, cpuVendor, cpuEdx, cpuEcx)
|
||||
else -> needed += listOf(volumeSerial, cpuVendor, cpuEdx, cpuEax)
|
||||
}
|
||||
return needed.all { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun fromJson(o: JSONObject): Hardware {
|
||||
fun s(k: String) = o.optString(k).trim()
|
||||
return Hardware(
|
||||
boardManufacturer = s("boardManufacturer"),
|
||||
boardSerial = s("boardSerial").ifEmpty { "None" },
|
||||
biosManufacturer = s("biosManufacturer"),
|
||||
biosSerial = s("biosSerial").ifEmpty { "None" },
|
||||
osInstallDate = s("osInstallDate"),
|
||||
osSerial = s("osSerial"),
|
||||
volumeSerial = s("volumeSerial").replace("-", "").lowercase().let { if (it.isEmpty()) it else it.padStart(8, '0') },
|
||||
gpuPnpId = s("gpuPnpId").ifEmpty { "None" },
|
||||
cpuVendor = s("cpuVendor"),
|
||||
cpuEdx = s("cpuEdx").uppercase(),
|
||||
cpuEax = s("cpuEax").uppercase(),
|
||||
cpuEcx = s("cpuEcx").lowercase(),
|
||||
brand = o.optString("cpuBrand"),
|
||||
hostname = s("hostname"),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun machineHash(hw: Hardware, version: Int): String {
|
||||
val edxEax = hw.cpuEdx + hw.cpuEax
|
||||
val edx = hw.cpuEdx.lowercase()
|
||||
val shortGpu = hw.gpuPnpId.substringBeforeLast('\\', hw.gpuPnpId)
|
||||
val parts = arrayListOf(hw.boardManufacturer, hw.boardSerial)
|
||||
when {
|
||||
version <= 1 -> parts += listOf(hw.hostname, hw.biosManufacturer, hw.biosSerial, hw.osInstallDate, hw.osSerial)
|
||||
version == 2 -> parts += listOf(hw.biosManufacturer, hw.biosSerial, hw.osInstallDate, hw.osSerial, hw.volumeSerial, shortGpu, hw.cpuVendor, edx, hw.cpuEcx)
|
||||
version == 3 -> parts += listOf(hw.biosManufacturer, hw.biosSerial, hw.volumeSerial, shortGpu, hw.cpuVendor, edx, hw.cpuEcx)
|
||||
else -> parts += listOf(hw.biosManufacturer, hw.biosSerial, hw.volumeSerial, hw.gpuPnpId, hw.cpuVendor, edxEax)
|
||||
}
|
||||
val text = StringBuilder(parts.joinToString(";")).append(';')
|
||||
if (version >= 2) text.append(hw.brand.take(47).padEnd(47, '\u0000')).append(';')
|
||||
val digest = EaCrypto.sha1(text.toString().toByteArray(Charsets.ISO_8859_1))
|
||||
return if (version < 4) digest.joinToString("") { Integer.toHexString(it.toInt() and 0xFF) } else EaCrypto.hex(digest)
|
||||
}
|
||||
|
||||
/** Version of the game's activation layer, which decides how the machine hash is built. */
|
||||
fun activationVersion(core: File): Int {
|
||||
val dll = listOf("activation.dll", "awc.dll").firstNotNullOfOrNull { EaPaths.find(core, it) } ?: return 1
|
||||
val (major, minor, patch) = productVersion(dll.readBytes()) ?: return 1
|
||||
return when {
|
||||
major >= 5 -> 4
|
||||
major == 4 && (minor > 7 || (minor == 7 && patch >= 6)) -> 3
|
||||
major == 4 && minor == 7 -> 2
|
||||
major == 4 -> 1
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
|
||||
/** The activation layer's folder: `Core` beside the game's exe, where EA ships it, or at the game root. */
|
||||
fun coreDir(game: File, exe: String): File? {
|
||||
val exeDir = exe.replace('\\', '/').substringBeforeLast('/', "")
|
||||
val candidates = listOfNotNull(exeDir.takeIf { it.isNotEmpty() }?.let { "$it/Core" }, "Core")
|
||||
return candidates.firstNotNullOfOrNull { EaPaths.find(game, it)?.takeIf { f -> f.isDirectory } }
|
||||
}
|
||||
|
||||
/** Games built on the 2012-era EA Core client, which want an opaque token rather than a JWS one. */
|
||||
fun legacyCore(core: File?): Boolean = core != null && EaPaths.find(core, "EACore.dll") != null
|
||||
|
||||
private fun encodedSignature(core: File): Boolean = EaPaths.find(core, "activation.exe") != null
|
||||
|
||||
internal fun productVersion(pe: ByteArray): Triple<Int, Int, Int>? {
|
||||
val magic = byteArrayOf(0xBD.toByte(), 0x04, 0xEF.toByte(), 0xFE.toByte())
|
||||
var i = 0
|
||||
while (i + 24 <= pe.size) {
|
||||
if (pe[i] == magic[0] && pe[i + 1] == magic[1] && pe[i + 2] == magic[2] && pe[i + 3] == magic[3]) {
|
||||
fun u32(at: Int) = (pe[at].toLong() and 0xFF) or ((pe[at + 1].toLong() and 0xFF) shl 8) or ((pe[at + 2].toLong() and 0xFF) shl 16) or ((pe[at + 3].toLong() and 0xFF) shl 24)
|
||||
val ms = u32(i + 16)
|
||||
val ls = u32(i + 20)
|
||||
return Triple((ms ushr 16).toInt(), (ms and 0xFFFF).toInt(), (ls ushr 16).toInt())
|
||||
}
|
||||
i++
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
class License(val fields: LinkedHashMap<String, String>, val namespace: String, val signature: String) {
|
||||
val gameToken: String? get() = fields["GameToken"]?.takeIf { it.isNotEmpty() }
|
||||
val contentId: String get() = fields["ContentId"].orEmpty()
|
||||
}
|
||||
|
||||
internal fun parseLicense(xml: String, signature: String): License {
|
||||
val parser = XmlPullParserFactory.newInstance().apply { isNamespaceAware = false }.newPullParser()
|
||||
parser.setInput(StringReader(xml.replace(Regex("^<\\?xml[^>]*\\?>"), "").trim()))
|
||||
val fields = LinkedHashMap<String, String>()
|
||||
var ns = ""
|
||||
var depth = 0
|
||||
var tag = ""
|
||||
while (parser.eventType != XmlPullParser.END_DOCUMENT) {
|
||||
when (parser.eventType) {
|
||||
XmlPullParser.START_TAG -> {
|
||||
depth++
|
||||
if (depth == 1) ns = parser.getAttributeValue(null, "xmlns").orEmpty() else tag = parser.name
|
||||
if (depth == 2) fields[tag] = ""
|
||||
}
|
||||
XmlPullParser.TEXT -> if (depth == 2) fields[tag] = fields[tag].orEmpty() + parser.text
|
||||
XmlPullParser.END_TAG -> depth--
|
||||
}
|
||||
parser.next()
|
||||
}
|
||||
return License(fields, ns, signature)
|
||||
}
|
||||
|
||||
private fun esc(s: String) = s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """)
|
||||
|
||||
fun licenseXml(l: License): String {
|
||||
val order = listOf("CipherKey", "MachineHash", "ContentId", "UserId", "GameToken", "GrantTime", "StartTime", "Nonce")
|
||||
val body = StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>")
|
||||
body.append("<License xmlns=\"").append(esc(l.namespace)).append("\">")
|
||||
for (k in order) {
|
||||
val v = l.fields[k] ?: continue
|
||||
if (k == "GameToken" && v.isEmpty()) continue
|
||||
body.append('<').append(k).append('>').append(esc(v)).append("</").append(k).append('>')
|
||||
}
|
||||
return body.append("</License>").toString()
|
||||
}
|
||||
|
||||
fun licenseBlob(l: License, encoded: Boolean): ByteArray {
|
||||
val signature = if (encoded) l.signature.toByteArray() else java.util.Base64.getDecoder().decode(l.signature)
|
||||
val head = ByteArray(SIGNATURE_SLOT)
|
||||
System.arraycopy(signature, 0, head, 0, signature.size.coerceAtMost(SIGNATURE_SLOT))
|
||||
return head + EaCrypto.licenseEncrypt(licenseXml(l).toByteArray())
|
||||
}
|
||||
|
||||
fun request(token: String, contentId: String, machineHash: String, requestToken: String? = null, requestType: String? = null): License {
|
||||
val nonce = EaCrypto.hex(ByteArray(4).also(SecureRandom()::nextBytes))
|
||||
val params = mutableListOf("contentId" to contentId, "machineHash" to machineHash, "nonce" to nonce, "ea_eadmtoken" to token)
|
||||
if (requestToken != null) params += "requestToken" to requestToken
|
||||
if (requestType != null) params += "requestType" to requestType
|
||||
val url = LICENSES + "?" + params.joinToString("&") { (k, v) -> k + "=" + URLEncoder.encode(v, "UTF-8") }
|
||||
val reply = EaHttp.request(url, headers = mapOf("X-Requester-Id" to "Origin Online Activation", "User-Agent" to "EACTransaction"))
|
||||
if (!reply.ok) throw IllegalStateException("EA refused the licence (${reply.status}): ${reply.text.replace(Regex("(eadmToken value=\")[^\"]*"), "$1<redacted>\"").take(600)}")
|
||||
val signature = reply.header("x-signature") ?: throw IllegalStateException("EA's licence had no signature")
|
||||
return parseLicense(String(EaCrypto.licenseDecrypt(reply.body), Charsets.UTF_8), signature)
|
||||
}
|
||||
|
||||
/** Licence files for a game about to start, named as the activation layer looks for them. */
|
||||
fun files(core: File, license: License): List<Pair<String, ByteArray>> {
|
||||
val blob = licenseBlob(license, encodedSignature(core))
|
||||
val id = license.contentId
|
||||
return listOf("$LICENSE_DIR/$id.dlf" to blob, "$LICENSE_DIR/${id}_cached.dlf" to blob)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.ea.EaUpdates
|
||||
|
||||
@Composable
|
||||
internal fun EaUpdateButton(installed: InstalledStoreGame, enabled: Boolean) {
|
||||
val ctx = LocalContext.current
|
||||
LaunchedEffect(installed.key, installed.sidecar.installVersion) { EaUpdates.check(ctx, installed) }
|
||||
if (EaUpdates.available[installed.key] == null) return
|
||||
SecondaryButton(stringResource(R.string.common_update), enabled = enabled) { EaUpdates.start(ctx, installed) }
|
||||
}
|
||||
@@ -430,6 +430,7 @@ internal fun GameActions(
|
||||
openUrl(ctx, item?.storeUrl.orEmpty().ifBlank { GameJoltApi.pageUrl("game", installed.sidecar.id) })
|
||||
}
|
||||
}
|
||||
if (store == Store.EA && installed != null) EaUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (store == Store.GOG && installed != null) GogMaintenanceActions(installed)
|
||||
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
|
||||
if (store == Store.XBOX && installed != null && id != null) {
|
||||
@@ -915,7 +916,7 @@ 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 } ?: return
|
||||
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON && it != Store.EA } ?: return
|
||||
val id = g.storeId ?: return
|
||||
val context = LocalContext.current.applicationContext
|
||||
var busy by remember(g.gameId) { mutableStateOf<String?>(null) }
|
||||
|
||||
@@ -742,7 +742,7 @@ internal fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?, showDownlo
|
||||
}
|
||||
}
|
||||
|
||||
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean = e.storeKey?.let { it in ItchUpdates.available || it in GameJoltUpdates.available } == true ||
|
||||
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean = e.storeKey?.let { it in ItchUpdates.available || it in GameJoltUpdates.available || it in com.droiddeck.launcher.stores.ea.EaUpdates.available } == true ||
|
||||
e.source == Store.GOG.id && (e.item?.id ?: e.game?.storeId)?.let { GogMaintenance.checks[it]?.state } == GogMaintenance.State.AVAILABLE
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -33,6 +33,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
|
||||
Store.ITCH.id -> SourceColours(Color(0xFF3A1A1E), Color(0xFFFFB3B3), Color(0xFFFF5C5C))
|
||||
Store.GAMEJOLT.id -> SourceColours(Color(0xFF232E00), Color(0xFFE3FF66), Color(0xFFCCFF00))
|
||||
Store.BATTLENET.id -> SourceColours(Color(0xFF0A2440), Color(0xFF9DD1FF), Color(0xFF148EFF))
|
||||
Store.EA.id -> SourceColours(Color(0xFF3A0E12), Color(0xFFFF9A9A), Color(0xFFFF4747))
|
||||
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
|
||||
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
|
||||
else -> SourceColours(Color(0xFF1A1D22), Color(0xFF9AA3AF), Color(0xFF9AA3AF))
|
||||
@@ -48,6 +49,7 @@ internal fun sourceLabel(source: String): String = when (source) {
|
||||
Store.ITCH.id -> Store.ITCH.label
|
||||
Store.GAMEJOLT.id -> Store.GAMEJOLT.label
|
||||
Store.BATTLENET.id -> Store.BATTLENET.label
|
||||
Store.EA.id -> Store.EA.label
|
||||
else -> stringResource(R.string.source_added)
|
||||
}
|
||||
|
||||
|
||||
@@ -1157,6 +1157,7 @@ internal fun storePalette(base: Palette, store: Store?): Palette {
|
||||
Store.ITCH -> Color(0xFFFF5C5C) to Color(0xFFD93B3B)
|
||||
Store.GAMEJOLT -> Color(0xFFCCFF00) to Color(0xFFA3CC00)
|
||||
Store.BATTLENET -> Color(0xFF148EFF) to Color(0xFF0B6BD3)
|
||||
Store.EA -> Color(0xFFFF4747) to Color(0xFFE03030)
|
||||
null -> return base
|
||||
}
|
||||
val on = if (accent.luminance() > 0.18f) Color(0xFF0B0B0D) else Color.White
|
||||
|
||||
Reference in new issue
Block a user