maps: add Google POI ratings/reviews/info (keyless)
- Commit
eee62f6efa16b4a1b92c5ce8fd347c176da618f6- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-16 20:59 UTC (3 months ago)
- Parents
e3f5e20
Diff
maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDataSource.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDataSource.kt b/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDataSource.ktnew file mode 100644index 0000000000..c8dc5d8d5a--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDataSource.kt@@ -0,0 +1,409 @@+package com.vayunmathur.maps.data.google++import com.vayunmathur.library.network.NetworkClient+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonNull+import java.math.BigInteger+import java.net.URLEncoder+import kotlin.math.atan2+import kotlin.math.cos+import kotlin.math.sin+import kotlin.math.sqrt++/**+ * Keyless Google Maps POI enrichment.+ *+ * Ported from Vela (github.com/PimpinPumpkin/Vela), which follows the NewPipe+ * model: the device calls the same undocumented google.com/maps web endpoints a+ * logged-out browser does — no API key, no Vela/first-party backend, no Play+ * Services. The request is a `pb` protobuf-ish string; the response is a+ * guard-prefixed, deeply nested *positional* JSON array (no field names). The+ * calibrated index paths ([Paths]) pull rating/reviews/hours/price/website/+ * photos/popular-times out of it.+ *+ * This is a scrape of a private endpoint, so it is inherently fragile:+ * - a Google-side reshape makes fields go null (paths rot) — every accessor+ * degrades to null instead of throwing, so the sheet keeps working;+ * - keyless responses are bot-degraded — popular times and the full photo+ * gallery are usually stripped, so those sections often just won't show.+ *+ * All network runs on [Dispatchers.IO]. Results are cached in a small bounded+ * in-memory LRU keyed by (name, lat, lon) so toggling a POI doesn't refetch.+ *+ * NOTE (on-device): the live scrape needs a device with network — it can't be+ * exercised at compile time. Session cookie warming relies on the platform+ * cookie handler; whether that persists across [NetworkClient] calls is a+ * device-verification item.+ */+object GooglePoiDataSource {++ // Endpoints (calibrated 2026-06, Vela). hl/gl pinned to en/us so the parser's+ // English status keywords line up with the response text.+ private const val SEARCH_ENDPOINT =+ "https://www.google.com/search?tbm=map&authuser=0&hl=en&gl=us"+ private const val REVIEWS_ENDPOINT =+ "https://www.google.com/maps/preview/review/listentitiesreviews?authuser=0&hl=en&gl=us"+ private const val SESSION_WARM_URL = "https://www.google.com/maps?hl=en&gl=us"++ // Browser-like identity. The endpoints authorise by referer + a normal+ // desktop UA rather than a key, so these headers ARE the credential.+ private const val USER_AGENT =+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " ++ "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"+ private val REQUEST_HEADERS = mapOf(+ "User-Agent" to USER_AGENT,+ "Accept-Language" to "en-US,en;q=0.9",+ "Referer" to "https://www.google.com/maps/",+ )++ // Reviews pb: feature id split into two unsigned-64 decimals (1y/2y); 2i/3i+ // page, 3e1 = most-relevant, 1s = any session token string.+ private const val REVIEWS_PB = "!1m2!1y{HIGH}!2y{LOW}!2m2!2i0!3i20!3e1!5m2!1smaps!7e81"++ /** Match radius: a scraped result must be within this of the OSM point to be+ * treated as the same place, else the enrichment is discarded (wrong match). */+ private const val MATCH_RADIUS_M = 250.0++ @Volatile private var sessionWarmed = false++ // Bounded LRU cache (access-ordered). Stores the resolved info OR null (a+ // negative cache entry) so a place with no Google match isn't retried on+ // every reselect. Guarded by `synchronized(cache)`.+ private data class Key(val name: String, val lat: Double, val lon: Double)+ private val cache = object : LinkedHashMap<Key, GooglePoiInfo?>(16, 0.75f, true) {+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Key, GooglePoiInfo?>) = size > 64+ }++ /**+ * Fetch enrichment for an OSM place identified by [name] at [lat],[lon].+ * Returns null when there's no confident Google match or the scrape fails —+ * callers treat null as "no enrichment available". Never throws.+ */+ suspend fun fetch(name: String, lat: Double, lon: Double): GooglePoiInfo? {+ if (name.isBlank()) return null+ val key = Key(name, lat, lon)+ synchronized(cache) { if (cache.containsKey(key)) return cache[key] }+ val info = runCatching { fetchUncached(name, lat, lon) }.getOrNull()+ synchronized(cache) { cache[key] = info }+ return info+ }++ private suspend fun fetchUncached(name: String, lat: Double, lon: Double): GooglePoiInfo? =+ withContext(Dispatchers.IO) {+ warmSession()+ val pb = buildSearchPb(name, lat, lon)+ val url = "$SEARCH_ENDPOINT&q=${name.enc()}&pb=${pb.enc()}"+ val body = get(url) ?: return@withContext null+ val root = GoogleResponse.parseOrNull(body) ?: return@withContext null+ val entry = pickEntry(root, lat, lon) ?: return@withContext null+ val base = parsePlace(entry) ?: return@withContext null+ // Reviews live behind a second RPC keyed on the feature id — fetch a+ // page best-effort once we have the id. No feature id → skip.+ val reviews = base.featureId?.let { fid ->+ runCatching { fetchReviews(fid) }.getOrDefault(emptyList())+ }.orEmpty()+ base.copy(reviews = reviews)+ }++ /**+ * Fetch a page of reviews for a Google feature id ("0xHIGH:0xLOW").+ * Best-effort: any failure or drift yields an empty list.+ */+ suspend fun fetchReviews(featureId: String): List<GoogleReview> = withContext(Dispatchers.IO) {+ val parts = featureId.split(":")+ if (parts.size != 2) return@withContext emptyList()+ val high = runCatching { BigInteger(parts[0].removePrefix("0x"), 16) }.getOrNull()+ ?: return@withContext emptyList()+ val low = runCatching { BigInteger(parts[1].removePrefix("0x"), 16) }.getOrNull()+ ?: return@withContext emptyList()+ val pb = REVIEWS_PB.replace("{HIGH}", high.toString()).replace("{LOW}", low.toString())+ val body = get("$REVIEWS_ENDPOINT&pb=${pb.enc()}") ?: return@withContext emptyList()+ val root = GoogleResponse.parseOrNull(body) ?: return@withContext emptyList()+ parseReviews(root)+ }++ // --- HTTP plumbing ------------------------------------------------------++ /**+ * One GET of the maps home page so the cookie jar (if the platform installs a+ * default CookieHandler) picks up Google's consent/NID cookies, after which+ * the data requests behave like one logged-out browser. Best-effort and+ * fire-once; failure never blocks a fetch.+ */+ private suspend fun warmSession() {+ if (sessionWarmed) return+ runCatching {+ NetworkClient.performRequest(+ url = SESSION_WARM_URL,+ headers = REQUEST_HEADERS + ("Accept" to "text/html,application/xhtml+xml"),+ useSystemTrust = true,+ )+ }+ sessionWarmed = true+ }++ /** GET returning the body text, or null on any non-2xx / transport error.+ * `useSystemTrust` because google.com is an arbitrary external host, not one+ * of the app's pinned first-party endpoints. */+ private suspend fun get(url: String): String? {+ val resp = runCatching {+ NetworkClient.performRequest(url = url, headers = REQUEST_HEADERS, useSystemTrust = true)+ }.getOrNull() ?: return null+ return if (resp.isSuccess) resp.body else null+ }++ // --- result selection + parsing ----------------------------------------++ /**+ * Pick the result entry that matches the OSM point. Results come back either+ * as a list at [Paths.RESULTS] or as a single geocoded node at+ * [Paths.SINGLE] (wrapped so its place node lands at entry[1], matching a+ * list entry). Among list entries we take the nearest within [MATCH_RADIUS_M],+ * so a category-y response doesn't graft a neighbour's data onto this place.+ */+ private fun pickEntry(root: JsonElement, lat: Double, lon: Double): JsonElement? {+ val list = root.at(*Paths.RESULTS).arr()+ if (list != null && list.isNotEmpty()) {+ val best = list+ .mapNotNull { e ->+ val plat = e.at(*Paths.LAT).dbl() ?: return@mapNotNull null+ val plng = e.at(*Paths.LNG).dbl() ?: return@mapNotNull null+ e to haversine(lat, lon, plat, plng)+ }+ .minByOrNull { it.second }+ if (best != null && best.second <= MATCH_RADIUS_M) return best.first+ // No close match, but a specific-name search often returns exactly one+ // focused result — accept a lone entry regardless of distance.+ if (list.size == 1) return list.first()+ return null+ }+ // Single geocoded node → wrap as [null, node] so the entry-relative paths+ // (place node at [1]) resolve unchanged.+ val node = root.at(*Paths.SINGLE) ?: return null+ val wrapped = JsonArray(listOf(JsonNull, node))+ return if (wrapped.at(*Paths.NAME).str() != null) wrapped else null+ }++ private fun parsePlace(entry: JsonElement): GooglePoiInfo? {+ entry.at(*Paths.NAME).str() ?: return null // gate: a real place node+ val rich = entry.at(*Paths.STATUS_RICH).str()+ val s118 = entry.at(*Paths.STATUS_118).str()+ val statusStr = rich ?: s118 ?: entry.at(*Paths.OPEN_STATUS).str()+ val priceText = entry.at(*Paths.PRICE_TEXT).str()+ val info = GooglePoiInfo(+ rating = entry.at(*Paths.RATING).dbl(),+ reviewCount = entry.at(*Paths.REVIEW_COUNT).int(),+ priceText = priceText,+ priceLevel = priceLevelOf(priceText),+ website = entry.at(*Paths.WEBSITE).str(),+ phone = entry.at(*Paths.PHONE).str(),+ openNow = parseOpenNow(statusStr),+ statusText = statusStr,+ category = entry.at(*Paths.CATEGORY).str(),+ editorialSummary = entry.at(*Paths.EDITORIAL).str()?.trim()?.ifBlank { null },+ featuredReview = entry.at(*Paths.FEATURED_REVIEW).str()?.trim()?.trim('"', '\u201C', '\u201D')?.ifBlank { null },+ hours = parseHours(entry, prefer118 = rich == null && s118 != null),+ photoUrls = parsePhotos(entry),+ popularTimes = parsePopularTimes(entry),+ featureId = entry.at(*Paths.FEATURE_ID).str(),+ )+ // Ignore an entry that carried nothing but a name (no signal to show).+ return if (info.isEmpty) null else info+ }++ /** Weekly hours — main-entity schedule ([Paths.HOURS_203]) first, falling+ * back to a department sub-schedule ([Paths.HOURS_118]); [prefer118] flips+ * the order when the displayed status itself came from the department block,+ * so table and status describe the same schedule. */+ private fun parseHours(entry: JsonElement, prefer118: Boolean): List<String> {+ val h203 = { readHours(entry.at(*Paths.HOURS_203)) }+ val h118 = { readHours(entry.at(*Paths.HOURS_118)) }+ return if (prefer118) h118().ifEmpty(h203) else h203().ifEmpty(h118)+ }++ private fun readHours(days: JsonElement?): List<String> {+ val arr = days.arr() ?: return emptyList()+ return arr.mapNotNull { day ->+ val name = day.at(0).str() ?: return@mapNotNull null+ val hrs = day.at(3).arr()?.mapNotNull { it.at(0).str()?.ifBlank { null } }+ ?.joinToString(", ")?.ifBlank { null } ?: return@mapNotNull null+ val note = day.at(6, 1).str()?.ifBlank { null }+ if (note != null) "$name: $hrs \u00B7 $note" else "$name: $hrs"+ }+ }++ /** Business photos. Google gutted the keyless preview to a single hero photo+ * (served duplicated → de-dup); big places carry a small extra gallery+ * preview. The full gallery is login-gated. De-dup by the resized URL. */+ private fun parsePhotos(entry: JsonElement): List<String> {+ val urls = LinkedHashSet<String>()+ fun add(u: String?) {+ if (u != null && u.contains("googleusercontent"))+ urls += u.replace(Regex("=w\\d+-h\\d+.*$"), "=w500-h350")+ }+ entry.at(*Paths.PHOTOS).arr()?.forEach { add(it.at(6, 0).str()) }+ entry.at(1, 204, 0).arr()?.forEach { add(it.at(1, 2, 0, 0).str()) }+ return urls.take(12)+ }++ /** Popular-times histogram. Usually stripped on a keyless response (returns+ * null and the section just doesn't render). */+ private fun parsePopularTimes(entry: JsonElement): PoiPopularTimes? {+ val days = entry.at(*Paths.POPULAR_TIMES).at(0).arr() ?: return null+ val parsed = days.mapNotNull { d ->+ val dow = d.at(0).int() ?: return@mapNotNull null+ val hours = d.at(1).arr().orEmpty().mapNotNull { h ->+ val hour = h.at(0).int() ?: return@mapNotNull null+ val occ = h.at(1).int() ?: return@mapNotNull null+ PoiHourBusyness(hour, occ)+ }+ if (hours.isEmpty()) null else PoiDayBusyness(dow, hours)+ }+ return if (parsed.isEmpty()) null else PoiPopularTimes(parsed)+ }++ private fun parseReviews(root: JsonElement): List<GoogleReview> {+ val arr = root.at(2).arr() ?: return emptyList()+ return arr.mapNotNull { rv ->+ val author = rv.at(0, 1).str() ?: return@mapNotNull null+ GoogleReview(+ author = author,+ authorPhoto = rv.at(0, 2).str(),+ rating = rv.at(4).int() ?: 0,+ relativeTime = rv.at(1).str(),+ text = rv.at(3).str()?.ifBlank { null },+ photos = reviewPhotos(rv),+ )+ }+ }++ private fun reviewPhotos(review: JsonElement?): List<String> {+ review ?: return emptyList()+ val urls = LinkedHashSet<String>()+ fun walk(x: JsonElement?) {+ when (x) {+ is JsonArray -> x.forEach(::walk)+ else -> x.str()?.let { s -> if (isUploadedPhoto(s)) urls.add(resizeReviewPhoto(s)) }+ }+ }+ walk(review)+ return urls.toList().take(10)+ }++ private fun isUploadedPhoto(u: String): Boolean {+ if (!u.startsWith("http")) return false+ if (!u.contains("googleusercontent.com/") && !u.contains("ggpht.com/")) return false+ if (AVATAR_PATH.containsMatchIn(u) || u.contains("ACg8oc") || u.contains("ALV-")) return false+ return u.contains("/gps-cs") || u.contains("/geougc") ||+ u.contains("/p/AF1Qip") || u.contains("googleusercontent.com/p/")+ }++ private fun resizeReviewPhoto(u: String): String =+ u.replace(Regex("=[swh]\\d[\\w-]*$"), "") + "=w400-h400"++ private val AVATAR_PATH = Regex("/a-?/")++ // --- small helpers ------------------------------------------------------++ /** Derive a 1..4 price level from Google's label ("$10–20"→2), or the count+ * of '$' for the symbol style ("$$"→2). Null when there's no price. */+ private fun priceLevelOf(text: String?): Int? {+ if (text.isNullOrBlank()) return null+ Regex("\\d+").find(text)?.value?.toIntOrNull()?.let { low ->+ return when {+ low < 10 -> 1+ low < 20 -> 2+ low < 35 -> 3+ else -> 4+ }+ }+ return text.count { it == '$' }.takeIf { it in 1..4 }+ }++ /** Open/closed from the English status text (hl=en pins the language). Closed+ * words are matched first — several are prefix-cousins of the open form. */+ private val CLOSED_WORDS = listOf("Closed", "Opens", "Opening", "Temporarily", "Permanently")+ private val OPEN_WORDS = listOf("Open", "Closes", "Closing")+ private fun parseOpenNow(status: String?): Boolean? {+ val s = status?.trim()?.ifBlank { null } ?: return null+ return when {+ CLOSED_WORDS.any { s.startsWith(it) } -> false+ OPEN_WORDS.any { s.startsWith(it) } -> true+ else -> null+ }+ }++ private fun String.enc(): String = URLEncoder.encode(this, "UTF-8")++ private fun haversine(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {+ val r = 6_371_000.0+ val dLat = Math.toRadians(lat2 - lat1)+ val dLon = Math.toRadians(lon2 - lon1)+ val a = sin(dLat / 2) * sin(dLat / 2) ++ cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) * sin(dLon / 2) * sin(dLon / 2)+ return r * 2 * atan2(sqrt(a), sqrt(1 - a))+ }++ /** Build the search `pb`. Calibrated template (Vela, 2026-06): a plain `q=`+ * returns an empty envelope, so search needs this full pb, and results are+ * viewport-driven (the `!2d<lng>!3d<lat>` block is the OSM point). */+ private fun buildSearchPb(query: String, lat: Double, lon: Double): String =+ SEARCH_PB_TEMPLATE+ .replace("{QUERY}", query.replace('!', ' ').trim())+ .replace("{LNG}", lon.toString())+ .replace("{LAT}", lat.toString())++ private const val SEARCH_PB_TEMPLATE =+ "!1s{QUERY}!4m8!1m3!1d25229.167291701906!2d{LNG}!3d{LAT}!3m2!1i1024!2i768!4f13.1!7i20" ++ "!10b1!12m52!1m5!18b1!30b1!31m1!1b1!34e1!2m4!5m1!6e2!20e3!39b1!6m25!32i1!49b1!63m0!66b1" ++ "!85b1!114b1!149b1!206b1!209b1!212b1!216b1!222b1!223b1!232b1!234b1!235b1!244b1!246b1" ++ "!250b1!253b1!260b1!266b1!273b1!281b1!291m0!10b1!12b1!13b1!14b1!16b1!17m1!3e1!20m3!5e2" ++ "!6b1!14b1!46m1!1b0!96b1!99b1!19m4!2m3!1i360!2i120!4i8!20m57!2m2!1i203!2i100!3m2!2i4!5b1" ++ "!6m6!1m2!1i86!2i86!1m2!1i408!2i240!7m33!1m3!1e1!2b0!3e3!1m3!1e2!2b1!3e2!1m3!1e2!2b0!3e3" ++ "!1m3!1e8!2b0!3e3!1m3!1e10!2b0!3e3!1m3!1e10!2b1!3e2!1m3!1e10!2b0!3e4!1m3!1e9!2b1!3e2!2b1" ++ "!9b0!15m8!1m7!1m2!1m1!1e2!2m2!1i195!2i195!3i20!15i9937!24m107!1m25!13m9!2b1!3b1!4b1!6i1" ++ "!8b1!9b1!14b1!20b1!25b1!18m14!3b1!4b1!5b1!6b1!13b1!14b1!17b1!21b1!22b1!32b1!33m1!1b1" ++ "!34b1!36e2!10m1!8e3!11m1!3e1!17b1!20m2!1e3!1e6!24b1!25b1!26b1!27b1!29b1!30m1!2b1!36b1" ++ "!37b1!39m3!2m2!2i1!3i1!43b1!52b1!54m1!1b1!55b1!56m1!1b1!61m2!1m1!1e1!65m5!3m4!1m3!1m2" ++ "!1i224!2i298!72m22!1m8!2b1!5b1!7b1!12m4!1b1!2b1!4m1!1e1!4b1!8m10!1m6!4m1!1e1!4m1!1e3" ++ "!4m1!1e4!3sother_user_google_review_posts__and__hotel_and_vr_partner_review_posts!6m1" ++ "!1e1!9b1!89b1!90m2!1m1!1e2!98m3!1b1!2b1!3b1!103b1!113b1!114m3!1b1!2m1!1b1!117b1!122m1" ++ "!1b1!126b1!127b1!128m1!1b0!26m4!2m3!1i80!2i92!4i8!30m28!1m6!1m2!1i0!2i0!2m2!1i530!2i768" ++ "!1m6!1m2!1i974!2i0!2m2!1i1024!2i768!1m6!1m2!1i0!2i0!2m2!1i1024!2i20!1m6!1m2!1i0!2i748" ++ "!2m2!1i1024!2i768!34m19!2b1!3b1!4b1!6b1!8m6!1b1!3b1!4b1!5b1!6b1!7b1!9b1!12b1!14b1!20b1" ++ "!23b1!25b1!26b1!31b1!37m1!1e81!42b1!49m10!3b1!6m2!1b1!2b1!7m2!1e3!2b1!8b1!9b1!10e2!50m3" ++ "!2e2!3m1!3b1!61b1!67m5!7b1!10b1!14b1!15m1!1b0!69i782!77b1"++ /**+ * Calibrated positional field-index paths (Vela DEFAULT_PATHS, 2026-06),+ * relative to a result *entry* whose place node is `[1]` (RESULTS/SINGLE are+ * relative to the response root). A Google reshape moves these; when that+ * happens each accessor returns null and the affected field simply drops out.+ */+ private object Paths {+ val RESULTS = intArrayOf(64)+ val SINGLE = intArrayOf(0, 1, 0, 14)+ val NAME = intArrayOf(1, 11)+ val LAT = intArrayOf(1, 9, 2)+ val LNG = intArrayOf(1, 9, 3)+ val CATEGORY = intArrayOf(1, 13, 0)+ val RATING = intArrayOf(1, 4, 7)+ val REVIEW_COUNT = intArrayOf(1, 4, 8)+ val PRICE_TEXT = intArrayOf(1, 4, 2)+ val WEBSITE = intArrayOf(1, 7, 0)+ val PHONE = intArrayOf(1, 178, 0, 0)+ val FEATURE_ID = intArrayOf(1, 10)+ val PHOTOS = intArrayOf(1, 72, 0)+ val FEATURED_REVIEW = intArrayOf(1, 142, 1, 0, 1, 0, 0)+ val EDITORIAL = intArrayOf(1, 32, 1, 1)+ val OPEN_STATUS = intArrayOf(1, 203, 1, 8, 0)+ val STATUS_RICH = intArrayOf(1, 203, 1, 4, 0)+ val STATUS_118 = intArrayOf(1, 118, 0, 3, 1, 4, 0)+ val HOURS_203 = intArrayOf(1, 203, 0)+ val HOURS_118 = intArrayOf(1, 118, 0, 3, 0)+ val POPULAR_TIMES = intArrayOf(1, 84)+ }+}
maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiModels.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiModels.kt b/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiModels.ktnew file mode 100644index 0000000000..33c00f26f9--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiModels.kt@@ -0,0 +1,55 @@+package com.vayunmathur.maps.data.google++/**+ * Clean, null-safe model of the POI enrichment scraped from Google Maps' keyless+ * web endpoints. Every field is nullable/optional because no single response+ * fills all of them (a keyless response is bot-degraded — popular times and the+ * full photo gallery are usually stripped), and because the scrape is fragile:+ * a Google-side reshape makes individual fields go null while the rest survive.+ *+ * The feature degrades gracefully — a section simply doesn't render when its+ * field is empty — and the parse never throws.+ */+data class GooglePoiInfo(+ val rating: Double? = null,+ val reviewCount: Int? = null,+ val priceText: String? = null, // Google's own label, e.g. "$10–20" / "$$"+ val priceLevel: Int? = null, // derived 1..4+ val website: String? = null,+ val phone: String? = null,+ val openNow: Boolean? = null,+ val statusText: String? = null, // e.g. "Open · Closes 9 PM"+ val category: String? = null,+ val editorialSummary: String? = null,+ val featuredReview: String? = null,+ val hours: List<String> = emptyList(), // 7 day strings, "Monday: 9 AM–5 PM"+ val photoUrls: List<String> = emptyList(), // FIFE image URLs, resized for thumbnails+ val reviews: List<GoogleReview> = emptyList(),+ val popularTimes: PoiPopularTimes? = null,+ val featureId: String? = null, // "0x..:0x.." → reviews RPC+) {+ /** True when nothing worth showing came back — the UI shows no enrichment. */+ val isEmpty: Boolean+ get() = rating == null && reviewCount == null && priceText == null && website == null &&+ phone == null && statusText == null && editorialSummary == null && featuredReview == null &&+ hours.isEmpty() && photoUrls.isEmpty() && reviews.isEmpty() && popularTimes == null+}++/** A single user review. [rating] is 1..5; [text] is null for rating-only reviews. */+data class GoogleReview(+ val author: String,+ val authorPhoto: String?,+ val rating: Int,+ val relativeTime: String?,+ val text: String?,+ val photos: List<String> = emptyList(),+)++/** Google's "popular times": a typical-busyness histogram per day of the week. */+data class PoiPopularTimes(val days: List<PoiDayBusyness>)++/** One day: [dayOfWeek] is 1=Mon … 7=Sun; [hours] are the busyness buckets. */+data class PoiDayBusyness(val dayOfWeek: Int, val hours: List<PoiHourBusyness>)++/** [hour] is 0..23; [occupancy] is the typical busyness 0..100. */+data class PoiHourBusyness(val hour: Int, val occupancy: Int)
maps/src/main/java/com/vayunmathur/maps/data/google/GoogleResponse.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/google/GoogleResponse.kt b/maps/src/main/java/com/vayunmathur/maps/data/google/GoogleResponse.ktnew file mode 100644index 0000000000..7b641de9c7--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/data/google/GoogleResponse.kt@@ -0,0 +1,55 @@+package com.vayunmathur.maps.data.google++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.doubleOrNull+import kotlinx.serialization.json.intOrNull+import kotlinx.serialization.json.longOrNull++/**+ * Google's map XHR responses begin with an XSSI guard (`)]}'` then a newline) and+ * then a deeply nested *positional* JSON array — no field names anywhere. This+ * object strips the guard and parses; the extension functions below give+ * null-safe positional access so a missing/reordered index returns null instead+ * of throwing.+ *+ * That defensiveness is the whole game: this is a keyless scrape of a private,+ * undocumented endpoint. Google inserts elements mid-array without notice and a+ * hard-coded `[0][1][3]` path silently rots — so every access degrades to null+ * and the enrichment feature just disappears rather than crashing the sheet.+ *+ * Ported from Vela's GoogleResponse (calibrated against maps.google.com 2026-06).+ */+internal object GoogleResponse {+ private val json = Json { ignoreUnknownKeys = true; isLenient = true }++ private val GUARDS = listOf(")]}'\n", ")]}',\n", ")]}'", ")]}", "while(1);", "for(;;);")++ fun strip(body: String): String {+ for (g in GUARDS) if (body.startsWith(g)) return body.substring(g.length).trimStart('\n', '\r')+ return body+ }++ /** Strip the guard and parse to a JSON tree. Returns null on any malformed body. */+ fun parseOrNull(body: String): JsonElement? =+ runCatching { json.parseToJsonElement(strip(body)) }.getOrNull()+}++/** Walk a positional path; any wrong/missing step yields null rather than throwing. */+internal fun JsonElement?.at(vararg path: Int): JsonElement? {+ var cur: JsonElement? = this+ for (i in path) {+ val arr = cur as? JsonArray ?: return null+ cur = arr.getOrNull(i)+ }+ return cur+}++internal fun JsonElement?.arr(): JsonArray? = this as? JsonArray+internal fun JsonElement?.str(): String? = (this as? JsonPrimitive)?.contentOrNull+internal fun JsonElement?.dbl(): Double? = (this as? JsonPrimitive)?.doubleOrNull+internal fun JsonElement?.int(): Int? = (this as? JsonPrimitive)?.intOrNull+internal fun JsonElement?.long(): Long? = (this as? JsonPrimitive)?.longOrNull
maps/src/main/java/com/vayunmathur/maps/ui/PoiEnrichment.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/PoiEnrichment.kt b/maps/src/main/java/com/vayunmathur/maps/ui/PoiEnrichment.ktnew file mode 100644index 0000000000..e3b273d846--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/PoiEnrichment.kt@@ -0,0 +1,223 @@+package com.vayunmathur.maps.ui++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.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+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.shape.CircleShape+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.Color+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontStyle+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.IconInfo+import com.vayunmathur.library.ui.IconPhotoLibrary+import com.vayunmathur.library.ui.IconSchedule+import com.vayunmathur.library.ui.IconStar+import com.vayunmathur.library.ui.IconStarBorder+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.ListItemDefaults+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.firstLetterUppercase+import com.vayunmathur.maps.R+import com.vayunmathur.maps.data.google.GooglePoiInfo+import com.vayunmathur.maps.data.google.GoogleReview+import com.vayunmathur.maps.data.google.PoiPopularTimes+import kotlinx.datetime.TimeZone+import kotlinx.datetime.isoDayNumber+import kotlinx.datetime.toLocalDateTime+import kotlin.time.Clock++/**+ * Renders the keyless Google Maps POI enrichment under a place's OSM details.+ *+ * Every section is conditional on its data being present — a keyless response is+ * bot-degraded (popular times and the full photo gallery are usually stripped)+ * and the scrape is fragile (a Google reshape nulls individual fields), so this+ * shows whatever came back and silently omits the rest. Nothing here can throw.+ *+ * Performance: photos are a horizontally-lazy [LazyRow] of async-loaded images;+ * reviews are capped to a handful (this sits inside the draggable bottom sheet,+ * which handles its own vertical scroll — no nested vertical LazyColumn).+ */+@Composable+fun GooglePoiEnrichment(info: GooglePoiInfo, hasOsmHours: Boolean) {+ if (info.isEmpty) return+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ // Price · category subtitle (rating itself is shown by the caller's header).+ val subtitle = listOfNotNull(info.priceText?.ifBlank { null }, info.category?.ifBlank { null })+ .joinToString(" \u00B7 ")+ if (subtitle.isNotBlank()) {+ Text(subtitle, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)+ }++ info.editorialSummary?.let {+ Text(it, style = MaterialTheme.typography.bodyMedium, fontStyle = FontStyle.Italic, maxLines = 3)+ }++ // Google's weekly hours — only when OSM didn't already provide them, to+ // avoid showing the same schedule twice.+ if (!hasOsmHours && info.hours.isNotEmpty()) {+ SectionHeader(stringResource(R.string.poi_hours_header)) { IconSchedule() }+ Card {+ Column {+ info.hours.forEach { line ->+ val day = line.substringBefore(':', "").trim()+ val hours = line.substringAfter(':', line).trim()+ ListItem(+ { Text(day.firstLetterUppercase()) },+ leadingContent = {},+ trailingContent = { Text(hours) },+ colors = ListItemDefaults.colors(Color.Transparent),+ )+ }+ }+ }+ }++ if (info.photoUrls.isNotEmpty()) {+ SectionHeader(stringResource(R.string.poi_photos_header)) { IconPhotoLibrary() }+ LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ items(info.photoUrls) { url ->+ AsyncImage(+ model = url,+ contentDescription = stringResource(R.string.poi_photo_description),+ modifier = Modifier+ .size(width = 160.dp, height = 120.dp)+ .clip(RoundedCornerShape(12.dp)),+ contentScale = ContentScale.Crop,+ )+ }+ }+ }++ info.popularTimes?.let { PopularTimesSection(it) }++ if (info.reviews.isNotEmpty()) {+ SectionHeader(stringResource(R.string.poi_reviews_header)) { IconStar() }+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ info.reviews.take(5).forEach { ReviewCard(it) }+ }+ } else info.featuredReview?.let {+ SectionHeader(stringResource(R.string.poi_reviews_header)) { IconStar() }+ Card {+ Text(+ "\u201C$it\u201D",+ Modifier.padding(12.dp),+ style = MaterialTheme.typography.bodyMedium,+ fontStyle = FontStyle.Italic,+ maxLines = 4,+ )+ }+ }++ // Trademark attribution ("Google Maps" is non-translatable, see strings.xml).+ Text(+ stringResource(R.string.poi_google_attribution),+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+}++@Composable+private fun SectionHeader(title: String, icon: @Composable () -> Unit) {+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ icon()+ Text(title, style = MaterialTheme.typography.titleMedium)+ }+}++@Composable+private fun ReviewCard(review: GoogleReview) {+ Card {+ Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ review.authorPhoto?.let {+ AsyncImage(+ model = it,+ contentDescription = stringResource(R.string.poi_reviewer_photo_description),+ modifier = Modifier.size(32.dp).clip(CircleShape),+ contentScale = ContentScale.Crop,+ )+ }+ Column {+ Text(review.author, style = MaterialTheme.typography.bodyMedium, maxLines = 1)+ review.relativeTime?.let {+ Text(it, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+ }+ }+ }+ if (review.rating in 1..5) RatingStars(review.rating)+ review.text?.let {+ Text(it, style = MaterialTheme.typography.bodyMedium, maxLines = 6)+ }+ if (review.photos.isNotEmpty()) {+ LazyRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ items(review.photos) { url ->+ AsyncImage(+ model = url,+ contentDescription = stringResource(R.string.poi_photo_description),+ modifier = Modifier.size(72.dp).clip(RoundedCornerShape(8.dp)),+ contentScale = ContentScale.Crop,+ )+ }+ }+ }+ }+ }+}++@Composable+private fun RatingStars(rating: Int) {+ Row {+ repeat(5) { i ->+ if (i < rating) IconStar(Modifier.size(16.dp), tint = MaterialTheme.colorScheme.tertiary)+ else IconStarBorder(Modifier.size(16.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant)+ }+ }+}++@Composable+private fun PopularTimesSection(popularTimes: PoiPopularTimes) {+ // Show today's histogram (falling back to the first day Google returned).+ val todayDow = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date.dayOfWeek.isoDayNumber+ val day = popularTimes.days.firstOrNull { it.dayOfWeek == todayDow } ?: popularTimes.days.firstOrNull() ?: return+ if (day.hours.isEmpty()) return+ SectionHeader(stringResource(R.string.poi_popular_times_header)) { IconInfo() }+ Card {+ Row(+ Modifier.fillMaxWidth().height(72.dp).padding(12.dp),+ verticalAlignment = Alignment.Bottom,+ horizontalArrangement = Arrangement.spacedBy(2.dp),+ ) {+ day.hours.forEach { h ->+ val frac = (h.occupancy.coerceIn(0, 100)) / 100f+ Box(+ Modifier+ .weight(1f)+ .height((4 + (44 * frac)).dp)+ .clip(RoundedCornerShape(2.dp))+ .background(MaterialTheme.colorScheme.primary),+ )+ }+ }+ }+}
maps/src/main/java/com/vayunmathur/maps/ui/RestaurantBottomSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantBottomSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantBottomSheet.ktindex 092aa8ae0f..4a403d9643 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantBottomSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantBottomSheet.kt@@ -60,7 +60,7 @@ fun goto(context: Context, uri: String) { @Composable fun RestaurantBottomSheet(viewModel: SelectedFeatureViewModel, inactiveNavigation: SpecificFeature.Route?, feature: SpecificFeature.Restaurant, requestDirections: () -> Unit) {- val reviews by viewModel.currentReviews.collectAsState()+ val poi by viewModel.currentPoiInfo.collectAsState() val context = LocalContext.current Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Row(verticalAlignment = Alignment.CenterVertically) {@@ -69,8 +69,8 @@ fun RestaurantBottomSheet(viewModel: SelectedFeatureViewModel, inactiveNavigatio feature.name, style = MaterialTheme.typography.titleLarge, )- }, supportingContent = reviews?.let { reviews ->- { Text(stringResource(R.string.reviews_summary, reviews.rating, reviews.userRatingCount)) }+ }, supportingContent = poi?.takeIf { it.rating != null }?.let { info ->+ { Text(stringResource(R.string.reviews_summary, info.rating!!, info.reviewCount ?: 0)) } }, trailingContent = { Button({requestDirections()}) { if(inactiveNavigation == null) {@@ -137,12 +137,13 @@ fun RestaurantBottomSheet(viewModel: SelectedFeatureViewModel, inactiveNavigatio feature.phone?.let { RestaurantItem({ IconCall() }, it) { goto(context, "tel:$it") } }+ poi?.let { GooglePoiEnrichment(it, hasOsmHours = feature.openingHours != null) } } } @Composable fun RestaurantBottomSheet(viewModel: SelectedFeatureViewModel, inactiveNavigation: SpecificFeature.Route?, feature: SpecificFeature.GenericPlace, requestDirections: () -> Unit) {- val reviews by viewModel.currentReviews.collectAsState()+ val poi by viewModel.currentPoiInfo.collectAsState() val context = LocalContext.current Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Row(verticalAlignment = Alignment.CenterVertically) {@@ -151,8 +152,8 @@ fun RestaurantBottomSheet(viewModel: SelectedFeatureViewModel, inactiveNavigatio feature.name, style = MaterialTheme.typography.titleLarge, )- }, supportingContent = reviews?.let { reviews ->- { Text(stringResource(R.string.reviews_summary, reviews.rating, reviews.userRatingCount)) }+ }, supportingContent = poi?.takeIf { it.rating != null }?.let { info ->+ { Text(stringResource(R.string.reviews_summary, info.rating!!, info.reviewCount ?: 0)) } }, trailingContent = { Button({requestDirections()}) { if(inactiveNavigation == null) {@@ -213,6 +214,7 @@ fun RestaurantBottomSheet(viewModel: SelectedFeatureViewModel, inactiveNavigatio feature.phone?.let { RestaurantItem({ IconCall() }, it) { goto(context, "tel:$it") } }+ poi?.let { GooglePoiEnrichment(it, hasOsmHours = feature.openingHours != null) } } }
maps/src/main/java/com/vayunmathur/maps/util/Reviews.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/Reviews.kt b/maps/src/main/java/com/vayunmathur/maps/util/Reviews.ktdeleted file mode 100644index 408911f151..0000000000--- a/maps/src/main/java/com/vayunmathur/maps/util/Reviews.kt+++ /dev/null@@ -1,56 +0,0 @@-package com.vayunmathur.maps.util-import com.vayunmathur.library.network.NetworkClient-import kotlinx.serialization.Serializable--@Serializable-data class PlaceMatchRequest(val name: String, val lat: Double, val lon: Double)--@Serializable-data class PlaceIdResponse(val id: String)--@Serializable-data class PlaceRatingRequest(val id: String)--@Serializable-data class PlaceRatingResponse(val rating: Float, val userRatingCount: Int)--@Serializable-data class FullPlaceInfo(val id: String, val rating: Float, val userRatingCount: Int)--object Reviews {- private const val BASE_URL = "https://api.vayunmathur.com"-- /**- * Chained call: 1. Match OSM data to Google ID -> 2. Get Stars from ID- */- suspend fun getRatingForOsmLocation(name: String, lat: Double, lon: Double): FullPlaceInfo? {- return try {- // Step 1: Get the Google Place ID from your server- val idResponse: PlaceIdResponse = NetworkClient.callJson(- url = "$BASE_URL/maps/place_match",- method = "POST",- headers = mapOf("Content-Type" to "application/json"),- body = PlaceMatchRequest(name, lat, lon)- )-- val placeId = idResponse.id-- // Step 2: Get the Rating using that ID- val ratingResponse: PlaceRatingResponse = NetworkClient.callJson(- url = "$BASE_URL/maps/place_rating",- method = "POST",- headers = mapOf("Content-Type" to "application/json"),- body = PlaceRatingRequest(placeId)- )-- FullPlaceInfo(- id = placeId,- rating = ratingResponse.rating,- userRatingCount = ratingResponse.userRatingCount- )- } catch (e: Exception) {- e.printStackTrace()- null // Handle errors or 404s gracefully- }- }-}
maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.ktindex 90bc72f7ad..0b924b5cbf 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt@@ -4,6 +4,8 @@ import android.hardware.SensorManager import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.data.google.GooglePoiDataSource+import com.vayunmathur.maps.data.google.GooglePoiInfo import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.*@@ -29,15 +31,6 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli val locationManager = FrameworkLocationManager(application) - // Small cache of reviews keyed by (name, lat, lon) to avoid refetching the- // same place when the user toggles back and forth. Bounded to cap memory.- private data class ReviewKey(val name: String, val lat: Double, val lon: Double)- private val reviewsCache = object : LinkedHashMap<ReviewKey, FullPlaceInfo?>(16, 0.75f, true) {- override fun removeEldestEntry(- eldest: MutableMap.MutableEntry<ReviewKey, FullPlaceInfo?>- ): Boolean = size > 32- }- init { locationManager.startUpdates( onUpdateReceived = { position, bearing ->@@ -65,26 +58,24 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli } /**- * Reviews for the currently selected restaurant or generic place. Emits null- * for other feature types or while the network call is in flight. Cancels- * the in-flight fetch when the selection changes.+ * Keyless Google Maps enrichment (rating, reviews, hours, photos, price,+ * popular times, …) for the currently selected restaurant or generic place.+ * Emits null for other feature types and while the network scrape is in+ * flight; cancels the in-flight fetch when the selection changes.+ * [GooglePoiDataSource] caches and does its own IO, so a re-select is instant. */ @OptIn(ExperimentalCoroutinesApi::class)- val currentReviews: StateFlow<FullPlaceInfo?> = selectedFeature+ val currentPoiInfo: StateFlow<GooglePoiInfo?> = selectedFeature .flatMapLatest { feature -> val (name, pos) = when (feature) { is SpecificFeature.Restaurant -> feature.name to feature.position is SpecificFeature.GenericPlace -> feature.name to feature.position else -> return@flatMapLatest flowOf(null) }- val key = ReviewKey(name, pos.latitude, pos.longitude)- val cached: FullPlaceInfo? = synchronized(reviewsCache) { reviewsCache[key] }- if (cached != null) return@flatMapLatest flowOf(cached)+ if (name.isBlank()) return@flatMapLatest flowOf(null) flow { emit(null)- val info = Reviews.getRatingForOsmLocation(name, pos.latitude, pos.longitude)- synchronized(reviewsCache) { reviewsCache[key] = info }- emit(info)+ emit(GooglePoiDataSource.fetch(name, pos.latitude, pos.longitude)) }.flowOn(Dispatchers.IO) } .stateIn(
maps/src/main/res/values/strings.xml
diff --git a/maps/src/main/res/values/strings.xml b/maps/src/main/res/values/strings.xmlindex 0d2a8af49d..6794695ecf 100644--- a/maps/src/main/res/values/strings.xml+++ b/maps/src/main/res/values/strings.xml@@ -51,6 +51,24 @@ <!-- Place detail: Rating summary. %1$s=stars e.g. "4.5", %2$s=review count e.g. "128" --> <string name="reviews_summary"><xliff:g id="rating" example="4.5">%1$s</xliff:g> stars | <xliff:g id="review_count" example="128">%2$s</xliff:g> reviews</string>++ <!-- Place detail: Attribution for scraped POI enrichment. "Google Maps" is a product+ trademark and must not be translated. -->+ <string name="poi_google_attribution" translatable="false">Data from Google Maps</string>+ <!-- Place detail: Photos section header. Noun. -->+ <string name="poi_photos_header">Photos</string>+ <!-- Place detail: Reviews section header. Noun. -->+ <string name="poi_reviews_header">Reviews</string>+ <!-- Place detail: Popular times section header. Noun phrase. -->+ <string name="poi_popular_times_header">Popular times</string>+ <!-- Place detail: About/overview section header. Noun. -->+ <string name="poi_about_header">About</string>+ <!-- Place detail: Google hours section header. Noun. -->+ <string name="poi_hours_header">Hours</string>+ <!-- Place detail: Content description for a business photo thumbnail. -->+ <string name="poi_photo_description">Business photo</string>+ <!-- Place detail: Content description for a reviewer's profile picture. -->+ <string name="poi_reviewer_photo_description">Reviewer photo</string> <!-- Button: Get directions. Noun/Verb. --> <string name="directions">Directions</string> <!-- Button: Add selected place as stop on route -->