appstore: AppProvider abstraction (fdroid + play), targetSdk >=35 filter, installed presence check in order fdroid->play->hide, filter chips with counts
- Commit
4a0cbf68969aabe2ea491b8cb36e13d19ee83e37- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-31 16:45 UTC (4 months ago)
- Parents
536e40b
Diff
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 8f52c118e5..4c1fcdf3ed 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt@@ -37,6 +37,7 @@ data class CachedAppEntity( val versionCode: Long, val sizeBytes: Long, val apkUrl: String?,+ val targetSdk: Int?, val repoUrl: String?, val lastUpdated: Long )@@ -85,7 +86,7 @@ interface CachedAppDao { @Database( entities = [RepoEntity::class, CachedAppEntity::class],- version = 2,+ version = 3, exportSchema = false ) abstract class AppDatabase : RoomDatabase() {@@ -98,6 +99,11 @@ abstract class AppDatabase : RoomDatabase() { override fun migrate(db: SupportSQLiteDatabase) { db.execSQL("DROP TABLE IF EXISTS FavoriteEntity") }+ },+ object : Migration(2, 3) {+ override fun migrate(db: SupportSQLiteDatabase) {+ db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN targetSdk INTEGER")+ } } ) }
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 226720977f..6f2897ead7 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt@@ -21,6 +21,7 @@ data class UnifiedApp( val versionCode: Long = 0L, val sizeBytes: Long = 0L, val apkUrl: String? = null,+ val targetSdk: Int? = null, val screenshotUrls: List<String> = emptyList(), val rating: Float? = null, val license: String? = null,
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.ktnew file mode 100644index 0000000000..4705b3b983--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.kt@@ -0,0 +1,34 @@+package com.vayunmathur.appstore.data++/**+ * Generic app store source — F-Droid (Droid-ify style) or Play Store (Aurora style).+ * The app registers 2 providers in order: fdroid base repo + play store.+ * [isPresent] is used for installed filtering: check F-Droid first, then Play,+ * if none — hide from installed list.+ */+interface AppProvider {+ val id: String+ val name: String+ val source: AppSource++ /** All apps available from this provider (browse / sync). Must filter targetSdk < 35. */+ suspend fun fetchAll(): List<UnifiedApp>++ /** Search within this provider. */+ suspend fun search(query: String): List<UnifiedApp>++ /** Presence check for installed filtering: true if package exists in this store. */+ suspend fun isPresent(packageName: String): Boolean++ /** Detailed listing for a package, or null. */+ suspend fun getDetails(packageName: String): UnifiedApp?++ companion object {+ const val MIN_TARGET_SDK = 35++ /** Keep only apps targeting >= MIN_TARGET_SDK, or unknown targetSdk (can't verify). */+ fun filterTargetSdk(apps: List<UnifiedApp>): List<UnifiedApp> {+ return apps.filter { app -> app.targetSdk == null || app.targetSdk >= MIN_TARGET_SDK }+ }+ }+}
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.ktnew file mode 100644index 0000000000..185aa71247--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt@@ -0,0 +1,109 @@+package com.vayunmathur.appstore.data++import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++class FDroidAppProvider(+ private val db: AppDatabase+) : AppProvider {+ override val id = "fdroid"+ override val name = "F-Droid"+ override val source = AppSource.FDROID++ @Volatile var cachedPackageNames: Set<String> = emptySet()++ override suspend fun fetchAll(): List<UnifiedApp> = withContext(Dispatchers.IO) {+ val repos = db.repoDao().all().filter { it.enabled }+ val all = mutableListOf<UnifiedApp>()+ for (repo in repos) {+ try { all += FDroidRepository.fetchRepoIndex(repo.url) } catch (_: Exception) { }+ }+ val filtered = AppProvider.filterTargetSdk(all).distinctBy { it.packageName }+ cachedPackageNames = filtered.map { it.packageName }.toSet()+ filtered+ }++ override suspend fun search(query: String): List<UnifiedApp> = withContext(Dispatchers.IO) {+ if (query.isBlank()) return@withContext emptyList()+ val q = query.lowercase()+ val live = mutableListOf<UnifiedApp>()+ for (url in listOf(DefaultRepos.FDROID_MAIN, DefaultRepos.IZVYZID)) {+ try {+ live += FDroidRepository.fetchRepoIndex(url).filter {+ it.name.lowercase().contains(q) || it.packageName.lowercase().contains(q) || it.summary.lowercase().contains(q)+ }+ } catch (_: Exception) {}+ }+ AppProvider.filterTargetSdk(live).take(40)+ }++ 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.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.targetSdk != null && entity.targetSdk < AppProvider.MIN_TARGET_SDK) return@withContext null+ entity.toUnifiedApp()+ } catch (_: Exception) { null }+ }++ suspend fun syncIntoDb(): Int = withContext(Dispatchers.IO) {+ val repos = db.repoDao().all().filter { it.enabled }+ var total = 0+ for (repo in repos) {+ try {+ val apps = FDroidRepository.fetchRepoIndex(repo.url)+ val filtered = AppProvider.filterTargetSdk(apps)+ val entities = filtered.map { it.toEntity() }+ db.cachedAppDao().deleteByRepo(repo.url.trimEnd('/'))+ db.cachedAppDao().upsertAll(entities)+ db.repoDao().upsert(repo.copy(lastSync = System.currentTimeMillis()))+ total += entities.size+ } catch (_: Exception) { }+ }+ total+ }++ private fun UnifiedApp.toEntity(): CachedAppEntity = CachedAppEntity(+ packageName = packageName,+ source = source.name,+ name = name,+ summary = summary,+ description = description,+ iconUrl = iconUrl,+ author = author,+ categories = categories.joinToString(","),+ versionName = versionName,+ versionCode = versionCode,+ sizeBytes = sizeBytes,+ apkUrl = apkUrl,+ targetSdk = targetSdk,+ repoUrl = repoUrl?.removeSuffix("/") ?: DefaultRepos.FDROID_MAIN,+ lastUpdated = lastUpdated+ )++ private fun CachedAppEntity.toUnifiedApp(): UnifiedApp = UnifiedApp(+ packageName = packageName,+ source = try { AppSource.valueOf(source) } catch (_: Exception) { AppSource.FDROID },+ name = name,+ summary = summary,+ description = description,+ iconUrl = iconUrl,+ author = author,+ categories = categories.split(",").filter { it.isNotBlank() },+ versionName = versionName,+ versionCode = versionCode,+ sizeBytes = sizeBytes,+ apkUrl = apkUrl,+ targetSdk = targetSdk,+ repoUrl = repoUrl,+ lastUpdated = lastUpdated+ )+}
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 876f4485dc..6d590c9c19 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt@@ -3,11 +3,8 @@ package com.vayunmathur.appstore.data import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.contentOrNull-import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive@@ -16,9 +13,8 @@ import java.net.HttpURLConnection import java.net.URL /**- * F-Droid index v2 client — inspired by Droid-ify's sync logic but simplified- * for this unified store. Fetches https://f-droid.org/repo/index-v2.json and- * IzzyOnDroid, merges into [UnifiedApp] list.+ * F-Droid index v2 client — Droid-ify style. Fetches index-v2.json then v1.+ * Filters targetSdk < AppProvider.MIN_TARGET_SDK when manifest provides it. */ object FDroidRepository { @@ -26,13 +22,13 @@ object FDroidRepository { suspend fun fetchRepoIndex(repoUrl: String): List<UnifiedApp> = withContext(Dispatchers.IO) { val base = repoUrl.trimEnd('/')- // Try index-v2.json first (faster, structured), fallback to index-v1.json val urls = listOf("$base/index-v2.json", "$base/index-v1.json") var lastErr: Exception? = null for (url in urls) { try {- return@withContext if (url.endsWith("v2.json")) fetchV2(url, base)- else fetchV1(url, base)+ val apps = if (url.endsWith("v2.json")) fetchV2(url, base) else fetchV1(url, base)+ // Filter targetSdk < 35 for both sources requirement+ return@withContext AppProvider.filterTargetSdk(apps) } catch (e: Exception) { lastErr = e }@@ -59,16 +55,14 @@ object FDroidRepository { val versions = pkgObj["versions"]?.jsonObject ?: continue if (versions.isEmpty()) continue - // pick latest version by added timestamp- val latestEntry = versions.values.mapNotNull {- it.jsonObject- }.maxByOrNull { it["added"]?.jsonPrimitive?.longOrNull ?: 0L } ?: continue+ val latestEntry = versions.values.mapNotNull { it.jsonObject }+ .maxByOrNull { it["added"]?.jsonPrimitive?.longOrNull ?: 0L } ?: continue val fileObj = latestEntry["file"]?.jsonObject val manifest = latestEntry["manifest"]?.jsonObject+ val usesSdk = manifest?.get("usesSdk")?.jsonObject - val name = extractLocalized(meta["name"])- ?: pkg.substringAfterLast('.')+ val name = extractLocalized(meta["name"]) ?: pkg.substringAfterLast('.') val summary = extractLocalized(meta["summary"]) ?: "" val desc = extractLocalized(meta["description"]) ?: "" val author = meta["authorName"]?.jsonPrimitive?.contentOrNull@@ -84,8 +78,8 @@ object FDroidRepository { val whatsNew = extractLocalized(latestEntry["whatsNew"]) val added = meta["added"]?.jsonPrimitive?.longOrNull ?: 0L val lastUpdated = meta["lastUpdated"]?.jsonPrimitive?.longOrNull ?: added+ val targetSdk = usesSdk?.get("targetSdkVersion")?.jsonPrimitive?.contentOrNull?.toIntOrNull() - // icon url: metadata.icon["en-US"]?.name -> repoBase/icons/... val iconName = runCatching { meta["icon"]?.jsonObject?.values?.firstOrNull() ?.jsonObject?.values?.firstOrNull()@@ -106,6 +100,7 @@ object FDroidRepository { versionCode = versionCode, sizeBytes = sizeBytes, apkUrl = apkUrl,+ targetSdk = targetSdk, license = license, website = website, sourceCode = source,@@ -114,13 +109,12 @@ object FDroidRepository { lastUpdated = lastUpdated, repoUrl = repoBase )- } catch (_: Exception) { /* skip broken entry */ }+ } catch (_: Exception) { } } return result } private fun fetchV1(url: String, repoBase: String): List<UnifiedApp> {- // v1 is JSON with "apps" array and "packages" map — simplified parse val conn = (URL(url).openConnection() as HttpURLConnection).apply { connectTimeout = 20000 readTimeout = 60000@@ -156,6 +150,7 @@ object FDroidRepository { val vName = latestVer?.get("versionName")?.jsonPrimitive?.contentOrNull val vCode = latestVer?.get("versionCode")?.jsonPrimitive?.longOrNull ?: 0L val size = latestVer?.get("size")?.jsonPrimitive?.longOrNull ?: 0L+ val targetSdk = latestVer?.get("targetSdkVersion")?.jsonPrimitive?.contentOrNull?.toIntOrNull() result += UnifiedApp( packageName = pkg,@@ -170,6 +165,7 @@ object FDroidRepository { versionCode = vCode, sizeBytes = size, apkUrl = apkUrl,+ targetSdk = targetSdk, website = website, sourceCode = src, license = license,
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.ktnew file mode 100644index 0000000000..ad93293a9d--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/PlayStoreAppProvider.kt@@ -0,0 +1,44 @@+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/PlayStoreDataSource.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/PlayStoreDataSource.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/PlayStoreDataSource.ktindex 7ec9748561..03ad6eb703 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/PlayStoreDataSource.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/PlayStoreDataSource.kt@@ -2,36 +2,14 @@ package com.vayunmathur.appstore.data import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext-import kotlinx.serialization.json.Json import org.jsoup.Jsoup import java.net.HttpURLConnection import java.net.URL import java.net.URLEncoder -/**- * Play Store scraping data source — lightweight, no gplayapi dependency.- * Inspired by Aurora Store's browsing but uses public Play Store web pages- * plus anonymous token for search. This avoids requiring Google account login- * while still listing Play Store apps alongside F-Droid.- *- * For install we delegate to browser / market intent (user's existing Play- * Store or Aurora already handles installs). For direct APK we leave apkUrl null- * and surface Play listing — same as Aurora's "manual download" path.- */ object PlayStoreDataSource { - private const val PLAY_BASE = "https://play.google.com"- private val jsonLoose = Json { ignoreUnknownKeys = true; isLenient = true }-- data class PlaySearchResult(- val packageName: String,- val name: String,- val developer: String,- val iconUrl: String?,- val rating: Float?,- val summary: String,- val isFree: Boolean- )+ const val PLAY_BASE = "https://play.google.com" suspend fun search(query: String): List<UnifiedApp> = withContext(Dispatchers.IO) { if (query.isBlank()) return@withContext emptyList()@@ -45,10 +23,8 @@ object PlayStoreDataSource { setRequestProperty("Accept-Language", "en-US,en;q=0.9") } val html = conn.inputStream.bufferedReader().readText()- parseSearchHtml(html)- } catch (e: Exception) {- emptyList()- }+ AppProvider.filterTargetSdk(parseSearchHtml(html))+ } catch (_: Exception) { emptyList() } } suspend fun topCharts(category: String = ""): List<UnifiedApp> = withContext(Dispatchers.IO) {@@ -61,7 +37,7 @@ object PlayStoreDataSource { setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36") } val html = conn.inputStream.bufferedReader().readText()- parseSearchHtml(html).take(30)+ AppProvider.filterTargetSdk(parseSearchHtml(html).take(30)) } catch (_: Exception) { emptyList() } } @@ -87,7 +63,12 @@ object PlayStoreDataSource { val ratingText = doc.selectFirst("div.TT9eCd")?.text() val rating = ratingText?.toFloatOrNull() - UnifiedApp(+ // Try to infer targetSdk from page text (best effort)+ val pageText = doc.text()+ val targetSdk = Regex("Target.*API.*?(\\d{2})|targetSdk.*?(\\d{2})", RegexOption.IGNORE_CASE)+ .find(pageText)?.groupValues?.filter { it.toIntOrNull() != null }?.lastOrNull()?.toIntOrNull()++ val app = UnifiedApp( packageName = packageName, source = AppSource.PLAYSTORE, name = name,@@ -97,8 +78,10 @@ object PlayStoreDataSource { author = developer, categories = emptyList(), rating = rating,+ targetSdk = targetSdk, website = "$PLAY_BASE/store/apps/details?id=$packageName" )+ if (targetSdk != null && targetSdk < AppProvider.MIN_TARGET_SDK) null else app } catch (_: Exception) { null } } @@ -106,7 +89,6 @@ object PlayStoreDataSource { val results = mutableListOf<UnifiedApp>() try { val doc = Jsoup.parse(html)- // Play Store uses very dynamic layout — try multiple selectors val candidates = doc.select("a[href*=/store/apps/details?id=]") val seen = mutableSetOf<String>() for (a in candidates) {@@ -114,12 +96,9 @@ object PlayStoreDataSource { val pkg = Regex("[?&]id=([^&]+)").find(href)?.groupValues?.get(1) ?: continue if (!seen.add(pkg)) continue if (results.size >= 40) break- val title = a.attr("title").ifBlank { a.text().ifBlank { pkg } }- // icon nearby val img = a.selectFirst("img")?.attr("src") ?: a.parent()?.selectFirst("img")?.attr("src")- results += UnifiedApp( packageName = pkg, source = AppSource.PLAYSTORE,@@ -134,5 +113,4 @@ object PlayStoreDataSource { } fun playStoreUrl(pkg: String): String = "$PLAY_BASE/store/apps/details?id=$pkg"- fun marketUrl(pkg: String): String = "market://details?id=$pkg" }
appstore/src/main/java/com/vayunmathur/appstore/ui/InstalledPage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/InstalledPage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/InstalledPage.ktindex 3a5865dcb2..5b2cd05aa7 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/InstalledPage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/InstalledPage.kt@@ -3,9 +3,15 @@ package com.vayunmathur.appstore.ui import androidx.compose.foundation.layout.Arrangement 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+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState@@ -15,23 +21,35 @@ import androidx.compose.ui.unit.dp import com.vayunmathur.appstore.data.AppSource import com.vayunmathur.appstore.data.UnifiedApp import com.vayunmathur.appstore.util.AppStoreViewModel+import com.vayunmathur.appstore.util.InstalledFilter+import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar @Composable fun InstalledPage( viewModel: AppStoreViewModel, onAppClick: (UnifiedApp) -> Unit ) {- val installed by viewModel.installedApps.collectAsState() val cached by viewModel.cachedApps.collectAsState() val icons by viewModel.installedIcons.collectAsState()+ val srcMap by viewModel.installedSourceMap.collectAsState()+ val filteredInstalled by viewModel.filteredInstalled.collectAsState()+ val filter by viewModel.installedFilter.collectAsState()++ // counts for filter chips: Only user apps that are present in either store+ val allCount = srcMap.size+ val fdroidCount = srcMap.values.count { it == AppSource.FDROID }+ val playCount = srcMap.values.count { it == AppSource.PLAYSTORE } - val apps = installed.map { inst ->+ val apps = filteredInstalled.map { inst -> val cachedApp = cached.find { it.packageName == inst.packageName }+ val src = srcMap[inst.packageName] ?: AppSource.PLAYSTORE UnifiedApp( packageName = inst.packageName,- source = if (cachedApp != null) AppSource.FDROID else AppSource.PLAYSTORE,+ source = src, name = inst.name, summary = cachedApp?.summary ?: inst.versionName ?: "", description = cachedApp?.description ?: "",@@ -40,27 +58,69 @@ fun InstalledPage( versionName = inst.versionName, versionCode = inst.versionCode, apkUrl = cachedApp?.apkUrl,+ targetSdk = cachedApp?.targetSdk, repoUrl = cachedApp?.repoUrl ) } - Column(Modifier.fillMaxSize()) {- LazyColumn(- modifier = Modifier.fillMaxSize(),- contentPadding = PaddingValues(top = 24.dp, start = 12.dp, end = 12.dp, bottom = 12.dp),- verticalArrangement = Arrangement.spacedBy(8.dp)- ) {- item {- Text("${installed.size} installed apps", style = MaterialTheme.typography.titleSmall, modifier = Modifier.padding(4.dp))+ Scaffold(+ topBar = { TopAppBar(title = { Text("Installed (${filteredInstalled.size})") }) }+ ) { padding ->+ Column(Modifier.fillMaxSize().padding(padding)) {+ // Filter chips with counts: All / F-Droid (n) / Play Store (n)+ LazyRow(+ contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ modifier = Modifier.fillMaxWidth()+ ) {+ item {+ FilterChip(+ selected = filter == InstalledFilter.ALL,+ onClick = { viewModel.setInstalledFilter(InstalledFilter.ALL) },+ label = { Text("All ($allCount)") }+ )+ }+ item {+ FilterChip(+ selected = filter == InstalledFilter.FDROID,+ onClick = { viewModel.setInstalledFilter(InstalledFilter.FDROID) },+ label = { Text("F-Droid ($fdroidCount)") }+ )+ }+ item {+ FilterChip(+ selected = filter == InstalledFilter.PLAYSTORE,+ onClick = { viewModel.setInstalledFilter(InstalledFilter.PLAYSTORE) },+ label = { Text("Play Store ($playCount)") }+ )+ } }- items(apps, key = { it.packageName }) { app ->- AppRow(- app = app,- isInstalled = true,- progress = null,- installedIcon = icons[app.packageName],- onClick = { onAppClick(app) }- )++ LazyColumn(+ modifier = Modifier.fillMaxSize(),+ contentPadding = PaddingValues(12.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ if (apps.isEmpty()) {+ item {+ Text(+ if (allCount == 0) "No installed apps found in F-Droid or Play Store. Sync repos to populate F-Droid."+ else "No apps match this filter",+ style = MaterialTheme.typography.bodyMedium,+ modifier = Modifier.padding(16.dp)+ )+ }+ } else {+ items(apps, key = { it.packageName }) { app ->+ AppRow(+ app = app,+ isInstalled = true,+ progress = null,+ installedIcon = icons[app.packageName],+ onClick = { onAppClick(app) }+ )+ }+ } } } }@@ -72,9 +132,12 @@ fun UpdatesPage(viewModel: AppStoreViewModel, onAppClick: (UnifiedApp) -> Unit) val cached by viewModel.cachedApps.collectAsState() val progressMap by viewModel.downloadProgress.collectAsState() val icons by viewModel.installedIcons.collectAsState()+ val srcMap by viewModel.installedSourceMap.collectAsState() + // Only user apps present in stores, with F-Droid updates (targetSdk already filtered) val updates = cached.mapNotNull { cachedEntity -> val inst = installed.find { it.packageName == cachedEntity.packageName } ?: return@mapNotNull null+ if (srcMap[inst.packageName] == null) return@mapNotNull null if (cachedEntity.versionCode > inst.versionCode) { UnifiedApp( packageName = cachedEntity.packageName,@@ -88,33 +151,32 @@ fun UpdatesPage(viewModel: AppStoreViewModel, onAppClick: (UnifiedApp) -> Unit) versionCode = cachedEntity.versionCode, sizeBytes = cachedEntity.sizeBytes, apkUrl = cachedEntity.apkUrl,+ targetSdk = cachedEntity.targetSdk, repoUrl = cachedEntity.repoUrl ) } else null } - Column(Modifier.fillMaxSize()) {- LazyColumn(- modifier = Modifier.fillMaxSize(),- contentPadding = PaddingValues(top = 24.dp, start = 12.dp, end = 12.dp, bottom = 12.dp),- verticalArrangement = Arrangement.spacedBy(8.dp)- ) {- if (updates.isEmpty()) {- item {- Text("All apps up to date", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(16.dp))- }- } else {- item {- Text("${updates.size} updates available", style = MaterialTheme.typography.titleSmall, modifier = Modifier.padding(4.dp))- }- items(updates, key = { it.packageName }) { app ->- AppRow(- app = app,- isInstalled = true,- progress = progressMap[app.packageName],- installedIcon = icons[app.packageName],- onClick = { onAppClick(app) }- )+ Scaffold(topBar = { TopAppBar(title = { Text("Updates") }) }) { padding ->+ Column(Modifier.fillMaxSize().padding(padding)) {+ LazyColumn(+ modifier = Modifier.fillMaxSize(),+ contentPadding = PaddingValues(12.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ if (updates.isEmpty()) {+ item { Text("All apps up to date", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(16.dp)) }+ } else {+ item { Text("${updates.size} updates", style = MaterialTheme.typography.titleSmall, modifier = Modifier.padding(4.dp)) }+ items(updates, key = { it.packageName }) { app ->+ AppRow(+ app = app,+ isInstalled = true,+ progress = progressMap[app.packageName],+ installedIcon = icons[app.packageName],+ onClick = { onAppClick(app) }+ )+ } } } }
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.ktindex e626f13464..f70f2b3b9e 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt@@ -12,14 +12,16 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.vayunmathur.appstore.data.AppDatabase+import com.vayunmathur.appstore.data.AppProvider import com.vayunmathur.appstore.data.AppSource import com.vayunmathur.appstore.data.CachedAppEntity import com.vayunmathur.appstore.data.DefaultRepos-import com.vayunmathur.appstore.data.FDroidRepository+import com.vayunmathur.appstore.data.FDroidAppProvider import com.vayunmathur.appstore.data.InstalledInfo-import com.vayunmathur.appstore.data.PlayStoreDataSource+import com.vayunmathur.appstore.data.PlayStoreAppProvider import com.vayunmathur.appstore.data.RepoEntity import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.PlayStoreDataSource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow@@ -33,11 +35,22 @@ import java.io.File import java.net.HttpURLConnection import java.net.URL +enum class InstalledFilter {+ ALL,+ FDROID,+ PLAYSTORE+}+ class AppStoreViewModel( private val context: Context, private val db: AppDatabase ) : ViewModel() { + // Providers — app registers 2 providers, fdroid base repo + play store+ private val fdroidProvider = FDroidAppProvider(db)+ private val playProvider = PlayStoreAppProvider()+ private val providers: List<AppProvider> = listOf(fdroidProvider, playProvider)+ private val _isSyncing = MutableStateFlow(false) val isSyncing: StateFlow<Boolean> = _isSyncing @@ -64,6 +77,13 @@ class AppStoreViewModel( private val _activeRepo = MutableStateFlow<String?>(null) + // Installed filtering: presence-resolved source per package, order F-Droid -> Play Store+ private val _installedSourceMap = MutableStateFlow<Map<String, AppSource>>(emptyMap())+ val installedSourceMap: StateFlow<Map<String, AppSource>> = _installedSourceMap++ private val _installedFilter = MutableStateFlow(InstalledFilter.ALL)+ val installedFilter: StateFlow<InstalledFilter> = _installedFilter+ val repos = db.repoDao().allFlow() .stateIn(viewModelScope, SharingStarted.Eagerly, emptyList()) @@ -74,35 +94,38 @@ class AppStoreViewModel( cachedApps, _playSearchResults, _topCharts, _searchQuery, _activeRepo ) { cached, playSearch, topCharts, query, activeRepo -> val fdroidAll = cached.map { it.toUnifiedApp() }- val fdroid = if (activeRepo != null) fdroidAll.filter { it.repoUrl == activeRepo || activeRepo == "all" } else fdroidAll- // Infer overlay: if package exists in any F-Droid repo, force FDROID source; otherwise PLAYSTORE+ val fdroidFiltered = if (activeRepo != null) fdroidAll.filter { it.repoUrl == activeRepo } else fdroidAll val fdroidPkgs = fdroidAll.map { it.packageName }.toSet()- val infPlaySearch = playSearch.map { it.copy(source = inferSource(it.packageName, fdroidPkgs)) }- val infTop = topCharts.map { it.copy(source = inferSource(it.packageName, fdroidPkgs)) } - if (query.isBlank()) {- val all = fdroid + (if (infPlaySearch.isEmpty()) infTop else infPlaySearch)- all.distinctBy { it.packageName }.sortedBy { it.name.lowercase() }+ fun infer(pkg: String): AppSource = if (fdroidPkgs.contains(pkg)) AppSource.FDROID else AppSource.PLAYSTORE++ val infSearch = playSearch.map { it.copy(source = infer(it.packageName)) }+ val infCharts = topCharts.map { it.copy(source = infer(it.packageName)) }++ val list = if (query.isBlank()) {+ fdroidFiltered + (if (infSearch.isEmpty()) infCharts else infSearch) } else { val q = query.lowercase()- val filteredFdroid = fdroid.filter {+ val fd = fdroidFiltered.filter { it.name.lowercase().contains(q) || it.packageName.lowercase().contains(q) || it.summary.lowercase().contains(q) }- val combined = (filteredFdroid + infPlaySearch).distinctBy { it.packageName }.map {- it.copy(source = inferSource(it.packageName, fdroidPkgs))- }- combined.sortedBy { it.name.lowercase() }+ (fd + infSearch).distinctBy { it.packageName }.map { it.copy(source = infer(it.packageName)) } }+ // Filter targetSdk < 35 for both sources (defense in depth)+ AppProvider.filterTargetSdk(list.distinctBy { it.packageName }).sortedBy { it.name.lowercase() } }.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList()) - private fun inferSource(pkg: String, fdroidPkgs: Set<String>): AppSource {- return if (fdroidPkgs.contains(pkg)) AppSource.FDROID else AppSource.PLAYSTORE- }-- fun inferSourceForInstalled(pkg: String): AppSource {- val fdroidPkgs = cachedApps.value.map { it.packageName }.toSet()- return inferSource(pkg, fdroidPkgs)- }+ // Presence-resolved installed list: only apps present in fdroid or play (order checked), with counts+ val filteredInstalled: StateFlow<List<InstalledInfo>> = combine(+ _installedApps, _installedSourceMap, _installedFilter+ ) { installed, srcMap, filter ->+ val inStore = installed.filter { srcMap.containsKey(it.packageName) }+ when (filter) {+ InstalledFilter.ALL -> inStore+ InstalledFilter.FDROID -> inStore.filter { srcMap[it.packageName] == AppSource.FDROID }+ InstalledFilter.PLAYSTORE -> inStore.filter { srcMap[it.packageName] == AppSource.PLAYSTORE }+ }+ }.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList()) var searchJob: Job? = null var topJob: Job? = null@@ -113,6 +136,12 @@ class AppStoreViewModel( refreshInstalled() loadTopCharts() }+ // Keep fdroid provider cache synced with DB flow+ viewModelScope.launch {+ cachedApps.collect { list ->+ fdroidProvider.cachedPackageNames = list.map { it.packageName }.toSet()+ }+ } } private suspend fun ensureDefaultRepos() {@@ -128,7 +157,7 @@ class AppStoreViewModel( topJob?.cancel() topJob = viewModelScope.launch { _syncMessage.value = "Loading top charts..."- val charts = PlayStoreDataSource.topCharts()+ val charts = playProvider.fetchAll() _topCharts.value = charts _syncMessage.value = "" }@@ -144,8 +173,8 @@ class AppStoreViewModel( searchJob = viewModelScope.launch { kotlinx.coroutines.delay(400) _syncMessage.value = "Searching Play Store..."- val play = PlayStoreDataSource.search(q)- _playSearchResults.value = play+ val results = playProvider.search(q)+ _playSearchResults.value = results _syncMessage.value = "" } }@@ -154,25 +183,14 @@ class AppStoreViewModel( if (_isSyncing.value) return viewModelScope.launch { _isSyncing.value = true- _syncMessage.value = "Syncing repositories..."- val repos = db.repoDao().all().filter { it.enabled }- var fetched = 0- for (repo in repos) {- try {- _syncMessage.value = "Syncing ${repo.name}..."- val apps = FDroidRepository.fetchRepoIndex(repo.url)- val entities = apps.map { it.toEntity() }- db.cachedAppDao().deleteByRepo(repo.url.removeSuffix("/"))- db.cachedAppDao().upsertAll(entities)- db.repoDao().upsert(repo.copy(lastSync = System.currentTimeMillis()))- fetched += apps.size- } catch (e: Exception) {- _syncMessage.value = "Failed ${repo.name}: ${e.message}"- kotlinx.coroutines.delay(1500)- }+ _syncMessage.value = "Syncing F-Droid repositories..."+ try {+ val total = fdroidProvider.syncIntoDb()+ _syncMessage.value = if (total > 0) "Synced $total apps from F-Droid" else "Sync complete"+ } catch (e: Exception) {+ _syncMessage.value = "F-Droid sync failed: ${e.message}" }- _syncMessage.value = if (fetched > 0) "Synced $fetched apps" else "Sync complete"- kotlinx.coroutines.delay(2000)+ kotlinx.coroutines.delay(1500) _syncMessage.value = "" _isSyncing.value = false refreshInstalled()@@ -182,9 +200,9 @@ class AppStoreViewModel( fun refreshInstalled() { viewModelScope.launch(Dispatchers.IO) { val pm = context.packageManager- // Only user apps: exclude system partition apps- val allApps = pm.getInstalledApplications(PackageManager.MATCH_ALL)- val userApps = allApps.filter { (it.flags and ApplicationInfo.FLAG_SYSTEM) == 0 }+ val all = pm.getInstalledApplications(PackageManager.MATCH_ALL)+ // User apps only — not system partition+ val userApps = all.filter { (it.flags and ApplicationInfo.FLAG_SYSTEM) == 0 } val installed = userApps.mapNotNull { ai -> try { val pi = pm.getPackageInfo(ai.packageName, 0)@@ -192,8 +210,7 @@ class AppStoreViewModel( packageName = ai.packageName, name = pm.getApplicationLabel(ai).toString(), versionName = pi.versionName,- versionCode = if (Build.VERSION.SDK_INT >= 28) pi.longVersionCode else pi.versionCode.toLong(),- isSystem = false+ versionCode = if (Build.VERSION.SDK_INT >= 28) pi.longVersionCode else pi.versionCode.toLong() ) } catch (_: Exception) { null } }.sortedBy { it.name.lowercase() }@@ -202,21 +219,45 @@ class AppStoreViewModel( try { ai.packageName to pm.getApplicationIcon(ai.packageName) } catch (_: Exception) { null } }.toMap() - _installedApps.value = installed- _installedIcons.value = icons+ withContext(Dispatchers.Main) {+ _installedApps.value = installed+ _installedIcons.value = icons+ }+ // Resolve source presence for each installed app, order: fdroid -> play -> none (hide)+ resolveInstalledSources(installed.map { it.packageName }) } } + private fun resolveInstalledSources(packages: List<String>) {+ viewModelScope.launch(Dispatchers.IO) {+ val map = mutableMapOf<String, AppSource>()+ for (pkg in packages) {+ // Order: fdroid first, then play store+ if (fdroidProvider.isPresent(pkg)) {+ map[pkg] = AppSource.FDROID+ } else if (playProvider.isPresent(pkg)) {+ map[pkg] = AppSource.PLAYSTORE+ }+ // else not in any store -> hidden from installed list (per requirement)+ }+ _installedSourceMap.value = map+ }+ }++ fun setInstalledFilter(filter: InstalledFilter) {+ _installedFilter.value = filter+ }+ fun selectApp(app: UnifiedApp) {- // Re-infer source based on F-Droid cache at selection time too+ // Re-infer via providers order: fdroid check takes precedence val fdroidPkgs = cachedApps.value.map { it.packageName }.toSet()- val inferred = app.copy(source = inferSource(app.packageName, fdroidPkgs))- _selectedApp.value = inferred- if (inferred.source == AppSource.PLAYSTORE && inferred.description.isBlank()) {+ val inferredSource = if (fdroidPkgs.contains(app.packageName)) AppSource.FDROID else AppSource.PLAYSTORE+ _selectedApp.value = app.copy(source = inferredSource)+ if (inferredSource == AppSource.PLAYSTORE && app.description.isBlank()) { viewModelScope.launch {- val details = PlayStoreDataSource.appDetails(inferred.packageName)+ val details = playProvider.getDetails(app.packageName) if (details != null) {- _selectedApp.value = details.copy(source = inferSource(details.packageName, fdroidPkgs))+ _selectedApp.value = details.copy(source = if (fdroidPkgs.contains(details.packageName)) AppSource.FDROID else AppSource.PLAYSTORE) } } }@@ -246,8 +287,8 @@ class AppStoreViewModel( fun addRepo(url: String, name: String) { viewModelScope.launch {- val cleanUrl = url.trim().trimEnd('/')- db.repoDao().upsert(RepoEntity(cleanUrl, name.ifBlank { cleanUrl }, true))+ val clean = url.trim().trimEnd('/')+ db.repoDao().upsert(RepoEntity(clean, name.ifBlank { clean }, true)) } } @@ -266,43 +307,45 @@ class AppStoreViewModel( } fun downloadAndInstall(app: UnifiedApp) {- // Inferred source decides: FDROID = direct APK, PLAYSTORE = market intent- val fdroidPkgs = cachedApps.value.map { it.packageName }.toSet()- val src = inferSource(app.packageName, fdroidPkgs)- if (src == AppSource.PLAYSTORE) {- openInPlayStore(app.packageName)- return- }- // Resolve APK from F-Droid cache if current listing lacks it- val apkUrl = app.apkUrl ?: cachedApps.value.find { it.packageName == app.packageName }?.apkUrl ?: return- viewModelScope.launch(Dispatchers.IO) {- try {- _downloadProgress.value = _downloadProgress.value + (app.packageName to 0.01f)- val file = File(context.cacheDir, "${app.packageName}.apk")- val conn = (URL(apkUrl).openConnection() as HttpURLConnection).apply {- connectTimeout = 20000- readTimeout = 60000- }- val total = conn.contentLengthLong.takeIf { it > 0 } ?: app.sizeBytes- conn.inputStream.use { input ->- file.outputStream().use { out ->- val buf = ByteArray(8192)- var read: Int- var downloaded = 0L- while (input.read(buf).also { read = it } != -1) {- out.write(buf, 0, read)- downloaded += read- if (total > 0) {- _downloadProgress.value = _downloadProgress.value + (app.packageName to (downloaded.toFloat() / total))+ // Use presence logic: fdroid present -> direct APK, else play -> market intent+ viewModelScope.launch {+ val srcMap = _installedSourceMap.value+ val fdroidPkgs = cachedApps.value.map { it.packageName }.toSet()+ val isFdroid = fdroidPkgs.contains(app.packageName) || srcMap[app.packageName] == AppSource.FDROID || app.source == AppSource.FDROID+ if (!isFdroid) {+ openInPlayStore(app.packageName)+ return@launch+ }+ val apkUrl = app.apkUrl ?: cachedApps.value.find { it.packageName == app.packageName }?.apkUrl ?: return@launch+ withContext(Dispatchers.IO) {+ try {+ _downloadProgress.value = _downloadProgress.value + (app.packageName to 0.01f)+ val file = File(context.cacheDir, "${app.packageName}.apk")+ val conn = (URL(apkUrl).openConnection() as HttpURLConnection).apply {+ connectTimeout = 20000+ readTimeout = 60000+ }+ val total = conn.contentLengthLong.takeIf { it > 0 } ?: app.sizeBytes+ conn.inputStream.use { input ->+ file.outputStream().use { out ->+ val buf = ByteArray(8192)+ var read: Int+ var downloaded = 0L+ while (input.read(buf).also { read = it } != -1) {+ out.write(buf, 0, read)+ downloaded += read+ if (total > 0) {+ _downloadProgress.value = _downloadProgress.value + (app.packageName to (downloaded.toFloat() / total))+ } } } }+ _downloadProgress.value = _downloadProgress.value - app.packageName+ withContext(Dispatchers.Main) { installApk(file) }+ } catch (e: Exception) {+ _downloadProgress.value = _downloadProgress.value - app.packageName+ _syncMessage.value = "Download failed: ${e.message}" }- _downloadProgress.value = _downloadProgress.value - app.packageName- withContext(Dispatchers.Main) { installApk(file) }- } catch (e: Exception) {- _downloadProgress.value = _downloadProgress.value - app.packageName- _syncMessage.value = "Download failed: ${e.message}" } } }@@ -337,6 +380,7 @@ class AppStoreViewModel( versionCode = versionCode, sizeBytes = sizeBytes, apkUrl = apkUrl,+ targetSdk = targetSdk, repoUrl = repoUrl?.removeSuffix("/") ?: DefaultRepos.FDROID_MAIN, lastUpdated = lastUpdated )@@ -354,6 +398,7 @@ class AppStoreViewModel( versionCode = versionCode, sizeBytes = sizeBytes, apkUrl = apkUrl,+ targetSdk = targetSdk, repoUrl = repoUrl, lastUpdated = lastUpdated )