mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 12:28:40 +00:00
feat: rewrite the Epic and Amazon store modules (#802)
Both store modules are rewritten from a protocol-level spec: new Rust engines behind a small JNI surface (nativeCall/nativeInstall) and thin Kotlin facades, with the launcher's own user agent. Epic: sign-in carries over, library, manifest download with byte-exact verification, assembly, uninstall, launch arguments, achievements. Amazon: sign-in carries over, library, manifest download with per-file hash checks, path checks, executable detection from fuel.json, uninstall. On-disk install layout is unchanged, so existing installs keep working. Store game pages now take controller focus on their lead hero action (Install, Uninstall, Pause, Resume, Get, Buy), fall back to Back, and keep D-pad focus inside the page while it covers the library.
This commit is contained in:
1 parent
a849556f3f
commit
7ad3c60efe
105 files changed
+10975
-13233
No files matched your search
@@ -25,22 +25,17 @@ object CloudSavePaths {
|
||||
}
|
||||
|
||||
fun epic(template: String, prefix: File, install: File, accountId: String, appName: String): File? {
|
||||
val norm = template.replace('\\', '/').trim().trimStart('/')
|
||||
val match = Regex("^\\{([^}]+)\\}").find(norm) ?: return null
|
||||
val parsed = com.droiddeck.launcher.stores.epic.EpicSaveTemplate.parse(template, accountId, appName) ?: return null
|
||||
val profile = profile(prefix)
|
||||
val (base, boundary) = when (match.groupValues[1].lowercase()) {
|
||||
"installdir" -> install to install
|
||||
"userprofile" -> profile to profile
|
||||
"userdir" -> File(profile, "Documents") to profile
|
||||
"usersavedgames" -> File(profile, "Saved Games") to profile
|
||||
"appdata", "localappdata" -> File(profile, "AppData/Local") to profile
|
||||
"roamingappdata" -> File(profile, "AppData/Roaming") to profile
|
||||
else -> return null
|
||||
val (base, boundary) = when (parsed.root) {
|
||||
com.droiddeck.launcher.stores.epic.EpicSaveTemplate.Root.INSTALL_DIR -> install to install
|
||||
com.droiddeck.launcher.stores.epic.EpicSaveTemplate.Root.USER_PROFILE -> profile to profile
|
||||
com.droiddeck.launcher.stores.epic.EpicSaveTemplate.Root.DOCUMENTS -> File(profile, "Documents") to profile
|
||||
com.droiddeck.launcher.stores.epic.EpicSaveTemplate.Root.SAVED_GAMES -> File(profile, "Saved Games") to profile
|
||||
com.droiddeck.launcher.stores.epic.EpicSaveTemplate.Root.LOCAL_APPDATA -> File(profile, "AppData/Local") to profile
|
||||
com.droiddeck.launcher.stores.epic.EpicSaveTemplate.Root.ROAMING_APPDATA -> File(profile, "AppData/Roaming") to profile
|
||||
}
|
||||
val rest = norm.substring(match.value.length)
|
||||
.replace("{epicid}", accountId, ignoreCase = true)
|
||||
.replace("{appname}", appName, ignoreCase = true)
|
||||
return walk(base, boundary, rest, fuzzy = true)
|
||||
return walk(base, boundary, parsed.rest, fuzzy = true)
|
||||
}
|
||||
|
||||
private fun walk(base: File, boundary: File, rest: String, fuzzy: Boolean): File? {
|
||||
|
||||
@@ -112,62 +112,10 @@ class GogCloud(private val userId: String, private val clientId: String, private
|
||||
}
|
||||
|
||||
class EpicCloud(private val accountId: String, private val appName: String, private val token: String) : CloudTransport {
|
||||
private val base = "https://datastorage-public-service-liveegs.live.use1a.on.epicgames.com/api/v1/access/egstore/savesync/$accountId/$appName/"
|
||||
private val ua = "EpicGamesLauncher/15.17.1-22692490"
|
||||
override fun list(): List<CloudFile> = com.droiddeck.launcher.stores.epic.EpicSaveSync.list(token, accountId, appName)
|
||||
|
||||
override fun list(): List<CloudFile> {
|
||||
val c = open(base, "GET", token, ua)
|
||||
val code = c.responseCode
|
||||
if (code == 404) { c.disconnect(); return emptyList() }
|
||||
if (code !in 200..299) { c.disconnect(); throw java.io.IOException("Epic cloud list HTTP $code") }
|
||||
val root = JSONObject(c.body().decodeToString().ifEmpty { "{}" })
|
||||
c.disconnect()
|
||||
val files = root.optJSONObject("files") ?: return emptyList()
|
||||
return files.keys().asSequence().mapNotNull { k ->
|
||||
val e = files.optJSONObject(k) ?: return@mapNotNull null
|
||||
CloudFile(strip(k), isoDate(e.optString("lastModified", null)), e.optString("hash", "").ifEmpty { null }, e.optString("readLink", "").ifEmpty { null })
|
||||
}.toList()
|
||||
}
|
||||
override fun get(file: CloudFile): Pair<ByteArray, Long> = com.droiddeck.launcher.stores.epic.EpicSaveSync.read(file)
|
||||
|
||||
private fun strip(key: String): String {
|
||||
val marker = "/$appName/"
|
||||
val i = key.indexOf(marker)
|
||||
if (i >= 0) return key.substring(i + marker.length)
|
||||
return key.removePrefix("$appName/")
|
||||
}
|
||||
|
||||
override fun get(file: CloudFile): Pair<ByteArray, Long> {
|
||||
val link = file.readLink ?: throw java.io.IOException("Epic cloud: no read link")
|
||||
val c = open(link, "GET", null, ua)
|
||||
if (c.responseCode !in 200..299) { val code = c.responseCode; c.disconnect(); throw java.io.IOException("Epic cloud get HTTP $code") }
|
||||
return c.body().also { c.disconnect() } to file.modifiedMs
|
||||
}
|
||||
|
||||
override fun put(files: Map<String, ByteArray>): Map<String, Long> {
|
||||
if (files.isEmpty()) return emptyMap()
|
||||
val c = open(base, "POST", token, ua)
|
||||
c.doOutput = true
|
||||
c.setRequestProperty("Content-Type", "application/json")
|
||||
val req = JSONObject().put("files", JSONArray(files.keys.toList())).toString().toByteArray()
|
||||
c.outputStream.use { it.write(req) }
|
||||
if (c.responseCode !in 200..299) { val code = c.responseCode; c.disconnect(); throw java.io.IOException("Epic cloud write links HTTP $code") }
|
||||
val links = JSONObject(c.body().decodeToString()).optJSONObject("files") ?: JSONObject()
|
||||
c.disconnect()
|
||||
val out = HashMap<String, Long>()
|
||||
for (k in links.keys()) {
|
||||
val link = links.optJSONObject(k)?.optString("writeLink", "")?.ifEmpty { null } ?: continue
|
||||
val name = strip(k)
|
||||
val data = files[name] ?: files[k] ?: continue
|
||||
val p = open(link, "PUT", null, ua)
|
||||
p.doOutput = true
|
||||
p.setRequestProperty("Content-Type", "application/octet-stream")
|
||||
p.setFixedLengthStreamingMode(data.size)
|
||||
p.outputStream.use { it.write(data) }
|
||||
val code = p.responseCode
|
||||
p.disconnect()
|
||||
if (code !in 200..299) throw java.io.IOException("Epic cloud put HTTP $code")
|
||||
out[name] = -1L
|
||||
}
|
||||
return out
|
||||
}
|
||||
override fun put(files: Map<String, ByteArray>): Map<String, Long> =
|
||||
com.droiddeck.launcher.stores.epic.EpicSaveSync.write(token, accountId, appName, files)
|
||||
}
|
||||
@@ -1,205 +0,0 @@
|
||||
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;
|
||||
|
||||
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 = "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() {}
|
||||
|
||||
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 null;
|
||||
}
|
||||
boolean answered = false;
|
||||
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);
|
||||
answered = true;
|
||||
JSONArray entitlements = json.optJSONArray("entitlements");
|
||||
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.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());
|
||||
}
|
||||
|
||||
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("pgCrownImageUrl", "");
|
||||
game.heroUrl = details.optString("backgroundUrl2", "");
|
||||
if (game.heroUrl.isEmpty()) game.heroUrl = details.optString("backgroundUrl1", "");
|
||||
if (game.heroUrl.isEmpty()) game.heroUrl = details.optString("pgCrownImageUrl", "");
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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 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());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
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("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) + ": " + (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() + ")");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
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,31 @@
|
||||
package com.droiddeck.launcher.stores.amazon
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
class GameDownloadSpec(@JvmField val downloadUrl: String, @JvmField val versionId: String)
|
||||
|
||||
object AmazonApiClient {
|
||||
@JvmStatic
|
||||
fun getGameDownload(accessToken: String, entitlementId: String): GameDownloadSpec? {
|
||||
val answer = AmazonNative.call(
|
||||
"download.lookup",
|
||||
JSONObject().put("accessToken", accessToken).put("entitlementId", entitlementId),
|
||||
) ?: return null
|
||||
if (answer.has("error")) return null
|
||||
val url = answer.optString("downloadUrl").ifEmpty { return null }
|
||||
return GameDownloadSpec(url, answer.optString("versionId"))
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun getBytes(url: String, accessToken: String?): ByteArray? {
|
||||
val request = JSONObject().put("url", url)
|
||||
if (accessToken != null) request.put("accessToken", accessToken)
|
||||
return AmazonNative.fetch("cdn.get", request)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun appendPath(baseUrl: String, segment: String): String {
|
||||
val q = baseUrl.indexOf('?')
|
||||
return if (q < 0) "$baseUrl/$segment" else baseUrl.substring(0, q) + "/" + segment + baseUrl.substring(q)
|
||||
}
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
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;
|
||||
|
||||
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;
|
||||
public String deviceSerial;
|
||||
}
|
||||
|
||||
private AmazonAuthClient() {}
|
||||
|
||||
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 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());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -2,155 +2,74 @@ 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
|
||||
import org.json.JSONObject
|
||||
|
||||
object AmazonBackend : StoreBackend {
|
||||
private const val TAG = "AmazonBackend"
|
||||
override val store: Store = Store.AMAZON
|
||||
|
||||
init { LoginFlows.amazonFlow = { LoginFlow() } }
|
||||
init {
|
||||
LoginFlows.amazonFlow = { AmazonLogin.create() }
|
||||
}
|
||||
|
||||
private fun engineMissing(): Boolean {
|
||||
if (AmazonNative.ready()) return false
|
||||
StoresState.logLine(AmazonNative.ENGINE_MISSING)
|
||||
StoresState.post { StoresState.problems[store] = AmazonNative.ENGINE_MISSING }
|
||||
return true
|
||||
}
|
||||
|
||||
override fun signIn(context: Context) {
|
||||
context.startActivity(Intent(context, StoreLoginActivity::class.java).putExtra(StoreLoginActivity.EXTRA_STORE, store.id).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
if (engineMissing()) return
|
||||
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()
|
||||
val app = context.applicationContext
|
||||
runCatching {
|
||||
val token = AmazonCredentialStore.load(app)?.accessToken
|
||||
if (!token.isNullOrEmpty()) {
|
||||
Thread({
|
||||
runCatching { AmazonNative.call("auth.deregister", JSONObject().put("accessToken", token)) }
|
||||
}, "amazon-deregister").start()
|
||||
}
|
||||
}
|
||||
runCatching { AmazonLibrary.forget(app) }
|
||||
}
|
||||
|
||||
override fun syncLibrary(context: Context, force: Boolean) {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
val cached = AmazonLibrary.cached(app)
|
||||
val quiet = cached.isNotEmpty() && !force
|
||||
StoresState.post {
|
||||
if (cached.isNotEmpty()) publish(app, cached)
|
||||
if (!quiet) StoresState.status[store] = app.getString(com.droiddeck.launcher.R.string.stores_sync_library)
|
||||
}
|
||||
val result = AmazonLibrary.sync(app, force) { line -> if (!quiet) 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] = StoresState.notSignedInLine(store)
|
||||
AmazonLibrary.SyncResult.Throttled -> publish(app, AmazonLibrary.cached(app))
|
||||
AmazonLibrary.SyncResult.Busy -> {}
|
||||
}
|
||||
}
|
||||
}, "amazon-sync").start()
|
||||
}
|
||||
|
||||
private fun publish(app: Context, games: List<AmazonGame>) {
|
||||
val items = games.map { AmazonLibrary.toCatalogItem(app, it) }
|
||||
StoresState.library[store] = com.droiddeck.launcher.stores.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.filter { it.id !in installed }, free = emptyList(), deals = emptyList(), whatsNew = emptyList())
|
||||
Thread({ AmazonLibrary.sync(app, force) }, "amazon-sync").start()
|
||||
}
|
||||
|
||||
override fun loadShelves(context: Context, force: Boolean) {}
|
||||
|
||||
override fun install(context: Context, item: CatalogItem, root: File) {
|
||||
override fun install(context: Context, item: CatalogItem, root: java.io.File) {
|
||||
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 ?: "" }
|
||||
val folder = StoreInstallRoot.folderFor(app, Store.AMAZON, game.productId, game.title, root)
|
||||
DownloadQueue.enqueue(app, DownloadEntry(store, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes, location = StoreInstallRoot.labelFor(app, folder))) { InstallJob(app, game, item, folder) }
|
||||
if (item.extra["entitlementId"].isNullOrEmpty()) {
|
||||
StoresState.logLine("amazon: \"${item.title}\" has no entitlement to download with")
|
||||
return
|
||||
}
|
||||
val folder = StoreInstallRoot.folderFor(app, Store.AMAZON, item.id, item.title, root)
|
||||
val entry = DownloadEntry(
|
||||
Store.AMAZON, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes,
|
||||
location = StoreInstallRoot.labelFor(app, folder),
|
||||
)
|
||||
DownloadQueue.enqueue(app, entry) { AmazonInstaller(app, item, folder) }
|
||||
}
|
||||
|
||||
override fun uninstall(context: Context, game: InstalledStoreGame) {}
|
||||
|
||||
private class InstallJob(val app: Context, val game: AmazonGame, val item: CatalogItem, val folder: File) : DownloadQueue.DownloadJob {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
handle.stage(DownloadStage.MANIFEST, app.getString(com.droiddeck.launcher.R.string.stores_sync_sign_in))
|
||||
val token = AmazonCredentialStore.getValidAccessToken(app) ?: throw AmazonDownloadManager.InstallException("Not signed in to Amazon Games")
|
||||
StoreInstalls.begin(folder, Store.AMAZON, game.productId, game.title, item.tallImageUrl ?: item.imageUrl, item.imageUrl)
|
||||
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) }
|
||||
override fun onSizes(downloadBytes: Long, diskBytes: Long) { handle.diskSize(diskBytes) }
|
||||
}) ?: return null
|
||||
if (cancelled.get()) return null
|
||||
handle.stage(DownloadStage.INSTALL, app.getString(com.droiddeck.launcher.R.string.stores_registering))
|
||||
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, 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(),
|
||||
cover = item.tallImageUrl ?: item.imageUrl, hero = item.imageUrl,
|
||||
extra = mapOf("entitlementId" to game.entitlementId, "sku" to game.productSku),
|
||||
)
|
||||
StoreInstalls.complete(app, folder, onStep = { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) }, sidecar = sidecar)
|
||||
return folder.path
|
||||
}
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
if (deleteFiles) StoreInstalls.discard(app, folder, emptyList())
|
||||
}
|
||||
}
|
||||
|
||||
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, result.deviceSerial ?: serial, clientId, System.currentTimeMillis() + result.expiresIn * 1000L, result.name)
|
||||
Log.i(TAG, "signed in")
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,50 +7,98 @@ import com.droiddeck.launcher.stores.StoreAccounts
|
||||
import org.json.JSONObject
|
||||
|
||||
object AmazonCredentialStore {
|
||||
private const val TAG = "AmazonAuth"
|
||||
private const val TAG = "AmazonCredentials"
|
||||
private const val REFRESH_MARGIN_MS = 5 * 60 * 1000L
|
||||
private val refreshLock = Any()
|
||||
|
||||
class Credentials(val accessToken: String, val refreshToken: String?, val deviceSerial: String, val clientId: String, val expiresAt: Long)
|
||||
const val ACCESS_TOKEN = "access_token"
|
||||
const val REFRESH_TOKEN = "refresh_token"
|
||||
const val DEVICE_SERIAL = "device_serial"
|
||||
const val CLIENT_ID = "client_id"
|
||||
const val EXPIRES_AT = "expires_at"
|
||||
const val DISPLAY_NAME = "display_name"
|
||||
|
||||
@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)
|
||||
class Account(
|
||||
val accessToken: String,
|
||||
val refreshToken: String,
|
||||
val deviceSerial: String,
|
||||
val clientId: String,
|
||||
val expiresAt: Long,
|
||||
val displayName: 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, ""),
|
||||
deviceSerial = o.optString(DEVICE_SERIAL, ""),
|
||||
clientId = o.optString(CLIENT_ID, ""),
|
||||
expiresAt = o.optLong(EXPIRES_AT, 0L),
|
||||
displayName = o.optString(DISPLAY_NAME, ""),
|
||||
)
|
||||
}
|
||||
|
||||
@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))
|
||||
}
|
||||
fun load(context: Context): Account? = StoreAccounts.read(context.applicationContext, Store.AMAZON)?.let(::fromJson)
|
||||
|
||||
@JvmStatic
|
||||
fun isLoggedIn(context: Context): Boolean = load(context) != null
|
||||
|
||||
@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
|
||||
internal fun saveSignIn(context: Context, answer: JSONObject) {
|
||||
val access = answer.optString(ACCESS_TOKEN, "")
|
||||
require(access.isNotEmpty()) { "no access token" }
|
||||
val record = JSONObject()
|
||||
.put(ACCESS_TOKEN, access)
|
||||
.put(DEVICE_SERIAL, answer.optString(DEVICE_SERIAL, ""))
|
||||
.put(CLIENT_ID, answer.optString(CLIENT_ID, ""))
|
||||
.put(EXPIRES_AT, answer.optLong(EXPIRES_AT, 0L))
|
||||
answer.optString(REFRESH_TOKEN, "").takeIf { it.isNotEmpty() }?.let { record.put(REFRESH_TOKEN, it) }
|
||||
answer.optString(DISPLAY_NAME, "").takeIf { it.isNotEmpty() }?.let { record.put(DISPLAY_NAME, it) }
|
||||
StoreAccounts.write(context.applicationContext, Store.AMAZON, record)
|
||||
}
|
||||
|
||||
private fun saveRefreshed(context: Context, before: Account, access: String, expiresAt: Long) {
|
||||
val app = context.applicationContext
|
||||
val record = StoreAccounts.read(app, Store.AMAZON) ?: return
|
||||
record.put(ACCESS_TOKEN, access)
|
||||
.put(DEVICE_SERIAL, before.deviceSerial)
|
||||
.put(CLIENT_ID, before.clientId)
|
||||
.put(EXPIRES_AT, expiresAt)
|
||||
StoreAccounts.write(app, Store.AMAZON, record)
|
||||
}
|
||||
|
||||
private fun fresh(a: Account): Boolean =
|
||||
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 answer = AmazonNative.call("auth.refresh", JSONObject().put("refreshToken", a.refreshToken))
|
||||
val access = answer?.takeIf { !it.has("error") }?.optString(ACCESS_TOKEN, "").orEmpty()
|
||||
if (access.isEmpty()) {
|
||||
Log.w(TAG, "token refresh failed: ${answer?.optString("error").orEmpty().ifEmpty { "no answer" }}")
|
||||
return null
|
||||
}
|
||||
val expiresAt = answer!!.optLong(EXPIRES_AT, System.currentTimeMillis() + 3_600_000L)
|
||||
saveRefreshed(context, a, access, expiresAt)
|
||||
return access
|
||||
}
|
||||
|
||||
@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")
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
fun refreshNow(context: Context, staleToken: String?): String? {
|
||||
synchronized(refreshLock) {
|
||||
val current = load(context) ?: return null
|
||||
if (staleToken != null && current.accessToken != staleToken) return current.accessToken
|
||||
return refreshLocked(context, current)
|
||||
}
|
||||
return creds.accessToken
|
||||
}
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
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;
|
||||
|
||||
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) {}
|
||||
default void onSizes(long downloadBytes, long diskBytes) {}
|
||||
}
|
||||
|
||||
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() {}
|
||||
|
||||
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 remainingBytes = remainingInstallBytes(manifest.allFiles, installDir);
|
||||
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installDir);
|
||||
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(remainingBytes, usable))
|
||||
throw new InstallException("Not enough free space: need " + fmt(remainingBytes) + ", only " + fmt(usable) + " free");
|
||||
cb.onSizes(manifest.totalInstallSize, manifest.totalInstallSize);
|
||||
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, com.droiddeck.launcher.stores.download.DownloadQueue.workerFactory("amazon-dl"));
|
||||
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() : ""));
|
||||
}
|
||||
}
|
||||
|
||||
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 (fileComplete(file, destFile)) { 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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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(); }
|
||||
|
||||
static long remainingInstallBytes(List<AmazonManifest.ManifestFile> files, File installDir) {
|
||||
long remaining = 0;
|
||||
for (AmazonManifest.ManifestFile file : files) {
|
||||
if (!fileComplete(file, new File(installDir, file.unixPath()))) remaining += file.size;
|
||||
}
|
||||
return remaining;
|
||||
}
|
||||
|
||||
private static boolean fileComplete(AmazonManifest.ManifestFile file, File output) {
|
||||
if (!output.isFile() || output.length() != file.size) return false;
|
||||
if (file.hashAlgorithm != 0 || file.hashBytes.length == 0) return true;
|
||||
try { return Arrays.equals(sha256(output), file.hashBytes); }
|
||||
catch (Exception e) { return false; }
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.droiddeck.launcher.stores.amazon;
|
||||
|
||||
public class AmazonGame {
|
||||
public String productId = "";
|
||||
public String entitlementId = "";
|
||||
public String title = "";
|
||||
public String artUrl = "";
|
||||
public String heroUrl = "";
|
||||
public String developer = "";
|
||||
public String publisher = "";
|
||||
public String productSku = "";
|
||||
public String versionId = "";
|
||||
public boolean isDLC = false;
|
||||
public String parentProductId = "";
|
||||
|
||||
public String shortId() {
|
||||
int dot = productId.lastIndexOf('.');
|
||||
return (dot >= 0 && dot < productId.length() - 1) ? productId.substring(dot + 1) : productId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.droiddeck.launcher.stores.amazon
|
||||
|
||||
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.StoreAccounts
|
||||
import com.droiddeck.launcher.stores.StoreExe
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import com.droiddeck.launcher.stores.download.StoreDownloadTier
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
internal class AmazonInstaller(
|
||||
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))
|
||||
val token = AmazonCredentialStore.getValidAccessToken(app) ?: throw IllegalStateException("Not signed in to Amazon Games")
|
||||
val entitlementId = item.extra["entitlementId"].orEmpty()
|
||||
val sku = item.extra["sku"].orEmpty()
|
||||
val cover = item.tallImageUrl ?: item.imageUrl
|
||||
StoreInstalls.begin(folder, Store.AMAZON, item.id, item.title, cover, item.imageUrl)
|
||||
if (cancelled.get()) return null
|
||||
|
||||
val tier = StoreDownloadTier.current(app)
|
||||
handle.log("amazon: \"${item.title}\" tier=${tier.id} window=${tier.networkWindow} process_workers=${tier.processWorkers}")
|
||||
val request = JSONObject()
|
||||
.put("accessToken", token)
|
||||
.put("entitlementId", entitlementId)
|
||||
.put("gameDir", folder.absolutePath)
|
||||
.put("maxWorkers", tier.networkWindow.coerceIn(1, 128))
|
||||
.put("processWorkers", tier.processWorkers)
|
||||
.put("caBundle", "")
|
||||
|
||||
val shown = AtomicLong(-1)
|
||||
val downloading = AtomicBoolean(false)
|
||||
val prefs = AmazonPrefs.get(app)
|
||||
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("amazon: $line") }
|
||||
|
||||
override fun beforeReplace(): Boolean = try {
|
||||
StoreInstalls.markUpdating(folder)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
handle.log("amazon: 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 = AmazonNative.install(request, listener, cancelled)
|
||||
if (outcome.cancelled || cancelled.get() && !outcome.success) return null
|
||||
if (!outcome.success) throw IllegalStateException(outcome.error.ifEmpty { "The Amazon install failed" })
|
||||
val result = outcome.result ?: JSONObject()
|
||||
|
||||
handle.stage(DownloadStage.INSTALL, "Finishing…")
|
||||
val versionId = result.optString("versionId")
|
||||
val total = result.optLong("totalBytes", 0L)
|
||||
prefs.edit().apply {
|
||||
if (total > 0) putLong("size_${item.id}", total)
|
||||
putString("version_${item.id}", versionId)
|
||||
}.apply()
|
||||
|
||||
handle.stage(DownloadStage.INSTALL, app.getString(R.string.stores_registering))
|
||||
val spec = AmazonNative.call("launch.spec", JSONObject().put("gameDir", folder.absolutePath).put("title", item.title))
|
||||
?: throw IllegalStateException(AmazonNative.ENGINE_MISSING)
|
||||
spec.optString("warning").takeIf { it.isNotEmpty() && it != "null" }?.let { handle.log("amazon: $it") }
|
||||
var exe = spec.optString("exe")
|
||||
if (exe.isEmpty()) exe = StoreExe.pick(folder, null, item.title)
|
||||
if (exe.isEmpty()) {
|
||||
handle.log("amazon: no exe found in ${folder.name}; pick one in Steam settings › Added games")
|
||||
exe = "game.exe"
|
||||
} else {
|
||||
handle.log("amazon: exe=$exe (${spec.optString("source").ifEmpty { "picker" }})")
|
||||
}
|
||||
val argList = spec.optJSONArray("args")
|
||||
val args = List(argList?.length() ?: 0) { argList!!.optString(it) }.filter { it.isNotEmpty() }
|
||||
|
||||
val display = StoreAccounts.signedInAs(app, Store.AMAZON).orEmpty()
|
||||
val envAnswer = AmazonNative.call(
|
||||
"launch.env",
|
||||
JSONObject().put("entitlementId", entitlementId).put("sku", sku).put("displayName", display),
|
||||
)?.optJSONArray("env") ?: throw IllegalStateException(AmazonNative.ENGINE_MISSING)
|
||||
val env = LinkedHashMap<String, String>()
|
||||
for (i in 0 until envAnswer.length()) {
|
||||
val pair = envAnswer.optJSONArray(i) ?: continue
|
||||
env[pair.optString(0)] = pair.optString(1)
|
||||
}
|
||||
|
||||
val sidecar = StoreGameSidecar(
|
||||
Store.AMAZON, item.id, item.title, exe = exe, args = args, env = env,
|
||||
installVersion = versionId, installedAt = System.currentTimeMillis(),
|
||||
cover = cover, hero = item.imageUrl,
|
||||
extra = mapOf("entitlementId" to entitlementId, "sku" to sku),
|
||||
)
|
||||
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())
|
||||
}
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
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;
|
||||
|
||||
public final class AmazonLaunchHelper {
|
||||
|
||||
private static final String TAG = "AmazonLaunch";
|
||||
|
||||
public static final class LaunchSpec {
|
||||
public String exeRelative = "";
|
||||
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;
|
||||
}
|
||||
|
||||
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=" + (displayName == null || displayName.isEmpty() ? "Player" : displayName),
|
||||
};
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,125 +1,208 @@
|
||||
package com.droiddeck.launcher.stores.amazon
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.util.Log
|
||||
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.Callable
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
data class AmazonGame(
|
||||
val productId: String,
|
||||
val entitlementId: String,
|
||||
val title: String,
|
||||
val artUrl: String = "",
|
||||
val heroUrl: String = "",
|
||||
val developer: String = "",
|
||||
val publisher: String = "",
|
||||
val productSku: String = "",
|
||||
val versionId: String = "",
|
||||
)
|
||||
|
||||
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 = 6L * 60L * 60L * 1000L
|
||||
private const val POSTER_BUDGET = 40
|
||||
const val KEY_CACHE = "library_cache"
|
||||
const val KEY_SYNCED_AT = "library_synced_at"
|
||||
private const val THROTTLE_MS = 6 * 60 * 60 * 1000L
|
||||
private const val POSTERS_PER_SYNC = 40
|
||||
private const val POSTER_THREADS = 4
|
||||
private const val STORE_URL = "https://gaming.amazon.com/home"
|
||||
|
||||
private val syncing = AtomicBoolean(false)
|
||||
private val running = AtomicBoolean(false)
|
||||
private val store = Store.AMAZON
|
||||
|
||||
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 toCacheJson(games: List<AmazonGame>): String = JSONArray().apply {
|
||||
for (g in games) 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),
|
||||
)
|
||||
}.toString()
|
||||
|
||||
fun fromCacheJson(text: String?): List<AmazonGame> {
|
||||
if (text.isNullOrBlank()) return emptyList()
|
||||
val array = runCatching { JSONArray(text) }.getOrNull() ?: return emptyList()
|
||||
val games = (0 until array.length()).mapNotNull { array.optJSONObject(it) }.mapNotNull { o ->
|
||||
AmazonGame(
|
||||
productId = o.optString("productId", "").ifEmpty { return@mapNotNull null },
|
||||
entitlementId = o.optString("entitlementId", ""),
|
||||
title = o.optString("title", ""),
|
||||
artUrl = o.optString("artUrl", ""),
|
||||
heroUrl = o.optString("heroUrl", ""),
|
||||
developer = o.optString("developer", ""),
|
||||
publisher = o.optString("publisher", ""),
|
||||
productSku = o.optString("productSku", ""),
|
||||
versionId = o.optString("versionId", ""),
|
||||
)
|
||||
}
|
||||
return tidy(games)
|
||||
}
|
||||
|
||||
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())
|
||||
private fun tidy(games: List<AmazonGame>): List<AmazonGame> =
|
||||
games.distinctBy { it.productId }.sortedBy { it.title.lowercase() }
|
||||
|
||||
fun cached(context: Context): List<AmazonGame> = fromCacheJson(AmazonPrefs.get(context).getString(KEY_CACHE, null))
|
||||
|
||||
fun forget(context: Context) {
|
||||
AmazonPrefs.get(context).edit().remove(KEY_CACHE).remove(KEY_SYNCED_AT).apply()
|
||||
}
|
||||
|
||||
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 toCatalogItem(context: Context, game: AmazonGame): CatalogItem {
|
||||
val prefs = AmazonPrefs.get(context)
|
||||
val poster = prefs.getString("vcover_${game.productId}", null)?.takeIf { it.isNotBlank() }
|
||||
val art = game.artUrl.ifEmpty { null }
|
||||
val hero = game.heroUrl.ifEmpty { null }
|
||||
val tags = listOf(game.developer, game.publisher.takeIf { it != game.developer }.orEmpty())
|
||||
.filter { it.isNotBlank() }
|
||||
.joinToString(", ")
|
||||
return CatalogItem(
|
||||
store = store,
|
||||
id = game.productId,
|
||||
title = game.title.ifBlank { game.productId.substringAfterLast('.') },
|
||||
imageUrl = hero ?: art,
|
||||
tallImageUrl = poster ?: art ?: hero,
|
||||
tags = tags,
|
||||
developer = game.developer,
|
||||
owned = true,
|
||||
sizeBytes = prefs.getLong("size_${game.productId}", 0L).takeIf { it > 0 } ?: 0L,
|
||||
storeUrl = STORE_URL,
|
||||
extra = mapOf("entitlementId" to game.entitlementId, "sku" to game.productSku, "version" to ""),
|
||||
)
|
||||
}
|
||||
|
||||
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(app, p, cachedList, onStatus)
|
||||
return SyncResult.Throttled
|
||||
}
|
||||
onStatus(app.getString(R.string.stores_sync_sign_in))
|
||||
val creds = AmazonCredentialStore.load(app) ?: return SyncResult.NotLoggedIn
|
||||
val token = AmazonCredentialStore.getValidAccessToken(app) ?: return SyncResult.Failed(StoresState.notSignedInLine(Store.AMAZON))
|
||||
onStatus(app.getString(R.string.stores_sync_game_list))
|
||||
val all = AmazonApiClient.getEntitlements(token, creds.deviceSerial)
|
||||
?: AmazonCredentialStore.refresh(app)?.let { AmazonApiClient.getEntitlements(it, creds.deviceSerial) }
|
||||
if (all == null) return if (cachedList.isEmpty()) SyncResult.Failed(app.getString(R.string.stores_sync_amazon_no_answer)) else SyncResult.Ok(cachedList)
|
||||
if (all.isEmpty()) return if (cachedList.isEmpty()) SyncResult.Failed(app.getString(R.string.stores_sync_no_games, Store.AMAZON.label)) 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(app, 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 ?: context.getString(R.string.stores_sync_failed))
|
||||
} finally {
|
||||
syncing.set(false)
|
||||
private fun publish(app: Context, games: List<AmazonGame>) {
|
||||
val items = games.map { toCatalogItem(app, it) }
|
||||
StoresState.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 })
|
||||
}
|
||||
}
|
||||
|
||||
private fun backfillPosters(app: Context, 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(app.getString(R.string.stores_sync_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
|
||||
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, "version" to (g.versionId ?: "")),
|
||||
private fun gameFrom(o: JSONObject, before: AmazonGame?): AmazonGame = AmazonGame(
|
||||
productId = o.optString("productId"),
|
||||
entitlementId = o.optString("entitlementId"),
|
||||
title = o.optString("title"),
|
||||
artUrl = o.optString("art"),
|
||||
heroUrl = o.optString("hero"),
|
||||
developer = o.optString("developer"),
|
||||
publisher = o.optString("publisher"),
|
||||
productSku = o.optString("sku"),
|
||||
versionId = before?.versionId.orEmpty(),
|
||||
)
|
||||
|
||||
private fun backfillPosters(app: Context, games: List<AmazonGame>) {
|
||||
val prefs = AmazonPrefs.get(app)
|
||||
val todo = games.filter { !prefs.contains("vcover_${it.productId}") }.take(POSTERS_PER_SYNC)
|
||||
if (todo.isEmpty()) return
|
||||
val pool = Executors.newFixedThreadPool(POSTER_THREADS)
|
||||
try {
|
||||
for (g in todo) pool.execute {
|
||||
val poster = runCatching { StoreNet.sgdbPoster(g.title) }.getOrDefault("")
|
||||
prefs.edit().putString("vcover_${g.productId}", poster).apply()
|
||||
}
|
||||
} finally {
|
||||
pool.shutdown()
|
||||
pool.awaitTermination(5, TimeUnit.MINUTES)
|
||||
}
|
||||
}
|
||||
|
||||
private fun entitlements(token: String, serial: String): JSONObject? =
|
||||
AmazonNative.call("library.entitlements", JSONObject().put("accessToken", token).put("deviceSerial", serial))
|
||||
|
||||
private fun failed(answer: JSONObject?): Boolean = answer == null || answer.has("error")
|
||||
|
||||
fun sync(context: Context, force: Boolean) {
|
||||
if (!running.compareAndSet(false, true)) return
|
||||
val app = context.applicationContext
|
||||
val prefs = AmazonPrefs.get(app)
|
||||
val cache = cached(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)
|
||||
if (!AmazonNative.ready()) return problem(AmazonNative.ENGINE_MISSING)
|
||||
val syncedAt = prefs.getLong(KEY_SYNCED_AT, 0L)
|
||||
if (!force && cache.isNotEmpty() && System.currentTimeMillis() - syncedAt in 0 until THROTTLE_MS) {
|
||||
backfillPosters(app, cache)
|
||||
publish(app, cache)
|
||||
return problem(null)
|
||||
}
|
||||
|
||||
status(R.string.stores_sync_sign_in)
|
||||
val account = AmazonCredentialStore.load(app) ?: return problem(StoresState.notSignedInLine(store))
|
||||
val token = AmazonCredentialStore.getValidAccessToken(app) ?: return problem(StoresState.notSignedInLine(store))
|
||||
status(R.string.stores_sync_game_list)
|
||||
var answer = entitlements(token, account.deviceSerial)
|
||||
if (failed(answer)) {
|
||||
StoresState.logLine("amazon: library call failed (${answer?.optString("error").orEmpty().ifEmpty { "no answer" }}); refreshing the session")
|
||||
AmazonCredentialStore.refreshNow(app, token)?.let { answer = entitlements(it, account.deviceSerial) }
|
||||
}
|
||||
val result = answer
|
||||
when {
|
||||
result != null && result.optBoolean("signIn", false) -> return problem(StoresState.notSignedInLine(store))
|
||||
failed(result) -> {
|
||||
StoresState.logLine("amazon: library sync failed: ${result?.optString("error").orEmpty().ifEmpty { "no answer" }}")
|
||||
return problem(if (cache.isEmpty()) app.getString(R.string.stores_sync_amazon_no_answer) else null)
|
||||
}
|
||||
}
|
||||
val list = result!!.optJSONArray("games") ?: JSONArray()
|
||||
if (list.length() == 0) {
|
||||
return problem(if (cache.isEmpty()) app.getString(R.string.stores_sync_no_games, store.label) else null)
|
||||
}
|
||||
val before = cache.associateBy { it.productId }
|
||||
val games = tidy(
|
||||
(0 until list.length()).mapNotNull { list.optJSONObject(it) }
|
||||
.filter { it.optString("productId").isNotEmpty() }
|
||||
.map { gameFrom(it, before[it.optString("productId")]) },
|
||||
)
|
||||
prefs.edit().putString(KEY_CACHE, toCacheJson(games)).putLong(KEY_SYNCED_AT, System.currentTimeMillis()).apply()
|
||||
StoresState.logLine("amazon: library has ${games.size} games (${result.optInt("total", games.size)} entitlements)")
|
||||
status(R.string.stores_sync_cover_art)
|
||||
backfillPosters(app, games)
|
||||
publish(app, games)
|
||||
problem(null)
|
||||
} catch (e: Exception) {
|
||||
problem(e.message ?: app.getString(R.string.stores_sync_failed))
|
||||
} finally {
|
||||
running.set(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.droiddeck.launcher.stores.amazon
|
||||
|
||||
import android.util.Log
|
||||
import android.webkit.WebView
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.StoreLoginActivity
|
||||
import org.json.JSONObject
|
||||
|
||||
internal class AmazonLogin private constructor(
|
||||
override val startUrl: String,
|
||||
override val userAgent: String,
|
||||
private val marker: String,
|
||||
private val serial: String,
|
||||
private val clientId: String,
|
||||
private val verifier: String,
|
||||
) : StoreLoginActivity.Flow {
|
||||
override fun isRedirect(url: String): Boolean = url.contains(marker)
|
||||
|
||||
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? {
|
||||
val answer = AmazonNative.call(
|
||||
"auth.register",
|
||||
JSONObject().put("url", url).put("serial", serial).put("clientId", clientId).put("verifier", verifier),
|
||||
)
|
||||
if (answer != null && answer.optBoolean("noCode", false)) {
|
||||
Log.w(TAG, "the return URL carried no authorization code")
|
||||
return activity.getString(R.string.stores_login_error_verification)
|
||||
}
|
||||
if (answer == null || answer.has("error")) {
|
||||
Log.w(TAG, "registration failed: ${answer?.optString("error").orEmpty().ifEmpty { "no answer" }}")
|
||||
return activity.getString(R.string.stores_login_error_generic)
|
||||
}
|
||||
return try {
|
||||
AmazonCredentialStore.saveSignIn(activity, answer)
|
||||
null
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "saving the sign-in failed: ${e.javaClass.simpleName}")
|
||||
activity.getString(R.string.stores_login_error_generic)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AmazonLogin"
|
||||
|
||||
fun create(): StoreLoginActivity.Flow? {
|
||||
val start = AmazonNative.call("auth.start") ?: return null
|
||||
if (start.has("error")) return null
|
||||
return AmazonLogin(
|
||||
startUrl = start.optString("startUrl").ifEmpty { return null },
|
||||
userAgent = start.optString("userAgent"),
|
||||
marker = start.optString("redirectMarker").ifEmpty { return null },
|
||||
serial = start.optString("serial"),
|
||||
clientId = start.optString("clientId"),
|
||||
verifier = start.optString("verifier"),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
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;
|
||||
|
||||
public final class AmazonManifest {
|
||||
|
||||
public static final class ManifestFile {
|
||||
public final String path;
|
||||
public final long size;
|
||||
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,15 @@
|
||||
package com.droiddeck.launcher.stores.amazon
|
||||
|
||||
import java.io.IOException
|
||||
|
||||
class ParsedManifest(@JvmField val totalInstallSize: Long, @JvmField val fileCount: Int)
|
||||
|
||||
object AmazonManifest {
|
||||
@JvmStatic
|
||||
@Throws(IOException::class)
|
||||
fun parse(data: ByteArray): ParsedManifest {
|
||||
val answer = AmazonNative.inspect(data) ?: throw IOException(AmazonNative.ENGINE_MISSING)
|
||||
if (answer.has("error")) throw IOException(answer.optString("error"))
|
||||
return ParsedManifest(answer.optLong("totalBytes", 0L), answer.optInt("files", 0))
|
||||
}
|
||||
}
|
||||
@@ -1,70 +1,119 @@
|
||||
package com.droiddeck.launcher.stores.amazon
|
||||
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import com.droiddeck.launcher.stores.StoresNative
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
object AmazonNative {
|
||||
const val TAG = "AmazonNative"
|
||||
private const val CANCEL_POLL_MS = 100L
|
||||
private const val TAG = "AmazonNative"
|
||||
private const val CANCEL_POLL_MS = 250L
|
||||
|
||||
interface Listener {
|
||||
fun onProgress(bytesDone: Long, bytesTotal: Long, filesDone: Long, filesTotal: Long)
|
||||
fun onLog(line: String)
|
||||
fun onComplete(success: Boolean, error: String, bytesWritten: Long)
|
||||
const val ENGINE_MISSING = "Amazon Games: the store engine is not available"
|
||||
|
||||
@Volatile private var configured = false
|
||||
|
||||
fun ready(): Boolean {
|
||||
if (!StoresNative.ensureLoaded()) return false
|
||||
if (!configured) synchronized(this) {
|
||||
if (!configured) {
|
||||
runCatching { nativeConfigure(BuildConfig.VERSION_NAME) }
|
||||
.onFailure { Log.w(TAG, "configure: ${it.javaClass.simpleName}") }
|
||||
configured = true
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
fun interface CancelCheck { fun isCancelled(): Boolean }
|
||||
fun call(op: String, request: JSONObject = 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()
|
||||
}
|
||||
|
||||
class RunResult(@JvmField val success: Boolean, @JvmField val cancelled: Boolean, @JvmField val error: String, @JvmField val bytesWritten: Long)
|
||||
fun fetch(op: String, request: JSONObject): ByteArray? {
|
||||
if (!ready()) return null
|
||||
return try {
|
||||
nativeFetch(op, request.toString())
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "$op: ${t.javaClass.simpleName}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun isAvailable(): Boolean = StoresNative.available
|
||||
fun inspect(manifest: ByteArray, request: JSONObject = JSONObject()): JSONObject? {
|
||||
if (!ready()) return null
|
||||
val text = try {
|
||||
nativeInspect(manifest, request.toString())
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "inspect: ${t.javaClass.simpleName}")
|
||||
null
|
||||
} ?: return null
|
||||
return runCatching { JSONObject(text) }.getOrNull()
|
||||
}
|
||||
|
||||
@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()
|
||||
interface InstallListener {
|
||||
fun onStatus(text: String)
|
||||
fun onCheck(doneBytes: Long, totalBytes: Long, files: Int, filesTotal: Int)
|
||||
fun onSizes(pendingBytes: Long, totalBytes: Long)
|
||||
fun onProgress(done: Long, total: Long, files: Int, filesTotal: Int)
|
||||
fun onLog(line: String)
|
||||
fun beforeReplace(): Boolean
|
||||
fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String)
|
||||
}
|
||||
|
||||
class InstallOutcome(val success: Boolean, val cancelled: Boolean, val error: String, val result: JSONObject?)
|
||||
|
||||
fun install(request: JSONObject, events: InstallListener, cancelled: AtomicBoolean): InstallOutcome {
|
||||
if (!ready()) return InstallOutcome(false, false, ENGINE_MISSING, null)
|
||||
val done = CountDownLatch(1)
|
||||
val holder = arrayOfNulls<InstallOutcome>(1)
|
||||
val bridge = object : InstallListener by events {
|
||||
override fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String) {
|
||||
holder[0] = InstallOutcome(success, cancelled, error, result.takeIf { it.isNotEmpty() }?.let { runCatching { JSONObject(it) }.getOrNull() })
|
||||
done.countDown()
|
||||
}
|
||||
}
|
||||
val handle = try {
|
||||
nativeStart(planJson, installDir, caBundlePath, maxWorkers, processWorkers, bridge)
|
||||
nativeInstall(request.toString(), bridge)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "nativeStart threw: ${t.javaClass.simpleName}: ${t.message}")
|
||||
return RunResult(false, false, "nativeStart: ${t.javaClass.simpleName}", 0L)
|
||||
return InstallOutcome(false, false, "The Amazon install could not start: ${t.javaClass.simpleName}", null)
|
||||
}
|
||||
if (handle == 0L) return outcome ?: RunResult(false, false, "native start failed", 0L)
|
||||
var cancelSent = false
|
||||
if (handle == 0L) return holder[0] ?: InstallOutcome(false, false, "The Amazon install could not start", null)
|
||||
try {
|
||||
while (!latch.await(CANCEL_POLL_MS, TimeUnit.MILLISECONDS)) {
|
||||
if (!cancelSent && isCancelled?.isCancelled() == true) { nativeCancel(handle); cancelSent = true }
|
||||
var forwarded = false
|
||||
while (true) {
|
||||
val finished = try {
|
||||
done.await(CANCEL_POLL_MS, TimeUnit.MILLISECONDS)
|
||||
} catch (e: InterruptedException) {
|
||||
cancelled.set(true)
|
||||
false
|
||||
}
|
||||
if (finished) break
|
||||
if (!forwarded && cancelled.get()) {
|
||||
nativeCancel(handle)
|
||||
forwarded = 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)
|
||||
return holder[0] ?: InstallOutcome(false, false, "The Amazon install ended without a result", null)
|
||||
}
|
||||
|
||||
@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)
|
||||
@JvmStatic private external fun nativeConfigure(appVersion: String)
|
||||
@JvmStatic private external fun nativeCall(op: String, request: String): String?
|
||||
@JvmStatic private external fun nativeFetch(op: String, request: String): ByteArray?
|
||||
@JvmStatic private external fun nativeInspect(manifest: ByteArray, request: String): String?
|
||||
@JvmStatic private external fun nativeInstall(request: String, listener: InstallListener): Long
|
||||
@JvmStatic private external fun nativeCancel(handle: Long)
|
||||
@JvmStatic private external fun nativeRelease(handle: Long)
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
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;
|
||||
|
||||
public final class AmazonPkce {
|
||||
private static final String DEVICE_TYPE = "A2UMVHOX7UP4V7";
|
||||
|
||||
private AmazonPkce() {}
|
||||
|
||||
public static String generateDeviceSerial() { return UUID.randomUUID().toString().replace("-", "").toUpperCase(); }
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
|
||||
object AmazonPrefs {
|
||||
const val FILE = "stores.amazon"
|
||||
|
||||
@JvmStatic
|
||||
fun get(context: Context): SharedPreferences = context.applicationContext.getSharedPreferences("stores.amazon", Context.MODE_PRIVATE)
|
||||
fun get(context: Context): SharedPreferences = context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)
|
||||
}
|
||||
@@ -3,87 +3,31 @@ package com.droiddeck.launcher.stores.epic
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreAchievements
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
import org.json.JSONObject
|
||||
|
||||
object EpicAchievements : StoreAchievements(Store.EPIC.id, Store.EPIC.shortLabel) {
|
||||
private const val GRAPHQL = "https://launcher.store.epicgames.com/graphql"
|
||||
private const val USER_AGENT = "EpicGamesLauncher/14.0.8-22004686+++Portal+Release-Live"
|
||||
|
||||
override fun request(context: Context, game: Game): Result {
|
||||
val namespace = game.extra["namespace"].orEmpty()
|
||||
if (namespace.isEmpty()) return Result.Failed(Reason.NO_SERVICE)
|
||||
val namespace = game.extra["namespace"].orEmpty().ifEmpty { return Result.Failed(Reason.NO_SERVICE) }
|
||||
val token = EpicCredentialStore.getValidAccessToken(context) ?: return Result.Failed(Reason.SIGNED_OUT)
|
||||
val account = EpicCredentialStore.load(context)?.accountId.orEmpty()
|
||||
val defs = query(token, GAME_ACHIEVEMENTS, JSONObject().put("sandboxId", namespace).put("locale", locale()))
|
||||
?: return Result.Failed(Reason.UNREACHABLE)
|
||||
val list = defs.optJSONObject("data")?.optJSONObject("Achievement")?.optJSONObject("productAchievementsRecordBySandbox")
|
||||
?.optJSONArray("achievements") ?: return Result.Found(emptyList())
|
||||
val unlocked = if (account.isEmpty()) emptyMap() else unlockTimes(token, account, namespace)
|
||||
val out = ArrayList<Achievement>()
|
||||
for (i in 0 until list.length()) {
|
||||
val a = list.optJSONObject(i)?.optJSONObject("achievement") ?: continue
|
||||
val id = a.optString("name")
|
||||
if (id.isEmpty()) continue
|
||||
val at = unlocked[id]
|
||||
val done = at != null
|
||||
out += Achievement(
|
||||
id = id,
|
||||
name = (if (done) a.optString("unlockedDisplayName") else a.optString("lockedDisplayName"))
|
||||
.ifEmpty { a.optString("unlockedDisplayName") }.ifEmpty { id },
|
||||
description = (if (done) a.optString("unlockedDescription") else a.optString("lockedDescription"))
|
||||
.ifEmpty { a.optString("unlockedDescription") },
|
||||
hidden = a.optBoolean("hidden"),
|
||||
unlocked = done,
|
||||
unlockedAt = at ?: 0,
|
||||
icon = a.optString("unlockedIconLink").ifEmpty { null },
|
||||
iconLocked = a.optString("lockedIconLink").ifEmpty { null },
|
||||
)
|
||||
}
|
||||
return Result.Found(out)
|
||||
val answer = EpicNative.call(
|
||||
"achievements",
|
||||
JSONObject().put("accessToken", token).put("namespace", namespace).put("accountId", account).put("locale", locale()),
|
||||
) ?: return Result.Failed(Reason.UNREACHABLE)
|
||||
val list = answer.optJSONArray("list") ?: return Result.Failed(Reason.UNREACHABLE)
|
||||
return Result.Found(
|
||||
(0 until list.length()).mapNotNull { list.optJSONObject(it) }.map { a ->
|
||||
Achievement(
|
||||
id = a.optString("id"),
|
||||
name = a.optString("name"),
|
||||
description = a.optString("description"),
|
||||
hidden = a.optBoolean("hidden", false),
|
||||
unlocked = a.optBoolean("unlocked", false),
|
||||
unlockedAt = a.optLong("unlockedAt", 0L),
|
||||
icon = a.optString("icon").ifEmpty { null },
|
||||
iconLocked = a.optString("iconLocked").ifEmpty { null },
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private fun unlockTimes(token: String, account: String, namespace: String): Map<String, Long> {
|
||||
val out = HashMap<String, Long>()
|
||||
val records = query(token, PLAYER_ACHIEVEMENTS, JSONObject().put("epicAccountId", account).put("sandboxId", namespace))
|
||||
?.optJSONObject("data")?.optJSONObject("PlayerAchievement")?.optJSONObject("playerAchievementGameRecordsBySandbox")
|
||||
?.optJSONArray("records") ?: return out
|
||||
for (r in 0 until records.length()) {
|
||||
val player = records.optJSONObject(r)?.optJSONArray("playerAchievements") ?: continue
|
||||
for (i in 0 until player.length()) {
|
||||
val pa = player.optJSONObject(i)?.optJSONObject("playerAchievement") ?: continue
|
||||
if (pa.optBoolean("unlocked")) out[pa.optString("achievementName")] = epochSeconds(pa.optString("unlockDate"))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun query(token: String, query: String, variables: JSONObject): JSONObject? =
|
||||
StoreNet.postJson(GRAPHQL, JSONObject().put("query", query).put("variables", variables).toString(), bearer = token, userAgent = USER_AGENT)
|
||||
?.let(::JSONObject)
|
||||
|
||||
private val GAME_ACHIEVEMENTS = """
|
||||
query Achievement(${'$'}sandboxId: String!, ${'$'}locale: String!) {
|
||||
Achievement {
|
||||
productAchievementsRecordBySandbox(sandboxId: ${'$'}sandboxId, locale: ${'$'}locale) {
|
||||
achievements {
|
||||
achievement {
|
||||
name hidden unlockedDisplayName lockedDisplayName unlockedDescription lockedDescription
|
||||
unlockedIconLink lockedIconLink XP
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val PLAYER_ACHIEVEMENTS = """
|
||||
query PlayerAchievement(${'$'}epicAccountId: String!, ${'$'}sandboxId: String!) {
|
||||
PlayerAchievement {
|
||||
playerAchievementGameRecordsBySandbox(epicAccountId: ${'$'}epicAccountId, sandboxId: ${'$'}sandboxId) {
|
||||
records { playerAchievements { playerAchievement { achievementName unlocked unlockDate XP } } }
|
||||
}
|
||||
}
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
package com.droiddeck.launcher.stores.epic;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import com.droiddeck.launcher.stores.StoreLog;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public final class EpicApiClient {
|
||||
|
||||
private static final String TAG = "EpicApi";
|
||||
private static final String LIBRARY_URL = "https://library-service.live.use1a.on.epicgames.com/library/api/public/items?includeMetadata=true";
|
||||
private static final String CATALOG_BASE = "https://catalog-public-service-prod06.ol.epicgames.com/catalog/api/shared/namespace";
|
||||
private static final String MANIFEST_BASE = "https://launcher-public-service-prod06.ol.epicgames.com/launcher/api/public/assets/v2/platform/Windows/namespace";
|
||||
private static final String LEGENDARY_UA = "Legendary/0.1.0 (GameNative)";
|
||||
|
||||
private EpicApiClient() {}
|
||||
|
||||
public static List<EpicGame> getLibraryItems(String accessToken) {
|
||||
List<EpicGame> result = new ArrayList<>();
|
||||
String cursor = null;
|
||||
do {
|
||||
try {
|
||||
String url = LIBRARY_URL + (cursor != null ? "&cursor=" + cursor : "");
|
||||
String resp = EpicAuthClient.getRequest(url, accessToken);
|
||||
if (resp == null) break;
|
||||
JSONObject json = new JSONObject(resp);
|
||||
JSONArray records = json.optJSONArray("records");
|
||||
if (records == null) break;
|
||||
for (int i = 0; i < records.length(); i++) {
|
||||
JSONObject rec = records.getJSONObject(i);
|
||||
String appName = rec.optString("appName", "");
|
||||
if (appName.isEmpty() || appName.equals("1")) continue;
|
||||
String namespace = rec.optString("namespace", "");
|
||||
if ("ue".equals(namespace) || "89efe5924d3d467c839449ab6ab52e7f".equals(namespace)) continue;
|
||||
if ("PRIVATE".equals(rec.optString("sandboxType", ""))) continue;
|
||||
JSONArray platforms = rec.optJSONArray("platform");
|
||||
if (platforms != null && platforms.length() > 0) {
|
||||
boolean windows = false;
|
||||
for (int j = 0; j < platforms.length(); j++) {
|
||||
String p = platforms.optString(j, "");
|
||||
if ("Windows".equals(p) || "Win32".equals(p)) { windows = true; break; }
|
||||
}
|
||||
if (!windows) continue;
|
||||
}
|
||||
EpicGame game = new EpicGame();
|
||||
game.appName = appName;
|
||||
game.namespace = namespace;
|
||||
game.catalogItemId = rec.optString("catalogItemId", "");
|
||||
result.add(game);
|
||||
}
|
||||
JSONObject meta = json.optJSONObject("responseMetadata");
|
||||
String next = meta != null ? meta.optString("nextCursor", null) : null;
|
||||
cursor = (next == null || next.isEmpty() || next.equals(cursor)) ? null : next;
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "library page failed: " + e.getClass().getSimpleName());
|
||||
break;
|
||||
}
|
||||
} while (cursor != null);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static boolean enrichFromCatalog(String accessToken, EpicGame game) {
|
||||
if (game.namespace.isEmpty() || game.catalogItemId.isEmpty()) return false;
|
||||
try {
|
||||
String url = CATALOG_BASE + "/" + game.namespace + "/bulk/items?id=" + game.catalogItemId + "&includeDLCDetails=true&includeMainGameDetails=true&country=US";
|
||||
String resp = getWithLegendaryUA(url, accessToken);
|
||||
if (resp == null) return false;
|
||||
JSONObject root = new JSONObject(resp);
|
||||
JSONObject item = root.optJSONObject(game.catalogItemId);
|
||||
if (item == null && root.length() > 0) item = root.optJSONObject(root.keys().next());
|
||||
if (item == null) return false;
|
||||
game.title = item.optString("title", game.title.isEmpty() ? game.appName : game.title);
|
||||
game.developer = item.optString("developer", "");
|
||||
game.description = item.optString("description", "");
|
||||
game.isDLC = item.has("mainGameItem");
|
||||
if (game.isDLC) {
|
||||
JSONObject main = item.optJSONObject("mainGameItem");
|
||||
if (main != null) game.baseGameCatalogItemId = main.optString("id", "");
|
||||
}
|
||||
JSONArray keyImages = item.optJSONArray("keyImages");
|
||||
if (keyImages != null) for (int i = 0; i < keyImages.length(); i++) {
|
||||
JSONObject img = keyImages.getJSONObject(i);
|
||||
String type = img.optString("type", ""), imgUrl = img.optString("url", "");
|
||||
if (imgUrl.isEmpty()) continue;
|
||||
if ("DieselGameBoxTall".equals(type)) game.artCover = imgUrl;
|
||||
else if (("DieselGameBox".equals(type) || "Thumbnail".equals(type)) && game.artSquare.isEmpty()) game.artSquare = imgUrl;
|
||||
}
|
||||
JSONObject attrs = item.optJSONObject("customAttributes");
|
||||
if (attrs != null) {
|
||||
JSONObject offline = attrs.optJSONObject("CanRunOffline");
|
||||
if (offline != null) game.canRunOffline = !"false".equalsIgnoreCase(offline.optString("value", "true"));
|
||||
JSONObject publisher = attrs.optJSONObject("publisherName");
|
||||
if (publisher != null) game.publisher = publisher.optString("value", "").trim();
|
||||
}
|
||||
JSONObject seller = item.optJSONObject("seller");
|
||||
if (game.publisher.isEmpty() && seller != null) game.publisher = seller.optString("name", "").trim();
|
||||
String rd = item.optString("viewableDate", "");
|
||||
if (rd.isEmpty()) rd = item.optString("effectiveDate", "");
|
||||
if (!rd.isEmpty()) game.releaseDate = rd;
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "catalog enrich failed for " + game.appName + ": " + e.getClass().getSimpleName());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getManifestApiJson(String accessToken, String namespace, String catalogItemId, String appName) {
|
||||
try {
|
||||
String url = MANIFEST_BASE + "/" + namespace + "/catalogItem/" + catalogItemId + "/app/" + appName + "/label/Live";
|
||||
String resp = getWithLegendaryUA(url, accessToken);
|
||||
if (resp == null) return null;
|
||||
JSONObject root = new JSONObject(resp);
|
||||
JSONArray elements = root.optJSONArray("elements");
|
||||
if (elements == null || elements.length() == 0) return null;
|
||||
JSONObject first = elements.getJSONObject(0);
|
||||
JSONObject wrapper = new JSONObject();
|
||||
wrapper.put("manifests", first.optJSONArray("manifests"));
|
||||
String ver = first.optString("buildVersion", "");
|
||||
if (ver.isEmpty()) ver = first.optString("versionId", "");
|
||||
wrapper.put("versionId", ver);
|
||||
JSONObject sidecar = first.optJSONObject("sidecar");
|
||||
if (sidecar != null) {
|
||||
String config = sidecar.optString("config", "");
|
||||
if (!config.isEmpty()) {
|
||||
try { wrapper.put("deploymentId", new JSONObject(config).optString("deploymentId", "")); } catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
return wrapper.toString();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "manifest API failed for " + appName + ": " + e.getClass().getSimpleName());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getAdditionalCommandLine(String accessToken, String namespace, String catalogItemId) {
|
||||
return getCustomAttribute(accessToken, namespace, catalogItemId, "AdditionalCommandLine");
|
||||
}
|
||||
|
||||
public static String getCustomAttribute(String accessToken, String namespace, String catalogItemId, String name) {
|
||||
try {
|
||||
String url = CATALOG_BASE + "/" + namespace + "/bulk/items?id=" + catalogItemId + "&country=US";
|
||||
String resp = getWithLegendaryUA(url, accessToken);
|
||||
if (resp == null) return null;
|
||||
JSONObject root = new JSONObject(resp);
|
||||
JSONObject item = root.optJSONObject(catalogItemId);
|
||||
if (item == null && root.length() > 0) item = root.optJSONObject(root.keys().next());
|
||||
if (item == null) return "";
|
||||
JSONObject attrs = item.optJSONObject("customAttributes");
|
||||
if (attrs == null) return "";
|
||||
JSONObject attr = attrs.optJSONObject(name);
|
||||
return attr == null ? "" : attr.optString("value", "");
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "catalog attribute " + name + ": " + e.getClass().getSimpleName());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static String getWithLegendaryUA(String urlStr, String accessToken) {
|
||||
java.net.HttpURLConnection conn = null;
|
||||
try {
|
||||
conn = (java.net.HttpURLConnection) new java.net.URL(urlStr).openConnection();
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setConnectTimeout(30000);
|
||||
conn.setReadTimeout(30000);
|
||||
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
|
||||
conn.setRequestProperty("User-Agent", LEGENDARY_UA);
|
||||
int code = conn.getResponseCode();
|
||||
java.io.InputStream is = (code < 400) ? conn.getInputStream() : conn.getErrorStream();
|
||||
String body = EpicAuthClient.readStream(is);
|
||||
if (code < 200 || code >= 300) { Log.e(TAG, "GET HTTP " + code + " from " + StoreLog.redactUrl(urlStr)); return null; }
|
||||
return body;
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "GET failed: " + StoreLog.redactUrl(urlStr) + " (" + e.getClass().getSimpleName() + ")");
|
||||
return null;
|
||||
} finally {
|
||||
if (conn != null) conn.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
object EpicApiClient {
|
||||
private fun request(token: String, namespace: String, catalogItemId: String) =
|
||||
JSONObject().put("accessToken", token).put("namespace", namespace).put("catalogItemId", catalogItemId)
|
||||
|
||||
@JvmStatic
|
||||
fun getManifestApiJson(token: String, namespace: String, catalogItemId: String, appName: String): String? =
|
||||
EpicNative.call("build.info", request(token, namespace, catalogItemId).put("appName", appName))
|
||||
?.optJSONObject("info")?.toString()
|
||||
|
||||
@JvmStatic
|
||||
fun getCustomAttribute(token: String, namespace: String, catalogItemId: String, name: String): String? {
|
||||
val answer = EpicNative.call("catalog.attribute", request(token, namespace, catalogItemId).put("name", name)) ?: return null
|
||||
if (answer.optBoolean("unknown", false) || !answer.has("value")) return null
|
||||
return answer.optString("value", "")
|
||||
}
|
||||
|
||||
internal fun catalogDetails(token: String, namespace: String, catalogItemId: String): JSONObject? =
|
||||
EpicNative.call("catalog.details", request(token, namespace, catalogItemId))?.optJSONObject("details")
|
||||
|
||||
internal fun exchangeCode(token: String): String? =
|
||||
EpicNative.call("auth.exchange", JSONObject().put("accessToken", token))?.optString("code", "")?.ifEmpty { null }
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
package com.droiddeck.launcher.stores.epic;
|
||||
|
||||
import android.util.Base64;
|
||||
import android.util.Log;
|
||||
|
||||
import com.droiddeck.launcher.stores.StoreLog;
|
||||
|
||||
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;
|
||||
|
||||
public final class EpicAuthClient {
|
||||
|
||||
private static final String TAG = "EpicAuth";
|
||||
|
||||
static final String CLIENT_ID = "34a02cf8f4414e29b15921876da36f9a";
|
||||
static final String CLIENT_SECRET = "daafbccc737745039dffe53d94fc76cf";
|
||||
private static final String TOKEN_URL = "https://account-public-service-prod03.ol.epicgames.com/account/api/oauth/token";
|
||||
private static final String EXCHANGE_URL = "https://account-public-service-prod03.ol.epicgames.com/account/api/oauth/exchange";
|
||||
public static final String USER_AGENT = "UELauncher/11.0.1-14907503+++Portal+Release-Live Windows/10.0.19041.1.256.64bit";
|
||||
|
||||
public static final class TokenResult {
|
||||
public String accessToken;
|
||||
public String refreshToken;
|
||||
public String accountId;
|
||||
public String displayName;
|
||||
public long expiresAt;
|
||||
}
|
||||
|
||||
private EpicAuthClient() {}
|
||||
|
||||
public static TokenResult exchangeCode(String authCode) {
|
||||
return postToken("grant_type=authorization_code&code=" + authCode + "&token_type=eg1");
|
||||
}
|
||||
|
||||
public static TokenResult refreshToken(String refreshToken) {
|
||||
return postToken("grant_type=refresh_token&refresh_token=" + refreshToken + "&token_type=eg1");
|
||||
}
|
||||
|
||||
private static TokenResult postToken(String formBody) {
|
||||
try {
|
||||
String creds64 = Base64.encodeToString((CLIENT_ID + ":" + CLIENT_SECRET).getBytes(StandardCharsets.UTF_8), Base64.NO_WRAP);
|
||||
HttpURLConnection conn = (HttpURLConnection) new URL(TOKEN_URL).openConnection();
|
||||
conn.setRequestMethod("POST");
|
||||
conn.setConnectTimeout(30000);
|
||||
conn.setReadTimeout(30000);
|
||||
conn.setDoOutput(true);
|
||||
conn.setRequestProperty("Authorization", "Basic " + creds64);
|
||||
conn.setRequestProperty("User-Agent", USER_AGENT);
|
||||
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
|
||||
byte[] bodyBytes = formBody.getBytes(StandardCharsets.UTF_8);
|
||||
conn.setRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
|
||||
try (OutputStream os = conn.getOutputStream()) { os.write(bodyBytes); }
|
||||
int code = conn.getResponseCode();
|
||||
InputStream is = (code < 400) ? conn.getInputStream() : conn.getErrorStream();
|
||||
String resp = readStream(is);
|
||||
conn.disconnect();
|
||||
if (code < 200 || code >= 300) { Log.e(TAG, "token HTTP " + code); return null; }
|
||||
JSONObject json = new JSONObject(resp);
|
||||
TokenResult result = new TokenResult();
|
||||
result.accessToken = json.optString("access_token", null);
|
||||
result.refreshToken = json.optString("refresh_token", null);
|
||||
result.accountId = json.optString("account_id", "");
|
||||
result.displayName = json.optString("displayName", "");
|
||||
long expiresIn = json.optLong("expires_in", 7200L);
|
||||
String expiresAtStr = json.optString("expires_at", null);
|
||||
long expiresAtMs;
|
||||
if (expiresAtStr != null && !expiresAtStr.isEmpty()) {
|
||||
try { expiresAtMs = parseIso8601(expiresAtStr); } catch (Exception e) { expiresAtMs = System.currentTimeMillis() + expiresIn * 1000L; }
|
||||
} else expiresAtMs = System.currentTimeMillis() + expiresIn * 1000L;
|
||||
result.expiresAt = expiresAtMs;
|
||||
return result.accessToken != null ? result : null;
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "token request failed: " + e.getClass().getSimpleName());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getExchangeCode(String accessToken) {
|
||||
try {
|
||||
String resp = getRequest(EXCHANGE_URL, accessToken);
|
||||
if (resp == null) { Log.i(TAG, "exchange code: no answer"); return null; }
|
||||
return new JSONObject(resp).optString("code", null);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "exchange code failed: " + e.getClass().getSimpleName());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getRequest(String urlStr, String accessToken) {
|
||||
HttpURLConnection conn = null;
|
||||
try {
|
||||
conn = (HttpURLConnection) new URL(urlStr).openConnection();
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setConnectTimeout(30000);
|
||||
conn.setReadTimeout(30000);
|
||||
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
|
||||
conn.setRequestProperty("User-Agent", USER_AGENT);
|
||||
int code = conn.getResponseCode();
|
||||
InputStream is = (code < 400) ? conn.getInputStream() : conn.getErrorStream();
|
||||
String resp = readStream(is);
|
||||
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;
|
||||
} finally {
|
||||
if (conn != null) conn.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] getBytes(String urlStr, String accessToken) {
|
||||
HttpURLConnection conn = null;
|
||||
try {
|
||||
conn = (HttpURLConnection) new URL(urlStr).openConnection();
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setConnectTimeout(30000);
|
||||
conn.setReadTimeout(120000);
|
||||
if (accessToken != null) conn.setRequestProperty("Authorization", "Bearer " + accessToken);
|
||||
conn.setRequestProperty("User-Agent", USER_AGENT);
|
||||
int code = conn.getResponseCode();
|
||||
if (code < 200 || code >= 300) { Log.e(TAG, "bytes HTTP " + code + " from " + StoreLog.redactUrl(urlStr)); return null; }
|
||||
return readAllBytes(conn.getInputStream());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "bytes failed: " + StoreLog.redactUrl(urlStr) + " (" + e.getClass().getSimpleName() + ")");
|
||||
return null;
|
||||
} finally {
|
||||
if (conn != null) conn.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
static byte[] readAllBytes(InputStream in) throws IOException {
|
||||
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
|
||||
byte[] buf = new byte[131072];
|
||||
int n;
|
||||
while ((n = in.read(buf)) != -1) out.write(buf, 0, n);
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
private static long parseIso8601(String s) {
|
||||
int year = Integer.parseInt(s.substring(0, 4));
|
||||
int month = Integer.parseInt(s.substring(5, 7));
|
||||
int day = Integer.parseInt(s.substring(8, 10));
|
||||
int hour = Integer.parseInt(s.substring(11, 13));
|
||||
int minute = Integer.parseInt(s.substring(14, 16));
|
||||
int second = Integer.parseInt(s.substring(17, 19));
|
||||
long jd = 367L * year - (7 * (year + (month + 9) / 12)) / 4 + (275 * month) / 9 + day + 1721013L;
|
||||
long epochDays = jd - 2440588L;
|
||||
return epochDays * 86400000L + hour * 3600000L + minute * 60000L + second * 1000L;
|
||||
}
|
||||
}
|
||||
@@ -2,40 +2,37 @@ package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.util.Log
|
||||
import android.webkit.WebView
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.EpicLaunchSupport
|
||||
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 org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import com.droiddeck.launcher.stores.mergeItems
|
||||
|
||||
object EpicBackend : StoreBackend, EpicLaunchSupport {
|
||||
private const val TAG = "EpicBackend"
|
||||
override val store: Store = Store.EPIC
|
||||
|
||||
init { LoginFlows.epicFlow = { LoginFlow } }
|
||||
init {
|
||||
LoginFlows.epicFlow = { EpicLogin.create() }
|
||||
}
|
||||
|
||||
override fun signIn(context: Context) {
|
||||
context.startActivity(Intent(context, StoreLoginActivity::class.java).putExtra(StoreLoginActivity.EXTRA_STORE, store.id).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
context.startActivity(
|
||||
Intent(context, StoreLoginActivity::class.java)
|
||||
.putExtra(StoreLoginActivity.EXTRA_STORE, store.id)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
}
|
||||
|
||||
override fun signOut(context: Context) {
|
||||
EpicPrefs.get(context).edit().remove("library_cache").remove("library_synced_at").apply()
|
||||
runCatching { EpicLibrary.forget(context) }
|
||||
}
|
||||
|
||||
override fun syncLibrary(context: Context, force: Boolean) {
|
||||
@@ -44,19 +41,20 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
|
||||
val cached = EpicLibrary.cached(app).map { EpicLibrary.toCatalogItem(app, it) }
|
||||
val quiet = cached.isNotEmpty() && !force
|
||||
StoresState.post {
|
||||
if (cached.isNotEmpty()) StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached)
|
||||
if (!quiet) StoresState.status[store] = app.getString(com.droiddeck.launcher.R.string.stores_sync_library)
|
||||
if (cached.isNotEmpty()) StoresState.library[store] = mergeItems(StoresState.library[store], cached)
|
||||
if (!quiet) StoresState.status[store] = app.getString(R.string.stores_sync_library)
|
||||
}
|
||||
val result = EpicLibrary.sync(app, force) { line -> if (!quiet) StoresState.post { StoresState.status[store] = line } }
|
||||
StoresState.post {
|
||||
StoresState.status.remove(store)
|
||||
when (result) {
|
||||
is EpicLibrary.SyncResult.Ok -> {
|
||||
StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { EpicLibrary.toCatalogItem(app, it) }); StoresState.problems.remove(store)
|
||||
StoresState.library[store] = mergeItems(StoresState.library[store], result.games.map { EpicLibrary.toCatalogItem(app, it) })
|
||||
StoresState.problems.remove(store)
|
||||
}
|
||||
is EpicLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message
|
||||
EpicLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = StoresState.notSignedInLine(store)
|
||||
EpicLibrary.SyncResult.Throttled -> if (!StoresState.library.containsKey(store)) StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached)
|
||||
EpicLibrary.SyncResult.Throttled -> if (!StoresState.library.containsKey(store)) StoresState.library[store] = cached
|
||||
EpicLibrary.SyncResult.Busy -> {}
|
||||
}
|
||||
}
|
||||
@@ -65,126 +63,33 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
|
||||
|
||||
override fun loadShelves(context: Context, force: Boolean) {
|
||||
val app = context.applicationContext
|
||||
EpicStoreCatalog.cachedFeatured(app)?.let { StoresState.post { StoresState.shelves[store] = markOwned(it) } }
|
||||
EpicShelves.cached(app)?.let { s -> StoresState.post { StoresState.shelves[store] = EpicShelves.markOwned(s, StoresState.library[store]) } }
|
||||
Thread({
|
||||
val shelves = EpicStoreCatalog.featured(app, force)
|
||||
StoresState.post { if (shelves != null) StoresState.shelves[store] = markOwned(shelves) }
|
||||
val shelves = runCatching { EpicShelves.featured(app, force) }.getOrNull()
|
||||
if (shelves != null) StoresState.post { StoresState.shelves[store] = EpicShelves.markOwned(shelves, StoresState.library[store]) }
|
||||
}, "epic-shelves").start()
|
||||
}
|
||||
|
||||
private fun markOwned(s: StoreShelves): StoreShelves {
|
||||
val owned = StoresState.library[store] ?: return s
|
||||
val byCatalogItem = owned.associateBy { it.extra["catalogItemId"] ?: "" }
|
||||
fun mark(l: List<CatalogItem>) = l.map { i ->
|
||||
val match = i.extra["items"]?.split(',')?.firstNotNullOfOrNull { byCatalogItem[it] }
|
||||
if (match != null) match.copy(
|
||||
imageUrl = i.imageUrl ?: match.imageUrl, tallImageUrl = i.tallImageUrl ?: match.tallImageUrl,
|
||||
developer = match.developer.ifBlank { i.developer }, publisher = match.publisher.ifBlank { i.publisher },
|
||||
releaseDate = match.releaseDate.ifBlank { i.releaseDate },
|
||||
) else i
|
||||
}
|
||||
return StoreShelves(mark(s.whatsNew), mark(s.deals), mark(s.free), mark(s.trending))
|
||||
}
|
||||
|
||||
override fun install(context: Context, item: CatalogItem, root: File) {
|
||||
override fun install(context: Context, item: CatalogItem, root: java.io.File) {
|
||||
val app = context.applicationContext
|
||||
val namespace = item.extra["namespace"] ?: ""
|
||||
val catalogItemId = item.extra["catalogItemId"] ?: ""
|
||||
if (namespace.isEmpty() || catalogItemId.isEmpty()) { StoresState.logLine("Epic: \"${item.title}\" is not in your library"); return }
|
||||
if (item.extra["namespace"].isNullOrEmpty() || item.extra["catalogItemId"].isNullOrEmpty()) {
|
||||
StoresState.logLine("Epic: \"${item.title}\" is not in your library")
|
||||
return
|
||||
}
|
||||
val folder = StoreInstallRoot.folderFor(app, Store.EPIC, item.id, item.title, root)
|
||||
val entry = DownloadEntry(store, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes, location = StoreInstallRoot.labelFor(app, folder))
|
||||
DownloadQueue.enqueue(app, entry) { InstallJob(app, item, namespace, catalogItemId, folder) }
|
||||
val entry = DownloadEntry(
|
||||
Store.EPIC, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes,
|
||||
location = StoreInstallRoot.labelFor(app, folder),
|
||||
)
|
||||
DownloadQueue.enqueue(app, entry) { EpicInstaller(app, item, folder) }
|
||||
}
|
||||
|
||||
override fun uninstall(context: Context, game: InstalledStoreGame) {}
|
||||
|
||||
override fun exchangeCode(context: Context): String? {
|
||||
val token = EpicCredentialStore.getValidAccessToken(context) ?: return null
|
||||
return EpicAuthClient.getExchangeCode(token)
|
||||
return EpicApiClient.exchangeCode(token)
|
||||
}
|
||||
|
||||
override fun signInExpired(context: Context): Boolean = EpicCredentialStore.expired(context)
|
||||
|
||||
private class InstallJob(val app: Context, val item: CatalogItem, val namespace: String, val catalogItemId: String, val folder: File) : DownloadQueue.DownloadJob {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
private val scratch: File? = if (StoreInstallRoot.isRemovable(app, folder) && !hasChunks(File(folder, ".chunks"))) StoreInstallRoot.scratchDir(app, Store.EPIC, item.id) else null
|
||||
|
||||
private fun hasChunks(dir: File): Boolean = dir.isDirectory && (dir.list()?.isNotEmpty() == true)
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
handle.stage(DownloadStage.MANIFEST, app.getString(com.droiddeck.launcher.R.string.stores_sync_sign_in))
|
||||
val token = EpicCredentialStore.getValidAccessToken(app) ?: throw EpicDownloadManager.InstallException("Not signed in to Epic Games")
|
||||
StoreInstalls.begin(folder, Store.EPIC, item.id, item.title, item.tallImageUrl ?: item.imageUrl, item.imageUrl)
|
||||
if (scratch == null && hasChunks(File(folder, ".chunks"))) handle.log("epic: resuming \"${item.title}\" with the chunks already beside it")
|
||||
val manifestJson = EpicApiClient.getManifestApiJson(token, namespace, catalogItemId, item.id)
|
||||
?: throw EpicDownloadManager.InstallException("The manifest could not be fetched")
|
||||
val tags = EpicInstallTags.tagsForDevice()
|
||||
var downloading = false
|
||||
val result = EpicDownloadManager.install(app, manifestJson, folder.path, scratch?.path ?: "", tags, cancelled, object : EpicDownloadManager.Callback {
|
||||
override fun onProgress(message: String, pct: Int) {
|
||||
when {
|
||||
message.startsWith("Writing") || message.startsWith("Complete") -> handle.stage(DownloadStage.INSTALL, message)
|
||||
message.startsWith("Downloading chunks") -> { if (!downloading) { downloading = true; handle.stage(DownloadStage.DOWNLOAD, message) } else handle.progress(-1, -1, message) }
|
||||
message.startsWith("Checking") -> handle.stage(DownloadStage.MANIFEST, 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) }
|
||||
override fun onSizes(downloadBytes: Long, diskBytes: Long) {
|
||||
handle.diskSize(diskBytes)
|
||||
EpicLibrary.rememberSize(app, item.id, diskBytes)
|
||||
}
|
||||
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
|
||||
// Assembly overlaps chunk fetching; only the final install event advances the UI.
|
||||
if (stage == "stream") return
|
||||
handle.stage(when (stage) { "check" -> DownloadStage.MANIFEST; "verify" -> DownloadStage.VERIFY; else -> DownloadStage.INSTALL })
|
||||
handle.stageProgress(done, total, items, itemsTotal, bytes = stage == "install")
|
||||
}
|
||||
}) ?: return null
|
||||
if (cancelled.get()) return null
|
||||
handle.stage(DownloadStage.INSTALL, app.getString(com.droiddeck.launcher.R.string.stores_registering))
|
||||
EpicLibrary.rememberSize(app, item.id, result.bytes)
|
||||
val deploymentId = runCatching { JSONObject(manifestJson).optString("deploymentId", "") }.getOrDefault("")
|
||||
val exe = StoreExe.pick(folder, result.launchExe, item.title)
|
||||
if (exe.isEmpty()) handle.log("epic: no exe found in ${folder.name}; pick one in Steam settings › Added games")
|
||||
val args = EpicLaunchData.arguments(app, token, item.id, namespace, catalogItemId, deploymentId)
|
||||
val sidecar = StoreGameSidecar(
|
||||
Store.EPIC, item.id, item.title, exe = exe.ifEmpty { "game.exe" }, args = args,
|
||||
installVersion = result.buildVersion, installedAt = System.currentTimeMillis(),
|
||||
cover = item.tallImageUrl ?: item.imageUrl, hero = item.imageUrl,
|
||||
extra = EpicLaunchData.extras(item.id, namespace, catalogItemId, deploymentId) + mapOf(
|
||||
com.droiddeck.launcher.frontend.WinCompSources.EPIC_PREREQ_PATH to result.prereqPath,
|
||||
com.droiddeck.launcher.frontend.WinCompSources.EPIC_PREREQ_NAME to result.prereqName,
|
||||
) + (if (result.prereqRead) mapOf(com.droiddeck.launcher.frontend.WinCompSources.LIST_READ to "1") else emptyMap()),
|
||||
)
|
||||
StoreInstalls.complete(app, folder, sidecar)
|
||||
return folder.path
|
||||
}
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
if (deleteFiles) StoreInstalls.discard(app, folder, listOfNotNull(File(folder, ".chunks"), scratch, StoreInstallRoot.scratchDir(app, Store.EPIC, item.id)))
|
||||
}
|
||||
}
|
||||
|
||||
private object LoginFlow : StoreLoginActivity.Flow {
|
||||
private const val REDIRECT = "https://www.epicgames.com/id/api/redirect"
|
||||
override val startUrl: String = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Fid%2Fapi%2Fredirect%3FclientId%3D${EpicAuthClient.CLIENT_ID}%26responseType%3Dcode"
|
||||
override val userAgent: String get() = EpicAuthClient.USER_AGENT
|
||||
override val readsPage: Boolean get() = true
|
||||
override fun isRedirect(url: String): Boolean = url.startsWith(REDIRECT)
|
||||
|
||||
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? {
|
||||
var text = url
|
||||
if (text.startsWith("\"")) text = text.substring(1, text.length - 1)
|
||||
text = text.replace("\\n", "").replace("\\r", "").replace("\\\"", "\"")
|
||||
val code = Regex("\"authorizationCode\":\"([^\"]+)\"").find(text)?.groupValues?.get(1)
|
||||
if (code.isNullOrEmpty()) { Log.w(TAG, "login: no authorization code on the redirect page"); return activity.getString(com.droiddeck.launcher.R.string.stores_login_error_verification) }
|
||||
val result = EpicAuthClient.exchangeCode(code) ?: return activity.getString(com.droiddeck.launcher.R.string.stores_login_error_generic)
|
||||
EpicCredentialStore.save(activity, result)
|
||||
Log.i(TAG, "signed in")
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,48 +7,99 @@ import com.droiddeck.launcher.stores.StoreAccounts
|
||||
import org.json.JSONObject
|
||||
|
||||
object EpicCredentialStore {
|
||||
private const val TAG = "EpicAuth"
|
||||
private const val TAG = "EpicCredentials"
|
||||
private const val REFRESH_MARGIN_MS = 5 * 60 * 1000L
|
||||
private val refreshLock = Any()
|
||||
|
||||
class Credentials(val accessToken: String, val refreshToken: String?, val accountId: String, val displayName: String, val expiresAt: Long)
|
||||
data class Credentials(
|
||||
val accessToken: String,
|
||||
val refreshToken: String?,
|
||||
val accountId: String,
|
||||
val displayName: String,
|
||||
val expiresAt: Long,
|
||||
)
|
||||
|
||||
@JvmStatic
|
||||
fun save(context: Context, result: EpicAuthClient.TokenResult) {
|
||||
val json = JSONObject().put("access_token", result.accessToken).put("account_id", result.accountId ?: "")
|
||||
.put("display_name", result.displayName ?: "").put("expires_at", result.expiresAt)
|
||||
if (!result.refreshToken.isNullOrEmpty()) json.put("refresh_token", result.refreshToken)
|
||||
StoreAccounts.write(context, Store.EPIC, json)
|
||||
class TokenResult(
|
||||
val accessToken: String,
|
||||
val refreshToken: String?,
|
||||
val accountId: String?,
|
||||
val displayName: String?,
|
||||
val expiresAt: Long,
|
||||
) {
|
||||
companion object {
|
||||
fun from(json: JSONObject): TokenResult? {
|
||||
if (json.has("error")) return null
|
||||
val access = json.optString("access_token", "").ifEmpty { return null }
|
||||
return TokenResult(
|
||||
access,
|
||||
json.optString("refresh_token", "").ifEmpty { null },
|
||||
json.optString("account_id", "").ifEmpty { null },
|
||||
json.optString("display_name", "").ifEmpty { null },
|
||||
json.optLong("expires_at", 0L),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun fromJson(o: JSONObject): Credentials? {
|
||||
val access = o.optString("access_token", "").ifEmpty { return null }
|
||||
return Credentials(
|
||||
accessToken = access,
|
||||
refreshToken = o.optString("refresh_token", "").ifEmpty { null },
|
||||
accountId = o.optString("account_id", ""),
|
||||
displayName = o.optString("display_name", ""),
|
||||
expiresAt = o.optLong("expires_at", 0L),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun toJson(c: Credentials): JSONObject = JSONObject().apply {
|
||||
put("access_token", c.accessToken)
|
||||
c.refreshToken?.takeIf { it.isNotEmpty() }?.let { put("refresh_token", it) }
|
||||
put("account_id", c.accountId)
|
||||
put("display_name", c.displayName)
|
||||
put("expires_at", c.expiresAt)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun load(context: Context): Credentials? {
|
||||
val json = StoreAccounts.read(context, Store.EPIC) ?: return null
|
||||
val token = json.optString("access_token", "").ifEmpty { return null }
|
||||
return Credentials(token, json.optString("refresh_token", "").ifEmpty { null }, json.optString("account_id", ""), json.optString("display_name", ""), json.optLong("expires_at", 0L))
|
||||
fun load(context: Context): Credentials? = StoreAccounts.read(context.applicationContext, Store.EPIC)?.let(::fromJson)
|
||||
|
||||
fun save(context: Context, result: TokenResult, merge: Boolean = true) {
|
||||
val before = if (merge) load(context) else null
|
||||
val next = Credentials(
|
||||
accessToken = result.accessToken,
|
||||
refreshToken = result.refreshToken ?: before?.refreshToken,
|
||||
accountId = result.accountId ?: before?.accountId.orEmpty(),
|
||||
displayName = result.displayName ?: before?.displayName.orEmpty(),
|
||||
expiresAt = result.expiresAt,
|
||||
)
|
||||
StoreAccounts.write(context.applicationContext, Store.EPIC, toJson(next))
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun isLoggedIn(context: Context): Boolean = load(context) != null
|
||||
|
||||
@JvmStatic
|
||||
fun expired(context: Context): Boolean {
|
||||
val creds = load(context) ?: return false
|
||||
return creds.expiresAt in 1 until System.currentTimeMillis()
|
||||
val c = load(context) ?: return false
|
||||
return c.expiresAt > 0 && c.expiresAt < System.currentTimeMillis()
|
||||
}
|
||||
|
||||
private fun fresh(c: Credentials): Boolean =
|
||||
c.expiresAt - System.currentTimeMillis() > REFRESH_MARGIN_MS || c.refreshToken.isNullOrEmpty()
|
||||
|
||||
@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 = EpicAuthClient.refreshToken(creds.refreshToken)
|
||||
if (result != null) {
|
||||
if (result.refreshToken.isNullOrEmpty()) result.refreshToken = creds.refreshToken
|
||||
if (result.accountId.isNullOrEmpty()) result.accountId = creds.accountId
|
||||
if (result.displayName.isNullOrEmpty()) result.displayName = creds.displayName
|
||||
save(context, result)
|
||||
Log.i(TAG, "token refreshed")
|
||||
return result.accessToken
|
||||
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
|
||||
val answer = EpicNative.call("auth.refresh", JSONObject().put("refreshToken", again.refreshToken))
|
||||
val result = answer?.let(TokenResult::from)
|
||||
if (result == null) {
|
||||
Log.w(TAG, "token refresh failed: ${answer?.optString("error").orEmpty().ifEmpty { "no answer" }}")
|
||||
return again.accessToken
|
||||
}
|
||||
Log.w(TAG, "token refresh failed; using the stored token")
|
||||
save(context, result)
|
||||
return result.accessToken
|
||||
}
|
||||
return creds.accessToken
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,76 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
class EpicCdn(val base: String, val dir: String, val auth: String)
|
||||
|
||||
class EpicManifest internal constructor(
|
||||
internal val bytes: ByteArray,
|
||||
val files: List<FileEntry>,
|
||||
val buildVersion: String,
|
||||
val launchExe: String,
|
||||
val prereqName: String,
|
||||
val prereqPath: String,
|
||||
val prereqRead: Boolean,
|
||||
) {
|
||||
class FileEntry(val path: String, private val size: Long, val tags: List<String>) {
|
||||
fun fileSize(): Long = size
|
||||
}
|
||||
}
|
||||
|
||||
object EpicDownloadManager {
|
||||
private fun info(json: String): JSONObject? = runCatching { JSONObject(json) }.getOrNull()
|
||||
|
||||
@JvmStatic
|
||||
fun parseCdnUrls(json: String): List<EpicCdn> {
|
||||
val info = info(json) ?: return emptyList()
|
||||
val list = EpicNative.call("build.cdns", JSONObject().put("info", info))?.optJSONArray("cdns") ?: return emptyList()
|
||||
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.map {
|
||||
EpicCdn(it.optString("base"), it.optString("dir"), it.optString("auth"))
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun downloadManifest(json: String, cdns: List<EpicCdn>): ByteArray? {
|
||||
val info = info(json) ?: return null
|
||||
if (cdns.isEmpty()) return null
|
||||
val list = JSONArray()
|
||||
cdns.forEach { list.put(JSONObject().put("base", it.base).put("dir", it.dir).put("auth", it.auth)) }
|
||||
return EpicNative.fetch("manifest.download", JSONObject().put("info", info).put("cdns", list))
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun parseManifest(bytes: ByteArray): EpicManifest? {
|
||||
val summary = EpicNative.inspect(bytes, JSONObject().put("op", "summary")) ?: return null
|
||||
if (summary.has("error")) return null
|
||||
val list = summary.optJSONArray("files") ?: return null
|
||||
val files = (0 until list.length()).mapNotNull { list.optJSONObject(it) }.map { f ->
|
||||
val tags = f.optJSONArray("tags")
|
||||
EpicManifest.FileEntry(f.optString("path"), f.optLong("size", 0L), List(tags?.length() ?: 0) { tags!!.optString(it) })
|
||||
}
|
||||
return EpicManifest(
|
||||
bytes, files,
|
||||
buildVersion = summary.optString("buildVersion"),
|
||||
launchExe = summary.optString("launchExe"),
|
||||
prereqName = summary.optString("prereqName"),
|
||||
prereqPath = summary.optString("prereqPath"),
|
||||
prereqRead = summary.optBoolean("prereqRead", false),
|
||||
)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun resolveInstallFiles(manifest: EpicManifest, tags: List<String>): List<EpicManifest.FileEntry> {
|
||||
val answer = EpicNative.inspect(manifest.bytes, JSONObject().put("op", "select").put("tags", JSONArray(tags))) ?: return emptyList()
|
||||
val indices = answer.optJSONArray("indices") ?: return emptyList()
|
||||
return (0 until indices.length()).mapNotNull { manifest.files.getOrNull(indices.optInt(it, -1)) }
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun fetchPrereq(json: String): Array<String>? {
|
||||
val info = info(json) ?: return null
|
||||
val answer = EpicNative.call("build.prereq", JSONObject().put("info", info)) ?: return null
|
||||
if (answer.has("error") || !answer.optBoolean("read", false)) return null
|
||||
return arrayOf(answer.optString("name"), answer.optString("path"))
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.droiddeck.launcher.stores.epic;
|
||||
|
||||
public class EpicGame {
|
||||
public String appName = "";
|
||||
public String namespace = "";
|
||||
public String catalogItemId = "";
|
||||
public String title = "";
|
||||
public String developer = "";
|
||||
public String description = "";
|
||||
public String artCover = "";
|
||||
public String artSquare = "";
|
||||
public String version = "";
|
||||
public long installSize = 0L;
|
||||
public boolean canRunOffline = true;
|
||||
public boolean isDLC = false;
|
||||
public String baseGameCatalogItemId = "";
|
||||
public String releaseDate = "";
|
||||
public String publisher = "";
|
||||
}
|
||||
@@ -1,37 +1,24 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import org.json.JSONObject
|
||||
import java.util.Locale
|
||||
|
||||
object EpicInstallTags {
|
||||
private val LANGUAGE_TO_TAGS: Map<String, List<String>> = mapOf(
|
||||
"ar" to listOf("Arabic", "ar"), "bg" to listOf("Bulgarian", "bg-BG", "bg"),
|
||||
"zh-Hans" to listOf("Chinese", "ChineseSimplified", "zh-Hans", "zh_Hans", "zh"), "zh-Hant" to listOf("ChineseTraditional", "zh-Hant", "zh_Hant"),
|
||||
"cs" to listOf("Czech", "cs-CZ", "cs"), "da" to listOf("Danish", "da-DK", "da"), "nl" to listOf("Dutch", "nl-NL", "nl"),
|
||||
"en" to listOf("English", "en-US", "en"), "fi" to listOf("Finnish", "fi-FI", "fi"), "fr" to listOf("French", "fr-FR", "fr"),
|
||||
"de" to listOf("German", "de-DE", "de"), "el" to listOf("Greek", "el-GR", "el"), "hu" to listOf("Hungarian", "hu-HU", "hu"),
|
||||
"it" to listOf("Italian", "it-IT", "it"), "ja" to listOf("Japanese", "ja-JP", "ja"), "ko" to listOf("Korean", "ko-KR", "ko"),
|
||||
"no" to listOf("Norwegian", "nb-NO", "no"), "pl" to listOf("Polish", "pl-PL", "pl"), "pt" to listOf("Portuguese", "pt-PT", "pt"),
|
||||
"pt-BR" to listOf("PortugueseBrazilian", "Brazilian", "pt-BR", "br"), "ro" to listOf("Romanian", "ro-RO", "ro"),
|
||||
"ru" to listOf("Russian", "ru-RU", "ru"), "es" to listOf("Spanish", "es-ES", "es"), "es-419" to listOf("SpanishLatinAmerica", "Latam", "es-MX", "es_mx"),
|
||||
"sv" to listOf("Swedish", "sv-SE", "sv"), "th" to listOf("Thai", "th-TH", "th"), "tr" to listOf("Turkish", "tr-TR", "tr"),
|
||||
"uk" to listOf("Ukrainian", "uk-UA", "uk"), "vi" to listOf("Vietnamese", "vi-VN", "vi"),
|
||||
)
|
||||
private class Answer(val locale: Locale, val tags: List<String>, val launchLocale: String)
|
||||
|
||||
private fun key(locale: Locale): String? {
|
||||
val l = locale.language.lowercase(Locale.ROOT)
|
||||
val r = locale.country.uppercase(Locale.ROOT)
|
||||
return when (l) {
|
||||
"zh" -> if (r == "TW" || r == "HK" || r == "MO") "zh-Hant" else "zh-Hans"
|
||||
"pt" -> if (r == "BR") "pt-BR" else "pt"
|
||||
"es" -> if (r == "ES" || r.isEmpty()) "es" else "es-419"
|
||||
"nb", "nn" -> "no"
|
||||
else -> if (LANGUAGE_TO_TAGS.containsKey(l)) l else null
|
||||
}
|
||||
@Volatile private var last: Answer? = null
|
||||
|
||||
private fun current(): Answer? {
|
||||
val locale = Locale.getDefault()
|
||||
last?.takeIf { it.locale == locale }?.let { return it }
|
||||
val answer = EpicNative.call("locale", JSONObject().put("language", locale.language).put("region", locale.country)) ?: return null
|
||||
val list = answer.optJSONArray("tags")
|
||||
val tags = List(list?.length() ?: 0) { list!!.optString(it) }.filter { it.isNotEmpty() }
|
||||
return Answer(locale, tags, answer.optString("launchLocale", "en").ifEmpty { "en" }).also { last = it }
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun tagsForDevice(): List<String> = LANGUAGE_TO_TAGS[key(Locale.getDefault()) ?: "en"] ?: LANGUAGE_TO_TAGS.getValue("en")
|
||||
fun tagsForDevice(): List<String> = current()?.tags ?: emptyList()
|
||||
|
||||
@JvmStatic
|
||||
fun localeCodeForDevice(): String = key(Locale.getDefault())?.substringBefore('-') ?: "en"
|
||||
fun launchLocale(): String = current()?.launchLocale ?: "en"
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.WinCompSources
|
||||
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.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreInstalls
|
||||
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 EpicInstaller(
|
||||
private val app: Context,
|
||||
private val item: CatalogItem,
|
||||
private val folder: File,
|
||||
) : DownloadQueue.DownloadJob {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
private val namespace = item.extra["namespace"].orEmpty()
|
||||
private val catalogItemId = item.extra["catalogItemId"].orEmpty()
|
||||
|
||||
private fun scratch(): File = StoreInstallRoot.scratchDir(app, Store.EPIC, item.id)
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
handle.stage(DownloadStage.MANIFEST, app.getString(R.string.stores_sync_sign_in))
|
||||
val token = EpicCredentialStore.getValidAccessToken(app) ?: throw IllegalStateException("Not signed in to Epic Games")
|
||||
val cover = item.tallImageUrl ?: item.imageUrl
|
||||
StoreInstalls.begin(folder, Store.EPIC, item.id, item.title, cover, item.imageUrl)
|
||||
if (cancelled.get()) return null
|
||||
|
||||
handle.stage(DownloadStage.MANIFEST, "Reading the build list…")
|
||||
val info = EpicApiClient.getManifestApiJson(token, namespace, catalogItemId, item.id)
|
||||
?: throw IllegalStateException("The manifest could not be fetched")
|
||||
if (cancelled.get()) return null
|
||||
|
||||
val tier = StoreDownloadTier.current(app)
|
||||
val request = JSONObject()
|
||||
.put("info", JSONObject(info))
|
||||
.put("gameDir", folder.absolutePath)
|
||||
.put("scratchDir", if (StoreInstallRoot.isRemovable(app, folder)) scratch().absolutePath else "")
|
||||
.put("storageLabel", StoreInstallRoot.labelFor(app, folder))
|
||||
.put("tags", JSONArray(EpicInstallTags.tagsForDevice()))
|
||||
.put("maxWorkers", tier.networkWindow.coerceIn(1, 128))
|
||||
.put("processWorkers", tier.processWorkers)
|
||||
.put("caBundle", "")
|
||||
|
||||
val shown = AtomicLong(-1)
|
||||
val installing = AtomicBoolean(false)
|
||||
val prefs = EpicPrefs.get(app)
|
||||
val listener = object : EpicNative.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)
|
||||
}
|
||||
|
||||
override fun onSizes(pendingBytes: Long, diskBytes: Long) {
|
||||
handle.diskSize(diskBytes)
|
||||
if (diskBytes > 0) prefs.edit().putLong("size_${item.id}", diskBytes).apply()
|
||||
}
|
||||
|
||||
override fun onProgress(written: Long, total: Long, files: Int, filesTotal: Int) {
|
||||
if (installing.get()) return
|
||||
while (true) {
|
||||
val before = shown.get()
|
||||
if (written < before) return
|
||||
if (shown.compareAndSet(before, written)) break
|
||||
}
|
||||
handle.progress(written, total, "Downloading chunks ($files/$filesTotal files)")
|
||||
}
|
||||
|
||||
override fun onInstall(done: Long, total: Long, files: Int, filesTotal: Int) {
|
||||
installing.set(true)
|
||||
handle.stage(DownloadStage.INSTALL)
|
||||
handle.stageProgress(done, total, files, filesTotal, bytes = true)
|
||||
}
|
||||
|
||||
override fun onLog(line: String) { handle.log("epic: $line") }
|
||||
|
||||
override fun beforeReplace(): Boolean = try {
|
||||
StoreInstalls.markUpdating(folder)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
handle.log("epic: 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 = EpicNative.install(request, listener, cancelled)
|
||||
if (outcome.cancelled || cancelled.get() && !outcome.success) return null
|
||||
if (!outcome.success) throw IllegalStateException(outcome.error.ifEmpty { "Native Epic install failed" })
|
||||
val result = outcome.result ?: JSONObject()
|
||||
|
||||
handle.stage(DownloadStage.INSTALL, app.getString(R.string.stores_registering))
|
||||
val picked = StoreExe.pick(folder, result.optString("launchExe"), item.title)
|
||||
if (picked.isEmpty()) handle.log("epic: no exe found in ${folder.name}; pick one in Steam settings › Added games")
|
||||
val creds = EpicCredentialStore.load(app)
|
||||
val additional = EpicApiClient.getCustomAttribute(token, namespace, catalogItemId, "AdditionalCommandLine").orEmpty()
|
||||
val deployment = result.optString("deploymentId")
|
||||
val argsAnswer = EpicNative.call(
|
||||
"launch.args",
|
||||
JSONObject().put("displayName", creds?.displayName.orEmpty()).put("accountId", creds?.accountId.orEmpty())
|
||||
.put("namespace", namespace).put("locale", EpicInstallTags.launchLocale()).put("appName", item.id)
|
||||
.put("deploymentId", deployment).put("additional", additional),
|
||||
)
|
||||
val argList = argsAnswer?.optJSONArray("args")
|
||||
val args = List(argList?.length() ?: 0) { argList!!.optString(it) }.filter { it.isNotEmpty() }
|
||||
|
||||
val extra = LinkedHashMap<String, String>()
|
||||
extra["appName"] = item.id
|
||||
extra["namespace"] = namespace
|
||||
extra["catalogItemId"] = catalogItemId
|
||||
if (deployment.isNotEmpty()) extra["deploymentId"] = deployment
|
||||
extra[WinCompSources.EPIC_PREREQ_PATH] = result.optString("prereqPath")
|
||||
extra[WinCompSources.EPIC_PREREQ_NAME] = result.optString("prereqName")
|
||||
if (result.optBoolean("prereqRead", false)) extra[WinCompSources.LIST_READ] = "1"
|
||||
|
||||
val sidecar = StoreGameSidecar(
|
||||
Store.EPIC, item.id, item.title, exe = picked.ifEmpty { "game.exe" }, args = args,
|
||||
installVersion = result.optString("buildVersion"), installedAt = System.currentTimeMillis(),
|
||||
cover = cover, hero = item.imageUrl, extra = extra,
|
||||
)
|
||||
StoreInstalls.complete(app, folder, sidecar, onStep = { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) })
|
||||
val disk = result.optLong("diskBytes", 0L)
|
||||
if (disk > 0) prefs.edit().putLong("size_${item.id}", disk).apply()
|
||||
return folder.path
|
||||
}
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
if (deleteFiles) StoreInstalls.discard(app, folder, listOf(File(folder, ".chunks"), scratch()))
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
|
||||
object EpicLaunchData {
|
||||
private const val TAG = "EpicLaunch"
|
||||
|
||||
fun arguments(context: Context, token: String?, appName: String, namespace: String, catalogItemId: String, deploymentId: String): List<String> {
|
||||
val creds = EpicCredentialStore.load(context)
|
||||
val displayName = creds?.displayName?.takeIf { it.isNotEmpty() } ?: "EpicUser"
|
||||
val accountId = creds?.accountId?.takeIf { it.isNotEmpty() } ?: "0"
|
||||
val args = ArrayList<String>()
|
||||
args += "-EpicPortal"
|
||||
args += "-epicusername=\"${sanitize(displayName).replace("\"", "")}\""
|
||||
args += "-epicuserid=${sanitize(accountId)}"
|
||||
args += "-epicsandboxid=${sanitize(namespace)}"
|
||||
args += "-epiclocale=${EpicInstallTags.localeCodeForDevice()}"
|
||||
args += "-epicapp=${sanitize(appName)}"
|
||||
args += "-epicenv=Prod"
|
||||
if (deploymentId.isNotEmpty()) args += "-epicdeploymentid=${sanitize(deploymentId)}"
|
||||
if (token != null && catalogItemId.isNotEmpty()) {
|
||||
val extra = EpicApiClient.getAdditionalCommandLine(token, namespace, catalogItemId)
|
||||
if (!extra.isNullOrBlank()) {
|
||||
val clean = extra.filter { it >= ' ' && it != '\u007f' }.trim()
|
||||
if (clean.isNotEmpty()) { args += clean; Log.i(TAG, "$appName: extra command line present") }
|
||||
}
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
fun extras(appName: String, namespace: String, catalogItemId: String, deploymentId: String): Map<String, String> = buildMap {
|
||||
put("appName", appName); put("namespace", namespace); put("catalogItemId", catalogItemId)
|
||||
if (deploymentId.isNotEmpty()) put("deploymentId", deploymentId)
|
||||
}
|
||||
|
||||
fun wantsExchangeCode(sidecar: StoreGameSidecar): Boolean = sidecar.store == com.droiddeck.launcher.stores.Store.EPIC
|
||||
|
||||
private fun sanitize(s: String): String = s.replace("\n", "").replace("\r", "").replace("\u0000", "")
|
||||
}
|
||||
@@ -1,116 +1,180 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.cleanStoreText
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.net.URLEncoder
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
data class EpicGame(
|
||||
val appName: String,
|
||||
val namespace: String,
|
||||
val catalogItemId: String,
|
||||
val title: String,
|
||||
val artCover: String = "",
|
||||
val artSquare: String = "",
|
||||
val developer: String = "",
|
||||
val description: String = "",
|
||||
val version: String = "",
|
||||
val installSize: Long = 0L,
|
||||
val canRunOffline: Boolean = true,
|
||||
val releaseDate: String = "",
|
||||
val publisher: String = "",
|
||||
val isDlc: Boolean = false,
|
||||
)
|
||||
|
||||
object EpicLibrary {
|
||||
private const val TAG = "EpicLibrary"
|
||||
private const val CACHE_KEY = "library_cache"
|
||||
private const val LAST_SYNC_KEY = "library_synced_at"
|
||||
private const val THROTTLE_MS = 6L * 60L * 60L * 1000L
|
||||
const val KEY_CACHE = "library_cache"
|
||||
const val KEY_SYNCED_AT = "library_synced_at"
|
||||
private const val THROTTLE_MS = 6 * 60 * 60 * 1000L
|
||||
private const val MAX_SIZE = 1L shl 40
|
||||
|
||||
private val syncing = AtomicBoolean(false)
|
||||
|
||||
sealed interface SyncResult {
|
||||
class Ok(val games: List<EpicGame>) : SyncResult
|
||||
class Failed(val message: String) : SyncResult
|
||||
object NotLoggedIn : SyncResult
|
||||
object Busy : SyncResult
|
||||
object Throttled : SyncResult
|
||||
sealed class SyncResult {
|
||||
class Ok(val games: List<EpicGame>) : SyncResult()
|
||||
class Failed(val message: String) : SyncResult()
|
||||
object NotLoggedIn : SyncResult()
|
||||
object Throttled : SyncResult()
|
||||
object Busy : SyncResult()
|
||||
}
|
||||
|
||||
fun cached(context: Context): List<EpicGame> {
|
||||
val json = EpicPrefs.get(context).getString(CACHE_KEY, null) ?: return emptyList()
|
||||
return runCatching {
|
||||
val arr = JSONArray(json)
|
||||
val list = ArrayList<EpicGame>(arr.length())
|
||||
for (i in 0 until arr.length()) {
|
||||
val j = arr.optJSONObject(i) ?: continue
|
||||
val g = EpicGame()
|
||||
g.appName = j.optString("appName", ""); g.namespace = j.optString("namespace", ""); g.catalogItemId = j.optString("catalogItemId", "")
|
||||
g.title = j.optString("title", ""); g.artCover = j.optString("artCover", ""); g.artSquare = j.optString("artSquare", "")
|
||||
g.developer = j.optString("developer", ""); g.description = j.optString("description", ""); g.version = j.optString("version", "")
|
||||
g.installSize = j.optLong("installSize", 0L).let { if (it > 1_099_511_627_776L) 0L else it }
|
||||
g.canRunOffline = j.optBoolean("canRunOffline", true)
|
||||
g.releaseDate = j.optString("releaseDate", "")
|
||||
g.publisher = j.optString("publisher", "")
|
||||
if (g.appName.isNotEmpty()) list.add(g)
|
||||
}
|
||||
list.distinctBy { it.appName }.sortedBy { it.title.lowercase() }
|
||||
}.getOrDefault(emptyList())
|
||||
private val running = AtomicBoolean(false)
|
||||
|
||||
fun toCacheJson(games: List<EpicGame>): String = JSONArray().apply {
|
||||
for (g in games) put(
|
||||
JSONObject()
|
||||
.put("appName", g.appName).put("namespace", g.namespace).put("catalogItemId", g.catalogItemId)
|
||||
.put("title", g.title).put("artCover", g.artCover).put("artSquare", g.artSquare)
|
||||
.put("developer", g.developer).put("description", g.description).put("version", g.version)
|
||||
.put("installSize", g.installSize).put("canRunOffline", g.canRunOffline)
|
||||
.put("releaseDate", g.releaseDate).put("publisher", g.publisher),
|
||||
)
|
||||
}.toString()
|
||||
|
||||
fun fromCacheJson(text: String?): List<EpicGame> {
|
||||
if (text.isNullOrBlank()) return emptyList()
|
||||
val array = runCatching { JSONArray(text) }.getOrNull() ?: return emptyList()
|
||||
val games = (0 until array.length()).mapNotNull { array.optJSONObject(it) }.mapNotNull { o ->
|
||||
val appName = o.optString("appName", "").ifEmpty { return@mapNotNull null }
|
||||
EpicGame(
|
||||
appName = appName,
|
||||
namespace = o.optString("namespace", ""),
|
||||
catalogItemId = o.optString("catalogItemId", ""),
|
||||
title = o.optString("title", "").ifEmpty { appName },
|
||||
artCover = o.optString("artCover", ""),
|
||||
artSquare = o.optString("artSquare", ""),
|
||||
developer = o.optString("developer", ""),
|
||||
description = o.optString("description", ""),
|
||||
version = o.optString("version", ""),
|
||||
installSize = o.optLong("installSize", 0L).takeIf { it in 0..MAX_SIZE } ?: 0L,
|
||||
canRunOffline = o.optBoolean("canRunOffline", true),
|
||||
releaseDate = o.optString("releaseDate", ""),
|
||||
publisher = o.optString("publisher", ""),
|
||||
)
|
||||
}
|
||||
return tidy(games)
|
||||
}
|
||||
|
||||
fun rememberSize(context: Context, appName: String, bytes: Long) {
|
||||
if (bytes <= 0) return
|
||||
val p = EpicPrefs.get(context)
|
||||
p.edit().putLong("size_$appName", bytes).apply()
|
||||
private fun tidy(games: List<EpicGame>): List<EpicGame> =
|
||||
games.distinctBy { it.appName }.sortedBy { it.title.lowercase() }
|
||||
|
||||
fun cached(context: Context): List<EpicGame> = fromCacheJson(EpicPrefs.get(context).getString(KEY_CACHE, null))
|
||||
|
||||
fun forget(context: Context) {
|
||||
EpicPrefs.get(context).edit().remove(KEY_CACHE).remove(KEY_SYNCED_AT).apply()
|
||||
}
|
||||
|
||||
fun sync(context: Context, force: Boolean = false, onStatus: (String) -> Unit = {}): SyncResult {
|
||||
if (!syncing.compareAndSet(false, true)) return SyncResult.Busy
|
||||
fun toCatalogItem(context: Context, game: EpicGame): CatalogItem {
|
||||
val prefs = EpicPrefs.get(context)
|
||||
val wide = game.artSquare.ifEmpty { null }
|
||||
val tall = game.artCover.ifEmpty { null }
|
||||
val title = game.title.ifEmpty { game.appName }
|
||||
return CatalogItem(
|
||||
store = Store.EPIC,
|
||||
id = game.appName,
|
||||
title = title,
|
||||
imageUrl = wide ?: tall,
|
||||
tallImageUrl = tall ?: wide,
|
||||
developer = game.developer,
|
||||
publisher = game.publisher,
|
||||
releaseDate = game.releaseDate.ifEmpty { prefs.getString("release_${game.appName}", "").orEmpty() },
|
||||
description = cleanStoreText(game.description),
|
||||
owned = true,
|
||||
sizeBytes = prefs.getLong("size_${game.appName}", 0L).takeIf { it > 0 } ?: game.installSize,
|
||||
storeUrl = "https://store.epicgames.com/en-US/browse?q=" + URLEncoder.encode(title, "UTF-8"),
|
||||
extra = mapOf("namespace" to game.namespace, "catalogItemId" to game.catalogItemId, "version" to game.version),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun gameFrom(record: JSONObject, details: JSONObject?, before: EpicGame?): EpicGame {
|
||||
val appName = record.optString("appName")
|
||||
val d = details ?: JSONObject()
|
||||
fun pick(key: String, fallback: String) = d.optString(key, "").ifEmpty { fallback }
|
||||
return EpicGame(
|
||||
appName = appName,
|
||||
namespace = record.optString("namespace"),
|
||||
catalogItemId = record.optString("catalogItemId"),
|
||||
title = pick("title", before?.title?.takeIf { it != appName } ?: appName),
|
||||
artCover = pick("tall", before?.artCover.orEmpty()),
|
||||
artSquare = pick("wide", before?.artSquare.orEmpty()),
|
||||
developer = pick("developer", before?.developer.orEmpty()),
|
||||
description = pick("description", before?.description.orEmpty()),
|
||||
version = before?.version.orEmpty(),
|
||||
installSize = before?.installSize ?: 0L,
|
||||
canRunOffline = if (details != null) d.optBoolean("canRunOffline", true) else before?.canRunOffline ?: true,
|
||||
releaseDate = pick("releaseDate", before?.releaseDate.orEmpty()),
|
||||
publisher = pick("publisher", before?.publisher.orEmpty()),
|
||||
isDlc = d.optBoolean("dlc", false),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun visible(games: List<EpicGame>): List<EpicGame> {
|
||||
val base = games.filterNot { it.isDlc }
|
||||
return tidy(if (base.isEmpty()) games else base)
|
||||
}
|
||||
|
||||
fun sync(context: Context, force: Boolean, status: (String) -> Unit): SyncResult {
|
||||
if (!running.compareAndSet(false, true)) return SyncResult.Busy
|
||||
try {
|
||||
val app = context.applicationContext
|
||||
val p = EpicPrefs.get(app)
|
||||
val cachedList = cached(app)
|
||||
val lastSync = p.getLong(LAST_SYNC_KEY, 0L)
|
||||
if (!force && cachedList.isNotEmpty() && System.currentTimeMillis() - lastSync < THROTTLE_MS) return SyncResult.Throttled
|
||||
onStatus(app.getString(R.string.stores_sync_sign_in))
|
||||
val prefs = EpicPrefs.get(app)
|
||||
val cache = cached(app)
|
||||
status(app.getString(R.string.stores_sync_sign_in))
|
||||
if (!EpicCredentialStore.isLoggedIn(app)) return SyncResult.NotLoggedIn
|
||||
val syncedAt = prefs.getLong(KEY_SYNCED_AT, 0L)
|
||||
if (!force && cache.isNotEmpty() && System.currentTimeMillis() - syncedAt in 0 until THROTTLE_MS) return SyncResult.Throttled
|
||||
val token = EpicCredentialStore.getValidAccessToken(app) ?: return SyncResult.NotLoggedIn
|
||||
onStatus(app.getString(R.string.stores_sync_game_list))
|
||||
val raw = EpicApiClient.getLibraryItems(token)
|
||||
if (raw.isNullOrEmpty()) return if (cachedList.isEmpty()) SyncResult.Failed(app.getString(R.string.stores_sync_no_games, Store.EPIC.label)) else SyncResult.Ok(cachedList)
|
||||
val total = raw.size
|
||||
var done = 0
|
||||
for (game in raw) {
|
||||
EpicApiClient.enrichFromCatalog(token, game)
|
||||
done++
|
||||
if (done % 5 == 0) onStatus(app.getString(R.string.stores_sync_details, done, total))
|
||||
|
||||
status(app.getString(R.string.stores_sync_game_list))
|
||||
val answer = EpicNative.call("library.owned", JSONObject().put("accessToken", token))
|
||||
?: return SyncResult.Failed(app.getString(R.string.stores_sync_failed))
|
||||
if (answer.optBoolean("signIn", false)) return SyncResult.NotLoggedIn
|
||||
if (answer.has("error")) return SyncResult.Failed(answer.optString("error").ifEmpty { app.getString(R.string.stores_sync_failed) })
|
||||
val records = answer.optJSONArray("records") ?: JSONArray()
|
||||
if (records.length() == 0) {
|
||||
return if (cache.isNotEmpty()) SyncResult.Ok(cache)
|
||||
else SyncResult.Failed(app.getString(R.string.stores_sync_no_games, Store.EPIC.label))
|
||||
}
|
||||
val main = raw.filter { !it.isDLC }
|
||||
val display = (if (main.isEmpty()) raw else main).distinctBy { it.appName }.sortedWith { a, b -> a.title.compareTo(b.title, ignoreCase = true) }
|
||||
for (fresh in display) {
|
||||
val old = cachedList.firstOrNull { it.appName == fresh.appName } ?: continue
|
||||
fresh.version = old.version
|
||||
fresh.installSize = old.installSize
|
||||
|
||||
val before = cache.associateBy { it.appName }
|
||||
val total = records.length()
|
||||
val games = ArrayList<EpicGame>(total)
|
||||
for (i in 0 until total) {
|
||||
val record = records.optJSONObject(i) ?: continue
|
||||
if (i % 5 == 0) status(app.getString(R.string.stores_sync_details, i, total))
|
||||
val details = EpicApiClient.catalogDetails(token, record.optString("namespace"), record.optString("catalogItemId"))
|
||||
games += gameFrom(record, details, before[record.optString("appName")])
|
||||
}
|
||||
saveCache(p, display)
|
||||
p.edit().putLong(LAST_SYNC_KEY, System.currentTimeMillis()).apply()
|
||||
Log.i(TAG, "sync: raw=${raw.size} shown=${display.size}")
|
||||
return SyncResult.Ok(display)
|
||||
val shown = visible(games)
|
||||
prefs.edit().putString(KEY_CACHE, toCacheJson(shown)).putLong(KEY_SYNCED_AT, System.currentTimeMillis()).apply()
|
||||
return SyncResult.Ok(shown)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "sync failed: ${e.message}")
|
||||
return SyncResult.Failed(e.message ?: context.getString(R.string.stores_sync_failed))
|
||||
} finally {
|
||||
syncing.set(false)
|
||||
running.set(false)
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveCache(prefs: SharedPreferences, games: List<EpicGame>) {
|
||||
runCatching {
|
||||
val arr = JSONArray()
|
||||
for (g in games) arr.put(JSONObject().put("appName", g.appName).put("namespace", g.namespace).put("catalogItemId", g.catalogItemId)
|
||||
.put("title", g.title).put("artCover", g.artCover).put("artSquare", g.artSquare).put("developer", g.developer)
|
||||
.put("description", g.description).put("version", g.version).put("installSize", g.installSize).put("canRunOffline", g.canRunOffline)
|
||||
.put("releaseDate", g.releaseDate).put("publisher", g.publisher))
|
||||
prefs.edit().putString(CACHE_KEY, arr.toString()).apply()
|
||||
}
|
||||
}
|
||||
|
||||
fun toCatalogItem(context: Context, g: EpicGame): CatalogItem = CatalogItem(
|
||||
store = Store.EPIC, id = g.appName, title = g.title.ifBlank { g.appName },
|
||||
imageUrl = g.artSquare.ifBlank { null } ?: g.artCover.ifBlank { null },
|
||||
tallImageUrl = g.artCover.ifBlank { null } ?: g.artSquare.ifBlank { null },
|
||||
developer = g.developer, publisher = g.publisher, description = com.droiddeck.launcher.stores.cleanStoreText(g.description), owned = true,
|
||||
releaseDate = g.releaseDate.ifEmpty { EpicPrefs.get(context).getString("release_${g.appName}", "").orEmpty() },
|
||||
sizeBytes = EpicPrefs.get(context).getLong("size_${g.appName}", g.installSize),
|
||||
storeUrl = "https://store.epicgames.com/en-US/browse?q=${java.net.URLEncoder.encode(g.title, "UTF-8")}",
|
||||
extra = mapOf("namespace" to g.namespace, "catalogItemId" to g.catalogItemId, "version" to (g.version ?: "")),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import android.util.Log
|
||||
import android.webkit.WebView
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.StoreLoginActivity
|
||||
import org.json.JSONObject
|
||||
|
||||
internal class EpicLogin private constructor(
|
||||
override val startUrl: String,
|
||||
override val userAgent: String,
|
||||
private val redirectPrefix: String,
|
||||
) : StoreLoginActivity.Flow {
|
||||
override val readsPage: Boolean get() = true
|
||||
|
||||
override fun isRedirect(url: String): Boolean = url.startsWith(redirectPrefix)
|
||||
|
||||
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? {
|
||||
val code = EpicNative.call("auth.codeFromPage", JSONObject().put("text", url))?.optString("code", "").orEmpty()
|
||||
if (code.isEmpty()) {
|
||||
Log.w(TAG, "the redirect page carried no authorization code")
|
||||
return activity.getString(R.string.stores_login_error_verification)
|
||||
}
|
||||
val answer = EpicNative.call("auth.signIn", JSONObject().put("code", code))
|
||||
val tokens = answer?.let(EpicCredentialStore.TokenResult::from)
|
||||
if (tokens == null) {
|
||||
Log.w(TAG, "code exchange failed: ${answer?.optString("error").orEmpty().ifEmpty { "no answer" }}")
|
||||
return activity.getString(R.string.stores_login_error_generic)
|
||||
}
|
||||
return try {
|
||||
EpicCredentialStore.save(activity, tokens, merge = false)
|
||||
null
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "saving the sign-in failed: ${e.javaClass.simpleName}")
|
||||
activity.getString(R.string.stores_login_error_generic)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "EpicLogin"
|
||||
|
||||
fun create(): StoreLoginActivity.Flow? {
|
||||
val config = EpicNative.call("auth.config") ?: return null
|
||||
val start = config.optString("startUrl").ifEmpty { return null }
|
||||
val prefix = config.optString("redirectPrefix").ifEmpty { return null }
|
||||
return EpicLogin(start, config.optString("webViewUserAgent"), prefix)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,189 +1,130 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import com.droiddeck.launcher.stores.StoresNative
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
object EpicNative {
|
||||
private const val TAG = "EpicNative"
|
||||
private const val CANCEL_POLL_MS = 250L
|
||||
|
||||
interface Listener {
|
||||
fun onPlan(chunksTotal: Int, bytesTotal: Long, chunkDir: String)
|
||||
fun onProgress(bytesDone: Long, bytesTotal: Long, done: Int, total: Int)
|
||||
fun onLog(line: String)
|
||||
fun onComplete(success: Boolean, error: String, bytes: Long)
|
||||
}
|
||||
@Volatile private var configured = false
|
||||
|
||||
interface InstallListener : Listener {
|
||||
/** Synchronous approval before the first verified atomic replacement. False aborts. */
|
||||
fun beforeSwap(): Boolean
|
||||
}
|
||||
|
||||
/** One native budgeted fetch/assembly run. A loaded-engine failure is never a Java retry. */
|
||||
@JvmStatic
|
||||
fun installAdaptive(request: String, cancel: AtomicBoolean, listener: InstallListener): Result =
|
||||
drive("nativeInstallAdaptive", cancel, listener, strict = true) { inner ->
|
||||
nativeInstallAdaptive(request, inner)
|
||||
}
|
||||
|
||||
/** Callbacks from a [stream] run; every method is called on a native thread. */
|
||||
interface StreamListener {
|
||||
/** File bytes written so far (staging included), and the files verified and swapped in so far. */
|
||||
fun onStreamProgress(bytesWritten: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, filesBytes: Long)
|
||||
/** Engine log line (already in logcat under `EpicNative`). */
|
||||
fun onLog(line: String)
|
||||
/** Once, before the first file replaces its destination; false (or a throw) fails the run with nothing replaced. */
|
||||
fun onBeforeReplace(): Boolean
|
||||
/** Terminal; `bytes` = file bytes written. */
|
||||
fun onComplete(success: Boolean, error: String, bytes: Long)
|
||||
}
|
||||
|
||||
class Result(
|
||||
@JvmField val started: Boolean, @JvmField val success: Boolean, @JvmField val cancelled: Boolean,
|
||||
@JvmField val error: String, @JvmField val bytes: Long, @JvmField val done: Int, @JvmField val total: Int,
|
||||
)
|
||||
|
||||
private class Completion(val success: Boolean, val error: String, val bytes: Long)
|
||||
|
||||
@JvmStatic
|
||||
fun run(
|
||||
manifest: ByteArray, installDir: String, chunkCacheDir: String, cdnPrefixes: Array<String>, pendingFileIdx: IntArray, expectedChunks: Int, expectedBytes: Long,
|
||||
caBundlePath: String, maxWorkers: Int, processWorkers: Int, cancel: AtomicBoolean?, listener: Listener,
|
||||
): Result = drive("nativeStart", cancel, listener) { inner ->
|
||||
nativeStart(manifest, installDir, chunkCacheDir, cdnPrefixes, pendingFileIdx, expectedChunks, expectedBytes, caBundlePath, maxWorkers, processWorkers, inner)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun assemble(manifest: ByteArray, installDir: String, chunkCacheDir: String, fileIdx: IntArray, cancel: AtomicBoolean?, listener: Listener): Result =
|
||||
drive("nativeAssemble", cancel, listener) { inner -> nativeAssemble(manifest, installDir, chunkCacheDir, fileIdx, inner) }
|
||||
|
||||
/**
|
||||
* The adaptive install of the files [pendingFileIdx] (indices into the manifest's file list),
|
||||
* with at most [cacheBudget] bytes of shared chunks cached and at most [overlapBudget] planned
|
||||
* bytes of replaced files staged at once (`-1` = no limit), staged in [stagingDir] (the
|
||||
* manager's owned staging directory). `started == false` means nothing was fetched or written.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun stream(
|
||||
manifest: ByteArray, installDir: String, chunkCacheDir: String, stagingDir: String, cdnPrefixes: Array<String>, pendingFileIdx: IntArray, expectedBytes: Long,
|
||||
cacheBudget: Long, overlapBudget: Long, caBundlePath: String, maxWorkers: Int, processWorkers: Int, cancel: AtomicBoolean?, listener: StreamListener,
|
||||
): Result {
|
||||
if (!StoresNative.ensureLoaded()) return Result(false, false, false, "engine not built", 0L, 0, 0)
|
||||
val latch = CountDownLatch(1)
|
||||
val completion = AtomicReference<Completion?>(null)
|
||||
val doneRef = AtomicReference(0)
|
||||
val totalRef = AtomicReference(pendingFileIdx.size)
|
||||
val inner = object : StreamListener {
|
||||
override fun onStreamProgress(bytesWritten: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, filesBytes: Long) {
|
||||
doneRef.set(filesDone); totalRef.set(filesTotal)
|
||||
listener.onStreamProgress(bytesWritten, bytesTotal, filesDone, filesTotal, filesBytes)
|
||||
}
|
||||
override fun onLog(line: String) = listener.onLog(line)
|
||||
override fun onBeforeReplace(): Boolean = runCatching { listener.onBeforeReplace() }.getOrDefault(false)
|
||||
override fun onComplete(success: Boolean, error: String, bytes: Long) {
|
||||
completion.set(Completion(success, error, bytes))
|
||||
latch.countDown()
|
||||
runCatching { listener.onComplete(success, error, bytes) }
|
||||
fun ready(): Boolean {
|
||||
if (!StoresNative.ensureLoaded()) return false
|
||||
if (!configured) synchronized(this) {
|
||||
if (!configured) {
|
||||
runCatching { nativeConfigure(BuildConfig.VERSION_NAME) }
|
||||
.onFailure { Log.w(TAG, "configure: ${it.javaClass.simpleName}") }
|
||||
configured = true
|
||||
}
|
||||
}
|
||||
val handle: Long = try {
|
||||
nativeStream(manifest, installDir, chunkCacheDir, stagingDir, cdnPrefixes, pendingFileIdx, expectedBytes, cacheBudget, overlapBudget, caBundlePath, maxWorkers, processWorkers, inner)
|
||||
return true
|
||||
}
|
||||
|
||||
fun call(op: String, request: JSONObject = JSONObject()): JSONObject? {
|
||||
if (!ready()) return null
|
||||
val text = try {
|
||||
nativeCall(op, request.toString())
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "engine unavailable: ${t.javaClass.simpleName}: ${t.message}")
|
||||
return Result(false, false, false, "nativeStream: ${t.javaClass.simpleName}: ${t.message}", 0L, 0, 0)
|
||||
Log.w(TAG, "$op: ${t.javaClass.simpleName}")
|
||||
null
|
||||
} ?: return null
|
||||
return runCatching { JSONObject(text) }.getOrNull()
|
||||
}
|
||||
|
||||
fun fetch(op: String, request: JSONObject): ByteArray? {
|
||||
if (!ready()) return null
|
||||
return try {
|
||||
nativeFetch(op, request.toString())
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "$op: ${t.javaClass.simpleName}")
|
||||
null
|
||||
}
|
||||
if (handle == 0L) return Result(false, false, false, completion.get()?.error ?: "not started", 0L, 0, totalRef.get())
|
||||
var cancelSent = false
|
||||
}
|
||||
|
||||
fun send(op: String, request: JSONObject, body: ByteArray): JSONObject? {
|
||||
if (!ready()) return null
|
||||
val text = try {
|
||||
nativeSend(op, request.toString(), body)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "$op: ${t.javaClass.simpleName}")
|
||||
null
|
||||
} ?: return null
|
||||
return runCatching { JSONObject(text) }.getOrNull()
|
||||
}
|
||||
|
||||
fun inspect(manifest: ByteArray, request: JSONObject): JSONObject? {
|
||||
if (!ready()) return null
|
||||
val text = try {
|
||||
nativeInspect(manifest, request.toString())
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "inspect: ${t.javaClass.simpleName}")
|
||||
null
|
||||
} ?: return null
|
||||
return runCatching { JSONObject(text) }.getOrNull()
|
||||
}
|
||||
|
||||
interface InstallListener {
|
||||
fun onStatus(text: String)
|
||||
fun onCheck(doneBytes: Long, totalBytes: Long, files: Int, filesTotal: Int)
|
||||
fun onSizes(pendingBytes: Long, diskBytes: Long)
|
||||
fun onProgress(written: Long, total: Long, files: Int, filesTotal: Int)
|
||||
fun onInstall(done: Long, total: Long, files: Int, filesTotal: Int)
|
||||
fun onLog(line: String)
|
||||
fun beforeReplace(): Boolean
|
||||
fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String)
|
||||
}
|
||||
|
||||
class InstallOutcome(val success: Boolean, val cancelled: Boolean, val error: String, val result: JSONObject?)
|
||||
|
||||
fun install(request: JSONObject, events: InstallListener, cancelled: AtomicBoolean): InstallOutcome {
|
||||
if (!ready()) return InstallOutcome(false, false, "Native Epic install failed: the store engine is not available", null)
|
||||
val done = CountDownLatch(1)
|
||||
val holder = arrayOfNulls<InstallOutcome>(1)
|
||||
val bridge = object : InstallListener by events {
|
||||
override fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String) {
|
||||
holder[0] = 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 InstallOutcome(false, false, "Native Epic install failed: ${t.javaClass.simpleName}", null)
|
||||
}
|
||||
if (handle == 0L) return holder[0] ?: InstallOutcome(false, false, "Native Epic install failed: the install could not start", null)
|
||||
try {
|
||||
while (!latch.await(250, TimeUnit.MILLISECONDS)) {
|
||||
if (!cancelSent && cancel != null && cancel.get()) {
|
||||
var forwarded = false
|
||||
while (true) {
|
||||
val finished = try {
|
||||
done.await(CANCEL_POLL_MS, TimeUnit.MILLISECONDS)
|
||||
} catch (e: InterruptedException) {
|
||||
cancelled.set(true)
|
||||
false
|
||||
}
|
||||
if (finished) break
|
||||
if (!forwarded && cancelled.get()) {
|
||||
nativeCancel(handle)
|
||||
cancelSent = true
|
||||
forwarded = true
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (completion.get() == null) nativeCancel(handle)
|
||||
nativeRelease(handle)
|
||||
}
|
||||
val c = completion.get()
|
||||
val cancelled = cancelSent || (c != null && !c.success && c.error == "cancelled")
|
||||
val success = !cancelled && c != null && c.success
|
||||
val error = when { cancelled -> "cancelled"; c == null -> "no completion"; else -> c.error }
|
||||
return Result(true, success, cancelled, error, c?.bytes ?: 0L, doneRef.get(), totalRef.get())
|
||||
return holder[0] ?: InstallOutcome(false, false, "Native Epic install failed: no result", null)
|
||||
}
|
||||
|
||||
private fun drive(what: String, cancel: AtomicBoolean?, listener: Listener, strict: Boolean = false, start: (Listener) -> Long): Result {
|
||||
if (!StoresNative.ensureLoaded()) return Result(false, false, false, "engine not built", 0L, 0, 0)
|
||||
val latch = CountDownLatch(1)
|
||||
val completion = AtomicReference<Completion?>(null)
|
||||
val doneRef = AtomicReference(0)
|
||||
val totalRef = AtomicReference(0)
|
||||
val inner = object : InstallListener {
|
||||
override fun beforeSwap(): Boolean = (listener as? InstallListener)?.beforeSwap() ?: false
|
||||
override fun onPlan(chunksTotal: Int, bytesTotal: Long, chunkDir: String) { totalRef.set(chunksTotal); listener.onPlan(chunksTotal, bytesTotal, chunkDir) }
|
||||
override fun onProgress(bytesDone: Long, bytesTotal: Long, done: Int, total: Int) { doneRef.set(done); totalRef.set(total); listener.onProgress(bytesDone, bytesTotal, done, total) }
|
||||
override fun onLog(line: String) = listener.onLog(line)
|
||||
override fun onComplete(success: Boolean, error: String, bytes: Long) {
|
||||
completion.set(Completion(success, error, bytes))
|
||||
latch.countDown()
|
||||
runCatching { listener.onComplete(success, error, bytes) }
|
||||
}
|
||||
}
|
||||
val handle: Long = try {
|
||||
start(inner)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "${if (strict) "engine start failed (no fallback)" else "engine unavailable"}: ${t.javaClass.simpleName}: ${t.message}")
|
||||
return Result(strict, false, false, "$what: ${t.javaClass.simpleName}: ${t.message}", 0L, 0, 0)
|
||||
}
|
||||
if (handle == 0L) return Result(strict, false, false, completion.get()?.error ?: "not started", 0L, 0, totalRef.get())
|
||||
var cancelSent = false
|
||||
try {
|
||||
while (!latch.await(250, TimeUnit.MILLISECONDS)) {
|
||||
if (cancel != null && cancel.get()) {
|
||||
nativeCancel(handle)
|
||||
cancelSent = true
|
||||
if (strict) {
|
||||
while (!latch.await(250, TimeUnit.MILLISECONDS)) { }
|
||||
} else {
|
||||
latch.await(5, TimeUnit.SECONDS)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (completion.get() == null) nativeCancel(handle)
|
||||
nativeRelease(handle)
|
||||
}
|
||||
val c = completion.get()
|
||||
val success = !cancelSent && c != null && c.success
|
||||
val error = when { cancelSent -> "cancelled"; c == null -> "no completion"; else -> c.error }
|
||||
return Result(true, success, cancelSent, error, c?.bytes ?: 0L, doneRef.get(), totalRef.get())
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeInstallAdaptive(request: String, listener: Listener): Long
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeStart(
|
||||
manifest: ByteArray, installDir: String, chunkCacheDir: String, cdnPrefixes: Array<String>, pendingFileIdx: IntArray, expectedChunks: Int, expectedBytes: Long,
|
||||
caBundlePath: String, maxWorkers: Int, processWorkers: Int, listener: Listener,
|
||||
): Long
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeAssemble(manifest: ByteArray, installDir: String, chunkCacheDir: String, fileIdx: IntArray, listener: Listener): Long
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeStream(
|
||||
manifest: ByteArray, installDir: String, chunkCacheDir: String, stagingDir: String, cdnPrefixes: Array<String>, pendingFileIdx: IntArray, expectedBytes: Long,
|
||||
cacheBudget: Long, overlapBudget: Long, caBundlePath: String, maxWorkers: Int, processWorkers: Int, listener: StreamListener,
|
||||
): Long
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeCancel(handle: Long)
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeRelease(handle: Long)
|
||||
@JvmStatic private external fun nativeConfigure(appVersion: String)
|
||||
@JvmStatic private external fun nativeCall(op: String, request: String): String?
|
||||
@JvmStatic private external fun nativeFetch(op: String, request: String): ByteArray?
|
||||
@JvmStatic private external fun nativeSend(op: String, request: String, body: ByteArray): String?
|
||||
@JvmStatic private external fun nativeInspect(manifest: ByteArray, request: String): String?
|
||||
@JvmStatic private external fun nativeInstall(request: String, listener: InstallListener): Long
|
||||
@JvmStatic private external fun nativeCancel(handle: Long)
|
||||
@JvmStatic private external fun nativeRelease(handle: Long)
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
|
||||
object EpicPrefs {
|
||||
const val FILE = "stores.epic"
|
||||
|
||||
@JvmStatic
|
||||
fun get(context: Context): SharedPreferences = context.applicationContext.getSharedPreferences("stores.epic", Context.MODE_PRIVATE)
|
||||
fun get(context: Context): SharedPreferences = context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import com.droiddeck.launcher.stores.CloudFile
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.IOException
|
||||
|
||||
object EpicSaveSync {
|
||||
private fun base(token: String, accountId: String, appName: String) =
|
||||
JSONObject().put("accessToken", token).put("accountId", accountId).put("appName", appName)
|
||||
|
||||
fun list(token: String, accountId: String, appName: String): List<CloudFile> {
|
||||
val answer = EpicNative.call("cloud.list", base(token, accountId, appName)) ?: throw IOException("Epic cloud is unavailable")
|
||||
if (answer.has("error")) throw IOException(answer.optString("error"))
|
||||
val files = answer.optJSONArray("files") ?: return emptyList()
|
||||
return (0 until files.length()).mapNotNull { files.optJSONObject(it) }.map { f ->
|
||||
CloudFile(
|
||||
f.optString("name"),
|
||||
f.optLong("modified", -1L),
|
||||
md5 = f.optString("hash").ifEmpty { null },
|
||||
readLink = f.optString("readLink").ifEmpty { null },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun read(file: CloudFile): Pair<ByteArray, Long> {
|
||||
val link = file.readLink ?: throw IOException("no download link for ${file.name}")
|
||||
val bytes = EpicNative.fetch("cloud.read", JSONObject().put("url", link)) ?: throw IOException("Epic cloud download failed")
|
||||
return bytes to file.modifiedMs
|
||||
}
|
||||
|
||||
fun write(token: String, accountId: String, appName: String, files: Map<String, ByteArray>): Map<String, Long> {
|
||||
if (files.isEmpty()) return emptyMap()
|
||||
val answer = EpicNative.call("cloud.writeLinks", base(token, accountId, appName).put("names", JSONArray(files.keys.toList())))
|
||||
?: throw IOException("Epic cloud is unavailable")
|
||||
if (answer.has("error")) throw IOException(answer.optString("error"))
|
||||
val links = answer.optJSONObject("links") ?: JSONObject()
|
||||
return files.mapValues { (name, data) ->
|
||||
val link = links.optString(name, "").ifEmpty { throw IOException("no upload link for $name") }
|
||||
val sent = EpicNative.send("cloud.write", JSONObject().put("url", link), data) ?: throw IOException("Epic cloud upload failed")
|
||||
if (sent.has("error")) throw IOException(sent.optString("error"))
|
||||
-1L
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
object EpicSaveTemplate {
|
||||
enum class Root { INSTALL_DIR, USER_PROFILE, DOCUMENTS, SAVED_GAMES, LOCAL_APPDATA, ROAMING_APPDATA }
|
||||
|
||||
class Parsed(val root: Root, val rest: String)
|
||||
|
||||
private val ROOTS = mapOf(
|
||||
"installdir" to Root.INSTALL_DIR,
|
||||
"userprofile" to Root.USER_PROFILE,
|
||||
"userdir" to Root.DOCUMENTS,
|
||||
"usersavedgames" to Root.SAVED_GAMES,
|
||||
"appdata" to Root.LOCAL_APPDATA,
|
||||
"localappdata" to Root.LOCAL_APPDATA,
|
||||
"roamingappdata" to Root.ROAMING_APPDATA,
|
||||
)
|
||||
|
||||
private val LEAD = Regex("^\\{([A-Za-z]+)\\}")
|
||||
private val EPIC_ID = Regex("\\{EpicId\\}", RegexOption.IGNORE_CASE)
|
||||
private val APP_NAME = Regex("\\{AppName\\}", RegexOption.IGNORE_CASE)
|
||||
|
||||
fun parse(template: String, accountId: String, appName: String): Parsed? {
|
||||
val norm = template.replace('\\', '/').trim()
|
||||
val match = LEAD.find(norm) ?: return null
|
||||
val root = ROOTS[match.groupValues[1].lowercase()] ?: return null
|
||||
val rest = norm.substring(match.value.length)
|
||||
.replace(EPIC_ID) { accountId }
|
||||
.replace(APP_NAME) { appName }
|
||||
return Parsed(root, rest)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreShelves
|
||||
import com.droiddeck.launcher.stores.cleanStoreText
|
||||
import com.droiddeck.launcher.stores.matureByTags
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.Locale
|
||||
|
||||
object EpicShelves {
|
||||
const val KEY_FEATURED = "store_featured"
|
||||
const val KEY_FEATURED_AT = "store_featured_at"
|
||||
private const val FRESH_MS = 3 * 60 * 60 * 1000L
|
||||
private val SHELF_KEYS = listOf("new", "deals", "free", "trending")
|
||||
|
||||
@Volatile private var memory: StoreShelves? = null
|
||||
@Volatile private var memoryAt = 0L
|
||||
|
||||
private fun fresh(at: Long) = System.currentTimeMillis() - at in 0 until FRESH_MS
|
||||
|
||||
fun itemFrom(o: JSONObject): CatalogItem? {
|
||||
val id = o.optString("id", "").ifEmpty { return null }
|
||||
val title = o.optString("title", "").ifEmpty { return null }
|
||||
val extra = LinkedHashMap<String, String>()
|
||||
o.optJSONObject("extra")?.let { e -> e.keys().forEach { k -> extra[k] = e.optString(k) } }
|
||||
val mature = if (o.has("mature")) o.optBoolean("mature") else {
|
||||
val tags = o.optJSONArray("allTags")
|
||||
matureByTags(List(tags?.length() ?: 0) { tags!!.optString(it) })
|
||||
}
|
||||
return CatalogItem(
|
||||
store = Store.EPIC, id = id, title = title,
|
||||
imageUrl = o.optString("image", "").ifEmpty { null },
|
||||
tallImageUrl = o.optString("tall", "").ifEmpty { null },
|
||||
tags = o.optString("tags", ""),
|
||||
isFree = o.optBoolean("free", false),
|
||||
hasPrice = o.optBoolean("hasPrice", false),
|
||||
finalPrice = o.optString("final", ""),
|
||||
originalPrice = o.optString("orig", ""),
|
||||
discountPercent = o.optInt("disc", 0),
|
||||
storeUrl = o.optString("url", ""),
|
||||
developer = o.optString("dev", ""),
|
||||
publisher = o.optString("pub", ""),
|
||||
releaseDate = o.optString("rel", ""),
|
||||
description = cleanStoreText(o.optString("desc", "")),
|
||||
extra = extra,
|
||||
mature = mature,
|
||||
)
|
||||
}
|
||||
|
||||
fun itemJson(i: CatalogItem): JSONObject = JSONObject()
|
||||
.put("id", i.id).put("title", i.title).put("image", i.imageUrl ?: "").put("tall", i.tallImageUrl ?: "")
|
||||
.put("tags", i.tags).put("free", i.isFree).put("hasPrice", i.hasPrice).put("final", i.finalPrice)
|
||||
.put("orig", i.originalPrice).put("disc", i.discountPercent).put("url", i.storeUrl).put("dev", i.developer)
|
||||
.put("pub", i.publisher).put("rel", i.releaseDate).put("desc", i.description)
|
||||
.put("extra", JSONObject(i.extra as Map<*, *>)).put("mature", i.mature)
|
||||
|
||||
fun fromJson(text: String?): StoreShelves? {
|
||||
if (text.isNullOrBlank()) return null
|
||||
val o = runCatching { JSONObject(text) }.getOrNull() ?: return null
|
||||
fun shelf(key: String): List<CatalogItem> {
|
||||
val a = o.optJSONArray(key) ?: return emptyList()
|
||||
return (0 until a.length()).mapNotNull { a.optJSONObject(it) }.mapNotNull(::itemFrom).distinctBy { it.id }
|
||||
}
|
||||
val s = StoreShelves(shelf("new"), shelf("deals"), shelf("free"), shelf("trending"))
|
||||
return if (s.isEmpty) null else s
|
||||
}
|
||||
|
||||
fun toJson(s: StoreShelves): String = JSONObject().apply {
|
||||
listOf(s.whatsNew, s.deals, s.free, s.trending).zip(SHELF_KEYS).forEach { (items, key) ->
|
||||
put(key, JSONArray().apply { items.forEach { put(itemJson(it)) } })
|
||||
}
|
||||
}.toString()
|
||||
|
||||
fun cached(context: Context): StoreShelves? =
|
||||
memory ?: fromJson(EpicPrefs.get(context).getString(KEY_FEATURED, null))?.also { memory = it }
|
||||
|
||||
fun featured(context: Context, force: Boolean): StoreShelves? {
|
||||
val prefs = EpicPrefs.get(context)
|
||||
if (!force) {
|
||||
memory?.takeIf { fresh(memoryAt) }?.let { return it }
|
||||
if (fresh(prefs.getLong(KEY_FEATURED_AT, 0L))) fromJson(prefs.getString(KEY_FEATURED, null))?.let {
|
||||
memory = it; memoryAt = prefs.getLong(KEY_FEATURED_AT, 0L); return it
|
||||
}
|
||||
}
|
||||
val country = Locale.getDefault().country.takeIf { it.length == 2 && it.all(Char::isLetter) }?.uppercase() ?: "US"
|
||||
val answer = EpicNative.call("shop.shelves", JSONObject().put("country", country))
|
||||
val shelves = fromJson(answer?.toString())
|
||||
if (shelves == null) return fromJson(prefs.getString(KEY_FEATURED, null))
|
||||
val now = System.currentTimeMillis()
|
||||
prefs.edit().putString(KEY_FEATURED, toJson(shelves)).putLong(KEY_FEATURED_AT, now).apply()
|
||||
memory = shelves
|
||||
memoryAt = now
|
||||
return shelves
|
||||
}
|
||||
|
||||
fun markOwned(s: StoreShelves, library: List<CatalogItem>?): StoreShelves {
|
||||
if (library.isNullOrEmpty()) return s
|
||||
val byCatalogId = HashMap<String, CatalogItem>()
|
||||
for (item in library) item.extra["catalogItemId"]?.takeIf { it.isNotEmpty() }?.let { byCatalogId[it] = item }
|
||||
fun mark(list: List<CatalogItem>) = list.map { shelf ->
|
||||
val owned = shelf.extra["items"].orEmpty().split(',').map { it.trim() }.firstNotNullOfOrNull { byCatalogId[it] }
|
||||
?: return@map shelf
|
||||
owned.copy(
|
||||
imageUrl = shelf.imageUrl ?: owned.imageUrl,
|
||||
tallImageUrl = shelf.tallImageUrl ?: owned.tallImageUrl,
|
||||
developer = owned.developer.ifBlank { shelf.developer },
|
||||
publisher = owned.publisher.ifBlank { shelf.publisher },
|
||||
releaseDate = owned.releaseDate.ifBlank { shelf.releaseDate },
|
||||
)
|
||||
}
|
||||
return StoreShelves(mark(s.whatsNew), mark(s.deals), mark(s.free), mark(s.trending))
|
||||
}
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
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 org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.TimeZone
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
object EpicStoreCatalog {
|
||||
private const val TAG = "EpicStore"
|
||||
private const val GRAPHQL = "https://store.epicgames.com/graphql"
|
||||
private const val PROMOS = "https://store-site-backend-static-ipv4.ak.epicgames.com/freeGamesPromotions"
|
||||
private const val FEATURED_TTL_MS = 3 * 60 * 60 * 1000L
|
||||
private const val SEARCH_TTL_MS = 5 * 60 * 1000L
|
||||
private const val KEY_FEATURED = "store_featured"
|
||||
|
||||
private const val ELEMENT_FIELDS =
|
||||
"title id namespace description effectiveDate releaseDate offerType productSlug urlSlug " +
|
||||
"items{id namespace} keyImages{type url} seller{name} tags{name} customAttributes{key value} " +
|
||||
"catalogNs{mappings(pageType:\"productHome\"){pageSlug pageType}} " +
|
||||
"price(country:\$country){totalPrice{discountPrice originalPrice discount currencyCode " +
|
||||
"fmtPrice(locale:\$locale){originalPrice discountPrice}}}"
|
||||
|
||||
private class Cached<T>(val value: T, val at: Long)
|
||||
private var featuredCache: Cached<StoreShelves>? = null
|
||||
private val searchCache = ConcurrentHashMap<String, Cached<List<CatalogItem>>>()
|
||||
|
||||
private fun country(): String = Locale.getDefault().country.takeIf { it.length == 2 }?.uppercase(Locale.ROOT) ?: "US"
|
||||
|
||||
private fun nowIso(): String {
|
||||
val f = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
|
||||
f.timeZone = TimeZone.getTimeZone("UTC")
|
||||
return f.format(Date())
|
||||
}
|
||||
|
||||
private fun searchStore(count: Int, keywords: String? = null, sortBy: String = "relevancy", sortDir: String = "DESC", onSale: Boolean? = null, freeGame: Boolean? = null, releasedOnly: Boolean = false): List<CatalogItem> {
|
||||
val args = StringBuilder("category:\"games/edition/base\",count:\$count,country:\$country,locale:\$locale,sortBy:\$sortBy,sortDir:\$sortDir,allowCountries:\$country")
|
||||
if (keywords != null) args.append(",keywords:\$keywords")
|
||||
if (onSale != null) args.append(",onSale:$onSale")
|
||||
if (freeGame != null) args.append(",freeGame:$freeGame")
|
||||
if (releasedOnly) args.append(",releaseDate:\"[,${nowIso()}]\"")
|
||||
val query = "query q(\$count:Int,\$country:String!,\$locale:String,\$sortBy:String,\$sortDir:String" +
|
||||
(if (keywords != null) ",\$keywords:String" else "") + "){Catalog{searchStore($args){elements{$ELEMENT_FIELDS} paging{total}}}}"
|
||||
val vars = JSONObject().put("count", count).put("country", country()).put("locale", "en-US").put("sortBy", sortBy).put("sortDir", sortDir)
|
||||
if (keywords != null) vars.put("keywords", keywords)
|
||||
val resp = StoreNet.postJson(GRAPHQL, JSONObject().put("query", query).put("variables", vars).toString()) ?: return emptyList()
|
||||
val elements = runCatching { JSONObject(resp).optJSONObject("data")?.optJSONObject("Catalog")?.optJSONObject("searchStore")?.optJSONArray("elements") }
|
||||
.onFailure { Log.w(TAG, "searchStore parse failed: ${it.message}") }.getOrNull() ?: return emptyList()
|
||||
return parseElements(elements)
|
||||
}
|
||||
|
||||
private fun parseElements(arr: JSONArray): List<CatalogItem> {
|
||||
val out = ArrayList<CatalogItem>(arr.length())
|
||||
for (i in 0 until arr.length()) arr.optJSONObject(i)?.let { e -> parseElement(e)?.let { out.add(it) } }
|
||||
return out.distinctBy { it.id }
|
||||
}
|
||||
|
||||
fun parseElement(e: JSONObject): CatalogItem? {
|
||||
val id = e.optString("id", "")
|
||||
val title = e.optString("title", "")
|
||||
if (id.isEmpty() || title.isEmpty()) return null
|
||||
val ns = e.optString("namespace", "")
|
||||
var wide: String? = null; var tall: String? = null; var thumb: String? = null
|
||||
e.optJSONArray("keyImages")?.let { imgs ->
|
||||
for (k in 0 until imgs.length()) {
|
||||
val img = imgs.optJSONObject(k) ?: continue
|
||||
val url = img.optString("url", "")
|
||||
if (url.isBlank()) continue
|
||||
when (img.optString("type", "")) {
|
||||
"DieselGameBox" -> wide = url
|
||||
"OfferImageWide", "DieselStoreFrontWide" -> if (wide == null) wide = url
|
||||
"DieselGameBoxTall" -> tall = url
|
||||
"OfferImageTall", "DieselStoreFrontTall" -> if (tall == null) tall = url
|
||||
"Thumbnail" -> if (thumb == null) thumb = url
|
||||
}
|
||||
}
|
||||
}
|
||||
val price = e.optJSONObject("price")?.optJSONObject("totalPrice")
|
||||
val original = price?.optLong("originalPrice", -1L) ?: -1L
|
||||
val discounted = price?.optLong("discountPrice", -1L) ?: -1L
|
||||
val fmt = price?.optJSONObject("fmtPrice")
|
||||
val fmtOriginal = fmt?.optString("originalPrice", "").orEmpty()
|
||||
val fmtDiscount = fmt?.optString("discountPrice", "").orEmpty()
|
||||
val hasPrice = original >= 0 && discounted >= 0
|
||||
val isFree = hasPrice && discounted == 0L
|
||||
val discountPct = if (hasPrice && original > 0 && discounted < original) ((original - discounted) * 100 / original).toInt() else 0
|
||||
val finalPrice = when { isFree -> "Free"; fmtDiscount.isNotBlank() && fmtDiscount != "0" -> fmtDiscount; else -> fmtOriginal }
|
||||
val tagLine = buildList {
|
||||
e.optJSONArray("tags")?.let { tags -> for (t in 0 until tags.length()) { val n = tags.optJSONObject(t)?.optString("name").orEmpty(); if (n.isNotBlank() && n != "Windows" && size < 3) add(n) } }
|
||||
}.joinToString(", ")
|
||||
val allTags = buildList { e.optJSONArray("tags")?.let { t -> for (k in 0 until t.length()) t.optJSONObject(k)?.optString("name")?.let { add(it) } } }
|
||||
val itemIds = buildList {
|
||||
e.optJSONArray("items")?.let { items -> for (j in 0 until items.length()) items.optJSONObject(j)?.optString("id")?.takeIf { it.isNotBlank() }?.let { add(it) } }
|
||||
}
|
||||
val slug = pageSlugOf(e)
|
||||
val storeUrl = if (slug.isNotBlank()) "https://store.epicgames.com/en-US/p/$slug" else "https://store.epicgames.com/en-US/browse?q=${java.net.URLEncoder.encode(title, "UTF-8")}"
|
||||
return CatalogItem(
|
||||
store = Store.EPIC, id = id, title = title, imageUrl = wide ?: thumb, tallImageUrl = tall ?: thumb, tags = tagLine,
|
||||
isFree = isFree, hasPrice = hasPrice, finalPrice = finalPrice, originalPrice = if (discountPct > 0) fmtOriginal else "", discountPercent = discountPct,
|
||||
storeUrl = storeUrl, developer = attribute(e, "developerName"),
|
||||
publisher = attribute(e, "publisherName").ifEmpty { e.optJSONObject("seller")?.optString("name", "").orEmpty() },
|
||||
releaseDate = e.optString("releaseDate", e.optString("effectiveDate", "")), description = com.droiddeck.launcher.stores.cleanStoreText(e.optString("description", "")),
|
||||
extra = buildMap { put("namespace", ns); if (itemIds.isNotEmpty()) put("items", itemIds.joinToString(",")); if (slug.isNotBlank()) put("slug", slug) },
|
||||
mature = com.droiddeck.launcher.stores.matureByTags(allTags),
|
||||
)
|
||||
}
|
||||
|
||||
private fun attribute(e: JSONObject, key: String): String {
|
||||
val attrs = e.optJSONArray("customAttributes") ?: return ""
|
||||
return (0 until attrs.length()).mapNotNull { attrs.optJSONObject(it) }.firstOrNull { it.optString("key") == key }
|
||||
?.optString("value", "")?.trim().orEmpty()
|
||||
}
|
||||
|
||||
private fun pageSlugOf(e: JSONObject): String {
|
||||
e.optJSONObject("catalogNs")?.optJSONArray("mappings")?.let { m ->
|
||||
for (i in 0 until m.length()) { val map = m.optJSONObject(i) ?: continue; if (map.optString("pageType") == "productHome") { val s = map.optString("pageSlug", ""); if (s.isNotBlank()) return s } }
|
||||
}
|
||||
var slug = e.optString("productSlug", "")
|
||||
if (slug == "null") slug = ""
|
||||
return slug.removeSuffix("/home")
|
||||
}
|
||||
|
||||
fun featured(context: Context, force: Boolean = false): StoreShelves? {
|
||||
val now = System.currentTimeMillis()
|
||||
featuredCache?.let { if (!force && now - it.at < FEATURED_TTL_MS) return it.value }
|
||||
if (!force && now - EpicPrefs.get(context).getLong("store_featured_at", 0L) < FEATURED_TTL_MS) cachedFeatured(context)?.let { return it }
|
||||
val freeNow = fetchPromos()
|
||||
val onSale = searchStore(24, sortBy = "currentPrice", sortDir = "ASC", onSale = true).filter { it.discountPercent > 0 }
|
||||
val newest = searchStore(24, sortBy = "releaseDate", sortDir = "DESC", releasedOnly = true)
|
||||
val freeToPlay = searchStore(24, sortBy = "relevancy", sortDir = "DESC", freeGame = true)
|
||||
val result = StoreShelves(whatsNew = newest, deals = onSale, free = (freeNow + freeToPlay).distinctBy { it.id }, trending = searchStore(24, sortBy = "relevancy", sortDir = "DESC", releasedOnly = true))
|
||||
if (!result.isEmpty) {
|
||||
featuredCache = Cached(result, now)
|
||||
persist(context, result)
|
||||
Log.i(TAG, "shelves: freeNow=${freeNow.size} sale=${onSale.size} new=${newest.size} f2p=${freeToPlay.size}")
|
||||
return result
|
||||
}
|
||||
Log.w(TAG, "every store feed came back empty; using the on-disk mirror")
|
||||
return loadPersisted(context)
|
||||
}
|
||||
|
||||
fun cachedFeatured(context: Context): StoreShelves? = featuredCache?.value ?: loadPersisted(context)
|
||||
|
||||
fun search(query: String): List<CatalogItem> {
|
||||
val term = query.trim()
|
||||
if (term.length < 2) return emptyList()
|
||||
val key = term.lowercase(Locale.ROOT)
|
||||
val now = System.currentTimeMillis()
|
||||
searchCache[key]?.let { if (now - it.at < SEARCH_TTL_MS) return it.value }
|
||||
val results = searchStore(30, keywords = term)
|
||||
searchCache[key] = Cached(results, now)
|
||||
return results
|
||||
}
|
||||
|
||||
private fun fetchPromos(): List<CatalogItem> {
|
||||
val body = StoreNet.get("$PROMOS?locale=en-US&country=${country()}&allowCountries=${country()}") ?: return emptyList()
|
||||
return runCatching {
|
||||
val elements = JSONObject(body).optJSONObject("data")?.optJSONObject("Catalog")?.optJSONObject("searchStore")?.optJSONArray("elements") ?: JSONArray()
|
||||
val out = ArrayList<CatalogItem>()
|
||||
for (i in 0 until elements.length()) {
|
||||
val el = elements.optJSONObject(i) ?: continue
|
||||
val current = el.optJSONObject("promotions")?.optJSONArray("promotionalOffers")
|
||||
if (current == null || current.length() == 0) continue
|
||||
val inner = current.optJSONObject(0)?.optJSONArray("promotionalOffers") ?: continue
|
||||
if (inner.length() == 0) continue
|
||||
val discount = inner.optJSONObject(0)?.optJSONObject("discountSetting")
|
||||
if (discount == null || discount.optInt("discountPercentage", -1) != 0) continue
|
||||
val end = inner.optJSONObject(0)?.optString("endDate", "").orEmpty()
|
||||
val base = parseElement(el) ?: continue
|
||||
out.add(base.copy(isFree = true, hasPrice = true, finalPrice = "Free", originalPrice = base.originalPrice.ifBlank {
|
||||
el.optJSONObject("price")?.optJSONObject("totalPrice")?.optJSONObject("fmtPrice")?.optString("originalPrice", "").orEmpty()
|
||||
}, discountPercent = 100, tags = if (end.length >= 10) "Free until ${end.take(10)}" else base.tags))
|
||||
}
|
||||
out.distinctBy { it.id }
|
||||
}.onFailure { Log.w(TAG, "promos parse failed: ${it.message}") }.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
private fun itemToJson(i: CatalogItem): JSONObject = JSONObject().apply {
|
||||
put("id", i.id); put("title", i.title); put("image", i.imageUrl ?: ""); put("tall", i.tallImageUrl ?: ""); put("tags", i.tags)
|
||||
put("free", i.isFree); put("hasPrice", i.hasPrice); put("final", i.finalPrice); put("orig", i.originalPrice); put("disc", i.discountPercent)
|
||||
put("url", i.storeUrl); put("dev", i.developer); put("pub", i.publisher); put("rel", i.releaseDate); put("desc", i.description); put("extra", JSONObject(i.extra as Map<*, *>))
|
||||
if (i.mature) put("mature", true)
|
||||
}
|
||||
|
||||
private fun itemFromJson(o: JSONObject): CatalogItem {
|
||||
val extra = HashMap<String, String>()
|
||||
o.optJSONObject("extra")?.let { e -> e.keys().forEach { k -> extra[k] = e.optString(k) } }
|
||||
return CatalogItem(
|
||||
store = Store.EPIC, id = o.optString("id"), title = o.optString("title"), imageUrl = o.optString("image").ifBlank { null }, tallImageUrl = o.optString("tall").ifBlank { null },
|
||||
tags = o.optString("tags"), isFree = o.optBoolean("free"), hasPrice = o.optBoolean("hasPrice"), finalPrice = o.optString("final"), originalPrice = o.optString("orig"),
|
||||
discountPercent = o.optInt("disc"), storeUrl = o.optString("url"), developer = o.optString("dev"), publisher = o.optString("pub"), releaseDate = o.optString("rel"), description = o.optString("desc"), extra = extra,
|
||||
mature = o.optBoolean("mature"),
|
||||
)
|
||||
}
|
||||
|
||||
private fun listToJson(l: List<CatalogItem>) = JSONArray().apply { l.forEach { put(itemToJson(it)) } }
|
||||
private fun listFromJson(a: JSONArray?): List<CatalogItem> = if (a == null) emptyList() else List(a.length()) { a.optJSONObject(it) }.filterNotNull().map(::itemFromJson)
|
||||
|
||||
private fun persist(context: Context, f: StoreShelves) {
|
||||
runCatching {
|
||||
EpicPrefs.get(context).edit().putString(KEY_FEATURED, JSONObject().put("new", listToJson(f.whatsNew)).put("deals", listToJson(f.deals)).put("free", listToJson(f.free)).put("trending", listToJson(f.trending)).toString()).putLong("store_featured_at", System.currentTimeMillis()).apply()
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadPersisted(context: Context): StoreShelves? = runCatching {
|
||||
val s = EpicPrefs.get(context).getString(KEY_FEATURED, null) ?: return null
|
||||
val o = JSONObject(s)
|
||||
StoreShelves(listFromJson(o.optJSONArray("new")), listFromJson(o.optJSONArray("deals")), listFromJson(o.optJSONArray("free")), listFromJson(o.optJSONArray("trending"))).takeIf { !it.isEmpty }
|
||||
}.getOrNull()
|
||||
}
|
||||
@@ -58,7 +58,8 @@ import com.droiddeck.launcher.stores.formatBytes
|
||||
|
||||
|
||||
@Composable
|
||||
internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: FrontEndActions, onBack: () -> Unit) {
|
||||
internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: FrontEndActions, lead: androidx.compose.ui.focus.FocusRequester, onBack: () -> Unit) {
|
||||
val leadOn = Modifier.focusRequester(lead)
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
@@ -117,19 +118,19 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
ActionChip(stringResource(R.string.stores_in_steam), ok = true)
|
||||
val gone = StoresState.uninstalling["${store.id}:$id"]
|
||||
if (gone != null) SecondaryButton(stringResource(R.string.stores_uninstalling), enabled = false, progress = gone) {}
|
||||
else UninstallButton(title, installed, enabled = download == null) {
|
||||
else UninstallButton(title, installed, enabled = download == null, modifier = leadOn) {
|
||||
StoresState.uninstall(ctx, installed) { StoresState.refresh(ctx); a.onLibraryChanged() }
|
||||
}
|
||||
}
|
||||
download != null -> {
|
||||
ActionChip(downloadLabel(download), ok = false)
|
||||
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { com.droiddeck.launcher.stores.download.DownloadQueue.pause(download.key) }
|
||||
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true) { com.droiddeck.launcher.stores.download.DownloadQueue.resume(ctx, download.key) }
|
||||
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { com.droiddeck.launcher.stores.download.DownloadQueue.pause(download.key) }
|
||||
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { com.droiddeck.launcher.stores.download.DownloadQueue.resume(ctx, download.key) }
|
||||
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { com.droiddeck.launcher.stores.download.DownloadQueue.cancel(ctx, download.key) }
|
||||
}
|
||||
failedDownload != null -> {
|
||||
ActionChip(stringResource(R.string.stores_dl_failed), ok = false)
|
||||
PrimaryButton(stringResource(R.string.stores_dl_resume), main = true) {
|
||||
PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) {
|
||||
if (item != null) StoresState.requestInstall(ctx, item)
|
||||
else com.droiddeck.launcher.stores.download.DownloadQueue.retry(ctx, failedDownload.key)
|
||||
}
|
||||
@@ -138,14 +139,15 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
}
|
||||
}
|
||||
item?.owned == true && StoresState.isUnfinished(item) -> {
|
||||
InstallButton(stringResource(R.string.stores_resume_install)) { StoresState.requestInstall(ctx, item) }
|
||||
InstallButton(stringResource(R.string.stores_resume_install), leadOn) { StoresState.requestInstall(ctx, item) }
|
||||
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
|
||||
}
|
||||
item?.owned == true -> InstallButton(
|
||||
if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install),
|
||||
leadOn,
|
||||
) { StoresState.requestInstall(ctx, item) }
|
||||
item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true) { openStoreUrl(ctx, item) }
|
||||
item != null -> PrimaryButton(if (item.hasPrice && item.finalPrice.isNotBlank()) stringResource(R.string.stores_buy_price, item.finalPrice) else stringResource(R.string.stores_view_on, store.shortLabel), main = true) { openStoreUrl(ctx, item) }
|
||||
item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
|
||||
item != null -> PrimaryButton(if (item.hasPrice && item.finalPrice.isNotBlank()) stringResource(R.string.stores_buy_price, item.finalPrice) else stringResource(R.string.stores_view_on, store.shortLabel), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
|
||||
}
|
||||
BusyChip(s)
|
||||
}
|
||||
@@ -221,7 +223,7 @@ private fun StoreAbout(text: String, height: Dp, modifier: Modifier = Modifier)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun UninstallButton(title: String, game: com.droiddeck.launcher.stores.InstalledStoreGame, enabled: Boolean, onUninstall: () -> Unit) {
|
||||
private fun UninstallButton(title: String, game: com.droiddeck.launcher.stores.InstalledStoreGame, enabled: Boolean, modifier: Modifier = Modifier, onUninstall: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
|
||||
val heading = stringResource(R.string.stores_uninstall_title, title)
|
||||
@@ -230,7 +232,7 @@ private fun UninstallButton(title: String, game: com.droiddeck.launcher.stores.I
|
||||
val keep = stringResource(R.string.stores_notification_keep)
|
||||
val remove = stringResource(R.string.stores_uninstall)
|
||||
Box(Modifier.onGloballyPositioned { placed[0] = it }) {
|
||||
SecondaryButton(remove, enabled = enabled) {
|
||||
SecondaryButton(remove, enabled = enabled, modifier = modifier) {
|
||||
val at = placed[0]?.takeIf { it.isAttached }?.boundsInRoot() ?: return@SecondaryButton
|
||||
var confirmed = false
|
||||
StoresMotion.ask(StepAsk(anchor = at, side = StepSide.Right, accent = colors.error, items = 3, pillCorner = 12.dp, maxWidth = 340.dp,
|
||||
@@ -249,10 +251,10 @@ private fun UninstallButton(title: String, game: com.droiddeck.launcher.stores.I
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InstallButton(label: String, onInstall: () -> Unit) {
|
||||
private fun InstallButton(label: String, modifier: Modifier = Modifier, onInstall: () -> Unit) {
|
||||
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
|
||||
Box(Modifier.onGloballyPositioned { placed[0] = it }) {
|
||||
PrimaryButton(label, main = true) {
|
||||
PrimaryButton(label, main = true, modifier = modifier) {
|
||||
StoresMotion.markInstall(placed[0]?.takeIf { it.isAttached }?.boundsInRoot(), label)
|
||||
onInstall()
|
||||
}
|
||||
|
||||
@@ -171,6 +171,8 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
|
||||
var focusMove by remember { mutableStateOf<Pair<String, Int>?>(null) }
|
||||
var lastOpened by remember { mutableStateOf<String?>(null) }
|
||||
val heroFocus = remember { androidx.compose.ui.focus.FocusRequester() }
|
||||
var detailFocused by remember { mutableStateOf(false) }
|
||||
fun move(kind: String) { focusMove = kind to (focusMove?.second ?: 0) + 1 }
|
||||
fun open(key: String) { lastOpened = key; openGame = key; move("detail") }
|
||||
fun closeGame() { openGame = null; move("card") }
|
||||
@@ -238,8 +240,6 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
fun target(): Pair<androidx.compose.ui.focus.FocusRequester, String?>? {
|
||||
val kind = focusMove?.first
|
||||
return when {
|
||||
openGame != null -> if (ff.primaryAttached > 0) ff.primary to FrontFocus.PRIMARY
|
||||
else "back:${store?.label}".let { id -> ff.items[id]?.takeIf { attached(id) }?.let { it to id } }
|
||||
kind == "card" -> lastOpened?.let { "card:$it" }?.let { id -> ff.items[id]?.takeIf { attached(id) }?.let { it to id } }
|
||||
?: ff.firstTile.takeIf { ff.firstTileAttached > 0 }?.let { it to null }
|
||||
kind == "first" -> ff.firstTile.takeIf { ff.firstTileAttached > 0 }?.let { it to null }
|
||||
@@ -250,6 +250,16 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
}
|
||||
}
|
||||
repeat(60) { if (!HeldKeys.confirm) return@repeat; androidx.compose.runtime.withFrameNanos { } }
|
||||
if (openGame != null) {
|
||||
val back = "back:${ctx.getString(R.string.common_back)}"
|
||||
repeat(45) { n ->
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
if (detailFocused) return@LaunchedEffect
|
||||
val req = if (n < 20) heroFocus else ff.items[back]?.takeIf { attached(back) } ?: heroFocus
|
||||
runCatching { req.requestFocus() }
|
||||
}
|
||||
return@LaunchedEffect
|
||||
}
|
||||
repeat(45) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
val (req, id) = target() ?: return@repeat
|
||||
@@ -374,7 +384,12 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { } }
|
||||
.verticalScroll(detailScroll).padding(top = 4.dp, bottom = 16.dp),
|
||||
) {
|
||||
if (detailStore != null) Column(Modifier.fillMaxWidth().focusGroup()) { StoreGameDetail(detailStore, key, s, a, onBack = { closeGame() }) }
|
||||
if (detailStore != null) Column(
|
||||
Modifier.fillMaxWidth()
|
||||
.onFocusChanged { detailFocused = it.hasFocus }
|
||||
.focusProperties { exit = { if (coveringNow.value) androidx.compose.ui.focus.FocusRequester.Cancel else androidx.compose.ui.focus.FocusRequester.Default } }
|
||||
.focusGroup(),
|
||||
) { StoreGameDetail(detailStore, key, s, a, heroFocus, onBack = { closeGame() }) }
|
||||
}
|
||||
}
|
||||
val from = detailFrom
|
||||
|
||||
Reference in new issue
Block a user