weather: self-hosted bundle cutover with on-device place search
- Commit
42a2b1e44a063c8ac53713d53cb5ec46a6016547- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-07 20:21 UTC (1 month ago)
- Parents
7e996a7
Diff
.gitignore
diff --git a/.gitignore b/.gitignoreindex 9d8359fa7f..ad4087af94 100644--- a/.gitignore+++ b/.gitignore@@ -64,6 +64,12 @@ health/src/main/assets/catalog.db health/src/main/assets/catalog.db.br health/src/main/assets/catalog.db.meta.json +# Built by scripts/generate_places_db.py from GeoNames cities1000. Same deal+# as the health catalogue: generated at build time, never committed.+weather/src/main/assets/places.db+weather/src/main/assets/places.db.br+weather/src/main/assets/places.db.meta.json+ # Compose preview screenshot rendering (common-conventions-preview-metadata). These PNGs # are an intermediate: the `metadata` task copies them into metadata_data/photos/<module>, # which is what is committed and what release.sh reads. Committing them too would store
scripts/generate_places_db.py
diff --git a/scripts/generate_places_db.py b/scripts/generate_places_db.pynew file mode 100644index 0000000000..3f06b15c32--- /dev/null+++ b/scripts/generate_places_db.py@@ -0,0 +1,256 @@+#!/usr/bin/env python3+"""Offline generator for the weather app's place-search catalogue.++The city search lets the user pick from real GeoNames places rather than+typing free text, so everything is compiled into the APK and no search+makes a network request at runtime - the downloads below happen here, at+build time, not on the device.++One output, handled like the health catalogue:++ weather/src/main/assets/places.db.br gitignored, plus a .meta.json++Source: GeoNames `cities1000` (places with population >= 1000, ~170k rows),+plus `admin1CodesASCII` and `countryInfo` for display names. The dump is+CC-BY 4.0 (https://www.geonames.org/about.html); attribution ships in the+app's about screen.++ https://download.geonames.org/export/dump/cities1000.zip+ https://download.geonames.org/export/dump/admin1CodesASCII.txt+ https://download.geonames.org/export/dump/countryInfo.txt++Schema mirrors the server's /wx/v1/search index byte-for-byte (same table+names, same FTS columns, same ranking SQL in GeoDatabase.kt), so results+match whether they come from the device or the server:++ places(id, name, asciiname, latitude, longitude, country_code,+ country_name, admin1, population, timezone)+ places_fts(name, asciiname, alternates) - hidden alias column like the+ health labs table: alternate names ("Bombay", "München" ASCII forms)+ are searchable but the display name stays canonical.++Ranking is exact-name, then prefix, then population, then bm25 - the same+ORDER BY as the server. Kept byte-for-byte in step with GeoDatabase.kt so+both resolve a query the same way.++Unlike `generate_food_db.py`, this ships a finished SQLite database rather+than a columnar file the app rebuilds. At ~170k rows the container and FTS+index cost little more than the data, and shipping the database directly+removes the whole on-device build step. Brotli, because the app already+links a decoder for it.++Usage+-----+ python3 scripts/generate_places_db.py # everything+ python3 scripts/generate_places_db.py --keep-db # keep unpacked SQLite+"""++from __future__ import annotations++import argparse+import json+import sqlite3+import subprocess+import sys+import zipfile+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parent.parent+ASSETS = REPO_ROOT / "weather" / "src" / "main" / "assets"++CITIES_URL = "https://download.geonames.org/export/dump/cities1000.zip"+ADMIN1_URL = "https://download.geonames.org/export/dump/admin1CodesASCII.txt"+COUNTRY_URL = "https://download.geonames.org/export/dump/countryInfo.txt"++CACHE_DIR = Path.home() / ".cache" / "geonames"+CACHED_CITIES = CACHE_DIR / "cities1000.zip"+CACHED_ADMIN1 = CACHE_DIR / "admin1CodesASCII.txt"+CACHED_COUNTRY = CACHE_DIR / "countryInfo.txt"++# Bumped in lockstep with SUPPORTED_SCHEMA_VERSION in GeoDatabase.kt.+SCHEMA_VERSION = 1+++def mb(n: int) -> str:+ return f"{n / 1_000_000:.1f} MB"+++def download(url: str, dest: Path) -> Path:+ """Fetch `url` to `dest`, skipping the download if it is already cached."""+ if dest.exists() and dest.stat().st_size > 0:+ print(f" cached {dest} ({mb(dest.stat().st_size)})")+ return dest+ dest.parent.mkdir(parents=True, exist_ok=True)+ print(f" fetching {url}")+ subprocess.run(["curl", "-sSL", "--fail", "-o", str(dest), url], check=True)+ print(f" saved {dest} ({mb(dest.stat().st_size)})")+ return dest+++def load_admin1(path: Path) -> dict[str, str]:+ """admin1 code ("US.CA") -> ASCII name ("California")."""+ names: dict[str, str] = {}+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():+ if not line.strip() or line.startswith("#"):+ continue+ cols = line.split("\t")+ if len(cols) >= 2:+ names[cols[0]] = cols[1]+ return names+++def load_countries(path: Path) -> dict[str, str]:+ """ISO code -> country name."""+ names: dict[str, str] = {}+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():+ if not line.strip() or line.startswith("#"):+ continue+ cols = line.split("\t")+ if len(cols) > 4:+ names[cols[0]] = cols[4]+ return names+++def build_places(+ cities_zip: Path,+ admin1_names: dict[str, str],+ country_names: dict[str, str],+ conn: sqlite3.Connection,+) -> int:+ conn.execute(+ """+ CREATE TABLE places (+ id INTEGER PRIMARY KEY,+ name TEXT NOT NULL,+ asciiname TEXT NOT NULL,+ latitude REAL NOT NULL,+ longitude REAL NOT NULL,+ country_code TEXT NOT NULL DEFAULT '',+ country_name TEXT NOT NULL DEFAULT '',+ admin1 TEXT NOT NULL DEFAULT '',+ population INTEGER NOT NULL DEFAULT 0,+ timezone TEXT NOT NULL DEFAULT ''+ )+ """+ )+ conn.execute(+ """+ CREATE VIRTUAL TABLE places_fts USING fts5(+ name, asciiname, alternates,+ content='places', content_rowid='rowid'+ )+ """+ )+ rows: list[tuple] = []+ with zipfile.ZipFile(cities_zip) as zf:+ name = next(n for n in zf.namelist() if n.endswith(".txt"))+ with zf.open(name) as handle:+ for raw in handle:+ line = raw.decode("utf-8", errors="replace").rstrip("\n")+ if not line.strip():+ continue+ # geonameid, name, asciiname, alternatenames, lat, lon,+ # feature class/code, country, cc2, admin1..4, population,+ # elevation, dem, timezone, modification.+ c = line.split("\t")+ if len(c) < 18:+ continue+ try:+ gid = int(c[0])+ lat = float(c[4])+ lon = float(c[5])+ except ValueError:+ continue+ if gid == 0:+ continue+ cc = c[8]+ admin1 = admin1_names.get(f"{cc}.{c[10]}", "")+ country = country_names.get(cc, "")+ try:+ pop = int(c[14])+ except ValueError:+ pop = 0+ tz = c[17] if len(c) > 17 else ""+ rows.append(+ (gid, c[1], c[2], lat, lon, cc, country, admin1, pop, tz,+ c[3].replace(",", " "))+ )+ rows.sort(key=lambda r: (r[1].lower(), -r[8]))+ conn.executemany(+ "INSERT INTO places VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",+ [r[:10] for r in rows],+ )+ conn.executemany(+ "INSERT INTO places_fts(rowid, name, asciiname, alternates) VALUES (?, ?, ?, ?)",+ [(r[0], r[1], r[2], r[10]) for r in rows],+ )+ print(f" places {len(rows)} cities")+ return len(rows)+++def build_catalog(db_path: Path) -> int:+ cities_zip = download(CITIES_URL, CACHED_CITIES)+ admin1_names = load_admin1(download(ADMIN1_URL, CACHED_ADMIN1))+ country_names = load_countries(download(COUNTRY_URL, CACHED_COUNTRY))+ db_path.parent.mkdir(parents=True, exist_ok=True)+ db_path.unlink(missing_ok=True)+ conn = sqlite3.connect(db_path)+ try:+ conn.execute("PRAGMA journal_mode = OFF")+ conn.execute("PRAGMA synchronous = OFF")+ count = build_places(cities_zip, admin1_names, country_names, conn)+ # DELETE, not OFF: the app reopens the file read-only, which a journal+ # mode of OFF does not survive cleanly.+ conn.execute("PRAGMA journal_mode = DELETE")+ conn.commit()+ conn.execute("VACUUM")+ conn.commit()+ finally:+ conn.close()+ print(f" built {db_path} ({mb(db_path.stat().st_size)})")+ return count+++def compress(src: Path, dest: Path) -> None:+ try:+ import brotli+ except ImportError:+ sys.exit("brotli is required to compress the asset: pip install brotli")+ dest.parent.mkdir(parents=True, exist_ok=True)+ dest.write_bytes(brotli.compress(src.read_bytes(), quality=11))+ print(f" wrote {dest} ({mb(dest.stat().st_size)})")+++def main() -> None:+ ap = argparse.ArgumentParser(description=__doc__)+ ap.add_argument("--keep-db", action="store_true",+ help="keep the uncompressed SQLite file next to the asset")+ args = ap.parse_args()++ print("Places (GeoNames cities1000)")+ staging = ASSETS / "places.db"+ count = build_catalog(staging)+ compress(staging, ASSETS / "places.db.br")++ meta = {+ "schemaVersion": SCHEMA_VERSION,+ "places": count,+ "bytes": staging.stat().st_size,+ "compressedBytes": (ASSETS / "places.db.br").stat().st_size,+ "sources": {+ "cities": CITIES_URL,+ "admin1": ADMIN1_URL,+ "country": COUNTRY_URL,+ },+ }+ (ASSETS / "places.db.meta.json").write_text(+ json.dumps(meta, indent=1) + "\n", newline="\n"+ )+ print(f" wrote {ASSETS / 'places.db.meta.json'}")++ if not args.keep_db:+ staging.unlink(missing_ok=True)+++if __name__ == "__main__":+ main()
weather/build.gradle.kts
diff --git a/weather/build.gradle.kts b/weather/build.gradle.ktsindex db902ca932..a6fd19d8a4 100644--- a/weather/build.gradle.kts+++ b/weather/build.gradle.kts@@ -14,6 +14,14 @@ android { defaultConfig { applicationId = "com.vayunmathur.weather" }++ androidResources {+ // The places database asset is already brotli-compressed by+ // scripts/generate_places_db.py. Letting AAPT deflate it again costs+ // build time, gains nothing, and makes the app pay a second inflate+ // pass on top of its own when unpacking it.+ noCompress += "br"+ } } androidComponents {@@ -35,6 +43,10 @@ dependencies { implementRoom(libs) implementation(project(":library:room")) + // Decodes the brotli-compressed places database asset. This is the only+ // reason the app links a codec at all; it does not use the network.+ implementation(libs.brotli.dec)+ // Android Auto (WEATHER): AndroidX Car App Library. `app` provides the // CarAppService/Session/Screen/template model. Only pulled into the car // code path (service/car/) — the phone UI is untouched.
weather/src/main/java/com/vayunmathur/weather/MainActivity.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt b/weather/src/main/java/com/vayunmathur/weather/MainActivity.ktindex 0edf744494..674baff0fb 100644--- a/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt+++ b/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt@@ -5,11 +5,13 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels+import androidx.lifecycle.lifecycleScope import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.util.OfflineAware import com.vayunmathur.library.widgets.updateWidgetPreviews+import com.vayunmathur.weather.data.GeoDatabase import com.vayunmathur.weather.data.WeatherRepository import com.vayunmathur.weather.platform.WeatherViewModel import com.vayunmathur.weather.platform.WeatherViewModelFactory@@ -22,8 +24,13 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState)- // FIRST_PARTY covers api.vayunmathur.com + api.open-meteo.com (ISRG) + data.vayunmathur.com+ // FIRST_PARTY covers api.vayunmathur.com (self-hosted weather bundle+ // and tiles proxy — place search is on-device, no hosts remain). NetworkClient.init(this, TrustBundle.FIRST_PARTY)+ GeoDatabase.init(this)+ // Unpacking is a ~13 MB brotli decompression and disk write. Do it now,+ // in the background, rather than the first time the user opens search.+ GeoDatabase.warmUp(lifecycleScope) updateWidgetPreviews(WeatherGlanceWidgetReceiver::class) enableEdgeToEdge() setContent {
weather/src/main/java/com/vayunmathur/weather/data/GeoDatabase.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/data/GeoDatabase.kt b/weather/src/main/java/com/vayunmathur/weather/data/GeoDatabase.ktnew file mode 100644index 0000000000..8141af59dc--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/data/GeoDatabase.kt@@ -0,0 +1,367 @@+package com.vayunmathur.weather.data++import android.content.Context+import android.os.storage.StorageManager+import android.util.Log+import com.vayunmathur.library.room.loadSqlCipher+import com.vayunmathur.weather.network.GeocodingResult+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.currentCoroutineContext+import kotlinx.coroutines.ensureActive+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import net.zetetic.database.sqlcipher.SQLiteDatabase+import org.brotli.dec.BrotliInputStream+import java.io.File+import java.io.IOException++/**+ * The place names the city search suggests, shipped inside the APK.+ *+ * One table in one SQLite file, built by `scripts/generate_places_db.py`+ * from GeoNames `cities1000` (+ `admin1CodesASCII`, `countryInfo`): ~171k+ * places with canonical name, ASCII name, hidden alternate names, coords,+ * country/admin1 display names, population, and time zone.+ *+ * No search makes a network request; the downloads happen at build time.+ * GeoNames is CC-BY 4.0 (https://www.geonames.org/about.html); attribution+ * ships in the app's about screen.+ *+ * Deliberately mirrors the health app's `ReferenceCatalog`: expanded into+ * `filesDir` once, opened read-only through SQLCipher's bundled SQLite+ * (which guarantees a known FTS5) with an empty passphrase, and written+ * through a `.part` file so a failure midway cannot leave a half-built+ * database in place.+ *+ * The ranking SQL is kept byte-for-byte in step with the generator's+ * documented ORDER BY (exact, then prefix, then population, then bm25) so a+ * rebuild never silently reshuffles results.+ *+ * When the asset is absent — a clean checkout where the generator has not+ * been run — [status] stays [Status.Absent] and search falls back to the+ * server geocoding endpoint rather than failing.+ */+object GeoDatabase {++ private const val TAG = "GeoDatabase"+ private const val ASSET_DB = "places.db.br"+ private const val ASSET_META = "places.db.meta.json"+ private const val DB_FILE = "places.db"+ private const val PART_DB = "places.db.part"+ private const val META_FILE = "places.db.meta.json"++ /** Schema this build can read. Bumped in lockstep with `generate_places_db.py`. */+ private const val SUPPORTED_SCHEMA_VERSION = 1++ /** The unpacked database runs about three times the asset size; reserve that up front. */+ private const val DB_SIZE_FACTOR = 3++ /** Brotli decoder window and stream-copy buffer. */+ private const val BROTLI_BUFFER = 64 * 1024+ private const val COPY_BUFFER = 256 * 1024++ /** Describes the bundled asset; emitted next to it by the generator. */+ @Serializable+ data class Meta(+ val schemaVersion: Int = 0,+ val places: Long = 0,+ /** Unpacked size, used for the free-space check. */+ val bytes: Long = 0,+ val compressedBytes: Long = 0,+ )++ sealed interface Status {+ val installed: Meta? get() = null++ /** Not unpacked yet; search falls back to the server endpoint. */+ data object Absent : Status++ data object Preparing : Status++ data class Ready(val meta: Meta) : Status {+ override val installed: Meta get() = meta+ }++ data class Failed(val message: String, override val installed: Meta?) : Status+ }++ private val json = Json { ignoreUnknownKeys = true }++ private val _status = MutableStateFlow<Status>(Status.Absent)+ val status: StateFlow<Status> = _status.asStateFlow()++ private lateinit var appContext: Context++ private val prepareMutex = Mutex()++ /**+ * The unpacked database, once confirmed to match the asset in this process.+ * Compares the whole descriptor rather than just [Meta.schemaVersion]:+ * two builds can share a schema and hold different data.+ */+ @Volatile+ private var verified: Meta? = null++ private var handle: SQLiteDatabase? = null+ private val lock = Any()++ private val dbFile: File get() = File(appContext.filesDir, DB_FILE)+ private val partDbFile: File get() = File(appContext.filesDir, PART_DB)+ private val metaFile: File get() = File(appContext.filesDir, META_FILE)++ fun init(context: Context) {+ appContext = context.applicationContext+ loadSqlCipher()+ partDbFile.delete()+ }++ /**+ * Unpack and open in the background, so the first search the user types+ * does not have to. Unpacking is a ~13 MB brotli decompression and disk+ * write — about a second, once.+ */+ fun warmUp(scope: CoroutineScope) {+ scope.launch { runCatching { prepare() } }+ }++ /**+ * Places matching [query], best first.+ *+ * Ranking (same ORDER BY as the generator documents): exact canonical or+ * ASCII name, then prefix matches, then population (famous cities win+ * ties), then bm25. Empty when the catalogue is absent — the caller falls+ * back to the server endpoint — or when nothing matches.+ */+ suspend fun searchPlaces(query: String, limit: Int = 5): List<GeocodingResult> =+ withContext(Dispatchers.IO) {+ val match = escapeFtsQuery(query) ?: return@withContext emptyList()+ val db = openHandle() ?: return@withContext emptyList()+ val trimmed = query.trim()+ // LIKE prefix pattern. Escape char is `!` (not backslash: in a+ // Kotlin raw string '\\' reaches SQLite as two characters, which+ // it rejects — "ESCAPE expression must be a single character").+ val like = trimmed+ .replace("!", "!!")+ .replace("%", "!%")+ .replace("_", "!_") + "%"+ try {+ db.rawQuery(+ """+ SELECT p.id, p.name, p.latitude, p.longitude,+ p.country_name, p.country_code, p.admin1, p.timezone+ FROM places_fts fts+ JOIN places p ON fts.rowid = p.rowid+ WHERE places_fts MATCH ?+ ORDER BY+ (p.name = ? OR p.asciiname = ?) DESC,+ (p.name LIKE ? ESCAPE '!' OR p.asciiname LIKE ? ESCAPE '!') DESC,+ p.population DESC,+ bm25(places_fts)+ LIMIT ?+ """.trimIndent(),+ arrayOf(match, trimmed, trimmed, like, like, limit.toString()),+ ).use { cursor ->+ buildList {+ while (cursor.moveToNext()) {+ add(+ GeocodingResult(+ id = cursor.getLong(0),+ name = cursor.getString(1),+ latitude = cursor.getDouble(2),+ longitude = cursor.getDouble(3),+ country = cursor.getString(4)?.takeIf { it.isNotEmpty() },+ countryCode = cursor.getString(5)?.takeIf { it.isNotEmpty() },+ admin1 = cursor.getString(6)?.takeIf { it.isNotEmpty() },+ timezone = cursor.getString(7)?.takeIf { it.isNotEmpty() },+ ),+ )+ }+ }+ }+ } catch (e: android.database.sqlite.SQLiteException) {+ Log.e(TAG, "Place search failed", e)+ emptyList()+ }+ }++ /**+ * Turn raw user input into an FTS5 expression.+ *+ * Every token is a **prefix** match (`"ber"*`). Without the trailing `*`+ * FTS5 only matches whole tokens, so a half-typed word finds nothing: a+ * search box that is empty until the last keystroke reads as broken.+ * Splitting on everything non-alphanumeric matches how the unicode61+ * tokenizer split the indexed text; quoting stops `-`, `(` and `*` in+ * the user's own input being read as operators.+ */+ internal fun escapeFtsQuery(raw: String): String? {+ val tokens = raw.split(Regex("[^\\p{L}\\p{N}]+")).filter { it.isNotEmpty() }+ return if (tokens.isEmpty()) null else tokens.joinToString(" ") { "\"$it\"*" }+ }++ // --- Unpacking (mirrors ReferenceCatalog) --------------------------------++ /**+ * Expand the bundled asset if that hasn't happened yet. Cheap and+ * idempotent once done, so the search screen can call it freely on every+ * appearance.+ */+ @Suppress("TooGenericExceptionCaught")+ suspend fun prepare(): Result<Meta> = withContext(Dispatchers.IO) {+ verified?.let { return@withContext Result.success(it) }++ prepareMutex.withLock {+ verified?.let { return@withLock Result.success(it) }++ val asset = assetMeta()+ ?: return@withLock fail("This build has no places catalogue")++ if (asset.schemaVersion != SUPPORTED_SCHEMA_VERSION) {+ return@withLock fail("Bundled places catalogue is not readable by this build")+ }++ installedMeta()?.let { current ->+ if (current == asset) {+ openHandle()+ verified = current+ _status.value = Status.Ready(current)+ return@withLock Result.success(current)+ }+ }++ val needed = asset.bytes * DB_SIZE_FACTOR+ val free = allocateForDatabase(needed)+ if (free in 1 until needed) {+ return@withLock fail("Not enough free space for the places catalogue")+ }++ _status.value = Status.Preparing+ partDbFile.delete()++ try {+ decompressAsset()+ swapInDatabase(asset)+ Result.success(asset)+ } catch (e: Exception) {+ partDbFile.delete()+ Log.e(TAG, "Unpack failed", e)+ if (e is kotlinx.coroutines.CancellationException) {+ _status.value = installedMeta()?.let { Status.Ready(it) } ?: Status.Absent+ throw e+ }+ fail(e.message ?: "Couldn't prepare the places catalogue")+ }+ }+ }++ /** Decompresses the bundled asset into the `.part` file. */+ private suspend fun decompressAsset() {+ BrotliInputStream(appContext.assets.open(ASSET_DB), BROTLI_BUFFER).use { input ->+ partDbFile.outputStream().buffered().use { output ->+ val buffer = ByteArray(COPY_BUFFER)+ var read = input.read(buffer)+ while (read >= 0) {+ currentCoroutineContext().ensureActive()+ if (read > 0) output.write(buffer, 0, read)+ read = input.read(buffer)+ }+ }+ }+ }++ /** Swaps the `.part` file into place and opens it, recording the new metadata. */+ private fun swapInDatabase(asset: Meta) {+ closeHandle()+ dbFile.delete()+ if (!partDbFile.renameTo(dbFile)) {+ partDbFile.delete()+ throw IOException("Couldn't save the places catalogue")+ }+ metaFile.writeText(json.encodeToString(asset))++ openHandle()+ verified = asset+ _status.value = Status.Ready(asset)+ }++ private fun assetMeta(): Meta? = try {+ appContext.assets.open(ASSET_META).bufferedReader().use {+ json.decodeFromString<Meta>(it.readText())+ }+ } catch (e: IOException) {+ Log.i(TAG, "No bundled places catalogue asset: ${e.message}")+ null+ } catch (e: IllegalArgumentException) {+ Log.i(TAG, "No bundled places catalogue asset: ${e.message}")+ null+ }++ private fun installedMeta(): Meta? {+ if (!dbFile.exists() || !metaFile.exists()) return null+ return try {+ val meta = json.decodeFromString<Meta>(metaFile.readText())+ if (meta.schemaVersion == SUPPORTED_SCHEMA_VERSION) meta else null+ } catch (e: IOException) {+ Log.e(TAG, "Unreadable unpacked metadata", e)+ null+ } catch (e: IllegalArgumentException) {+ Log.e(TAG, "Unreadable unpacked metadata", e)+ null+ }+ }++ private fun openHandle(): SQLiteDatabase? {+ synchronized(lock) {+ handle?.let { return it }+ if (!dbFile.exists()) return null+ return try {+ // Empty passphrase => open as an ordinary unencrypted database. This is public+ // reference data, deliberately separate from the SQLCipher-encrypted Room database.+ SQLiteDatabase.openDatabase(+ dbFile.absolutePath,+ "",+ null,+ SQLiteDatabase.OPEN_READONLY,+ null,+ ).also { handle = it }+ } catch (e: android.database.sqlite.SQLiteException) {+ Log.e(TAG, "Failed to open the places catalogue", e)+ null+ }+ }+ }++ private fun closeHandle() {+ synchronized(lock) {+ try { handle?.close() } catch (_: Exception) {}+ handle = null+ }+ }++ private fun allocateForDatabase(needed: Long): Long {+ val sm = appContext.getSystemService(StorageManager::class.java)+ ?: return appContext.filesDir.usableSpace+ return try {+ val uuid = sm.getUuidForPath(appContext.filesDir)+ val allocatable = sm.getAllocatableBytes(uuid)+ if (allocatable >= needed) sm.allocateBytes(uuid, needed)+ allocatable+ } catch (_: IOException) {+ appContext.filesDir.usableSpace+ }+ }++ private fun fail(message: String): Result<Meta> {+ _status.value = Status.Failed(message, installedMeta())+ return Result.failure(IllegalStateException(message))+ }+}
weather/src/main/java/com/vayunmathur/weather/data/WeatherRefreshWorker.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/data/WeatherRefreshWorker.kt b/weather/src/main/java/com/vayunmathur/weather/data/WeatherRefreshWorker.ktindex f1dacb9822..9a006ad2b5 100644--- a/weather/src/main/java/com/vayunmathur/weather/data/WeatherRefreshWorker.kt+++ b/weather/src/main/java/com/vayunmathur/weather/data/WeatherRefreshWorker.kt@@ -11,6 +11,8 @@ import androidx.work.WorkerParameters import com.vayunmathur.weather.widget.glance.WeatherBlobGlanceWidget import com.vayunmathur.weather.widget.glance.WeatherGlanceWidget import com.vayunmathur.weather.network.WeatherApi+import com.vayunmathur.weather.network.toAirQuality+import com.vayunmathur.weather.network.toForecastResponse import java.util.concurrent.TimeUnit class WeatherRefreshWorker(@@ -27,10 +29,11 @@ class WeatherRefreshWorker( val locations = repo.getLocations() for (location in locations) { try {- val forecast = WeatherApi.forecast(location.latitude, location.longitude)- val airQuality = runCatching {- WeatherApi.airQuality(location.latitude, location.longitude)- }.getOrNull()+ // One bundle call carries forecast + AQ (same object,+ // split into the two cache halves below).+ val bundle = WeatherApi.bundle(location.latitude, location.longitude)+ val forecast = bundle.toForecastResponse()+ val airQuality = bundle.toAirQuality() repo.writeForecastCache(location.latitude, location.longitude, forecast, airQuality) } catch (e: Exception) { Log.w(TAG, "Failed to refresh weather for ${location.name}: ${e.message}")
weather/src/main/java/com/vayunmathur/weather/domain/MetricSeries.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/domain/MetricSeries.kt b/weather/src/main/java/com/vayunmathur/weather/domain/MetricSeries.ktindex 3f0200d205..ef4789b3bb 100644--- a/weather/src/main/java/com/vayunmathur/weather/domain/MetricSeries.kt+++ b/weather/src/main/java/com/vayunmathur/weather/domain/MetricSeries.kt@@ -182,8 +182,8 @@ fun metricSeries( private fun rawSeries( hourly: com.vayunmathur.weather.network.Hourly, metric: WeatherMetric,-): List<Double> {- val outcome: List<Double> = when (metric) {+): List<Double?> {+ val outcome: List<Double?> = when (metric) { WeatherMetric.Temperature -> hourly.temperature WeatherMetric.FeelsLike -> hourly.apparentTemperature WeatherMetric.Humidity -> hourly.relativeHumidity.map { it.toDouble() }@@ -212,7 +212,7 @@ private fun targetDateFor( private fun collectDayPoints( times: List<String>,- raw: List<Double>,+ raw: List<Double?>, targetDate: String, utcOffsetSeconds: Int, ): List<MetricPoint> {
weather/src/main/java/com/vayunmathur/weather/domain/map/OmMapMetadata.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/domain/map/OmMapMetadata.kt b/weather/src/main/java/com/vayunmathur/weather/domain/map/OmMapMetadata.ktindex 8e34c6e6fa..daaf2476a4 100644--- a/weather/src/main/java/com/vayunmathur/weather/domain/map/OmMapMetadata.kt+++ b/weather/src/main/java/com/vayunmathur/weather/domain/map/OmMapMetadata.kt@@ -8,8 +8,9 @@ import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json /**- * Metadata for an Open-Meteo spatial model, from- * `https://map-tiles.open-meteo.com/data_spatial/<model>/latest.json`.+ * Metadata for a spatial model, from+ * `https://api.vayunmathur.com/data_spatial/<model>/latest.json` (P1 tiles+ * passthrough; upstream is the Open-Meteo S3 bucket). * * - [referenceTime] is the model run (drives the `.om` folder path). * - [validTimes] are the hourly forecast steps (drive the time slider).@@ -37,7 +38,8 @@ val WeatherMetric.omVariable: String private const val WIND_U = "wind_u_component_10m" private const val WIND_V = "wind_v_component_10m" -private const val SPATIAL_BASE = "https://map-tiles.open-meteo.com/data_spatial"+/** Self-hosted tiles origin: axum Range proxy on `api.vayunmathur.com` (P1). */+private const val SPATIAL_BASE = "https://api.vayunmathur.com/data_spatial" private val metadataJson = Json { ignoreUnknownKeys = true }
weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherByNameIntent.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherByNameIntent.kt b/weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherByNameIntent.ktindex 0c5d8905c6..08dd365952 100644--- a/weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherByNameIntent.kt+++ b/weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherByNameIntent.kt@@ -13,7 +13,7 @@ data class LocationQueryInput(val name: String) /** * "Headless" activity launched by OpenAssistant's `get_weather_by_name`- * tool. Resolves [LocationQueryInput.name] via Open-Meteo's geocoding API,+ * tool. Resolves [LocationQueryInput.name] via self-hosted geocoding, * then fetches a forecast for the first match. Returns [WeatherData] with * `error` set if no place matched or the network call failed. */
weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherIntent.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherIntent.kt b/weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherIntent.ktindex 2bae40b33a..440dabd8d6 100644--- a/weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherIntent.kt+++ b/weather/src/main/java/com/vayunmathur/weather/intents/GetWeatherIntent.kt@@ -19,9 +19,9 @@ data class LatLonInput(val latitude: Double, val longitude: Double) /** * "Headless" activity launched by OpenAssistant's `get_weather` tool. Fetches- * a fresh forecast from Open-Meteo for the supplied lat/lon and returns it as- * a [WeatherData] payload. No UI — the activity finishes immediately as- * dictated by the [AssistantIntent] base class.+ * a fresh forecast from the self-hosted bundle for the supplied lat/lon and+ * returns it as a [WeatherData] payload. No UI — the activity finishes+ * immediately as dictated by the [AssistantIntent] base class. */ @OptIn(InternalSerializationApi::class) class GetWeatherIntent : AssistantIntent<LatLonInput, WeatherData>(
weather/src/main/java/com/vayunmathur/weather/network/AirQualityDto.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/AirQualityDto.kt b/weather/src/main/java/com/vayunmathur/weather/network/AirQualityDto.ktindex dd6bd8adc7..26838f4fba 100644--- a/weather/src/main/java/com/vayunmathur/weather/network/AirQualityDto.kt+++ b/weather/src/main/java/com/vayunmathur/weather/network/AirQualityDto.kt@@ -4,8 +4,9 @@ import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /**- * Subset of Open-Meteo's `/v1/air-quality` response we use. Endpoint:- * https://air-quality-api.open-meteo.com/v1/air-quality+ * Subset of the air-quality response we use. Shape-origin: Open-Meteo's+ * `/v1/air-quality` (now served mapped from the self-hosted `wx/v1/bundle`+ * `aq` section). * * Provides US AQI (0..500 with 0..50 = good, 51..100 = moderate, …) plus * tree/grass/weed/ragweed/birch/olive/mugwort/alder pollen concentrations
weather/src/main/java/com/vayunmathur/weather/network/GeocodingDto.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/GeocodingDto.kt b/weather/src/main/java/com/vayunmathur/weather/network/GeocodingDto.ktindex 3dd7b87ef6..1eb9156677 100644--- a/weather/src/main/java/com/vayunmathur/weather/network/GeocodingDto.kt+++ b/weather/src/main/java/com/vayunmathur/weather/network/GeocodingDto.kt@@ -4,8 +4,8 @@ import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /**- * Open-Meteo geocoding API response for `/v1/search?name=...`.- * Endpoint: https://geocoding-api.open-meteo.com/v1/search+ * Self-hosted geocoding response (`GET /wx/v1/search?name=...`), shape 1:1+ * with the Open-Meteo geocoding API it replaces. */ @Serializable data class GeocodingResponse(val results: List<GeocodingResult> = emptyList())
weather/src/main/java/com/vayunmathur/weather/network/OpenMeteoDto.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/OpenMeteoDto.kt b/weather/src/main/java/com/vayunmathur/weather/network/OpenMeteoDto.ktindex 1adb079bbe..e873f67a17 100644--- a/weather/src/main/java/com/vayunmathur/weather/network/OpenMeteoDto.kt+++ b/weather/src/main/java/com/vayunmathur/weather/network/OpenMeteoDto.kt@@ -4,8 +4,8 @@ import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /**- * Subset of the Open-Meteo `/v1/forecast` response we actually use.- * Endpoint: https://api.open-meteo.com/v1/forecast+ * Subset of the forecast response we actually use. Shape-origin: Open-Meteo+ * `/v1/forecast` (now served mapped from the self-hosted `wx/v1/bundle`). * * We always request: current weather + hourly arrays + daily arrays in metric * units. Unit conversion for the UI happens at display time so swapping@@ -91,7 +91,7 @@ data class Hourly( @SerialName("visibility") val visibility: List<Double> = emptyList(), @SerialName("cloud_cover") val cloudCover: List<Int> = emptyList(), @SerialName("wind_gusts_10m") val windGusts: List<Double> = emptyList(),- @SerialName("uv_index") val uvIndex: List<Double> = emptyList(),+ @SerialName("uv_index") val uvIndex: List<Double?> = emptyList(), @SerialName("is_day") val isDay: List<Int> = emptyList(), ) @@ -107,7 +107,7 @@ data class Daily( @SerialName("sunset") val sunset: List<String> = emptyList(), @SerialName("daylight_duration") val daylightDuration: List<Double> = emptyList(), @SerialName("sunshine_duration") val sunshineDuration: List<Double> = emptyList(),- @SerialName("uv_index_max") val uvIndexMax: List<Double> = emptyList(),+ @SerialName("uv_index_max") val uvIndexMax: List<Double?> = emptyList(), @SerialName("precipitation_probability_max") val precipitationProbabilityMax: List<Int> = emptyList(), @SerialName("precipitation_sum") val precipitationSum: List<Double> = emptyList(), // 0/1 = new moon, 0.25 = first quarter, 0.5 = full, 0.75 = last quarter.
weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt b/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.ktindex 5f4b238e92..2840c8bb6d 100644--- a/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt+++ b/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt@@ -1,73 +1,37 @@ package com.vayunmathur.weather.network import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.weather.data.GeoDatabase /**- * Thin wrapper over the shared [NetworkClient] for the two Open-Meteo- * endpoints we use. Open-Meteo requires no API key and returns JSON, so this- * is just URL construction + delegation to the shared client.+ * Thin wrapper over the shared [NetworkClient] for the self-hosted `wx/v1`+ * bundle API on `api.vayunmathur.com` (+ self-hosted geocoding on the same+ * host). One `bundle()` call carries everything the weather screen needs;+ * the mapper normalizes it into the existing DTOs so nothing downstream of+ * `network/` changes. * * Everything is requested in metric units; the UI converts at display time so * toggling °C/°F doesn't trigger another HTTP call. */ object WeatherApi { - private const val FORECAST_BASE = "https://api.open-meteo.com/v1/forecast"- private const val GEOCODE_BASE = "https://geocoding-api.open-meteo.com/v1/search"- private const val AIR_QUALITY_BASE = "https://air-quality-api.open-meteo.com/v1/air-quality"- /** Days of historical data prepended to the forecast response. */- private const val PAST_DAYS = 7+ private const val BUNDLE_BASE = "https://api.vayunmathur.com/wx/v1"+ private const val GEOCODE_BASE = "https://api.vayunmathur.com/wx/v1/search" - private val CURRENT_FIELDS = listOf(- "temperature_2m",- "apparent_temperature",- "relative_humidity_2m",- "dew_point_2m",- "weather_code",- "wind_speed_10m",- "wind_direction_10m",- "pressure_msl",- "visibility",- "cloud_cover",- "wind_gusts_10m",- "is_day",- )-- private val HOURLY_FIELDS = listOf(- "temperature_2m",- "apparent_temperature",- "relative_humidity_2m",- "dew_point_2m",- "weather_code",- "precipitation_probability",- "precipitation",- "wind_speed_10m",- "wind_direction_10m",- "pressure_msl",- "visibility",- "uv_index",- "cloud_cover",- "wind_gusts_10m",- "is_day",- )-- private val DAILY_FIELDS = listOf(- "weather_code",- "temperature_2m_max",- "temperature_2m_min",- "apparent_temperature_max",- "apparent_temperature_min",- "sunrise",- "sunset",- "daylight_duration",- "sunshine_duration",- "uv_index_max",- "precipitation_probability_max",- "precipitation_sum",- "moon_phase",- "moonrise",- "moonset",- )+ /**+ * Fetch the full bundle (current + hourly + daily + 15-min + AQ) for a+ * single coordinate. Single HTTP call. Throws on network / parse failure+ * — callers wrap in try/catch and fall back to cache.+ */+ suspend fun bundle(latitude: Double, longitude: Double, fields: String = "all"): WxBundle {+ val url = buildString {+ append(BUNDLE_BASE).append("/bundle")+ append("?lat=").append(latitude)+ append("&lon=").append(longitude)+ append("&fields=").append(fields)+ }+ return NetworkClient.getJson(url)+ } /** * Fetch the current conditions + 24h hourly + 7-day daily forecast for a@@ -75,95 +39,75 @@ object WeatherApi { * try/catch and fall back to cache. */ suspend fun forecast(latitude: Double, longitude: Double): ForecastResponse {- val url = buildString {- append(FORECAST_BASE)- append("?latitude=").append(latitude)- append("&longitude=").append(longitude)- append("¤t=").append(CURRENT_FIELDS.joinToString(","))- append("&hourly=").append(HOURLY_FIELDS.joinToString(","))- append("&daily=").append(DAILY_FIELDS.joinToString(","))- append("&minutely_15=precipitation")- append("&timezone=auto")- append("&past_days=").append(PAST_DAYS)- append("&forecast_days=7")- }- return NetworkClient.getJson(url)+ return bundle(latitude, longitude).toForecastResponse() } /** * Look up up to [limit] places that match the user-typed [query]. Used by * the in-app city search and by the OpenAssistant * `get_weather_by_name` intent.+ *+ * On-device catalogue first (offline-capable, no network); the server+ * endpoint is the fallback for checkouts without the generated asset. */ suspend fun geocode(query: String, limit: Int = 5): GeocodingResponse { if (query.isBlank()) return GeocodingResponse(emptyList())+ val local = runCatching {+ GeoDatabase.searchPlaces(query, limit)+ }.getOrDefault(emptyList())+ if (local.isNotEmpty()) return GeocodingResponse(local)+ // Catalogue absent (or genuinely no match): try the server index. val url = buildString { append(GEOCODE_BASE) append("?name=").append(java.net.URLEncoder.encode(query, "UTF-8")) append("&count=").append(limit)- append("&format=json")- append("&language=en") }- return NetworkClient.getJson(url)+ return runCatching {+ NetworkClient.getJson<GeocodingResponse>(url)+ }.getOrDefault(GeocodingResponse(emptyList())) } /** * Fetch just the current temperature (°C) for a coordinate. Used by the- * city-search list to show the current temp next to each result. Requests- * a single variable to keep these on-demand lookups lightweight.+ * city-search list to show the current temp next to each result.+ * Requests only the `current` bundle section (~200-byte body). */ suspend fun currentTemperature(latitude: Double, longitude: Double): Double? {+ return bundle(latitude, longitude, "current").current?.temp+ }++ /**+ * Batch current temperatures for search results: one round trip for all+ * rows instead of N parallel [currentTemperature] calls. Returns+ * temp-per-coordinate in request order; a failed point is absent (callers+ * keep the per-row spinner → blank, same as today's `getOrNull`).+ */+ suspend fun currentTemperatures(points: List<Pair<Double, Double>>): Map<Pair<Double, Double>, Double> {+ if (points.isEmpty()) return emptyMap() val url = buildString {- append(FORECAST_BASE)- append("?latitude=").append(latitude)- append("&longitude=").append(longitude)- append("¤t=temperature_2m")- append("&forecast_days=1")+ append(BUNDLE_BASE).append("/current?points=")+ append(points.take(20).joinToString("|") { (lat, lon) -> "$lat,$lon" }) }- return NetworkClient.getJson<CurrentTemperatureResponse>(url).current?.temperature+ val batch: WxCurrentBatch = NetworkClient.getJson(url)+ return batch.points.associate { p -> (p.lat to p.lon) to p.temp } } /**- * Resolve the IANA time zone for a coordinate via Open-Meteo's- * `timezone=auto`. Requests a single trivial variable (the endpoint rejects- * variable-less requests) and reads only the timezone fields. Used by the- * map to label the zoomed-in region's local time. Throws on failure.+ * Resolve the IANA time zone for a coordinate. Requests only the envelope+ * (no weather data at all). Used by the map to label the zoomed-in+ * region's local time. Throws on failure. */ suspend fun timezoneAt(latitude: Double, longitude: Double): RegionTimezone {- val url = buildString {- append(FORECAST_BASE)- append("?latitude=").append(latitude)- append("&longitude=").append(longitude)- append("¤t=temperature_2m")- append("&timezone=auto")- append("&forecast_days=1")- }- return NetworkClient.getJson(url)+ return bundle(latitude, longitude, "tz").toRegionTimezone() } /**- * Air quality + pollen for a coordinate. Best-effort: the air-quality- * service has gaps outside Europe/North America, so callers should treat- * the whole response as optional.+ * Air quality + pollen for a coordinate. Best-effort: the service has gaps+ * outside Europe/North America, so callers should treat the whole response+ * as optional. Missing `aq` section maps to [AirQualityResponse](null),+ * exactly like today's nullable DTO. */ suspend fun airQuality(latitude: Double, longitude: Double): AirQualityResponse {- val url = buildString {- append(AIR_QUALITY_BASE)- append("?latitude=").append(latitude)- append("&longitude=").append(longitude)- append("¤t=").append(- listOf(- "us_aqi",- "alder_pollen",- "birch_pollen",- "grass_pollen",- "mugwort_pollen",- "olive_pollen",- "ragweed_pollen",- ).joinToString(",")- )- append("&timezone=auto")- }- return NetworkClient.getJson(url)+ return bundle(latitude, longitude).toAirQuality() ?: AirQualityResponse(null) } }
weather/src/main/java/com/vayunmathur/weather/network/WxBundleDto.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/WxBundleDto.kt b/weather/src/main/java/com/vayunmathur/weather/network/WxBundleDto.ktnew file mode 100644index 0000000000..2985f0ad7b--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/network/WxBundleDto.kt@@ -0,0 +1,130 @@+package com.vayunmathur.weather.network++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++/**+ * Wire DTOs for the self-hosted `GET /wx/v1/bundle` (custom versioned spec).+ *+ * Design rules (server guarantees): no time arrays — every regular series is+ * `{start, step, count, values}` with Unix-epoch `start`; epochs, never+ * local-ISO strings; absent sections are missing (never explicit null);+ * floats rounded to 2 decimals server-side; all 6 pollen species kept.+ *+ * The mapper ([WxBundleMapper]) expands these into the existing+ * [ForecastResponse]/[AirQualityResponse] types, so `domain/`, `platform/`,+ * `ui/`, `data/`, `intents/`, widgets, and the Room cache work byte-identical.+ */+@Serializable+data class WxBundle(+ val v: Int = 1,+ val lat: Double,+ val lon: Double,+ val tz: String = "UTC",+ @SerialName("tz_abbr") val tzAbbr: String = "UTC",+ @SerialName("utc_offset") val utcOffset: Int = 0,+ val model: String = "dwd_icon",+ val run: String = "",+ val current: WxCurrent? = null,+ val hourly: WxHourly? = null,+ val daily: WxDaily? = null,+ val min15: WxMin15? = null,+ val aq: WxAq? = null,+)++@Serializable+data class WxCurrent(+ val time: Long,+ val temp: Double,+ val feels: Double,+ val rh: Int,+ val dew: Double,+ val code: Int,+ @SerialName("wind_spd") val windSpd: Double,+ @SerialName("wind_dir") val windDir: Int,+ val pres: Double,+ val vis: Double,+ val cloud: Int,+ val gust: Double,+ val day: Int,+)++@Serializable+data class WxHourly(+ val start: Long,+ val step: Long = 3600,+ val count: Int = 0,+ val temp: List<Double> = emptyList(),+ val feels: List<Double> = emptyList(),+ val rh: List<Int> = emptyList(),+ val dew: List<Double> = emptyList(),+ val code: List<Int> = emptyList(),+ val pprob: List<Int> = emptyList(),+ val precip: List<Double> = emptyList(),+ @SerialName("wind_spd") val windSpd: List<Double> = emptyList(),+ @SerialName("wind_dir") val windDir: List<Int> = emptyList(),+ val pres: List<Double> = emptyList(),+ val vis: List<Double> = emptyList(),+ /** Nullable per element: CAMS UV coverage (~4d) is shorter than the 14-day window. */+ val uv: List<Double?> = emptyList(),+ val cloud: List<Int> = emptyList(),+ val gust: List<Double> = emptyList(),+ val day: List<Int> = emptyList(),+)++@Serializable+data class WxDaily(+ val start: String = "",+ val count: Int = 0,+ val code: List<Int> = emptyList(),+ val tmax: List<Double> = emptyList(),+ val tmin: List<Double> = emptyList(),+ @SerialName("feels_max") val feelsMax: List<Double> = emptyList(),+ @SerialName("feels_min") val feelsMin: List<Double> = emptyList(),+ val sunrise: List<Long> = emptyList(),+ val sunset: List<Long> = emptyList(),+ val daylight: List<Long> = emptyList(),+ val sunshine: List<Long> = emptyList(),+ @SerialName("uv_max") val uvMax: List<Double?> = emptyList(),+ @SerialName("pprob_max") val pprobMax: List<Int> = emptyList(),+ @SerialName("precip_sum") val precipSum: List<Double> = emptyList(),+ @SerialName("moon_phase") val moonPhase: List<Double> = emptyList(),+ val moonrise: List<Long?> = emptyList(),+ val moonset: List<Long?> = emptyList(),+)++@Serializable+data class WxMin15(+ val start: Long,+ val step: Long = 900,+ val count: Int = 0,+ val precip: List<Double> = emptyList(),+)++@Serializable+data class WxAq(+ val time: Long,+ @SerialName("us_aqi") val usAqi: Int? = null,+ val grass: Double? = null,+ val birch: Double? = null,+ val olive: Double? = null,+ val alder: Double? = null,+ val ragweed: Double? = null,+ val mugwort: Double? = null,+)++/** P4 batch response: current-hour temp/code/is_day per requested point. */+@Serializable+data class WxCurrentBatch(+ val v: Int = 1,+ val points: List<WxCurrentPoint> = emptyList(),+)++@Serializable+data class WxCurrentPoint(+ val lat: Double,+ val lon: Double,+ val temp: Double,+ val code: Int,+ val day: Int,+)
weather/src/main/java/com/vayunmathur/weather/network/WxBundleMapper.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/WxBundleMapper.kt b/weather/src/main/java/com/vayunmathur/weather/network/WxBundleMapper.ktnew file mode 100644index 0000000000..9d1122424f--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/network/WxBundleMapper.kt@@ -0,0 +1,147 @@+package com.vayunmathur.weather.network++import kotlinx.datetime.Instant+import kotlinx.datetime.TimeZone+import kotlinx.datetime.toLocalDateTime++/**+ * Boundary mapper: self-hosted [WxBundle] → the existing+ * [ForecastResponse]/[AirQualityResponse] types.+ *+ * Epoch→local-ISO formatting reproduces exactly the naive-local strings+ * Open-Meteo sends today (`yyyy-MM-dd'T'HH:mm` hourly/current/sun/moon,+ * `yyyy-MM-dd` daily) using the bundle's own `utcOffset` — so+ * [com.vayunmathur.weather.domain.SelectedData] string-matching,+ * `MetricSeries`, the [com.vayunmathur.weather.platform.precipitationNowcast]+ * nowcast, and `todayIndex` behave identically. Nothing downstream of+ * `network/` changes.+ *+ * Missing `pprob` passes through as-is (the server always sends the §4.6+ * heuristic today). Pollen collapses to grass/tree/weed at the display+ * layer, unchanged.+ */++private fun epochToNaiveLocal(epochSec: Long, utcOffsetSec: Int): String {+ // Shift by the location's offset, then format the wall clock — exactly+ // the naive-local strings Open-Meteo sends today.+ val ldt = Instant.fromEpochSeconds(epochSec + utcOffsetSec)+ .toLocalDateTime(TimeZone.UTC)+ val d = ldt.date+ val t = ldt.time+ return "%04d-%02d-%02dT%02d:%02d".format(+ d.year, d.monthNumber, d.dayOfMonth, t.hour, t.minute,+ )+}++/** `WxBundle` → [ForecastResponse] (mapped shape, cache-compatible). */+fun WxBundle.toForecastResponse(): ForecastResponse {+ val off = utcOffset+ val h = hourly+ val hourlyResp = if (h == null) null else Hourly(+ time = List(h.count) { k -> epochToNaiveLocal(h.start + k * h.step, off) },+ temperature = h.temp,+ apparentTemperature = h.feels,+ relativeHumidity = h.rh,+ dewPoint = h.dew,+ weatherCode = h.code,+ precipitationProbability = h.pprob,+ precipitation = h.precip,+ windSpeed = h.windSpd,+ windDirection = h.windDir,+ pressureMsl = h.pres,+ visibility = h.vis,+ cloudCover = h.cloud,+ windGusts = h.gust,+ uvIndex = h.uv,+ isDay = h.day,+ )+ val d = daily+ // Daily `start` is the first LOCAL date; entries are consecutive days.+ // Add k days with date arithmetic (DST-safe; avoids 86400 assumptions).+ val firstDate: kotlinx.datetime.LocalDate? = runCatching {+ kotlinx.datetime.LocalDate.parse(d?.start ?: "")+ }.getOrNull()+ val startDate = firstDate ?: kotlinx.datetime.LocalDate(2000, 1, 1)+ // UV gaps (past the CAMS horizon) map to NaN; consumers use getOrNull ++ // takeIf(isFinite) fallbacks (see SelectedData), mirroring how the map+ // colorizer already treats NaN as missing.+ val dailyResp = if (d == null || firstDate == null) null else Daily(+ time = List(d.count) { k ->+ val date = kotlinx.datetime.LocalDate.fromEpochDays(startDate.toEpochDays() + k)+ "%04d-%02d-%02d".format(date.year, date.monthNumber, date.dayOfMonth)+ },+ weatherCode = d.code,+ temperatureMax = d.tmax,+ temperatureMin = d.tmin,+ apparentTemperatureMax = d.feelsMax,+ apparentTemperatureMin = d.feelsMin,+ sunrise = d.sunrise.map { epochToNaiveLocal(it, off) },+ sunset = d.sunset.map { epochToNaiveLocal(it, off) },+ daylightDuration = d.daylight.map { it.toDouble() },+ sunshineDuration = d.sunshine.map { it.toDouble() },+ uvIndexMax = d.uvMax,+ precipitationProbabilityMax = d.pprobMax,+ precipitationSum = d.precipSum,+ moonPhase = d.moonPhase,+ moonrise = d.moonrise.map { it?.let { e -> epochToNaiveLocal(e, off) } },+ moonset = d.moonset.map { it?.let { e -> epochToNaiveLocal(e, off) } },+ )+ val m = min15+ val min15Resp = if (m == null) null else Minutely15(+ time = List(m.count) { k -> epochToNaiveLocal(m.start + k * m.step, off) },+ precipitation = m.precip,+ )+ val c = current+ val currentResp = if (c == null) null else Current(+ time = epochToNaiveLocal(c.time, off),+ temperature = c.temp,+ apparentTemperature = c.feels,+ relativeHumidity = c.rh,+ dewPoint = c.dew,+ weatherCode = c.code,+ windSpeed = c.windSpd,+ windDirection = c.windDir,+ pressureMsl = c.pres,+ visibility = c.vis,+ cloudCover = c.cloud,+ windGusts = c.gust,+ isDay = c.day,+ )+ return ForecastResponse(+ latitude = lat,+ longitude = lon,+ timezone = tz,+ timezoneAbbreviation = tzAbbr,+ utcOffsetSeconds = off,+ current = currentResp,+ hourly = hourlyResp,+ daily = dailyResp,+ minutely15 = min15Resp,+ )+}++/** `WxBundle` → [AirQualityResponse]? (null when the `aq` section is absent). */+fun WxBundle.toAirQuality(): AirQualityResponse? {+ val a = aq ?: return null+ // Server sends current-hourestamp; the display layer parses `time` as a+ // naive-local string like today's DTO.+ return AirQualityResponse(+ current = AirQualityCurrent(+ time = epochToNaiveLocal(a.time, utcOffset),+ usAqi = a.usAqi,+ alderPollen = a.alder,+ birchPollen = a.birch,+ grassPollen = a.grass,+ mugwortPollen = a.mugwort,+ olivePollen = a.olive,+ ragweedPollen = a.ragweed,+ ),+ )+}++/** `RegionTimezone` from a tz-only bundle (envelope-only body). */+fun WxBundle.toRegionTimezone(): RegionTimezone = RegionTimezone(+ timezone = tz,+ abbreviation = tzAbbr,+ utcOffsetSeconds = utcOffset,+)
weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt b/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.ktindex c9897a9c29..59714b5a75 100644--- a/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt+++ b/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt@@ -17,8 +17,8 @@ import com.vayunmathur.weather.widget.glance.WeatherGlanceWidget import com.vayunmathur.weather.network.AirQualityResponse import com.vayunmathur.weather.network.ForecastResponse import com.vayunmathur.weather.network.WeatherApi-import kotlinx.coroutines.async-import kotlinx.coroutines.coroutineScope+import com.vayunmathur.weather.network.toAirQuality+import com.vayunmathur.weather.network.toForecastResponse import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow@@ -144,17 +144,12 @@ class WeatherViewModel( val refreshing = prev?.copy(refreshing = true) ?: ForecastUiState(refreshing = true) current + (location.id to refreshing) }- val fetched: FetchResult = coroutineScope {- val forecastDeferred = async {- runCatching { WeatherApi.forecast(target.latitude, target.longitude) }- }- val airQualityDeferred = async {- runCatching {- WeatherApi.airQuality(target.latitude, target.longitude)- }.getOrNull()- }- FetchResult(forecastDeferred.await(), airQualityDeferred.await())- }+ // One bundle call carries forecast + AQ (same object, zero extra I/O).+ val bundle = runCatching { WeatherApi.bundle(target.latitude, target.longitude) }+ val fetched = FetchResult(+ forecast = bundle.map { it.toForecastResponse() },+ air = bundle.map { it.toAirQuality() }.getOrNull(),+ ) applyFetched(location, target, fetched) }
weather/src/main/java/com/vayunmathur/weather/ui/SearchLocationPage.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/SearchLocationPage.kt b/weather/src/main/java/com/vayunmathur/weather/ui/SearchLocationPage.ktindex 73f256a943..9ba09bd82b 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/SearchLocationPage.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/SearchLocationPage.kt@@ -44,12 +44,10 @@ import com.vayunmathur.weather.network.GeocodingResult import com.vayunmathur.weather.network.WeatherApi import com.vayunmathur.weather.platform.WeatherViewModel import com.vayunmathur.weather.platform.rememberTempUnit-import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flow-import kotlinx.coroutines.launch /** * Search-location screen registered as a `DialogPage()` route entry.@@ -91,15 +89,22 @@ fun SearchLocationPage(backStack: NavBackStack<Route>, viewModel: WeatherViewMod LaunchedEffect(results) { temps = emptyMap()- coroutineScope {- results.forEach { r ->- launch {- val temp = runCatching {- WeatherApi.currentTemperature(r.latitude, r.longitude)- }.getOrNull()- temps = temps + (r.id to temp)- }- }+ if (results.isEmpty()) return@LaunchedEffect+ // One batch call for all rows (P4) instead of N parallel+ // currentTemperature calls. Render path untouched.+ val batch = runCatching {+ WeatherApi.currentTemperatures(results.map { it.latitude to it.longitude })+ }.getOrDefault(emptyMap())+ temps = results.associate { r ->+ // Match by coordinate (batch keys are rounded server-side; fall+ // back to per-point lookup for any row the batch omitted).+ val t = batch.entries.firstOrNull { (key, _) ->+ kotlin.math.abs(key.first - r.latitude) < 0.005 &&+ kotlin.math.abs(key.second - r.longitude) < 0.005+ }?.value ?: runCatching {+ WeatherApi.currentTemperature(r.latitude, r.longitude)+ }.getOrNull()+ r.id to t } }
weather/src/test/java/com/vayunmathur/weather/data/GeoDatabaseTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/data/GeoDatabaseTest.kt b/weather/src/test/java/com/vayunmathur/weather/data/GeoDatabaseTest.ktnew file mode 100644index 0000000000..0e662c4c2b--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/data/GeoDatabaseTest.kt@@ -0,0 +1,33 @@+package com.vayunmathur.weather.data++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++class GeoDatabaseTest {++ @Test+ fun escaper_prefixMatchesEveryToken() {+ // Prefix `*` on every token: half-typed words must match (see+ // ReferenceCatalog.escapeFtsQuery — same contract).+ assertEquals("\"Ber\"*", GeoDatabase.escapeFtsQuery("Ber"))+ assertEquals("\"New\"* \"York\"*", GeoDatabase.escapeFtsQuery("New York"))+ }++ @Test+ fun escaper_quotesOperators() {+ assertEquals("\"Ben\"* \"Jerry\"* \"s\"*", GeoDatabase.escapeFtsQuery("Ben & Jerry's"))+ }++ @Test+ fun escaper_unicodeSurvivesWhole() {+ assertEquals("\"caf\u00e9\"*", GeoDatabase.escapeFtsQuery("café"))+ }++ @Test+ fun escaper_blankIsNull() {+ assertNull(GeoDatabase.escapeFtsQuery(""))+ assertNull(GeoDatabase.escapeFtsQuery(" "))+ assertNull(GeoDatabase.escapeFtsQuery("- *"))+ }+}
weather/src/test/java/com/vayunmathur/weather/network/WxBundleMapperTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/network/WxBundleMapperTest.kt b/weather/src/test/java/com/vayunmathur/weather/network/WxBundleMapperTest.ktnew file mode 100644index 0000000000..cadda049a2--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/network/WxBundleMapperTest.kt@@ -0,0 +1,136 @@+package com.vayunmathur.weather.network++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Golden tests for the self-hosted bundle mapper: wire epochs in, the exact+ * naive-local strings Open-Meteo used to send out. Anchored on Berlin+ * (CEST, UTC+2 in October): 2026-10-07T01:00Z == "2026-10-07T03:00" local.+ */+class WxBundleMapperTest {++ private fun bundle() = WxBundle(+ lat = 52.52,+ lon = 13.41,+ tz = "Europe/Berlin",+ tzAbbr = "CEST",+ utcOffset = 7200,+ current = WxCurrent(+ time = 1791334800, temp = 13.05, feels = 12.3, rh = 91,+ dew = 11.6, code = 2, windSpd = 3.6, windDir = 96,+ pres = 1017.4, vis = 8000.0, cloud = 62, gust = 6.5, day = 0,+ ),+ hourly = WxHourly(+ start = 1791334800, step = 3600, count = 2,+ temp = listOf(13.05, 12.8), feels = listOf(12.3, 12.0),+ rh = listOf(91, 92), dew = listOf(11.6, 11.4),+ code = listOf(2, 2), pprob = listOf(5, 5),+ precip = listOf(0.0, 0.0), windSpd = listOf(3.6, 4.0),+ windDir = listOf(96, 100), pres = listOf(1017.4, 1017.0),+ vis = listOf(8000.0, 8000.0), uv = listOf(0.0, 0.0),+ cloud = listOf(62, 65), gust = listOf(6.5, 7.0),+ day = listOf(0, 0),+ ),+ daily = WxDaily(+ start = "2026-10-07", count = 2,+ code = listOf(2, 3), tmax = listOf(18.0, 17.0),+ tmin = listOf(11.0, 10.0), feelsMax = listOf(17.5, 16.5),+ feelsMin = listOf(10.5, 9.5),+ sunrise = listOf(1791315600, 1791402000),+ sunset = listOf(1791356400, 1791442800),+ daylight = listOf(40800, 40800), sunshine = listOf(20000, 18000),+ uvMax = listOf(3.0, 2.5), pprobMax = listOf(10, 20),+ precipSum = listOf(0.0, 0.5), moonPhase = listOf(0.98, 0.01),+ moonrise = listOf(1791320000, null), moonset = listOf(1791340000, 1791420000),+ ),+ min15 = WxMin15(start = 1791334800, step = 900, count = 4, precip = listOf(0.0, 0.0, 0.0, 0.0)),+ aq = WxAq(+ time = 1791334800, usAqi = 61, grass = 0.2, birch = 0.0,+ olive = 0.0, alder = 0.0, ragweed = 0.0, mugwort = 0.6,+ ),+ )++ @Test+ fun current_mapsToNaiveLocalStrings() {+ val f = bundle().toForecastResponse()+ assertEquals("Europe/Berlin", f.timezone)+ assertEquals("CEST", f.timezoneAbbreviation)+ assertEquals(7200, f.utcOffsetSeconds)+ val c = assertNotNull(f.current)+ assertEquals("2026-10-07T03:00", c.time)+ assertEquals(13.05, c.temperature)+ assertEquals(2, c.weatherCode)+ }++ @Test+ fun hourly_expandsSeriesToLocalIso() {+ val h = assertNotNull(bundle().toForecastResponse().hourly)+ assertEquals(listOf("2026-10-07T03:00", "2026-10-07T04:00"), h.time)+ assertEquals(listOf(13.05, 12.8), h.temperature)+ assertEquals(listOf(2, 2), h.weatherCode)+ }++ @Test+ fun daily_datesAreConsecutiveFromStart() {+ val d = assertNotNull(bundle().toForecastResponse().daily)+ assertEquals(listOf("2026-10-07", "2026-10-08"), d.time)+ assertEquals(listOf(18.0, 17.0), d.temperatureMax)+ // Epoch sun/moon instants become naive-local `yyyy-MM-dd'T'HH:mm`;+ // monthly-skipped moon events stay null.+ val iso = Regex("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}")+ assertTrue(d.sunrise.all { iso.matches(it) })+ assertTrue(d.sunset.all { iso.matches(it) })+ assertEquals(null, d.moonrise[1])+ assertNotNull(d.moonset[1])+ }++ @Test+ fun min15_expandsQuarterHours() {+ val m = assertNotNull(bundle().toForecastResponse().minutely15)+ assertEquals(+ listOf("2026-10-07T03:00", "2026-10-07T03:15", "2026-10-07T03:30", "2026-10-07T03:45"),+ m.time,+ )+ }++ @Test+ fun aq_mapsPollenBySpecies() {+ val a = assertNotNull(bundle().toAirQuality()?.current)+ assertEquals(61, a.usAqi)+ assertEquals(0.2, a.grassPollen)+ assertEquals("2026-10-07T03:00", a.time)+ }++ @Test+ fun missingAq_mapsToNull() {+ assertNull(bundle().copy(aq = null).toAirQuality())+ }++ @Test+ fun tzBundle_mapsToRegionTimezone() {+ val tz = bundle().toRegionTimezone()+ assertEquals("Europe/Berlin", tz.timezone)+ assertEquals("CEST", tz.abbreviation)+ assertEquals(7200, tz.utcOffsetSeconds)+ }++ @Test+ fun nullUv_passesThrough_notCrash() {+ // CAMS UV horizon (~4d) is shorter than the 14-day window: the wire+ // carries JSON null past coverage. Nulls pass through end-to-end+ // (DTO lists are nullable-element, JSON- and cache-safe); consumers+ // skip them via getOrNull fallbacks. NaN must never appear: JSON can+ // neither parse nor emit it under strict kotlinx settings.+ val b = bundle().copy(+ hourly = bundle().hourly!!.copy(uv = listOf(3.0, null)),+ daily = bundle().daily!!.copy(uvMax = listOf(3.0, null)),+ )+ val f = b.toForecastResponse()+ assertEquals(listOf(3.0, null), assertNotNull(f.hourly).uvIndex)+ assertEquals(listOf(3.0, null), assertNotNull(f.daily).uvIndexMax)+ }+}