Modern Apps git

← Modern-Apps.git

fix lint issues

Commit
827ba555669f83f500a3c37b58431449eb920669
Author
vayun-mathur <[email protected]>
When
2026-10-05 17:56 UTC (2 months ago)
Parents
e563d15

Diff

Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 212d65e9b7..522e4b7380 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -967,8 +967,8 @@ dependencies = [  "ctr",  "ed25519-dalek",  "hex",- "hkdf 0.12.4",- "hmac 0.12.1",+ "hkdf 0.13.0",+ "hmac 0.13.0",  "p256",  "rand 0.8.8",  "rand_chacha 0.3.1",@@ -3988,7 +3988,7 @@ dependencies = [  "crypto_provider_default",  "getrandom 0.2.17",  "hkdf 0.12.4",- "hmac 0.12.1",+ "hmac 0.13.0",  "jni",  "np_adv",  "p256",@@ -4584,7 +4584,7 @@ dependencies = [  "eyre",  "getrandom 0.2.17",  "hex",- "hmac 0.12.1",+ "hmac 0.13.0",  "jni",  "libc",  "parking_lot",
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex 7176c69491..e4289cbdc1 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -149,7 +149,7 @@ openmls_basic_credential = "0.6.0" openmls_traits = "0.6.0" tls_codec = "0.5.0" x25519-dalek = { version = "2.0.1", default-features = false, features = ["static_secrets"] }-hmac = "0.12.1"+hmac = "0.13.0" subtle = "2.6.1" fips203 = "0.4.3" fips204 = "0.4.6"@@ -223,7 +223,7 @@ rand_pcg = "0.3.1" base64 = "0.22.1" ctr = "0.9.2" cbc = { version = "0.1.2", features = ["block-padding"] }-hkdf = "0.12.3"+hkdf = "0.13.0" aes-gcm = "0.10.3" aes-gcm-siv = { version = "0.11.1", features = ["aes"], default-features = false } aead = "0.5.1"
appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.ktindex 0292e01066..fcc5de969d 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt@@ -281,7 +281,10 @@ interface CachedAppDao {     )     suspend fun searchAll(q: String, limit: Int): List<CachedAppEntity> -    @Query("SELECT * FROM CachedAppEntity WHERE packageName LIKE '%' || :q || '%' OR name LIKE '%' || :q || '%' ORDER BY name ASC")+    @Query(+        "SELECT * FROM CachedAppEntity WHERE packageName LIKE '%' || :q || '%' " ++            "OR name LIKE '%' || :q || '%' ORDER BY name ASC"+    )     fun searchFlow(q: String): Flow<List<CachedAppEntity>>      @Query("SELECT * FROM CachedAppEntity")@@ -369,10 +372,14 @@ abstract class AppDatabase : RoomDatabase() {                     connection.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN installs INTEGER NOT NULL DEFAULT 0")                     connection.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN updatedOn TEXT")                     connection.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN contentRating TEXT")-                    connection.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN containsAds INTEGER NOT NULL DEFAULT 0")+                    connection.execSQL(+                        "ALTER TABLE CachedAppEntity ADD COLUMN containsAds INTEGER NOT NULL DEFAULT 0"+                    )                     connection.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN antiFeatures TEXT")                     connection.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN whatsNew TEXT")-                    connection.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN addedTimestamp INTEGER NOT NULL DEFAULT 0")+                    connection.execSQL(+                        "ALTER TABLE CachedAppEntity ADD COLUMN addedTimestamp INTEGER NOT NULL DEFAULT 0"+                    )                 }             },             object : Migration(5, 6) {
appstore/src/main/java/com/vayunmathur/appstore/data/FDroidJson.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidJson.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidJson.ktnew file mode 100644index 0000000000..30115358f3--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidJson.kt@@ -0,0 +1,300 @@+package com.vayunmathur.appstore.data++import android.util.JsonReader+import android.util.JsonToken+import java.io.IOException++/**+ * Scalar JsonReader helpers for the F-Droid index-v2 streaming parser.+ *+ * Extracted from [FDroidRepository] so the repository object stays under+ * detekt's TooManyFunctions cap. All functions are internal top-level:+ * same module, no behavior change.+ */++internal fun readLocalizedString(reader: JsonReader): String? {+    return when (reader.peek()) {+        JsonToken.STRING -> reader.nextString()+        JsonToken.BEGIN_OBJECT -> readLocalizedObject(reader)+        else -> {+            reader.skipValue()+            null+        }+    }+}++private fun readLocalizedObject(reader: JsonReader): String? {+    var first: String? = null+    var enUs: String? = null+    var en: String? = null+    reader.beginObject()+    while (reader.hasNext()) {+        val locale = reader.nextName()+        if (reader.peek() != JsonToken.STRING) {+            reader.skipValue()+            continue+        }+        val v = reader.nextString()+        if (first == null) first = v+        if (locale == LOCALE_US) enUs = v+        if (locale == LOCALE_EN) en = v+    }+    reader.endObject()+    return enUs ?: en ?: first+}++internal fun readIconName(reader: JsonReader): String? {+    // icon can be: { "en-US": { "96": {"name":...} } } or { "en-US": {"name":...} }+    return try {+        if (reader.peek() != JsonToken.BEGIN_OBJECT) {+            reader.skipValue()+            return null+        }+        var found: String? = null+        reader.beginObject()+        while (reader.hasNext() && found == null) {+            reader.nextName() // locale+            found = findFirstNameInAnyNested(reader)+        }+        while (reader.hasNext()) {+            reader.nextName()+            reader.skipValue()+        }+        reader.endObject()+        found+    } catch (_: IOException) {+        null+    } catch (_: IllegalStateException) {+        null+    }+}++internal fun findFirstNameInAnyNested(reader: JsonReader): String? {+    // searches recursively for first object containing key "name" = String+    return when (reader.peek()) {+        JsonToken.BEGIN_OBJECT -> findNameInObject(reader)+        JsonToken.BEGIN_ARRAY -> findNameInArray(reader)+        else -> {+            reader.skipValue()+            null+        }+    }+}++private fun findNameInObject(reader: JsonReader): String? {+    var found: String? = null+    reader.beginObject()+    while (reader.hasNext()) {+        val key = reader.nextName()+        found = found ?: readNameOrNested(reader, key)+    }+    reader.endObject()+    return found+}++private fun readNameOrNested(reader: JsonReader, key: String): String? {+    if (key == "name" && reader.peek() == JsonToken.STRING) {+        return reader.nextString()+    }+    if (reader.peek() == JsonToken.BEGIN_OBJECT) {+        return findFirstNameInAnyNested(reader)+    }+    reader.skipValue()+    return null+}++private fun findNameInArray(reader: JsonReader): String? {+    reader.beginArray()+    var found: String? = null+    while (reader.hasNext() && found == null) {+        found = findFirstNameInAnyNested(reader)+    }+    while (reader.hasNext()) reader.skipValue()+    reader.endArray()+    return found+}++/**+ * index-v2 `screenshots`: `{ phone: { "en-US": [ { name, sha256, size }, … ] }, … }`.+ *+ * Only the phone set is taken — the tablet, TV and wear sets are the same app shot on+ * hardware the reader isn't holding, and mixing them makes the carousel jump between+ * aspect ratios. Falls back to whichever set exists if there is no phone one.+ */+internal fun readScreenshotsV2(reader: JsonReader, repoBase: String): List<String> {+    if (reader.peek() != JsonToken.BEGIN_OBJECT) {+        reader.skipValue()+        return emptyList()+    }+    var phone: List<String> = emptyList()+    var fallback: List<String> = emptyList()+    reader.beginObject()+    while (reader.hasNext()) {+        val kind = reader.nextName()+        val shots = readLocalizedFileList(reader, repoBase)+        if (kind == SCREENSHOT_PHONE) {+            phone = shots+        } else if (fallback.isEmpty()) {+            fallback = shots+        }+    }+    reader.endObject()+    return phone.ifEmpty { fallback }+}++/** `{ "en-US": [ { "name": "/pkg/en-US/phoneScreenshots/1.png" }, … ], … }`. */+private fun readLocalizedFileList(reader: JsonReader, repoBase: String): List<String> {+    if (reader.peek() != JsonToken.BEGIN_OBJECT) {+        reader.skipValue()+        return emptyList()+    }+    var enUs: List<String>? = null+    var en: List<String>? = null+    var first: List<String>? = null+    reader.beginObject()+    while (reader.hasNext()) {+        val locale = reader.nextName()+        val names = readFileNameArray(reader).map { repoBase + "/" + it.trimStart('/') }+        if (first == null) first = names+        when (locale) {+            LOCALE_US -> enUs = names+            LOCALE_EN -> en = names+        }+    }+    reader.endObject()+    return enUs ?: en ?: first ?: emptyList()+}++/** `[ { "name": …, "sha256": …, "size": … }, … ]` reduced to the names. */+private fun readFileNameArray(reader: JsonReader): List<String> {+    if (reader.peek() != JsonToken.BEGIN_ARRAY) {+        reader.skipValue()+        return emptyList()+    }+    val names = mutableListOf<String>()+    reader.beginArray()+    while (reader.hasNext()) {+        if (reader.peek() != JsonToken.BEGIN_OBJECT) {+            reader.skipValue()+            continue+        }+        reader.beginObject()+        while (reader.hasNext()) {+            if (reader.nextName() == "name") {+                nextStringOrNull(reader)?.let { names.add(it) }+            } else {+                reader.skipValue()+            }+        }+        reader.endObject()+    }+    reader.endArray()+    return names+}++/** Keys of an object whose values are of no interest, e.g. v2's anti-feature map. */+internal fun readObjectKeys(reader: JsonReader): List<String> {+    if (reader.peek() != JsonToken.BEGIN_OBJECT) {+        reader.skipValue()+        return emptyList()+    }+    val keys = mutableListOf<String>()+    reader.beginObject()+    while (reader.hasNext()) {+        keys.add(reader.nextName())+        reader.skipValue()+    }+    reader.endObject()+    return keys+}++internal fun readStringArray(reader: JsonReader): List<String> {+    return try {+        if (reader.peek() != JsonToken.BEGIN_ARRAY) {+            reader.skipValue()+            return emptyList()+        }+        val list = mutableListOf<String>()+        reader.beginArray()+        while (reader.hasNext()) {+            if (reader.peek() == JsonToken.STRING) {+                list.add(reader.nextString())+            } else {+                reader.skipValue()+            }+        }+        reader.endArray()+        list+    } catch (_: IOException) {+        emptyList()+    } catch (_: IllegalStateException) {+        emptyList()+    }+}++internal fun nextStringOrNull(reader: JsonReader): String? {+    return try {+        when (reader.peek()) {+            JsonToken.STRING -> reader.nextString()+            JsonToken.NULL -> {+                reader.nextNull()+                null+            }+            JsonToken.NUMBER -> reader.nextString()+            else -> {+                reader.skipValue()+                null+            }+        }+    } catch (_: IOException) {+        null+    } catch (_: IllegalStateException) {+        null+    }+}++internal fun nextLongOrNull(reader: JsonReader): Long? {+    return try {+        when (reader.peek()) {+            JsonToken.NUMBER -> reader.nextLong()+            JsonToken.STRING -> reader.nextString().toLongOrNull()+            JsonToken.NULL -> {+                reader.nextNull()+                null+            }+            else -> {+                reader.skipValue()+                null+            }+        }+    } catch (_: IOException) {+        null+    } catch (_: IllegalStateException) {+        null+    }+}++internal fun nextIntOrNull(reader: JsonReader): Int? {+    return try {+        when (reader.peek()) {+            JsonToken.NUMBER -> reader.nextInt()+            JsonToken.STRING -> reader.nextString().toIntOrNull()+            JsonToken.NULL -> {+                reader.nextNull()+                null+            }+            else -> {+                reader.skipValue()+                null+            }+        }+    } catch (_: IOException) {+        null+    } catch (_: IllegalStateException) {+        null+    }+}++private const val LOCALE_US = "en-US"+private const val LOCALE_EN = "en"+private const val SCREENSHOT_PHONE = "phone"
appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.ktindex fcf420539c..e76493ccda 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt@@ -3,7 +3,6 @@ package com.vayunmathur.appstore.data import android.content.Context import android.os.Build import android.util.JsonReader-import android.util.JsonToken import com.vayunmathur.appstore.data.security.ApkCertificates import com.vayunmathur.appstore.data.security.SignedJarIndex import com.vayunmathur.library.network.NetworkClient@@ -70,13 +69,7 @@ object FDroidRepository {         downloadToFile("$base/entry.jar", entryJar)         val verified = SignedJarIndex.readVerified(entryJar, "entry.json", pinnedFingerprint) -        val entry = JSONObject(String(verified.content, Charsets.UTF_8))-        val index = entry.optJSONObject("index")-            ?: throw java.io.IOException("entry.json has no index section")-        val name = index.optString("name").takeIf { it.isNotBlank() }-            ?: throw java.io.IOException("entry.json index has no name")-        val expectedSha = index.optString("sha256").takeIf { it.isNotBlank() }-            ?: throw java.io.IOException("entry.json index has no sha256")+        val (name, expectedSha) = entryIndexRef(verified.content)          val indexFile = File(work, "index-v2.json")         downloadToFile(base + "/" + name.trimStart('/'), indexFile)@@ -93,6 +86,20 @@ object FDroidRepository {         )     } +    private data class IndexRef(val name: String, val sha256: String)++    private fun entryIndexRef(entryJson: ByteArray): IndexRef {+        val entry = JSONObject(String(entryJson, Charsets.UTF_8))+        val index = entry.optJSONObject("index")+            ?: throw java.io.IOException("entry.json has no index section")+        val name = index.optString("name").takeIf { it.isNotBlank() }+        val sha = index.optString("sha256").takeIf { it.isNotBlank() }+        if (name == null || sha == null) {+            throw java.io.IOException("entry.json index has no name/sha256")+        }+        return IndexRef(name, sha)+    }+     internal fun downloadToFile(url: String, outFile: File) {         val rawConnection = URL(url).openConnection()         val sslSocketFactory = NetworkClient.defaultSslSocketFactory@@ -100,19 +107,19 @@ object FDroidRepository {             rawConnection.sslSocketFactory = sslSocketFactory         }         val conn = (rawConnection as HttpURLConnection).apply {-            connectTimeout = 30000-            readTimeout = 120000+            connectTimeout = CONNECT_TIMEOUT_MS+            readTimeout = READ_TIMEOUT_MS             setRequestProperty("Accept", "application/json")-            setRequestProperty("User-Agent", "ModernAppStore/1.0")+            setRequestProperty("User-Agent", USER_AGENT)             instanceFollowRedirects = true         }         try {-            if (conn.responseCode !in 200..299) {+            if (conn.responseCode !in HTTP_OK_MIN..HTTP_OK_MAX) {                 throw java.io.IOException("HTTP ${conn.responseCode} for $url")             }             conn.inputStream.use { input ->                 outFile.outputStream().use { out ->-                    val buf = ByteArray(32 * 1024)+                    val buf = ByteArray(DOWNLOAD_BUFFER_SIZE)                     var n: Int                     while (input.read(buf).also { n = it } != -1) out.write(buf, 0, n)                 }@@ -135,21 +142,10 @@ object FDroidRepository {             r.isLenient = true             r.beginObject()             while (r.hasNext()) {-                when (r.nextName()) {-                    "packages" -> {-                        r.beginObject()-                        while (r.hasNext()) {-                            val pkg = r.nextName()-                            try {-                                val app = parsePackageV2(r, pkg, repoBase, source, isReproducible)-                                if (app != null) result.add(app)-                            } catch (_: Exception) {-                                try { r.skipValue() } catch (_: Exception) {}-                            }-                        }-                        r.endObject()-                    }-                    else -> r.skipValue()+                if (r.nextName() == PACKAGES_KEY) {+                    readPackagesV2(r, repoBase, source, isReproducible, result)+                } else {+                    r.skipValue()                 }             }             r.endObject()@@ -157,14 +153,40 @@ object FDroidRepository {         return result     } -    private fun parsePackageV2(-        reader: JsonReader,-        packageName: String,+    private fun readPackagesV2(+        r: JsonReader,         repoBase: String,         source: AppSource,         isReproducible: (String, Long) -> Boolean,-    ): UnifiedApp? {-        // reader at BEGIN_OBJECT of package+        result: MutableList<UnifiedApp>,+    ) {+        r.beginObject()+        while (r.hasNext()) {+            val pkg = r.nextName()+            try {+                val app = parsePackageV2(r, pkg, repoBase, source, isReproducible)+                if (app != null) result.add(app)+            } catch (_: Exception) {+                try {+                    r.skipValue()+                } catch (_: Exception) {+                }+            }+        }+        r.endObject()+    }++    companion object {+        private const val PACKAGES_KEY = "packages"+        private const val CONNECT_TIMEOUT_MS = 30000+        private const val READ_TIMEOUT_MS = 120000+        private const val DOWNLOAD_BUFFER_SIZE = 32 * 1024+        private const val HTTP_OK_MIN = 200+        private const val HTTP_OK_MAX = 299+        private const val USER_AGENT = "ModernAppStore/1.0"+    }++    private class PackageBuilder {         var metaName: String? = null         var metaSummary: String? = null         var metaDesc: String? = null@@ -180,136 +202,52 @@ object FDroidRepository {         var screenshots: List<String> = emptyList()         var antiFeatures: List<String> = emptyList()         val versions = mutableListOf<VersionCandidate>()+    }++    private class VersionBuilder {+        var added: Long = 0L+        var fileName: String? = null+        var fileSize: Long = 0L+        var fileSha256: String? = null+        var signers: List<String> = emptyList()+        var versionName: String? = null+        var versionCode: Long = 0L+        var targetSdk: Int? = null+        var nativeCode: List<String> = emptyList()+        var whatsNew: String? = null++        fun build(): VersionCandidate? {+            val name = fileName ?: return null+            return VersionCandidate(+                added = added,+                fileName = name,+                size = fileSize,+                sha256 = fileSha256,+                signers = signers,+                versionName = versionName,+                versionCode = versionCode,+                targetSdk = targetSdk,+                nativeCode = nativeCode,+                whatsNew = whatsNew,+            )+        }+    }++    private fun parsePackageV2(+        reader: JsonReader,+        packageName: String,+        repoBase: String,+        source: AppSource,+        isReproducible: (String, Long) -> Boolean,+    ): UnifiedApp? {+        // reader at BEGIN_OBJECT of package+        val b = PackageBuilder()          reader.beginObject()         while (reader.hasNext()) {             when (reader.nextName()) {-                "metadata" -> {-                    reader.beginObject()-                    while (reader.hasNext()) {-                        when (val mk = reader.nextName()) {-                            "name" -> metaName = readLocalizedString(reader)-                            "summary" -> metaSummary = readLocalizedString(reader)-                            "description" -> metaDesc = readLocalizedString(reader)-                            "authorName" -> author = nextStringOrNull(reader)-                            "categories" -> categories = readStringArray(reader)-                            "webSite" -> website = nextStringOrNull(reader)-                            "sourceCode" -> sourceCode = nextStringOrNull(reader)-                            "license" -> license = nextStringOrNull(reader)-                            "added" -> added = nextLongOrNull(reader) ?: 0L-                            "lastUpdated" -> lastUpdated = nextLongOrNull(reader) ?: 0L-                            "icon" -> {-                                // index-v2 icon names are repo-absolute ("/icons/foo.png");-                                // don't prepend /icons/ again as the v1 branch has to.-                                val iconName = readIconName(reader)-                                if (iconName != null) iconUrl = repoBase + "/" + iconName.trimStart('/')-                            }-                            "featureGraphic" -> {-                                val name = readIconName(reader)-                                if (name != null) featureGraphic = repoBase + "/" + name.trimStart('/')-                            }-                            "screenshots" -> screenshots = readScreenshotsV2(reader, repoBase)-                            // v2 states anti-features as a map of id -> localised reason;-                            // the ids are what the UI shows, so only the keys are kept.-                            "antiFeatures" -> antiFeatures = readObjectKeys(reader)-                            else -> reader.skipValue()-                        }-                    }-                    reader.endObject()-                }-                "versions" -> {-                    reader.beginObject()-                    while (reader.hasNext()) {-                        reader.nextName() // version key-                        try {-                            reader.beginObject()-                            var vAdded: Long = 0L-                            var vFileName: String? = null-                            var vFileSize: Long = 0L-                            var vFileSha256: String? = null-                            var vSigners: List<String> = emptyList()-                            var vVersionName: String? = null-                            var vVersionCode: Long = 0L-                            var vTargetSdk: Int? = null-                            var vNativeCode: List<String> = emptyList()-                            var vWhatsNew: String? = null-                            while (reader.hasNext()) {-                                when (reader.nextName()) {-                                    "added" -> vAdded = nextLongOrNull(reader) ?: 0L-                                    "file" -> {-                                        reader.beginObject()-                                        while (reader.hasNext()) {-                                            when (reader.nextName()) {-                                                "name" -> vFileName = nextStringOrNull(reader)-                                                "size" -> vFileSize = nextLongOrNull(reader) ?: 0L-                                                "sha256" -> vFileSha256 = nextStringOrNull(reader)-                                                else -> reader.skipValue()-                                            }-                                        }-                                        reader.endObject()-                                    }-                                    "manifest" -> {-                                        reader.beginObject()-                                        while (reader.hasNext()) {-                                            when (reader.nextName()) {-                                                "versionName" -> vVersionName = nextStringOrNull(reader)-                                                "versionCode" -> vVersionCode = nextLongOrNull(reader) ?: 0L-                                                "usesSdk" -> {-                                                    reader.beginObject()-                                                    while (reader.hasNext()) {-                                                        when (reader.nextName()) {-                                                            "targetSdkVersion" -> vTargetSdk = nextIntOrNull(reader)-                                                            else -> reader.skipValue()-                                                        }-                                                    }-                                                    reader.endObject()-                                                }-                                                // The ABIs this APK carries native libraries for.-                                                // Absent means it has none and runs anywhere.-                                                "nativecode" -> vNativeCode = readStringArray(reader)-                                                // signer.sha256 is the list of signing-certificate-                                                // fingerprints this APK is expected to carry.-                                                "signer" -> {-                                                    reader.beginObject()-                                                    while (reader.hasNext()) {-                                                        when (reader.nextName()) {-                                                            "sha256" -> vSigners = readStringArray(reader)-                                                            else -> reader.skipValue()-                                                        }-                                                    }-                                                    reader.endObject()-                                                }-                                                else -> reader.skipValue()-                                            }-                                        }-                                        reader.endObject()-                                    }-                                    "whatsNew" -> vWhatsNew = readLocalizedString(reader)-                                    else -> reader.skipValue()-                                }-                            }-                            reader.endObject()-                            val fileName = vFileName-                            if (fileName != null) {-                                versions += VersionCandidate(-                                    added = vAdded,-                                    fileName = fileName,-                                    size = vFileSize,-                                    sha256 = vFileSha256,-                                    signers = vSigners,-                                    versionName = vVersionName,-                                    versionCode = vVersionCode,-                                    targetSdk = vTargetSdk,-                                    nativeCode = vNativeCode,-                                    whatsNew = vWhatsNew,-                                )-                            }-                        } catch (_: Exception) {-                            try { reader.endObject() } catch (_: Exception) {}-                        }-                    }-                    reader.endObject()-                }+                "metadata" -> readMetadataV2(reader, repoBase, b)+                "versions" -> readVersionsV2(reader, b)                 else -> reader.skipValue()             }         }@@ -317,7 +255,7 @@ object FDroidRepository {          // Nothing this device can run — drop the package rather than advertising an entry         // that has no installable APK behind it.-        val latest = selectVersion(versions, deviceAbis) ?: return null+        val latest = selectVersion(b.versions, deviceAbis) ?: return null          // index-v2 file names are repo-absolute ("/com.example_12.apk").         val apkUrl = repoBase + "/" + latest.fileName.trimStart('/')@@ -327,30 +265,178 @@ object FDroidRepository {             expectedSigners = latest.signers,             apkSha256 = latest.sha256,             reproducible = isReproducible(packageName, latest.versionCode),-            name = metaName ?: packageName.substringAfterLast('.'),-            summary = metaSummary ?: "",-            description = metaDesc ?: "",-            iconUrl = iconUrl,-            featureGraphic = featureGraphic,-            screenshots = screenshots,-            antiFeatures = antiFeatures,-            author = author,-            categories = categories,+            name = b.metaName ?: packageName.substringAfterLast('.'),+            summary = b.metaSummary ?: "",+            description = b.metaDesc ?: "",+            iconUrl = b.iconUrl,+            featureGraphic = b.featureGraphic,+            screenshots = b.screenshots,+            antiFeatures = b.antiFeatures,+            author = b.author,+            categories = b.categories,             versionName = latest.versionName,             versionCode = latest.versionCode,             sizeBytes = latest.size,             apkUrl = apkUrl,             targetSdk = latest.targetSdk,-            license = license,-            website = website,-            sourceCode = sourceCode,+            license = b.license,+            website = b.website,+            sourceCode = b.sourceCode,             whatsNew = latest.whatsNew,-            addedTimestamp = added,-            lastUpdated = if (lastUpdated != 0L) lastUpdated else added,+            addedTimestamp = b.added,+            lastUpdated = if (b.lastUpdated != 0L) b.lastUpdated else b.added,             repoUrl = repoBase         )     } +    private fun readMetadataV2(reader: JsonReader, repoBase: String, b: PackageBuilder) {+        reader.beginObject()+        while (reader.hasNext()) {+            val key = reader.nextName()+            if (!readMetadataScalar(reader, b, key)) {+                readMetadataNested(reader, repoBase, b, key)+            }+        }+        reader.endObject()+    }++    private fun readMetadataScalar(+        reader: JsonReader,+        b: PackageBuilder,+        key: String,+    ): Boolean {+        when (key) {+            "name" -> b.metaName = readLocalizedString(reader)+            "summary" -> b.metaSummary = readLocalizedString(reader)+            "description" -> b.metaDesc = readLocalizedString(reader)+            "authorName" -> b.author = nextStringOrNull(reader)+            "categories" -> b.categories = readStringArray(reader)+            "webSite" -> b.website = nextStringOrNull(reader)+            "sourceCode" -> b.sourceCode = nextStringOrNull(reader)+            "license" -> b.license = nextStringOrNull(reader)+            "added" -> b.added = nextLongOrNull(reader) ?: 0L+            "lastUpdated" -> b.lastUpdated = nextLongOrNull(reader) ?: 0L+            else -> return false+        }+        return true+    }++    private fun readMetadataNested(+        reader: JsonReader,+        repoBase: String,+        b: PackageBuilder,+        key: String,+    ) {+        when (key) {+            "icon" -> b.iconUrl = repoAssetUrl(reader, repoBase)+            "featureGraphic" -> b.featureGraphic = repoAssetUrl(reader, repoBase)+            "screenshots" -> b.screenshots = readScreenshotsV2(reader, repoBase)+            // v2 states anti-features as a map of id -> localised reason;+            // the ids are what the UI shows, so only the keys are kept.+            "antiFeatures" -> b.antiFeatures = readObjectKeys(reader)+            else -> reader.skipValue()+        }+    }++    private fun repoAssetUrl(reader: JsonReader, repoBase: String): String? {+        // index-v2 icon names are repo-absolute ("/icons/foo.png");+        // don't prepend /icons/ again as the v1 branch has to.+        val iconName = readIconName(reader) ?: return null+        return repoBase + "/" + iconName.trimStart('/')+    }++    private fun readVersionsV2(reader: JsonReader, b: PackageBuilder) {+        reader.beginObject()+        while (reader.hasNext()) {+            reader.nextName() // version key+            try {+                readOneVersionV2(reader, b)+            } catch (_: Exception) {+                try {+                    reader.endObject()+                } catch (_: Exception) {+                }+            }+        }+        reader.endObject()+    }++    private fun readOneVersionV2(reader: JsonReader, b: PackageBuilder) {+        reader.beginObject()+        val v = VersionBuilder()+        while (reader.hasNext()) {+            when (reader.nextName()) {+                "added" -> v.added = nextLongOrNull(reader) ?: 0L+                "file" -> readVersionFileV2(reader, v)+                "manifest" -> readVersionManifestV2(reader, v)+                "whatsNew" -> v.whatsNew = readLocalizedString(reader)+                else -> reader.skipValue()+            }+        }+        reader.endObject()+        v.build()?.let { b.versions += it }+    }++    private fun readVersionFileV2(reader: JsonReader, v: VersionBuilder) {+        reader.beginObject()+        while (reader.hasNext()) {+            when (reader.nextName()) {+                "name" -> v.fileName = nextStringOrNull(reader)+                "size" -> v.fileSize = nextLongOrNull(reader) ?: 0L+                "sha256" -> v.fileSha256 = nextStringOrNull(reader)+                else -> reader.skipValue()+            }+        }+        reader.endObject()+    }++    private fun readVersionManifestV2(reader: JsonReader, v: VersionBuilder) {+        reader.beginObject()+        while (reader.hasNext()) {+            when (reader.nextName()) {+                "versionName" -> v.versionName = nextStringOrNull(reader)+                "versionCode" -> v.versionCode = nextLongOrNull(reader) ?: 0L+                "usesSdk" -> v.targetSdk = readTargetSdkV2(reader)+                // The ABIs this APK carries native libraries for.+                // Absent means it has none and runs anywhere.+                "nativecode" -> v.nativeCode = readStringArray(reader)+                // signer.sha256 is the list of signing-certificate+                // fingerprints this APK is expected to carry.+                "signer" -> v.signers = readSignerShaV2(reader)+                else -> reader.skipValue()+            }+        }+        reader.endObject()+    }++    private fun readTargetSdkV2(reader: JsonReader): Int? {+        reader.beginObject()+        var target: Int? = null+        while (reader.hasNext()) {+            if (reader.nextName() == "targetSdkVersion") {+                target = nextIntOrNull(reader)+            } else {+                reader.skipValue()+            }+        }+        reader.endObject()+        return target+    }++    private fun readSignerShaV2(reader: JsonReader): List<String> {+        reader.beginObject()+        var signers: List<String> = emptyList()+        while (reader.hasNext()) {+            if (reader.nextName() == "sha256") {+                signers = readStringArray(reader)+            } else {+                reader.skipValue()+            }+        }+        reader.endObject()+        return signers+    }+     // ---- Version selection ----      /**@@ -413,227 +499,4 @@ object FDroidRepository {         return nativeCode.mapNotNull { abi -> deviceAbis.indexOf(abi).takeIf { it >= 0 } }.minOrNull()     } -    // ---- Helpers ------    private fun readLocalizedString(reader: JsonReader): String? {-        return when (reader.peek()) {-            JsonToken.STRING -> reader.nextString()-            JsonToken.BEGIN_OBJECT -> {-                var first: String? = null-                var enUs: String? = null-                var en: String? = null-                reader.beginObject()-                while (reader.hasNext()) {-                    val locale = reader.nextName()-                    when (reader.peek()) {-                        JsonToken.STRING -> {-                            val v = reader.nextString()-                            if (first == null) first = v-                            if (locale == "en-US") enUs = v-                            if (locale == "en") en = v-                        }-                        else -> reader.skipValue()-                    }-                }-                reader.endObject()-                enUs ?: en ?: first-            }-            else -> { reader.skipValue(); null }-        }-    }--    private fun readIconName(reader: JsonReader): String? {-        // icon can be: { "en-US": { "96": {"name":...} } } or { "en-US": {"name":...} }-        return try {-            if (reader.peek() != JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null }-            var found: String? = null-            reader.beginObject()-            while (reader.hasNext() && found == null) {-                reader.nextName() // locale-                found = findFirstNameInAnyNested(reader)-            }-            while (reader.hasNext()) { reader.nextName(); reader.skipValue() }-            reader.endObject()-            found-        } catch (_: Exception) { null }-    }--    private fun findFirstNameInAnyNested(reader: JsonReader): String? {-        // searches recursively for first object containing key "name" = String-        return when (reader.peek()) {-            JsonToken.BEGIN_OBJECT -> {-                var found: String? = null-                reader.beginObject()-                while (reader.hasNext()) {-                    val key = reader.nextName()-                    if (key == "name" && reader.peek() == JsonToken.STRING) {-                        val v = reader.nextString()-                        if (found == null) found = v-                        // keep consuming remaining to properly close-                    } else {-                        if (found == null && reader.peek() == JsonToken.BEGIN_OBJECT) {-                            val inner = findFirstNameInAnyNested(reader)-                            if (inner != null) found = inner-                        } else if (found == null && reader.peek() == JsonToken.BEGIN_ARRAY) {-                            reader.skipValue()-                        } else {-                            reader.skipValue()-                        }-                    }-                }-                reader.endObject()-                found-            }-            JsonToken.BEGIN_ARRAY -> {-                reader.beginArray()-                var found: String? = null-                while (reader.hasNext() && found == null) {-                    found = findFirstNameInAnyNested(reader)-                }-                while (reader.hasNext()) reader.skipValue()-                reader.endArray()-                found-            }-            else -> { reader.skipValue(); null }-        }-    }--    /**-     * index-v2 `screenshots`: `{ phone: { "en-US": [ { name, sha256, size }, … ] }, … }`.-     *-     * Only the phone set is taken — the tablet, TV and wear sets are the same app shot on-     * hardware the reader isn't holding, and mixing them makes the carousel jump between-     * aspect ratios. Falls back to whichever set exists if there is no phone one.-     */-    private fun readScreenshotsV2(reader: JsonReader, repoBase: String): List<String> {-        if (reader.peek() != JsonToken.BEGIN_OBJECT) {-            reader.skipValue()-            return emptyList()-        }-        var phone: List<String> = emptyList()-        var fallback: List<String> = emptyList()-        reader.beginObject()-        while (reader.hasNext()) {-            val kind = reader.nextName()-            val shots = readLocalizedFileList(reader, repoBase)-            when {-                kind == "phone" -> phone = shots-                fallback.isEmpty() -> fallback = shots-            }-        }-        reader.endObject()-        return phone.ifEmpty { fallback }-    }--    /** `{ "en-US": [ { "name": "/pkg/en-US/phoneScreenshots/1.png" }, … ], … }`. */-    private fun readLocalizedFileList(reader: JsonReader, repoBase: String): List<String> {-        if (reader.peek() != JsonToken.BEGIN_OBJECT) {-            reader.skipValue()-            return emptyList()-        }-        var enUs: List<String>? = null-        var en: List<String>? = null-        var first: List<String>? = null-        reader.beginObject()-        while (reader.hasNext()) {-            val locale = reader.nextName()-            val names = readFileNameArray(reader).map { repoBase + "/" + it.trimStart('/') }-            if (first == null) first = names-            when (locale) {-                "en-US" -> enUs = names-                "en" -> en = names-            }-        }-        reader.endObject()-        return enUs ?: en ?: first ?: emptyList()-    }--    /** `[ { "name": …, "sha256": …, "size": … }, … ]` reduced to the names. */-    private fun readFileNameArray(reader: JsonReader): List<String> {-        if (reader.peek() != JsonToken.BEGIN_ARRAY) {-            reader.skipValue()-            return emptyList()-        }-        val names = mutableListOf<String>()-        reader.beginArray()-        while (reader.hasNext()) {-            if (reader.peek() != JsonToken.BEGIN_OBJECT) {-                reader.skipValue()-                continue-            }-            reader.beginObject()-            while (reader.hasNext()) {-                if (reader.nextName() == "name") {-                    nextStringOrNull(reader)?.let { names.add(it) }-                } else {-                    reader.skipValue()-                }-            }-            reader.endObject()-        }-        reader.endArray()-        return names-    }--    /** Keys of an object whose values are of no interest, e.g. v2's anti-feature map. */-    private fun readObjectKeys(reader: JsonReader): List<String> {-        if (reader.peek() != JsonToken.BEGIN_OBJECT) {-            reader.skipValue()-            return emptyList()-        }-        val keys = mutableListOf<String>()-        reader.beginObject()-        while (reader.hasNext()) {-            keys.add(reader.nextName())-            reader.skipValue()-        }-        reader.endObject()-        return keys-    }--    private fun readStringArray(reader: JsonReader): List<String> {-        return try {-            if (reader.peek() != JsonToken.BEGIN_ARRAY) { reader.skipValue(); return emptyList() }-            val list = mutableListOf<String>()-            reader.beginArray()-            while (reader.hasNext()) {-                if (reader.peek() == JsonToken.STRING) list.add(reader.nextString()) else reader.skipValue()-            }-            reader.endArray()-            list-        } catch (_: Exception) { emptyList() }-    }--    private fun nextStringOrNull(reader: JsonReader): String? {-        return try {-            when (reader.peek()) {-                JsonToken.STRING -> reader.nextString()-                JsonToken.NULL -> { reader.nextNull(); null }-                JsonToken.NUMBER -> reader.nextString()-                else -> { reader.skipValue(); null }-            }-        } catch (_: Exception) { null }-    }--    private fun nextLongOrNull(reader: JsonReader): Long? {-        return try {-            when (reader.peek()) {-                JsonToken.NUMBER -> reader.nextLong()-                JsonToken.STRING -> reader.nextString().toLongOrNull()-                JsonToken.NULL -> { reader.nextNull(); null }-                else -> { reader.skipValue(); null }-            }-        } catch (_: Exception) { null }-    }--    private fun nextIntOrNull(reader: JsonReader): Int? {-        return try {-            when (reader.peek()) {-                JsonToken.NUMBER -> reader.nextInt()-                JsonToken.STRING -> reader.nextString().toIntOrNull()-                JsonToken.NULL -> { reader.nextNull(); null }-                else -> { reader.skipValue(); null }-            }-        } catch (_: Exception) { null }-    } }
appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.ktindex 1ac2e23ded..ae0e0ad931 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt@@ -61,114 +61,174 @@ class UpdateCheckWorker(         // WorkManager can cold-start the process without MainActivity initializing TLS.         NetworkClient.init(context, TrustBundle.STANDARD)         val scope = CoroutineScope(SupervisorJob())+        try {+            runCheck(scope)+        } finally {+            scope.cancel()+        }+        Result.success()+    } catch (expected: java.io.IOException) {+        Log.w(TAG, "Update check failed", expected)+        Result.retry()+    } catch (expected: IllegalStateException) {+        Log.w(TAG, "Update check failed", expected)+        Result.retry()+    } catch (expected: SecurityException) {+        Log.w(TAG, "Update check failed", expected)+        Result.retry()+    }++    private data class CheckEnv(+        val scope: CoroutineScope,+        val db: AppDatabase,+        val catalog: CatalogRepository,+        val installedRepo: InstalledAppsRepository,+        val play: PlayRepository,+        val accrescent: AccrescentRepository,+        val grapheneOS: GrapheneOSRepository,+        val settings: SettingsRepository,+    )++    private suspend fun runCheck(scope: CoroutineScope) {         val db = AppStoreDatabaseRepository.get(context).database-        val catalog = CatalogRepository(context, db, scope)-        val installedRepo = InstalledAppsRepository(context)-        val play = PlayRepository(context)-        val accrescent = AccrescentRepository(context, db)-        val grapheneOS = GrapheneOSRepository(context)-        val settings = SettingsRepository(context, scope)-        val enabled = settings.readEnabledSources()+        val env = CheckEnv(+            scope = scope,+            db = db,+            catalog = CatalogRepository(context, db, scope),+            installedRepo = InstalledAppsRepository(context),+            play = PlayRepository(context),+            accrescent = AccrescentRepository(context, db),+            grapheneOS = GrapheneOSRepository(context),+            settings = SettingsRepository(context, scope),+        )+        val enabled = env.settings.readEnabledSources()++        env.catalog.sync(enabled)+        env.installedRepo.refresh()+        if (AppSource.PLAYSTORE in enabled) env.play.restore() -        catalog.sync(enabled)-        installedRepo.refresh()-        if (AppSource.PLAYSTORE in enabled) play.restore()+        val updates = collectUpdates(env, enabled)+        reportUpdates(env, updates) -        val installed = installedRepo.updatable.value-        val fromCatalog = catalog.updatesFor(installed)+        env.accrescent.shutdown()+    }++    private suspend fun collectUpdates(+        env: CheckEnv,+        enabled: Set<AppSource>,+    ): List<UnifiedApp> {+        val installed = env.installedRepo.updatable.value+        val fromCatalog = env.catalog.updatesFor(installed)+        val fromPlay = playUpdates(env, enabled, installed)+        val fromAccrescent = accrescentUpdates(env, enabled, installed)+        val fromGrapheneOS = grapheneOSUpdates(env, installed)++        // The surviving row's source decides which download-and-verify path the update takes,+        // so it has to be the same precedence the rest of the store uses.+        return (fromCatalog + fromPlay + fromAccrescent + fromGrapheneOS)+            .sortedBy { it.source.priority }+            .distinctBy { it.packageName }+    } +    private suspend fun playUpdates(+        env: CheckEnv,+        enabled: Set<AppSource>,+        installed: List<InstalledInfo>,+    ): List<UnifiedApp> {         // Only Play can answer for packages the offline catalogues have never heard of — except         // the Sandboxed Google Play components, which Play also hosts but must never update         // here: only the builds GrapheneOS re-hosts are the ones this device can use. Their         // updates come from GrapheneOS's own signed index instead, below.-        val index = catalog.packageIndex.value-        val fromPlay = if (AppSource.PLAYSTORE in enabled) {-            val unknown = installed-                .filter {-                    it.packageName !in index &&-                        it.packageName !in SandboxedGooglePlay.PACKAGES-                }-                .map { it.packageName }-            val remote = play.details(unknown).associateBy { it.packageName }-            installed.mapNotNull { inst ->-                remote[inst.packageName]?.takeIf { it.versionCode > inst.versionCode }+        if (AppSource.PLAYSTORE !in enabled) return emptyList()+        val index = env.catalog.packageIndex.value+        val unknown = installed+            .filter {+                it.packageName !in index &&+                    it.packageName !in SandboxedGooglePlay.PACKAGES             }-        } else {-            emptyList()+            .map { it.packageName }+        val remote = env.play.details(unknown).associateBy { it.packageName }+        return installed.mapNotNull { inst ->+            remote[inst.packageName]?.takeIf { it.versionCode > inst.versionCode }         }+    } +    private suspend fun accrescentUpdates(+        env: CheckEnv,+        enabled: Set<AppSource>,+        installed: List<InstalledInfo>,+    ): List<UnifiedApp> {         // Accrescent: refresh its signed allowlist, then ask its API for a newer build of each         // installed package it vouches for. Auto-install still routes through InstallCoordinator,         // which re-verifies signer + min-version before committing.-        val fromAccrescent = if (AppSource.ACCRESCENT in enabled) {-            accrescent.refreshRepoData()-            val accrescentIds = accrescent.appIds()-            installed-                .filter { it.packageName in accrescentIds }-                .mapNotNull { inst ->-                    val update = runCatching {-                        accrescent.updateInfo(inst.packageName, inst.versionCode)-                    }.getOrNull() ?: return@mapNotNull null-                    val details = accrescent.details(inst.packageName) ?: UnifiedApp(-                        packageName = inst.packageName,-                        source = AppSource.ACCRESCENT,-                        name = inst.packageName.substringAfterLast('.'),-                    )-                    details.copy(versionCode = update.versionCode, versionName = update.versionName)-                }-        } else {-            emptyList()-        }+        if (AppSource.ACCRESCENT !in enabled) return emptyList()+        env.accrescent.refreshRepoData()+        val accrescentIds = env.accrescent.appIds()+        return installed+            .filter { it.packageName in accrescentIds }+            .mapNotNull { inst ->+                val update = runCatching {+                    env.accrescent.updateInfo(inst.packageName, inst.versionCode)+                }.getOrNull() ?: return@mapNotNull null+                val details = env.accrescent.details(inst.packageName) ?: UnifiedApp(+                    packageName = inst.packageName,+                    source = AppSource.ACCRESCENT,+                    name = inst.packageName.substringAfterLast('.'),+                )+                details.copy(versionCode = update.versionCode, versionName = update.versionName)+            }+    } +    private suspend fun grapheneOSUpdates(+        env: CheckEnv,+        installed: List<InstalledInfo>,+    ): List<UnifiedApp> {         // GrapheneOS: refresh its signed index and offer a newer build of each Sandboxed         // Google Play component that is installed. Skipped on stock Android, where these         // packages cannot work at all for want of the OS's gmscompat layer.-        val fromGrapheneOS = if (RestrictedPackages.isGrapheneOS(context)) {-            grapheneOS.refresh(SandboxedGooglePlay.PACKAGES).getOrNull().orEmpty()-                .mapNotNull { entry ->-                    val current = installed.firstOrNull { it.packageName == entry.packageName }-                        ?: return@mapNotNull null-                    entry.toUnifiedApp().takeIf { it.versionCode > current.versionCode }-                }-        } else {-            emptyList()-        }--        // The surviving row's source decides which download-and-verify path the update takes,-        // so it has to be the same precedence the rest of the store uses.-        val updates = (fromCatalog + fromPlay + fromAccrescent + fromGrapheneOS)-            .sortedBy { it.source.priority }-            .distinctBy { it.packageName }+        if (!RestrictedPackages.isGrapheneOS(context)) return emptyList()+        return env.grapheneOS.refresh(SandboxedGooglePlay.PACKAGES).getOrNull().orEmpty()+            .mapNotNull { entry ->+                val current = installed.firstOrNull { it.packageName == entry.packageName }+                    ?: return@mapNotNull null+                entry.toUnifiedApp().takeIf { it.versionCode > current.versionCode }+            }+    } -        val autoInstall = settings.readAutoInstallUpdates()+    private suspend fun reportUpdates(env: CheckEnv, updates: List<UnifiedApp>) {+        val autoInstall = env.settings.readAutoInstallUpdates() -        if (autoInstall && updates.isNotEmpty()) {-            val eligible = updates.filter { canSilentlyUpdate(it.packageName) }-            if (eligible.isNotEmpty()) {-                autoInstall(eligible, db, play, accrescent, grapheneOS, scope)-                installedRepo.refresh()-            }-            // Only nag about the updates we could not apply on our own.-            val remaining = updates.filterNot { canSilentlyUpdate(it.packageName) }-            notifyIfChanged(-                remaining.map { it.packageName }.toSortedSet(),-                remaining.size,-                needsConfirmation = true,-            )-        } else {+        if (!autoInstall || updates.isEmpty()) {             notifyIfChanged(                 updates.map { it.packageName }.toSortedSet(),                 updates.size,                 needsConfirmation = false,             )+            return+        }+        val eligible = updates.filter { canSilentlyUpdate(it.packageName) }+        if (eligible.isNotEmpty()) {+            autoInstall(eligible, env)+            env.installedRepo.refresh()         }+        // Only nag about the updates we could not apply on our own.+        val remaining = updates.filterNot { canSilentlyUpdate(it.packageName) }+        notifyIfChanged(+            remaining.map { it.packageName }.toSortedSet(),+            remaining.size,+            needsConfirmation = true,+        )+    } -        accrescent.shutdown()-        scope.cancel()-        Result.success()-    } catch (e: Exception) {-        Log.w(TAG, "Update check failed", e)-        Result.retry()+    private suspend fun autoInstall(eligible: List<UnifiedApp>, env: CheckEnv) {+        autoInstall(+            eligible,+            env.db,+            env.play,+            env.accrescent,+            env.grapheneOS,+            env.scope,+        )     }      /**
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentApi.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentApi.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentApi.ktindex b47bcdbc28..70c321613d 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentApi.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentApi.kt@@ -40,6 +40,10 @@ class AccrescentApi {     @Volatile     private var channelRef: ManagedChannel? = null +    private companion object {+        private const val HTTPS_PORT = 443+    }+     private fun stub(): AppServiceGrpcKt.AppServiceCoroutineStub =         AppServiceGrpcKt.AppServiceCoroutineStub(channel()) @@ -48,7 +52,7 @@ class AccrescentApi {         return synchronized(this) {             channelRef?.let { if (!it.isShutdown && !it.isTerminated) return it }             OkHttpChannelBuilder-                .forAddress(AccrescentRepo.APP_STORE_API_DOMAIN, 443)+                .forAddress(AccrescentRepo.APP_STORE_API_DOMAIN, HTTPS_PORT)                 .useTransportSecurity()                 .build()                 .also { channelRef = it }
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepoData.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepoData.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepoData.ktindex 0424773c82..9b83b53068 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepoData.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepoData.kt@@ -53,7 +53,7 @@ class AccrescentRepoDataFetcher(private val context: Context) {         return try {             val (jsonStatus, _, jsonBytes) =                 NetworkClient.performRequestBytesFull(AccrescentRepo.REPODATA_JSON_URL)-            if (jsonStatus !in 200..299 || jsonBytes.isEmpty()) {+            if (jsonStatus !in HTTP_OK_MIN..HTTP_OK_MAX || jsonBytes.isEmpty()) {                 return Result.failure(IllegalStateException("repodata fetch failed: HTTP $jsonStatus"))             } @@ -82,27 +82,40 @@ class AccrescentRepoDataFetcher(private val context: Context) {             persistTimestamp(repoData.timestamp)              Result.success(repoData)-        } catch (e: Exception) {-            Log.w(TAG, "repodata fetch/verify failed", e)-            Result.failure(e)+        } catch (expected: IllegalStateException) {+            Log.w(TAG, "repodata fetch/verify failed", expected)+            Result.failure(expected)+        } catch (expected: java.io.IOException) {+            Log.w(TAG, "repodata fetch/verify failed", expected)+            Result.failure(expected)+        } catch (expected: SecurityException) {+            Log.w(TAG, "repodata fetch/verify failed", expected)+            Result.failure(expected)         }     }      private suspend fun readStoredTimestamp(): Long =         try {             context.accrescentDataStore.data.first()[REPODATA_TIMESTAMP_KEY] ?: 0L-        } catch (_: Exception) {+        } catch (expected: java.io.IOException) {+            Log.w(TAG, "read stored timestamp", expected)+            0L+        } catch (expected: IllegalStateException) {+            Log.w(TAG, "read stored timestamp", expected)             0L         }      private suspend fun persistTimestamp(timestamp: Long) {         try {             context.accrescentDataStore.edit { it[REPODATA_TIMESTAMP_KEY] = timestamp }-        } catch (_: Exception) {+        } catch (expected: java.io.IOException) {+            Log.w(TAG, "persist timestamp", expected)         }     }      private companion object {         const val TAG = "AccrescentRepoData"+        private const val HTTP_OK_MIN = 200+        private const val HTTP_OK_MAX = 299     } }
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepository.ktindex 29280ae186..79e6449851 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepository.kt@@ -87,8 +87,11 @@ class AccrescentRepository(             AccrescentPage(apps, response.nextPageToken)         } catch (e: CancellationException) {             throw e-        } catch (e: Exception) {-            Log.w(TAG, "listApps failed", e)+        } catch (expected: java.io.IOException) {+            Log.w(TAG, "listApps failed", expected)+            AccrescentPage(emptyList(), "")+        } catch (expected: IllegalStateException) {+            Log.w(TAG, "listApps failed", expected)             AccrescentPage(emptyList(), "")         }     }@@ -114,29 +117,40 @@ class AccrescentRepository(         if (allListingsLoaded) return         listingsMutex.withLock {             if (allListingsLoaded) return-            var token = ""-            var pages = 0-            var complete = false-            while (pages < MAX_LISTING_PAGES) {-                val response = try {-                    api.listAppListings(PAGE_SIZE, token, preferredLanguages())-                } catch (e: CancellationException) {-                    throw e-                } catch (e: Exception) {-                    Log.w(TAG, "listAppListings page $pages failed", e)-                    break-                }-                response.listingsList.forEach { listingsCache[it.appId] = it.toUnifiedApp() }-                token = response.nextPageToken-                pages++-                if (token.isBlank()) {-                    complete = true-                    break-                }-            }+            val loaded = loadAllPages()             // Mark loaded when we reached the end (or the page cap); leave it false on a network             // failure so the next search retries the full load.-            if (complete || pages >= MAX_LISTING_PAGES) allListingsLoaded = true+            if (loaded) allListingsLoaded = true+        }+    }++    private suspend fun loadAllPages(): Boolean {+        var token = ""+        var pages = 0+        while (pages < MAX_LISTING_PAGES) {+            val response = loadOnePage(token, pages) ?: return false+            response.listingsList.forEach { listingsCache[it.appId] = it.toUnifiedApp() }+            token = response.nextPageToken+            pages+++            if (token.isBlank()) return true+        }+        return pages >= MAX_LISTING_PAGES+    }++    private suspend fun loadOnePage(+        token: String,+        pages: Int,+    ): app.accrescent.appstore.v1.ListAppListingsResponse? {+        return try {+            api.listAppListings(PAGE_SIZE, token, preferredLanguages())+        } catch (e: CancellationException) {+            throw e+        } catch (expected: java.io.IOException) {+            Log.w(TAG, "listAppListings page $pages failed", expected)+            null+        } catch (expected: IllegalStateException) {+            Log.w(TAG, "listAppListings page $pages failed", expected)+            null         }     } @@ -153,8 +167,11 @@ class AccrescentRepository(             ).also { listingsCache[appId] = it }         } catch (e: CancellationException) {             throw e-        } catch (e: Exception) {-            Log.w(TAG, "details failed for $appId", e)+        } catch (expected: java.io.IOException) {+            Log.w(TAG, "details failed for $appId", expected)+            null+        } catch (expected: IllegalStateException) {+            Log.w(TAG, "details failed for $appId", expected)             null         }     }
appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSIndex.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSIndex.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSIndex.ktindex 0e94921dc9..d8c706b5e7 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSIndex.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSIndex.kt@@ -157,20 +157,34 @@ object GrapheneOSIndex {     private fun newestInstallableVariant(variants: JSONObject): Pair<Long, JSONObject>? {         var best: Pair<Long, JSONObject>? = null         for (key in variants.keys()) {-            val versionCode = key.toLongOrNull() ?: continue-            val variant = variants.optJSONObject(key) ?: continue-            if (variant.optString("channel", STABLE) != STABLE) continue-            if (Build.VERSION.SDK_INT < variant.optInt("minSdk", 0)) continue-            if (Build.VERSION.SDK_INT > variant.optInt("maxSdk", Int.MAX_VALUE)) continue--            val abis = variant.optJSONArray("abis")?.toStringList()-            if (abis != null && DEVICE_ABI !in abis) continue--            if (best == null || versionCode > best.first) best = versionCode to variant+            val candidate = installableVariant(variants, key) ?: continue+            if (best == null || candidate.first > best.first) best = candidate         }         return best     } +    private fun installableVariant(variants: JSONObject, key: String): Pair<Long, JSONObject>? {+        val versionCode = key.toLongOrNull() ?: return null+        val variant = variants.optJSONObject(key) ?: return null+        if (!isStableVariant(variant)) return null+        if (!sdkSupports(variant)) return null+        if (!abiSupports(variant)) return null+        return versionCode to variant+    }++    private fun isStableVariant(variant: JSONObject): Boolean =+        variant.optString("channel", STABLE) == STABLE++    private fun sdkSupports(variant: JSONObject): Boolean {+        if (Build.VERSION.SDK_INT < variant.optInt("minSdk", 0)) return false+        return Build.VERSION.SDK_INT <= variant.optInt("maxSdk", Int.MAX_VALUE)+    }++    private fun abiSupports(variant: JSONObject): Boolean {+        val abis = variant.optJSONArray("abis")?.toStringList() ?: return true+        return DEVICE_ABI in abis+    }+     /**      * The files to download: the base APK plus the splits this device needs.      *@@ -187,37 +201,61 @@ object GrapheneOSIndex {             return null         } -        val languages = deviceLanguages(context)-        val kept = mutableListOf<GrapheneOSApk>()-        val byDensity = mutableMapOf<Int, MutableList<GrapheneOSApk>>()--        for (i in 0 until count) {-            val apk = GrapheneOSApk(-                name = names.optString(i),-                sha256 = hashes.optString(i).lowercase(),-                size = sizes.optLong(i),-                gzSize = gzSizes.optLong(i),-            )-            val qualifier = configQualifier(apk.name)-            val density = qualifier?.let { DENSITY_QUALIFIERS[it] }-            when {-                qualifier == null -> kept += apk-                density != null -> byDensity.getOrPut(density) { mutableListOf() }.add(apk)-                qualifier in ABI_QUALIFIERS.values ->-                    if (qualifier == DEVICE_ABI_QUALIFIER) kept += apk-                else -> if (qualifier in languages) kept += apk+        val picker = ApkPicker(context, names, hashes, sizes, gzSizes, count)+        return picker.select()+    }++    private class ApkPicker(+        context: Context,+        private val names: JSONArray,+        private val hashes: JSONArray,+        private val sizes: JSONArray,+        private val gzSizes: JSONArray,+        private val count: Int,+    ) {+        private val languages = deviceLanguages(context)+        private val targetDensity = context.resources.displayMetrics.densityDpi+        private val kept = mutableListOf<GrapheneOSApk>()+        private val byDensity = mutableMapOf<Int, MutableList<GrapheneOSApk>>()++        fun select(): List<GrapheneOSApk> {+            for (i in 0 until count) {+                classify(apkAt(i))             }+            // One density split, not all of them: the closest at or above this screen, falling+            // back to the largest published when the screen is denser than anything on offer.+            if (byDensity.isNotEmpty()) {+                val densities = byDensity.keys.sorted()+                val chosen = densities.firstOrNull { it >= targetDensity } ?: densities.last()+                kept += byDensity.getValue(chosen)+            }+            return kept         } -        // One density split, not all of them: the closest at or above this screen, falling-        // back to the largest published when the screen is denser than anything on offer.-        if (byDensity.isNotEmpty()) {-            val densities = byDensity.keys.sorted()-            val target = context.resources.displayMetrics.densityDpi-            val chosen = densities.firstOrNull { it >= target } ?: densities.last()-            kept += byDensity.getValue(chosen)+        private fun apkAt(i: Int): GrapheneOSApk = GrapheneOSApk(+            name = names.optString(i),+            sha256 = hashes.optString(i).lowercase(),+            size = sizes.optLong(i),+            gzSize = gzSizes.optLong(i),+        )++        private fun classify(apk: GrapheneOSApk) {+            val qualifier = configQualifier(apk.name)+            if (qualifier == null) {+                kept += apk+                return+            }+            val density = qualifier.let { DENSITY_QUALIFIERS[it] }+            if (density != null) {+                byDensity.getOrPut(density) { mutableListOf() }.add(apk)+                return+            }+            if (qualifier in ABI_QUALIFIERS.values) {+                if (qualifier == DEVICE_ABI_QUALIFIER) kept += apk+                return+            }+            if (qualifier in languages) kept += apk         }-        return kept     }      /** The part after the last `config.`, or null for a file that is not a config split. */
appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSRepository.ktindex 4b24cd532c..06a8808e88 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSRepository.kt@@ -55,7 +55,7 @@ class GrapheneOSRepository(private val context: Context) {         try {             val (status, _, bytes) =                 NetworkClient.performRequestBytesFull(GrapheneOSRepo.METADATA_URL)-            if (status !in 200..299) {+            if (status !in HTTP_OK_MIN..HTTP_OK_MAX) {                 return@withLock Result.failure(                     IllegalStateException("index fetch failed: HTTP $status")                 )@@ -89,9 +89,15 @@ class GrapheneOSRepository(private val context: Context) {             val parsed = GrapheneOSIndex.packagesFor(context, index, wanted)             cached = parsed             Result.success(parsed)-        } catch (e: Exception) {-            Log.w(TAG, "index fetch/verify failed", e)-            Result.failure(e)+        } catch (expected: IllegalStateException) {+            Log.w(TAG, "index fetch/verify failed", expected)+            Result.failure(expected)+        } catch (expected: java.io.IOException) {+            Log.w(TAG, "index fetch/verify failed", expected)+            Result.failure(expected)+        } catch (expected: SecurityException) {+            Log.w(TAG, "index fetch/verify failed", expected)+            Result.failure(expected)         }     } @@ -113,14 +119,19 @@ class GrapheneOSRepository(private val context: Context) {      private suspend fun readStoredTimestamp(): Long = try {         context.grapheneOSDataStore.data.first()[INDEX_TIMESTAMP_KEY] ?: 0L-    } catch (_: Exception) {+    } catch (expected: java.io.IOException) {+        Log.w(TAG, "read stored timestamp", expected)+        0L+    } catch (expected: IllegalStateException) {+        Log.w(TAG, "read stored timestamp", expected)         0L     }      private suspend fun persistTimestamp(timestamp: Long) {         try {             context.grapheneOSDataStore.edit { it[INDEX_TIMESTAMP_KEY] = timestamp }-        } catch (_: Exception) {+        } catch (expected: java.io.IOException) {+            Log.w(TAG, "persist timestamp", expected)         }     } @@ -129,5 +140,7 @@ class GrapheneOSRepository(private val context: Context) {          /** Newline + 100 base64 signature characters + newline. */         const val TRAILER_BYTES = 102+        private const val HTTP_OK_MIN = 200+        private const val HTTP_OK_MAX = 299     } }
appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.ktindex ac92364f8a..8bfa958f19 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt@@ -106,30 +106,45 @@ class InstallCoordinator(         }         stage(app.packageName, InstallStage.Preparing)         return try {-            when (app.source) {+            val outcome = when (app.source) {                 AppSource.PLAYSTORE -> installFromPlay(app)                 AppSource.ACCRESCENT -> installFromAccrescent(app)                 AppSource.GRAPHENEOS -> installFromGrapheneOS(app)                 else -> installFromUrl(app)-            }.also { outcome ->-                if (outcome.started) {-                    // The bytes are committed but the OS is still writing them in; hold the-                    // row at Installing until InstallStatusReceiver reports the real outcome-                    // (a large split install can take several seconds past this point).-                    stage(app.packageName, InstallStage.Installing)-                } else {-                    stage(app.packageName, InstallStage.Failed(outcome.verification.shortReason()))-                }-                record(app.packageName, outcome.verification)             }+            record(app.packageName, outcome.verification)+            finishInstall(app.packageName, outcome)         } catch (e: CancellationException) {             clear(app.packageName)             throw e-        } catch (e: Exception) {-            Log.e(TAG, "Install failed for ${app.packageName}", e)-            stage(app.packageName, InstallStage.Failed(e.message ?: "download failed"))-            SessionInstaller.Outcome(false, VerificationResult.Rejected(e.message ?: "download failed"))+        } catch (e: IOException) {+            failInstall(app.packageName, e)+        } catch (e: SecurityException) {+            failInstall(app.packageName, e)+        } catch (e: IllegalStateException) {+            failInstall(app.packageName, e)+        }+    }++    private fun finishInstall(+        packageName: String,+        outcome: SessionInstaller.Outcome,+    ): SessionInstaller.Outcome {+        if (outcome.started) {+            // The bytes are committed but the OS is still writing them in; hold the+            // row at Installing until InstallStatusReceiver reports the real outcome+            // (a large split install can take several seconds past this point).+            stage(packageName, InstallStage.Installing)+        } else {+            stage(packageName, InstallStage.Failed(outcome.verification.shortReason()))         }+        return outcome+    }++    private fun failInstall(packageName: String, e: Exception): SessionInstaller.Outcome {+        Log.e(TAG, "Install failed for $packageName", e)+        stage(packageName, InstallStage.Failed(e.message ?: "download failed"))+        return SessionInstaller.Outcome(false, VerificationResult.Rejected(e.message ?: "download failed"))     }      /** Drop a terminal [InstallStage.Failed] marker, e.g. when the user retries. */@@ -187,8 +202,8 @@ class InstallCoordinator(             rawConnection.sslSocketFactory = sslSocketFactory         }         val conn = (rawConnection as HttpURLConnection).apply {-            connectTimeout = 20_000-            readTimeout = 60_000+            connectTimeout = CONNECT_TIMEOUT_MS+            readTimeout = READ_TIMEOUT_MS             instanceFollowRedirects = true         }         try {@@ -196,7 +211,7 @@ class InstallCoordinator(             // message is the URL, which the UI then shows the user as the reason the install             // failed. Read the status first and say what the server actually said.             val code = conn.responseCode-            if (code !in 200..299) {+            if (code !in HTTP_OK_MIN..HTTP_OK_MAX) {                 throw IOException("the server returned HTTP $code for ${target.name}")             } @@ -218,7 +233,7 @@ class InstallCoordinator(             val input = if (gzipped) GZIPInputStream(counting) else counting             input.use { source ->                 target.outputStream().use { out ->-                    source.copyTo(out, 64 * 1024)+                    source.copyTo(out, COPY_BUFFER_SIZE)                 }             }         } finally {@@ -323,7 +338,8 @@ class InstallCoordinator(              val splits = try {                 accrescent.downloadInfo(app.packageName)-            } catch (e: IncompatibleDeviceException) {+            } catch (expected: IncompatibleDeviceException) {+                Log.w(TAG, "no Accrescent build for ${app.packageName}", expected)                 return@withContext SessionInstaller.Outcome(                     false, VerificationResult.Rejected("this app has no build for your device")                 )@@ -429,8 +445,11 @@ class InstallCoordinator(         certHash: String?,     ) = try {         play.purchase(packageName, versionCode, offerType, certHash)-    } catch (e: Exception) {-        if (certHash == null) throw e+    } catch (expected: IOException) {+        if (certHash == null) throw expected+        play.purchase(packageName, versionCode, offerType, null)+    } catch (expected: IllegalStateException) {+        if (certHash == null) throw expected         play.purchase(packageName, versionCode, offerType, null)     } @@ -443,7 +462,7 @@ class InstallCoordinator(     private suspend fun record(packageName: String, result: VerificationResult) {         _verification.value = _verification.value + (packageName to result)         val stamp = result.stamp ?: return-        runCatching {+        try {             db.pinnedStampDao().upsert(                 PinnedStampEntity(                     packageName = packageName,@@ -451,6 +470,10 @@ class InstallCoordinator(                     firstSeen = System.currentTimeMillis(),                 )             )+        } catch (expected: android.database.sqlite.SQLiteException) {+            Log.w(TAG, "pin stamp for $packageName", expected)+        } catch (expected: IllegalStateException) {+            Log.w(TAG, "pin stamp for $packageName", expected)         }     } @@ -470,5 +493,10 @@ class InstallCoordinator(      private companion object {         const val TAG = "InstallCoordinator"+        private const val CONNECT_TIMEOUT_MS = 20_000+        private const val READ_TIMEOUT_MS = 60_000+        private const val HTTP_OK_MIN = 200+        private const val HTTP_OK_MAX = 299+        private const val COPY_BUFFER_SIZE = 64 * 1024     } }
appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallStatusReceiver.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallStatusReceiver.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallStatusReceiver.ktindex 9f6c40286d..b99d77a1b0 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallStatusReceiver.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallStatusReceiver.kt@@ -27,60 +27,75 @@ class InstallStatusReceiver : BroadcastReceiver() {     companion object {         const val ACTION_INSTALL_STATUS = "com.vayunmathur.appstore.INSTALL_STATUS"         private const val TAG = "InstallStatusReceiver"+        private const val UNKNOWN_STATUS = -1     }      override fun onReceive(context: Context, intent: Intent) {-        val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -1)+        val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, UNKNOWN_STATUS)         val message = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)         val pkg = intent.getStringExtra(PackageInstaller.EXTRA_PACKAGE_NAME)          when (status) {-            PackageInstaller.STATUS_PENDING_USER_ACTION -> {-                // Forward user action intent-                val userAction = if (android.os.Build.VERSION.SDK_INT >= 33) {-                    intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)-                } else {-                    @Suppress("DEPRECATION")-                    intent.getParcelableExtra(Intent.EXTRA_INTENT)-                }-                try {-                    userAction?.let {-                        it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)-                        context.startActivity(it)-                    }-                } catch (e: Exception) {-                    Log.w(TAG, "Failed to start user action: ${e.message}")-                }-            }-            PackageInstaller.STATUS_SUCCESS -> {-                Log.i(TAG, "Install success for $pkg")-                pkg?.let { InstallEvents.publish(InstallResult(it, success = true)) }-            }+            PackageInstaller.STATUS_PENDING_USER_ACTION -> forwardUserAction(context, intent)+            PackageInstaller.STATUS_SUCCESS -> reportSuccess(pkg)             // The user backing out of the system prompt is not a failure worth reporting back.-            PackageInstaller.STATUS_FAILURE_ABORTED -> {-                Log.i(TAG, "Install aborted for $pkg")-                pkg?.let { InstallEvents.publish(InstallResult(it, success = false)) }-            }-            else -> {-                Log.w(TAG, "Install failed for $pkg status=$status message=$message")-                pkg?.let { InstallEvents.publish(InstallResult(it, success = false)) }-                // A source-restricted refusal is the OS's final answer, so stop offering it.-                RestrictedPackages.recordIfRestricted(context, pkg, message)-                val reason = when (status) {-                    PackageInstaller.STATUS_FAILURE_INCOMPATIBLE ->-                        context.getString(R.string.install_failure_incompatible)-                    PackageInstaller.STATUS_FAILURE_STORAGE ->-                        context.getString(R.string.install_failure_storage)-                    PackageInstaller.STATUS_FAILURE_CONFLICT ->-                        context.getString(R.string.install_failure_conflict)-                    else -> message?.takeIf { it.isNotBlank() }-                        ?: context.getString(R.string.install_failure_unknown)-                }-                val text = context.getString(R.string.install_failed_reason, pkg.orEmpty(), reason)-                if (!InstallFailureBatch.collect(text)) {-                    AppMessages.show(text, duration = AppMessages.Duration.Long)-                }+            PackageInstaller.STATUS_FAILURE_ABORTED -> reportAborted(pkg)+            else -> reportFailure(context, status, message, pkg)+        }+    }++    private fun forwardUserAction(context: Context, intent: Intent) {+        // Forward user action intent+        val userAction = if (android.os.Build.VERSION.SDK_INT >= 33) {+            intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)+        } else {+            @Suppress("DEPRECATION")+            intent.getParcelableExtra(Intent.EXTRA_INTENT)+        }+        try {+            userAction?.let {+                it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+                context.startActivity(it)             }+        } catch (expected: android.content.ActivityNotFoundException) {+            Log.w(TAG, "Failed to start user action: ${expected.message}")+        } catch (expected: SecurityException) {+            Log.w(TAG, "Failed to start user action: ${expected.message}")+        }+    }++    private fun reportSuccess(pkg: String?) {+        Log.i(TAG, "Install success for $pkg")+        pkg?.let { InstallEvents.publish(InstallResult(it, success = true)) }+    }++    private fun reportAborted(pkg: String?) {+        Log.i(TAG, "Install aborted for $pkg")+        pkg?.let { InstallEvents.publish(InstallResult(it, success = false)) }+    }++    private fun reportFailure(context: Context, status: Int, message: String?, pkg: String?) {+        Log.w(TAG, "Install failed for $pkg status=$status message=$message")+        pkg?.let { InstallEvents.publish(InstallResult(it, success = false)) }+        // A source-restricted refusal is the OS's final answer, so stop offering it.+        RestrictedPackages.recordIfRestricted(context, pkg, message)+        val reason = failureReason(context, status, message)+        val text = context.getString(R.string.install_failed_reason, pkg.orEmpty(), reason)+        if (!InstallFailureBatch.collect(text)) {+            AppMessages.show(text, duration = AppMessages.Duration.Long)+        }+    }++    private fun failureReason(context: Context, status: Int, message: String?): String {+        return when (status) {+            PackageInstaller.STATUS_FAILURE_INCOMPATIBLE ->+                context.getString(R.string.install_failure_incompatible)+            PackageInstaller.STATUS_FAILURE_STORAGE ->+                context.getString(R.string.install_failure_storage)+            PackageInstaller.STATUS_FAILURE_CONFLICT ->+                context.getString(R.string.install_failure_conflict)+            else -> message?.takeIf { it.isNotBlank() }+                ?: context.getString(R.string.install_failure_unknown)         }     } }
appstore/src/main/java/com/vayunmathur/appstore/data/installer/PlayDownloader.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/PlayDownloader.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/PlayDownloader.ktindex 9ca3ada654..eaf4775e79 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/PlayDownloader.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/PlayDownloader.kt@@ -22,9 +22,17 @@ class PlayDownloader( ) {     companion object {         private const val TAG = "PlayDownloader"+        private const val CONNECT_TIMEOUT_MS = 30_000+        private const val READ_TIMEOUT_MS = 60_000+        private const val COPY_BUFFER_SIZE = 8192+        private const val HTTP_OK_MIN = 200+        private const val HTTP_OK_MAX = 299+        private const val HTTP_PARTIAL = 206+        private const val HTTP_FORBIDDEN = 403+        private const val HTTP_GONE = 410     } -    class ExpiredUrlException(message: String) : Exception(message)+    class ExpiredUrlException(message: String) : java.io.IOException(message)      /**      * Download list of PlayFiles to cache dir, verify, and return local Files.@@ -46,25 +54,21 @@ class PlayDownloader(                 val destFile = File(baseDir, fileName)                 val tmpFile = File(baseDir, "$fileName.tmp") -                if (destFile.exists() && destFile.length() > 0) {-                    if (gFile.size <= 0 || destFile.length() == gFile.size) {-                        localFiles.add(destFile)-                        totalDownloaded += destFile.length()-                        continue-                    }+                if (isCachedComplete(destFile, gFile.size)) {+                    localFiles.add(destFile)+                    totalDownloaded += destFile.length()+                    continue                 }                  val result = downloadSingleFile(gFile, destFile, tmpFile) { bytesDownloaded ->-                    val overall = if (totalSize > 0) {-                        (totalDownloaded + bytesDownloaded).toFloat() / totalSize-                    } else {-                        (index.toFloat() + (if (gFile.size > 0) bytesDownloaded.toFloat() / gFile.size else 0f)) / gplayFiles.size-                    }-                    progressCallback(overall.coerceIn(0f, 1f))+                    progressCallback(+                        overallProgress(index, gFile, bytesDownloaded, totalDownloaded, totalSize, gplayFiles.size)+                    )                 }                  if (result.isFailure) {-                    return Result.failure(result.exceptionOrNull() ?: Exception("Download failed for $fileName"))+                    val cause = result.exceptionOrNull() ?: java.io.IOException("Download failed for $fileName")+                    return Result.failure(cause)                 }                  val file = result.getOrNull()!!@@ -73,85 +77,127 @@ class PlayDownloader(             }              Result.success(localFiles)-        } catch (e: Exception) {-            Log.e(TAG, "downloadFiles failed: ${e.message}", e)-            Result.failure(e)+        } catch (expected: java.io.IOException) {+            Log.e(TAG, "downloadFiles failed: ${expected.message}", expected)+            Result.failure(expected)+        } catch (expected: SecurityException) {+            Log.e(TAG, "downloadFiles failed: ${expected.message}", expected)+            Result.failure(expected)         }     } +    private fun isCachedComplete(destFile: File, expectedSize: Long): Boolean {+        if (!destFile.exists() || destFile.length() <= 0) return false+        return expectedSize <= 0 || destFile.length() == expectedSize+    }++    private fun overallProgress(+        index: Int,+        gFile: PlayFile,+        bytesDownloaded: Long,+        totalDownloaded: Long,+        totalSize: Long,+        fileCount: Int,+    ): Float {+        val overall = if (totalSize > 0) {+            (totalDownloaded + bytesDownloaded).toFloat() / totalSize+        } else {+            val fileFraction = if (gFile.size > 0) bytesDownloaded.toFloat() / gFile.size else 0f+            (index.toFloat() + fileFraction) / fileCount+        }+        return overall.coerceIn(0f, 1f)+    }+     private fun downloadSingleFile(         gFile: PlayFile,         destFile: File,         tmpFile: File,         progressCallback: (Long) -> Unit     ): Result<File> {-        return try {-            val urlString = gFile.url.takeIf { it.isNotBlank() } ?: return Result.failure(Exception("Empty URL for ${gFile.name}"))-            val existing = if (tmpFile.exists()) tmpFile.length() else 0L--            val conn = (URL(urlString).openConnection() as HttpURLConnection).apply {-                connectTimeout = 30_000-                readTimeout = 60_000-                instanceFollowRedirects = true-                useCaches = false-                if (existing > 0) {-                    setRequestProperty("Range", "bytes=$existing-")-                }+        val urlString = gFile.url.takeIf { it.isNotBlank() }+            ?: return Result.failure(java.io.IOException("Empty URL for ${gFile.name}"))+        val existing = if (tmpFile.exists()) tmpFile.length() else 0L++        val conn = (URL(urlString).openConnection() as HttpURLConnection).apply {+            connectTimeout = CONNECT_TIMEOUT_MS+            readTimeout = READ_TIMEOUT_MS+            instanceFollowRedirects = true+            useCaches = false+            if (existing > 0) {+                setRequestProperty("Range", "bytes=$existing-")             }+        } -            val code = try { conn.responseCode } catch (e: Exception) {-                conn.disconnect()-                throw e-            }+        val code = openConnection(conn) ?: return Result.failure(java.io.IOException("No response"))+        if (code !in HTTP_OK_MIN..HTTP_OK_MAX && code != HTTP_PARTIAL) {+            conn.disconnect()+            return expiredOrFailed(code)+        } -            if (code !in 200..299 && code != 206) {-                conn.disconnect()-                if (code == 403 || code == 410) {-                    return Result.failure(ExpiredUrlException("URL expired $code"))-                }-                return Result.failure(Exception("HTTP $code"))-            }+        val input = openInput(conn)+            ?: return Result.failure(java.io.IOException("Empty body"))+        return try {+            streamToTmp(input, tmpFile, existing, progressCallback)+            promoteTmp(tmpFile, destFile)+            Result.success(destFile)+        } catch (expected: java.io.IOException) {+            Result.failure(expected)+        } finally {+            conn.disconnect()+        }+    } -            val input = try {-                conn.inputStream-            } catch (_: Exception) {-                conn.disconnect()-                return Result.failure(Exception("Empty body"))-            }+    private fun openConnection(conn: HttpURLConnection): Int? {+        return try {+            conn.responseCode+        } catch (expected: java.io.IOException) {+            conn.disconnect()+            null+        }+    } -            val output = if (existing > 0) {-                java.io.FileOutputStream(tmpFile, true)-            } else {-                java.io.FileOutputStream(tmpFile, false)-            }+    private fun openInput(conn: HttpURLConnection): java.io.InputStream? {+        return try {+            conn.inputStream+        } catch (_: java.io.IOException) {+            conn.disconnect()+            null+        }+    } -            var downloaded = existing-            try {-                output.use { out ->-                    input.use { inp ->-                        val buffer = ByteArray(8192)-                        var read: Int-                        while (inp.read(buffer).also { read = it } != -1) {-                            out.write(buffer, 0, read)-                            downloaded += read-                            progressCallback(downloaded)-                        }-                    }-                }-            } finally {-                conn.disconnect()-            }+    private fun expiredOrFailed(code: Int): Result<File> {+        return if (code == HTTP_FORBIDDEN || code == HTTP_GONE) {+            Result.failure(ExpiredUrlException("URL expired $code"))+        } else {+            Result.failure(java.io.IOException("HTTP $code"))+        }+    } -            if (tmpFile.exists()) {-                if (destFile.exists()) destFile.delete()-                tmpFile.renameTo(destFile)+    private fun streamToTmp(+        input: java.io.InputStream,+        tmpFile: File,+        existing: Long,+        progressCallback: (Long) -> Unit,+    ) {+        val output = java.io.FileOutputStream(tmpFile, existing > 0)+        var downloaded = existing+        output.use { out ->+            input.use { inp ->+                val buffer = ByteArray(COPY_BUFFER_SIZE)+                var read: Int+                while (inp.read(buffer).also { read = it } != -1) {+                    out.write(buffer, 0, read)+                    downloaded += read+                    progressCallback(downloaded)+                }             }--            Result.success(destFile)-        } catch (e: Exception) {-            if (e is ExpiredUrlException) Result.failure(e)-            else Result.failure(e)         }     } +    private fun promoteTmp(tmpFile: File, destFile: File) {+        if (tmpFile.exists()) {+            if (destFile.exists()) destFile.delete()+            tmpFile.renameTo(destFile)+        }+    } }
appstore/src/main/java/com/vayunmathur/appstore/data/installer/SessionInstaller.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/SessionInstaller.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/SessionInstaller.ktindex c80c8b4031..1c034a614d 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/SessionInstaller.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/SessionInstaller.kt@@ -69,69 +69,122 @@ class SessionInstaller(             // second session for the same package makes PackageManager reject it with             // INSTALL_FAILED_DUPLICATE_PACKAGE ("Duplicate package ... in pending install             // requests"). Multi-split installs (e.g. Accrescent) hit this most, being slower.-            runCatching {-                installer.mySessions-                    .filter { it.appPackageName == packageName }-                    .forEach { runCatching { installer.abandonSession(it.sessionId) } }-            }+            abandonPendingSessions(installer, packageName) -            val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply {-                if (computedSize > 0) setSize(computedSize)-                setAppPackageName(packageName)-                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {-                    // API 34+. Below that the system fills the installer package-                    // in from the calling UID anyway.-                    setInstallerPackageName(context.packageName)-                    setRequestUpdateOwnership(true)-                }-                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {-                    setPackageSource(PackageInstaller.PACKAGE_SOURCE_STORE)-                }-                // Silent install is only offered for updates: the OS honours-                // USER_ACTION_NOT_REQUIRED when this app is the target's update owner, and-                // a first-time install of a package owned by someone else would prompt-                // anyway. First installs keep the confirmation dialog unconditionally.-                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && isInstalled(packageName)) {-                    setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED)-                }-                setInstallLocation(android.content.pm.PackageInfo.INSTALL_LOCATION_AUTO)-                setOriginatingUid(Process.myUid())-            }+            val params = sessionParams(computedSize, packageName)              val sessionId = installer.createSession(params)             val session = installer.openSession(sessionId)              try {-                for (file in files) {-                    val name = file.name-                    session.openWrite(name, 0, file.length()).use { out ->-                        file.inputStream().use { input ->-                            input.copyTo(out)-                        }-                        session.fsync(out)+                writeFiles(session, files)+            } catch (expected: java.io.IOException) {+                Log.e(TAG, "Write failed for $packageName: ${expected.message}", expected)+                abandonQuietly(session)+                return false+            }++            commitSession(session, sessionId, packageName)+            Log.i(TAG, "Commit started for $packageName sessionId=$sessionId")+            true+        } catch (expected: SecurityException) {+            Log.e(TAG, "Install failed for $packageName: ${expected.message}", expected)+            false+        } catch (expected: java.io.IOException) {+            Log.e(TAG, "Install failed for $packageName: ${expected.message}", expected)+            false+        } catch (expected: IllegalStateException) {+            Log.e(TAG, "Install failed for $packageName: ${expected.message}", expected)+            false+        }+    }++    private fun abandonPendingSessions(+        installer: android.content.pm.PackageInstaller,+        packageName: String,+    ) {+        try {+            installer.mySessions+                .filter { it.appPackageName == packageName }+                .forEach {+                    try {+                        installer.abandonSession(it.sessionId)+                    } catch (expected: SecurityException) {+                        Log.w(TAG, "abandon ${it.sessionId}", expected)                     }                 }-            } catch (e: Exception) {-                Log.e(TAG, "Write failed for $packageName: ${e.message}", e)-                try { session.abandon() } catch (_: Exception) {}-                return false+        } catch (expected: SecurityException) {+            Log.w(TAG, "list sessions", expected)+        }+    }++    private fun sessionParams(+        computedSize: Long,+        packageName: String,+    ): PackageInstaller.SessionParams {+        return PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply {+            if (computedSize > 0) setSize(computedSize)+            setAppPackageName(packageName)+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+                // API 34+. Below that the system fills the installer package+                // in from the calling UID anyway.+                setInstallerPackageName(context.packageName)+                setRequestUpdateOwnership(true)+            }+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+                setPackageSource(PackageInstaller.PACKAGE_SOURCE_STORE)             }+            // Silent install is only offered for updates: the OS honours+            // USER_ACTION_NOT_REQUIRED when this app is the target's update owner, and+            // a first-time install of a package owned by someone else would prompt+            // anyway. First installs keep the confirmation dialog unconditionally.+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && isInstalled(packageName)) {+                setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED)+            }+            setInstallLocation(android.content.pm.PackageInfo.INSTALL_LOCATION_AUTO)+            setOriginatingUid(Process.myUid())+        }+    } -            val intent = Intent(context, InstallStatusReceiver::class.java).apply {-                action = InstallStatusReceiver.ACTION_INSTALL_STATUS+    private fun writeFiles(session: PackageInstaller.Session, files: List<File>) {+        for (file in files) {+            val name = file.name+            session.openWrite(name, 0, file.length()).use { out ->+                file.inputStream().use { input ->+                    input.copyTo(out)+                }+                session.fsync(out)             }-            val pendingFlags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE-            val pendingIntent = PendingIntent.getBroadcast(-                context, sessionId, intent, pendingFlags-            )+        }+    }++    private fun abandonQuietly(session: PackageInstaller.Session) {+        try {+            session.abandon()+        } catch (expected: SecurityException) {+            Log.w(TAG, "abandon session", expected)+        }+    }++    private fun commitSession(+        session: PackageInstaller.Session,+        sessionId: Int,+        packageName: String,+    ) {+        val intent = Intent(context, InstallStatusReceiver::class.java).apply {+            action = InstallStatusReceiver.ACTION_INSTALL_STATUS+        }+        val pendingFlags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE+        val pendingIntent = PendingIntent.getBroadcast(+            context, sessionId, intent, pendingFlags+        )+        try {             session.commit(pendingIntent.intentSender)             session.close()--            Log.i(TAG, "Commit started for $packageName sessionId=$sessionId")-            true-        } catch (e: Exception) {-            Log.e(TAG, "Install failed for $packageName: ${e.message}", e)-            false+        } catch (expected: SecurityException) {+            Log.e(TAG, "commit failed for $packageName", expected)+            abandonQuietly(session)+            throw expected         }     } 
appstore/src/main/java/com/vayunmathur/appstore/data/play/AnonymousAuthRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/play/AnonymousAuthRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/play/AnonymousAuthRepository.ktindex 9534fc9b7d..1d2a4fcef9 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/play/AnonymousAuthRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/play/AnonymousAuthRepository.kt@@ -1,6 +1,5 @@ package com.vayunmathur.appstore.data.play -import android.content.Context import android.util.Log import com.aurora.gplayapi.data.models.AuthData import com.aurora.gplayapi.helpers.AuthHelper@@ -69,6 +68,18 @@ class AnonymousAuthRepository {         /** First backoff step; doubles each attempt. */         private const val BASE_BACKOFF_MS = 800L +        private const val CONNECT_TIMEOUT_MS = 15_000+        private const val READ_TIMEOUT_MS = 15_000+        private const val HTTP_ERROR_MIN = 400+        private const val HTTP_OK_MIN = 200+        private const val HTTP_OK_MAX = 299+        private const val HTTP_BAD_REQUEST = 400+        private const val HTTP_FORBIDDEN = 403+        private const val HTTP_NOT_FOUND = 404+        private const val HTTP_RATE_LIMITED = 429+        private const val HTTP_UNAVAILABLE = 503+        private const val HTTP_SERVER_ERROR_MIN = 500+         /**          * Statuses worth retrying.          *@@ -82,7 +93,7 @@ class AnonymousAuthRepository {         private fun isTransient(error: Throwable): Boolean = when (error) {             is AuthError.RateLimited, is AuthError.VpnRequired, is AuthError.Maintenance -> true             is AuthError.Network -> true-            is AuthError.Unknown -> error.code >= 500+            is AuthError.Unknown -> error.code >= HTTP_SERVER_ERROR_MIN             else -> false         }     }@@ -115,8 +126,8 @@ class AnonymousAuthRepository {             val bodyBytes = propsJson.toByteArray(Charsets.UTF_8)              val conn = (URL(dispenserUrl).openConnection() as HttpURLConnection).apply {-                connectTimeout = 15_000-                readTimeout = 15_000+                connectTimeout = CONNECT_TIMEOUT_MS+                readTimeout = READ_TIMEOUT_MS                 requestMethod = "POST"                 doOutput = true                 doInput = true@@ -129,30 +140,34 @@ class AnonymousAuthRepository {             }             conn.outputStream.use { it.write(bodyBytes) } -            val code = try { conn.responseCode } catch (e: Exception) {+            val code = try {+                conn.responseCode+            } catch (expected: java.io.IOException) {                 conn.disconnect()-                return@withContext Result.failure(AuthError.Network(e.message))+                return@withContext Result.failure(AuthError.Network(expected.message))             }             val responseBody = try {-                val stream = if (code >= 400) conn.errorStream ?: conn.inputStream else conn.inputStream+                val stream = if (code >= HTTP_ERROR_MIN) conn.errorStream ?: conn.inputStream else conn.inputStream                 stream?.bufferedReader(Charsets.UTF_8)?.readText() ?: ""-            } catch (_: Exception) { "" } finally {+            } catch (_: java.io.IOException) {+                ""+            } finally {                 conn.disconnect()             } -            if (code !in 200..299) {+            if (code !in HTTP_OK_MIN..HTTP_OK_MAX) {                 return@withContext Result.failure(mapError(code, responseBody))             }              try {                 val auth = json.decodeFromString(AuthResponse.serializer(), responseBody)                 Result.success(auth)-            } catch (e: Exception) {-                Log.w(TAG, "Parse auth failed: ${e.message}")+            } catch (expected: IllegalArgumentException) {+                Log.w(TAG, "Parse auth failed: ${expected.message}")                 Result.failure(AuthError.Unknown(code, responseBody))             }-        } catch (e: Exception) {-            Result.failure(AuthError.Network(e.message))+        } catch (expected: java.io.IOException) {+            Result.failure(AuthError.Network(expected.message))         }     } @@ -160,7 +175,6 @@ class AnonymousAuthRepository {      * Build AuthData from dispenser response using gplayapi AuthHelper.      */     suspend fun buildAuthData(-        context: Context,         email: String,         token: String,         deviceProps: Properties@@ -177,9 +191,12 @@ class AnonymousAuthRepository {                     locale = locale                 )             Result.success(authData)-        } catch (e: Exception) {-            Log.w(TAG, "buildAuthData failed: ${e.message}", e)-            Result.failure(e)+        } catch (expected: IllegalStateException) {+            Log.w(TAG, "buildAuthData failed: ${expected.message}", expected)+            Result.failure(expected)+        } catch (expected: IllegalArgumentException) {+            Log.w(TAG, "buildAuthData failed: ${expected.message}", expected)+            Result.failure(expected)         }     } @@ -192,7 +209,6 @@ class AnonymousAuthRepository {      * and throttle each other again.      */     suspend fun ensureAuthData(-        context: Context,         deviceProps: Properties,         dispenserUrls: List<String> = FALLBACK_DISPENSERS     ): Result<AuthData> = withContext(Dispatchers.IO) {@@ -205,7 +221,7 @@ class AnonymousAuthRepository {                 val credResult = fetchAnonCredentials(deviceProps, url)                 val cred = credResult.getOrNull()                 if (cred != null) {-                    val authResult = buildAuthData(context, cred.email, cred.auth, deviceProps)+                    val authResult = buildAuthData(cred.email, cred.auth, deviceProps)                     if (authResult.isSuccess) return@withContext authResult                     // Credentials arrived but were unusable. A different                     // account may well work, so this is worth another attempt.@@ -236,7 +252,11 @@ class AnonymousAuthRepository {         var first = true         for ((k, v) in props.entries) {             if (!first) sb.append(",")-            sb.append("\"").append(escapeJson(k.toString())).append("\":\"").append(escapeJson(v.toString())).append("\"")+            sb.append("\"")+                .append(escapeJson(k.toString()))+                .append("\":\"")+                .append(escapeJson(v.toString()))+                .append("\"")             first = false         }         sb.append("}")@@ -252,11 +272,11 @@ class AnonymousAuthRepository {      private fun mapError(code: Int, body: String?): Throwable {         return when (code) {-            400 -> AuthError.BadRequest-            403 -> AuthError.VpnRequired-            404 -> AuthError.NotFound-            429 -> AuthError.RateLimited-            503 -> AuthError.Maintenance+            HTTP_BAD_REQUEST -> AuthError.BadRequest+            HTTP_FORBIDDEN -> AuthError.VpnRequired+            HTTP_NOT_FOUND -> AuthError.NotFound+            HTTP_RATE_LIMITED -> AuthError.RateLimited+            HTTP_UNAVAILABLE -> AuthError.Maintenance             else -> AuthError.Unknown(code, body)         }     }
appstore/src/main/java/com/vayunmathur/appstore/data/play/DeviceInfoProvider.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/play/DeviceInfoProvider.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/play/DeviceInfoProvider.ktindex 3330f8623c..282b1bb42f 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/play/DeviceInfoProvider.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/play/DeviceInfoProvider.kt@@ -37,7 +37,9 @@ object DeviceInfoProvider {         } else {             buildDeviceProperties(context)         }-    } catch (_: Exception) {+    } catch (_: android.content.res.Resources.NotFoundException) {+        buildDeviceProperties(context)+    } catch (_: java.io.IOException) {         buildDeviceProperties(context)     } @@ -46,6 +48,28 @@ object DeviceInfoProvider {         val pm = context.packageManager         val gsf = GsfVersionProvider.get(context) +        setBuildProps(props)+        setConfigProps(context, props)+        setDisplayProps(context, props)++        // ABIs+        props.setProperty("Platforms", Build.SUPPORTED_ABIS.joinToString(","))+        setFeatureProps(pm, props)+        setLocaleProps(context, props)+        setSharedLibProps(pm, props)+        setGlProps(props)+        setGsfProps(gsf, props)++        props.setProperty("Client", "android-google")+        props.setProperty("Roaming", "mobile-notroaming")+        props.setProperty("TimeZone", "UTC-10")+        props.setProperty("CellOperator", "310")+        props.setProperty("SimOperator", "38")++        return props+    }++    private fun setBuildProps(props: Properties) {         // Build.*         props.setProperty("Ro.product.brand", Build.BRAND)         props.setProperty("Ro.product.name", Build.PRODUCT)@@ -69,16 +93,22 @@ object DeviceInfoProvider {         props.setProperty("Build.RADIO", Build.getRadioVersion() ?: "unknown")         props.setProperty("Build.SDK_INT", Build.VERSION.SDK_INT.toString())         props.setProperty("Build.RELEASE", Build.VERSION.RELEASE ?: "13")+    } +    private fun setConfigProps(context: Context, props: Properties) {         // Config         val config = context.resources.configuration         props.setProperty("TouchScreen", config.touchscreen.toString())         props.setProperty("Keyboard", config.keyboard.toString())         props.setProperty("Navigation", config.navigation.toString())-        props.setProperty("ScreenLayout", (config.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK).toString())+        val screenSize = (config.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK).toString()+        props.setProperty("ScreenLayout", screenSize)         props.setProperty("HasHardKeyboard", (config.keyboard == Configuration.KEYBOARD_QWERTY).toString())-        props.setProperty("HasFiveWayNavigation", (config.navigation == Configuration.NAVIGATION_DPAD).toString())+        val hasDpad = (config.navigation == Configuration.NAVIGATION_DPAD).toString()+        props.setProperty("HasFiveWayNavigation", hasDpad)+    } +    private fun setDisplayProps(context: Context, props: Properties) {         // Display         try {             val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager@@ -88,62 +118,70 @@ object DeviceInfoProvider {             props.setProperty("Screen.Density", metrics.densityDpi.toString())             props.setProperty("Screen.Width", metrics.widthPixels.toString())             props.setProperty("Screen.Height", metrics.heightPixels.toString())-        } catch (_: Exception) {-            props.setProperty("Screen.Density", "420")-            props.setProperty("Screen.Width", "1080")-            props.setProperty("Screen.Height", "1920")+        } catch (_: SecurityException) {+            setFallbackDisplayProps(props)+        } catch (_: IllegalStateException) {+            setFallbackDisplayProps(props)         }+    } -        // ABIs-        props.setProperty("Platforms", Build.SUPPORTED_ABIS.joinToString(","))+    private fun setFallbackDisplayProps(props: Properties) {+        props.setProperty("Screen.Density", "420")+        props.setProperty("Screen.Width", "1080")+        props.setProperty("Screen.Height", "1920")+    } +    private fun setFeatureProps(pm: PackageManager, props: Properties) {         // Features         try {             val features = pm.systemAvailableFeatures.mapNotNull { it.name }.joinToString(",")             props.setProperty("Features", features)-        } catch (_: Exception) {+        } catch (_: SecurityException) {             props.setProperty("Features", "")         }+    } +    private fun setLocaleProps(context: Context, props: Properties) {         // Locales         try {             val locales = context.assets.locales?.joinToString(",") ?: Locale.getDefault().toString()             props.setProperty("Locales", locales)-        } catch (_: Exception) {+        } catch (_: java.io.IOException) {             props.setProperty("Locales", "en_US")         }+    } +    private fun setSharedLibProps(pm: PackageManager, props: Properties) {         // Shared libs         try {             val libs = pm.systemSharedLibraryNames?.joinToString(",") ?: ""             props.setProperty("SharedLibraries", libs)-        } catch (_: Exception) {+        } catch (_: SecurityException) {             props.setProperty("SharedLibraries", "")         }+    } +    private fun setGlProps(props: Properties) {         // GL - best effort-        props.setProperty("GL.Version", "OpenGL ES 3.0")+        props.setProperty("GL.Version", EglExtensionProvider.GL_VERSION)         props.setProperty("GL.Extensions", "")         props.setProperty("GL.EGL.Extensions", "")+    } +    private fun setGsfProps(gsf: GsfVersion, props: Properties) {         // GSF / Vending         props.setProperty("GSF.version", gsf.gsfVersionCode.toString())         props.setProperty("Vending.version", gsf.vendingVersionCode.toString())         props.setProperty("Vending.versionString", gsf.vendingVersionString)--        props.setProperty("Client", "android-google")-        props.setProperty("Roaming", "mobile-notroaming")-        props.setProperty("TimeZone", "UTC-10")-        props.setProperty("CellOperator", "310")-        props.setProperty("SimOperator", "38")--        return props     }      /**      * Convert our Properties to gplayapi's DeviceInfoProvider      */-    fun toGplayDeviceInfoProvider(props: Properties, locale: String = Locale.getDefault().toString()): com.aurora.gplayapi.data.providers.DeviceInfoProvider {+    fun toGplayDeviceInfoProvider(+        props: Properties,+        locale: String = Locale.getDefault().toString()+    ): com.aurora.gplayapi.data.providers.DeviceInfoProvider {         return com.aurora.gplayapi.data.providers.DeviceInfoProvider(props, locale)     } }
appstore/src/main/java/com/vayunmathur/appstore/data/play/EglExtensionProvider.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/play/EglExtensionProvider.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/play/EglExtensionProvider.ktindex 7357dc2558..cec50d3280 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/play/EglExtensionProvider.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/play/EglExtensionProvider.kt@@ -6,6 +6,6 @@ package com.vayunmathur.appstore.data.play  */ object EglExtensionProvider {     val eglExtensions: List<String> = emptyList()-    fun getGlVersion(): String = "OpenGL ES 3.0"+    const val GL_VERSION = "OpenGL ES 3.0"     fun getGlExtensions(): List<String> = emptyList() }
appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayHttpClient.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayHttpClient.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayHttpClient.ktindex bdc96062b9..7adc08a33f 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayHttpClient.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayHttpClient.kt@@ -32,10 +32,14 @@ class PlayHttpClient : IHttpClient {     companion object {         private const val CONNECT_TIMEOUT = 30_000         private const val READ_TIMEOUT = 30_000-        private const val MAX_REDIRECTS = 5+        private const val HTTP_OK_MIN = 200+        private const val HTTP_OK_MAX = 299+        private const val HTTP_ERROR_MIN = 400          private const val TOO_MANY_REQUESTS = 429         private const val SERVICE_UNAVAILABLE = 503+        private const val MILLIS_PER_SECOND = 1_000L+        private const val NETWORK_FAILURE_CODE = -1          /** Smallest gap between two requests starting, before anything has been refused. */         private const val MIN_REQUEST_GAP_MS = 250L@@ -118,7 +122,7 @@ class PlayHttpClient : IHttpClient {     }      /** One attempt's answer, plus how long the server asked us to wait before the next. */-    private data class Attempt(val response: PlayResponse, val retryAfterMs: Long)+    internal data class Attempt(val response: PlayResponse, val retryAfterMs: Long)      private fun execute(         url: String,@@ -181,7 +185,7 @@ class PlayHttpClient : IHttpClient {     private fun retryAfterMs(conn: HttpURLConnection): Long =         conn.getHeaderField("Retry-After")?.trim()?.toLongOrNull()             ?.takeIf { it >= 0 }-            ?.times(1_000L)+            ?.times(MILLIS_PER_SECOND)             ?: 0L      private fun executeOnce(@@ -192,90 +196,104 @@ class PlayHttpClient : IHttpClient {         contentType: String? = null     ): Attempt {         return try {-            var currentUrl = url-            var currentMethod = method-            var currentBody: ByteArray? = rawBody-            var currentContentType: String? = contentType-            var redirects = 0-            var lastConn: HttpURLConnection? = null-            var result: Attempt? = null--            while (result == null) {-                val conn = openConnection(currentUrl, currentMethod, headers, currentBody, currentContentType)-                lastConn = conn-                val code = try {-                    conn.responseCode-                } catch (e: IOException) {-                    conn.disconnect()-                    throw e-                }--                // Manual redirect handling-                if (code in 301..308 && code != 304 && redirects < MAX_REDIRECTS) {-                    val loc = conn.getHeaderField("Location") ?: conn.getHeaderField("location")-                    if (loc != null) {-                        currentUrl = URL(URL(currentUrl), loc).toString()-                        if (code == 303) {-                            currentMethod = "GET"-                            currentBody = null-                            currentContentType = null-                        }-                        redirects++-                        try { conn.inputStream?.close() } catch (_: Exception) {}-                        conn.disconnect()-                        continue-                    }-                }--                val ct = conn.getHeaderField("Content-Type")-                val responseMessage = try { conn.responseMessage } catch (_: Exception) { "" } ?: ""-                val retryAfter = retryAfterMs(conn)-                _responseCode.value = code--                val bytes = try {-                    val stream = if (code >= 400) conn.errorStream ?: conn.inputStream else conn.inputStream-                    stream?.readBytes() ?: ByteArray(0)-                } catch (_: Exception) {-                    ByteArray(0)-                } finally {-                    try { lastConn.inputStream?.close() } catch (_: Exception) {}-                    try { lastConn.errorStream?.close() } catch (_: Exception) {}-                    lastConn.disconnect()-                }--                val isSuccessful = code in 200..299-                val errStr = if (!isSuccessful) {-                    responseMessage.ifEmpty { "Error $code" }-                } else ""--                val errBytes = if (!isSuccessful) bytes else ByteArray(0)-                val respBytes = if (isSuccessful) bytes else ByteArray(0)--                result = Attempt(-                    PlayResponse(-                        responseBytes = respBytes,-                        errorBytes = errBytes,-                        errorString = errStr,-                        isSuccessful = isSuccessful,-                        code = code,-                        type = ct-                    ),-                    retryAfter,-                )+            RedirectFollower(+                ::openConnection,+                ::readResponseCode,+                ::readAttempt,+                ::closeQuietly,+            ).follow(url, method, headers, rawBody, contentType)+        } catch (expected: IOException) {+            networkFailure(expected)+        } catch (expected: IllegalStateException) {+            networkFailure(expected)+        } catch (expected: SecurityException) {+            networkFailure(expected)+        }+    }++    private fun networkFailure(e: Exception): Attempt {+        return Attempt(+            PlayResponse(+                isSuccessful = false,+                code = NETWORK_FAILURE_CODE,+                errorString = e.message ?: "Network error",+                errorBytes = ByteArray(0),+                responseBytes = ByteArray(0)+            ),+            0L,+        )+    }++    private fun readResponseCode(conn: HttpURLConnection): Int {+        return try {+            conn.responseCode+        } catch (expected: IOException) {+            conn.disconnect()+            throw expected+        }+    }++    private fun readAttempt(conn: HttpURLConnection, code: Int): Attempt {+        val ct = conn.getHeaderField("Content-Type")+        val responseMessage = readResponseMessage(conn)+        val retryAfter = retryAfterMs(conn)+        _responseCode.value = code++        val bytes = readBodyBytes(conn, code)+        closeQuietly(conn)++        val isSuccessful = code in HTTP_OK_MIN..HTTP_OK_MAX+        val errStr = if (!isSuccessful) {+            responseMessage.ifEmpty { "Error $code" }+        } else ""++        val errBytes = if (!isSuccessful) bytes else ByteArray(0)+        val respBytes = if (isSuccessful) bytes else ByteArray(0)++        return Attempt(+            PlayResponse(+                responseBytes = respBytes,+                errorBytes = errBytes,+                errorString = errStr,+                isSuccessful = isSuccessful,+                code = code,+                type = ct+            ),+            retryAfter,+        )+    }++    private fun readResponseMessage(conn: HttpURLConnection): String {+        return try {+            conn.responseMessage+        } catch (_: IOException) {+            ""+        } ?: ""+    }++    private fun readBodyBytes(conn: HttpURLConnection, code: Int): ByteArray {+        return try {+            val stream = if (code >= HTTP_ERROR_MIN) {+                conn.errorStream ?: conn.inputStream+            } else {+                conn.inputStream             }-            result-        } catch (e: Exception) {-            Attempt(-                PlayResponse(-                    isSuccessful = false,-                    code = -1,-                    errorString = e.message ?: "Network error",-                    errorBytes = ByteArray(0),-                    responseBytes = ByteArray(0)-                ),-                0L,-            )+            stream?.readBytes() ?: ByteArray(0)+        } catch (_: IOException) {+            ByteArray(0)+        }+    }++    private fun closeQuietly(conn: HttpURLConnection) {+        try {+            conn.inputStream?.close()+        } catch (_: IOException) {+        }+        try {+            conn.errorStream?.close()+        } catch (_: IOException) {         }+        conn.disconnect()     }      private fun openConnection(@@ -300,29 +318,52 @@ class PlayHttpClient : IHttpClient {             doOutput = bodyBytes != null         } -        // Set method, with reflection fallback for custom verbs+        setRequestMethod(conn, method)++        headers.forEach { (k, v) ->+            conn.setRequestProperty(k, v)+        }++        applyContentType(conn, method, bodyBytes, contentType)+        writeBody(conn, bodyBytes)++        return conn+    }++    // Set method, with reflection fallback for custom verbs+    private fun setRequestMethod(conn: HttpURLConnection, method: String) {         try {             conn.requestMethod = method         } catch (_: java.net.ProtocolException) {-            var clazz: Class<*>? = conn.javaClass-            var success = false-            while (clazz != null && !success) {-                try {-                    val f = clazz.getDeclaredField("method")-                    f.isAccessible = true-                    f.set(conn, method)-                    success = true-                } catch (_: Exception) {-                    clazz = clazz.superclass-                }-            }+            setMethodByReflection(conn, method)         }+    } -        headers.forEach { (k, v) ->-            conn.setRequestProperty(k, v)+    private fun setMethodByReflection(conn: HttpURL

Diff truncated.