Skip to content

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.kt
index 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.putTargetExtras
import com.gotcha.notifications.NotificationCategory
import com.gotcha.notifications.NotificationTarget
import com.gotcha.notifications.inQuietHours
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
import java.time.Instant
import 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.OFF
val notifier = UpdateNotifier(context)
+ // Includes the updates channel: a post to a muted one is silently dropped.
if (!notifier.canPost()) return UpdateCheckOutcome.CANNOT_POST
val 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_DATE
store.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.kt
index 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.updater
import android.Manifest
import android.app.Application
+import android.app.NotificationChannel
import android.app.NotificationManager
import androidx.test.core.app.ApplicationProvider
import com.gotcha.data.Settings
@@ -11,6 +12,9 @@ import com.gotcha.notifications.LocalNotifier
import com.gotcha.notifications.NotificationCategory
import com.gotcha.notifications.NotificationTarget
import com.gotcha.testsupport.FakeAndroidKeyStore
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.runBlocking
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
@@ -26,6 +30,7 @@ import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import java.time.LocalDate
import 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)
+ }
}