Modern Apps git

← Modern-Apps.git

general: moved filedownloader to library to use for openassistant and maps

Commit
090dc69cecaad890fb6726df9e6735d3bf8a4c90
Author
Vayun Mathur <[email protected]>
When
2026-03-09 22:23 UTC (9 months ago)
Parents
4684ee3

Diff

library/src/main/java/com/vayunmathur/library/ui/InitialDownloader.kt
diff --git a/library/src/main/java/com/vayunmathur/library/ui/InitialDownloader.kt b/library/src/main/java/com/vayunmathur/library/ui/InitialDownloader.ktnew file mode 100644index 0000000000..58abc4a998--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/ui/InitialDownloader.kt@@ -0,0 +1,147 @@+package com.vayunmathur.library.ui++import android.app.DownloadManager+import android.content.Context+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import androidx.core.net.toUri+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.util.round+import kotlinx.coroutines.delay+++@Composable+fun InitialDownloadChecker(ds: DataStoreUtils, filesToDownload: List<Triple<String, String, String>>, mainPage: @Composable () -> Unit) {+    val dbSetup by ds.booleanFlow("dbSetupComplete").collectAsState(false)+    if(dbSetup) {+        mainPage()+    } else {+        InitialDownloadScreen(ds, filesToDownload)+    }+}++@Composable+fun InitialDownloadScreen(ds: DataStoreUtils, filesToDownload: List<Triple<String, String, String>>) {+    val context = LocalContext.current+    val progress by ds.doubleFlow("downloadProgress").collectAsState(0.0)++    LaunchedEffect(Unit) {+        // Enqueue all downloads and collect their DownloadManager IDs+        val downloadIds = filesToDownload.map { (url, fileName, desc) ->+            downloadFile(context, url, fileName, desc)+        }++        // Poll DownloadManager until aggregate progress is 1.0 (100%)+        while (true) {+            val currentProgress = getAggregateProgress(context, downloadIds)+            ds.setDouble("downloadProgress", currentProgress)++            if (currentProgress >= 1.0) break+            delay(500) // Check twice a second+        }++        ds.setBoolean("dbSetupComplete", true)+    }++    Scaffold { paddingValues ->+        Box(+            Modifier.padding(paddingValues).fillMaxSize(),+            contentAlignment = Alignment.Center+        ) {+            Column(horizontalAlignment = Alignment.CenterHorizontally) {+                CircularProgressIndicator(progress = { progress.toFloat() })+                Spacer(modifier = Modifier.height(16.dp))+                Text("Downloading Initial Data: ${(progress * 100).round(2)}%")+            }+        }+    }+}++private fun getAggregateProgress(context: Context, downloadIds: List<Long>): Double {+    if (downloadIds.isEmpty()) return 1.0++    val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager+    val query = DownloadManager.Query().setFilterById(*downloadIds.toLongArray())+    val cursor = downloadManager.query(query) ?: return 0.0++    var totalBytes = 0L+    var downloadedBytes = 0L+    var allCompleted = true++    while (cursor.moveToNext()) {+        val status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))+        val bytesDownloaded = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))+        val bytesTotal = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))++        if (status != DownloadManager.STATUS_SUCCESSFUL) {+            allCompleted = false+        }++        if (bytesTotal > 0) {+            totalBytes += bytesTotal+            downloadedBytes += bytesDownloaded+        }+    }+    cursor.close()++    // If totalBytes is still 0 (e.g., pending connection), report 0%+    if (totalBytes == 0L) return if (allCompleted) 1.0 else 0.0++    // Ensure we return exactly 1.0 if completed, otherwise a precise ratio+    return if (allCompleted) 1.0 else (downloadedBytes.toDouble() / totalBytes)+}++private fun downloadFile(context: Context, url: String, fileName: String, description: String): Long {+    val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager++    // 1. Check if the specific file is already downloading or completed+    val query = DownloadManager.Query()+    val cursor = downloadManager.query(query)++    if (cursor != null) {+        while (cursor.moveToNext()) {+            val title = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE))+            val status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))++            // Check by the specific fileName so we don't mix up the routing binaries+            if (title == fileName) {+                val id = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID))++                // If it's running, pending, or successful, return the existing ID+                if (status == DownloadManager.STATUS_RUNNING ||+                    status == DownloadManager.STATUS_PENDING ||+                    status == DownloadManager.STATUS_SUCCESSFUL) {+                    cursor.close()+                    return id+                }+            }+        }+        cursor.close()+    }++    // 2. If no active/completed download found for this file, start a new one+    val request = DownloadManager.Request(url.toUri())+        .setTitle(fileName)+        .setDescription(description)+        .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)+        .setDestinationInExternalFilesDir(context, null, fileName)+        .setAllowedOverMetered(false) // Wait for WiFi for these massive files+        .setRequiresCharging(false)++    return downloadManager.enqueue(request)+}\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/MainActivity.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt b/maps/src/main/java/com/vayunmathur/maps/MainActivity.ktindex 8dbd453e45..1fc6e825ed 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -28,6 +28,7 @@ import androidx.core.net.toUri import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation3.runtime.NavKey import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.InitialDownloadChecker import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack@@ -63,65 +64,21 @@ class MainActivity : ComponentActivity() {         ensurePmtilesReady(this)         setContent {             DynamicTheme {-                val dbSetup by ds.booleanFlow("dbSetupComplete").collectAsState(false)-                if(dbSetup) {+                InitialDownloadChecker(ds, listOf(+                    Triple("https://data.vayunmathur.com/amenities.db", "amenities.db", "Downloading Amenity Database..."),+                    Triple("https://data.vayunmathur.com/nodes_lookup.bin", "nodes_lookup.bin", "Downloading Routing Nodes..."),+                    Triple("https://data.vayunmathur.com/nodes_spatial.bin", "nodes_spatial.bin", "Downloading Spatial Index..."),+                    Triple("https://data.vayunmathur.com/edges.bin", "edges.bin", "Downloading Routing Graph..."),+                    Triple("https://data.vayunmathur.com/edge_index.bin", "edge_index.bin", "Downloading Edge Index...")+                )) {                     val db = remember { buildAmenityDatabase(this@MainActivity) }                     Navigation(ds, db)-                } else {-                    DatabaseSetup(ds)                 }             }         }     } } -@Composable-fun DatabaseSetup(ds: DataStoreUtils) {-    val context = LocalContext.current-    val progress by ds.doubleFlow("downloadProgress").collectAsState(0.0)--    LaunchedEffect(Unit) {-        // Define all the files needed for the routing engine and amenities-        val filesToDownload = listOf(-            Triple("https://data.vayunmathur.com/amenities.db", "amenities.db", "Downloading Amenity Database..."),-            Triple("https://data.vayunmathur.com/nodes_lookup.bin", "nodes_lookup.bin", "Downloading Routing Nodes..."),-            Triple("https://data.vayunmathur.com/nodes_spatial.bin", "nodes_spatial.bin", "Downloading Spatial Index..."),-            Triple("https://data.vayunmathur.com/edges.bin", "edges.bin", "Downloading Routing Graph..."),-            Triple("https://data.vayunmathur.com/edge_index.bin", "edge_index.bin", "Downloading Edge Index...")-        )--        // Enqueue all downloads and collect their DownloadManager IDs-        val downloadIds = filesToDownload.map { (url, fileName, desc) ->-            downloadMapData(context, url, fileName, desc)-        }--        // Poll DownloadManager until aggregate progress is 1.0 (100%)-        while (true) {-            val currentProgress = getAggregateProgress(context, downloadIds)-            ds.setDouble("downloadProgress", currentProgress)--            if (currentProgress >= 1.0) break-            delay(500) // Check twice a second-        }--        ds.setBoolean("dbSetupComplete", true)-    }--    Scaffold { paddingValues ->-        Box(-            Modifier.padding(paddingValues).fillMaxSize(),-            contentAlignment = Alignment.Center-        ) {-            Column(horizontalAlignment = Alignment.CenterHorizontally) {-                CircularProgressIndicator(progress = { progress.toFloat() })-                Spacer(modifier = Modifier.height(16.dp))-                Text("Downloading Offline Map Data: ${String.format("%.1f", progress * 100)}%")-                Text("Please keep the app open.", modifier = Modifier.padding(top = 8.dp))-            }-        }-    }-}- @Serializable sealed interface Route: NavKey {     @Serializable@@ -147,78 +104,4 @@ fun Navigation(ds: DataStoreUtils, db: AmenityDatabase, viewModel: SelectedFeatu             SearchPage(backStack, viewModel, db, it.idx, it.east, it.west, it.north, it.south)         }     }-}--fun getAggregateProgress(context: Context, downloadIds: List<Long>): Double {-    if (downloadIds.isEmpty()) return 1.0--    val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager-    val query = DownloadManager.Query().setFilterById(*downloadIds.toLongArray())-    val cursor = downloadManager.query(query) ?: return 0.0--    var totalBytes = 0L-    var downloadedBytes = 0L-    var allCompleted = true--    while (cursor.moveToNext()) {-        val status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))-        val bytesDownloaded = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))-        val bytesTotal = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))--        if (status != DownloadManager.STATUS_SUCCESSFUL) {-            allCompleted = false-        }--        if (bytesTotal > 0) {-            totalBytes += bytesTotal-            downloadedBytes += bytesDownloaded-        }-    }-    cursor.close()--    // If totalBytes is still 0 (e.g., pending connection), report 0%-    if (totalBytes == 0L) return if (allCompleted) 1.0 else 0.0--    // Ensure we return exactly 1.0 if completed, otherwise a precise ratio-    return if (allCompleted) 1.0 else (downloadedBytes.toDouble() / totalBytes)-}--fun downloadMapData(context: Context, url: String, fileName: String, description: String): Long {-    val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager--    // 1. Check if the specific file is already downloading or completed-    val query = DownloadManager.Query()-    val cursor = downloadManager.query(query)--    if (cursor != null) {-        while (cursor.moveToNext()) {-            val title = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE))-            val status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))--            // Check by the specific fileName so we don't mix up the routing binaries-            if (title == fileName) {-                val id = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID))--                // If it's running, pending, or successful, return the existing ID-                if (status == DownloadManager.STATUS_RUNNING ||-                    status == DownloadManager.STATUS_PENDING ||-                    status == DownloadManager.STATUS_SUCCESSFUL) {-                    cursor.close()-                    return id-                }-            }-        }-        cursor.close()-    }--    // 2. If no active/completed download found for this file, start a new one-    val request = DownloadManager.Request(url.toUri())-        .setTitle(fileName)-        .setDescription(description)-        .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)-        .setDestinationInExternalFilesDir(context, null, fileName)-        .setAllowedOverMetered(false) // Wait for WiFi for these massive files-        .setRequiresCharging(false)--    return downloadManager.enqueue(request) }\ No newline at end of file
openassistant/build.gradle.kts
diff --git a/openassistant/build.gradle.kts b/openassistant/build.gradle.ktsindex 58d4b8700c..56ed1135fe 100644--- a/openassistant/build.gradle.kts+++ b/openassistant/build.gradle.kts@@ -22,6 +22,8 @@ dependencies {     implementation(libs.androidx.work.runtime.ktx)     ksp(libs.androidx.room.compiler) +    implementation("org.codeshipping:llama-kotlin-android:0.1.0")+     // markdown     implementation(libs.compose.markdown) }\ No newline at end of file
openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.ktindex f9dd979b17..cb292b0e99 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt@@ -7,6 +7,7 @@ import androidx.activity.enableEdgeToEdge import androidx.compose.runtime.Composable import androidx.navigation3.runtime.NavKey import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.InitialDownloadChecker import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.DatabaseViewModel import com.vayunmathur.library.util.IntentLauncher@@ -35,7 +36,11 @@ class MainActivity : ComponentActivity() {          setContent {             DynamicTheme {-                Navigation(viewModel, ds)+                InitialDownloadChecker(ds, listOf(+                    Triple("https://huggingface.co/bartowski/Phi-3.5-mini-instruct-GGUF/resolve/main/Phi-3.5-mini-instruct-Q4_K_M.gguf", "phi3.gguf", "model weights")+                )) {+                    Navigation(viewModel, ds)+                }             }         }     }