Modern Apps git

← Modern-Apps.git

various fixes

Commit
6e0473a065e7c65a9bd82f79b2d46e1656c12731
Author
Vayun Mathur <[email protected]>
When
2026-08-03 19:28 UTC (4 months ago)
Parents
3179a6f

Diff

appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt b/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.ktindex 367501bdc1..e155f53fc1 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt@@ -9,7 +9,6 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue@@ -20,9 +19,13 @@ import androidx.lifecycle.viewmodel.compose.viewModel import com.vayunmathur.appstore.data.AppDatabase import com.vayunmathur.appstore.data.DB_NAME import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.UpdateCheckWorker import com.vayunmathur.appstore.ui.AppDetailPage-import com.vayunmathur.appstore.ui.InstalledPage-import com.vayunmathur.appstore.ui.ReposPage+import com.vayunmathur.appstore.ui.HomePage+import com.vayunmathur.appstore.ui.LibraryPage+import com.vayunmathur.appstore.ui.SearchPage+import com.vayunmathur.appstore.ui.SourcesPage+import com.vayunmathur.appstore.ui.TrustPage import com.vayunmathur.appstore.ui.UpdatesPage import com.vayunmathur.appstore.util.AppStoreViewModel import com.vayunmathur.appstore.util.AppStoreViewModelFactory@@ -32,8 +35,8 @@ import com.vayunmathur.library.room.buildDatabase import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.IconDownload import com.vayunmathur.library.ui.IconHome-import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.ui.IconPackage+import com.vayunmathur.library.ui.IconSearch import com.vayunmathur.library.util.BottomBarItem import com.vayunmathur.library.util.BottomNavBar import com.vayunmathur.library.util.MainNavigation@@ -46,9 +49,11 @@ import kotlinx.serialization.Serializable  class MainActivity : ComponentActivity() { -    private val readyState = mutableStateOf(false)     private var factoryState by mutableStateOf<AppStoreViewModelFactory?>(null)-    private var externalPkg: String? = null++    /** Package named by a `market://` or listing URL we were launched with. */+    private var externalPkg by mutableStateOf<String?>(null)+     private var vmRef: AppStoreViewModel? = null      override fun onCreate(savedInstanceState: Bundle?) {@@ -57,6 +62,7 @@ class MainActivity : ComponentActivity() {         // + ISRG X1/X2 (F-Droid) + DigiCert G2/G3 (GitHub). Covers all appstore hosts without full system ~140 roots.         NetworkClient.init(this, TrustBundle.STANDARD)         enableEdgeToEdge()+        UpdateCheckWorker.schedule(this)          lifecycleScope.launch(Dispatchers.IO) {             val db = buildDatabase<AppDatabase>(dbName = DB_NAME, migrations = AppDatabase.migrations)@@ -64,40 +70,18 @@ class MainActivity : ComponentActivity() {             withContext(Dispatchers.Main) {                 factoryState = factory                 handleIntentUrl(intent)-                readyState.value = true             }         }          setContent {             DynamicTheme {-                Box(Modifier.fillMaxSize()) {-                    if (!readyState.value || factoryState == null) {-                        Box(Modifier.fillMaxSize())-                    } else {-                        val vm: AppStoreViewModel = viewModel(factory = factoryState!!)-                        vmRef = vm-                        LaunchedEffect(externalPkg) {-                            externalPkg?.let { pkg ->-                                val cached = vm.cachedApps.value.find { it.packageName == pkg }-                                if (cached != null) {-                                    vm.selectApp(-                                        UnifiedApp(-                                            packageName = cached.packageName,-                                            source = try { com.vayunmathur.appstore.data.AppSource.valueOf(cached.source) } catch (_: Exception) { com.vayunmathur.appstore.data.AppSource.FDROID },-                                            name = cached.name,-                                            summary = cached.summary,-                                            description = cached.description,-                                            iconUrl = cached.iconUrl,-                                            versionName = cached.versionName,-                                            versionCode = cached.versionCode,-                                            apkUrl = cached.apkUrl-                                        )-                                    )-                                }-                            }-                        }-                        AppRoot(vm, onAppClick = { app -> vm.selectApp(app) })-                    }+                val factory = factoryState+                if (factory == null) {+                    Box(Modifier.fillMaxSize())+                } else {+                    val vm: AppStoreViewModel = viewModel(factory = factory)+                    vmRef = vm+                    AppRoot(vm, externalPkg) { externalPkg = null }                 }             }         }@@ -105,7 +89,7 @@ class MainActivity : ComponentActivity() {      override fun onResume() {         super.onResume()-        // Refresh installed after uninstall or install from system dialog+        // Catch installs and uninstalls that completed in the system dialog.         vmRef?.refreshInstalled()     } @@ -115,85 +99,118 @@ class MainActivity : ComponentActivity() {     }      private fun handleIntentUrl(intent: Intent?) {-        intent ?: return-        val data = intent.dataString ?: return+        val data = intent?.dataString ?: return         val pkg = when {-            data.startsWith("market://") -> Regex("[?&]id=([^&]+)").find(data)?.groupValues?.get(1)-            data.contains("play.google.com") -> Regex("[?&]id=([^&]+)").find(data)?.groupValues?.get(1)+            data.startsWith("market://") -> ID_PARAM.find(data)?.groupValues?.get(1)+            data.contains("play.google.com") -> ID_PARAM.find(data)?.groupValues?.get(1)             data.contains("f-droid.org") -> data.substringAfterLast('/').substringBefore('?')             else -> null         }-        if (pkg != null) externalPkg = pkg+        if (!pkg.isNullOrBlank()) externalPkg = pkg+    }++    private companion object {+        val ID_PARAM = Regex("[?&]id=([^&]+)")     } }  @Serializable sealed interface Route : NavKey {-    @Serializable data object Browse : Route-    @Serializable data object Installed : Route+    @Serializable data object Home : Route+    @Serializable data object Search : Route     @Serializable data object Updates : Route-    @Serializable data object Repos : Route+    @Serializable data object Library : Route+    @Serializable data object Sources : Route+    @Serializable data object Trust : Route     @Serializable data object Detail : Route } +/**+ * Four tabs and three pushed screens.+ *+ * Sources and the trust explainer used to be a tab each, which spent a quarter of the+ * bottom bar on screens opened perhaps once. They are now behind the gear on the home+ * bar, and the freed slot went to search — which was previously a text field wedged above+ * the browse list, so browsing and searching fought over the same screen.+ */ @Composable private fun AppRoot(     viewModel: AppStoreViewModel,-    onAppClick: (UnifiedApp) -> Unit+    externalPackage: String?,+    onExternalPackageHandled: () -> Unit, ) {-    val selected by viewModel.selectedApp.collectAsState()-    val initial: Route = if (selected != null) Route.Detail else Route.Browse-    val backStack = rememberNavBackStack<Route>(initial)+    val backStack = rememberNavBackStack<Route>(Route.Home)     val current = backStack.last() -    LaunchedEffect(selected) {-        if (selected != null && current !is Route.Detail) {-            backStack.add(Route.Detail)-        }+    LaunchedEffect(externalPackage) {+        val pkg = externalPackage ?: return@LaunchedEffect+        viewModel.selectPackage(pkg)+        if (backStack.last() !is Route.Detail) backStack.add(Route.Detail)+        onExternalPackageHandled()+    }++    fun openDetail(app: UnifiedApp) {+        viewModel.selectApp(app)+        if (backStack.last() !is Route.Detail) backStack.add(Route.Detail)     }      MainNavigation(         backStack,         bottomBar = {-            if (current !is Route.Detail) {+            if (current is Route.Home || current is Route.Search ||+                current is Route.Updates || current is Route.Library+            ) {                 BottomNavBar(                     backStack,                     listOf(-                        BottomBarItem(stringResource(R.string.nav_browse), Route.Browse) { IconHome() },-                        BottomBarItem(stringResource(R.string.nav_installed), Route.Installed) { IconPackage() },+                        BottomBarItem(stringResource(R.string.nav_home), Route.Home) { IconHome() },+                        BottomBarItem(stringResource(R.string.nav_search), Route.Search) { IconSearch() },                         BottomBarItem(stringResource(R.string.nav_updates), Route.Updates) { IconDownload() },-                        BottomBarItem(stringResource(R.string.nav_sources), Route.Repos) { IconSettings() },+                        BottomBarItem(stringResource(R.string.nav_library), Route.Library) { IconPackage() },                     ),-                    current+                    current,                 )             }         }     ) {-        entry<Route.Browse> {-            com.vayunmathur.appstore.ui.SearchAndBrowsePage(viewModel = viewModel, onAppClick = { app ->-                onAppClick(app)-                backStack.add(Route.Detail)-            })+        entry<Route.Home> {+            HomePage(+                viewModel = viewModel,+                onAppClick = ::openDetail,+                onOpenUpdates = { backStack.reset(Route.Updates) },+                onOpenSources = { backStack.add(Route.Sources) },+            )         }-        entry<Route.Installed> {-            InstalledPage(viewModel = viewModel, onAppClick = { app ->-                viewModel.selectApp(app)-                backStack.add(Route.Detail)-            })+        entry<Route.Search> {+            SearchPage(viewModel = viewModel, onAppClick = ::openDetail)         }         entry<Route.Updates> {-            UpdatesPage(viewModel = viewModel, onAppClick = { app ->-                viewModel.selectApp(app)-                backStack.add(Route.Detail)-            })+            UpdatesPage(viewModel = viewModel, onAppClick = ::openDetail)         }-        entry<Route.Repos> {-            ReposPage(viewModel = viewModel)+        entry<Route.Library> {+            LibraryPage(viewModel = viewModel, onAppClick = ::openDetail)+        }+        entry<Route.Sources> {+            SourcesPage(+                viewModel = viewModel,+                onBack = { backStack.pop() },+                onOpenTrust = { backStack.add(Route.Trust) },+            )+        }+        entry<Route.Trust> {+            TrustPage(+                ownSigningCertificates = viewModel.ownSigningCertificates,+                onBack = { backStack.pop() },+            )         }         entry<Route.Detail> {             AppDetailPage(                 viewModel = viewModel,-                onBack = { backStack.pop() },+                onBack = {+                    backStack.pop()+                    viewModel.clearSelection()+                },+                onOpenTrust = { backStack.add(Route.Trust) },             )         }     }
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 62292b179c..f5d7e974ed 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt@@ -47,9 +47,31 @@ data class CachedAppEntity(     val apkSha256: String? = null,     val license: String? = null,     val website: String? = null,-    val sourceCode: String? = null+    val sourceCode: String? = null,+    /** Newline-joined listing screenshot URLs, in publication order. */+    val screenshots: String? = null,+    val featureGraphic: String? = null,+    val rating: Float? = null,+    val ratingCount: Long = 0L,+    val installs: Long = 0L,+    val updatedOn: String? = null,+    val contentRating: String? = null,+    val containsAds: Boolean = false,+    /** Comma-joined F-Droid anti-feature identifiers. */+    val antiFeatures: String? = null,+    val whatsNew: String? = null,+    val addedTimestamp: Long = 0L, ) +/** URLs never contain a newline, so this survives values a comma would split apart. */+private const val LIST_SEP = "\n"++private fun List<String>.packList(): String? =+    filter { it.isNotBlank() }.joinToString(LIST_SEP).ifBlank { null }++private fun String?.unpackList(): List<String> =+    this?.split(LIST_SEP)?.filter { it.isNotBlank() } ?: emptyList()+ fun UnifiedApp.toEntity(): CachedAppEntity = CachedAppEntity(     packageName = packageName,     source = source.name,@@ -71,6 +93,17 @@ fun UnifiedApp.toEntity(): CachedAppEntity = CachedAppEntity(     license = license,     website = website,     sourceCode = sourceCode,+    screenshots = screenshots.packList(),+    featureGraphic = featureGraphic,+    rating = rating,+    ratingCount = ratingCount,+    installs = installs,+    updatedOn = updatedOn,+    contentRating = contentRating,+    containsAds = containsAds,+    antiFeatures = antiFeatures.packList(),+    whatsNew = whatsNew,+    addedTimestamp = addedTimestamp, )  fun CachedAppEntity.toUnifiedApp(): UnifiedApp = UnifiedApp(@@ -94,6 +127,17 @@ fun CachedAppEntity.toUnifiedApp(): UnifiedApp = UnifiedApp(     license = license,     website = website,     sourceCode = sourceCode,+    screenshots = screenshots.unpackList(),+    featureGraphic = featureGraphic,+    rating = rating,+    ratingCount = ratingCount,+    installs = installs,+    updatedOn = updatedOn,+    contentRating = contentRating,+    containsAds = containsAds,+    antiFeatures = antiFeatures.unpackList(),+    whatsNew = whatsNew,+    addedTimestamp = addedTimestamp, )  /**@@ -142,11 +186,54 @@ interface RepoDao {     suspend fun deleteByUrl(url: String) } +/**+ * The three columns every catalogue-wide question needs, without dragging each app's+ * description and screenshot list into memory with them.+ *+ * The store caches the whole F-Droid index — several thousand rows — so the old habit of+ * collecting `allFlow()` and filtering in Kotlin meant holding the entire catalogue live+ * just to answer "is this package known, and is it newer than what's installed".+ */+data class PackageIndexRow(+    val packageName: String,+    val source: String,+    val versionCode: Long,+)+ @Dao interface CachedAppDao {     @Query("SELECT * FROM CachedAppEntity ORDER BY name ASC")     fun allFlow(): Flow<List<CachedAppEntity>> +    /** Package → source/version, for attribution and update detection. */+    @Query("SELECT packageName, source, versionCode FROM CachedAppEntity")+    fun indexFlow(): Flow<List<PackageIndexRow>>++    @Query("SELECT * FROM CachedAppEntity WHERE source = :source ORDER BY name ASC")+    fun bySourceFlow(source: String): Flow<List<CachedAppEntity>>++    @Query("SELECT * FROM CachedAppEntity ORDER BY lastUpdated DESC LIMIT :limit")+    suspend fun recentlyUpdated(limit: Int): List<CachedAppEntity>++    @Query(+        "SELECT * FROM CachedAppEntity WHERE ',' || categories || ',' LIKE '%,' || :category || ',%' " ++            "ORDER BY lastUpdated DESC LIMIT :limit"+    )+    suspend fun byCategory(category: String, limit: Int): List<CachedAppEntity>++    @Query("SELECT categories FROM CachedAppEntity WHERE categories != ''")+    suspend fun allCategoryStrings(): List<String>++    @Query("SELECT * FROM CachedAppEntity WHERE packageName IN (:packages)")+    suspend fun byPackages(packages: List<String>): List<CachedAppEntity>++    @Query(+        "SELECT * FROM CachedAppEntity WHERE " ++            "packageName LIKE '%' || :q || '%' OR name LIKE '%' || :q || '%' " ++            "OR summary LIKE '%' || :q || '%' ORDER BY name ASC LIMIT :limit"+    )+    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")     fun searchFlow(q: String): Flow<List<CachedAppEntity>> @@ -178,7 +265,7 @@ interface CachedAppDao {  @Database(     entities = [RepoEntity::class, CachedAppEntity::class, PinnedStampEntity::class],-    version = 4,+    version = 5,     exportSchema = false ) abstract class AppDatabase : RoomDatabase() {@@ -217,6 +304,23 @@ abstract class AppDatabase : RoomDatabase() {                             "firstSeen INTEGER NOT NULL)"                     )                 }+            },+            object : Migration(4, 5) {+                override fun migrate(db: SupportSQLiteDatabase) {+                    // Listing media and store metadata. All nullable or defaulted, so+                    // existing rows stay usable and fill in on the next sync.+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN screenshots TEXT")+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN featureGraphic TEXT")+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN rating REAL")+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN ratingCount INTEGER NOT NULL DEFAULT 0")+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN installs INTEGER NOT NULL DEFAULT 0")+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN updatedOn TEXT")+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN contentRating TEXT")+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN containsAds INTEGER NOT NULL DEFAULT 0")+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN antiFeatures TEXT")+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN whatsNew TEXT")+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN addedTimestamp INTEGER NOT NULL DEFAULT 0")+                }             }         )     }
appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.ktindex c52a54a31e..29ea774774 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt@@ -30,9 +30,26 @@ data class UnifiedApp(     val antiFeatures: List<String> = emptyList(),     val repoUrl: String? = null,     val offerType: Int = 0,-    val rating: Float? = null,     val containsSplit: Boolean = false,     val isFree: Boolean = true,+    /** Listing screenshots, in the order the source published them. */+    val screenshots: List<String> = emptyList(),+    /** Wide header image, where the source publishes one. */+    val featureGraphic: String? = null,+    /** Average star rating, 0..5. Null when the source doesn't publish one. */+    val rating: Float? = null,+    /** How many ratings [rating] is an average of, 0 when unknown. */+    val ratingCount: Long = 0L,+    /** Install count as the source reports it, 0 when unknown. */+    val installs: Long = 0L,+    /** Human-readable release date from the source, e.g. "Jul 28, 2026". */+    val updatedOn: String? = null,+    /** Age rating label, e.g. "Everyone" / "PEGI 3". */+    val contentRating: String? = null,+    val privacyPolicyUrl: String? = null,+    val containsAds: Boolean = false,+    /** Permission names the listing declares, before install. */+    val permissions: List<String> = emptyList(),     /**      * Lowercase-hex SHA-256 fingerprints of the certificates the publisher says this      * APK is signed with, from a source we authenticated (a JAR-signed F-Droid index).@@ -41,14 +58,19 @@ data class UnifiedApp(     val expectedSigners: List<String> = emptyList(),     /** Lowercase-hex SHA-256 of the APK itself, when the source publishes one. */     val apkSha256: String? = null,-)+) {+    /** The single best image to head the detail page with. */+    val heroImage: String? get() = featureGraphic ?: screenshots.firstOrNull()+}  data class InstalledInfo(     val packageName: String,     val name: String,     val versionName: String?,     val versionCode: Long,-    val enabled: Boolean = true+    val enabled: Boolean = true,+    /** When the package was last updated on this device, ms since epoch. */+    val lastUpdateTime: Long = 0L, )  /**
appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.ktindex 6e99f29cf4..4b16c29ba8 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.kt@@ -1,40 +1,27 @@ package com.vayunmathur.appstore.data  /**- * Generic abstraction for any app provider (F-Droid base repo, Play Store via Aurora anonymous).- * App registers 2 providers in order: fdroid base repo + play store.- * Installed presence check: F-Droid first -> Play Store -> if none, hide app from list.+ * Rules that apply to every listing, whichever source produced it.+ *+ * This used to be an interface that each source implemented — `fetchAll`, `search`,+ * `isPresent`, `getDetails` — with the ViewModel picking between three implementations at+ * every call site. All reads now go through [CatalogRepository] (offline) or+ * [com.vayunmathur.appstore.data.play.PlayRepository] (live), so the sources are left with+ * one job each: fetch a catalogue and write it to the cache table. What survived is the+ * part that was genuinely shared.  */-interface AppProvider {-    val id: String-    val name: String-    val source: AppSource--    /** Full catalog — must pre-filter targetSdk < MIN_TARGET_SDK. */-    suspend fun fetchAll(): List<UnifiedApp>--    /** Search within this provider. */-    suspend fun search(query: String): List<UnifiedApp>--    /** Presence check for installed filtering. */-    suspend fun isPresent(packageName: String): Boolean--    /** Detailed entry or null. */-    suspend fun getDetails(packageName: String): UnifiedApp?--    companion object {-        const val MIN_TARGET_SDK = 35--        fun filterTargetSdk(apps: List<UnifiedApp>): List<UnifiedApp> {-            return apps.filter { app -> app.targetSdk == null || app.targetSdk >= MIN_TARGET_SDK }-        }--        /** Resolve source for a package using ordered providers: fdroid first, then play. Returns null if absent in all. */-        suspend fun resolveSource(packageName: String, providers: List<AppProvider>): AppSource? {-            for (provider in providers) {-                if (provider.isPresent(packageName)) return provider.source-            }-            return null-        }-    }+object AppProvider {++    /**+     * The oldest Android an app may be built for and still be listed.+     *+     * Enforced twice: here, against the target SDK the source *claims*, and again at+     * install time against the manifest actually downloaded (see+     * [com.vayunmathur.appstore.data.security.InstallVerifier]), because a source may+     * claim nothing at all.+     */+    const val MIN_TARGET_SDK = 35++    fun filterTargetSdk(apps: List<UnifiedApp>): List<UnifiedApp> =+        apps.filter { app -> app.targetSdk == null || app.targetSdk >= MIN_TARGET_SDK } }
appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.ktnew file mode 100644index 0000000000..4d8e5fe507--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt@@ -0,0 +1,180 @@+package com.vayunmathur.appstore.data++import android.content.Context+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.withContext++/** Which source a sync run is currently working on, for a progress line. */+enum class SyncStep { FDROID, MODERN_APPS }++/** What one sync run managed to do, per source. */+data class SyncReport(+    val fdroidCount: Int? = null,+    val fdroidSkipped: Int = 0,+    val modernCount: Int? = null,+) {+    val anyFailed: Boolean get() = fdroidCount == null || modernCount == null+}++/**+ * The offline catalogue: the F-Droid index and the Modern Apps release list, as cached in+ * Room, plus the sync that refreshes them.+ *+ * Play is deliberately absent — it has no downloadable catalogue and is queried live (see+ * [com.vayunmathur.appstore.data.play.PlayRepository]). What lives here is everything the+ * store can answer without a network.+ *+ * Queries are targeted rather than "load every row and filter in Kotlin". The F-Droid+ * index is several thousand apps with descriptions and screenshot lists attached, and the+ * browse screen only ever shows a screenful of them.+ */+class CatalogRepository(+    context: Context,+    private val db: AppDatabase,+    scope: CoroutineScope,+) {+    private val appContext = context.applicationContext+    private val fdroidProvider = FDroidAppProvider(db, appContext)+    private val modernProvider = ModernAppsProvider(appContext)++    val repos: StateFlow<List<RepoEntity>> =+        db.repoDao().allFlow().stateIn(scope, SharingStarted.Eagerly, emptyList())++    /**+     * Package → what the catalogue knows about it, without the payload.+     *+     * Backs both source attribution for installed apps and the F-Droid/Modern Apps side+     * of the update check, neither of which needs a single description.+     */+    val packageIndex: StateFlow<Map<String, PackageIndexRow>> = db.cachedAppDao().indexFlow()+        .map { rows -> rows.associateBy { it.packageName } }+        .stateIn(scope, SharingStarted.Eagerly, emptyMap())++    /** This repo's own apps. Small, always shown in full, so it stays a live flow. */+    val modernApps: StateFlow<List<UnifiedApp>> =+        db.cachedAppDao().bySourceFlow(AppSource.MODERN_APPS.name)+            .map { rows -> rows.map { it.toUnifiedApp() } }+            .stateIn(scope, SharingStarted.Eagerly, emptyList())++    fun sourceOf(packageName: String): AppSource? =+        packageIndex.value[packageName]?.source?.let {+            runCatching { AppSource.valueOf(it) }.getOrNull()+        }++    /** F-Droid's most recently published builds — the browse screen's "New and updated". */+    suspend fun recentlyUpdated(limit: Int = 30): List<UnifiedApp> = withContext(Dispatchers.IO) {+        runCatching { db.cachedAppDao().recentlyUpdated(limit).map { it.toUnifiedApp() } }+            .getOrDefault(emptyList())+    }++    suspend fun byCategory(category: String, limit: Int = 60): List<UnifiedApp> =+        withContext(Dispatchers.IO) {+            runCatching { db.cachedAppDao().byCategory(category, limit).map { it.toUnifiedApp() } }+                .getOrDefault(emptyList())+        }++    /** Categories present in the catalogue, most-populated first. */+    suspend fun categories(): List<String> = withContext(Dispatchers.IO) {+        runCatching {+            db.cachedAppDao().allCategoryStrings()+                .flatMap { it.split(",") }+                .map { it.trim() }+                .filter { it.isNotBlank() }+                .groupingBy { it }+                .eachCount()+                .entries+                .sortedWith(compareByDescending<Map.Entry<String, Int>> { it.value }.thenBy { it.key })+                .map { it.key }+        }.getOrDefault(emptyList())+    }++    suspend fun searchLocal(query: String, limit: Int = 60): List<UnifiedApp> =+        withContext(Dispatchers.IO) {+            if (query.isBlank()) return@withContext emptyList()+            runCatching { db.cachedAppDao().searchAll(query, limit).map { it.toUnifiedApp() } }+                .getOrDefault(emptyList())+        }++    suspend fun byPackage(packageName: String): UnifiedApp? = withContext(Dispatchers.IO) {+        runCatching { db.cachedAppDao().byPackage(packageName)?.toUnifiedApp() }.getOrNull()+    }++    suspend fun byPackages(packages: List<String>): List<UnifiedApp> = withContext(Dispatchers.IO) {+        if (packages.isEmpty()) return@withContext emptyList()+        runCatching {+            packages.chunked(SQLITE_VARIABLE_LIMIT)+                .flatMap { db.cachedAppDao().byPackages(it) }+                .map { it.toUnifiedApp() }+        }.getOrDefault(emptyList())+    }++    /** Rows for packages that are installed but older than what the catalogue offers. */+    suspend fun updatesFor(installed: List<InstalledInfo>): List<UnifiedApp> {+        val index = packageIndex.value+        val stale = installed.filter { inst ->+            val known = index[inst.packageName] ?: return@filter false+            known.versionCode > inst.versionCode+        }.map { it.packageName }+        return byPackages(stale)+    }++    /**+     * Refresh both offline sources.+     *+     * Order matters: `packageName` is the cache table's primary key, so when a package is+     * published by both sources the *later* upsert wins the row. Modern Apps goes last —+     * every app in this repo is also on F-Droid, and the copy signed with this store's own+     * key is the one that can be verified end to end.+     *+     * Each source is independent: one failing leaves the other's rows updated and its own+     * previous rows untouched, rather than aborting the whole run.+     */+    suspend fun sync(onProgress: (SyncStep) -> Unit = {}): SyncReport = withContext(Dispatchers.IO) {+        ensureDefaultRepos()++        onProgress(SyncStep.FDROID)+        val fdroid = runCatching { fdroidProvider.syncIntoDb() }.getOrNull()++        onProgress(SyncStep.MODERN_APPS)+        val modern = runCatching { modernProvider.syncIntoDb(db) }.getOrNull()++        SyncReport(+            fdroidCount = fdroid,+            fdroidSkipped = fdroidProvider.lastFilteredOut,+            modernCount = modern,+        )+    }++    /**+     * There is exactly one supported F-Droid repository and it cannot be changed, so this+     * both seeds it and prunes anything else a previous version may have stored.+     */+    private suspend fun ensureDefaultRepos() {+        val existing = db.repoDao().all()+        existing.filter { it.url != DefaultRepos.FDROID_MAIN && it.url != ModernAppsRepo.REPO_KEY }+            .forEach {+                db.repoDao().deleteByUrl(it.url)+                db.cachedAppDao().deleteByRepo(it.url)+            }+        if (existing.none { it.url == DefaultRepos.FDROID_MAIN }) {+            db.repoDao().upsert(+                RepoEntity(+                    url = DefaultRepos.FDROID_MAIN,+                    name = "F-Droid",+                    enabled = true,+                    fingerprint = FDroidRepository.FDROID_SIGNING_CERT_SHA256,+                )+            )+        }+    }++    private companion object {+        /** SQLite's default host-parameter ceiling; `IN (:packages)` binds one each. */+        const val SQLITE_VARIABLE_LIMIT = 900+    }+}
appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.ktindex 178ac873f4..2fa3295c78 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt@@ -16,58 +16,19 @@ import kotlinx.coroutines.withContext  * Both gates fail closed: if the signed index or the verification feed can't be  * fetched and checked, the sync throws and the previous catalogue is left untouched  * rather than being replaced with unverified entries.+ *+ * Reads go through [CatalogRepository], which queries the cache table this writes.  */ class FDroidAppProvider(     private val db: AppDatabase,-    private val appContext: Context-) : AppProvider {-    override val id = "fdroid"-    override val name = "F-Droid"-    override val source = AppSource.FDROID--    @Volatile var cachedPackageNames: Set<String> = emptySet()+    private val appContext: Context,+) {      /** Number of packages dropped by the reproducibility gate on the last sync. */-    @Volatile var lastFilteredOut: Int = 0+    @Volatile+    var lastFilteredOut: Int = 0         private set -    override suspend fun fetchAll(): List<UnifiedApp> = withContext(Dispatchers.IO) {-        val result = fetchVerifiedIndex()-        cachedPackageNames = result.apps.map { it.packageName }.toSet()-        result.apps-    }--    override suspend fun search(query: String): List<UnifiedApp> = withContext(Dispatchers.IO) {-        if (query.isBlank()) return@withContext emptyList()-        // Search the synced cache; re-downloading a 54 MB index per keystroke is not an option.-        try {-            db.cachedAppDao().search(AppSource.FDROID.name, query).map { it.toUnifiedApp() }-        } catch (_: Exception) { emptyList() }-    }--    override suspend fun isPresent(packageName: String): Boolean = withContext(Dispatchers.IO) {-        if (cachedPackageNames.contains(packageName)) return@withContext true-        try {-            val entity = db.cachedAppDao().byPackage(packageName) ?: return@withContext false-            if (entity.source != AppSource.FDROID.name) return@withContext false-            if (entity.targetSdk != null && entity.targetSdk < AppProvider.MIN_TARGET_SDK) {-                return@withContext false-            }-            true-        } catch (_: Exception) { false }-    }--    override suspend fun getDetails(packageName: String): UnifiedApp? = withContext(Dispatchers.IO) {-        try {-            val entity = db.cachedAppDao().byPackage(packageName) ?: return@withContext null-            if (entity.source != AppSource.FDROID.name) return@withContext null-            if (entity.targetSdk != null && entity.targetSdk < AppProvider.MIN_TARGET_SDK) {-                return@withContext null-            }-            entity.toUnifiedApp()-        } catch (_: Exception) { null }-    }-     /**      * Refresh from f-droid.org and replace this source's rows. Throws if either the index      * signature or the reproducibility feed can't be obtained — the caller surfaces that@@ -84,7 +45,6 @@ class FDroidAppProvider(                 lastSync = System.currentTimeMillis(),             )         )-        cachedPackageNames = result.apps.map { it.packageName }.toSet()         result.apps.size     } 
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 829878eb78..bea8a7ba85 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt@@ -194,6 +194,9 @@ object FDroidRepository {         var added: Long = 0L         var lastUpdated: Long = 0L         var iconUrl: String? = null+        var featureGraphic: String? = null+        var screenshots: List<String> = emptyList()+        var antiFeatures: List<String> = emptyList()         var latestAdded: Long = -1L         var latestFileName: String? = null         var latestSize: Long = 0L@@ -227,6 +230,14 @@ object FDroidRepository {                                 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()                         }                     }@@ -340,6 +351,9 @@ object FDroidRepository {             summary = metaSummary ?: "",             description = metaDesc ?: "",             iconUrl = iconUrl,+            featureGraphic = featureGraphic,+            screenshots = screenshots,+            antiFeatures = antiFeatures,             author = author,             categories = categories,             versionName = latestVersionName,@@ -414,6 +428,15 @@ object FDroidRepository {                     summary = meta.summary ?: "",                     description = meta.description ?: "",                     iconUrl = meta.icon?.let { "$repoBase/icons/$it" },+                    // v1 localised media is stored per-locale under the package's own+                    // directory, so the locale the names came from is part of the path.+                    featureGraphic = meta.featureGraphic?.let {+                        "$repoBase/$pkg/${meta.localeDir}/$it"+                    },+                    screenshots = meta.phoneScreenshots.map {+                        "$repoBase/$pkg/${meta.localeDir}/phoneScreenshots/$it"+                    },+                    antiFeatures = meta.antiFeatures,                     author = meta.authorName,                     categories = meta.categories,                     versionName = latest?.versionName,@@ -448,7 +471,19 @@ object FDroidRepository {         val sourceCode: String?,         val license: String?,         val added: Long,-        val lastUpdated: Long+        val lastUpdated: Long,+        val antiFeatures: List<String> = emptyList(),+        val featureGraphic: String? = null,+        val phoneScreenshots: List<String> = emptyList(),+        /** Locale the media above came from; it is a path segment in v1. */+        val localeDir: String = "en-US",+    )++    /** The subset of a v1 `localized` block this store shows. */+    private data class V1Localized(+        val locale: String,+        val featureGraphic: String?,+        val phoneScreenshots: List<String>,     )      private data class V1PackageLatest(@@ -475,6 +510,8 @@ object FDroidRepository {         var license: String? = null         var added: Long = 0L         var lastUpdated: Long = 0L+        var antiFeatures: List<String> = emptyList()+        var localized: V1Localized? = null          reader.beginObject()         while (reader.hasNext()) {@@ -491,12 +528,67 @@ object FDroidRepository {                 "license" -> license = nextStringOrNull(reader)                 "added" -> added = nextLongOrNull(reader) ?: 0L                 "lastUpdated" -> lastUpdated = nextLongOrNull(reader) ?: 0L+                // v1 lists anti-features as plain strings, unlike v2's id -> reason map.+                "antiFeatures" -> antiFeatures = readStringArray(reader)+                "localized" -> localized = readV1Localized(reader)                 else -> reader.skipValue()             }         }         reader.endObject()         val pkg = packageName ?: return null-        return V1AppMeta(pkg, name, summary, description, icon, authorName, categories, webSite, sourceCode, license, added, lastUpdated)+        return V1AppMeta(+            pkg, name, summary, description, icon, authorName, categories, webSite,+            sourceCode, license, added, lastUpdated,+            antiFeatures = antiFeatures,+            featureGraphic = localized?.featureGraphic,+            phoneScreenshots = localized?.phoneScreenshots ?: emptyList(),+            localeDir = localized?.locale ?: "en-US",+        )+    }++    /**+     * v1 `localized`: `{ "en-US": { "phoneScreenshots": ["1.png"], "featureGraphic": … } }`.+     *+     * Takes the first locale that actually carries media rather than insisting on en-US,+     * since an app localised only into, say, German still has usable screenshots.+     */+    private fun readV1Localized(reader: JsonReader): V1Localized? {+        if (reader.peek() != JsonToken.BEGIN_OBJECT) {+            reader.skipValue()+            return null+        }+        var best: V1Localized? = null+        reader.beginObject()+        while (reader.hasNext()) {+            val locale = reader.nextName()+            if (reader.peek() != JsonToken.BEGIN_OBJECT) {+                reader.skipValue()+                continue+            }+            var feature: String? = null+            var shots: List<String> = emptyList()+            reader.beginObject()+            while (reader.hasNext()) {+                when (reader.nextName()) {+                    "featureGraphic" -> feature = nextStringOrNull(reader)+                    "phoneScreenshots" -> shots = readStringArray(reader)+                    else -> reader.skipValue()+                }+            }+            reader.endObject()+            val candidate = V1Localized(locale, feature, shots)+            val hasMedia = feature != null || shots.isNotEmpty()+            // en-US wins outright; otherwise the first locale with anything to show.+            if (hasMedia && (locale == "en-US" || best == null)) {+                best = candidate+                if (locale == "en-US") {+                    // Keep draining so the object closes cleanly.+                    while (reader.hasNext()) { reader.nextName(); reader.skipValue() }+                }+            }+        }+        reader.endObject()+        return best     }      private fun parseV1PackagesArray(@@ -631,6 +723,99 @@ object FDroidRepository {         }     } +    /**+     * 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() }
appstore/src/main/java/com/vayunmathur/appstore/data/InstalledAppsRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/InstalledAppsRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/InstalledAppsRepository.ktnew file mode 100644index 0000000000..850aafd6d0--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/InstalledAppsRepository.kt@@ -0,0 +1,64 @@+package com.vayunmathur.appstore.data++import android.content.Context+import android.content.pm.ApplicationInfo+import android.content.pm.PackageManager+import android.graphics.drawable.Drawable+import android.os.Build+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.withContext++/**+ * What is on the device, and which of the store's sources offers it.+ *+ * Published in two waves on purpose. The package list itself is one cheap PackageManager+ * sweep and goes out immediately; launcher icons cost a binder call and a bitmap decode+ * each, so several hundred of them arrive afterwards. Doing it the other way round is+ * what used to leave the Installed tab blank for ten seconds.+ */+class InstalledAppsRepository(private val context: Context) {++    private val _apps = MutableStateFlow<List<InstalledInfo>>(emptyList())+    val apps: StateFlow<List<InstalledInfo>> = _apps.asStateFlow()++    private val _icons = MutableStateFlow<Map<String, Drawable>>(emptyMap())+    val icons: StateFlow<Map<String, Drawable>> = _icons.asStateFlow()++    /** Re-read the device. Safe to call from `onResume`. */+    suspend fun refresh() = withContext(Dispatchers.IO) {+        val pm = context.packageManager+        val userApps = try {+            pm.getInstalledApplications(PackageManager.MATCH_ALL)+                .filter { (it.flags and ApplicationInfo.FLAG_SYSTEM) == 0 }+        } catch (_: Exception) {+            emptyList<ApplicationInfo>()+        }++        _apps.value = userApps.mapNotNull { ai -> pm.readInstalledInfo(ai) }+            .sortedBy { it.name.lowercase() }++        _icons.value = userApps.mapNotNull { ai ->+            try {+                ai.packageName to pm.getApplicationIcon(ai.packageName)+            } catch (_: Exception) {+                null+            }+        }.toMap()+    }++    private fun PackageManager.readInstalledInfo(ai: ApplicationInfo): InstalledInfo? = try {+        val pi = getPackageInfo(ai.packageName, 0)+        InstalledInfo(+            packageName = ai.packageName,+            name = getApplicationLabel(ai).toString(),+            versionName = pi.versionName,+            versionCode = if (Build.VERSION.SDK_INT >= 28) pi.longVersionCode else @Suppress("DEPRECATION") pi.versionCode.toLong(),+            lastUpdateTime = pi.lastUpdateTime,+        )+    } catch (_: Exception) {+        null+    }+}
appstore/src/main/java/com/vayunmathur/appstore/data/ModernAppsProvider.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/ModernAppsProvider.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/ModernAppsProvider.ktindex c50649052f..fcbba458b2 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/ModernAppsProvider.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/ModernAppsProvider.kt@@ -30,23 +30,14 @@ import java.net.URL  * index, a compromised GitHub account, or a hostile CDN can change which bytes are  * offered, but cannot produce bytes that will install: that needs the release signing  * key, which is the sole trust root here.+ *+ * Reads go through [CatalogRepository], which queries the cache table this writes.  */-class ModernAppsProvider(private val appContext: Context) : AppProvider {--    override val id = "modern-apps"-    override val name = "Modern Apps"-    override val source = AppSource.MODERN_APPS--    @Volatile-    var cachedPackageNames: Set<String> = emptySet()-        private set--    @Volatile-    private var cached: List<UnifiedApp> = emptyList()+class ModernAppsProvider(private val appContext: Context) {      private val json = Json { ignoreUnknownKeys = true; isLenient = true } -    override suspend fun fetchAll(): List<UnifiedApp> = withContext(Dispatchers.IO) {+    private suspend fun fetchAll(): List<UnifiedApp> = withContext(Dispatchers.IO) {         val release = json.decodeFromString(             GithubRelease.serializer(),             httpGetString(ModernAppsRepo.LATEST_RELEASE_API, accept = GITHUB_ACCEPT),@@ -57,10 +48,7 @@ class ModernAppsProvider(private val appContext: Context) : AppProvider {         } else {             fetchFromGitTree(release)         }-        val filtered = AppProvider.filterTargetSdk(apps).distinctBy { it.packageName }-        cached = filtered-        cachedPackageNames = filtered.map { it.packageName }.toSet()-        filtered+        AppProvider.filterTargetSdk(apps).distinctBy { it.packageName }     }      /** Preferred path: the release states its own contents. */@@ -182,22 +170,6 @@ class ModernAppsProvider(private val appContext: Context) : AppProvider {         lastUpdated = publishedAt,     ) -    override suspend fun search(query: String): List<UnifiedApp> {-        if (query.isBlank()) return emptyList()-        val q = query.lowercase()-        return cached.filter {-            it.name.lowercase().contains(q) ||-                it.packageName.lowercase().contains(q) ||-                it.summary.lowercase().contains(q)-        }-    }--    override suspend fun isPresent(packageName: String): Boolean =-        cachedPackageNames.contains(packageName)--    override suspend fun getDetails(packageName: String): UnifiedApp? =-        cached.find { it.packageName == packageName }-     /** Refresh from GitHub and replace this source's rows in the shared cache table. */     suspend fun syncIntoDb(db: AppDatabase): Int = withContext(Dispatchers.IO) {         val apps = fetchAll()@@ -206,15 +178,6 @@ class ModernAppsProvider(private val appContext: Context) : AppProvider {         apps.size     } -    /** Seed the in-memory view from previously cached rows so browse works offline. */-    fun primeFrom(entities: List<CachedAppEntity>) {-        val apps = entities-            .filter { it.source == AppSource.MODERN_APPS.name }-            .map { it.toUnifiedApp() }-        cached = apps-        cachedPackageNames = apps.map { it.packageName }.toSet()-    }-     private fun httpGetString(url: String, accept: String): String {         val conn = (URL(url).openConnection() as HttpURLConnection).apply {             connectTimeout = 20_000
appstore/src/main/java/com/vayunmathur/appstore/data/PlayStoreAppProvider.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/PlayStoreAppProvider.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/PlayStoreAppProvider.ktdeleted file mode 100644index ad93293a9d..0000000000--- a/appstore/src/main/java/com/vayunmathur/appstore/data/PlayStoreAppProvider.kt+++ /dev/null@@ -1,44 +0,0 @@-package com.vayunmathur.appstore.data--import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.withContext--class PlayStoreAppProvider : AppProvider {-    override val id = "playstore"-    override val name = "Play Store"-    override val source = AppSource.PLAYSTORE--    private val knownPackages = mutableSetOf<String>()--    override suspend fun fetchAll(): List<UnifiedApp> = withContext(Dispatchers.IO) {-        val charts = PlayStoreDataSource.topCharts()-        val filtered = AppProvider.filterTargetSdk(charts)-        knownPackages.addAll(filtered.map { it.packageName })-        filtered-    }--    override suspend fun search(query: String): List<UnifiedApp> = withContext(Dispatchers.IO) {-        if (query.isBlank()) return@withContext emptyList()-        val results = PlayStoreDataSource.search(query)-        val filtered = AppProvider.filterTargetSdk(results)-        knownPackages.addAll(filtered.map { it.packageName })-        filtered-    }--    override suspend fun isPresent(packageName: String): Boolean = withContext(Dispatchers.IO) {-        if (knownPackages.contains(packageName)) return@withContext true-        try {-            val details = PlayStoreDataSource.appDetails(packageName) ?: return@withContext false-            if (details.targetSdk != null && details.targetSdk < AppProvider.MIN_TARGET_SDK) return@withContext false-            knownPackages.add(packageName)-            true-        } catch (_: Exception) { false }-    }--    override suspend fun getDetails(packageName: String): UnifiedApp? = withContext(Dispatchers.IO) {-        try {-            val details = PlayStoreDataSource.appDetails(packageName) ?: return@withContext null-            if (details.targetSdk != null && details.targetSdk < AppProvider.MIN_TARGET_SDK) null else details-        } 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.ktnew file mode 100644index 0000000000..0d82dd8bdd--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt@@ -0,0 +1,176 @@+package com.vayunmathur.appstore.data++import android.Manifest+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.os.Build+import android.util.Log+import androidx.core.app.ActivityCompat+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat+import androidx.work.Constraints+import androidx.work.CoroutineWorker+import androidx.work.ExistingPeriodicWorkPolicy+import androidx.work.NetworkType+import androidx.work.PeriodicWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import com.vayunmathur.appstore.MainActivity+import com.vayunmathur.appstore.R+import com.vayunmathur.appstore.data.play.PlayRepository+import com.vayunmathur.library.room.buildDatabase+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import java.util.concurrent.TimeUnit++/**+ * Checks for updates in the background and says so once, quietly.+ *+ * The store used to require two manual taps — "Sync F-Droid", then "Check Play" — which+ * is not something anyone remembers to do, so an app installed here would sit on a stale+ * version indefinitely. This refreshes the offline catalogues, asks Play about the+ * packages neither of them lists, and posts a notification only when the set of available+ * updates has actually changed since the last notification.+ *+ * It deliberately does not install anything. Every install path in this store shows a+ * verification outcome and, on most devices, a system confirmation dialog; doing that+ * unattended would either bury the user in prompts or hide the outcome.+ */+class UpdateCheckWorker(+    private val context: Context,+    params: WorkerParameters,+) : CoroutineWorker(context, params) {++    override suspend fun doWork(): Result = try {+        val scope = CoroutineScope(SupervisorJob())+        val db = context.buildDatabase<AppDatabase>(+            dbName = DB_NAME,+            migrations = AppDatabase.migrations,+        )+        val catalog = CatalogRepository(context, db, scope)+        val installedRepo = InstalledAppsRepository(context)+        val play = PlayRepository(context)++        catalog.sync()+        installedRepo.refresh()+        play.restore()++        val installed = installedRepo.apps.value+        val fromCatalog = catalog.updatesFor(installed)++        // Only Play can answer for packages the offline catalogues have never heard of.+        val index = catalog.packageIndex.value+        val unknown = installed.filter { it.packageName !in index }.map { it.packageName }+        val remote = play.details(unknown).associateBy { it.packageName }+        val fromPlay = installed.mapNotNull { inst ->+            remote[inst.packageName]?.takeIf { it.versionCode > inst.versionCode }+        }++        val updates = (fromCatalog + fromPlay).distinctBy { it.packageName }+        notifyIfChanged(updates.map { it.packageName }.toSortedSet(), updates.size)++        scope.cancel()+        Result.success()+    } catch (e: Exception) {+        Log.w(TAG, "Update check failed", e)+        Result.retry()+    }++    /**+     * Notify only when the set of updatable packages differs from last time.+     *+     * Without this, a daily check on a phone with one perpetually-stale app would post the+     * same notification every day until the user turned notifications off.+     */+    private fun notifyIfChanged(packages: Set<String>, count: Int) {+        val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)+        val signature = packages.joinToString(",")+        if (prefs.getString(KEY_LAST_NOTIFIED, "") == signature) return+        prefs.edit().putString(KEY_LAST_NOTIFIED, signature).apply()++        if (count == 0) {+            NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)+            return+        }+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&+            ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=+            PackageManager.PERMISSION_GRANTED+        ) {+            return+        }++        createChannel()+        val open = PendingIntent.getActivity(+            context,+            0,+            Intent(context, MainActivity::class.java)+                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP),+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )+        val notification = NotificationCompat.Builder(context, CHANNEL_ID)+            .setSmallIcon(android.R.drawable.stat_sys_download_done)+            .setContentTitle(+                context.resources.getQuantityString(R.plurals.updates_count, count, count)+            )+            .setContentText(context.getString(R.string.updates_notification_body))+            .setContentIntent(open)+            .setAutoCancel(true)+            .setPriority(NotificationCompat.PRIORITY_LOW)+            .build()++        runCatching {+            NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, notification)+        }+    }++    private fun createChannel() {+        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return+        val manager = context.getSystemService(NotificationManager::class.java) ?: return+        manager.createNotificationChannel(+            NotificationChannel(+                CHANNEL_ID,+                context.getString(R.string.updates_channel_name),+                NotificationManager.IMPORTANCE_LOW,+            ).apply { description = context.getString(R.string.updates_channel_description) }+        )+    }++    companion object {+        private const val TAG = "UpdateCheckWorker"+        private const val CHANNEL_ID = "appstore-updates"+        private const val NOTIFICATION_ID = 4201+        private const val PREFS = "appstore-update-check"+        private const val KEY_LAST_NOTIFIED = "last_notified_packages"++        /**+         * Twelve hours, and no immediate run.+         *+         * A sync pulls F-Droid's reproducibility feed and signed index — tens of megabytes+         * — so kicking one off every time the activity starts would be a lot of somebody's+         * data allowance. `KEEP` leaves an already-scheduled chain alone, and the periodic+         * request only fires on an unmetered connection.+         */+        fun schedule(context: Context) {+            val request = PeriodicWorkRequestBuilder<UpdateCheckWorker>(12, TimeUnit.HOURS)+                .setConstraints(+                    Constraints.Builder()+                        .setRequiredNetworkType(NetworkType.UNMETERED)+                        .setRequiresBatteryNotLow(true)+                        .build()+                )+                .build()+            WorkManager.getInstance(context).enqueueUniquePeriodicWork(+                WORK_NAME,+                ExistingPeriodicWorkPolicy.KEEP,+                request,+            )+        }++        private const val WORK_NAME = "AppStoreUpdateCheck"+    }+}
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.ktnew file mode 100644index 0000000000..ba4d055815--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt@@ -0,0 +1,276 @@+package com.vayunmathur.appstore.data.installer++import android.content.Context+import android.util.Log+import com.vayunmathur.appstore.data.AppDatabase+import com.vayunmathur.appstore.data.AppSource+import com.vayunmathur.appstore.data.PinnedStampEntity+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.play.CertUtil+import com.vayunmathur.appstore.data.play.PlayRepository+import com.vayunmathur.appstore.data.security.InstallRequirement+import com.vayunmathur.appstore.data.security.VerificationResult+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.withContext+import java.io.File+import java.net.HttpURLConnection+import java.net.URL++/**+ * Where an install has got to.+ *+ * The old UI had a single `Float?` per package, which meant the whole verify-and-commit+ * tail — often several seconds on a large split install — showed as either "100%" or+ * nothing at all, and a rejected APK looked identical to a finished one.+ */+sealed interface InstallStage {+    data object Preparing : InstallStage+    data class Downloading(val fraction: Float) : InstallStage+    data object Verifying : InstallStage+    data object Installing : InstallStage++    /** The install is over and did not start. Cleared when the row is next touched. */+    data class Failed(val reason: String) : InstallStage+}++/**+ * Downloads, verifies and installs, for every source.+ *+ * Both paths end at the same place — [SessionInstaller.installSplits] with an+ * [InstallRequirement] describing what the bytes have to prove — but they get there+ * differently: F-Droid and Modern Apps publish a URL and a hash, while Play requires an+ * account, a purchase call and a delivery response that names the files.+ */+class InstallCoordinator(+    private val context: Context,+    private val db: AppDatabase,+    private val play: PlayRepository,+    private val ownSigningCertificates: () -> Set<String>,+) {+    private val sessionInstaller = SessionInstaller(context)+    private val playDownloader = PlayDownloader(context)++    private val _stages = MutableStateFlow<Map<String, InstallStage>>(emptyMap())+    val stages: StateFlow<Map<String, InstallStage>> = _stages.asStateFlow()++    /** Per-package result of the last install attempt's certificate/hash checks. */+    private val _verification = MutableStateFlow<Map<String, VerificationResult>>(emptyMap())+    val verification: StateFlow<Map<String, VerificationResult>> = _verification.asStateFlow()++    /** True while anything is downloading or installing. */+    fun isBusy(packageName: String): Boolean =+        _stages.value[packageName].let { it != null && it !is InstallStage.Failed }++    /**+     * Run one install to completion.+     *+     * Returns the outcome so a caller updating several apps in a row can wait for each+     * rather than poll a progress map, which is what the old "update all" did.+     */+    suspend fun install(app: UnifiedApp): SessionInstaller.Outcome {+        if (isBusy(app.packageName)) {+            return SessionInstaller.Outcome(false, VerificationResult.Rejected("already installing"))+        }+        stage(app.packageName, InstallStage.Preparing)+        return try {+            when (app.source) {+                AppSource.PLAYSTORE -> installFromPlay(app)+                else -> installFromUrl(app)+            }.also { outcome ->+                if (outcome.started) {+                    clear(app.packageName)+                } else {+                    stage(app.packageName, InstallStage.Failed(outcome.verification.shortReason()))+                }+                record(app.packageName, outcome.verification)+            }+        } 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"))+        }+    }++    /** Drop a terminal [InstallStage.Failed] marker, e.g. when the user retries. */+    fun dismissFailure(packageName: String) {+        if (_stages.value[packageName] is InstallStage.Failed) clear(packageName)+    }++    // --- Direct APK: Modern Apps and F-Droid ---------------------------------------++    private suspend fun installFromUrl(app: UnifiedApp): SessionInstaller.Outcome =+        withContext(Dispatchers.IO) {+            val apkUrl = app.apkUrl+                ?: return@withContext SessionInstaller.Outcome(+                    false, VerificationResult.Rejected("this source published no download")+                )++            val requirement = when (app.source) {+                // The trust root: whatever certificate this store is itself signed+                // with, read back from PackageManager rather than hardcoded.+                AppSource.MODERN_APPS -> InstallRequirement(+                    expectedPackage = app.packageName,+                    requiredSigners = ownSigningCertificates(),+                    expectedSha256 = app.apkSha256+                        ?.let { mapOf("${app.packageName}.apk" to it) } ?: emptyMap(),+                    signerOrigin = "this store",+                )+                else -> InstallRequirement(+                    expectedPackage = app.packageName,+                    requiredSigners = app.expectedSigners.toSet(),+                    expectedSha256 = app.apkSha256+                        ?.let { mapOf("${app.packageName}.apk" to it) } ?: emptyMap(),+                    signerOrigin = "F-Droid's signed app list",+                )+            }++            val file = File(context.cacheDir, "${app.packageName}.apk")+            download(apkUrl, file, app.sizeBytes) { fraction ->+                stage(app.packageName, InstallStage.Downloading(fraction))+            }++            stage(app.packageName, InstallStage.Verifying)+            sessionInstaller.installSplits(app.packageName, listOf(file), requirement, file.length())+        }++    private fun download(url: String, target: File, expectedSize: Long, onProgress: (Float) -> Unit) {+        val conn = (URL(url).openConnection() as HttpURLConnection).apply {+            connectTimeout = 20_000+            readTimeout = 60_000+            instanceFollowRedirects = true+        }+        try {+            val total = conn.contentLengthLong.takeIf { it > 0 } ?: expectedSize+            conn.inputStream.use { input ->+                target.outputStream().use { out ->+                    val buf = ByteArray(64 * 1024)+                    var downloaded = 0L+                    var read: Int+                    while (input.read(buf).also { read = it } != -1) {+                        out.write(buf, 0, read)+                        downloaded += read+                        if (total > 0) onProgress((downloaded.toFloat() / total).coerceIn(0f, 1f))+                    }+                }+            }+        } finally {+            conn.disconnect()+        }+    }++    // --- Play ----------------------------------------------------------------------++    private suspend fun installFromPlay(app: UnifiedApp): SessionInstaller.Outcome =+        withContext(Dispatchers.IO) {+            // The listing that got the user here may be a cluster entry with no version+            // code, and purchase() needs one that matches what Play will serve.+            val details = play.details(app.packageName) ?: app+            val versionCode = details.versionCode.takeIf { it > 0 } ?: app.versionCode+            val offerType = details.offerType++            // Key rotation: Play wants the certificate of the copy already on the device+            // so it can serve a delivery the installer will accept as an update.+            val certHash = runCatching {+                CertUtil.getEncodedCertificateHashes(context, app.packageName).lastOrNull()+            }.getOrNull()++            var files = purchase(app.packageName, versionCode, offerType, certHash)+            if (files.isEmpty()) throw java.io.IOException("Play returned no files to download")++            var downloaded = playDownloader.downloadFiles(app.packageName, versionCode, files) { f ->+                stage(app.packageName, InstallStage.Downloading(f))+            }++            // Delivery URLs are short-lived; one expiry is worth a second purchase call+            // rather than making the user tap install again.+            if (downloaded.exceptionOrNull() is PlayDownloader.ExpiredUrlException) {+                files = purchase(app.packageName, versionCode, offerType, certHash)+                downloaded = playDownloader.downloadFiles(app.packageName, versionCode, files) { f ->+                    stage(app.packageName, InstallStage.Downloading(f))+                }+            }+            val localFiles = downloaded.getOrThrow()++            stage(app.packageName, InstallStage.Verifying)++            // Everything Play can actually give us, all enforced:+            //  - per-split SHA-256 from the delivery response (PlayFile.sha256)+            //  - the expected signing certificate from AppDetails.certificateSet+            //  - the source stamp, pinned TOFU (survives Play App Signing)+            //  - continuity with the installed copy (InstallVerifier, always)+            val expectedHashes = files.mapNotNull { f ->+                val name = f.name.takeIf { it.isNotBlank() } ?: return@mapNotNull null+                f.sha256?.takeIf { it.isNotBlank() }?.let { name to it }+            }.toMap()++            val requirement = InstallRequirement(+                expectedPackage = app.packageName,+                requiredSigners = details.expectedSigners.toSet(),+                expectedSha256 = expectedHashes,+                signerOrigin = "Google",+                pinnedStamp = db.pinnedStampDao().byPackage(app.packageName)?.stampSha256,+            )++            sessionInstaller.installSplits(+                app.packageName, localFiles, requirement, localFiles.sumOf { it.length() }+            )+        }++    /** Retries once without the installed-copy certificate, which Play sometimes rejects. */+    private suspend fun purchase(+        packageName: String,+        versionCode: Long,+        offerType: Int,+        certHash: String?,+    ) = try {+        play.purchase(packageName, versionCode, offerType, certHash)+    } catch (e: Exception) {+        if (certHash == null) throw e+        play.purchase(packageName, versionCode, offerType, null)+    }++    // --- Bookkeeping ----------------------------------------------------------------++    /**+     * Surface the verdict, and persist a newly observed source stamp so the next update+     * for this package is pinned to it.+     */+    private suspend fun record(packageName: String, result: VerificationResult) {+        _verification.value = _verification.value + (packageName to result)+        val stamp = result.stamp ?: return+        runCatching {+            db.pinnedStampDao().upsert(+                PinnedStampEntity(+                    packageName = packageName,+                    stampSha256 = stamp,+                    firstSeen = System.currentTimeMillis(),+                )+            )+        }+    }++    private fun stage(packageName: String, stage: InstallStage) {+        _stages.value = _stages.value + (packageName to stage)+    }++    private fun clear(packageName: String) {+        _stages.value = _stages.value - packageName+    }++    private fun VerificationResult.shortReason(): String = when (this) {+        is VerificationResult.Rejected -> reason+        is VerificationResult.Unverified -> reason+        is VerificationResult.Verified -> "install did not start"+    }++    private companion object {+        const val TAG = "InstallCoordinator"+    }+}
appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayRepository.ktnew file mode 100644index 0000000000..82995a804f--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayRepository.kt@@ -0,0 +1,236 @@+package com.vayunmathur.appstore.data.play++import android.content.Context+import android.util.Log+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.longPreferencesKey+import androidx.datastore.preferences.core.stringPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import com.aurora.gplayapi.data.models.AuthData+import com.aurora.gplayapi.data.models.PlayFile+import com.aurora.gplayapi.helpers.AuthHelper+import com.vayunmathur.appstore.data.UnifiedApp+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext+import kotlinx.serialization.json.Json++private val Context.authDataStore by preferencesDataStore(name = "play_auth")+private val PLAY_AUTH_JSON_KEY = stringPreferencesKey("play_auth_json")+private val PLAY_AUTH_DISPENSED_AT_KEY = longPreferencesKey("play_auth_dispensed_at")++/**+ * How long a dispensed anonymous account is trusted before it is replaced.+ *+ * The dispenser hands out shared accounts that Google eventually invalidates,+ * and a dead one fails silently - Play calls just start erroring and the app+ * falls back to scraping. Cycling on age keeps that from being the way we find+ * out.+ */+private const val PLAY_AUTH_MAX_AGE_MS = 12L * 60 * 60 * 1000++sealed interface PlayAuthState {+    data object Idle : PlayAuthState+    data object Authenticating : PlayAuthState+    data class Authenticated(val authData: AuthData) : PlayAuthState+    data class Error(val message: String) : PlayAuthState+}++/**+ * Everything that needs a Play session, behind one object.+ *+ * This used to be spread across the ViewModel — the anonymous account, its persistence,+ * its expiry, the retry-once-on-a-dead-account dance, and every call site that had to+ * remember to use it. Keeping it here means a caller can ask for search results without+ * knowing that an account has to be dispensed first, and the "cycle a dead account and+ * try again" rule exists in exactly one place.+ */+class PlayRepository(private val context: Context) {++    private val anonAuthRepo = AnonymousAuthRepository()+    private val httpClient = PlayHttpClient()+    private val json = Json { ignoreUnknownKeys = true; isLenient = true }++    private val _authState = MutableStateFlow<PlayAuthState>(PlayAuthState.Idle)+    val authState: StateFlow<PlayAuthState> = _authState.asStateFlow()++    private var cachedAuthData: AuthData? = null++    /** When [cachedAuthData] was dispensed, for age-based cycling. */+    private var dispensedAt: Long = 0L++    /**+     * Serialises dispensing.+     *+     * Browse, the update check and an install can all discover a dead account within a+     * few milliseconds of each other; without this each would dispense its own, and the+     * last writer would win while the others' accounts leaked.+     */+    private val authMutex = Mutex()++    /** Reload a persisted account, if it is young enough and still alive. */+    suspend fun restore() {+        try {+            val prefs = context.authDataStore.data.first()+            val jsonStr = prefs[PLAY_AUTH_JSON_KEY]?.takeIf { it.isNotBlank() } ?: return+            val storedAt = prefs[PLAY_AUTH_DISPENSED_AT_KEY] ?: 0L+            if (System.currentTimeMillis() - storedAt > PLAY_AUTH_MAX_AGE_MS) {+                // Past its useful life; ensureAuth will dispense a new one rather than+                // spend a round-trip proving this is dead.+                invalidate()+                return+            }+            val authData = runCatching {+                json.decodeFromString(AuthData.serializer(), jsonStr)+            }.getOrNull() ?: return+            if (isValid(authData)) {+                cachedAuthData = authData+                dispensedAt = storedAt+                _authState.value = PlayAuthState.Authenticated(authData)+            } else {+                invalidate()+            }+        } catch (_: Exception) {+        }+    }++    /**+     * Run a Play call with whatever account is already available, cycling it if it has+     * died.+     *+     * Returns null when there is no account to use or both attempts failed, so callers+     * keep their existing fallback. Deliberately does *not* dispense when nothing is+     * cached: being signed out is the caller's cue to use the scraping path, and+     * dispensing here would put a retrying network call in front of every keystroke of+     * search.+     */+    suspend fun <T> withApi(block: suspend (PlayStoreApi) -> T): T? {+        val cached = cachedAuthData ?: return null+        try {+            return block(PlayStoreApi(cached, httpClient))+        } catch (e: CancellationException) {+            throw e+        } catch (e: Exception) {+            Log.w(TAG, "Play call failed; cycling anonymous account", e)+        }++        invalidate()+        val fresh = ensureAuth().getOrNull() ?: return null+        return try {+            block(PlayStoreApi(fresh, httpClient))+        } catch (e: CancellationException) {+            throw e+        } catch (e: Exception) {+            Log.w(TAG, "Play call failed again after cycling", e)+            null+        }+    }++    /** Like [withApi], but dispenses an account first if there isn't one. */+    suspend fun <T> withFreshApi(block: suspend (PlayStoreApi) -> T): T? {+        if (cachedAuthData == null && ensureAuth().isFailure) return null+        return withApi(block)+    }++    suspend fun ensureAuth(): Result<AuthData> = authMutex.withLock {+        cachedAuthData?.let { cached ->+            if (System.currentTimeMillis() - dispensedAt <= PLAY_AUTH_MAX_AGE_MS && isValid(cached)) {+                return@withLock Result.success(cached)+            }+            invalidate()+        }++        _authState.value = PlayAuthState.Authenticating++        val deviceProps = DeviceInfoProvider.buildDeviceProperties(context)+        val result = anonAuthRepo.ensureAuthData(context, deviceProps)+        val authData = result.getOrElse { err ->+            _authState.value = PlayAuthState.Error(anonAuthRepo.errorMessage(err))+            return@withLock Result.failure(err)+        }++        cachedAuthData = authData+        dispensedAt = System.currentTimeMillis()+        _authState.value = PlayAuthState.Authenticated(authData)+        persist(authData)+        Result.success(authData)+    }++    // --- Convenience wrappers -----------------------------------------------------++    suspend fun search(query: String): List<UnifiedApp> =+        withApi { it.search(query) }.orEmpty()++    suspend fun details(packageName: String): UnifiedApp? =+        withApi { it.getDetails(packageName) }++    suspend fun details(packageNames: List<String>): List<UnifiedApp> =+        withFreshApi { it.getDetails(packageNames) }.orEmpty()++    suspend fun topChart(): List<UnifiedApp> =+        withFreshApi { it.topChart() }.orEmpty()++    suspend fun homeClusters(): List<PlayCluster> =+        withFreshApi { it.homeClusters() }.orEmpty()++    /** Throws, unlike the readers above: an install has no silent fallback. */+    suspend fun purchase(+        packageName: String,+        versionCode: Long,+        offerType: Int,+        certHash: String?,+    ): List<PlayFile> {+        val authData = ensureAuth().getOrThrow()+        return PlayStoreApi(authData, httpClient)+            .purchase(context, packageName, versionCode, offerType, certHash)+    }++    // --- Internals ----------------------------------------------------------------++    private suspend fun isValid(authData: AuthData): Boolean = withContext(Dispatchers.IO) {+        try {+            AuthHelper.using(httpClient).isValid(authData)+        } catch (_: Exception) {+            false+        }+    }++    /**+     * Forget the current anonymous account so the next Play call dispenses a+     * fresh one. Clears the persisted copy too, or a restart would restore the+     * dead credentials.+     */+    private suspend fun invalidate() {+        cachedAuthData = null+        dispensedAt = 0L+        _authState.value = PlayAuthState.Idle+        try {+            context.authDataStore.edit { prefs ->+                prefs.remove(PLAY_AUTH_JSON_KEY)+                prefs.remove(PLAY_AUTH_DISPENSED_AT_KEY)+            }+        } catch (_: Exception) {+        }+    }++    private suspend fun persist(authData: AuthData) {+        try {+            val jsonStr = json.encodeToString(AuthData.serializer(), authData)+            context.authDataStore.edit { prefs ->+                prefs[PLAY_AUTH_JSON_KEY] = jsonStr+                prefs[PLAY_AUTH_DISPENSED_AT_KEY] = dispensedAt+            }+        } catch (_: Exception) {+        }+    }++    private companion object {+        const val TAG = "PlayRepository"+    }+}
appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayStoreApi.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayStoreApi.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayStoreApi.ktindex c6e6af96c7..a203f692cd 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayStoreApi.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayStoreApi.kt@@ -1,17 +1,27 @@ package com.vayunmathur.appstore.data.play  import android.content.Context+import com.aurora.gplayapi.data.models.App import com.aurora.gplayapi.data.models.AuthData import com.aurora.gplayapi.data.models.PlayFile+import com.aurora.gplayapi.data.models.StreamCluster import com.aurora.gplayapi.helpers.AppDetailsHelper import com.aurora.gplayapi.helpers.PurchaseHelper import com.aurora.gplayapi.helpers.SearchHelper+import com.aurora.gplayapi.helpers.StreamHelper+import com.aurora.gplayapi.helpers.TopChartsHelper+import com.aurora.gplayapi.helpers.contracts.StreamContract+import com.aurora.gplayapi.helpers.contracts.TopChartsContract+import com.vayunmathur.appstore.data.AppProvider import com.vayunmathur.appstore.data.AppSource import com.vayunmathur.appstore.data.UnifiedApp import com.vayunmathur.appstore.data.security.ApkCertificates import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext +/** A titled row of apps, as Play's own home screen is built from. */+data class PlayCluster(val title: String, val apps: List<UnifiedApp>)+ /**  * Wrapper around gplayapi helpers for Play Store operations.  * Uses AuthData + IHttpClient (PlayHttpClient).@@ -23,63 +33,79 @@ class PlayStoreApi(      suspend fun getDetails(packageName: String): UnifiedApp? = withContext(Dispatchers.IO) {         try {-            val helper = AppDetailsHelper(authData).using(httpClient)-            val app = helper.getAppByPackageName(packageName)--            UnifiedApp(-                packageName = app.packageName,-                source = AppSource.PLAYSTORE,-                name = app.displayName.takeIf { it.isNotBlank() } ?: packageName.substringAfterLast('.'),-                summary = app.shortDescription,-                description = app.description.takeIf { it.isNotBlank() } ?: app.shortDescription,-                iconUrl = app.iconArtwork.url.takeIf { it.isNotBlank() },-                author = app.developerName,-                categories = emptyList(),-                versionName = app.versionName,-                versionCode = app.versionCode,-                sizeBytes = app.size,-                website = "https://play.google.com/store/apps/details?id=$packageName",-                offerType = app.offerType,-                isFree = app.isFree,-                whatsNew = app.changes.takeIf { it.isNotBlank() },-                targetSdk = app.targetSdk,-                // AppDetails.certificateSet[].sha256 is the signing certificate Google-                // says this package should carry — the same expectation the Play client-                // stores on its library entry and compares against PackageManager. It-                // pins the bytes against a swapped CDN response, but note that Google-                // supplies both this value and the APK, so it is not a publisher key.-                expectedSigners = app.certificateSetList-                    .mapNotNull { it.sha256?.let(ApkCertificates::normalizeFingerprint) }-                    .distinct(),-            )-        } catch (e: Exception) {+            AppDetailsHelper(authData).using(httpClient)+                .getAppByPackageName(packageName)+                .toUnifiedApp()+        } catch (_: Exception) {             null         }     } +    /**+     * Details for many packages in one request.+     *+     * Play accepts a batch here, and the update check is the reason it matters: asking+     * per-package meant one round trip plus a throttling delay for every installed app,+     * so a phone with 60 Play apps spent minutes on a check that this does in a handful+     * of requests. Chunked because the endpoint rejects unbounded lists.+     */+    suspend fun getDetails(packageNames: List<String>): List<UnifiedApp> = withContext(Dispatchers.IO) {+        if (packageNames.isEmpty()) return@withContext emptyList()+        val helper = AppDetailsHelper(authData).using(httpClient)+        packageNames.chunked(DETAILS_BATCH).flatMap { chunk ->+            try {+                helper.getAppByPackageName(chunk).map { it.toUnifiedApp() }+            } catch (_: Exception) {+                emptyList()+            }+        }+    }+     suspend fun search(query: String): List<UnifiedApp> = withContext(Dispatchers.IO) {         try {-            val helper = SearchHelper(authData).using(httpClient)-            val bundle = helper.searchResults(query)-            val allApps = bundle.streamClusters.values.flatMap { it.clusterAppList }-            allApps.mapNotNull { app ->-                try {-                    UnifiedApp(-                        packageName = app.packageName,-                        source = AppSource.PLAYSTORE,-                        name = app.displayName.takeIf { it.isNotBlank() } ?: app.packageName.substringAfterLast('.'),-                        summary = app.shortDescription,-                        description = app.shortDescription,-                        iconUrl = app.iconArtwork.url.takeIf { it.isNotBlank() },-                        author = app.developerName,-                        versionName = app.versionName,-                        versionCode = app.versionCode,-                        website = "https://play.google.com/store/apps/details?id=${app.packageName}",-                        offerType = app.offerType-                    )-                } catch (_: Exception) { null }-            }-        } catch (e: Exception) {+            val bundle = SearchHelper(authData).using(httpClient).searchResults(query)+            bundle.streamClusters.values+                .flatMap { it.clusterAppList }+                .map { it.toUnifiedApp() }+                .distinctBy { it.packageName }+        } catch (_: Exception) {+            emptyList()+        }+    }++    /** A real top chart, rather than whatever the store's HTML happened to render. */+    suspend fun topChart(+        type: TopChartsContract.Type = TopChartsContract.Type.APPLICATION,+        chart: TopChartsContract.Chart = TopChartsContract.Chart.TOP_SELLING_FREE,+    ): List<UnifiedApp> = withContext(Dispatchers.IO) {+        try {+            TopChartsHelper(authData).using(httpClient)+                .getCluster(type.value, chart.value)+                .toApps()+        } catch (_: Exception) {+            emptyList()+        }+    }++    /**+     * Play's own home stream: several titled clusters ("Recommended for you", "New+     * releases", …). Used to give the browse screen real editorial rows instead of one+     * undifferentiated list.+     */+    suspend fun homeClusters(+        category: StreamContract.Category = StreamContract.Category.APPLICATION,+    ): List<PlayCluster> = withContext(Dispatchers.IO) {+        try {+            StreamHelper(authData).using(httpClient)+                .fetch(StreamContract.Type.HOME, category)+                .streamClusters.values+                .mapNotNull { cluster ->+                    val apps = cluster.toApps()+                    if (apps.isEmpty()) null+                    else PlayCluster(cluster.clusterTitle.ifBlank { "" }, apps)+                }+                .filter { it.title.isNotBlank() }+        } catch (_: Exception) {             emptyList()         }     }@@ -98,4 +124,65 @@ class PlayStoreApi(         val purchaseHelper = PurchaseHelper(authData).using(httpClient)         purchaseHelper.purchase(packageName, versionCode, offerType, certHash)     }++    private fun StreamCluster.toApps(): List<UnifiedApp> =+        AppProvider.filterTargetSdk(clusterAppList.map { it.toUnifiedApp() })+            .distinctBy { it.packageName }++    companion object {+        /**+         * Play rejects very long batches, and a rejected chunk loses every package in it,+         * so this stays well under whatever the real ceiling is.+         */+        private const val DETAILS_BATCH = 40+    }+}++/**+ * Everything Play publishes that the store shows, in one place.+ *+ * Cluster listings fill in far less than a details call does — most fields come back+ * empty — which is fine: the detail screen refetches by package name, and the empty+ * defaults on [UnifiedApp] are what a list row falls back to.+ */+internal fun App.toUnifiedApp(): UnifiedApp {+    val ratingCount = rating.let {+        it.oneStar + it.twoStar + it.threeStar + it.fourStar + it.fiveStar+    }+    return UnifiedApp(+        packageName = packageName,+        source = AppSource.PLAYSTORE,+        name = displayName.takeIf { it.isNotBlank() } ?: packageName.substringAfterLast('.'),+        summary = shortDescription,+        description = description.takeIf { it.isNotBlank() } ?: shortDescription,+        iconUrl = iconArtwork.url.takeIf { it.isNotBlank() },+        featureGraphic = coverArtwork.url.takeIf { it.isNotBlank() },+        screenshots = screenshots.mapNotNull { it.url.takeIf { u -> u.isNotBlank() } },+        author = developerName.takeIf { it.isNotBlank() },+        categories = listOfNotNull(categoryName.takeIf { it.isNotBlank() }),+        versionName = versionName.takeIf { it.isNotBlank() },+        versionCode = versionCode,+        sizeBytes = size,+        website = "https://play.google.com/store/apps/details?id=$packageName",+        offerType = offerType,+        isFree = isFree,+        whatsNew = changes.takeIf { it.isNotBlank() },+        targetSdk = targetSdk.takeIf { it > 0 },+        rating = rating.average.toFloat().takeIf { it > 0f },+        ratingCount = ratingCount,+        installs = installs,+        updatedOn = updatedOn.takeIf { it.isNotBlank() },+        contentRating = contentRating.title.takeIf { it.isNotBlank() },+        privacyPolicyUrl = privacyPolicyUrl.takeIf { it.isNotBlank() },+        containsAds = containsAds,+        permissions = permissions,+        // AppDetails.certificateSet[].sha256 is the signing certificate Google+        // says this package should carry — the same expectation the Play client+        // stores on its library entry and compares against PackageManager. It+        // pins the bytes against a swapped CDN response, but note that Google+        // supplies both this value and the APK, so it is not a publisher key.+        expectedSigners = certificateSetList+            .mapNotNull { it.sha256?.let(ApkCertificates::normalizeFingerprint) }+            .distinct(),+    ) }
appstore/src/main/java/com/vayunmathur/appstore/data/security/SecurityTier.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/security/SecurityTier.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/security/SecurityTier.ktdeleted file mode 100644index 0280fb8eab..0000000000--- a/appstore/src/main/java/com/vayunmathur/appstore/data/security/SecurityTier.kt+++ /dev/null@@ -1,142 +0,0 @@-package com.vayunmathur.appstore.data.security--import androidx.annotation.StringRes-import com.vayunmathur.appstore.R-import com.vayunmathur.appstore.data.AppProvider-import com.vayunmathur.appstore.data.AppSource--/**- * A rule the store applies to every app, whatever its source.- *- * Everything user-visible here is a string resource rather than a literal, because this is- * the text that explains the store's security model and it has to be readable in the user's- * own language to be worth anything.- */-data class StoreRule(-    @param:StringRes val title: Int,-    @param:StringRes val detail: Int,-    /** Format arguments for [detail], when it takes any. */-    val detailArgs: List<Any> = emptyList(),-)--/**- * Guarantees that hold for **every** install, from every source.- *- * These live here rather than being repeated on each tier so that a tier card only ever- * describes what is *distinctive* about that tier. If something is true of all three, it- * belongs in this list.- */-object StoreGuarantees {--    val rules: List<StoreRule> = listOf(-        StoreRule(-            R.string.store_rule_modern_android_title,-            R.string.store_rule_modern_android_detail,-            listOf(AppProvider.MIN_TARGET_SDK),-        ),-        StoreRule(R.string.store_rule_signed_title, R.string.store_rule_signed_detail),-        StoreRule(R.string.store_rule_identity_title, R.string.store_rule_identity_detail),-        StoreRule(R.string.store_rule_same_key_title, R.string.store_rule_same_key_detail),-        StoreRule(R.string.store_rule_split_key_title, R.string.store_rule_split_key_detail),-        StoreRule(R.string.store_rule_precheck_title, R.string.store_rule_precheck_detail),-        StoreRule(R.string.store_rule_fail_blocks_title, R.string.store_rule_fail_blocks_detail),-        StoreRule(R.string.store_rule_updates_stay_title, R.string.store_rule_updates_stay_detail),-        StoreRule(R.string.store_rule_fixed_sources_title, R.string.store_rule_fixed_sources_detail),-    )-}--/**- * How much a successful install can be verified, ranked by how feasible a supply-chain- * attack against it is.- *- * The ranking is about **who is able to produce bytes this device will accept as an- * update**, because that is the question that survives contact with reality once an app- * is installed: review, scanning and store policy reduce the odds of a bad app arriving,- * while the signing key decides who can replace a good one.- *- * Everything in [StoreGuarantees] applies here too and is deliberately not repeated.- */-enum class SecurityTier {--    /**-     * Signed with the same key as this store app, checked against our own signing-     * certificate as read back from PackageManager at install time.-     */-    FIRST_PARTY,--    /**-     * F-Droid, restricted to builds F-Droid's verification server independently-     * reproduced bit-for-bit.-     */-    REPRODUCIBLE,--    /** Play, where Google holds the signing key and no publisher key exists to pin. */-    GOOGLE_PLAY;--    val rank: Int get() = ordinal + 1--    @get:StringRes-    val title: Int-        get() = when (this) {-            FIRST_PARTY -> R.string.tier_first_party_title-            REPRODUCIBLE -> R.string.tier_reproducible_title-            GOOGLE_PLAY -> R.string.tier_play_title-        }--    /** One line, shown under the badge on the app's page. */-    @get:StringRes-    val summary: Int-        get() = when (this) {-            FIRST_PARTY -> R.string.tier_first_party_summary-            REPRODUCIBLE -> R.string.tier_reproducible_summary-            GOOGLE_PLAY -> R.string.tier_play_summary-        }--    /** Who has to be compromised to push you malicious code. */-    @get:StringRes-    val threatModel: Int-        get() = when (this) {-            FIRST_PARTY -> R.string.tier_first_party_threat-            REPRODUCIBLE -> R.string.tier_reproducible_threat-            GOOGLE_PLAY -> R.string.tier_play_threat-        }--    /** Checks specific to this tier, on top of [StoreGuarantees.rules]. */-    val additionalChecks: List<Int>-        get() = when (this) {-            FIRST_PARTY -> listOf(-                R.string.tier_first_party_check_key,-                R.string.tier_first_party_check_hash,-            )-            REPRODUCIBLE -> listOf(-                R.string.tier_reproducible_check_index_signed,-                R.string.tier_reproducible_check_chained,-                R.string.tier_reproducible_check_rebuilt,-                R.string.tier_reproducible_check_hash_and_key,-            )-            GOOGLE_PLAY -> listOf(-                R.string.tier_play_check_hash,-                R.string.tier_play_check_key,-                R.string.tier_play_check_stamp,-            )-        }--    /** The honest downside of this tier. */-    @get:StringRes-    val caveat: Int-        get() = when (this) {-            FIRST_PARTY -> R.string.tier_first_party_caveat-            REPRODUCIBLE -> R.string.tier_reproducible_caveat-            GOOGLE_PLAY -> R.string.tier_play_caveat-        }--    companion object {-        fun of(source: AppSource): SecurityTier = when (source) {-            AppSource.MODERN_APPS -> FIRST_PARTY-            // Non-reproduced F-Droid packages are dropped during sync and never reach the-            // UI, so anything surviving from FDROID is tier 2 by construction.-            AppSource.FDROID -> REPRODUCIBLE-            AppSource.PLAYSTORE -> GOOGLE_PLAY-        }-    }-}
appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.ktnew file mode 100644index 0000000000..aea84cde79--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt@@ -0,0 +1,159 @@+package com.vayunmathur.appstore.data.security++import androidx.annotation.StringRes+import com.vayunmathur.appstore.R+import com.vayunmathur.appstore.data.AppProvider+import com.vayunmathur.appstore.data.AppSource++/**+ * A rule the store applies to every app, whatever its source.+ *+ * Everything user-visible here is a string resource rather than a literal, because this is+ * the text that explains the store's security model and it has to be readable in the user's+ * own language to be worth anything.+ */+data class StoreRule(+    @param:StringRes val title: Int,+    @param:StringRes val detail: Int,+    /** Format arguments for [detail], when it takes any. */+    val detailArgs: List<Any> = emptyList(),+)++/**+ * Guarantees that hold for **every** install, from every source.+ *+ * These live here rather than being repeated on each profile so that a profile card only+ * ever describes what is *distinctive* about that source. If something is true of all+ * three, it belongs in this list.+ */+object StoreGuarantees {++    val rules: List<StoreRule> = listOf(+        StoreRule(+            R.string.store_rule_modern_android_title,+            R.string.store_rule_modern_android_detail,+            listOf(AppProvider.MIN_TARGET_SDK),+        ),+        StoreRule(R.string.store_rule_signed_title, R.string.store_rule_signed_detail),+        StoreRule(R.string.store_rule_identity_title, R.string.store_rule_identity_detail),+        StoreRule(R.string.store_rule_same_key_title, R.string.store_rule_same_key_detail),+        StoreRule(R.string.store_rule_split_key_title, R.string.store_rule_split_key_detail),+        StoreRule(R.string.store_rule_precheck_title, R.string.store_rule_precheck_detail),+        StoreRule(R.string.store_rule_fail_blocks_title, R.string.store_rule_fail_blocks_detail),+        StoreRule(R.string.store_rule_updates_stay_title, R.string.store_rule_updates_stay_detail),+        StoreRule(R.string.store_rule_fixed_sources_title, R.string.store_rule_fixed_sources_detail),+    )+}++/**+ * How an app's provenance can be checked, described **per source and deliberately not+ * ranked**.+ *+ * This used to be a 1-2-3 "security tier" with Play at the bottom, which was wrong in a+ * way worth spelling out: the ranking scored only "can this phone verify the bytes+ * against a publisher key", and then presented that single axis as overall security.+ * Google Play holds its signing keys in hardware security modules, requires verified+ * developer identity, scans every upload and every device, and can pull a malicious app+ * from the whole fleet within hours — a set of practices no F-Droid build server comes+ * close to. F-Droid's reproducible builds prove a *different* thing (that the binary+ * matches published source), and prove it well, but F-Droid also holds the signing key+ * itself and can take weeks to publish a security fix.+ *+ * Neither of those is strictly better than the other, so the store no longer pretends+ * one is. Each profile below states what its source actually does, what this app checks+ * on top, and where it falls short — and the UI presents the three side by side in source+ * order rather than best-to-worst.+ */+enum class TrustProfile {++    /**+     * Signed with the same key as this store app, checked against our own signing+     * certificate as read back from PackageManager at install time.+     */+    MODERN_APPS,++    /**+     * F-Droid, restricted to builds F-Droid's verification server independently+     * reproduced bit-for-bit.+     */+    FDROID,++    /** Google Play, via an anonymous account. */+    PLAY;++    @get:StringRes+    val title: Int+        get() = when (this) {+            MODERN_APPS -> R.string.trust_modern_apps_title+            FDROID -> R.string.trust_fdroid_title+            PLAY -> R.string.trust_play_title+        }++    /** One line, shown under the heading on the app's page. */+    @get:StringRes+    val summary: Int+        get() = when (this) {+            MODERN_APPS -> R.string.trust_modern_apps_summary+            FDROID -> R.string.trust_fdroid_summary+            PLAY -> R.string.trust_play_summary+        }++    /** What the source itself does, beyond anything this app can check. */+    val sourcePractices: List<Int>+        get() = when (this) {+            MODERN_APPS -> listOf(+                R.string.trust_modern_apps_practice_open,+                R.string.trust_modern_apps_practice_one_key,+            )+            FDROID -> listOf(+                R.string.trust_fdroid_practice_source,+                R.string.trust_fdroid_practice_rebuild,+                R.string.trust_fdroid_practice_antifeatures,+            )+            PLAY -> listOf(+                R.string.trust_play_practice_identity,+                R.string.trust_play_practice_scanning,+                R.string.trust_play_practice_hsm,+                R.string.trust_play_practice_takedown,+            )+        }++    /** Checks this app performs on the download, on top of [StoreGuarantees.rules]. */+    val ourChecks: List<Int>+        get() = when (this) {+            MODERN_APPS -> listOf(+                R.string.trust_modern_apps_check_key,+                R.string.trust_modern_apps_check_hash,+            )+            FDROID -> listOf(+                R.string.trust_fdroid_check_index_signed,+                R.string.trust_fdroid_check_chained,+                R.string.trust_fdroid_check_rebuilt,+                R.string.trust_fdroid_check_hash_and_key,+            )+            PLAY -> listOf(+                R.string.trust_play_check_hash,+                R.string.trust_play_check_key,+                R.string.trust_play_check_stamp,+            )+        }++    /** Where this source is weaker than the others. Every source has one. */+    @get:StringRes+    val limits: Int+        get() = when (this) {+            MODERN_APPS -> R.string.trust_modern_apps_limits+            FDROID -> R.string.trust_fdroid_limits+            PLAY -> R.string.trust_play_limits+        }++    companion object {+        fun of(source: AppSource): TrustProfile = when (source) {+            AppSource.MODERN_APPS -> MODERN_APPS+            // Non-reproduced F-Droid packages are dropped during sync and never reach the+            // UI, so anything surviving from FDROID really was rebuilt.+            AppSource.FDROID -> FDROID+            AppSource.PLAYSTORE -> PLAY+        }+    }+}
appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.ktnew file mode 100644index 0000000000..3b25bc8964--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.kt@@ -0,0 +1,393 @@+package com.vayunmathur.appstore.ui++import android.graphics.drawable.Drawable+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.core.graphics.drawable.toBitmap+import com.vayunmathur.appstore.R+import com.vayunmathur.appstore.data.AppSource+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.installer.InstallStage+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CardDefaults+import com.vayunmathur.library.ui.IconCheck+import com.vayunmathur.library.ui.IconStar+import com.vayunmathur.library.ui.LinearProgressIndicator+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import java.util.Locale++/**+ * The app icon, from whichever of the three places actually has one.+ *+ * A locally installed app has a real launcher icon in PackageManager, which beats+ * re-downloading the listing's copy; a catalogue entry has a URL; a Play cluster row+ * sometimes has neither. Every screen needs the same fallback chain, so it lives here+ * rather than being written out again per call site.+ */+@Composable+fun AppIcon(+    app: UnifiedApp,+    installedIcon: Drawable?,+    modifier: Modifier = Modifier,+    size: Dp = 48.dp,+    corner: Dp = 12.dp,+) {+    val shape = RoundedCornerShape(corner)+    val box = modifier.size(size).clip(shape)+    val bitmap = installedIcon?.let {+        runCatching {+            val px = (size.value * 2).toInt().coerceAtLeast(1)+            it.toBitmap(width = px, height = px).asImageBitmap()+        }.getOrNull()+    }+    when {+        bitmap != null -> Image(+            bitmap = bitmap,+            contentDescription = null,+            modifier = box,+            contentScale = ContentScale.Crop,+        )+        app.iconUrl != null -> AsyncImage(+            model = app.iconUrl,+            contentDescription = null,+            modifier = box,+            contentScale = ContentScale.Crop,+        )+        // No icon anywhere: an initial on a tinted tile reads better than a blank hole,+        // and keeps rows the same height whether or not the artwork loaded.+        else -> Box(+            box.background(MaterialTheme.colorScheme.surfaceVariant),+            contentAlignment = Alignment.Center,+        ) {+            Text(+                app.name.take(1).uppercase(),+                style = MaterialTheme.typography.titleMedium,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+        }+    }+}++/** Where an app came from. Purely factual — the sources are not ranked. */+@Composable+fun SourceChip(source: AppSource, modifier: Modifier = Modifier) {+    val label = stringResource(+        when (source) {+            AppSource.MODERN_APPS -> R.string.source_chip_modern_apps+            AppSource.FDROID -> R.string.source_chip_fdroid+            AppSource.PLAYSTORE -> R.string.source_chip_play+        }+    )+    Text(+        label,+        style = MaterialTheme.typography.labelSmall,+        color = MaterialTheme.colorScheme.onSurfaceVariant,+        modifier = modifier+            .clip(RoundedCornerShape(6.dp))+            .background(MaterialTheme.colorScheme.surfaceVariant)+            .padding(horizontal = 6.dp, vertical = 2.dp),+    )+}++/** "4.6 ★" plus the rating count, when the source published one. */+@Composable+fun RatingLabel(app: UnifiedApp, modifier: Modifier = Modifier) {+    val rating = app.rating ?: return+    Row(modifier, verticalAlignment = Alignment.CenterVertically) {+        Text(+            String.format(Locale.US, "%.1f", rating),+            style = MaterialTheme.typography.labelSmall,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+        )+        Spacer(Modifier.width(2.dp))+        IconStar(Modifier.size(12.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant)+    }+}++/**+ * A full-width list row: icon, name, summary, and whatever the caller puts on the right.+ *+ * [stage] draws its own progress bar underneath, so a row that is mid-install says which+ * part of the install it is in rather than showing a bar that sits at 100% through+ * verification and commit.+ */+@Composable+fun AppRow(+    app: UnifiedApp,+    modifier: Modifier = Modifier,+    isInstalled: Boolean = false,+    stage: InstallStage? = null,+    installedIcon: Drawable? = null,+    onClick: () -> Unit = {},+    trailing: @Composable (() -> Unit)? = null,+) {+    Column(+        modifier+            .fillMaxWidth()+            .clickable(onClick = onClick)+            .padding(horizontal = 16.dp, vertical = 10.dp),+    ) {+        Row(verticalAlignment = Alignment.CenterVertically) {+            AppIcon(app, installedIcon, size = 48.dp)+            Spacer(Modifier.width(14.dp))+            Column(Modifier.weight(1f)) {+                Text(+                    app.name,+                    style = MaterialTheme.typography.titleSmall,+                    fontWeight = FontWeight.SemiBold,+                    maxLines = 1,+                    overflow = TextOverflow.Ellipsis,+                )+                val subtitle = app.summary.ifBlank { app.author.orEmpty() }+                if (subtitle.isNotBlank()) {+                    Text(+                        subtitle,+                        style = MaterialTheme.typography.bodySmall,+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                        maxLines = 2,+                        overflow = TextOverflow.Ellipsis,+                    )+                }+                Row(+                    Modifier.padding(top = 2.dp),+                    verticalAlignment = Alignment.CenterVertically,+                    horizontalArrangement = Arrangement.spacedBy(6.dp),+                ) {+                    SourceChip(app.source)+                    RatingLabel(app)+                    if (isInstalled) {+                        IconCheck(Modifier.size(12.dp), tint = MaterialTheme.colorScheme.primary)+                    }+                }+            }+            if (trailing != null) {+                Spacer(Modifier.width(8.dp))+                trailing()+            }+        }+        StageProgress(stage, Modifier.padding(top = 8.dp))+    }+}++/**+ * A carousel tile: icon over name over rating, in a fixed-width column.+ *+ * Fixed width rather than intrinsic so that the tiles in a row line up regardless of how+ * long each app's name is — a carousel of ragged columns reads as broken.+ */+@Composable+fun AppTile(+    app: UnifiedApp,+    modifier: Modifier = Modifier,+    isInstalled: Boolean = false,+    installedIcon: Drawable? = null,+    onClick: () -> Unit = {},+) {+    Column(+        modifier+            .width(96.dp)+            .clip(RoundedCornerShape(12.dp))+            .clickable(onClick = onClick)+            .padding(vertical = 4.dp),+        horizontalAlignment = Alignment.CenterHorizontally,+    ) {+        AppIcon(app, installedIcon, size = 72.dp, corner = 18.dp)+        Spacer(Modifier.height(8.dp))+        Text(+            app.name,+            style = MaterialTheme.typography.labelMedium,+            textAlign = TextAlign.Center,+            maxLines = 2,+            overflow = TextOverflow.Ellipsis,+            // Two lines' worth whatever the name's length, so tiles stay aligned.+            modifier = Modifier.heightIn(min = 32.dp),+        )+        if (isInstalled) {+            Text(+                stringResource(R.string.installed),+                style = MaterialTheme.typography.labelSmall,+                color = MaterialTheme.colorScheme.primary,+            )+        } else {+            RatingLabel(app)+        }+    }+}++/** Heading above a section of the home screen. */+@Composable+fun SectionHeader(title: String, subtitle: String?, modifier: Modifier = Modifier) {+    Column(modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {+        Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)+        if (!subtitle.isNullOrBlank()) {+            Text(+                subtitle,+                style = MaterialTheme.typography.bodySmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+        }+    }+}++/** One horizontally scrolling row of [AppTile]s. */+@Composable+fun AppCarousel(+    apps: List<UnifiedApp>,+    installedPackages: Set<String>,+    installedIcons: Map<String, Drawable>,+    onAppClick: (UnifiedApp) -> Unit,+    modifier: Modifier = Modifier,+) {+    LazyRow(+        modifier = modifier.fillMaxWidth(),+        contentPadding = PaddingValues(horizontal = 12.dp),+        horizontalArrangement = Arrangement.spacedBy(4.dp),+    ) {+        items(apps, key = { it.packageName }) { app ->+            AppTile(+                app = app,+                isInstalled = app.packageName in installedPackages,+                installedIcon = installedIcons[app.packageName],+                onClick = { onAppClick(app) },+            )+        }+    }+}++/**+ * The progress line for an in-flight install, or nothing when there isn't one.+ *+ * Download is determinate; verification and the PackageInstaller commit are not, and an+ * indeterminate bar is the honest way to say "still working, no idea how long".+ */+@Composable+fun StageProgress(stage: InstallStage?, modifier: Modifier = Modifier) {+    if (stage == null) return+    Column(modifier.fillMaxWidth()) {+        when (stage) {+            is InstallStage.Downloading -> LinearProgressIndicator(+                progress = { stage.fraction },+                modifier = Modifier.fillMaxWidth(),+            )+            is InstallStage.Failed -> Unit+            else -> LinearProgressIndicator(Modifier.fillMaxWidth())+        }+        Text(+            stageLabel(stage),+            style = MaterialTheme.typography.labelSmall,+            color = if (stage is InstallStage.Failed) {+                MaterialTheme.colorScheme.error+            } else {+                MaterialTheme.colorScheme.onSurfaceVariant+            },+            modifier = Modifier.padding(top = 2.dp),+        )+    }+}++@Composable+fun stageLabel(stage: InstallStage): String = when (stage) {+    InstallStage.Preparing -> stringResource(R.string.stage_preparing)+    is InstallStage.Downloading ->+        stringResource(R.string.stage_downloading, (stage.fraction * 100).toInt())+    InstallStage.Verifying -> stringResource(R.string.stage_verifying)+    InstallStage.Installing -> stringResource(R.string.stage_installing)+    is InstallStage.Failed -> stringResource(R.string.stage_failed, stage.reason)+}++/** A labelled value in the facts grid on the detail page. */+@Composable+fun StatCell(label: String, value: String, modifier: Modifier = Modifier) {+    Column(modifier, horizontalAlignment = Alignment.CenterHorizontally) {+        Text(+            value,+            style = MaterialTheme.typography.titleSmall,+            fontWeight = FontWeight.SemiBold,+            maxLines = 1,+        )+        Text(+            label,+            style = MaterialTheme.typography.labelSmall,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+            maxLines = 1,+        )+    }+}++/** A read-only chip, for categories and anti-features. */+@Composable+fun InfoChip(+    text: String,+    modifier: Modifier = Modifier,+    emphasise: Boolean = false,+) {+    Card(+        modifier = modifier,+        colors = CardDefaults.cardColors(+            containerColor = if (emphasise) {+                MaterialTheme.colorScheme.errorContainer+            } else {+                MaterialTheme.colorScheme.surfaceVariant+            },+            contentColor = if (emphasise) {+                MaterialTheme.colorScheme.onErrorContainer+            } else {+                MaterialTheme.colorScheme.onSurfaceVariant+            },+        ),+    ) {+        Text(+            text,+            style = MaterialTheme.typography.labelSmall,+            modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp),+        )+    }+}++/** "12 MB", "980 kB" — SI units, because that is what stores quote. */+fun formatSize(bytes: Long): String = when {+    bytes <= 0L -> ""+    bytes < 1_000L -> "$bytes B"+    bytes < 1_000_000L -> String.format(Locale.US, "%.0f kB", bytes / 1_000.0)+    bytes < 1_000_000_000L -> String.format(Locale.US, "%.1f MB", bytes / 1_000_000.0)+    else -> String.format(Locale.US, "%.2f GB", bytes / 1_000_000_000.0)+}++/** "1.2M+", "50K+" — the rounded form an install count is meaningful at. */+fun formatCount(count: Long): String = when {+    count <= 0L -> ""+    count < 1_000L -> count.toString()+    count < 1_000_000L -> "${count / 1_000}K+"+    count < 1_000_000_000L -> String.format(Locale.US, "%.1fM+", count / 1_000_000.0)+    else -> String.format(Locale.US, "%.1fB+", count / 1_000_000_000.0)+}
appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.ktindex 8ee02c88bc..3bb86f5fb0 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt@@ -1,11 +1,10 @@ package com.vayunmathur.appstore.ui -import androidx.compose.ui.res.stringResource-import com.vayunmathur.appstore.R-import android.graphics.drawable.Drawable-import androidx.compose.foundation.Image+import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize@@ -14,338 +13,501 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip-import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp-import androidx.core.graphics.drawable.toBitmap-import com.vayunmathur.library.ui.R as UiR-import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.appstore.R import com.vayunmathur.appstore.data.AppSource-import com.vayunmathur.appstore.data.security.SecurityTier+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.installer.InstallStage+import com.vayunmathur.appstore.data.security.TrustProfile import com.vayunmathur.appstore.data.security.VerificationResult import com.vayunmathur.appstore.util.AppDetailActions import com.vayunmathur.appstore.util.AppDetailUiState import com.vayunmathur.appstore.util.AppStoreViewModel+import com.vayunmathur.library.image.compose.AsyncImage import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CenterAlignedTopAppBar+import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.FilledTonalButton import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.IconBack+import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.IconDownload import com.vayunmathur.library.ui.IconGlobe-import com.vayunmathur.library.ui.IconShoppingCart-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.LinearProgressIndicator+import com.vayunmathur.library.ui.IconKeyboardArrowDown+import com.vayunmathur.library.ui.IconKeyboardArrowUp+import com.vayunmathur.library.ui.IconShare import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.setValue  /** Binds [AppStoreViewModel] to the stateless [AppDetailScreen]. */ @Composable fun AppDetailPage(     viewModel: AppStoreViewModel,     onBack: () -> Unit,-    onOpenTiers: () -> Unit = {},+    onOpenTrust: () -> Unit = {}, ) {-    val app by viewModel.selectedApp.collectAsState()-    val verificationMap by viewModel.verification.collectAsState()-    val installed by viewModel.installedApps.collectAsState()-    val progressMap by viewModel.downloadProgress.collectAsState()-    val icons by viewModel.installedIcons.collectAsState()-    val syncMessage by viewModel.syncMessage.collectAsState()-    // "" can never be a real package name, so the lookups below miss harmlessly while-    // nothing is selected and the screen bails out.-    val pkg = app?.packageName.orEmpty()--    AppDetailScreen(-        state = AppDetailUiState(-            app = app,-            installedInfo = installed.find { it.packageName == pkg },-            verification = verificationMap[pkg],-            progress = progressMap[pkg],-            installedIcon = icons[pkg],-            syncMessage = syncMessage,-        ),-        actions = viewModel,-        onBack = onBack,-        onOpenTiers = onOpenTiers,-    )+    val state by viewModel.detail.collectAsState()+    AppDetailScreen(state = state, actions = viewModel, onBack = onBack, onOpenTrust = onOpenTrust) }  /**- * The app detail screen, with no dependency on the ViewModel so it can be rendered from a- * `@Preview` — see `src/screenshotTest`, which is where the store listing images come from.+ * One app's page: what it is, what it looks like, and what installing it would mean.+ *+ * The previous version led with a wall of label/value rows, which is a debug dump rather+ * than a listing. The order here is the order the questions actually get asked —+ * screenshots, the install button, the description, then the facts, then provenance.+ *+ * Stateless so it can be rendered from a `@Preview` — see `src/screenshotTest`, which is+ * where the store listing images come from.  */ @Composable fun AppDetailScreen(     state: AppDetailUiState,     actions: AppDetailActions,     onBack: () ->

Diff truncated.