Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
fix(updater): skip a muted updates channel and serialize overlapping checks
Durganshue1c0d086ed32
diff --git a/app/src/main/java/com/gotcha/updater/UpdateNotifications.kt b/app/src/main/java/com/gotcha/updater/UpdateNotifications.ktindex db65057..619e929 100644--- a/app/src/main/java/com/gotcha/updater/UpdateNotifications.kt+++ b/app/src/main/java/com/gotcha/updater/UpdateNotifications.kt@@ -20,6 +20,8 @@ import com.gotcha.notifications.LocalNotifier.Companion.putTargetExtrasimport com.gotcha.notifications.NotificationCategoryimport com.gotcha.notifications.NotificationTargetimport com.gotcha.notifications.inQuietHours+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLockimport java.time.Instantimport java.time.ZoneId@@ -48,6 +50,13 @@ internal fun updateCheckDue(now: Long, lastCheckedAt: Long): Boolean =/** What one background check did, for tests and the log. */enum class UpdateCheckOutcome { OFF, CANNOT_POST, NOT_DUE, OFFLINE, QUIET_HOURS, FAILED, UP_TO_DATE, NOTIFIED }+/**+ * App start and the reminder alarm can both start a check. Without this, two+ * overlapping checks read the same timestamps, fetch the same manifest, and+ * each announce the same version.+ */+private val updateCheckLock = Mutex()+/** When the check last ran and which version was last announced. Not personal, so not encrypted. */internal class UpdateCheckStore(private val prefs: SharedPreferences) {@@ -92,10 +101,11 @@ internal suspend fun runUpdateCheck(installedVersionCode: Int = BuildConfig.VERSION_CODE,zone: ZoneId = ZoneId.systemDefault(),isOnline: () -> Boolean = { hasValidatedNetwork(context) }-): UpdateCheckOutcome {+): UpdateCheckOutcome = updateCheckLock.withLock {val settings = SettingsRepository(context).load()if (!settings.updateNotificationsEnabled) return UpdateCheckOutcome.OFFval notifier = UpdateNotifier(context)+ // Includes the updates channel: a post to a muted one is silently dropped.if (!notifier.canPost()) return UpdateCheckOutcome.CANNOT_POSTval store = UpdateCheckStore(context)if (!updateCheckDue(now, store.lastCheckedAt)) return UpdateCheckOutcome.NOT_DUE@@ -122,7 +132,7 @@ internal suspend fun runUpdateCheck()if (!notify || !notifier.post(info, LocalNotificationStore(context))) return UpdateCheckOutcome.UP_TO_DATEstore.lastNotifiedVersionCode = info.versionCode- return UpdateCheckOutcome.NOTIFIED+ UpdateCheckOutcome.NOTIFIED}/** An alarm has no network constraint, so the check asks for itself. */@@ -140,7 +150,18 @@ private fun hasValidatedNetwork(context: Context): Boolean {*/class UpdateNotifier(private val context: Context) {- fun canPost(): Boolean = ChatCompletionNotifier(context).canPost()+ /**+ * The app may post and the user has not muted this channel. Android drops a+ * post to a muted channel without a word, so posting there would mark the+ * version announced and lose it. A channel not created yet is created on+ * the first post with default importance, so it counts as on.+ */+ fun canPost(): Boolean {+ if (!ChatCompletionNotifier(context).canPost()) return false+ val channel = context.getSystemService(NotificationManager::class.java)+ ?.getNotificationChannel(CHANNEL_ID) ?: return true+ return channel.importance != NotificationManager.IMPORTANCE_NONE+ }@Suppress("MissingPermission") // canPost() checks it.fun post(info: AppUpdateInfo, inbox: LocalNotificationStore): Boolean {diff --git a/app/src/test/java/com/gotcha/updater/UpdateNotificationsTest.kt b/app/src/test/java/com/gotcha/updater/UpdateNotificationsTest.ktindex 3af3308..f5fd89f 100644--- a/app/src/test/java/com/gotcha/updater/UpdateNotificationsTest.kt+++ b/app/src/test/java/com/gotcha/updater/UpdateNotificationsTest.kt@@ -2,6 +2,7 @@ package com.gotcha.updaterimport android.Manifestimport android.app.Application+import android.app.NotificationChannelimport android.app.NotificationManagerimport androidx.test.core.app.ApplicationProviderimport com.gotcha.data.Settings@@ -11,6 +12,9 @@ import com.gotcha.notifications.LocalNotifierimport com.gotcha.notifications.NotificationCategoryimport com.gotcha.notifications.NotificationTargetimport com.gotcha.testsupport.FakeAndroidKeyStore+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAllimport kotlinx.coroutines.runBlockingimport okhttp3.mockwebserver.MockResponseimport okhttp3.mockwebserver.MockWebServer@@ -26,6 +30,7 @@ import org.robolectric.Shadows.shadowOfimport org.robolectric.annotation.Configimport java.time.LocalDateimport java.time.ZoneId+import java.util.concurrent.TimeUnit/** The background update check and its notification (issue #126). */@RunWith(RobolectricTestRunner::class)@@ -61,7 +66,9 @@ class UpdateNotificationsTest {private fun trustedUrl(versionCode: Int) ="https://github.com/samosa-ai-com/Gotcha/releases/download/v1.$versionCode.0/gotcha.apk"- private fun check(now: Long = noon, online: Boolean = true) = runBlocking {+ private fun check(now: Long = noon, online: Boolean = true) = runBlocking { checkNow(now, online) }++ private suspend fun checkNow(now: Long = noon, online: Boolean = true) =runUpdateCheck(application,now = now,@@ -71,6 +78,15 @@ class UpdateNotificationsTest {zone = zone,isOnline = { online })++ /** What the user does in Android's settings; an app cannot raise a channel's importance itself. */+ private fun setChannelImportance(importance: Int) {+ val channel = manager.getNotificationChannel(UpdateNotifier.CHANNEL_ID)+ if (channel == null) {+ manager.createNotificationChannel(NotificationChannel(UpdateNotifier.CHANNEL_ID, "Updates", importance))+ } else {+ channel.importance = importance+ }}private fun posted() = shadowOf(manager).allNotifications@@ -188,4 +204,38 @@ class UpdateNotificationsTest {server.enqueue(manifest(8))assertEquals(UpdateCheckOutcome.NOTIFIED, check(noon + 2 * 60 * 60 * 1000L))}++ @Test+ fun `with the updates channel muted, nothing is fetched or recorded`() {+ setChannelImportance(NotificationManager.IMPORTANCE_NONE)++ assertEquals(UpdateCheckOutcome.CANNOT_POST, check())+ assertEquals(0, server.requestCount)+ assertTrue(LocalNotificationStore(application).entries().isEmpty())++ // Unmuted later: the same version is still announced.+ setChannelImportance(NotificationManager.IMPORTANCE_DEFAULT)+ server.enqueue(manifest(8))+ assertEquals(UpdateCheckOutcome.NOTIFIED, check(noon + 1))+ assertEquals(1, posted().size)+ }++ @Test+ fun `overlapping checks fetch and announce a version once`() {+ // Slow enough that the second check starts while the first waits on the network.+ server.enqueue(manifest(8).setBodyDelay(300, TimeUnit.MILLISECONDS))+ server.enqueue(manifest(8))++ val outcomes = runBlocking {+ List(2) { async(Dispatchers.IO) { checkNow() } }.awaitAll()+ }++ assertEquals(+ listOf(UpdateCheckOutcome.NOTIFIED, UpdateCheckOutcome.NOT_DUE),+ outcomes.sortedBy { it.ordinal }.reversed()+ )+ assertEquals(1, server.requestCount)+ assertEquals(1, posted().size)+ assertEquals(1, LocalNotificationStore(application).entries().size)+ }}