Stores: Amazon Games - device sign-in, library, installs with the FuelPump environment

Amazon's PKCE device sign-in in StoreLoginActivity and a device
registration for tokens; the entitlements as the library, with posters
backfilled from SteamGridDB since Amazon ships none. Amazon has no public
catalog, so the Store tab's shelves are cut from the account's own games.
An install asks GetGameDownload for the root, parses manifest.proto
(LZMA/XZ, the app's xz library), and fetches every file through the native
engine or eight Java threads, SHA-256 checked. fuel.json or the exe scorer
names the exe; the sidecar carries the Amazon Games Services variables.
This commit is contained in:
The412Banner committed 2026-10-08 17:05:05 -04:00
1 parent 0c59f551af
commit 4bcfca58e2
13 files changed
+1478

No files matched your search

@@ -31,5 +31,7 @@ class App : Application() {
com.droiddeck.launcher.frontend.GameFileSync.start(this)
// The game stores the Stores section can talk to; the native engine loads only when one needs it.
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gog.GogBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.epic.EpicBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
}
}
@@ -0,0 +1,203 @@
package com.droiddeck.launcher.stores.amazon;
import android.util.Log;
import com.droiddeck.launcher.stores.StoreLog;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Amazon's distribution API, as the launcher calls it: every gaming call carries `X-Amz-Target`,
* `x-amzn-token`, the launcher's User-Agent and `Content-Encoding: amz-1.0`.
*/
public final class AmazonApiClient {
private static final String TAG = "AmazonApi";
private static final String ENTITLEMENTS_URL = "https://gaming.amazon.com/api/distribution/entitlements";
private static final String DISTRIBUTION_URL = "https://gaming.amazon.com/api/distribution/v2/public";
private static final String GAMING_USER_AGENT = "com.amazon.agslauncher.win/3.0.9202.1";
private static final String DOWNLOAD_USER_AGENT = "nile/0.1 Amazon";
private static final String KEY_ID = "d5dc8b8b-86c8-4fc4-ae93-18c0def5314d";
private AmazonApiClient() {}
/** The owned games, every page, one per productId. */
public static List<AmazonGame> getEntitlements(String accessToken, String deviceSerial) {
Map<String, AmazonGame> seen = new HashMap<>();
String nextToken = null;
String hardwareHash;
try {
hardwareHash = AmazonPkce.sha256Upper(deviceSerial);
} catch (Exception e) {
Log.e(TAG, "hardware hash failed", e);
return new ArrayList<>();
}
do {
try {
JSONObject body = new JSONObject();
body.put("Operation", "GetEntitlements");
body.put("clientId", "Sonic");
body.put("syncPoint", JSONObject.NULL);
body.put("nextToken", nextToken != null ? nextToken : JSONObject.NULL);
body.put("maxResults", 50);
body.put("productIdFilter", JSONObject.NULL);
body.put("keyId", KEY_ID);
body.put("hardwareHash", hardwareHash);
String resp = postGaming(ENTITLEMENTS_URL, "com.amazon.animusdistributionservice.entitlement.AnimusEntitlementsService.GetEntitlements", accessToken, body.toString());
if (resp == null) break;
JSONObject json = new JSONObject(resp);
JSONArray entitlements = json.optJSONArray("entitlements");
if (entitlements == null) break;
for (int i = 0; i < entitlements.length(); i++) {
AmazonGame game = parseEntitlement(entitlements.getJSONObject(i));
if (game != null && !game.productId.isEmpty()) seen.put(game.productId, game);
}
nextToken = json.optString("nextToken", null);
if (nextToken != null && nextToken.isEmpty()) nextToken = null;
} catch (Exception e) {
Log.e(TAG, "entitlements page failed: " + e.getClass().getSimpleName());
break;
}
} while (nextToken != null);
return new ArrayList<>(seen.values());
}
static AmazonGame parseEntitlement(JSONObject e) {
try {
JSONObject product = e.optJSONObject("product");
if (product == null) return null;
AmazonGame game = new AmazonGame();
game.entitlementId = e.optString("id", "");
game.productId = product.optString("id", "");
game.title = product.optString("title", "Unknown");
game.productSku = product.optString("sku", "");
String productType = product.optString("productType", "");
if (productType.isEmpty()) productType = product.optString("type", "");
String parentId = product.optString("parentProductId", "");
if (parentId.isEmpty()) parentId = product.optString("baseProductId", "");
if (parentId.isEmpty()) parentId = product.optString("parentId", "");
JSONObject detail = product.optJSONObject("productDetail");
if (detail != null) {
game.artUrl = detail.optString("iconUrl", "");
JSONObject details = detail.optJSONObject("details");
if (details != null) {
if (game.artUrl.isEmpty()) game.artUrl = details.optString("logoUrl", "");
game.heroUrl = details.optString("backgroundUrl1", "");
if (game.heroUrl.isEmpty()) game.heroUrl = details.optString("backgroundUrl2", "");
game.developer = details.optString("developer", "");
game.publisher = details.optString("publisher", "");
if (productType.isEmpty()) productType = details.optString("productType", "");
if (parentId.isEmpty()) parentId = details.optString("parentProductId", "");
}
}
boolean typeIsDlc = !productType.isEmpty() && !productType.equalsIgnoreCase("GAME");
if (typeIsDlc || !parentId.isEmpty()) { game.isDLC = true; game.parentProductId = parentId; }
return game;
} catch (Exception ex) {
Log.e(TAG, "entitlement parse failed: " + ex.getClass().getSimpleName());
return null;
}
}
public static final class GameDownloadSpec {
public String downloadUrl;
public String versionId;
}
/** The download root and version for a game; takes the entitlement id, not the product id. */
public static GameDownloadSpec getGameDownload(String accessToken, String entitlementId) {
try {
JSONObject body = new JSONObject().put("entitlementId", entitlementId).put("Operation", "GetGameDownload");
String resp = postGaming(DISTRIBUTION_URL, "com.amazon.animusdistributionservice.external.AnimusDistributionService.GetGameDownload", accessToken, body.toString());
if (resp == null) return null;
JSONObject json = new JSONObject(resp);
GameDownloadSpec spec = new GameDownloadSpec();
spec.downloadUrl = json.optString("downloadUrl", "");
spec.versionId = json.optString("versionId", "");
return spec.downloadUrl.isEmpty() ? null : spec;
} catch (Exception e) {
Log.e(TAG, "GetGameDownload failed: " + e.getClass().getSimpleName());
return null;
}
}
/** The live version id of a product, for update checks. */
public static String getLiveVersionId(String accessToken, String productId) {
try {
JSONObject body = new JSONObject().put("adgProductIds", new JSONArray().put(productId)).put("Operation", "GetLiveVersionIds");
String resp = postGaming(DISTRIBUTION_URL, "com.amazon.animusdistributionservice.external.AnimusDistributionService.GetLiveVersionIds", accessToken, body.toString());
if (resp == null) return null;
JSONObject versions = new JSONObject(resp).optJSONObject("versionIds");
return versions == null ? null : versions.optString(productId, null);
} catch (Exception e) {
Log.e(TAG, "GetLiveVersionIds failed: " + e.getClass().getSimpleName());
return null;
}
}
/** `baseUrl/segment`, keeping a query string on the base where it belongs. */
public static String appendPath(String baseUrl, String segment) {
int q = baseUrl.indexOf('?');
if (q >= 0) return baseUrl.substring(0, q) + "/" + segment + baseUrl.substring(q);
return baseUrl + "/" + segment;
}
static String postGaming(String urlStr, String target, String accessToken, String body) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setRequestProperty("X-Amz-Target", target);
conn.setRequestProperty("x-amzn-token", accessToken);
conn.setRequestProperty("User-Agent", GAMING_USER_AGENT);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Content-Encoding", "amz-1.0");
try (OutputStream os = conn.getOutputStream()) { os.write(body.getBytes(StandardCharsets.UTF_8)); }
int code = conn.getResponseCode();
String resp = AmazonAuthClient.readStream(code < 400 ? conn.getInputStream() : conn.getErrorStream());
conn.disconnect();
if (code < 200 || code >= 300) { Log.e(TAG, "HTTP " + code + " from " + StoreLog.redactUrl(urlStr)); return null; }
return resp;
} catch (Exception e) {
Log.e(TAG, "POST failed: " + StoreLog.redactUrl(urlStr) + " (" + e.getClass().getSimpleName() + ")");
return null;
}
}
/** Raw bytes (the manifest). */
public static byte[] getBytes(String urlStr, String accessToken) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(30000);
conn.setReadTimeout(120000);
if (accessToken != null) conn.setRequestProperty("x-amzn-token", accessToken);
conn.setRequestProperty("User-Agent", DOWNLOAD_USER_AGENT);
int code = conn.getResponseCode();
if (code < 200 || code >= 300) { Log.e(TAG, "bytes HTTP " + code + " from " + StoreLog.redactUrl(urlStr)); conn.disconnect(); return null; }
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
try (java.io.InputStream in = conn.getInputStream()) {
byte[] buf = new byte[131072];
int n;
while ((n = in.read(buf)) != -1) out.write(buf, 0, n);
}
conn.disconnect();
return out.toByteArray();
} catch (Exception e) {
Log.e(TAG, "bytes failed: " + StoreLog.redactUrl(urlStr) + " (" + e.getClass().getSimpleName() + ")");
return null;
}
}
}
@@ -0,0 +1,174 @@
package com.droiddeck.launcher.stores.amazon;
import android.util.Log;
import com.droiddeck.launcher.stores.StoreLog;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
/**
* Amazon's device-auth endpoints, as the Amazon Games launcher registers itself:
* POST api.amazon.com/auth/register (the PKCE code for bearer tokens, with a device registration)
* POST api.amazon.com/auth/token (access token renewal; the refresh token stays)
* POST api.amazon.com/auth/deregister (sign-out, best-effort)
*/
public final class AmazonAuthClient {
private static final String TAG = "AmazonAuth";
static final String REGISTER_URL = "https://api.amazon.com/auth/register";
static final String REFRESH_URL = "https://api.amazon.com/auth/token";
static final String DEREGISTER_URL = "https://api.amazon.com/auth/deregister";
public static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0";
static final String APP_NAME = "AGSLauncher for Windows";
static final String APP_VERSION = "1.0.0";
static final String DEVICE_TYPE = "A2UMVHOX7UP4V7";
static final String OS_VERSION = "10.0.19044.0";
public static final class RegisterResult {
public String accessToken;
public String refreshToken;
public long expiresIn;
public String name;
}
private AmazonAuthClient() {}
/** Exchanges the PKCE authorization code for bearer tokens; null on failure. */
public static RegisterResult registerDevice(String authCode, String codeVerifier, String deviceSerial, String clientId) {
try {
JSONObject authData = new JSONObject();
authData.put("authorization_code", authCode);
authData.put("client_domain", "DeviceLegacy");
authData.put("client_id", clientId);
authData.put("code_algorithm", "SHA-256");
authData.put("code_verifier", codeVerifier);
authData.put("use_global_authentication", false);
JSONObject regData = new JSONObject();
regData.put("app_name", APP_NAME);
regData.put("app_version", APP_VERSION);
regData.put("device_model", "Windows");
regData.put("device_name", JSONObject.NULL);
regData.put("device_serial", deviceSerial);
regData.put("device_type", DEVICE_TYPE);
regData.put("domain", "Device");
regData.put("os_version", OS_VERSION);
JSONArray tokenTypes = new JSONArray().put("bearer").put("mac_dms");
JSONArray extensions = new JSONArray().put("customer_info").put("device_info");
JSONObject body = new JSONObject();
body.put("auth_data", authData);
body.put("registration_data", regData);
body.put("requested_extensions", extensions);
body.put("requested_token_type", tokenTypes);
body.put("user_context_map", new JSONObject());
String response = postJson(REGISTER_URL, body.toString(), null, null, null);
if (response == null) return null;
JSONObject success = new JSONObject(response).getJSONObject("response").getJSONObject("success");
JSONObject bearer = success.getJSONObject("tokens").getJSONObject("bearer");
RegisterResult result = new RegisterResult();
result.accessToken = bearer.getString("access_token");
result.refreshToken = bearer.getString("refresh_token");
result.expiresIn = bearer.optLong("expires_in", 3600L);
JSONObject customer = success.optJSONObject("extensions") != null ? success.getJSONObject("extensions").optJSONObject("customer_info") : null;
result.name = customer != null ? customer.optString("name", "") : "";
return result;
} catch (Exception e) {
Log.e(TAG, "registerDevice failed: " + e.getClass().getSimpleName());
return null;
}
}
/** A new access token; the refresh token is not returned and stays as it was. */
public static RegisterResult refreshAccessToken(String refreshToken) {
try {
JSONObject body = new JSONObject();
body.put("source_token", refreshToken);
body.put("source_token_type", "refresh_token");
body.put("requested_token_type", "access_token");
body.put("app_name", APP_NAME);
body.put("app_version", APP_VERSION);
String response = postJson(REFRESH_URL, body.toString(), null, "x-amzn-identity-auth-domain", "api.amazon.com");
if (response == null) return null;
JSONObject json = new JSONObject(response);
RegisterResult result = new RegisterResult();
result.accessToken = json.getString("access_token");
result.refreshToken = refreshToken;
result.expiresIn = json.optLong("expires_in", 3600L);
return result;
} catch (Exception e) {
Log.e(TAG, "refresh failed: " + e.getClass().getSimpleName());
return null;
}
}
public static void deregisterDevice(String accessToken) {
try {
JSONObject body = new JSONObject().put("requested_extensions", new JSONArray().put("device_info").put("customer_info"));
postJson(DEREGISTER_URL, body.toString(), accessToken, null, null);
} catch (Exception e) {
Log.w(TAG, "deregister failed (ignored): " + e.getClass().getSimpleName());
}
}
static String postJson(String urlStr, String body, String bearerToken, String extraKey, String extraVal) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
if (bearerToken != null) conn.setRequestProperty("Authorization", "Bearer " + bearerToken);
if (extraKey != null) conn.setRequestProperty(extraKey, extraVal);
try (OutputStream os = conn.getOutputStream()) { os.write(body.getBytes(StandardCharsets.UTF_8)); }
int code = conn.getResponseCode();
String resp = readStream(code < 400 ? conn.getInputStream() : conn.getErrorStream());
conn.disconnect();
if (code < 200 || code >= 300) { Log.e(TAG, "HTTP " + code + " from " + StoreLog.redactUrl(urlStr)); return null; }
return resp;
} catch (Exception e) {
Log.e(TAG, "POST failed: " + StoreLog.redactUrl(urlStr) + " (" + e.getClass().getSimpleName() + ")");
return null;
}
}
static String getRequest(String urlStr, String token, String tokenHeader, String extraKey, String extraVal) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(30000);
conn.setReadTimeout(120000);
if (token != null && tokenHeader != null) conn.setRequestProperty(tokenHeader, token);
if (extraKey != null) conn.setRequestProperty(extraKey, extraVal);
int code = conn.getResponseCode();
String resp = readStream(code < 400 ? conn.getInputStream() : conn.getErrorStream());
conn.disconnect();
if (code < 200 || code >= 300) { Log.e(TAG, "GET HTTP " + code + " from " + StoreLog.redactUrl(urlStr)); return null; }
return resp;
} catch (Exception e) {
Log.e(TAG, "GET failed: " + StoreLog.redactUrl(urlStr) + " (" + e.getClass().getSimpleName() + ")");
return null;
}
}
static String readStream(InputStream is) throws IOException {
if (is == null) return "";
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) sb.append(line);
}
return sb.toString();
}
}
@@ -0,0 +1,161 @@
package com.droiddeck.launcher.stores.amazon
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.webkit.WebView
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.StoreExe
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoreLoginActivity
import com.droiddeck.launcher.stores.StoreShelves
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
/**
* Amazon Games in the Stores section. Amazon has no browsable catalog for third-party clients -
* Prime Gaming's claims live on gaming.amazon.com, signed in - so the Store tab's shelves are cut
* from the account's own library: owned-not-installed as Trending, installed as Your library.
*/
object AmazonBackend : StoreBackend {
private const val TAG = "AmazonBackend"
override val store: Store = Store.AMAZON
init { LoginFlows.amazonFlow = { LoginFlow() } }
override fun signIn(context: Context) {
context.startActivity(Intent(context, StoreLoginActivity::class.java).putExtra(StoreLoginActivity.EXTRA_STORE, store.id).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
override fun signOut(context: Context) {
AmazonCredentialStore.load(context)?.let { Thread({ AmazonAuthClient.deregisterDevice(it.accessToken) }, "amazon-deregister").start() }
AmazonPrefs.get(context).edit().remove("library_cache").remove("library_synced_at").apply()
}
override fun syncLibrary(context: Context, force: Boolean) {
val app = context.applicationContext
val cached = AmazonLibrary.cached(app)
if (cached.isNotEmpty()) StoresState.post { publish(app, cached) }
StoresState.post { StoresState.status[store] = "Fetching your library…" }
Thread({
val result = AmazonLibrary.sync(app, force) { line -> StoresState.post { StoresState.status[store] = line } }
StoresState.post {
StoresState.status.remove(store)
when (result) {
is AmazonLibrary.SyncResult.Ok -> { publish(app, result.games); StoresState.problems.remove(store) }
is AmazonLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message
AmazonLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = "Amazon session expired: sign in again."
AmazonLibrary.SyncResult.Throttled -> publish(app, AmazonLibrary.cached(app))
AmazonLibrary.SyncResult.Busy -> {}
}
}
}, "amazon-sync").start()
}
/** The library and, from it, the shelves. */
private fun publish(app: Context, games: List<AmazonGame>) {
val items = games.map { AmazonLibrary.toCatalogItem(app, it) }
StoresState.library[store] = items
val installed = StoresState.installed.filter { it.sidecar.store == store }.map { it.sidecar.id }.toSet()
StoresState.shelves[store] = StoreShelves(trending = items.filter { it.id !in installed }, free = emptyList(), deals = emptyList(), whatsNew = emptyList())
}
override fun loadShelves(context: Context, force: Boolean) {
// Nothing public to fetch; the shelves follow the library sync.
if (!StoresState.library.containsKey(store)) syncLibrary(context, force)
}
override fun install(context: Context, item: CatalogItem) {
val app = context.applicationContext
val entitlementId = item.extra["entitlementId"] ?: ""
if (entitlementId.isEmpty()) { StoresState.logLine("Amazon: \"${item.title}\" has no entitlement to download with"); return }
val game = AmazonGame().apply { productId = item.id; this.entitlementId = entitlementId; title = item.title; productSku = item.extra["sku"] ?: ""; heroUrl = item.imageUrl ?: ""; artUrl = item.tallImageUrl ?: "" }
DownloadQueue.enqueue(app, DownloadEntry(store, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes)) { InstallJob(app, game, item) }
}
override fun uninstall(context: Context, game: InstalledStoreGame) {}
private class InstallJob(val app: Context, val game: AmazonGame, val item: CatalogItem) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
private val folder: File = StoreInstallRoot.folderFor(app, Store.AMAZON, game.productId, game.title)
override fun run(handle: DownloadQueue.JobHandle): String? {
handle.stage(DownloadStage.MANIFEST, "Checking sign-in…")
val token = AmazonCredentialStore.getValidAccessToken(app) ?: throw AmazonDownloadManager.InstallException("Not signed in to Amazon Games")
var downloading = false
val result = AmazonDownloadManager.install(app, game, token, folder, cancelled, object : AmazonDownloadManager.Callback {
override fun onProgress(message: String, pct: Int) {
when {
message.startsWith("Finishing") -> handle.stage(DownloadStage.INSTALL, message)
message.startsWith("Downloading") && !message.startsWith("Downloading manifest") -> { if (!downloading) { downloading = true; handle.stage(DownloadStage.DOWNLOAD, message) } else handle.progress(-1, -1, message) }
else -> handle.stage(DownloadStage.MANIFEST, message)
}
}
override fun onBytes(done: Long, total: Long, speedBps: Long) { handle.progress(done, total, null, speedBps) }
override fun onLog(line: String) { handle.log(line) }
}) ?: return null
if (cancelled.get()) return null
handle.stage(DownloadStage.INSTALL, "Registering with Steam…")
AmazonLibrary.rememberSize(app, game.productId, result.bytes)
AmazonPrefs.get(app).edit().putString("version_${game.productId}", result.versionId).apply()
val spec = AmazonLaunchHelper.buildLaunchSpec(folder, game.title)
val exe = spec.exeRelative.ifEmpty { StoreExe.pick(folder, null, game.title) }
if (exe.isEmpty()) handle.log("amazon: no exe found in ${folder.name}; pick one in Steam settings › Added games")
val env = LinkedHashMap<String, String>()
for (kv in AmazonLaunchHelper.buildFuelEnv(game.entitlementId, game.productSku)) env[kv.substringBefore('=')] = kv.substringAfter('=')
val sidecar = StoreGameSidecar(
Store.AMAZON, game.productId, game.title, exe = exe.ifEmpty { "game.exe" }, args = spec.args, env = env,
installVersion = result.versionId ?: "", installedAt = System.currentTimeMillis(),
cover = item.tallImageUrl ?: item.imageUrl, hero = item.imageUrl,
extra = mapOf("entitlementId" to game.entitlementId, "sku" to game.productSku),
)
StoreInstalls.complete(app, folder, sidecar)
return folder.path
}
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
if (deleteFiles) Thread({ StoreInstalls.deleteTree(folder) }, "amazon-cancel-clean").start()
}
}
/** Amazon's device sign-in: a PKCE challenge on the sign-in page, the code on the return URL, a device registration for tokens. */
private class LoginFlow : StoreLoginActivity.Flow {
private val serial = AmazonPkce.generateDeviceSerial()
private val clientId = AmazonPkce.generateClientId(serial)
private val verifier = AmazonPkce.generateCodeVerifier()
override val startUrl: String = "https://www.amazon.com/ap/signin" +
"?openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0" +
"&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select" +
"&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select" +
"&openid.mode=checkid_setup&openid.oa2.scope=device_auth_access" +
"&openid.ns.oa2=http%3A%2F%2Fwww.amazon.com%2Fap%2Fext%2Foauth%2F2&openid.oa2.response_type=code" +
"&openid.oa2.code_challenge_method=S256&openid.oa2.client_id=device%3A$clientId" +
"&language=en_US&marketPlaceId=ATVPDKIKX0DER&openid.return_to=https%3A%2F%2Fwww.amazon.com" +
"&openid.pape.max_auth_age=0&openid.ns.pape=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fpape%2F1.0" +
"&openid.assoc_handle=amzn_sonic_games_launcher&pageId=amzn_sonic_games_launcher" +
"&openid.oa2.code_challenge=${AmazonPkce.generateCodeChallenge(verifier)}"
override val userAgent: String get() = AmazonAuthClient.USER_AGENT
override fun isRedirect(url: String): Boolean = url.contains("openid.oa2.authorization_code=")
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? {
val code = Uri.parse(url).getQueryParameter("openid.oa2.authorization_code")
if (code.isNullOrEmpty()) { Log.w(TAG, "login: return URL without a code"); return activity.getString(com.droiddeck.launcher.R.string.stores_login_error_verification) }
val result = AmazonAuthClient.registerDevice(code, verifier, serial, clientId) ?: return activity.getString(com.droiddeck.launcher.R.string.stores_login_error_generic)
AmazonCredentialStore.save(activity, result.accessToken, result.refreshToken, serial, clientId, System.currentTimeMillis() + result.expiresIn * 1000L, result.name)
Log.i(TAG, "signed in")
return null
}
}
}
@@ -0,0 +1,52 @@
package com.droiddeck.launcher.stores.amazon
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAccounts
import org.json.JSONObject
/**
* The Amazon sign-in in StoreAccounts' private file: the bearer tokens, the device serial and
* client id the registration was made with (the entitlements call hashes the serial), the expiry.
*/
object AmazonCredentialStore {
private const val TAG = "AmazonAuth"
class Credentials(val accessToken: String, val refreshToken: String?, val deviceSerial: String, val clientId: String, val expiresAt: Long)
@JvmStatic
fun save(context: Context, accessToken: String, refreshToken: String?, deviceSerial: String, clientId: String, expiresAt: Long, displayName: String?) {
val json = StoreAccounts.read(context, Store.AMAZON) ?: JSONObject()
json.put("access_token", accessToken).put("device_serial", deviceSerial).put("client_id", clientId).put("expires_at", expiresAt)
if (!refreshToken.isNullOrEmpty()) json.put("refresh_token", refreshToken)
if (!displayName.isNullOrEmpty()) json.put("display_name", displayName)
StoreAccounts.write(context, Store.AMAZON, json)
}
@JvmStatic
fun load(context: Context): Credentials? {
val json = StoreAccounts.read(context, Store.AMAZON) ?: return null
val token = json.optString("access_token", "").ifEmpty { return null }
return Credentials(token, json.optString("refresh_token", "").ifEmpty { null }, json.optString("device_serial", ""), json.optString("client_id", ""), json.optLong("expires_at", 0L))
}
@JvmStatic
fun isLoggedIn(context: Context): Boolean = load(context) != null
/** A valid access token, refreshed within five minutes of expiry; null when signed out or the refresh failed. */
@JvmStatic
fun getValidAccessToken(context: Context): String? {
val creds = load(context) ?: return null
if (creds.expiresAt - System.currentTimeMillis() < 5L * 60L * 1000L && creds.refreshToken != null) {
val result = AmazonAuthClient.refreshAccessToken(creds.refreshToken)
if (result != null) {
save(context, result.accessToken, creds.refreshToken, creds.deviceSerial, creds.clientId, System.currentTimeMillis() + result.expiresIn * 1000L, null)
Log.i(TAG, "token refreshed")
return result.accessToken
}
Log.w(TAG, "token refresh failed; using the stored token")
}
return creds.accessToken
}
}
@@ -0,0 +1,285 @@
package com.droiddeck.launcher.stores.amazon;
import android.content.Context;
import android.util.Log;
import com.droiddeck.launcher.stores.StoreLog;
import com.droiddeck.launcher.stores.download.StoreDownloadTier;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
/**
* The Amazon Games install pipeline, ported from Bannerlator: GetGameDownload for the download
* root and version, `manifest.proto`, then every file fetched (the native engine when it is
* there, eight Java threads otherwise), SHA-256 checked, written as `.tmp` and renamed. A
* complete file on disk is skipped by size, so a rerun resumes. Blocking; the queue runs it.
*/
public final class AmazonDownloadManager {
private static final String TAG = "AmazonDownload";
private static final int MAX_PARALLEL = 8;
private static final int MAX_RETRIES = 3;
private static final long PROGRESS_INTERVAL = 512L * 1024L;
private static final String DOWNLOAD_USER_AGENT = "nile/0.1 Amazon";
private static final String IN_PROGRESS_MARKER = ".amazon_download_in_progress";
private static final String COMPLETE_MARKER = ".amazon_download_complete";
public interface Callback {
void onProgress(String message, int pct);
default void onBytes(long done, long total, long speedBps) {}
default void onLog(String line) {}
}
public static final class Result {
public final String versionId;
public final long bytes;
Result(String versionId, long bytes) { this.versionId = versionId; this.bytes = bytes; }
}
public static final class InstallException extends Exception {
InstallException(String message) { super(message); }
}
private AmazonDownloadManager() {}
/** Installs the game into {@code installDir}; null when cancelled, an exception when it fails. */
public static Result install(Context ctx, AmazonGame game, String accessToken, File installDir, AtomicBoolean cancel, Callback cb) throws InstallException {
if (game.entitlementId == null || game.entitlementId.isEmpty()) throw new InstallException("This game has no entitlement to download with");
try {
installDir.mkdirs();
new File(installDir, IN_PROGRESS_MARKER).createNewFile();
cb.onProgress("Asking Amazon for the download…", 0);
AmazonApiClient.GameDownloadSpec spec = AmazonApiClient.getGameDownload(accessToken, game.entitlementId);
if (spec == null) throw new InstallException("Amazon gave no download for this game");
cb.onLog("amazon: version " + spec.versionId);
cb.onProgress("Downloading manifest…", 1);
byte[] manifestBytes = AmazonApiClient.getBytes(AmazonApiClient.appendPath(spec.downloadUrl, "manifest.proto"), accessToken);
if (manifestBytes == null) throw new InstallException("The manifest could not be downloaded");
AmazonManifest.ParsedManifest manifest = AmazonManifest.parse(manifestBytes);
cb.onLog("amazon: " + manifest.allFiles.size() + " files, " + fmt(manifest.totalInstallSize));
long usable = installDir.getUsableSpace();
if (manifest.totalInstallSize > 0 && usable > 0 && manifest.totalInstallSize > usable)
throw new InstallException("Not enough free space: need " + fmt(manifest.totalInstallSize) + ", only " + fmt(usable) + " free");
cb.onBytes(0, manifest.totalInstallSize, 0);
if (cancel.get()) return null;
AtomicLong downloaded = new AtomicLong(0);
AtomicLong lastEmit = new AtomicLong(0);
AtomicLong lastSpeedMs = new AtomicLong(System.currentTimeMillis());
AtomicLong lastSpeedBytes = new AtomicLong(0);
AtomicLong speedBps = new AtomicLong(0);
List<AmazonManifest.ManifestFile> files = manifest.allFiles;
final long total = manifest.totalInstallSize;
if (AmazonNative.isAvailable()) {
if (!downloadAllNative(ctx, spec.downloadUrl, files, total, installDir, downloaded, lastEmit, lastSpeedMs, lastSpeedBytes, speedBps, cancel, cb)) {
if (cancel.get()) return null;
throw new InstallException("A file failed to download");
}
} else {
cb.onLog("amazon: engine=built-in (" + MAX_PARALLEL + " threads)");
ExecutorService pool = Executors.newFixedThreadPool(MAX_PARALLEL);
List<Future<Boolean>> futures = new ArrayList<>();
for (AmazonManifest.ManifestFile file : files) {
final String dlUrl = spec.downloadUrl;
futures.add(pool.submit(() -> downloadFileWithRetry(file, dlUrl, installDir, downloaded, lastEmit, total, lastSpeedMs, lastSpeedBytes, speedBps, cb, cancel)));
}
pool.shutdown();
try {
for (Future<Boolean> f : futures) {
if (!f.get()) {
pool.shutdownNow();
if (cancel.get()) return null;
throw new InstallException("A file failed to download");
}
}
} catch (InstallException e) {
throw e;
} catch (Exception e) {
pool.shutdownNow();
throw new InstallException("download pool error: " + e.getClass().getSimpleName());
}
}
if (cancel.get()) return null;
cb.onProgress("Finishing…", 98);
new File(installDir, IN_PROGRESS_MARKER).delete();
new File(installDir, COMPLETE_MARKER).createNewFile();
return new Result(spec.versionId, total);
} catch (InstallException e) {
throw e;
} catch (Exception e) {
Log.w(TAG, "install failed", e);
throw new InstallException(e.getClass().getSimpleName() + (e.getMessage() != null ? ": " + e.getMessage() : ""));
}
}
/** One entry per manifest file with the exact URL the Java loop would open and the SHA-256 when it would check it. */
static String buildPlan(List<AmazonManifest.ManifestFile> files, String baseUrl) {
JSONArray arr = new JSONArray();
try {
for (AmazonManifest.ManifestFile file : files) {
String hashHex = file.hashHex();
arr.put(new JSONObject().put("relPath", file.unixPath()).put("url", AmazonApiClient.appendPath(baseUrl, "files/" + hashHex))
.put("size", file.size).put("sha256hex", (file.hashAlgorithm == 0 && file.hashBytes.length > 0) ? hashHex : ""));
}
} catch (Exception e) {
Log.e(TAG, "plan failed", e);
return "";
}
return arr.toString();
}
private static boolean downloadAllNative(Context ctx, String baseUrl, List<AmazonManifest.ManifestFile> files, long totalSize, File installDir,
AtomicLong totalDownloaded, AtomicLong lastEmit, AtomicLong lastSpeedMs, AtomicLong lastSpeedBytes, AtomicLong speedBps,
AtomicBoolean cancel, Callback cb) {
String plan = buildPlan(files, baseUrl);
if (plan.isEmpty()) return false;
StoreDownloadTier tier = StoreDownloadTier.Companion.current(ctx);
int maxWorkers = Math.max(1, Math.min(128, tier.getNetworkWindow()));
int processWorkers = Math.max(Math.max(1, Runtime.getRuntime().availableProcessors() / 2), tier.getProcessWorkers());
cb.onLog("amazon: engine=native workers=" + maxWorkers + " process_workers=" + processWorkers + " tier=" + tier.getId());
AmazonNative.Listener listener = new AmazonNative.Listener() {
@Override public void onProgress(long bytesDone, long bytesTotal, long filesDone, long filesTotal) {
totalDownloaded.set(bytesDone);
long emit = lastEmit.get();
if (bytesDone - emit >= PROGRESS_INTERVAL && lastEmit.compareAndSet(emit, bytesDone)) {
sampleSpeed(bytesDone, lastSpeedMs, lastSpeedBytes, speedBps);
cb.onProgress("Downloading (" + filesDone + "/" + filesTotal + " files)" + speedSuffix(speedBps.get()), (int) (bytesDone * 95L / Math.max(1, totalSize)));
cb.onBytes(bytesDone, totalSize, speedBps.get());
}
}
@Override public void onLog(String line) { cb.onLog(line); }
@Override public void onComplete(boolean success, String error, long bytesWritten) {
cb.onLog("amazon: complete success=" + success + " bytes=" + bytesWritten + (error.isEmpty() ? "" : " error=" + error));
}
};
AmazonNative.RunResult result = AmazonNative.runBlocking(plan, installDir.getAbsolutePath(), "", maxWorkers, processWorkers, cancel::get, listener);
if (result.cancelled) return false;
if (!result.success) { cb.onLog("amazon: engine failed: " + result.error); return false; }
return true;
}
private static boolean downloadFileWithRetry(AmazonManifest.ManifestFile file, String baseUrl, File installDir, AtomicLong totalDownloaded, AtomicLong lastEmit, long totalSize,
AtomicLong lastSpeedMs, AtomicLong lastSpeedBytes, AtomicLong speedBps, Callback cb, AtomicBoolean cancel) {
File destFile = new File(installDir, file.unixPath());
File tmpFile = new File(installDir, file.unixPath() + ".tmp");
if (destFile.exists() && destFile.length() == file.size) { totalDownloaded.addAndGet(file.size); return true; }
String fileUrl = AmazonApiClient.appendPath(baseUrl, "files/" + file.hashHex());
for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
destFile.getParentFile().mkdirs();
try {
if (!downloadFile(fileUrl, tmpFile, totalDownloaded, lastEmit, totalSize, lastSpeedMs, lastSpeedBytes, speedBps, cb, cancel)) { tmpFile.delete(); return false; }
if (file.hashAlgorithm == 0 && file.hashBytes.length > 0 && !Arrays.equals(sha256(tmpFile), file.hashBytes)) {
cb.onLog("amazon: SHA-256 mismatch for " + file.unixPath());
tmpFile.delete();
if (attempt < MAX_RETRIES) { Thread.sleep(1000L << (attempt - 1)); continue; }
return false;
}
if (destFile.exists()) destFile.delete();
return tmpFile.renameTo(destFile);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
tmpFile.delete();
return false;
} catch (Exception e) {
cb.onLog("amazon: attempt " + attempt + " failed for " + file.unixPath() + ": " + e.getClass().getSimpleName());
tmpFile.delete();
if (attempt < MAX_RETRIES) { try { Thread.sleep(1000L << (attempt - 1)); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return false; } }
}
}
return false;
}
/** Streams one file; false = cancelled. */
private static boolean downloadFile(String urlStr, File tmpFile, AtomicLong totalDownloaded, AtomicLong lastEmit, long totalSize,
AtomicLong lastSpeedMs, AtomicLong lastSpeedBytes, AtomicLong speedBps, Callback cb, AtomicBoolean cancel) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(120000);
conn.setRequestProperty("User-Agent", DOWNLOAD_USER_AGENT);
int code = conn.getResponseCode();
if (code < 200 || code >= 300) { conn.disconnect(); throw new IOException("HTTP " + code + " " + StoreLog.redactUrl(urlStr)); }
try (InputStream in = conn.getInputStream(); FileOutputStream out = new FileOutputStream(tmpFile)) {
byte[] buf = new byte[65536];
int n;
while ((n = in.read(buf)) >= 0) {
if (cancel.get()) { conn.disconnect(); return false; }
out.write(buf, 0, n);
long dl = totalDownloaded.addAndGet(n);
long emit = lastEmit.get();
if (dl - emit >= PROGRESS_INTERVAL && lastEmit.compareAndSet(emit, dl)) {
sampleSpeed(dl, lastSpeedMs, lastSpeedBytes, speedBps);
cb.onProgress("Downloading: " + tmpFile.getName().replace(".tmp", "") + speedSuffix(speedBps.get()), (int) (dl * 95L / Math.max(1, totalSize)));
cb.onBytes(dl, totalSize, speedBps.get());
}
}
} finally {
conn.disconnect();
}
return true;
}
/** The install size from the manifest alone, or -1. Blocking. */
public static long fetchInstallSizeBytes(String accessToken, String entitlementId) {
try {
AmazonApiClient.GameDownloadSpec spec = AmazonApiClient.getGameDownload(accessToken, entitlementId);
if (spec == null) return -1;
byte[] bytes = AmazonApiClient.getBytes(AmazonApiClient.appendPath(spec.downloadUrl, "manifest.proto"), accessToken);
if (bytes == null) return -1;
AmazonManifest.ParsedManifest m = AmazonManifest.parse(bytes);
return m.totalInstallSize > 0 ? m.totalInstallSize : -1;
} catch (Exception e) {
return -1;
}
}
public static boolean isInstalled(File installDir) { return new File(installDir, COMPLETE_MARKER).exists(); }
private static byte[] sha256(File file) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
try (FileInputStream fis = new FileInputStream(file)) {
byte[] buf = new byte[65536];
int n;
while ((n = fis.read(buf)) >= 0) digest.update(buf, 0, n);
}
return digest.digest();
}
private static void sampleSpeed(long done, AtomicLong lastSpeedMs, AtomicLong lastSpeedBytes, AtomicLong speedBps) {
long nowMs = System.currentTimeMillis(), prevMs = lastSpeedMs.get();
if (nowMs - prevMs >= 500 && lastSpeedMs.compareAndSet(prevMs, nowMs)) {
long prevB = lastSpeedBytes.getAndSet(done);
long dt = nowMs - prevMs;
if (dt > 0) speedBps.set((done - prevB) * 1000L / dt);
}
}
private static String speedSuffix(long bps) {
if (bps <= 0) return "";
return " " + (bps >= 1048576 ? String.format("%.1f MB/s", bps / 1048576.0) : (bps / 1024) + " KB/s");
}
private static String fmt(long bytes) {
if (bytes >= 1073741824L) return String.format("%.1f GB", bytes / 1073741824.0);
if (bytes >= 1048576L) return String.format("%.1f MB", bytes / 1048576.0);
return String.format("%.0f KB", bytes / 1024.0);
}
}
@@ -0,0 +1,28 @@
package com.droiddeck.launcher.stores.amazon;
/**
* One Amazon Games library entry. {@code productId} ("amzn1.adg.product.…") names the game,
* {@code entitlementId} (the top-level UUID of GetEntitlements) is what GetGameDownload takes,
* {@code productSku} goes to the game as AMAZON_GAMES_FUEL_PRODUCT_SKU.
*/
public class AmazonGame {
public String productId = "";
public String entitlementId = "";
public String title = "";
/** iconUrl: square art. */
public String artUrl = "";
/** backgroundUrl1: the wide background. */
public String heroUrl = "";
public String developer = "";
public String publisher = "";
public String productSku = "";
public String versionId = "";
public boolean isDLC = false;
public String parentProductId = "";
/** The id's last segment, for display when there is no title. */
public String shortId() {
int dot = productId.lastIndexOf('.');
return (dot >= 0 && dot < productId.length() - 1) ? productId.substring(dot + 1) : productId;
}
}
@@ -0,0 +1,140 @@
package com.droiddeck.launcher.stores.amazon;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* How an installed Amazon game is started: its `fuel.json` names the exe, a working subfolder and
* arguments when the publisher shipped one; otherwise the exe is scored (Unreal shipping binaries
* first, the title's name, never crash handlers or installers). The FuelPump variables the Amazon
* Games Services SDK reads go into the game's environment.
*/
public final class AmazonLaunchHelper {
private static final String TAG = "AmazonLaunch";
public static final class LaunchSpec {
/** The exe relative to the install folder, forward slashes. */
public String exeRelative = "";
/** The arguments fuel.json names, in order. */
public List<String> args = new ArrayList<>();
}
private AmazonLaunchHelper() {}
public static LaunchSpec buildLaunchSpec(File installDir, String gameTitle) {
LaunchSpec spec = new LaunchSpec();
String fuelCommand = null;
File fuelFile = new File(installDir, "fuel.json");
if (fuelFile.exists()) {
try {
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(fuelFile))) {
String line;
while ((line = br.readLine()) != null) sb.append(line);
}
JSONObject main = new JSONObject(sb.toString()).optJSONObject("Main");
if (main != null) {
String cmd = main.optString("Command", "").trim();
if (!cmd.isEmpty()) fuelCommand = cmd;
JSONArray argsArr = main.optJSONArray("Args");
if (argsArr != null) for (int i = 0; i < argsArr.length(); i++) {
String a = argsArr.optString(i);
if (a != null && !a.isEmpty()) spec.args.add(a);
}
}
} catch (Exception e) {
Log.w(TAG, "fuel.json unreadable; choosing the exe by name");
}
}
if (fuelCommand != null && new File(installDir, fuelCommand.replace('\\', '/')).isFile()) {
spec.exeRelative = fuelCommand.replace('\\', '/');
} else {
File chosen = choosePrimaryExe(installDir, gameTitle);
if (chosen != null) spec.exeRelative = relativePath(installDir, chosen);
}
return spec;
}
/** The FuelPump variables, as KEY=VALUE, for the game's environment. */
public static String[] buildFuelEnv(String entitlementId, String productSku) {
return new String[]{
"FUEL_DIR=C:\\ProgramData\\Amazon Games Services\\Legacy",
"AMAZON_GAMES_SDK_PATH=C:\\ProgramData\\Amazon Games Services\\AmazonGamesSDK",
"AMAZON_GAMES_FUEL_ENTITLEMENT_ID=" + entitlementId,
"AMAZON_GAMES_FUEL_PRODUCT_SKU=" + productSku,
"AMAZON_GAMES_FUEL_DISPLAY_NAME=Player",
};
}
private static final Pattern UE_SHIPPING = Pattern.compile(".*-win(32|64)(-shipping)?\\.exe$", Pattern.CASE_INSENSITIVE);
private static final Pattern UE_BINARIES = Pattern.compile(".*/binaries/win(32|64)/.*\\.exe$", Pattern.CASE_INSENSITIVE);
private static final Pattern GENERIC_NAME = Pattern.compile("^[a-z]\\d{1,3}\\.exe$", Pattern.CASE_INSENSITIVE);
private static final String[] NEGATIVE_KEYWORDS = { "crash", "handler", "viewer", "compiler", "tool", "setup", "unins", "eac", "launcher", "steam" };
private static boolean isLikelyStub(File f) {
String n = f.getName().toLowerCase();
if (GENERIC_NAME.matcher(n).matches()) return true;
if (f.length() < 1_000_000L) return true;
for (String kw : NEGATIVE_KEYWORDS) if (n.contains(kw)) return true;
return false;
}
static int scoreExe(File f, String gameNameLower) {
int score = 50;
String path = f.getAbsolutePath().replace('\\', '/').toLowerCase();
if (UE_SHIPPING.matcher(path).matches()) score += 300;
if (UE_BINARIES.matcher(path).find()) score += 250;
String fn = f.getName().toLowerCase();
String cleanGame = gameNameLower.replaceAll("[^a-z]", "");
String cleanFile = fn.replaceAll("[^a-z]", "");
boolean nameMatch = path.contains(gameNameLower) || (cleanGame.length() >= 5 && cleanFile.length() >= 5 && cleanGame.substring(0, 5).equals(cleanFile.substring(0, 5)));
if (nameMatch) score += 100;
for (String kw : NEGATIVE_KEYWORDS) if (path.contains(kw)) { score -= 150; break; }
if (GENERIC_NAME.matcher(fn).matches()) score -= 200;
return score;
}
static File choosePrimaryExe(File installDir, String gameTitle) {
if (!installDir.isDirectory()) return null;
List<File> all = new ArrayList<>();
collectExe(installDir, all);
if (all.isEmpty()) return null;
List<File> pool = new ArrayList<>();
for (File f : all) if (!isLikelyStub(f)) pool.add(f);
if (pool.isEmpty()) pool = all;
String lowerTitle = gameTitle.toLowerCase();
File best = null;
int bestScore = Integer.MIN_VALUE;
for (File f : pool) {
int s = scoreExe(f, lowerTitle);
if (best == null || s > bestScore || (s == bestScore && f.length() > best.length())) { best = f; bestScore = s; }
}
return best;
}
private static void collectExe(File dir, List<File> out) {
File[] entries = dir.listFiles();
if (entries == null) return;
for (File f : entries) {
if (f.isDirectory()) collectExe(f, out);
else if (f.getName().toLowerCase().endsWith(".exe")) out.add(f);
}
}
private static String relativePath(File base, File absolute) {
String b = base.getAbsolutePath();
if (!b.endsWith("/")) b += "/";
String a = absolute.getAbsolutePath();
return a.startsWith(b) ? a.substring(b.length()) : absolute.getName();
}
}
@@ -0,0 +1,128 @@
package com.droiddeck.launcher.stores.amazon
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreNet
import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
/**
* The signed-in account's Amazon Games library: the entitlements, DLC folded under their base
* game, cached so the tab paints at once, re-synced when forced or 15 minutes stale. Amazon
* publishes a square icon and a wide background only, so a 2:3 poster per title is backfilled
* from SteamGridDB (a few per pass). Ported from Bannerlator's AmazonLibraryRepo.
*/
object AmazonLibrary {
private const val TAG = "AmazonLibrary"
private const val CACHE_KEY = "library_cache"
private const val LAST_SYNC_KEY = "library_synced_at"
private const val THROTTLE_MS = 15L * 60L * 1000L
private const val POSTER_BUDGET = 40
private val syncing = AtomicBoolean(false)
sealed interface SyncResult {
class Ok(val games: List<AmazonGame>) : SyncResult
class Failed(val message: String) : SyncResult
object NotLoggedIn : SyncResult
object Busy : SyncResult
object Throttled : SyncResult
}
fun cached(context: Context): List<AmazonGame> {
val json = AmazonPrefs.get(context).getString(CACHE_KEY, null) ?: return emptyList()
return runCatching {
val arr = JSONArray(json)
val out = ArrayList<AmazonGame>(arr.length())
for (i in 0 until arr.length()) {
val j = arr.optJSONObject(i) ?: continue
val g = AmazonGame()
g.productId = j.optString("productId", ""); g.entitlementId = j.optString("entitlementId", ""); g.title = j.optString("title", "")
g.artUrl = j.optString("artUrl", ""); g.heroUrl = j.optString("heroUrl", ""); g.developer = j.optString("developer", "")
g.publisher = j.optString("publisher", ""); g.productSku = j.optString("productSku", ""); g.versionId = j.optString("versionId", "")
if (g.productId.isNotEmpty()) out.add(g)
}
out.distinctBy { it.productId }.sortedBy { it.title.lowercase() }
}.getOrDefault(emptyList())
}
fun poster(context: Context, productId: String): String? = AmazonPrefs.get(context).getString("vcover_$productId", null)?.ifBlank { null }
fun rememberSize(context: Context, productId: String, bytes: Long) {
if (bytes > 0) AmazonPrefs.get(context).edit().putLong("size_$productId", bytes).apply()
}
fun sync(context: Context, force: Boolean = false, onStatus: (String) -> Unit = {}): SyncResult {
if (!syncing.compareAndSet(false, true)) return SyncResult.Busy
try {
val app = context.applicationContext
val p = AmazonPrefs.get(app)
val cachedList = cached(app)
if (!force && cachedList.isNotEmpty() && System.currentTimeMillis() - p.getLong(LAST_SYNC_KEY, 0L) < THROTTLE_MS) {
backfillPosters(p, cachedList, onStatus)
return SyncResult.Throttled
}
onStatus("Checking sign-in…")
val creds = AmazonCredentialStore.load(app) ?: return SyncResult.NotLoggedIn
val token = AmazonCredentialStore.getValidAccessToken(app) ?: return SyncResult.Failed("Amazon session expired: sign in again.")
onStatus("Fetching game list…")
val all = AmazonApiClient.getEntitlements(token, creds.deviceSerial)
if (all.isNullOrEmpty()) return if (cachedList.isEmpty()) SyncResult.Failed("No games found in your Amazon library") else SyncResult.Ok(cachedList)
val games = all.filter { !(it.isDLC && it.parentProductId.isNotEmpty()) }.ifEmpty { all }
.sortedWith { a, b -> a.title.compareTo(b.title, ignoreCase = true) }
for (fresh in games) cachedList.firstOrNull { it.productId == fresh.productId }?.let { fresh.versionId = it.versionId }
saveCache(p, games)
p.edit().putLong(LAST_SYNC_KEY, System.currentTimeMillis()).apply()
backfillPosters(p, games, onStatus)
Log.i(TAG, "sync: entitlements=${all.size} games=${games.size}")
return SyncResult.Ok(games)
} catch (e: Exception) {
Log.w(TAG, "sync failed: ${e.message}")
return SyncResult.Failed(e.message ?: "Sync failed")
} finally {
syncing.set(false)
}
}
private fun backfillPosters(p: SharedPreferences, games: List<AmazonGame>, onStatus: (String) -> Unit) {
val missing = games.filter { it.productId.isNotEmpty() && !p.contains("vcover_${it.productId}") }.take(POSTER_BUDGET)
if (missing.isEmpty()) return
onStatus("Fetching cover art…")
val pool = Executors.newFixedThreadPool(4)
val futures = missing.map { g -> pool.submit(Callable { g.productId to StoreNet.sgdbPoster(g.title) }) }
pool.shutdown()
val ed = p.edit()
for (f in futures) {
val (pid, url) = runCatching { f.get() }.getOrNull() ?: continue
// A miss is recorded as "" so it is not asked again every pass.
ed.putString("vcover_$pid", url)
}
ed.apply()
}
private fun saveCache(p: SharedPreferences, games: List<AmazonGame>) {
runCatching {
val arr = JSONArray()
for (g in games) arr.put(JSONObject().put("productId", g.productId).put("entitlementId", g.entitlementId).put("title", g.title).put("artUrl", g.artUrl)
.put("heroUrl", g.heroUrl).put("developer", g.developer).put("publisher", g.publisher).put("productSku", g.productSku).put("versionId", g.versionId))
p.edit().putString(CACHE_KEY, arr.toString()).apply()
}
}
fun toCatalogItem(context: Context, g: AmazonGame): CatalogItem = CatalogItem(
store = Store.AMAZON, id = g.productId, title = g.title.ifBlank { g.shortId() },
imageUrl = g.heroUrl.ifBlank { null } ?: g.artUrl.ifBlank { null },
tallImageUrl = poster(context, g.productId) ?: g.artUrl.ifBlank { null } ?: g.heroUrl.ifBlank { null },
tags = listOfNotNull(g.developer.ifBlank { null }, g.publisher.ifBlank { null }.takeIf { it != g.developer }).joinToString(", "),
developer = g.developer, owned = true,
sizeBytes = AmazonPrefs.get(context).getLong("size_${g.productId}", 0L),
storeUrl = "https://gaming.amazon.com/home",
extra = mapOf("entitlementId" to g.entitlementId, "sku" to g.productSku),
)
}
@@ -0,0 +1,158 @@
package com.droiddeck.launcher.stores.amazon;
import org.tukaani.xz.LZMAInputStream;
import org.tukaani.xz.XZInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Amazon's `manifest.proto`: a big-endian header length, a ManifestHeader protobuf naming the
* compression, then an LZMA (or XZ) body holding the Manifest protobuf - packages of files, each
* with a Windows path, a size and a SHA-256. Read with a tiny protobuf walker; the XZ library the
* app already carries does the decompression.
*/
public final class AmazonManifest {
public static final class ManifestFile {
public final String path;
public final long size;
/** 0 = SHA-256. */
public final int hashAlgorithm;
public final byte[] hashBytes;
ManifestFile(String path, long size, int hashAlgorithm, byte[] hashBytes) {
this.path = path; this.size = size; this.hashAlgorithm = hashAlgorithm; this.hashBytes = hashBytes;
}
public String unixPath() { return path.replace('\\', '/'); }
public String hashHex() {
StringBuilder sb = new StringBuilder();
for (byte b : hashBytes) sb.append(String.format("%02x", b & 0xFF));
return sb.toString();
}
}
public static final class ParsedManifest {
public final List<ManifestFile> allFiles;
public final long totalInstallSize;
ParsedManifest(List<ManifestFile> files) {
this.allFiles = files;
long total = 0;
for (ManifestFile f : files) total += f.size;
this.totalInstallSize = total;
}
}
private AmazonManifest() {}
public static ParsedManifest parse(byte[] data) throws IOException {
if (data == null || data.length < 4) throw new IOException("Manifest too short");
int headerSize = ByteBuffer.wrap(data, 0, 4).order(ByteOrder.BIG_ENDIAN).getInt();
if (headerSize < 0 || 4 + headerSize > data.length) throw new IOException("Invalid header size " + headerSize);
byte[] body = Arrays.copyOfRange(data, 4 + headerSize, data.length);
return parseManifest(decompress(body));
}
private static byte[] decompress(byte[] body) throws IOException {
if (body.length < 2) return body;
boolean isXz = (body[0] & 0xFF) == 0xFD && (body[1] & 0xFF) == 0x37;
try (InputStream in = isXz ? new XZInputStream(new ByteArrayInputStream(body), -1) : new LZMAInputStream(new ByteArrayInputStream(body), -1)) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[65536];
int n;
while ((n = in.read(buf)) >= 0) bos.write(buf, 0, n);
return bos.toByteArray();
}
}
private static ParsedManifest parseManifest(byte[] bytes) {
List<ManifestFile> files = new ArrayList<>();
ProtoReader r = new ProtoReader(bytes);
while (r.hasMore()) {
int tag = (int) r.readVarint();
if ((tag >>> 3) == 1 && (tag & 7) == 2) parsePackage(r.readBytes(), files); else r.skip(tag & 7);
}
return new ParsedManifest(files);
}
private static void parsePackage(byte[] bytes, List<ManifestFile> out) {
ProtoReader r = new ProtoReader(bytes);
while (r.hasMore()) {
int tag = (int) r.readVarint();
int field = tag >>> 3, wire = tag & 7;
if (field == 2 && wire == 2) { ManifestFile f = parseFile(r.readBytes()); if (f != null) out.add(f); }
else r.skip(wire);
}
}
private static ManifestFile parseFile(byte[] bytes) {
String path = "";
long size = 0L;
int hashAlgo = 0;
byte[] hashValue = new byte[0];
ProtoReader r = new ProtoReader(bytes);
while (r.hasMore()) {
int tag = (int) r.readVarint();
int field = tag >>> 3, wire = tag & 7;
if (field == 1 && wire == 2) path = r.readString();
else if (field == 3 && wire == 0) size = r.readVarint();
else if (field == 5 && wire == 2) {
ProtoReader hr = new ProtoReader(r.readBytes());
while (hr.hasMore()) {
int ht = (int) hr.readVarint();
int hf = ht >>> 3, hw = ht & 7;
if (hf == 1 && hw == 0) hashAlgo = (int) hr.readVarint();
else if (hf == 2 && hw == 2) hashValue = hr.readBytes();
else hr.skip(hw);
}
} else r.skip(wire);
}
if (path.isEmpty()) return null;
return new ManifestFile(path, size, hashAlgo, hashValue);
}
private static final class ProtoReader {
private final byte[] buf;
private int pos;
ProtoReader(byte[] buf) { this.buf = buf; }
boolean hasMore() { return pos < buf.length; }
long readVarint() {
long result = 0;
int shift = 0;
while (pos < buf.length) {
int b = buf[pos++] & 0xFF;
result |= (long) (b & 0x7F) << shift;
if ((b & 0x80) == 0) break;
shift += 7;
}
return result;
}
byte[] readBytes() {
int len = (int) readVarint();
if (len < 0 || pos + len > buf.length) return new byte[0];
byte[] out = Arrays.copyOfRange(buf, pos, pos + len);
pos += len;
return out;
}
String readString() { return new String(readBytes(), java.nio.charset.StandardCharsets.UTF_8); }
void skip(int wireType) {
switch (wireType) {
case 0: readVarint(); break;
case 1: pos += 8; break;
case 2: readBytes(); break;
case 5: pos += 4; break;
default: pos = buf.length; break;
}
}
}
}
@@ -0,0 +1,84 @@
// JNI symbols depend on this package path and class name (app/src/main/rust/stores/JNI.md).
package com.droiddeck.launcher.stores.amazon
import android.util.Log
import com.droiddeck.launcher.stores.StoresNative
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* The native Amazon file fetcher in `libdroiddeckstores.so`: one streamed GET per manifest file,
* SHA-256 checked, written as `<dest>.tmp` and renamed. The manager keeps manifest, auth, markers
* and post-install; [runBlocking] mirrors the Java loop's shape and polls the cancel probe.
*/
object AmazonNative {
const val TAG = "AmazonNative"
private const val CANCEL_POLL_MS = 100L
/** Callbacks from the engine; every method is called on a native thread. */
interface Listener {
/** Once up front with the resume-skipped credit, then after each committed file; [bytesDone] includes skipped files. */
fun onProgress(bytesDone: Long, bytesTotal: Long, filesDone: Long, filesTotal: Long)
/** One diagnostic line; the engine itself does not write to logcat. */
fun onLog(line: String)
/** Exactly once, when the run succeeds, fails or is cancelled. */
fun onComplete(success: Boolean, error: String, bytesWritten: Long)
}
fun interface CancelCheck { fun isCancelled(): Boolean }
class RunResult(@JvmField val success: Boolean, @JvmField val cancelled: Boolean, @JvmField val error: String, @JvmField val bytesWritten: Long)
@JvmStatic
fun isAvailable(): Boolean = StoresNative.available
/**
* Runs one download to completion. [planJson]: `[{relPath, url, size, sha256hex}]`, every
* manifest file (the engine skips complete ones itself). [maxWorkers] <= 0 = the engine's default.
*/
@JvmStatic
fun runBlocking(planJson: String, installDir: String, caBundlePath: String, maxWorkers: Int, processWorkers: Int, isCancelled: CancelCheck?, listener: Listener): RunResult {
if (!StoresNative.ensureLoaded()) return RunResult(false, false, "engine not built", 0L)
val latch = CountDownLatch(1)
var outcome: RunResult? = null
val bridge = object : Listener {
override fun onProgress(bytesDone: Long, bytesTotal: Long, filesDone: Long, filesTotal: Long) = listener.onProgress(bytesDone, bytesTotal, filesDone, filesTotal)
override fun onLog(line: String) = listener.onLog(line)
override fun onComplete(success: Boolean, error: String, bytesWritten: Long) {
outcome = RunResult(success, false, error, bytesWritten)
listener.onComplete(success, error, bytesWritten)
latch.countDown()
}
}
val handle = try {
nativeStart(planJson, installDir, caBundlePath, maxWorkers, processWorkers, bridge)
} catch (t: Throwable) {
Log.w(TAG, "nativeStart threw: ${t.javaClass.simpleName}: ${t.message}")
return RunResult(false, false, "nativeStart: ${t.javaClass.simpleName}", 0L)
}
if (handle == 0L) return outcome ?: RunResult(false, false, "native start failed", 0L)
var cancelSent = false
try {
while (!latch.await(CANCEL_POLL_MS, TimeUnit.MILLISECONDS)) {
if (!cancelSent && isCancelled?.isCancelled() == true) { nativeCancel(handle); cancelSent = true }
}
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
if (!cancelSent) { nativeCancel(handle); cancelSent = true }
try { latch.await(30, TimeUnit.SECONDS) } catch (_: InterruptedException) {}
} finally {
nativeRelease(handle)
}
val r = outcome ?: RunResult(false, cancelSent, "no completion", 0L)
return RunResult(r.success && !cancelSent, cancelSent, r.error, r.bytesWritten)
}
@JvmStatic
private external fun nativeStart(planJson: String, installDir: String, caBundlePath: String, maxWorkers: Int, processWorkers: Int, listener: Listener): Long
@JvmStatic
private external fun nativeCancel(handle: Long)
@JvmStatic
private external fun nativeRelease(handle: Long)
}
@@ -0,0 +1,53 @@
package com.droiddeck.launcher.stores.amazon;
import android.util.Base64;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.UUID;
/** The PKCE values Amazon's device sign-in takes, generated the way the Amazon Games launcher does. */
public final class AmazonPkce {
private static final String DEVICE_TYPE = "A2UMVHOX7UP4V7";
private AmazonPkce() {}
/** One per sign-in: a UUID as uppercase hex. */
public static String generateDeviceSerial() { return UUID.randomUUID().toString().replace("-", "").toUpperCase(); }
/** hex("serial#DEVICE_TYPE"). */
public static String generateClientId(String serial) {
byte[] bytes = (serial + "#" + DEVICE_TYPE).getBytes(StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
for (byte b : bytes) sb.append(String.format("%02x", b & 0xFF));
return sb.toString();
}
public static String generateCodeVerifier() {
byte[] random = new byte[32];
new SecureRandom().nextBytes(random);
return Base64.encodeToString(random, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);
}
public static String generateCodeChallenge(String verifier) {
try {
byte[] hash = MessageDigest.getInstance("SHA-256").digest(verifier.getBytes(StandardCharsets.UTF_8));
return Base64.encodeToString(hash, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);
} catch (Exception e) {
throw new RuntimeException("SHA-256 unavailable", e);
}
}
/** SHA-256 of the input as uppercase hex: the entitlements call's hardwareHash. */
public static String sha256Upper(String input) {
try {
byte[] hash = MessageDigest.getInstance("SHA-256").digest(input.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hash) sb.append(String.format("%02x", b & 0xFF));
return sb.toString().toUpperCase();
} catch (Exception e) {
throw new RuntimeException("SHA-256 unavailable", e);
}
}
}
@@ -0,0 +1,10 @@
package com.droiddeck.launcher.stores.amazon
import android.content.Context
import android.content.SharedPreferences
/** Amazon's own records that are not credentials: the library cache, posters, versions. Public for the Java clients. */
object AmazonPrefs {
@JvmStatic
fun get(context: Context): SharedPreferences = context.applicationContext.getSharedPreferences("stores.amazon", Context.MODE_PRIVATE)
}