From a5712c0d20d292f0d5b97d65cbca699828863c60 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:08:33 -0500 Subject: [PATCH] feat(stores): EA and Ubisoft stores browse their catalogs, and EA's Get for free works in the app (#2527) * feat(stores): EA and Ubisoft stores browse their catalogs with prices, deals and search * feat(stores): Get for free adds EA's free games to the account in the app * fix(stores): an owned EA game matches its store card by its full product name --- .../droiddeck/launcher/stores/StoreCatalog.kt | 1 + .../droiddeck/launcher/stores/StoreFront.kt | 119 ++++++++++++++++ .../droiddeck/launcher/stores/StoresState.kt | 27 ++++ .../com/droiddeck/launcher/stores/ea/EaApi.kt | 14 ++ .../droiddeck/launcher/stores/ea/EaBackend.kt | 30 +++- .../droiddeck/launcher/stores/ea/EaLibrary.kt | 16 ++- .../droiddeck/launcher/stores/ea/EaStore.kt | 120 ++++++++++++++++ .../launcher/stores/ubisoft/UbisoftBackend.kt | 20 ++- .../launcher/stores/ubisoft/UbisoftStore.kt | 129 ++++++++++++++++++ .../com/droiddeck/launcher/ui/GameDetail.kt | 7 +- app/src/main/res/values-ar/strings.xml | 1 + app/src/main/res/values-b+es+419/strings.xml | 1 + app/src/main/res/values-bg/strings.xml | 1 + app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-da/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-el/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fi/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-hi/strings.xml | 1 + app/src/main/res/values-hu/strings.xml | 1 + app/src/main/res/values-in/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-ja/strings.xml | 1 + app/src/main/res/values-ko/strings.xml | 1 + app/src/main/res/values-ms/strings.xml | 1 + app/src/main/res/values-nb/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-pt-rPT/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values-ro/strings.xml | 1 + app/src/main/res/values-ru/strings.xml | 1 + app/src/main/res/values-sv/strings.xml | 1 + app/src/main/res/values-th/strings.xml | 1 + app/src/main/res/values-tr/strings.xml | 1 + app/src/main/res/values-uk/strings.xml | 1 + app/src/main/res/values-vi/strings.xml | 1 + app/src/main/res/values-zh-rCN/strings.xml | 1 + app/src/main/res/values-zh-rHK/strings.xml | 1 + app/src/main/res/values-zh-rTW/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + .../ea/graphql/GetGameProductOfferIds.gql | 15 ++ .../resources/ea/graphql/grantEntitlement.gql | 23 ++++ .../droiddeck/launcher/stores/ea/EaTest.kt | 42 ++++++ .../launcher/stores/ubisoft/UbisoftTest.kt | 30 ++++ 47 files changed, 614 insertions(+), 12 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/stores/StoreFront.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/stores/ea/EaStore.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftStore.kt create mode 100644 app/src/main/resources/ea/graphql/GetGameProductOfferIds.gql create mode 100644 app/src/main/resources/ea/graphql/grantEntitlement.gql diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreCatalog.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreCatalog.kt index cb46d23601..e87266df65 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreCatalog.kt @@ -106,6 +106,7 @@ fun detailCatalogItem( library.firstOrNull { it.store == store && it.id == id } ?: found.firstOrNull { it.store == store && it.id == id } ?: shelves?.all?.firstOrNull { it.store == store && it.id == id } + ?: shelves?.all?.firstOrNull { it.store == store && it.extra[StoreFront.STORE_CARD] == id } fun mergeItems(old: List?, new: List): List { if (old.isNullOrEmpty()) return new diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreFront.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreFront.kt new file mode 100644 index 0000000000..5791656111 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreFront.kt @@ -0,0 +1,119 @@ +package com.droiddeck.launcher.stores + +import android.content.SharedPreferences +import org.json.JSONArray +import org.json.JSONObject +import java.text.Normalizer +import java.util.Locale + +/** Store shelves fetched from a public catalog, kept in memory and on disk between refreshes. */ +internal class StoreFront( + private val store: Store, + private val prefs: () -> SharedPreferences, + private val fetch: () -> Catalog, + private val key: String = "store_front", + private val ttlMs: Long = 3 * 60 * 60 * 1000L, +) { + /** One refresh: the shelves and every game the store lists, for search. */ + class Catalog(val shelves: StoreShelves, val all: List = shelves.all) + + @Volatile private var memory: Catalog? = null + @Volatile private var memoryAt = 0L + + fun cached(): StoreShelves? = cachedCatalog()?.shelves + + fun everything(): List = cachedCatalog()?.all.orEmpty() + + private fun cachedCatalog(): Catalog? = memory ?: decode(prefs().getString(key, null))?.also { memory = it } + + /** The shelves, refreshed when stale; a refresh that fails keeps the last good set. */ + fun shelves(force: Boolean): StoreShelves? { + val now = System.currentTimeMillis() + if (!force) { + memory?.takeIf { now - memoryAt in 0 until ttlMs }?.let { return it.shelves } + val at = prefs().getLong("${key}_at", 0L) + if (now - at in 0 until ttlMs) decode(prefs().getString(key, null))?.let { memory = it; memoryAt = at; return it.shelves } + } + val fresh = runCatching(fetch).onFailure { StoresState.logLine("${store.label}: store shelves failed: ${it.javaClass.simpleName} ${it.message.orEmpty().take(160)}") } + .getOrNull()?.takeUnless { it.shelves.isEmpty } + ?: return cached() + prefs().edit().putString(key, encode(fresh)).putLong("${key}_at", now).apply() + memory = fresh + memoryAt = now + return fresh.shelves + } + + private fun encode(c: Catalog): String = JSONObject().apply { + val s = c.shelves + listOf(s.whatsNew, s.deals, s.free, s.trending).zip(SHELVES).forEach { (items, k) -> put(k, JSONArray(items.map { it.id })) } + put("art", JSONArray(s.art)) + put("items", JSONArray().apply { (c.all + s.all).distinctBy { it.id }.forEach { put(itemJson(it)) } }) + }.toString() + + private fun decode(text: String?): Catalog? { + val o = text?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return null + val items = o.optJSONArray("items")?.let { a -> (0 until a.length()).mapNotNull { a.optJSONObject(it)?.let(::itemFrom) } }.orEmpty() + val byId = items.associateBy { it.id } + fun shelf(k: String) = o.optJSONArray(k)?.let { a -> (0 until a.length()).mapNotNull { byId[a.optString(it)] } }.orEmpty() + val art = o.optJSONArray("art")?.let { a -> List(a.length()) { a.optString(it) }.filter { it.isNotEmpty() } }.orEmpty() + val shelves = StoreShelves(shelf("new"), shelf("deals"), shelf("free"), shelf("trending"), art).takeUnless { it.isEmpty } ?: return null + return Catalog(shelves, items) + } + + private fun itemJson(i: CatalogItem) = JSONObject() + .put("id", i.id).put("title", i.title).put("image", i.imageUrl.orEmpty()).put("tall", i.tallImageUrl.orEmpty()).put("tags", i.tags) + .put("free", i.isFree).put("hasPrice", i.hasPrice).put("final", i.finalPrice).put("orig", i.originalPrice).put("disc", i.discountPercent) + .put("url", i.storeUrl).put("dev", i.developer).put("pub", i.publisher).put("rel", i.releaseDate).put("desc", i.description) + .put("mature", i.mature).put("logo", i.logoUrl.orEmpty()).put("extra", JSONObject(i.extra as Map<*, *>)) + + private fun itemFrom(o: JSONObject): CatalogItem? { + val extra = LinkedHashMap() + o.optJSONObject("extra")?.let { e -> e.keys().forEach { k -> extra[k] = e.optString(k) } } + return CatalogItem( + store = store, id = o.optString("id").ifEmpty { return null }, title = o.optString("title").ifEmpty { return null }, + imageUrl = o.optString("image").ifEmpty { null }, tallImageUrl = o.optString("tall").ifEmpty { null }, tags = o.optString("tags"), + isFree = o.optBoolean("free"), hasPrice = o.optBoolean("hasPrice"), finalPrice = o.optString("final"), originalPrice = o.optString("orig"), + discountPercent = o.optInt("disc"), storeUrl = o.optString("url"), developer = o.optString("dev"), publisher = o.optString("pub"), + releaseDate = o.optString("rel"), description = o.optString("desc"), mature = o.optBoolean("mature"), + logoUrl = o.optString("logo").ifEmpty { null }, extra = extra, + ) + } + + companion object { + /** On an owned game standing in for a store card: the card's id, so a page opened on the card still finds it. */ + const val STORE_CARD = "storeCard" + private val SHELVES = listOf("new", "deals", "free", "trending") + private val MARKS = Regex("[\\u2122\\u00AE\\u00A9]") + private val COMBINING = Regex("\\p{M}+") + private val NOT_WORD = Regex("[^\\p{L}\\p{N}]+") + + /** A title reduced to letters and digits, so "Far Cry® 6" and "Far Cry 6" meet, and "Pokémon" meets "Pokemon". */ + fun titleKey(title: String): String = + Normalizer.normalize(title.replace(MARKS, ""), Normalizer.Form.NFD).replace(COMBINING, "") + .lowercase(Locale.ROOT).replace(NOT_WORD, " ").trim() + + /** + * Shelf cards the account owns become its library entry, which carries what installing needs, + * keeping the shelf's art and price. + */ + fun markOwned(s: StoreShelves, library: List?, match: (CatalogItem, CatalogItem) -> Boolean): StoreShelves { + if (library.isNullOrEmpty()) return s + fun mark(list: List) = markOwned(list, library, match) + return StoreShelves(mark(s.whatsNew), mark(s.deals), mark(s.free), mark(s.trending), s.art) + } + + fun markOwned(list: List, library: List?, match: (CatalogItem, CatalogItem) -> Boolean): List { + if (library.isNullOrEmpty()) return list + return list.map { shelf -> + val owned = library.firstOrNull { match(shelf, it) } ?: return@map shelf + owned.copy( + imageUrl = shelf.imageUrl ?: owned.imageUrl, tallImageUrl = owned.tallImageUrl ?: shelf.tallImageUrl, + tags = owned.tags.ifBlank { shelf.tags }, description = owned.description.ifBlank { shelf.description }, + releaseDate = owned.releaseDate.ifBlank { shelf.releaseDate }, storeUrl = shelf.storeUrl.ifBlank { owned.storeUrl }, + developer = owned.developer.ifBlank { shelf.developer }, mature = shelf.mature, + extra = owned.extra + (STORE_CARD to shelf.id), + ) + }.distinctBy { it.id } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt index e7a9383f32..40fedbded2 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt @@ -236,6 +236,27 @@ object StoresState { var itchPicking by mutableStateOf(null) var gameJoltPicking by mutableStateOf(null) + /** Store cards whose free game is being added to the account. */ + val claiming = mutableStateMapOf() + + fun canClaim(item: CatalogItem): Boolean = !item.accessible && isSignedIn(item.store) && backends[item.store]?.canClaim(item) == true + + /** Adds a free game to the account, then refreshes the library so it can be installed; [failed] runs when the store refused. */ + fun claim(context: Context, item: CatalogItem, failed: () -> Unit) { + val backend = backends[item.store] ?: return failed() + if (claiming.put(item.key, true) == true) return + val app = context.applicationContext + background("stores-claim", onFailure = { main.post { claiming.remove(item.key); failed() } }) { + val ok = backend.claim(app, item) + logLine("${item.store.label}: ${item.title} ${if (ok) "added to the library" else "could not be added; opening the store page"}") + if (ok) backend.syncLibrary(app, true) + main.post { + claiming.remove(item.key) + if (!ok) failed() + } + } + } + fun requestInstall(context: Context, item: CatalogItem) { askForNotifications(context) if (item.store == Store.ITCH && item.extra["uploadId"].isNullOrEmpty()) { itchPicking = item; return } @@ -359,6 +380,12 @@ interface StoreBackend { fun syncLibrary(context: Context, force: Boolean) fun loadShelves(context: Context, force: Boolean) fun search(context: Context, query: String): List = emptyList() + + /** Whether this store can add a free game to the account itself, rather than through its website. */ + fun canClaim(item: CatalogItem): Boolean = false + + /** Adds a free game to the account; true once the store has it in the account's library. */ + fun claim(context: Context, item: CatalogItem): Boolean = false fun install(context: Context, item: CatalogItem, root: java.io.File) fun uninstall(context: Context, game: InstalledStoreGame) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaApi.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaApi.kt index 185e23f424..55ecf79455 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaApi.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaApi.kt @@ -22,6 +22,7 @@ object EaApi { val downloadable: Boolean, val trial: Boolean, val ownership: List, + val productName: String = "", ) class Offer( @@ -109,6 +110,7 @@ object EaApi { downloadable = product.optBoolean("downloadable", true), trial = product.optJSONObject("trialDetails")?.optString("trialType").orEmpty().let { it.isNotEmpty() && it != "null" }, ownership = (0 until (methods?.length() ?: 0)).map { methods!!.optString(it) }, + productName = product.optString("name").replace("\n", " ").trim(), ) } val next = owned.optString("next").takeIf { it.isNotBlank() && it != "null" } @@ -197,6 +199,18 @@ object EaApi { } } + /** The free offer EA sells under a store slug, or null when the game has none. */ + fun freeOffer(token: String, slug: String): String? { + val variables = JSONObject().put("slug", slug).put("locale", "en-us").put("overrideCountryCode", "US") + val product = call(token, "GetGameProductOfferIds", variables).optJSONObject("game")?.optJSONObject("lowestPriceGameProduct") ?: return null + return product.optString("originOfferId").takeIf { product.optBoolean("isFree") && it.isNotBlank() && it != "null" } + } + + /** Adds a free offer to the account, as the EA app's "Get for free" does; the answer names what EA refused. */ + fun grantEntitlement(token: String, offerId: String): JSONObject = + call(token, "grantEntitlement", JSONObject().put("input", JSONObject().put("offerId", offerId).put("source", EaAuth.CLIENT_ID))) + .optJSONObject("grantEntitlement") ?: throw EaApiException(0, "EA gave no answer to the grant") + fun legacyEntitlements(token: String): List { val out = ArrayList() var next: String? = "0" diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt index 091243ae53..bd8d5c1212 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt @@ -11,6 +11,7 @@ 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.StoreFront import com.droiddeck.launcher.stores.StoreInstallRoot import com.droiddeck.launcher.stores.StoreLoginActivity import com.droiddeck.launcher.stores.StoresState @@ -40,6 +41,8 @@ object EaBackend : StoreBackend { val app = context.applicationContext EaAuth.signOut(app) EaLibrary.reset(app) + signOuts.incrementAndGet() + StoresState.post { StoresState.shelves.remove(store) } EaUpdates.available.clear() runCatching { WebCookies.expire(EaLogin.SIGN_IN_URLS, ".ea.com", listOf("/")) {} } } @@ -50,7 +53,32 @@ object EaBackend : StoreBackend { Thread({ EaLibrary.sync(app, force) }, "ea-sync").start() } - override fun loadShelves(context: Context, force: Boolean) {} + override fun loadShelves(context: Context, force: Boolean) { + val app = context.applicationContext + val account = signOuts.get() + EaStore.cached(app)?.let { s -> StoresState.post { StoresState.shelves[store] = StoreFront.markOwned(s, StoresState.library[store], EaStore::sameGame) } } + Thread({ + val shelves = EaStore.featured(app, force) ?: return@Thread + StoresState.post { if (signOuts.get() == account) StoresState.shelves[store] = StoreFront.markOwned(shelves, StoresState.library[store], EaStore::sameGame) } + }, "ea-shelves").start() + } + + private val signOuts = java.util.concurrent.atomic.AtomicInteger() + + override fun canClaim(item: CatalogItem): Boolean = item.isFree && !item.extra["slug"].isNullOrEmpty() + + override fun claim(context: Context, item: CatalogItem): Boolean { + val app = context.applicationContext + val token = EaAuth.accessToken(app) ?: return false + val slug = item.extra["slug"] ?: return false + val offer = EaApi.freeOffer(token, slug) ?: run { StoresState.logLine("ea: no free offer for $slug"); return false } + val answer = EaApi.grantEntitlement(token, offer) + StoresState.logLine("ea: grant $offer for $slug: $answer") + return answer.optBoolean("success") || answer.optJSONArray("entitledOfferIds")?.let { ids -> (0 until ids.length()).any { ids.optString(it) == offer } } == true + } + + override fun search(context: Context, query: String): List = + StoreFront.markOwned(EaStore.search(context.applicationContext, query), StoresState.library[store], EaStore::sameGame) override fun install(context: Context, item: CatalogItem, root: java.io.File) { val app = context.applicationContext diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaLibrary.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaLibrary.kt index 37fd6269f8..336b8b6390 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaLibrary.kt @@ -5,8 +5,8 @@ import android.content.SharedPreferences import com.droiddeck.launcher.R import com.droiddeck.launcher.stores.CatalogItem import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreFront import com.droiddeck.launcher.stores.StoreNet -import com.droiddeck.launcher.stores.StoreShelves import com.droiddeck.launcher.stores.StoresState import com.droiddeck.launcher.stores.mergeItems import org.json.JSONArray @@ -36,13 +36,14 @@ data class EaGame( val masterTitleId: String = "", val cloudSaves: String = "", val locales: List = emptyList(), + val productName: String = "", ) { fun toJson(): JSONObject = JSONObject() .put("offerId", offerId).put("contentId", contentId).put("title", title).put("slug", slug) .put("tall", tall).put("wide", wide).put("logo", logo).put("version", version) .put("executePath", executePath).put("installCheck", installCheck).put("parameters", parameters) .put("multiplayerId", multiplayerId).put("masterTitleId", masterTitleId).put("cloudSaves", cloudSaves) - .put("locales", JSONArray(locales)) + .put("locales", JSONArray(locales)).put("productName", productName) companion object { fun fromJson(o: JSONObject): EaGame? { @@ -63,14 +64,15 @@ data class EaGame( masterTitleId = o.optString("masterTitleId"), cloudSaves = o.optString("cloudSaves"), locales = (0 until (locales?.length() ?: 0)).map { locales!!.optString(it) }, + productName = o.optString("productName"), ) } } } object EaLibrary { - private const val KEY_CACHE = "library_cache_v2" - private const val KEY_SYNCED_AT = "library_synced_at_v2" + private const val KEY_CACHE = "library_cache_v3" + private const val KEY_SYNCED_AT = "library_synced_at_v3" private const val THROTTLE_MS = 6 * 60 * 60 * 1000L private const val ART_TTL_MS = 7 * 24 * 60 * 60 * 1000L private const val ART_THREADS = 4 @@ -118,7 +120,7 @@ object EaLibrary { owned = true, sizeBytes = prefs.getLong("size_${g.offerId}", 0L), storeUrl = STORE_URL, - extra = mapOf("contentId" to g.contentId, "slug" to g.slug, "version" to g.version), + extra = mapOf("contentId" to g.contentId, "slug" to g.slug, "version" to g.version, "productName" to g.productName), logoUrl = g.logo.ifEmpty { null }, ) } @@ -199,8 +201,7 @@ object EaLibrary { StoresState.post { if (gen != generation.get()) return@post StoresState.library[store] = mergeItems(StoresState.library[store], items) - val installed = StoresState.installed.filter { it.sidecar.store == store }.map { it.sidecar.id }.toSet() - StoresState.shelves[store] = StoreShelves(trending = items.filterNot { it.id in installed }, art = StoresState.shelves[store]?.art.orEmpty()) + StoresState.shelves[store]?.let { StoresState.shelves[store] = StoreFront.markOwned(it, items, EaStore::sameGame) } } } @@ -271,6 +272,7 @@ object EaLibrary { tall = img?.tall.orEmpty(), wide = img?.wide.orEmpty(), logo = img?.logo.orEmpty(), version = offer.gameVersion, executePath = offer.executePathOverride, installCheck = offer.installCheckOverride, parameters = offer.executeParameters, multiplayerId = offer.multiplayerId, masterTitleId = offer.masterTitleId, cloudSaves = offer.cloudSaves, locales = offer.locales, + productName = o.productName, ) } if (!storeCache(app, games, gen)) return diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaStore.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaStore.kt new file mode 100644 index 0000000000..b585dfec98 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaStore.kt @@ -0,0 +1,120 @@ +package com.droiddeck.launcher.stores.ea + +import android.content.Context +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreFront +import com.droiddeck.launcher.stores.StoreNet +import com.droiddeck.launcher.stores.StoreShelves +import com.droiddeck.launcher.stores.cleanStoreText +import org.json.JSONObject +import java.time.Instant +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit + +/** EA's PC catalog, read from the game pages ea.com renders for the EA app's games. */ +object EaStore { + private const val SITE = "https://www.ea.com" + private const val CATALOG = "$SITE/games/library/pc-download" + private const val PAGE_SIZE = 12 + private const val MAX_PAGES = 20 + private const val SHELF = 24 + private val NEXT_DATA = Regex("""""", RegexOption.DOT_MATCHES_ALL) + + private var front: StoreFront? = null + + private fun front(context: Context): StoreFront = synchronized(this) { + front ?: StoreFront(Store.EA, { EaPrefs.get(context) }, { fetchAll().let { StoreFront.Catalog(shelves(it), it) } }, key = "store_front_catalog").also { front = it } + } + + fun cached(context: Context): StoreShelves? = front(context).cached() + + fun featured(context: Context, force: Boolean): StoreShelves? = front(context).shelves(force) + + fun search(context: Context, query: String): List { + val q = StoreFront.titleKey(query) + if (q.length < 2) return emptyList() + return front(context).everything().filter { StoreFront.titleKey(it.title).contains(q) } + } + + /** Whether a store card and a library entry are the same game. */ + fun sameGame(shelf: CatalogItem, owned: CatalogItem): Boolean { + val slug = shelf.extra["slug"].orEmpty() + if (slug.isNotEmpty() && slug == owned.extra["slug"]) return true + val shelfKey = StoreFront.titleKey(shelf.title).ifEmpty { return false } + return listOf(owned.title, owned.extra["productName"].orEmpty()).any { StoreFront.titleKey(it) == shelfKey } + } + + /** + * The device's currency. ea.com's pages are cached with whichever region asked first, so one page can carry + * roubles and the next dollars; a price in another currency is left off rather than shown wrong. + */ + private fun localCurrency(): String = + runCatching { java.util.Currency.getInstance(java.util.Locale.getDefault()).currencyCode }.getOrNull() ?: "USD" + + internal fun parsePage(html: String, currency: String = localCurrency()): Pair, Int> { + val data = NEXT_DATA.find(html)?.groupValues?.get(1) ?: return emptyList() to 0 + val props = JSONObject(data).optJSONObject("props")?.optJSONObject("pageProps") ?: return emptyList() to 0 + val games = props.optJSONArray("games") ?: return emptyList() to 0 + val items = (0 until games.length()).mapNotNull { games.optJSONObject(it) }.mapNotNull { item(it, currency) } + return items to props.optInt("totalItems", items.size) + } + + internal fun item(g: JSONObject, currency: String): CatalogItem? { + fun s(o: JSONObject?, k: String) = o?.optString(k)?.takeIf { it.isNotBlank() && it != "null" } + val slug = s(g, "slug") ?: return null + val title = s(g, "title")?.replace("\n", " ")?.trim() ?: return null + val art = g.optJSONObject("packArt") + val price = g.optJSONObject("price") + val total = s(price, "displayTotal").orEmpty() + val now = s(price, "displayTotalWithDiscount") ?: total + val discount = price?.optInt("discountPercentage") ?: 0 + val free = g.optBoolean("isFreeToPlay") || now.filter { it.isDigit() }.trimStart('0').isEmpty() && now.isNotEmpty() + val shown = !free && s(price, "currency").equals(currency, true) + val genres = g.optJSONArray("genres") + val franchise = s(g, "franchiseSlug") + return CatalogItem( + store = Store.EA, id = "ea-store:$slug", title = title, + imageUrl = s(art, "ar16X9") ?: s(art, "ar2X1"), tallImageUrl = s(art, "ar2X3") ?: s(art, "ar3X4"), + tags = (0 until (genres?.length() ?: 0)).mapNotNull { genres!!.optJSONObject(it)?.optString("name")?.takeIf(String::isNotBlank) }.take(3).joinToString(", "), + isFree = free, hasPrice = shown, finalPrice = if (shown) now else "", + originalPrice = if (shown && discount > 0) total else "", discountPercent = discount.coerceAtLeast(0), + storeUrl = if (franchise != null) "$SITE/games/$franchise/$slug" else "$SITE/games/$slug", + publisher = "Electronic Arts", releaseDate = s(g, "releaseDate")?.take(10).orEmpty(), + description = cleanStoreText(s(g, "shortDescription")), + extra = buildMap { put("slug", slug); s(g, "tier")?.let { put("tier", it) } }, + ) + } + + private fun page(n: Int): Pair, Int>? = + StoreNet.get(if (n == 1) CATALOG else "$CATALOG?page=$n", headers = mapOf("Accept" to "text/html"))?.let(::parsePage) + + /** Every page of the catalog; a page that fails fails the whole refresh, so a partial list never replaces a good one. */ + private fun fetchAll(): List { + val (first, total) = page(1) ?: throw java.io.IOException("ea.com catalog page 1 failed") + val pages = ((total + PAGE_SIZE - 1) / PAGE_SIZE).coerceIn(1, MAX_PAGES) + val rest = java.util.concurrent.ConcurrentHashMap>() + val pool = Executors.newFixedThreadPool(4) + try { + for (n in 2..pages) pool.execute { page(n)?.first?.let { rest[n] = it } } + } finally { + pool.shutdown() + if (!pool.awaitTermination(1, TimeUnit.MINUTES)) pool.shutdownNow() + } + (2..pages).firstOrNull { !rest.containsKey(it) }?.let { throw java.io.IOException("ea.com catalog page $it failed") } + return (first + (2..pages).flatMap { rest.getValue(it) }).distinctBy { it.id } + } + + internal fun shelves(all: List, now: Instant = Instant.now()): StoreShelves { + val today = now.toString().take(10) + val released = all.filter { it.releaseDate.isNotEmpty() && it.releaseDate <= today } + val headline = released.filter { it.extra["tier"] == "Tier1" || it.extra["tier"] == "Tier2" } + return StoreShelves( + whatsNew = released.sortedByDescending { it.releaseDate }.take(SHELF), + deals = released.filter { it.discountPercent > 0 }.sortedByDescending { it.discountPercent }.take(SHELF), + free = released.filter { it.isFree }.take(SHELF), + trending = (headline + released).distinctBy { it.id }.take(SHELF), + art = all.mapNotNull { it.imageUrl }.take(SHELF), + ) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt index 8a4b253135..5d1a8c31bc 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt @@ -10,6 +10,7 @@ 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.StoreFront import com.droiddeck.launcher.stores.StoreInstallRoot import com.droiddeck.launcher.stores.download.DownloadEntry import com.droiddeck.launcher.stores.download.DownloadQueue @@ -44,7 +45,18 @@ object UbisoftBackend : StoreBackend { Thread({ UbisoftLibrary.sync(app, force) }, "ubisoft-sync").start() } - override fun loadShelves(context: Context, force: Boolean) {} + override fun loadShelves(context: Context, force: Boolean) { + val app = context.applicationContext + val account = UbisoftLibrary.account() + UbisoftStore.cached(app)?.let { s -> StoresState.post { StoresState.shelves[store] = StoreFront.markOwned(s, StoresState.library[store], UbisoftStore::sameGame) } } + Thread({ + val shelves = UbisoftStore.featured(app, force) ?: return@Thread + StoresState.post { if (UbisoftLibrary.account() == account) StoresState.shelves[store] = StoreFront.markOwned(shelves, StoresState.library[store], UbisoftStore::sameGame) } + }, "ubisoft-shelves").start() + } + + override fun search(context: Context, query: String): List = + StoreFront.markOwned(UbisoftStore.search(query), StoresState.library[store], UbisoftStore::sameGame) override fun install(context: Context, item: CatalogItem, root: java.io.File) { val app = context.applicationContext @@ -97,6 +109,9 @@ object UbisoftLibrary { StoresState.post { StoresState.shelves.remove(Store.UBISOFT) } } + /** Changes on every sign-out, so work begun for the old account can tell. */ + fun account(): Int = generation.get() + private fun post(gen: Int, block: () -> Unit) = StoresState.post { if (generation.get() == gen) block() } internal fun parsePage(body: String): Pair, Int> { @@ -224,8 +239,7 @@ object UbisoftLibrary { StoresState.status.remove(Store.UBISOFT) StoresState.problems.remove(Store.UBISOFT) StoresState.library[Store.UBISOFT] = games - StoresState.shelves[Store.UBISOFT] = com.droiddeck.launcher.stores.StoreShelves( - trending = games.sortedByDescending { it.extra.containsKey("productId") }, art = games.mapNotNull { it.imageUrl }) + StoresState.shelves[Store.UBISOFT]?.let { StoresState.shelves[Store.UBISOFT] = StoreFront.markOwned(it, games, UbisoftStore::sameGame) } } StoresState.logLine("Ubisoft: ${games.size} owned games") } catch (e: Exception) { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftStore.kt b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftStore.kt new file mode 100644 index 0000000000..13edb2084f --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftStore.kt @@ -0,0 +1,129 @@ +package com.droiddeck.launcher.stores.ubisoft + +import android.content.Context +import android.net.Uri +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreFront +import com.droiddeck.launcher.stores.StoreNet +import com.droiddeck.launcher.stores.StoreShelves +import com.droiddeck.launcher.stores.cleanStoreText +import com.droiddeck.launcher.stores.matureByAge +import org.json.JSONArray +import org.json.JSONObject +import java.text.NumberFormat +import java.time.Instant +import java.util.Currency +import java.util.Locale + +/** Ubisoft's PC catalog, from the product search the Ubisoft Store website uses. */ +object UbisoftStore { + /** The Ubisoft Store website's own read-only search key, sent by every store page. */ + private const val APP = "XELY3U4LOD" + private const val KEY = "5638539fd9edb8f2c6b024b49ec375bd" + private const val SHELF = 24 + private val RATING_AGE = mapOf("esrb-m" to 17, "esrb-ao" to 18, "pegi-18" to 18, "pegi-16" to 16, "usk-18" to 18) + + /** The store sites with an English catalog: site, index locale, currency. */ + private val SITES = mapOf( + "US" to Triple("us", "en_US", "USD"), "GB" to Triple("uk", "en_GB", "GBP"), + "CA" to Triple("ca", "en_CA", "CAD"), "AU" to Triple("anz", "en_AU", "AUD"), "NZ" to Triple("anz", "en_AU", "NZD"), + ) + + private fun site() = SITES[Locale.getDefault().country.uppercase(Locale.ROOT)] ?: SITES.getValue("US") + + private fun index(site: Triple, order: String) = "production__${site.first}_ubisoft__products__${site.second}__$order" + + private val fronts = HashMap, StoreFront>() + + /** Each store site keeps its own shelves, so a region change never shows another region's prices. */ + private fun front(context: Context): StoreFront = synchronized(fronts) { + val site = site() + fronts.getOrPut(site) { + StoreFront(Store.UBISOFT, { context.applicationContext.getSharedPreferences("stores.ubisoft", Context.MODE_PRIVATE) }, + { fetch(site) }, key = "store_front_${site.first}_${site.third}") + } + } + + fun cached(context: Context): StoreShelves? = front(context).cached() + + fun featured(context: Context, force: Boolean): StoreShelves? = front(context).shelves(force) + + fun search(query: String): List { + val term = query.trim() + if (term.length < 2) return emptyList() + return query(site(), "best_sellers", 40, query = term).orEmpty() + } + + /** Whether a store card and a library entry are the same game. */ + fun sameGame(shelf: CatalogItem, owned: CatalogItem): Boolean { + val product = shelf.extra["productId"].orEmpty() + if (product.isNotEmpty() && product == owned.extra["productId"]) return true + val key = StoreFront.titleKey(owned.title) + return key.isNotEmpty() && key == baseTitle(shelf.title) + } + + /** A product title without its edition, so "Far Cry® 6 - Gold Edition" is "far cry 6". */ + internal fun baseTitle(title: String): String = StoreFront.titleKey(title.substringBefore(" - ")) + + /** One page of the index, or null when Ubisoft did not answer. */ + private fun query(site: Triple, order: String, hits: Int, query: String = "", filters: String = "", facets: List = emptyList()): List? { + val facetFilters = JSONArray().put("product_type:Games").put("Platform:PC (Digital)").apply { facets.forEach { put(it) } } + val url = Uri.parse("https://$APP-dsn.algolia.net/1/indexes/${index(site, order)}").buildUpon() + .appendQueryParameter("query", query) + .appendQueryParameter("hitsPerPage", (hits * 2).toString()) + .appendQueryParameter("facetFilters", facetFilters.toString()) + .apply { if (filters.isNotEmpty()) appendQueryParameter("filters", filters) } + .build().toString() + val body = StoreNet.get(url, headers = mapOf("X-Algolia-Application-Id" to APP, "X-Algolia-API-Key" to KEY)) ?: return null + return parse(JSONObject(body), site.third).take(hits) + } + + internal fun parse(answer: JSONObject, currency: String, now: Instant = Instant.now()): List { + val hits = answer.optJSONArray("hits") ?: return emptyList() + val items = (0 until hits.length()).mapNotNull { hits.optJSONObject(it) }.mapNotNull { item(it, currency, now) } + return items.groupBy { baseTitle(it.title) }.values.map { editions -> editions.firstOrNull { " - " !in it.title } ?: editions.first() } + } + + private fun money(amount: Double, currency: String): String = NumberFormat.getCurrencyInstance(Locale.US).apply { + this.currency = Currency.getInstance(currency) + }.format(amount) + + internal fun item(h: JSONObject, currency: String, now: Instant): CatalogItem? { + fun s(k: String) = h.optString(k).takeIf { it.isNotBlank() && it != "null" } + val id = s("objectID") ?: s("id") ?: return null + val title = s("title") ?: s("name") ?: return null + if (s("Free_offer") == "demo") return null + val price = h.optJSONObject("price")?.optDouble(currency)?.takeUnless { it.isNaN() } + val base = h.optJSONObject("default_price")?.optDouble(currency)?.takeUnless { it.isNaN() } + val discount = s("promotion_percentage")?.toDoubleOrNull()?.toInt() ?: 0 + val released = s("release_date")?.let { runCatching { Instant.parse(it) }.getOrNull() } + if (released != null && released.isAfter(now) && s("preorder") != "true") return null + val free = s("Free_offer") == "freeplay" || price == 0.0 + val image = s("image_link")?.substringBefore("?") + return CatalogItem( + store = Store.UBISOFT, id = "ubisoft-store:$id", title = title.trim(), + imageUrl = image, tallImageUrl = image, tags = listOfNotNull(s("Genre"), s("Edition")).joinToString(", "), + isFree = free, hasPrice = price != null, finalPrice = price?.let { money(it, currency) }.orEmpty(), + originalPrice = if (discount > 0 && base != null) money(base, currency) else "", discountPercent = if (discount > 0 && base != null) discount else 0, + storeUrl = s("link") ?: s("linkWeb").orEmpty(), publisher = "Ubisoft", releaseDate = released?.toString()?.take(10).orEmpty(), + description = cleanStoreText(s("longDescription")), + mature = s("adult").equals("TRUE", true) || matureByAge(listOfNotNull(s("Rating")?.let(RATING_AGE::get))), + extra = buildMap { + s("productLauncherIDString")?.let { put("productId", it) } + if (s("partOfUbisoftPlus").equals("true", true)) put("ubisoftPlus", "true") + }, + ) + } + + /** All four rows, or a failure when any of them failed, so a partial refresh never replaces a good one. */ + private fun fetch(site: Triple): StoreFront.Catalog { + fun row(order: String, filters: String = "", facets: List = emptyList()) = + query(site, order, SHELF, filters = filters, facets = facets) ?: throw java.io.IOException("Ubisoft store $order $filters$facets failed") + val trending = row("best_sellers") + val newest = row("release_date") + val deals = row("best_sellers", filters = "promotion_percentage > 0") + val free = row("best_sellers", facets = listOf("Free_offer:freeplay")) + return StoreFront.Catalog(StoreShelves(whatsNew = newest, deals = deals, free = free, trending = trending, art = trending.mapNotNull { it.imageUrl })) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index f42a85de51..9ac3a96027 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -505,7 +505,12 @@ internal fun GameActions( InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) } SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) } } - item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true, modifier = leadOn) { openStoreUrl(ctx, item) } + item != null && item.isFree -> { + val adding = StoresState.claiming[item.key] == true + PrimaryButton(stringResource(if (adding) R.string.stores_claiming else R.string.stores_get_free), enabled = !adding, main = true, modifier = leadOn) { + if (StoresState.canClaim(item)) StoresState.claim(ctx, item) { openStoreUrl(ctx, item) } else openStoreUrl(ctx, item) + } + } item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) } } if (cloud && (download != null || failed != null)) { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 5dbf1a47eb..cc56dbb7a7 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -2335,6 +2335,7 @@ منقطع تثبيت · %1$s احصل عليها مجانًا + جارٍ الإضافة إلى المكتبة… عرض على %1$s شراء · %1$s مثبَّتة diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index a14f49e9a1..46e5035656 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -2304,6 +2304,7 @@ Interrumpida Instalar · %1$s Obtener gratis + Agregando a la biblioteca… Ver en %1$s Comprar · %1$s Instalado diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 09c26b8075..d3e14dd32c 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -2235,6 +2235,7 @@ Прекъснато Инсталация · %1$s Вземи безплатно + Добавяне в библиотеката… Виж в %1$s Купи · %1$s Инсталирана diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 43169adfb0..c318b3081b 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -2285,6 +2285,7 @@ Přerušeno Instalace · %1$s Získat zdarma + Přidávání do knihovny… Zobrazit na %1$s Koupit · %1$s Nainstalováno diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 3a41c0928b..0936040739 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -2235,6 +2235,7 @@ Afbrudt Installation · %1$s Få gratis + Føjer til biblioteket… Se på %1$s Køb · %1$s Installeret diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 53a0591334..1db47d2b34 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -2227,6 +2227,7 @@ Unterbrochen Installieren · %1$s Kostenlos erhalten + Wird zur Bibliothek hinzugefügt… Auf %1$s ansehen Kaufen · %1$s Installiert diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 1f2a7f6fa5..4fe414040c 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -2235,6 +2235,7 @@ Διακόπηκε Εγκατάσταση · %1$s Απόκτηση δωρεάν + Προσθήκη στη βιβλιοθήκη… Προβολή στο %1$s Αγορά · %1$s Εγκατεστημένο diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index bc362f264d..8cff6535ff 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -2260,6 +2260,7 @@ Interrumpida Instalar · %1$s Obtener gratis + Añadiendo a la biblioteca… Ver en %1$s Comprar · %1$s Instalado diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 70e0c2e8ee..71a1e78a74 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -2235,6 +2235,7 @@ Keskeytynyt Asenna · %1$s Hanki ilmaiseksi + Lisätään kirjastoon… Näytä %1$s:ssä Osta · %1$s Asennettu diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 8a8bd2cb69..a182aeb39a 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -2260,6 +2260,7 @@ Interrompu Installer · %1$s Obtenir gratuitement + Ajout à la bibliothèque… Voir sur %1$s Acheter · %1$s Installé diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 62f8a6d867..ad96817016 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -2235,6 +2235,7 @@ बाधित इंस्टॉल · %1$s मुफ़्त में पाएं + लाइब्रेरी में जोड़ा जा रहा है… %1$s पर देखें खरीदें · %1$s इंस्टॉल है diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 854208f327..26fafb1bd2 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -2235,6 +2235,7 @@ Megszakítva Telepítés · %1$s Ingyenes beszerzés + Hozzáadás a könyvtárhoz… Megtekintés itt: %1$s Megvétel · %1$s Telepítve diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index d18a42fe96..fc440af4e9 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -2210,6 +2210,7 @@ Terhenti Instal · %1$s Dapatkan gratis + Menambahkan ke pustaka… Lihat di %1$s Beli · %1$s Terinstal diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 655d1bb9e5..6e2493bc4b 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -2252,6 +2252,7 @@ Interrotto Installa · %1$s Ottieni gratis + Aggiunta alla libreria… Visualizza su %1$s Acquista · %1$s Installato diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 0b16c04969..326f88634d 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -2210,6 +2210,7 @@ 中断 インストール · %1$s 無料で入手 + ライブラリに追加中… %1$sで見る 購入 · %1$s インストール済み diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index ec2fc2dc3c..c93c5b0d20 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -2210,6 +2210,7 @@ 중단됨 설치 · %1$s 무료로 받기 + 라이브러리에 추가하는 중… %1$s에서 보기 구매 · %1$s 설치됨 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index ff08492061..6d0077c92e 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -2210,6 +2210,7 @@ Terganggu Pasang · %1$s Dapatkan percuma + Menambah ke pustaka… Lihat pada %1$s Beli · %1$s Dipasang diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 0be006b622..b95bffcc69 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -2235,6 +2235,7 @@ Avbrutt Installer · %1$s Hent gratis + Legger til i biblioteket … Vis på %1$s Kjøp · %1$s Installert diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 6097f32580..b9c476a349 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -2235,6 +2235,7 @@ Onderbroken Installeren · %1$s Gratis verkrijgen + Toevoegen aan bibliotheek… Bekijken op %1$s Kopen · %1$s Geïnstalleerd diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index bfe36b08d9..cba0b85efa 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -2285,6 +2285,7 @@ Przerwano Instalacja · %1$s Odbierz bezpłatnie + Dodawanie do biblioteki… Zobacz w %1$s Kup · %1$s Zainstalowano diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index e278e59f25..39b93f25b0 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -2252,6 +2252,7 @@ Interrompida Instalar · %1$s Obter grátis + A adicionar à biblioteca… Ver em %1$s Comprar · %1$s Instalado diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 9d2305b2b6..b4d3cf7ddd 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -2252,6 +2252,7 @@ Interrompido Instalar · %1$s Obter grátis + Adicionando à biblioteca… Ver em %1$s Comprar · %1$s Instalado diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index cbd0b85423..bd8696e74a 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -2260,6 +2260,7 @@ Întreruptă Instalare · %1$s Obține gratuit + Se adaugă în bibliotecă… Vezi pe %1$s Cumpără · %1$s Instalat diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 0bfb8f26ae..8dee9e4c9e 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -2368,6 +2368,7 @@ Прервано Установить · %1$s Получить бесплатно + Добавление в библиотеку… Открыть в %1$s Купить · %1$s Установлено diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 674f7ca9ff..5a35123390 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -2235,6 +2235,7 @@ Avbruten Installation · %1$s Hämta gratis + Lägger till i biblioteket … Visa på %1$s Köp · %1$s Installerat diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 31e38b728f..81017bbb02 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -2210,6 +2210,7 @@ ถูกขัดจังหวะ ติดตั้ง · %1$s รับไปเลยฟรี + กำลังเพิ่มลงในคลัง… ดูบน %1$s ซื้อ · %1$s ติดตั้งแล้ว diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index f66424d69d..b65fc85813 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -2227,6 +2227,7 @@ Kesintiye uğradı Yükle · %1$s Ücretsiz al + Kitaplığa ekleniyor… %1$s\'te görüntüle Satın al · %1$s Yüklü diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 8aebdeebdd..bd977f8e42 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -2285,6 +2285,7 @@ Перервано Встановити · %1$s Отримати безкоштовно + Додавання до бібліотеки… Переглянути на %1$s Купити · %1$s Встановлено diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index a6a392b8f0..a6411681d2 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -2210,6 +2210,7 @@ Bị gián đoạn Cài · %1$s Lấy miễn phí + Đang thêm vào thư viện… Xem trên %1$s Mua · %1$s Đã cài diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 45aebc4133..e3263afcc6 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -2291,6 +2291,7 @@ 已中断 安装 · %1$s 免费领取 + 正在添加到游戏库… 在 %1$s 上查看 购买 · %1$s 已安装 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 65b40bad57..6ea69859e5 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -2210,6 +2210,7 @@ 已中斷 安裝 · %1$s 免費領取 + 正在加入遊戲庫… 在 %1$s 查看 購買 · %1$s 已安裝 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index c05aeafcd3..6b34c26263 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -2210,6 +2210,7 @@ 已中斷 安裝 · %1$s 免費取得 + 正在加入收藏庫… 在 %1$s 檢視 購買 · %1$s 已安裝 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 114ec48d94..cc8da5f577 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2585,6 +2585,7 @@ Interrupted Install · %1$s Get for free + Adding to library… View on %1$s Buy · %1$s Installed diff --git a/app/src/main/resources/ea/graphql/GetGameProductOfferIds.gql b/app/src/main/resources/ea/graphql/GetGameProductOfferIds.gql new file mode 100644 index 0000000000..9c1c1dbd5c --- /dev/null +++ b/app/src/main/resources/ea/graphql/GetGameProductOfferIds.gql @@ -0,0 +1,15 @@ +query GetGameProductOfferIds($slug: String!, $locale: Locale!, $overrideCountryCode: String!) { + game(slug: $slug, locale: $locale) { + id + isFreeToPlay + slug + lowestPriceGameProduct(availabilities: [ACQUIRABLE], overrideCountryCode: $overrideCountryCode) { + id + isFree + name + originOfferId + __typename + } + __typename + } +} diff --git a/app/src/main/resources/ea/graphql/grantEntitlement.gql b/app/src/main/resources/ea/graphql/grantEntitlement.gql new file mode 100644 index 0000000000..9871d7231f --- /dev/null +++ b/app/src/main/resources/ea/graphql/grantEntitlement.gql @@ -0,0 +1,23 @@ +mutation grantEntitlement($input: GrantEntitlementInput!) { + grantEntitlement(input: $input) { + success + entitledOfferIds + entitlementType + errors { + ... on GrantEntitlementOfferDoesNotExistError { + __typename + } + ... on GrantEntitlementNotQualifiedError { + __typename + } + ... on GrantEntitlementNotFreeOrNoAppropriateSubscriptionError { + __typename + } + ... on GrantEntitlementUpstreamConflictError { + __typename + } + __typename + } + __typename + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt index 83c03495ae..b9deb11a11 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.stores.ea +import com.droiddeck.launcher.stores.CatalogItem import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoreGameSidecar import com.droiddeck.launcher.stores.StoreLaunch @@ -239,6 +240,47 @@ class EaTest { assertTrue(EaLibrary.withoutGameDownload(emptyList()).isEmpty()) } + @Test fun theStorePageNamesEachGameWithItsPrice() { + val game = { slug: String, title: String, date: String, price: String, sale: String, off: Int, free: Boolean -> + """{"slug":"$slug","title":"$title +","isFreeToPlay":$free,"franchiseSlug":"f","tier":"Tier1","releaseDate":"$date", + "packArt":{"ar16X9":"https://img/$slug-wide","ar2X3":"https://img/$slug-tall"},"genres":[{"name":"RPG"}], + "price":{"displayTotal":"$price","displayTotalWithDiscount":"$sale","discountPercentage":$off,"currency":"USD"}}""" + } + val html = """" + val (items, total) = EaStore.parsePage(html, "USD") + assertEquals("", EaStore.parsePage(html, "EUR").first.first().finalPrice) + assertEquals(40, total) + val ultima = items.first() + assertEquals("Ultima VII", ultima.title) + assertEquals("$2.49", ultima.finalPrice) + assertEquals("$4.99", ultima.originalPrice) + assertEquals(50, ultima.discountPercent) + assertEquals("https://www.ea.com/games/f/ultima-7", ultima.storeUrl) + assertTrue(items[1].isFree) + val shelves = EaStore.shelves(items, java.time.Instant.parse("2026-11-12T00:00:00Z")) + assertEquals(listOf("Ultima VII", "REDSEC"), shelves.whatsNew.map { it.title }) + assertEquals(listOf("Ultima VII"), shelves.deals.map { it.title }) + assertEquals(listOf("REDSEC"), shelves.free.map { it.title }) + val owned = CatalogItem(Store.EA, "Origin.OFR.1", "Ultima™ VII", null, owned = true, extra = mapOf("slug" to "other")) + val marked = com.droiddeck.launcher.stores.StoreFront.markOwned(shelves, listOf(owned), EaStore::sameGame) + assertEquals("Origin.OFR.1", marked.deals.single().id) + assertEquals("https://img/ultima-7-wide", marked.deals.single().imageUrl) + val bf = CatalogItem(Store.EA, "Origin.OFR.50.0005511", "Battlefield™", null, owned = true, extra = mapOf("slug" to "glacier", "productName" to "Battlefield™ 6")) + assertTrue(EaStore.sameGame(CatalogItem(Store.EA, "ea-store:battlefield-6", "Battlefield™ 6", null, extra = mapOf("slug" to "battlefield-6")), bf)) + assertFalse(EaStore.sameGame(CatalogItem(Store.EA, "ea-store:bf-2042", "Battlefield™ 2042", null), bf)) + } + + @Test fun titlesMatchAcrossMarksAndAccentsButNeverWhenEmpty() { + assertEquals("pokemon", com.droiddeck.launcher.stores.StoreFront.titleKey("Pokémon™")) + assertEquals("ファイナル 7", com.droiddeck.launcher.stores.StoreFront.titleKey("ファイナル® 7")) + val shelf = CatalogItem(Store.EA, "ea-store:a", "™", null) + assertFalse(EaStore.sameGame(shelf, CatalogItem(Store.EA, "Origin.OFR.2", "®", null, owned = true))) + } + @Test fun ownedPageParses() { val page = JSONObject( """{"me":{"ownedGameProducts":{"next":"100","items":[{"originOfferId":"Origin.OFR.50.0001","product":{"id":"x","name":"N","downloadable":true,"gameSlug":"titanfall-2", diff --git a/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt index 7f163ce351..aecf4ca779 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt @@ -45,6 +45,36 @@ class UbisoftTest { assertEquals(listOf("space-gone", "space-sc"), UbisoftLibrary.assemble(profile, null).map { it.id }) } + @Test fun theStoreSearchNamesEachGameWithItsPrice() { + fun hit(id: String, title: String, price: Double, base: Double, off: String, date: String, free: String = "") = JSONObject() + .put("objectID", id).put("title", title).put("price", JSONObject().put("USD", price)).put("default_price", JSONObject().put("USD", base)) + .put("promotion_percentage", off).put("release_date", date).put("Free_offer", free).put("link", "https://store.ubisoft.com/us/$id.html") + .put("image_link", "https://img/$id.jpg?sw=300").put("productLauncherIDString", id.takeLast(3)).put("Rating", "esrb-m") + val answer = JSONObject().put("hits", JSONArray() + .put(hit("p-109", "Far Cry® 6", 15.0, 60.0, "75", "2021-10-07T00:00:00.000Z")) + .put(hit("p-110", "Far Cry® 6 - Gold Edition", 30.0, 100.0, "70", "2021-10-07T00:00:00.000Z")) + .put(hit("p-111", "Some Demo", 0.0, 0.0, "", "2021-10-07T00:00:00.000Z", free = "demo")) + .put(hit("p-112", "Next Year", 70.0, 70.0, "", "2030-01-01T00:00:00.000Z"))) + val items = UbisoftStore.parse(answer, "USD", java.time.Instant.parse("2026-11-12T00:00:00Z")) + assertEquals(listOf("Far Cry® 6"), items.map { it.title }) + val game = items.single() + assertEquals("$15.00", game.finalPrice) + assertEquals("$60.00", game.originalPrice) + assertEquals(75, game.discountPercent) + assertEquals("https://img/p-109.jpg", game.imageUrl) + assertTrue(game.mature) + val owned = CatalogItem(Store.UBISOFT, "space-fc6", "Far Cry 6", null, owned = true, extra = mapOf("productId" to "5266")) + val ezio = CatalogItem(Store.UBISOFT, "ubisoft-store:x", "Assassin's Creed® The Ezio Collection", null) + assertTrue(UbisoftStore.sameGame(game, owned)) + assertTrue(!UbisoftStore.sameGame(ezio, CatalogItem(Store.UBISOFT, "space-ac", "Assassin's Creed™", null, owned = true))) + } + + @Test fun theBaseEditionStandsForItsGameWhicheverComesFirst() { + fun hit(id: String, title: String) = JSONObject().put("objectID", id).put("title", title).put("price", JSONObject().put("USD", 10.0)) + val answer = JSONObject().put("hits", JSONArray().put(hit("gold", "Far Cry® 6 - Gold Edition")).put(hit("base", "Far Cry® 6"))) + assertEquals(listOf("ubisoft-store:base"), UbisoftStore.parse(answer, "USD").map { it.id }) + } + @Test fun theEntitlementNamesTheGamesApplication() { val body = JSONObject().put("items", JSONArray() .put(JSONObject().put("productId", 82).put("applicationId", "app-82"))