π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Wrap the Android model download in a user-initiated data transfer job
Manav Rathi2a45eea0985b
diff --git a/mobile/native/android/apps/ensu/app/src/main/AndroidManifest.xml b/mobile/native/android/apps/ensu/app/src/main/AndroidManifest.xmlindex 4e502af05d..cf009beba6 100644--- a/mobile/native/android/apps/ensu/app/src/main/AndroidManifest.xml+++ b/mobile/native/android/apps/ensu/app/src/main/AndroidManifest.xml@@ -4,6 +4,7 @@<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.RECORD_AUDIO" /><uses-permission android:name="android.permission.VIBRATE" />+ <uses-permission android:name="android.permission.RUN_USER_INITIATED_JOBS" /><applicationandroid:name=".EnsuApplication"@@ -24,6 +25,11 @@</intent-filter></activity>+ <service+ android:name=".llm.ModelDownloadJobService"+ android:exported="false"+ android:permission="android.permission.BIND_JOB_SERVICE" />+<providerandroid:name="androidx.core.content.FileProvider"android:authorities="${applicationId}.fileprovider"diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.ktindex 94998d1ba6..d7d7c0e927 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt@@ -33,6 +33,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {val logRepository = FileLogRepository(application)private val llmProvider = LlmProvider(+ context = application,modelDir = resolveModelDir(application),transcriber = transcriber,legacyModelDir = File(application.filesDir, "llm"),diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.ktindex 84cbf322b3..2189806304 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt@@ -1,5 +1,6 @@package io.ente.ensu.llm+import android.content.Contextimport android.util.Logimport io.ente.ensu.bindings.LlmChatMessage as NativeChatMessageimport io.ente.ensu.bindings.LlmChatRequest@@ -35,6 +36,7 @@ import kotlinx.coroutines.withContextimport okhttp3.OkHttpClientclass LlmProvider(+ context: Context,private val modelDir: File,private val transcriber: Transcriber,private val deviceCapabilityProvider: AndroidDeviceCapabilityProvider,@@ -47,6 +49,7 @@ class LlmProvider()private val httpClient = OkHttpClient()+ private val appContext = context.applicationContext@Volatile private var loadedModel: LlmModel? = null@Volatile private var loadedContext: LlmContext? = null@@ -298,6 +301,7 @@ class LlmProvider(val downloadJob = coroutineContext[Job]manualDownloadCancelled = falsemanualDownloadActive = true+ ModelDownloadJobService.begin(appContext) { manualDownloadCancelled = true }try {val targets = ModelDownloadSupport.expectedTargets(modelDir, target).map {@@ -312,6 +316,11 @@ class LlmProvider(object : LlmModelDownloadCallback {override fun onProgress(progress: LlmModelDownloadProgress) {logDownloadMetrics(progress)+ ModelDownloadJobService.update(+ appContext,+ progress.downloadedBytes,+ progress.totalBytes+ )onProgress(progress.toDomainProgress())}@@ -321,6 +330,7 @@ class LlmProvider()} finally {manualDownloadActive = false+ ModelDownloadJobService.end(appContext)}}diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelDownloadJobService.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelDownloadJobService.ktnew file mode 100644index 0000000000..5165f45936--- /dev/null+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelDownloadJobService.kt@@ -0,0 +1,134 @@+package io.ente.ensu.llm++import android.app.Notification+import android.app.job.JobInfo+import android.app.job.JobParameters+import android.app.job.JobScheduler+import android.app.job.JobService+import android.content.ComponentName+import android.content.Context+import android.os.Build+import android.os.SystemClock+import androidx.annotation.RequiresApi+import androidx.core.app.NotificationChannelCompat+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat++@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)+class ModelDownloadJobService : JobService() {+ override fun onStartJob(params: JobParameters): Boolean {+ synchronized(lock) {+ if (!downloadActive) return false+ runningJob = this+ runningParams = params+ }+ setNotification(+ params,+ NOTIFICATION_ID,+ buildNotification(this, 0, true),+ JOB_END_NOTIFICATION_POLICY_REMOVE+ )+ return true+ }++ override fun onStopJob(params: JobParameters): Boolean {+ val cancel: (() -> Unit)?+ synchronized(lock) {+ if (runningParams !== params) return false+ runningJob = null+ runningParams = null+ cancel = onCancel+ }+ cancel?.invoke()+ return false+ }++ companion object {+ private const val CHANNEL_ID = "model-download"+ private const val NOTIFICATION_ID = 1+ private const val JOB_ID = 1+ private const val NOTIFY_INTERVAL_MS = 1000L++ private val lock = Any()+ private var onCancel: (() -> Unit)? = null+ private var downloadActive = false+ private var lastNotifyMs = 0L+ private var runningJob: ModelDownloadJobService? = null+ private var runningParams: JobParameters? = null++ fun begin(context: Context, onCancelled: () -> Unit) {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return+ synchronized(lock) {+ onCancel = onCancelled+ downloadActive = true+ lastNotifyMs = 0L+ }+ val scheduler = context.getSystemService(JobScheduler::class.java) ?: return+ val job = JobInfo.Builder(JOB_ID, ComponentName(context, ModelDownloadJobService::class.java))+ .setUserInitiated(true)+ .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)+ .build()+ runCatching { scheduler.schedule(job) }+ }++ fun update(context: Context, downloadedBytes: Long, totalBytes: Long?) {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return+ val job: ModelDownloadJobService+ val params: JobParameters+ synchronized(lock) {+ if (!downloadActive) return+ job = runningJob ?: return+ params = runningParams ?: return+ val now = SystemClock.elapsedRealtime()+ if (now - lastNotifyMs < NOTIFY_INTERVAL_MS) return+ lastNotifyMs = now+ }+ val percent = totalBytes?.takeIf { it > 0 }+ ?.let { ((downloadedBytes * 100) / it).toInt().coerceIn(0, 100) }+ job.setNotification(+ params,+ NOTIFICATION_ID,+ buildNotification(context, percent ?: 0, percent == null),+ JOB_END_NOTIFICATION_POLICY_REMOVE+ )+ }++ fun end(context: Context) {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return+ val job: ModelDownloadJobService?+ val params: JobParameters?+ synchronized(lock) {+ downloadActive = false+ onCancel = null+ job = runningJob+ params = runningParams+ runningJob = null+ runningParams = null+ }+ if (job != null && params != null) {+ job.jobFinished(params, false)+ } else {+ context.getSystemService(JobScheduler::class.java)?.cancel(JOB_ID)+ }+ }++ private fun buildNotification(+ context: Context,+ percent: Int,+ indeterminate: Boolean+ ): Notification {+ NotificationManagerCompat.from(context).createNotificationChannel(+ NotificationChannelCompat.Builder(CHANNEL_ID, NotificationManagerCompat.IMPORTANCE_LOW)+ .setName("Model downloads")+ .build()+ )+ return NotificationCompat.Builder(context, CHANNEL_ID)+ .setSmallIcon(android.R.drawable.stat_sys_download)+ .setContentTitle("Downloading model")+ .setProgress(100, percent, indeterminate)+ .setOngoing(true)+ .setOnlyAlertOnce(true)+ .build()+ }+ }+}