diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreExe.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreExe.kt new file mode 100644 index 0000000000..f1a97541b4 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreExe.kt @@ -0,0 +1,44 @@ +package com.droiddeck.launcher.stores + +import java.io.File + +/** + * Which .exe in an install folder is the game. The store's own hint (a manifest's launch + * executable) wins when the file exists; else the candidates, helpers and installers left out, + * the one named most like the title first, then the shallowest. Relative to the folder, forward + * slashes; "" when the folder has none. + */ +object StoreExe { + private val SKIP = listOf("redist", "unins", "setup", "crash", "report", "helper", "dotnet", "vcredist", "directx", "eac", "easyanticheat", "battleye", "launcher", "updater", "config") + + fun pick(folder: File, hint: String?, title: String): String { + val hinted = hint?.takeIf { it.isNotBlank() }?.replace('\\', '/')?.trimStart('/')?.let { File(folder, it) } + if (hinted != null && hinted.isFile) return relative(folder, hinted) + val candidates = ArrayList() + collect(folder, candidates, 0) + if (candidates.isEmpty()) return "" + val key = title.lowercase().replace(Regex("[^a-z0-9]"), "") + val best = candidates.firstOrNull { f -> + val n = f.nameWithoutExtension.lowercase().replace(Regex("[^a-z0-9]"), "") + n.isNotEmpty() && (n == key || (key.length >= 4 && key.startsWith(n)) || (n.length >= 4 && n.startsWith(key))) + } ?: candidates.sortedWith(compareBy { depth(folder, it) }.thenByDescending { it.length() }).first() + return relative(folder, best) + } + + private fun collect(dir: File, out: MutableList, depth: Int) { + if (depth > 4) return + val files = dir.listFiles() ?: return + for (f in files) { + if (f.isFile && f.name.endsWith(".exe", ignoreCase = true)) { + val lower = f.name.lowercase() + if (SKIP.none { lower.contains(it) }) out.add(f) + } + } + for (f in files) if (f.isDirectory && !f.name.startsWith(".")) collect(f, out, depth + 1) + } + + private fun depth(root: File, f: File): Int = relative(root, f).count { it == '/' } + + fun relative(root: File, f: File): String = + f.absolutePath.removePrefix(root.absolutePath).trimStart('/').replace('\\', '/') +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicApiClient.java b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicApiClient.java new file mode 100644 index 0000000000..6cd453639b --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicApiClient.java @@ -0,0 +1,191 @@ +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; + +/** + * Epic's library, catalog and launcher-assets services, as the launcher calls them: + * library-service.live.use1a.on.epicgames.com/library/api/public/items (owned items, paginated) + * catalog-public-service-prod06.ol.epicgames.com/catalog/api/shared/namespace/{ns}/bulk/items + * launcher-public-service-prod06.ol.epicgames.com/launcher/api/public/assets/v2/platform/Windows/... + * All with a bearer token. + */ +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() {} + + /** The owned games, every page; Unreal assets, private sandboxes and non-Windows items left out. */ + public static List getLibraryItems(String accessToken) { + List 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; + } + + /** Fills title, developer, art, description and the DLC flag from the catalog; true on success. */ + 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")); + } + 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; + } + } + + /** + * The manifest API answer for a game, flattened to {"manifests": [...], "versionId": "..."} as + * the download manager reads it. {@code appName} is the library record's, not the catalog's. + */ + 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); + // The sidecar's EOS deployment id, when the app has one. + 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; + } + } + + /** `customAttributes.AdditionalCommandLine.value` for the game, "" when it has none, null when the call failed. */ + public static String getAdditionalCommandLine(String accessToken, String namespace, String catalogItemId) { + 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("AdditionalCommandLine"); + return attr == null ? "" : attr.optString("value", ""); + } catch (Exception e) { + Log.w(TAG, "additional command line: " + 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(); + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicAuthClient.java b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicAuthClient.java new file mode 100644 index 0000000000..fef64d7dfd --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicAuthClient.java @@ -0,0 +1,180 @@ +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; + +/** + * Epic's OAuth2 token endpoint, with the launcher's public client credentials (the ones every + * third-party Epic client uses): + * POST account-public-service-prod03.ol.epicgames.com/account/api/oauth/token + * Basic base64(clientId:clientSecret), form grant_type=authorization_code|refresh_token, token_type=eg1 + * GET .../account/api/oauth/exchange with a bearer token: a short-lived exchange code for a launch. + * Error bodies are never logged: they carry correlation ids and account context. + */ +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; + } + } + + /** A short-lived exchange code for a game launch (-AUTH_PASSWORD); null on any failure. */ + public static String getExchangeCode(String accessToken) { + try { + String resp = getRequest(EXCHANGE_URL, accessToken); + if (resp == null) return null; + return new JSONObject(resp).optString("code", null); + } catch (Exception e) { + Log.e(TAG, "exchange code failed: " + e.getClass().getSimpleName()); + return null; + } + } + + /** Authorized GET; the body or 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(); + } + } + + /** Authorized GET of raw bytes (the manifest binary). */ + 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(); + } + + /** "2026-03-29T12:00:00.000Z" to epoch millis, without java.time. */ + 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; + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt new file mode 100644 index 0000000000..244ce3fd98 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt @@ -0,0 +1,169 @@ +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.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 + +/** Epic Games in the Stores section: sign-in, the library, the public store, installs and the per-launch sign-in code. */ +object EpicBackend : StoreBackend, EpicLaunchSupport { + private const val TAG = "EpicBackend" + override val store: Store = Store.EPIC + + init { LoginFlows.epicFlow = { LoginFlow } } + + override fun signIn(context: Context) { + context.startActivity(Intent(context, StoreLoginActivity::class.java).putExtra(StoreLoginActivity.EXTRA_STORE, store.id).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } + + override fun signOut(context: Context) { + EpicPrefs.get(context).edit().remove("library_cache").remove("library_synced_at").apply() + } + + override fun syncLibrary(context: Context, force: Boolean) { + val app = context.applicationContext + val cached = EpicLibrary.cached(app) + if (cached.isNotEmpty()) StoresState.post { StoresState.library[store] = cached.map { EpicLibrary.toCatalogItem(app, it) } } + StoresState.post { StoresState.status[store] = "Fetching your library…" } + Thread({ + val result = EpicLibrary.sync(app, force) { line -> StoresState.post { StoresState.status[store] = line } } + StoresState.post { + StoresState.status.remove(store) + when (result) { + is EpicLibrary.SyncResult.Ok -> { 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] = "Epic session expired: sign in again." + EpicLibrary.SyncResult.Throttled -> if (!StoresState.library.containsKey(store)) StoresState.library[store] = cached.map { EpicLibrary.toCatalogItem(app, it) } + EpicLibrary.SyncResult.Busy -> {} + } + } + }, "epic-sync").start() + } + + override fun loadShelves(context: Context, force: Boolean) { + val app = context.applicationContext + EpicStoreCatalog.cachedFeatured(app)?.let { StoresState.post { StoresState.shelves[store] = markOwned(it) } } + Thread({ + val shelves = EpicStoreCatalog.featured(app, force) + StoresState.post { if (shelves != null) StoresState.shelves[store] = markOwned(shelves) } + }, "epic-shelves").start() + } + + /** Store offers whose catalog item is in the library are owned: their cards offer Install under the library's id. */ + private fun markOwned(s: StoreShelves): StoreShelves { + val owned = StoresState.library[store] ?: return s + val byCatalogItem = owned.associateBy { it.extra["catalogItemId"] ?: "" } + fun mark(l: List) = 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) else i + } + return StoreShelves(mark(s.whatsNew), mark(s.deals), mark(s.free), mark(s.trending)) + } + + override fun install(context: Context, item: CatalogItem) { + 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 } + val entry = DownloadEntry(store, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes) + DownloadQueue.enqueue(app, entry) { InstallJob(app, item, namespace, catalogItemId) } + } + + override fun uninstall(context: Context, game: InstalledStoreGame) {} + + /** A fresh exchange code for the signed-in account; null when signed out or offline. Blocking. */ + override fun exchangeCode(context: Context): String? { + val token = EpicCredentialStore.getValidAccessToken(context) ?: return null + return EpicAuthClient.getExchangeCode(token) + } + + private class InstallJob(val app: Context, val item: CatalogItem, val namespace: String, val catalogItemId: String) : DownloadQueue.DownloadJob { + private val cancelled = AtomicBoolean(false) + private val folder: File = StoreInstallRoot.folderFor(app, Store.EPIC, item.id, item.title) + + override fun run(handle: DownloadQueue.JobHandle): String? { + handle.stage(DownloadStage.MANIFEST, "Checking sign-in…") + val token = EpicCredentialStore.getValidAccessToken(app) ?: throw EpicDownloadManager.InstallException("Not signed in to Epic Games") + 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, 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("Verifying") -> handle.stage(DownloadStage.VERIFY, message) + else -> handle.stage(DownloadStage.MANIFEST, message) + } + } + override fun onBytes(done: Long, total: Long, speedBps: Long) { handle.progress(done, total, null, speedBps) } + override fun onLog(line: String) { handle.log(line) } + }) ?: return null + if (cancelled.get()) return null + handle.stage(DownloadStage.INSTALL, "Registering with Steam…") + 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), + ) + StoreInstalls.complete(app, folder, sidecar) + return folder.path + } + + override fun cancel(deleteFiles: Boolean) { + cancelled.set(true) + if (deleteFiles) Thread({ StoreInstalls.deleteTree(folder) }, "epic-cancel-clean").start() + } + } + + /** + * Epic's web sign-in: the login page redirects to a JSON page carrying an authorization code, + * read out of the document and exchanged for tokens. + */ + 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? { + // The document's text comes JSON-quoted from evaluateJavascript. + 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 + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicCredentialStore.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicCredentialStore.kt new file mode 100644 index 0000000000..3fea58fd41 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicCredentialStore.kt @@ -0,0 +1,55 @@ +package com.droiddeck.launcher.stores.epic + +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreAccounts +import org.json.JSONObject + +/** + * The Epic sign-in in StoreAccounts' private file: access and refresh tokens, the account id and + * display name (the launch arguments carry both), the expiry. Refreshed when within five minutes + * of expiring. + */ +object EpicCredentialStore { + private const val TAG = "EpicAuth" + + 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) + } + + @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)) + } + + @JvmStatic + fun isLoggedIn(context: Context): Boolean = load(context) != null + + /** A valid access token, refreshed when within five minutes of expiry; null when signed out or the refresh failed. */ + @JvmStatic + fun getValidAccessToken(context: Context): String? { + val creds = load(context) ?: return null + if (creds.expiresAt - System.currentTimeMillis() < 5L * 60L * 1000L && creds.refreshToken != null) { + val result = 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 + } + Log.w(TAG, "token refresh failed; using the stored token") + } + return creds.accessToken + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicDownloadManager.java b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicDownloadManager.java new file mode 100644 index 0000000000..734a813abf --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicDownloadManager.java @@ -0,0 +1,731 @@ +package com.droiddeck.launcher.stores.epic; + +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.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +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.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.zip.Inflater; + +/** + * The Epic install pipeline, ported from Bannerlator's EpicDownloadManager: the manifest API's CDN + * list, the manifest binary (ChunksV4, or the older JSON form), the files narrowed to the base + * set plus the device's language, a delta pass that skips files already on disk with the right + * size and SHA-1, the chunk fetch into `.chunks/` (the native engine when it is there, the + * Java pool otherwise), and the assembly of files from those chunks. + * + * Chunk URLs carry no auth tokens; the subfolder is the decimal group number; the Cloudflare + * mirror is skipped (it refuses chunks). Blocking; the download queue runs it on its own thread. + */ +public final class EpicDownloadManager { + + private static final String TAG = "EpicDownload"; + private static final String UA = EpicAuthClient.USER_AGENT; + + public interface Callback { + void onProgress(String message, int pct); + default void onBytes(long done, long total, long speedBps) {} + default void onLog(String line) {} + } + + private EpicDownloadManager() {} + + public static final class CdnUrl { + public final String baseUrl, cloudDir, authParams; + CdnUrl(String baseUrl, String cloudDir, String authParams) { this.baseUrl = baseUrl; this.cloudDir = cloudDir; this.authParams = authParams; } + } + + public static final class ChunkInfo { + public int[] guid = new int[4]; + public long hash; + public byte[] sha1; + public int groupNum; + public int windowSize; + public long fileSize; + public String guidStr() { return String.format("%08X%08X%08X%08X", guid[0], guid[1], guid[2], guid[3]); } + public String getPath(String chunkDir) { return chunkDir + "/" + String.format("%02d", groupNum) + "/" + String.format("%016X", hash) + "_" + guidStr() + ".chunk"; } + } + + public static final class ChunkPart { + public int[] guid = new int[4]; + public int offset, size; + public String guidStr() { return String.format("%08X%08X%08X%08X", guid[0], guid[1], guid[2], guid[3]); } + } + + public static final class FileInfo { + public String filename = ""; + public List parts = new ArrayList<>(); + public List installTags = new ArrayList<>(); + public byte[] sha1 = null; + public long fileSize() { long t = 0; for (ChunkPart p : parts) t += (p.size & 0xFFFFFFFFL); return t; } + } + + /** The parsed manifest: its chunks, files, and from the meta block the exe the launcher starts. */ + public static final class Manifest { + public String chunkDir = "ChunksV4"; + public List uniqueChunks = new ArrayList<>(); + public List files = new ArrayList<>(); + public String launchExe = ""; + public String launchCommand = ""; + public String buildVersion = ""; + public List cdnUrls = new ArrayList<>(); + } + + /** What an install leaves for the sidecar. */ + public static final class Result { + public final String launchExe; + public final String buildVersion; + public final long bytes; + Result(String launchExe, String buildVersion, long bytes) { this.launchExe = launchExe; this.buildVersion = buildVersion; this.bytes = bytes; } + } + + public static final class InstallException extends Exception { + InstallException(String message) { super(message); } + } + + /** + * Installs the app the manifest API JSON describes into {@code installDir}. {@code installTags} + * null = every file. Returns null when cancelled; throws when it fails. + */ + public static Result install(Context ctx, String manifestApiJson, String installDirPath, List installTags, AtomicBoolean cancel, Callback cb) throws InstallException { + try { + if (cancel.get()) return null; + cb.onProgress("Reading CDN list…", 0); + List cdnUrls = parseCdnUrls(manifestApiJson); + if (cdnUrls.isEmpty()) throw new InstallException("No CDN in the manifest answer"); + for (CdnUrl c : cdnUrls) cb.onLog("epic: CDN " + c.baseUrl + " auth=" + (c.authParams.isEmpty() ? "no" : "yes")); + cb.onProgress("Downloading manifest…", 0); + byte[] manifestBytes = downloadManifest(manifestApiJson, cdnUrls); + if (manifestBytes == null) throw new InstallException("The manifest could not be downloaded"); + if (cancel.get()) return null; + cb.onProgress("Parsing manifest…", 0); + Manifest manifest = parseManifest(manifestBytes); + if (manifest == null) throw new InstallException("The manifest could not be parsed"); + manifest.cdnUrls = cdnUrls; + cb.onLog("epic: chunkDir=" + manifest.chunkDir + " chunks=" + manifest.uniqueChunks.size() + " files=" + manifest.files.size() + " exe=" + manifest.launchExe); + + File installDir = new File(installDirPath); + installDir.mkdirs(); + File chunkCacheDir = new File(installDir, ".chunks"); + chunkCacheDir.mkdirs(); + + List selected = resolveInstallFiles(manifest, installTags); + cb.onLog("epic: " + selected.size() + "/" + manifest.files.size() + " files for tags " + (installTags == null ? "(all)" : installTags.toString())); + long installBytes = 0; + for (FileInfo f : selected) installBytes += f.fileSize(); + final long planned = installBytes; + long usable = installDir.getUsableSpace(); + if (planned > 0 && usable > 0 && planned > usable) throw new InstallException("Not enough free space: need " + fmt(planned) + ", only " + fmt(usable) + " free"); + + cb.onProgress("Verifying existing files…", 0); + List pending = new ArrayList<>(selected.size()); + int checked = 0, good = 0; + for (FileInfo f : selected) { + if (cancel.get()) return null; + File out = new File(installDir, f.filename.replace("\\", "/")); + if (fileExistsWithCorrectHash(out, f.fileSize(), f.sha1)) good++; else pending.add(f); + checked++; + if ((checked & 63) == 0) cb.onProgress("Verifying existing files… (" + checked + "/" + selected.size() + ")", 0); + } + cb.onLog("epic: delta " + good + " up to date, " + pending.size() + " to download"); + if (pending.isEmpty()) { + deleteDir(chunkCacheDir); + cb.onProgress("Complete", 100); + return new Result(manifest.launchExe, manifest.buildVersion, planned); + } + List needed = uniqueChunksForFiles(manifest, pending); + long totalBytes = 0; + for (ChunkInfo c : needed) totalBytes += Math.max(c.fileSize, 1); + final long fTotalBytes = totalBytes; + final int totalChunks = needed.size(); + final AtomicLong completedBytes = new AtomicLong(0); + final AtomicInteger completedCount = new AtomicInteger(0); + final AtomicInteger failCount = new AtomicInteger(0); + final AtomicLong lastSpeedMs = new AtomicLong(System.currentTimeMillis()); + final AtomicLong lastSpeedBytes = new AtomicLong(0); + final AtomicLong speedBps = new AtomicLong(0); + cb.onBytes(0, fTotalBytes, 0); + cb.onLog("epic: " + fmt(fTotalBytes) + " in " + totalChunks + " chunks"); + + boolean javaPool = true; + if (com.droiddeck.launcher.stores.StoresNative.INSTANCE.getAvailable()) { + NativeOutcome r = runNativePool(ctx, manifestBytes, manifest, pending, needed, fTotalBytes, installDirPath, cdnUrls, cancel, cb, + completedBytes, completedCount, lastSpeedMs, lastSpeedBytes, speedBps); + if (r.started) { + javaPool = false; + if (r.cancelled) return null; + if (!r.success) { cb.onLog("epic: engine failed: " + r.error); failCount.incrementAndGet(); } + } else cb.onLog("epic: engine not started (" + r.error + "); using the built-in pool"); + } + if (javaPool) { + cb.onLog("epic: engine=built-in (8 threads)"); + ExecutorService pool = Executors.newFixedThreadPool(8); + for (ChunkInfo chunk : needed) { + final ChunkInfo fc = chunk; + pool.submit(() -> { + if (cancel.get()) return; + File cached = new File(chunkCacheDir, fc.guidStr()); + if (!cached.exists() && !downloadChunkStreaming(fc, manifest.chunkDir, cdnUrls, cached)) { + cb.onLog("FAIL chunk=" + fc.guidStr()); + failCount.incrementAndGet(); + return; + } + long done = completedBytes.addAndGet(Math.max(fc.fileSize, 1)); + int cnt = completedCount.incrementAndGet(); + sampleSpeed(done, lastSpeedMs, lastSpeedBytes, speedBps); + cb.onProgress("Downloading chunks (" + cnt + "/" + totalChunks + ")" + speedSuffix(speedBps.get()), (int) (done * 80L / Math.max(1, fTotalBytes))); + cb.onBytes(done, fTotalBytes, speedBps.get()); + }); + } + pool.shutdown(); + try { + while (!pool.awaitTermination(250, TimeUnit.MILLISECONDS)) { + if (cancel.get()) { pool.shutdownNow(); pool.awaitTermination(5, TimeUnit.SECONDS); return null; } + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + pool.shutdownNow(); + throw new InstallException("interrupted"); + } + } + if (cancel.get()) return null; + if (failCount.get() > 0) throw new InstallException(failCount.get() + " chunk(s) failed to download"); + + int totalFiles = pending.size(), doneFiles = 0; + for (FileInfo file : pending) { + if (cancel.get()) return null; + String relPath = file.filename.replace("\\", "/"); + File outFile = new File(installDir, relPath); + File parent = outFile.getParentFile(); + if (parent != null) parent.mkdirs(); + cb.onProgress("Writing: " + (relPath.contains("/") ? relPath.substring(relPath.lastIndexOf('/') + 1) : relPath), 80 + (int) (doneFiles * 20L / totalFiles)); + try (FileOutputStream fos = new FileOutputStream(outFile); BufferedOutputStream bos = new BufferedOutputStream(fos, 65536)) { + for (ChunkPart part : file.parts) { + File cachedChunk = new File(chunkCacheDir, part.guidStr()); + if (!cachedChunk.exists()) throw new InstallException("Missing chunk " + part.guidStr() + " for " + relPath); + byte[] data = readFile(cachedChunk); + bos.write(data, part.offset, part.size); + } + } + doneFiles++; + } + deleteDir(chunkCacheDir); + cb.onProgress("Complete", 100); + return new Result(manifest.launchExe, manifest.buildVersion, planned); + } 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() : "")); + } + } + + private static final class NativeOutcome { boolean started, success, cancelled; String error = ""; } + + /** The native chunk pool on the same counters; never throws. */ + private static NativeOutcome runNativePool(Context ctx, byte[] manifestBytes, Manifest manifest, List pending, List needed, long totalBytes, + String installDirPath, List cdnUrls, AtomicBoolean cancel, Callback cb, + AtomicLong completedBytes, AtomicInteger completedCount, AtomicLong lastSpeedMs, AtomicLong lastSpeedBytes, AtomicLong speedBps) { + NativeOutcome r = new NativeOutcome(); + try { + java.util.IdentityHashMap index = new java.util.IdentityHashMap<>(); + for (int i = 0; i < manifest.files.size(); i++) index.put(manifest.files.get(i), i); + int[] pendingIdx = new int[pending.size()]; + for (int i = 0; i < pending.size(); i++) { + Integer k = index.get(pending.get(i)); + if (k == null) { r.error = "pending file not in manifest"; return r; } + pendingIdx[i] = k; + } + String[] prefixes = new String[cdnUrls.size()]; + for (int i = 0; i < cdnUrls.size(); i++) prefixes[i] = cdnUrls.get(i).baseUrl + cdnUrls.get(i).cloudDir; + final int totalChunks = needed.size(); + StoreDownloadTier tier = StoreDownloadTier.Companion.current(ctx); + int workers = Math.max(1, Math.min(128, tier.getNetworkWindow())); + int process = Math.max(2, tier.getProcessWorkers()); + cb.onLog("epic: engine=native workers=" + workers + " process_workers=" + process + " tier=" + tier.getId()); + EpicNative.Result res = EpicNative.run(manifestBytes, installDirPath, prefixes, pendingIdx, totalChunks, totalBytes, "", workers, process, cancel, + new EpicNative.Listener() { + @Override public void onPlan(int chunksTotal, long bytesTotal, String chunkDir) { cb.onLog("epic: plan chunks=" + chunksTotal + " bytes=" + bytesTotal + " dir=" + chunkDir); } + @Override public void onProgress(long bytesDone, long bytesTotal, int chunksDone, int chunksTotal) { + completedBytes.set(bytesDone); + completedCount.set(chunksDone); + sampleSpeed(bytesDone, lastSpeedMs, lastSpeedBytes, speedBps); + cb.onProgress("Downloading chunks (" + chunksDone + "/" + totalChunks + ")" + speedSuffix(speedBps.get()), (int) (bytesDone * 80L / Math.max(1, totalBytes))); + cb.onBytes(bytesDone, totalBytes, speedBps.get()); + } + @Override public void onLog(String line) { cb.onLog(line); } + @Override public void onComplete(boolean success, String error, long bytesCredited) {} + }); + r.started = res.started; r.success = res.success; r.cancelled = res.cancelled; r.error = res.error == null ? "" : res.error; + } catch (Throwable t) { + r.started = false; + r.error = t.getClass().getSimpleName() + ": " + t.getMessage(); + } + return r; + } + + // ---- CDN list and manifest download --------------------------------------------------------- + + public static List parseCdnUrls(String json) { + List result = new ArrayList<>(); + try { + JSONArray manifests = new JSONObject(json).optJSONArray("manifests"); + if (manifests == null) return result; + for (int i = 0; i < manifests.length(); i++) { + JSONObject m = manifests.optJSONObject(i); + if (m == null) continue; + String uri = m.optString("uri", ""); + int buildsIdx = uri.indexOf("/Builds"); + if (buildsIdx < 0) continue; + String baseUrl = uri.substring(0, buildsIdx); + if (!baseUrl.startsWith("http") || baseUrl.contains("cloudflare.epicgamescdn.com")) continue; + String afterBase = uri.substring(buildsIdx); + int q = afterBase.indexOf('?'); + if (q >= 0) afterBase = afterBase.substring(0, q); + int lastSlash = afterBase.lastIndexOf('/'); + if (lastSlash < 0) continue; + String cloudDir = afterBase.substring(0, lastSlash); + StringBuilder auth = new StringBuilder(); + JSONArray params = m.optJSONArray("queryParams"); + if (params != null) for (int j = 0; j < params.length(); j++) { + JSONObject p = params.optJSONObject(j); + if (p == null) continue; + auth.append(auth.length() == 0 ? "?" : "&").append(p.optString("name")).append('=').append(p.optString("value")); + } + result.add(new CdnUrl(baseUrl, cloudDir, auth.toString())); + } + } catch (Exception e) { + Log.e(TAG, "CDN parse: " + e.getClass().getSimpleName()); + } + return result; + } + + /** The manifest binary from the first CDN that serves it; the auth query goes on this URL only. */ + public static byte[] downloadManifest(String json, List cdnUrls) { + try { + JSONArray manifests = new JSONObject(json).optJSONArray("manifests"); + if (manifests == null || manifests.length() == 0) return null; + String firstUri = manifests.getJSONObject(0).optString("uri", ""); + String uriPath = firstUri.contains("?") ? firstUri.substring(0, firstUri.indexOf('?')) : firstUri; + int lastSlash = uriPath.lastIndexOf('/'); + if (lastSlash < 0) return null; + String manifestFilename = uriPath.substring(lastSlash + 1); + for (CdnUrl cdn : cdnUrls) { + byte[] bytes = downloadBytes(cdn.baseUrl + cdn.cloudDir + "/" + manifestFilename + cdn.authParams); + if (bytes != null && bytes.length > 4) return bytes; + } + } catch (Exception e) { + Log.e(TAG, "manifest download: " + e.getClass().getSimpleName()); + } + return null; + } + + // ---- manifest parsing ----------------------------------------------------------------------- + + public static Manifest parseManifest(byte[] bytes) { + try { + ByteBuffer buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN); + int magic = buf.getInt(); + if (magic != 0x44BEC00C) return parseJsonManifest(bytes); + int headerSize = buf.getInt(); + int sizeUncompressed = buf.getInt(); + buf.getInt(); + buf.position(buf.position() + 20); + int storedAs = buf.get() & 0xFF; + int version = buf.getInt(); + String chunkDir = version >= 15 ? "ChunksV4" : version >= 6 ? "ChunksV3" : version >= 3 ? "ChunksV2" : "Chunks"; + buf.position(headerSize); + byte[] body = new byte[buf.remaining()]; + buf.get(body); + if ((storedAs & 1) != 0) { + Inflater inflater = new Inflater(); + inflater.setInput(body); + byte[] decomp = new byte[sizeUncompressed]; + int got = inflater.inflate(decomp); + inflater.end(); + if (got != sizeUncompressed) { Log.e(TAG, "manifest inflate size mismatch"); return null; } + body = decomp; + } + ByteBuffer b = ByteBuffer.wrap(body).order(ByteOrder.LITTLE_ENDIAN); + Manifest m = new Manifest(); + m.chunkDir = chunkDir; + // ManifestMeta: the launch exe and build version live here; the rest is skipped by size. + int metaStart = b.position(); + int metaSize = b.getInt(); + try { + b.get(); // data version + b.getInt(); // feature level + b.get(); // isFileData + b.getInt(); // app id + readFString(b); // app name + m.buildVersion = readFString(b); + m.launchExe = readFString(b).replace('\\', '/'); + m.launchCommand = readFString(b); + } catch (Exception e) { + Log.w(TAG, "manifest meta: " + e.getClass().getSimpleName()); + } + b.position(metaStart + metaSize); + + int cdlStart = b.position(); + int cdlSize = b.getInt(); + b.get(); + int chunkCount = b.getInt(); + List chunks = new ArrayList<>(chunkCount); + for (int i = 0; i < chunkCount; i++) chunks.add(new ChunkInfo()); + for (ChunkInfo c : chunks) { c.guid[0] = b.getInt(); c.guid[1] = b.getInt(); c.guid[2] = b.getInt(); c.guid[3] = b.getInt(); } + for (ChunkInfo c : chunks) c.hash = b.getLong(); + for (ChunkInfo c : chunks) { c.sha1 = new byte[20]; b.get(c.sha1); } + for (ChunkInfo c : chunks) c.groupNum = b.get() & 0xFF; + for (ChunkInfo c : chunks) c.windowSize = b.getInt(); + for (ChunkInfo c : chunks) c.fileSize = b.getLong(); + b.position(cdlStart + cdlSize); + + int fmlStart = b.position(); + int fmlSize = b.getInt(); + b.get(); + int fileCount = b.getInt(); + List files = new ArrayList<>(fileCount); + for (int i = 0; i < fileCount; i++) files.add(new FileInfo()); + for (FileInfo f : files) f.filename = readFString(b); + for (int i = 0; i < fileCount; i++) readFString(b); + for (FileInfo f : files) { f.sha1 = new byte[20]; b.get(f.sha1); } + b.position(b.position() + fileCount); + for (int i = 0; i < fileCount; i++) { + int tagCount = b.getInt(); + for (int j = 0; j < tagCount; j++) { String tag = readFString(b); if (tag != null && !tag.isEmpty()) files.get(i).installTags.add(tag); } + } + for (FileInfo f : files) { + int partCount = b.getInt(); + for (int j = 0; j < partCount; j++) { + int partStart = b.position(); + int partStructSize = b.getInt(); + ChunkPart part = new ChunkPart(); + part.guid[0] = b.getInt(); part.guid[1] = b.getInt(); part.guid[2] = b.getInt(); part.guid[3] = b.getInt(); + part.offset = b.getInt(); part.size = b.getInt(); + f.parts.add(part); + b.position(partStart + partStructSize); + } + } + b.position(fmlStart + fmlSize); + Map seen = new LinkedHashMap<>(chunkCount * 2); + for (ChunkInfo c : chunks) seen.put(c.guidStr(), c); + m.uniqueChunks = new ArrayList<>(seen.values()); + m.files = files; + return m; + } catch (Exception e) { + Log.e(TAG, "manifest parse: " + e.getClass().getSimpleName()); + return null; + } + } + + private static Manifest parseJsonManifest(byte[] bytes) { + try { + JSONObject root = new JSONObject(new String(bytes, StandardCharsets.UTF_8)); + int manifestVersion = 0; + try { manifestVersion = Integer.parseInt(root.optString("ManifestFileVersion", "0")); } catch (NumberFormatException ignored) {} + Manifest m = new Manifest(); + m.chunkDir = manifestVersion >= 15 ? "ChunksV4" : manifestVersion >= 6 ? "ChunksV3" : manifestVersion >= 3 ? "ChunksV2" : "ChunksV4"; + m.launchExe = root.optString("LaunchExe", "").replace('\\', '/'); + m.launchCommand = root.optString("LaunchCommand", ""); + m.buildVersion = root.optString("BuildVersionString", ""); + JSONObject chunkHashList = root.optJSONObject("ChunkHashList"); + JSONObject dataGroupList = root.optJSONObject("DataGroupList"); + JSONObject chunkFilesizeList = root.optJSONObject("ChunkFilesizeList"); + if (chunkHashList == null) return null; + Map chunkMap = new LinkedHashMap<>(); + Iterator keys = chunkHashList.keys(); + while (keys.hasNext()) { + String guidHex = keys.next(); + if (guidHex.length() < 32) continue; + ChunkInfo c = new ChunkInfo(); + for (int k = 0; k < 4; k++) c.guid[k] = (int) Long.parseLong(guidHex.substring(k * 8, k * 8 + 8), 16); + String hashHex = chunkHashList.getString(guidHex); + if (hashHex != null && hashHex.length() >= 16) { try { c.hash = Long.parseUnsignedLong(hashHex.substring(0, 16), 16); } catch (Exception ignored) {} } + if (dataGroupList != null) { try { c.groupNum = Integer.parseInt(dataGroupList.optString(guidHex, "0")); } catch (NumberFormatException ignored) {} } + if (chunkFilesizeList != null) { try { c.fileSize = Long.parseLong(chunkFilesizeList.optString(guidHex, "0"), 16); } catch (NumberFormatException ignored) {} } + chunkMap.put(guidHex, c); + } + JSONArray fileList = root.optJSONArray("FileManifestList"); + if (fileList == null) return null; + List files = new ArrayList<>(fileList.length()); + for (int i = 0; i < fileList.length(); i++) { + JSONObject fo = fileList.getJSONObject(i); + FileInfo fi = new FileInfo(); + fi.filename = fo.optString("Filename", ""); + JSONArray tags = fo.optJSONArray("InstallTags"); + if (tags != null) for (int t = 0; t < tags.length(); t++) { String tag = tags.optString(t, ""); if (!tag.isEmpty()) fi.installTags.add(tag); } + JSONArray parts = fo.optJSONArray("FileChunkParts"); + if (parts != null) for (int j = 0; j < parts.length(); j++) { + JSONObject po = parts.getJSONObject(j); + ChunkPart part = new ChunkPart(); + String g = po.optString("Guid", ""); + if (g.length() >= 32) for (int k = 0; k < 4; k++) part.guid[k] = (int) Long.parseLong(g.substring(k * 8, k * 8 + 8), 16); + try { part.offset = Integer.parseInt(po.optString("Offset", "0")); } catch (NumberFormatException ignored) {} + try { part.size = Integer.parseInt(po.optString("Size", "0")); } catch (NumberFormatException ignored) {} + fi.parts.add(part); + } + files.add(fi); + } + m.uniqueChunks = new ArrayList<>(chunkMap.values()); + m.files = files; + return m; + } catch (Exception e) { + Log.e(TAG, "json manifest parse: " + e.getClass().getSimpleName()); + return null; + } + } + + public static String readFString(ByteBuffer buf) { + int length = buf.getInt(); + if (length == 0) return ""; + if (length < 0) { + int chars = (-length) - 1; + byte[] bytes = new byte[chars * 2]; + buf.get(bytes); + buf.getShort(); + return new String(bytes, StandardCharsets.UTF_16LE); + } + byte[] bytes = new byte[length - 1]; + buf.get(bytes); + buf.get(); + return new String(bytes, StandardCharsets.US_ASCII); + } + + // ---- chunk fetch (the built-in pool) -------------------------------------------------------- + + public static byte[] downloadBytes(String urlStr) { + HttpURLConnection conn = null; + try { + conn = (HttpURLConnection) new URL(urlStr).openConnection(); + conn.setConnectTimeout(30000); + conn.setReadTimeout(60000); + conn.setRequestProperty("User-Agent", UA); + if (conn.getResponseCode() != 200) { Log.w(TAG, "HTTP " + conn.getResponseCode() + " for " + StoreLog.redactUrl(urlStr)); return null; } + return EpicAuthClient.readAllBytes(conn.getInputStream()); + } catch (Exception e) { + Log.w(TAG, "download error [" + StoreLog.redactUrl(urlStr) + "]: " + e.getClass().getSimpleName()); + return null; + } finally { + if (conn != null) conn.disconnect(); + } + } + + /** One chunk streamed from the first CDN that serves it, SHA-1 checked, published by rename. */ + private static boolean downloadChunkStreaming(ChunkInfo chunk, String chunkDir, List cdnUrls, File outFile) { + String chunkPath = chunk.getPath(chunkDir); + File tmp = new File(outFile.getPath() + ".part"); + tmp.delete(); + for (CdnUrl cdn : cdnUrls) { + HttpURLConnection conn = null; + try { + conn = (HttpURLConnection) new URL(cdn.baseUrl + cdn.cloudDir + "/" + chunkPath).openConnection(); + conn.setConnectTimeout(30000); + conn.setReadTimeout(60000); + conn.setRequestProperty("User-Agent", UA); + if (conn.getResponseCode() != 200) { conn.disconnect(); continue; } + MessageDigest sha = null; + if (chunk.sha1 != null && chunk.sha1.length == 20) { + boolean allZero = true; + for (byte x : chunk.sha1) if (x != 0) { allZero = false; break; } + if (!allZero) { try { sha = MessageDigest.getInstance("SHA-1"); } catch (Exception ignored) {} } + } + try (InputStream in = conn.getInputStream(); FileOutputStream fos = new FileOutputStream(tmp)) { + byte[] hdrBuf = new byte[41]; + readFully(in, hdrBuf); + ByteBuffer hdr = ByteBuffer.wrap(hdrBuf).order(ByteOrder.LITTLE_ENDIAN); + if (hdr.getInt() != 0xB1FE3AA2) { Log.w(TAG, "bad chunk magic"); continue; } + hdr.getInt(); + int headerSize = hdr.getInt(); + int compressedSize = hdr.getInt(); + hdr.position(hdr.position() + 24); + int storedAs = hdr.get() & 0xFF; + if (headerSize > 41) skipFully(in, headerSize - 41); + byte[] iobuf = new byte[131072]; + if ((storedAs & 1) != 0) { + Inflater inflater = new Inflater(); + byte[] obuf = new byte[131072]; + int remaining = compressedSize; + try { + while (remaining > 0 && !inflater.finished()) { + if (inflater.needsInput()) { + int n = in.read(iobuf, 0, Math.min(iobuf.length, remaining)); + if (n <= 0) break; + remaining -= n; + inflater.setInput(iobuf, 0, n); + } + int out = inflater.inflate(obuf); + if (out > 0) { fos.write(obuf, 0, out); if (sha != null) sha.update(obuf, 0, out); } + } + int out; + while ((out = inflater.inflate(obuf)) > 0) { fos.write(obuf, 0, out); if (sha != null) sha.update(obuf, 0, out); } + } finally { + inflater.end(); + } + } else { + int remaining = compressedSize; + while (remaining > 0) { + int n = in.read(iobuf, 0, Math.min(iobuf.length, remaining)); + if (n <= 0) break; + fos.write(iobuf, 0, n); + if (sha != null) sha.update(iobuf, 0, n); + remaining -= n; + } + } + } + if (sha != null && !MessageDigest.isEqual(sha.digest(), chunk.sha1)) { tmp.delete(); conn.disconnect(); continue; } + if (!tmp.renameTo(outFile)) { tmp.delete(); conn.disconnect(); continue; } + conn.disconnect(); + return true; + } catch (Exception e) { + tmp.delete(); + if (conn != null) conn.disconnect(); + } + } + tmp.delete(); + Log.e(TAG, "every CDN failed for chunk " + chunk.guidStr()); + return false; + } + + private static void readFully(InputStream in, byte[] buf) throws IOException { + int off = 0; + while (off < buf.length) { int n = in.read(buf, off, buf.length - off); if (n < 0) throw new IOException("stream ended"); off += n; } + } + + private static void skipFully(InputStream in, int count) throws IOException { + byte[] skip = new byte[Math.min(count, 4096)]; + int remaining = count; + while (remaining > 0) { int n = in.read(skip, 0, Math.min(skip.length, remaining)); if (n < 0) throw new IOException("stream ended"); remaining -= n; } + } + + // ---- selection and verification ------------------------------------------------------------- + + public static List getRequiredInstallFiles(Manifest manifest) { + List required = new ArrayList<>(); + for (FileInfo f : manifest.files) if (f.installTags.isEmpty()) required.add(f); + return required.isEmpty() ? new ArrayList<>(manifest.files) : required; + } + + /** Base files plus any file carrying one of the tags; null tags = every file; nothing matched = base only. */ + public static List resolveInstallFiles(Manifest manifest, List selectedTags) { + if (selectedTags == null) return new ArrayList<>(manifest.files); + if (selectedTags.isEmpty()) return getRequiredInstallFiles(manifest); + Set want = new LinkedHashSet<>(selectedTags); + List out = new ArrayList<>(); + for (FileInfo f : manifest.files) { + if (f.installTags.isEmpty()) { out.add(f); continue; } + for (String t : f.installTags) if (want.contains(t)) { out.add(f); break; } + } + return out.isEmpty() ? getRequiredInstallFiles(manifest) : out; + } + + public static List uniqueChunksForFiles(Manifest manifest, List files) { + Map byGuid = new LinkedHashMap<>(); + for (ChunkInfo c : manifest.uniqueChunks) byGuid.put(c.guidStr(), c); + Set seen = new LinkedHashSet<>(); + List chunks = new ArrayList<>(); + for (FileInfo f : files) for (ChunkPart p : f.parts) { String g = p.guidStr(); if (seen.add(g)) { ChunkInfo c = byGuid.get(g); if (c != null) chunks.add(c); } } + return chunks; + } + + public static boolean fileExistsWithCorrectHash(File outputFile, long expectedSize, byte[] expectedHash) { + if (outputFile == null || !outputFile.exists() || outputFile.length() != expectedSize) return false; + if (expectedHash == null || expectedHash.length != 20) return false; + boolean allZero = true; + for (byte x : expectedHash) if (x != 0) { allZero = false; break; } + if (allZero) return false; + try (FileInputStream fis = new FileInputStream(outputFile)) { + MessageDigest digest = MessageDigest.getInstance("SHA-1"); + byte[] buf = new byte[64 * 1024]; + int n; + while ((n = fis.read(buf)) != -1) digest.update(buf, 0, n); + return MessageDigest.isEqual(digest.digest(), expectedHash); + } catch (Exception e) { + return false; + } + } + + /** The install size for the tags (null = every file), from the manifest alone; -1 on failure. Blocking. */ + public static long fetchInstallSizeBytes(String manifestApiJson, List installTags) { + try { + List cdnUrls = parseCdnUrls(manifestApiJson); + if (cdnUrls.isEmpty()) return -1; + byte[] bytes = downloadManifest(manifestApiJson, cdnUrls); + if (bytes == null) return -1; + Manifest m = parseManifest(bytes); + if (m == null) return -1; + long total = 0; + for (FileInfo f : resolveInstallFiles(m, installTags)) total += Math.max(f.fileSize(), 0); + return total > 0 ? total : -1; + } catch (Exception e) { + return -1; + } + } + + // ---- helpers -------------------------------------------------------------------------------- + + static byte[] readFile(File f) throws IOException { + try (FileInputStream fis = new FileInputStream(f)) { + byte[] data = new byte[(int) f.length()]; + int off = 0; + while (off < data.length) { int r = fis.read(data, off, data.length - off); if (r < 0) break; off += r; } + return data; + } + } + + static void deleteDir(File dir) { + if (!dir.exists()) return; + File[] files = dir.listFiles(); + if (files != null) for (File f : files) { if (f.isDirectory()) deleteDir(f); else f.delete(); } + dir.delete(); + } + + 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); + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicGame.java b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicGame.java new file mode 100644 index 0000000000..2cb9c7fb36 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicGame.java @@ -0,0 +1,25 @@ +package com.droiddeck.launcher.stores.epic; + +/** + * One Epic Games library entry. {@code appName} is the launcher's app slug (the manifest URL and + * the launch arguments take it), {@code namespace} the product's sandbox, {@code catalogItemId} + * the catalog UUID; the three together address every Epic API call for the game. + */ +public class EpicGame { + public String appName = ""; + public String namespace = ""; + public String catalogItemId = ""; + public String title = ""; + public String developer = ""; + public String description = ""; + /** DieselGameBoxTall: the tall portrait art. */ + public String artCover = ""; + /** DieselGameBox or Thumbnail. */ + public String artSquare = ""; + public String version = ""; + public long installSize = 0L; + public boolean canRunOffline = true; + public boolean isDLC = false; + public String baseGameCatalogItemId = ""; + public String releaseDate = ""; +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicInstallTags.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicInstallTags.kt new file mode 100644 index 0000000000..dcb178d505 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicInstallTags.kt @@ -0,0 +1,44 @@ +package com.droiddeck.launcher.stores.epic + +import java.util.Locale + +/** + * Epic tags a manifest's files by language so a client installs the base files plus one language + * instead of every language. The table (the launcher's tag names per language) is Legendary's; + * the language is the device's locale, English when it is not one Epic ships. + */ +object EpicInstallTags { + private val LANGUAGE_TO_TAGS: Map> = 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 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 + } + } + + /** The install tags for the device's language; English when Epic has no tags for it. Never empty. */ + @JvmStatic + fun tagsForDevice(): List = LANGUAGE_TO_TAGS[key(Locale.getDefault()) ?: "en"] ?: LANGUAGE_TO_TAGS.getValue("en") + + /** The two-letter code handed to the game as -epiclocale; "en" when the language is not one Epic knows. */ + @JvmStatic + fun localeCodeForDevice(): String = key(Locale.getDefault())?.substringBefore('-') ?: "en" +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLaunchData.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLaunchData.kt new file mode 100644 index 0000000000..6119bda75e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLaunchData.kt @@ -0,0 +1,55 @@ +package com.droiddeck.launcher.stores.epic + +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.stores.StoreGameSidecar + +/** + * What an Epic game's launch line needs beyond the exe, built once at install time into the + * sidecar's arguments: the portal and identity arguments every EOS title expects + * (`-EpicPortal -epicusername -epicuserid -epicsandboxid -epiclocale -epicapp -epicenv=Prod`), the + * deployment id when the app has an EOS sidecar, and the extra flags Epic ships for the title + * (`AdditionalCommandLine`). The sign-in triple (`-AUTH_LOGIN/-AUTH_PASSWORD/-AUTH_TYPE`) is not + * here: the exchange code lives minutes, so the launcher .bat takes it from a file the app writes + * right before a launch (StoreLaunch.prepare). + * + * The EOS overlay is never provisioned: nothing points the game's EOS SDK at an overlay component. + */ +object EpicLaunchData { + private const val TAG = "EpicLaunch" + + /** The static launch arguments for [appName] in [namespace]. Blocking: one catalog call for the extra flags. */ + fun arguments(context: Context, token: String?, appName: String, namespace: String, catalogItemId: String, deploymentId: String): List { + val creds = EpicCredentialStore.load(context) + val displayName = creds?.displayName?.takeIf { it.isNotEmpty() } ?: "EpicUser" + val accountId = creds?.accountId?.takeIf { it.isNotEmpty() } ?: "0" + val args = ArrayList() + 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 + } + + /** The sidecar's identifiers the launcher reads back. */ + fun extras(appName: String, namespace: String, catalogItemId: String, deploymentId: String): Map = buildMap { + put("appName", appName); put("namespace", namespace); put("catalogItemId", catalogItemId) + if (deploymentId.isNotEmpty()) put("deploymentId", deploymentId) + } + + /** True when [sidecar] is an Epic install that can take a sign-in code. */ + 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", "") +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLibrary.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLibrary.kt new file mode 100644 index 0000000000..d5590e0c23 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLibrary.kt @@ -0,0 +1,119 @@ +package com.droiddeck.launcher.stores.epic + +import android.content.Context +import android.content.SharedPreferences +import android.util.Log +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.Store +import org.json.JSONArray +import org.json.JSONObject +import java.util.concurrent.atomic.AtomicBoolean + +/** + * The signed-in account's Epic library: the library service's records, each enriched from the + * catalog (title, art, DLC flag), cached so the tab paints at once and re-synced when forced or + * 15 minutes stale. DLC entries are folded away under their base game. Ported from Bannerlator's + * EpicLibraryRepo. + */ +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 = 15L * 60L * 1000L + + private val syncing = AtomicBoolean(false) + + sealed interface SyncResult { + class Ok(val games: List) : SyncResult + class Failed(val message: String) : SyncResult + object NotLoggedIn : SyncResult + object Busy : SyncResult + object Throttled : SyncResult + } + + fun cached(context: Context): List { + val json = EpicPrefs.get(context).getString(CACHE_KEY, null) ?: return emptyList() + return runCatching { + val arr = JSONArray(json) + val list = ArrayList(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) + if (g.appName.isNotEmpty()) list.add(g) + } + list.distinctBy { it.appName }.sortedBy { it.title.lowercase() } + }.getOrDefault(emptyList()) + } + + /** Remembers a game's install size once the manifest said it, for the Install button. */ + fun rememberSize(context: Context, appName: String, bytes: Long) { + if (bytes <= 0) return + val p = EpicPrefs.get(context) + p.edit().putLong("size_$appName", bytes).apply() + } + + fun sync(context: Context, force: Boolean = false, onStatus: (String) -> Unit = {}): SyncResult { + if (!syncing.compareAndSet(false, true)) return SyncResult.Busy + try { + val app = context.applicationContext + val p = 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("Checking sign-in…") + val token = EpicCredentialStore.getValidAccessToken(app) ?: return SyncResult.NotLoggedIn + onStatus("Fetching game list…") + val raw = EpicApiClient.getLibraryItems(token) + if (raw.isNullOrEmpty()) return if (cachedList.isEmpty()) SyncResult.Failed("No games found in your Epic library") else SyncResult.Ok(cachedList) + val total = raw.size + var done = 0 + for (game in raw) { + EpicApiClient.enrichFromCatalog(token, game) + if (game.releaseDate.isNotEmpty()) p.edit().putString("release_${game.appName}", game.releaseDate).apply() + done++ + if (done % 5 == 0) onStatus("Loading game details… ($done/$total)") + } + 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 + } + 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) + } catch (e: Exception) { + Log.w(TAG, "sync failed: ${e.message}") + return SyncResult.Failed(e.message ?: "Sync failed") + } finally { + syncing.set(false) + } + } + + private fun saveCache(prefs: SharedPreferences, games: List) { + 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)) + 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, description = g.description, owned = true, + 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), + ) +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicNative.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicNative.kt new file mode 100644 index 0000000000..9d1a6c7a25 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicNative.kt @@ -0,0 +1,99 @@ +// JNI symbols depend on this package path and class name (app/src/main/rust/stores/JNI.md). +package com.droiddeck.launcher.stores.epic + +import android.util.Log +import com.droiddeck.launcher.stores.StoresNative +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference + +/** + * The native Epic chunk fetcher in `libdroiddeckstores.so`: it fills `/.chunks/` + * with verified, decompressed chunks for the files the manager says are pending. Everything + * around it (manifest, install tags, delta pass, assembly, post-install) stays in the manager. + * + * [run] blocks like the Java pool it replaces and polls [AtomicBoolean] `cancel` every 250 ms: on + * cancel it flips the native flag, waits up to 5 s for the run to wind down, then returns. + */ +object EpicNative { + private const val TAG = "EpicNative" + + /** Callbacks from the native run; every method is called on a native thread. */ + interface Listener { + /** Once, before any fetch: the plan the engine derived (the manager cross-checks it). */ + fun onPlan(chunksTotal: Int, bytesTotal: Long, chunkDir: String) + /** Per accounted chunk (cached-skip or fetched). */ + fun onProgress(bytesDone: Long, bytesTotal: Long, chunksDone: Int, chunksTotal: Int) + /** Engine log line (already in logcat under `EpicNative`). */ + fun onLog(line: String) + /** Terminal. */ + fun onComplete(success: Boolean, error: String, bytesCredited: Long) + } + + /** Outcome of [run]. `started == false`: nothing was fetched, the caller runs its own pool. */ + class Result( + @JvmField val started: Boolean, @JvmField val success: Boolean, @JvmField val cancelled: Boolean, + @JvmField val error: String, @JvmField val bytesCredited: Long, @JvmField val chunksDone: Int, @JvmField val chunksTotal: Int, + ) + + private class Completion(val success: Boolean, val error: String, val bytes: Long) + + @JvmStatic + fun run( + manifest: ByteArray, installDir: String, cdnPrefixes: Array, pendingFileIdx: IntArray, expectedChunks: Int, expectedBytes: Long, + caBundlePath: String, maxWorkers: Int, processWorkers: Int, cancel: AtomicBoolean?, listener: Listener, + ): Result { + if (!StoresNative.ensureLoaded()) return Result(false, false, false, "engine not built", 0L, 0, 0) + val latch = CountDownLatch(1) + val completion = AtomicReference(null) + val doneRef = AtomicReference(0) + val totalRef = AtomicReference(0) + val inner = object : Listener { + override fun onPlan(chunksTotal: Int, bytesTotal: Long, chunkDir: String) { totalRef.set(chunksTotal); listener.onPlan(chunksTotal, bytesTotal, chunkDir) } + override fun onProgress(bytesDone: Long, bytesTotal: Long, chunksDone: Int, chunksTotal: Int) { doneRef.set(chunksDone); listener.onProgress(bytesDone, bytesTotal, chunksDone, chunksTotal) } + override fun onLog(line: String) = listener.onLog(line) + override fun onComplete(success: Boolean, error: String, bytesCredited: Long) { + completion.set(Completion(success, error, bytesCredited)) + latch.countDown() + runCatching { listener.onComplete(success, error, bytesCredited) } + } + } + val handle: Long = try { + nativeStart(manifest, installDir, cdnPrefixes, pendingFileIdx, expectedChunks, expectedBytes, caBundlePath, maxWorkers, processWorkers, inner) + } catch (t: Throwable) { + Log.w(TAG, "engine unavailable: ${t.javaClass.simpleName}: ${t.message}") + return Result(false, false, false, "nativeStart: ${t.javaClass.simpleName}", 0L, 0, 0) + } + if (handle == 0L) return Result(false, 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 + latch.await(5, TimeUnit.SECONDS) + break + } + } + } finally { + 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 nativeStart( + manifest: ByteArray, installDir: String, cdnPrefixes: Array, pendingFileIdx: IntArray, expectedChunks: Int, expectedBytes: Long, + caBundlePath: String, maxWorkers: Int, processWorkers: Int, listener: Listener, + ): Long + + @JvmStatic + private external fun nativeCancel(handle: Long) + + @JvmStatic + private external fun nativeRelease(handle: Long) +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicPrefs.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicPrefs.kt new file mode 100644 index 0000000000..ae2bfadb34 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicPrefs.kt @@ -0,0 +1,14 @@ +package com.droiddeck.launcher.stores.epic + +import android.content.Context +import android.content.SharedPreferences + +/** + * Epic's own records that are not credentials: the library cache, each game's release date, the + * cached deployment id and extra command line a launch needs. App-private preferences; the sign-in + * lives in StoreAccounts. Public: the Java clients read it too. + */ +object EpicPrefs { + @JvmStatic + fun get(context: Context): SharedPreferences = context.applicationContext.getSharedPreferences("stores.epic", Context.MODE_PRIVATE) +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicStoreCatalog.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicStoreCatalog.kt new file mode 100644 index 0000000000..baa91b6b6f --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicStoreCatalog.kt @@ -0,0 +1,214 @@ +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 + +/** + * The Epic Games Store catalog through the GraphQL endpoint the store website uses + * (`store.epicgames.com/graphql`, which wants a browser User-Agent): `Catalog.searchStore` with + * the base-game category, sorted by price / release date / relevance, on sale or free. Elements + * carry the offer id, the namespace, the catalog item ids (what the library records, so ownership + * is matched on those), key images and pre-formatted prices. "Free this week" comes from the + * static `freeGamesPromotions` feed. + */ +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 = 30 * 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} " + + "catalogNs{mappings(pageType:\"productHome\"){pageSlug pageType}} " + + "price(country:\$country){totalPrice{discountPrice originalPrice discount currencyCode " + + "fmtPrice(locale:\$locale){originalPrice discountPrice}}}" + + private class Cached(val value: T, val at: Long) + private var featuredCache: Cached? = null + private val searchCache = ConcurrentHashMap>>() + + 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 { + 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 { + val out = ArrayList(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", "")) { + "OfferImageWide", "DieselStoreFrontWide" -> if (wide == null) wide = url + "OfferImageTall", "DieselStoreFrontTall", "DieselGameBoxTall" -> 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 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 = e.optJSONObject("seller")?.optString("name", "").orEmpty(), + releaseDate = e.optString("releaseDate", e.optString("effectiveDate", "")), description = e.optString("description", ""), + extra = buildMap { put("namespace", ns); if (itemIds.isNotEmpty()) put("items", itemIds.joinToString(",")); if (slug.isNotBlank()) put("slug", slug) }, + ) + } + + 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") + } + + /** The Store tab's shelves: this week's giveaways as Free, sales as Deals, newest releases, trending = free-to-play picks. Blocking. */ + 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 } + 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 { + 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 + } + + /** This week's giveaway titles (100% off right now). */ + private fun fetchPromos(): List { + 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() + 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("rel", i.releaseDate); put("desc", i.description); put("extra", JSONObject(i.extra as Map<*, *>)) + } + + private fun itemFromJson(o: JSONObject): CatalogItem { + val extra = HashMap() + 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"), releaseDate = o.optString("rel"), description = o.optString("desc"), extra = extra, + ) + } + + private fun listToJson(l: List) = JSONArray().apply { l.forEach { put(itemToJson(it)) } } + private fun listFromJson(a: JSONArray?): List = 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()).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() +}