appstore: rank search results and widen the query (#595)
- Commit
e4e01b579b7d6bb0e87fe3b3225364a71a1cf00a- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-07 04:00 UTC (3 months ago)
- Parents
f90633b
Diff
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 6d4aaccb95..d60b81e368 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt@@ -1,5 +1,7 @@ package com.vayunmathur.appstore.data +import com.vayunmathur.appstore.domain.SearchRanking+ enum class AppSource { /** This monorepo's own repository, signed with the same key as this app. */ MODERN_APPS,@@ -122,6 +124,15 @@ data class UnifiedApp( val heroImage: String? get() = featureGraphic ?: screenshots.firstOrNull() } +/** The fields [SearchRanking] looks at, for a listing from any source. */+fun UnifiedApp.searchCandidate(): SearchRanking.Candidate = SearchRanking.Candidate(+ name = name,+ packageName = packageName,+ author = author.orEmpty(),+ summary = summary,+ popularity = installs,+)+ data class InstalledInfo( val packageName: String, val name: String,
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.ktindex aad2166cea..fbaf9774e1 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt@@ -1,6 +1,7 @@ package com.vayunmathur.appstore.data import android.content.Context+import com.vayunmathur.appstore.domain.SearchRanking import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.SharingStarted@@ -104,9 +105,18 @@ class CatalogRepository( 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())+ val phrase = query.trim()+ if (phrase.isBlank()) return@withContext emptyList()+ // `LIKE '%chase mobile%'` only matches a row that holds both words together and+ // in that order, which is why a two-word query used to come back empty even+ // when each word was there. Ask per word as well, and let the ranking decide+ // what the extra hits are worth (issue #595).+ val queries = (listOf(phrase) + SearchRanking.tokenize(phrase)).distinct()+ runCatching {+ queries.flatMap { db.cachedAppDao().searchAll(it, limit) }+ .distinctBy { it.packageName }+ .map { it.toUnifiedApp() }+ }.getOrDefault(emptyList()) } suspend fun byPackage(packageName: String): UnifiedApp? = withContext(Dispatchers.IO) {
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.ktindex 4596763f2c..2a5d40448d 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayRepository.kt@@ -10,6 +10,8 @@ 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 com.vayunmathur.appstore.data.searchCandidate+import com.vayunmathur.appstore.domain.SearchRanking import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow@@ -166,8 +168,25 @@ class PlayRepository(private val context: Context) { // --- Convenience wrappers ----------------------------------------------------- - suspend fun search(query: String): List<UnifiedApp> =- withApi { it.search(query) }.orEmpty()+ /**+ * Play's search: more pages while the answer is unsatisfying, then the first word.+ *+ * A phrase Play does not recognise comes back either as filler or as nothing at all —+ * the reason "Google Maps" returned Facebook and Netflix and "chase mobile" returned+ * nothing (issue #595). Neither is worth showing, so the search reads on, and failing+ * that asks the broader question. [SearchRanking] decides what any of it is worth, and+ * is also what decides whether an answer counts as one.+ */+ suspend fun search(query: String): List<UnifiedApp> {+ val answered: (List<UnifiedApp>) -> Boolean = { results ->+ results.any { SearchRanking.score(it.searchCandidate(), query) != null }+ }+ val direct = withApi { it.search(query, SEARCH_MAX_PAGES, answered) }.orEmpty()+ val tokens = SearchRanking.tokenize(query)+ if (tokens.size < 2 || answered(direct)) return direct+ val broader = withApi { it.search(tokens.first(), SEARCH_MAX_PAGES, answered) }.orEmpty()+ return (direct + broader).distinctBy { it.packageName }+ } suspend fun details(packageName: String): UnifiedApp? = withApi { it.getDetails(packageName) }@@ -234,5 +253,11 @@ class PlayRepository(private val context: Context) { private companion object { const val TAG = "PlayRepository"++ /**+ * How far into Play's search stream to read before giving up on a query. Only+ * reached when the pages so far hold nothing that answers it.+ */+ const val SEARCH_MAX_PAGES = 3 } }
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 aaf2fa55ce..95762322de 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@@ -61,13 +61,38 @@ class PlayStoreApi( } } - suspend fun search(query: String): List<UnifiedApp> = withContext(Dispatchers.IO) {+ /**+ * Play's search, following pages only while the answer is unsatisfying.+ *+ * The first page is often editorial filler — searching "Google Maps" and getting+ * Facebook, Messenger, Netflix and Snapchat is issue #595 — with the genuine hits on+ * the page behind it. [answered] decides when to stop, so a query that is answered+ * straight away still costs exactly one request and the extra round trips are spent+ * only where the alternative was showing the user nothing they asked for.+ */+ suspend fun search(+ query: String,+ maxPages: Int,+ answered: (List<UnifiedApp>) -> Boolean,+ ): List<UnifiedApp> = withContext(Dispatchers.IO) { try {- val bundle = SearchHelper(authData).using(httpClient).searchResults(query)- bundle.streamClusters.values- .flatMap { it.clusterAppList }- .map { it.toUnifiedApp() }- .distinctBy { it.packageName }+ val helper = SearchHelper(authData).using(httpClient)+ val found = LinkedHashMap<String, UnifiedApp>()+ var bundle = helper.searchResults(query)+ var page = 1+ while (true) {+ bundle.streamClusters.values+ .flatMap { it.clusterAppList }+ .forEach { app ->+ val unified = app.toUnifiedApp()+ found.putIfAbsent(unified.packageName, unified)+ }+ if (answered(found.values.toList())) break+ if (page >= maxPages || !bundle.hasNext()) break+ bundle = helper.nextStreamBundle(query, bundle.streamNextPageUrl)+ page+++ }+ found.values.toList() } catch (_: Exception) { emptyList() }
appstore/src/main/java/com/vayunmathur/appstore/domain/SearchRanking.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/domain/SearchRanking.kt b/appstore/src/main/java/com/vayunmathur/appstore/domain/SearchRanking.ktnew file mode 100644index 0000000000..dfb3bc4dd5--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/domain/SearchRanking.kt@@ -0,0 +1,113 @@+package com.vayunmathur.appstore.domain++/**+ * Turns a query and a set of candidate listings into an order.+ *+ * The old ranking treated the query as one literal string, which is what issue #595 is+ * about: "Google Maps" only ever reached the `contains` tier, so everything Play returned+ * alongside the real answer — Facebook, Netflix — scored the same and sorted in+ * alphabetically, and "chase mobile" matched nothing at all even though it is the app's+ * exact name, because no single field holds those two words together.+ *+ * So the query is split into words. A result has to account for every one of them before+ * it is shown at all, and where it lands is decided by how the words line up with the+ * name rather than by whether the whole phrase happens to appear verbatim.+ */+object SearchRanking {++ /**+ * The fields ranking looks at, so this stays independent of the store's app model and+ * can be exercised without a Play session.+ */+ data class Candidate(+ val name: String,+ val packageName: String,+ val author: String = "",+ val summary: String = "",+ /** Install count where the source publishes one; separates equally good matches. */+ val popularity: Long = 0L,+ )++ /** Query words, lowercased. Capped so a pasted sentence can't fan out into a scan. */+ fun tokenize(query: String): List<String> = words(query).take(MAX_QUERY_TOKENS)++ /**+ * How well [candidate] answers [query], lower being better, or null when it does not+ * answer it at all.+ *+ * Every query word has to appear somewhere — the author counts, so a search for the+ * publisher plus the product ("Google Maps") still finds a listing simply named "Maps"+ * — but only the name decides the tier, because that is the thing the user is reading+ * down the list.+ */+ fun score(candidate: Candidate, query: String): Int? {+ val tokens = tokenize(query)+ if (tokens.isEmpty()) return null+ val fields = fields(candidate)+ if (tokens.any { token -> fields.none { it.contains(token) } }) return null++ val q = query.trim().lowercase()+ val name = candidate.name.lowercase()+ val nameWords = words(name)+ return when {+ name == q || candidate.packageName.lowercase() == q -> EXACT+ name.startsWith(q) -> NAME_PREFIX+ tokens.all { token -> nameWords.any { it.startsWith(token) } } -> WORD_PREFIX+ tokens.all { token -> name.contains(token) } -> NAME_CONTAINS+ else -> ELSEWHERE+ }+ }++ /**+ * Rank [items], dropping the ones that do not answer [query].+ *+ * When nothing answers all of it, results answering part of it are shown instead:+ * a query a person would call reasonable — "chase mobile" against a store that only+ * lists "Chase Bank" — should not come back as an empty screen.+ */+ fun <T> rank(items: List<T>, query: String, candidate: (T) -> Candidate): List<T> {+ if (query.isBlank()) return items+ val scored = items.mapNotNull { item -> score(candidate(item), query)?.let { item to it } }+ .ifEmpty {+ items.mapNotNull { item -> partialScore(candidate(item), query)?.let { item to it } }+ }+ return scored+ .sortedWith(+ compareBy<Pair<T, Int>> { it.second }+ .thenByDescending { candidate(it.first).popularity }+ .thenBy { candidate(it.first).name.lowercase() }+ )+ .map { it.first }+ }++ /** Rank for a result that matches some of the query but not all of it. */+ private fun partialScore(candidate: Candidate, query: String): Int? {+ val tokens = tokenize(query)+ val fields = fields(candidate)+ val missing = tokens.count { token -> fields.none { it.contains(token) } }+ return if (missing == tokens.size) null else PARTIAL + missing+ }++ private fun fields(candidate: Candidate): List<String> = listOf(+ candidate.name.lowercase(),+ candidate.packageName.lowercase(),+ candidate.author.lowercase(),+ candidate.summary.lowercase(),+ )++ private fun words(text: String): List<String> =+ text.lowercase().split(SEPARATORS).filter { it.isNotBlank() }++ private val SEPARATORS = Regex("[^\\p{L}\\p{N}]+")++ private const val MAX_QUERY_TOKENS = 4++ private const val EXACT = 0+ private const val NAME_PREFIX = 1+ private const val WORD_PREFIX = 2+ private const val NAME_CONTAINS = 3+ private const val ELSEWHERE = 4++ /** Floor for the relaxed pass, so a partial match can never outrank a whole one. */+ private const val PARTIAL = 10+}
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 6ff2c38db8..db8d4b42fd 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt@@ -28,8 +28,10 @@ import com.vayunmathur.appstore.data.installer.InstallStage import com.vayunmathur.appstore.data.play.PlayAuthState import com.vayunmathur.appstore.data.play.PlayRepository import com.vayunmathur.appstore.data.priority+import com.vayunmathur.appstore.data.searchCandidate import com.vayunmathur.appstore.data.security.ApkCertificates import com.vayunmathur.appstore.data.security.VerificationResult+import com.vayunmathur.appstore.domain.SearchRanking import com.vayunmathur.library.util.AppMessages import kotlinx.coroutines.Job import kotlinx.coroutines.delay@@ -679,21 +681,9 @@ class AppStoreViewModel( .distinctBy { it.packageName } .toList() - /** Exact hits first, then name prefixes, then everything else alphabetically. */- private fun rank(apps: List<UnifiedApp>, query: String): List<UnifiedApp> {- val q = query.trim().lowercase()- fun score(app: UnifiedApp): Int {- val name = app.name.lowercase()- return when {- name == q || app.packageName.lowercase() == q -> 0- name.startsWith(q) -> 1- name.split(' ').any { it.startsWith(q) } -> 2- name.contains(q) -> 3- else -> 4- }- }- return apps.sortedWith(compareBy({ score(it) }, { it.name.lowercase() }))- }+ /** See [SearchRanking]: exact and prefix hits first, and nothing that answers no word. */+ private fun rank(apps: List<UnifiedApp>, query: String): List<UnifiedApp> =+ SearchRanking.rank(apps, query) { it.searchCandidate() } // --- Detail -----------------------------------------------------------------------
appstore/src/test/java/com/vayunmathur/appstore/domain/SearchRankingTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/domain/SearchRankingTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/domain/SearchRankingTest.ktnew file mode 100644index 0000000000..1047d27053--- /dev/null+++ b/appstore/src/test/java/com/vayunmathur/appstore/domain/SearchRankingTest.kt@@ -0,0 +1,103 @@+package com.vayunmathur.appstore.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Issue #595's two reported queries, held as the acceptance test.+ *+ * The candidate lists are what the reporter said the store showed them: "Google Maps"+ * returned Facebook, GMaps WV, Messenger, Netflix and Snapchat, and "chase mobile"+ * returned nothing at all.+ */+class SearchRankingTest {++ private fun app(+ name: String,+ packageName: String,+ author: String = "",+ summary: String = "",+ popularity: Long = 0L,+ ) = SearchRanking.Candidate(name, packageName, author, summary, popularity)++ private fun names(results: List<SearchRanking.Candidate>) = results.map { it.name }++ private fun rank(items: List<SearchRanking.Candidate>, query: String) =+ SearchRanking.rank(items, query) { it }++ private val playResultsForGoogleMaps = listOf(+ app("Facebook", "com.facebook.katana", "Meta Platforms", popularity = 5_000_000_000),+ app("GMaps WV", "com.gmapswv", "Divested Computing", "Google Maps in a WebView"),+ app("Messenger", "com.facebook.orca", "Meta Platforms", popularity = 4_000_000_000),+ app("Netflix", "com.netflix.mediaclient", "Netflix, Inc.", popularity = 1_000_000_000),+ app("Snapchat", "com.snapchat.android", "Snap Inc.", popularity = 1_000_000_000),+ app("Google Maps", "com.google.android.apps.maps", "Google LLC", popularity = 10_000_000_000),+ )++ @Test+ fun `Google Maps is the first result and the unrelated apps are dropped`() {+ val ranked = rank(playResultsForGoogleMaps, "Google Maps")++ assertEquals("Google Maps", names(ranked).first())+ assertTrue("Facebook" !in names(ranked))+ assertTrue("Netflix" !in names(ranked))+ assertTrue("Snapchat" !in names(ranked))+ }++ @Test+ fun `a listing named Maps by Google still answers Google Maps`() {+ val ranked = rank(+ playResultsForGoogleMaps + app("Maps", "com.google.android.apps.maps2", "Google LLC"),+ "Google Maps",+ )++ assertTrue("Maps" in names(ranked))+ }++ @Test+ fun `chase mobile finds the app whose name it is`() {+ val results = listOf(+ app("Chase Mobile", "com.chase.sig.android", "JPMorgan Chase & Co.", popularity = 50_000_000),+ app("Chase Bank Locations", "com.locations.chase"),+ app("T-Mobile", "com.tmobile.pr.mytmobile", popularity = 100_000_000),+ )++ assertEquals("Chase Mobile", names(rank(results, "chase mobile")).first())+ }++ @Test+ fun `chase mobile falls back to partial matches rather than an empty screen`() {+ val results = listOf(+ app("Chase Bank", "com.chase.sig.android", "JPMorgan Chase & Co."),+ app("Netflix", "com.netflix.mediaclient"),+ )++ assertEquals(listOf("Chase Bank"), names(rank(results, "chase mobile")))+ }++ @Test+ fun `an exact name beats a more popular partial match`() {+ val results = listOf(+ app("Signal Booster", "com.example.booster", popularity = 9_000_000),+ app("Signal", "org.thoughtcrime.securesms", popularity = 100_000_000),+ )++ assertEquals("Signal", names(rank(results, "signal")).first())+ }++ @Test+ fun `a package name typed in full wins`() {+ val results = listOf(+ app("Maps Deluxe", "com.example.maps", popularity = 9_000_000),+ app("Organic Maps", "app.organicmaps"),+ )++ assertEquals("Organic Maps", names(rank(results, "app.organicmaps")).first())+ }++ @Test+ fun `a blank query is left alone`() {+ assertEquals(playResultsForGoogleMaps, rank(playResultsForGoogleMaps, " "))+ }+}