diff --git a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonApiClient.java b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonApiClient.java index bfe7a617d2..7683217d91 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonApiClient.java +++ b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonApiClient.java @@ -25,13 +25,15 @@ 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"; + // As nile sends them: the session's User-Agent, and the launcher's own string under "UserAgent". + private static final String GAMING_USER_AGENT = "AGSLauncher/1.0.0"; + private static final String LAUNCHER_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. */ + /** The owned games, every page, one per productId; null when Amazon refused or could not be reached. */ public static List getEntitlements(String accessToken, String deviceSerial) { Map seen = new HashMap<>(); String nextToken = null; @@ -40,8 +42,9 @@ public final class AmazonApiClient { hardwareHash = AmazonPkce.sha256Upper(deviceSerial); } catch (Exception e) { Log.e(TAG, "hardware hash failed", e); - return new ArrayList<>(); + return null; } + boolean answered = false; do { try { JSONObject body = new JSONObject(); @@ -56,19 +59,22 @@ public final class AmazonApiClient { String resp = postGaming(ENTITLEMENTS_URL, "com.amazon.animusdistributionservice.entitlement.AnimusEntitlementsService.GetEntitlements", accessToken, body.toString()); if (resp == null) break; JSONObject json = new JSONObject(resp); + answered = true; JSONArray entitlements = json.optJSONArray("entitlements"); - if (entitlements == null) break; - for (int i = 0; i < entitlements.length(); i++) { + if (entitlements != null) 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); + // A JSON null reads as "null" through optString; the last page carries none. + nextToken = json.isNull("nextToken") ? null : json.optString("nextToken", ""); if (nextToken != null && nextToken.isEmpty()) nextToken = null; } catch (Exception e) { Log.e(TAG, "entitlements page failed: " + e.getClass().getSimpleName()); break; } } while (nextToken != null); + if (!answered) return null; + Log.i(TAG, "entitlements: " + seen.size()); return new ArrayList<>(seen.values()); } @@ -140,7 +146,9 @@ public final class AmazonApiClient { 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"); + JSONObject json = new JSONObject(resp); + JSONObject versions = json.optJSONObject("adgProductIdToVersionIdMap"); + if (versions == null) versions = json.optJSONObject("versionIds"); return versions == null ? null : versions.optString(productId, null); } catch (Exception e) { Log.e(TAG, "GetLiveVersionIds failed: " + e.getClass().getSimpleName()); @@ -165,13 +173,17 @@ public final class AmazonApiClient { conn.setRequestProperty("X-Amz-Target", target); conn.setRequestProperty("x-amzn-token", accessToken); conn.setRequestProperty("User-Agent", GAMING_USER_AGENT); + conn.setRequestProperty("UserAgent", LAUNCHER_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; } + if (code < 200 || code >= 300) { + Log.e(TAG, "HTTP " + code + " from " + StoreLog.redactUrl(urlStr) + ": " + (resp.length() > 200 ? resp.substring(0, 200) : resp)); + return null; + } return resp; } catch (Exception e) { Log.e(TAG, "POST failed: " + StoreLog.redactUrl(urlStr) + " (" + e.getClass().getSimpleName() + ")"); diff --git a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonAuthClient.java b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonAuthClient.java index 2cd0f5eec0..878f659ae1 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonAuthClient.java +++ b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonAuthClient.java @@ -39,6 +39,8 @@ public final class AmazonAuthClient { public String refreshToken; public long expiresIn; public String name; + /** The serial Amazon registered the device under; the entitlements call hashes this one. */ + public String deviceSerial; } private AmazonAuthClient() {} @@ -78,8 +80,12 @@ public final class AmazonAuthClient { 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; + JSONObject ext = success.optJSONObject("extensions"); + JSONObject customer = ext != null ? ext.optJSONObject("customer_info") : null; result.name = customer != null ? customer.optString("name", "") : ""; + JSONObject device = ext != null ? ext.optJSONObject("device_info") : null; + String registered = device != null ? device.optString("device_serial_number", "") : ""; + result.deviceSerial = registered.isEmpty() ? deviceSerial : registered; return result; } catch (Exception e) { Log.e(TAG, "registerDevice failed: " + e.getClass().getSimpleName()); diff --git a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonBackend.kt index 1523741a4d..9f16663a53 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonBackend.kt @@ -75,10 +75,9 @@ object AmazonBackend : StoreBackend { 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) - } + // Nothing public to fetch; the shelves follow the library sync, which StoresState.open starts + // alongside this. A second sync here only came back Busy and cleared the first one's status. + override fun loadShelves(context: Context, force: Boolean) {} override fun install(context: Context, item: CatalogItem, root: File) { val app = context.applicationContext @@ -119,7 +118,7 @@ object AmazonBackend : StoreBackend { 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() - for (kv in AmazonLaunchHelper.buildFuelEnv(game.entitlementId, game.productSku)) env[kv.substringBefore('=')] = kv.substringAfter('=') + for (kv in AmazonLaunchHelper.buildFuelEnv(game.entitlementId, game.productSku, com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, Store.AMAZON)?.takeIf { it != Store.AMAZON.label })) 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(), @@ -159,7 +158,7 @@ object AmazonBackend : StoreBackend { 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) + AmazonCredentialStore.save(activity, result.accessToken, result.refreshToken, result.deviceSerial ?: serial, clientId, System.currentTimeMillis() + result.expiresIn * 1000L, result.name) Log.i(TAG, "signed in") return null } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonCredentialStore.kt b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonCredentialStore.kt index 9b9873c2bf..95944375df 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonCredentialStore.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonCredentialStore.kt @@ -34,6 +34,16 @@ object AmazonCredentialStore { @JvmStatic fun isLoggedIn(context: Context): Boolean = load(context) != null + /** A fresh access token whatever the stored expiry says: for a call Amazon refused with the stored one. */ + @JvmStatic + fun refresh(context: Context): String? { + val creds = load(context) ?: return null + val result = AmazonAuthClient.refreshAccessToken(creds.refreshToken ?: return null) ?: return null + save(context, result.accessToken, creds.refreshToken, creds.deviceSerial, creds.clientId, System.currentTimeMillis() + result.expiresIn * 1000L, null) + Log.i(TAG, "token refreshed (forced)") + return result.accessToken + } + /** A valid access token, refreshed within five minutes of expiry; null when signed out or the refresh failed. */ @JvmStatic fun getValidAccessToken(context: Context): String? { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonLaunchHelper.java b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonLaunchHelper.java index 525b3c7a12..bc1bba6677 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonLaunchHelper.java +++ b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonLaunchHelper.java @@ -66,13 +66,13 @@ public final class AmazonLaunchHelper { } /** The FuelPump variables, as KEY=VALUE, for the game's environment. */ - public static String[] buildFuelEnv(String entitlementId, String productSku) { + public static String[] buildFuelEnv(String entitlementId, String productSku, String displayName) { 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", + "AMAZON_GAMES_FUEL_DISPLAY_NAME=" + (displayName == null || displayName.isEmpty() ? "Player" : displayName), }; } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonLibrary.kt b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonLibrary.kt index 401fd09cb6..197d6a8163 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonLibrary.kt @@ -73,8 +73,11 @@ object AmazonLibrary { val creds = AmazonCredentialStore.load(app) ?: return SyncResult.NotLoggedIn val token = AmazonCredentialStore.getValidAccessToken(app) ?: return SyncResult.Failed(StoresState.notSignedInLine(Store.AMAZON)) onStatus("Fetching game list…") + // Refused with the stored token (revoked, or an expiry read wrong): once more on a fresh one. 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) + ?: AmazonCredentialStore.refresh(app)?.let { AmazonApiClient.getEntitlements(it, creds.deviceSerial) } + if (all == null) return if (cachedList.isEmpty()) SyncResult.Failed("Amazon Games did not answer for your library: refresh, or sign in again") else SyncResult.Ok(cachedList) + if (all.isEmpty()) 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 }