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.

feat(updater): notify when a new version is released (#126)

Durganshu1bb043f3f482
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b5e761a..edd23d2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,12 @@ All notable changes to Gotcha are documented here.
## [Unreleased]
### Added
+- **A notification when a new version is out** (#126). About twice a day,
+ Gotcha checks GitHub for a newer release and, once per version, posts a
+ notification. Tapping it opens Settings ▸ About, already checking, with the
+ download ready. The check skips quiet hours and stays silent when offline.
+ It can be turned off under Settings ▸ Notifications ▸ App updates, or muted
+ through its own "App updates" channel in Android's settings.
- **Russian voice and replies, and roubles** (#122). Russian can now be picked
as the voice language and the reply language: Android speech is asked for
`ru-RU` and API speech-to-text for `ru`, and the short phrases Gotcha speaks
diff --git a/README.md b/README.md
index c308902..26935c0 100644
--- a/README.md
+++ b/README.md
@@ -38,6 +38,8 @@ Everything runs in **one self-contained app on your phone**. Bring your own API
Grab the latest `.apk` from [**GitHub Releases**](https://github.com/samosa-ai-com/Gotcha/releases/latest), then follow the **[Getting Started Guide](https://samosa-ai.com/gotcha/docs/getting-started)** — or watch the [**video walkthrough**](https://www.youtube.com/watch?v=Zk5-dtqRB64) above. 🛠️
+Once installed, Gotcha tells you when a new version is out. About twice a day it downloads [`update.json`](update.json) from GitHub; the request carries no account or device identifier, though GitHub sees your IP address as with any download. Tapping the notification opens **Settings ▸ About**, which downloads the APK, checks its SHA-256 and hands it to Android's installer. Turn it off under **Settings ▸ Notifications ▸ App updates**.
+
Building from source instead? 👇
```bash
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 198263b..47a1a71 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -93,6 +93,7 @@ import com.gotcha.ui.tour.TourNavigation
import com.gotcha.ui.tour.TourOverlay
import com.gotcha.ui.tour.TourPlace
import com.gotcha.ui.tour.rememberTourHost
+import com.gotcha.updater.runUpdateCheck
import com.gotcha.util.GotchaLog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@@ -153,6 +154,9 @@ class MainActivity : ComponentActivity() {
*/
private var openDraftRequested by mutableStateOf<NotificationTarget.Draft?>(null)
+ /** Set when an update notification (or its inbox entry) is tapped: Settings ▸ About, checking (issue #126). */
+ private var openUpdateRequested by mutableStateOf(false)
+
/** Gotcha's own notification history: the inbox, its unread count, per-chat privacy (issue #100). */
private val localNotificationStore by lazy { LocalNotificationStore(applicationContext) }
private var inboxUnread by mutableStateOf(0)
@@ -332,6 +336,10 @@ class MainActivity : ComponentActivity() {
// notification alarms are armed here too. Re-arming is idempotent.
lifecycleScope.launch(Dispatchers.IO) {
runCatching { LocalNotificationScheduler.scheduleAll(applicationContext) }
+ // Re-arming pushes the 4-hour check back, so someone who opens Gotcha
+ // more often than that would never reach the update check through the
+ // alarm alone. It limits itself to about twice a day (issue #126).
+ runCatching { runUpdateCheck(applicationContext) }
}
// Tools report what they need the moment they need it. A special-access
@@ -590,6 +598,10 @@ class MainActivity : ComponentActivity() {
// Consumed, as above: a recreation must not open another chat.
intent.removeExtra(LocalNotifier.EXTRA_DRAFT_PROMPT)
}
+ if (intent?.getBooleanExtra(LocalNotifier.EXTRA_OPEN_UPDATE, false) == true) {
+ openUpdateRequested = true
+ intent.removeExtra(LocalNotifier.EXTRA_OPEN_UPDATE)
+ }
intent?.getStringExtra(LocalNotificationStore.EXTRA_INBOX_ENTRY_ID)?.let { entryId ->
intent.removeExtra(LocalNotificationStore.EXTRA_INBOX_ENTRY_ID)
lifecycleScope.launch(Dispatchers.IO) {
@@ -636,6 +648,7 @@ class MainActivity : ComponentActivity() {
when (val target = entry.target) {
is NotificationTarget.Chat -> openSessionRequested = target.sessionId
is NotificationTarget.Draft -> openDraftRequested = target
+ NotificationTarget.Update -> openUpdateRequested = true
NotificationTarget.Home -> Unit
}
}
@@ -774,6 +787,9 @@ class MainActivity : ComponentActivity() {
// rotation the page is back where it was, and a replayed highlight would
// point at something the user has already been shown.
var settingsHighlight by remember { mutableStateOf<String?>(null) }
+ // About runs its update check on arrival once, after an update notification's tap.
+ // Not saveable either: a rotation must not check again.
+ var checkUpdateOnOpen by remember { mutableStateOf(false) }
var assistiveBallOn by remember { mutableStateOf(initial.assistiveBallEnabled) }
var showFeedbackSheet by remember { mutableStateOf(false) }
var showReferralInviteDialog by remember { mutableStateOf(false) }
@@ -840,6 +856,17 @@ class MainActivity : ComponentActivity() {
}
}
+ // A tapped update notification: About, which checks and offers the download.
+ LaunchedEffect(openUpdateRequested) {
+ if (openUpdateRequested) {
+ currentRoute = Route.SETTINGS
+ settingsPage = SettingsPage.ABOUT
+ settingsHighlight = null
+ checkUpdateOnOpen = true
+ openUpdateRequested = false
+ }
+ }
+
// Honor the assistive ball's "Open Chat" option.
LaunchedEffect(openChatRequested) {
if (openChatRequested) {
@@ -1042,7 +1069,9 @@ class MainActivity : ComponentActivity() {
onOpenSearchResult = { page, field ->
settingsPage = page
settingsHighlight = field
- }
+ },
+ checkUpdateOnOpen = checkUpdateOnOpen,
+ onUpdateCheckStarted = { checkUpdateOnOpen = false }
)
}
Route.INBOX -> {
diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
index 215eeac..d51cbbc 100644
--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt
+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
@@ -237,6 +237,11 @@ data class Settings(
val pauseNightLightForScreenshots: Boolean = false,
/** Server-driven notifications from `<SAMOSA_API_URL>/v1/gotcha/notifications`. */
val serverMessagesEnabled: Boolean = true,
+ /**
+ * A notification when a newer Gotcha is published (issue #126), from a
+ * background check of update.json about twice a day. On by default.
+ */
+ val updateNotificationsEnabled: Boolean = true,
/** Epoch millis of the last successful server-messages fetch. 0 = never. */
val serverMessagesLastFetchedAt: Long = 0L,
/** Last seen ETag from the notifications endpoint; round-tripped in `If-None-Match`. */
@@ -705,6 +710,7 @@ class SettingsRepository(context: Context) : SettingsStore {
}.getOrDefault(WakeWordListeningMode.ALWAYS),
pauseNightLightForScreenshots = prefs.getBoolean(KEY_PAUSE_NIGHT_LIGHT, false),
serverMessagesEnabled = prefs.getBoolean(KEY_SERVER_MESSAGES_ENABLED, true),
+ updateNotificationsEnabled = prefs.getBoolean(KEY_UPDATE_NOTIFICATIONS_ENABLED, true),
serverMessagesLastFetchedAt = prefs.getLong(KEY_SERVER_MESSAGES_LAST_FETCHED, 0L),
serverMessagesEtag = string(KEY_SERVER_MESSAGES_ETAG),
skinId = resolvedSkinId(),
@@ -798,6 +804,7 @@ class SettingsRepository(context: Context) : SettingsStore {
.putString(KEY_WAKE_WORD_LISTENING_MODE, settings.wakeWordListeningMode.name)
.putBoolean(KEY_PAUSE_NIGHT_LIGHT, settings.pauseNightLightForScreenshots)
.putBoolean(KEY_SERVER_MESSAGES_ENABLED, settings.serverMessagesEnabled)
+ .putBoolean(KEY_UPDATE_NOTIFICATIONS_ENABLED, settings.updateNotificationsEnabled)
.putLong(KEY_SERVER_MESSAGES_LAST_FETCHED, settings.serverMessagesLastFetchedAt)
.putString(KEY_SERVER_MESSAGES_ETAG, settings.serverMessagesEtag)
.putString(KEY_SKIN_ID, settings.skinId)
@@ -934,6 +941,7 @@ class SettingsRepository(context: Context) : SettingsStore {
const val KEY_WAKE_WORD_LISTENING_MODE = "wake_word_listening_mode"
const val KEY_PAUSE_NIGHT_LIGHT = "pause_night_light_for_screenshots"
const val KEY_SERVER_MESSAGES_ENABLED = "server_messages_enabled"
+ const val KEY_UPDATE_NOTIFICATIONS_ENABLED = "update_notifications_enabled"
const val KEY_SERVER_MESSAGES_LAST_FETCHED = "server_messages_last_fetched"
const val KEY_SERVER_MESSAGES_ETAG = "server_messages_etag"
const val KEY_SKIN_ID = "skin_id"
diff --git a/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt b/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt
index 9c81628..14aa053 100644
--- a/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt
+++ b/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt
@@ -9,6 +9,7 @@ import android.util.Log
import com.gotcha.data.ChatHistoryRepository
import com.gotcha.data.SettingsRepository
import com.gotcha.i18n.stringLookup
+import com.gotcha.updater.runUpdateCheck
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@@ -113,12 +114,22 @@ class DailyTipAlarmReceiver : BroadcastReceiver() {
}
}
-/** The periodic reminder check. Not exported. */
+/**
+ * The periodic reminder check, which also carries the update check (issue #126):
+ * that one limits itself to about twice a day. Not exported.
+ */
class ReminderCheckReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val app = context.applicationContext
- runAsync("ReminderCheck") { runLocalNotificationCheck(app, includeTip = false) }
+ runAsync("ReminderCheck") {
+ // finally: a failed reminder check must not skip the update check.
+ try {
+ runLocalNotificationCheck(app, includeTip = false)
+ } finally {
+ runUpdateCheck(app)
+ }
+ }
}
}
diff --git a/app/src/main/java/com/gotcha/notifications/LocalNotificationStore.kt b/app/src/main/java/com/gotcha/notifications/LocalNotificationStore.kt
index e7430cc..0c52f05 100644
--- a/app/src/main/java/com/gotcha/notifications/LocalNotificationStore.kt
+++ b/app/src/main/java/com/gotcha/notifications/LocalNotificationStore.kt
@@ -31,6 +31,7 @@ data class InboxEntry(
val target: NotificationTarget
get() = when {
+ categoryOrNull == NotificationCategory.APP_UPDATE -> NotificationTarget.Update
sessionId != null -> NotificationTarget.Chat(sessionId)
prompt != null -> NotificationTarget.Draft(
prompt,
diff --git a/app/src/main/java/com/gotcha/notifications/LocalNotifications.kt b/app/src/main/java/com/gotcha/notifications/LocalNotifications.kt
index d492730..a791d41 100644
--- a/app/src/main/java/com/gotcha/notifications/LocalNotifications.kt
+++ b/app/src/main/java/com/gotcha/notifications/LocalNotifications.kt
@@ -25,7 +25,10 @@ enum class NotificationCategory(@StringRes val label: Int, val proactive: Boolea
INACTIVITY(R.string.notification_category_reminder, proactive = true),
DAILY_TIP(R.string.notification_category_daily_tip, proactive = true),
TASK_FINISHED(R.string.notification_category_task_finished, proactive = false),
- SERVER(R.string.notification_category_server, proactive = false)
+ SERVER(R.string.notification_category_server, proactive = false),
+
+ /** A newer Gotcha is published (issue #126). Last, so the ids of the others keep their ordinals. */
+ APP_UPDATE(R.string.notification_category_app_update, proactive = false)
}
/** Where tapping a notification (or its inbox entry) goes. */
@@ -38,6 +41,9 @@ sealed interface NotificationTarget {
/** A new chat in [mode], with [prompt] in the composer and not sent. */
data class Draft(val prompt: String, val mode: AgentMode) : NotificationTarget
+
+ /** Settings ▸ About, checking for the update the notification announced (issue #126). */
+ data object Update : NotificationTarget
}
/**
@@ -134,6 +140,7 @@ private fun categoryEnabled(category: NotificationCategory, settings: Settings):
NotificationCategory.DAILY_TIP -> settings.dailyTipsEnabled
NotificationCategory.TASK_FINISHED -> settings.chatCompletionNotificationsEnabled
NotificationCategory.SERVER -> settings.serverMessagesEnabled
+ NotificationCategory.APP_UPDATE -> settings.updateNotificationsEnabled
}
/**
diff --git a/app/src/main/java/com/gotcha/notifications/LocalNotifier.kt b/app/src/main/java/com/gotcha/notifications/LocalNotifier.kt
index 8ccb945..3e78ad4 100644
--- a/app/src/main/java/com/gotcha/notifications/LocalNotifier.kt
+++ b/app/src/main/java/com/gotcha/notifications/LocalNotifier.kt
@@ -100,6 +100,7 @@ class LocalNotifier(private val context: Context) {
const val ACTION_OPEN_LOCAL_NOTIFICATION = "com.gotcha.ACTION_OPEN_LOCAL_NOTIFICATION"
const val EXTRA_DRAFT_PROMPT = "com.gotcha.DRAFT_PROMPT"
const val EXTRA_DRAFT_MODE = "com.gotcha.DRAFT_MODE"
+ const val EXTRA_OPEN_UPDATE = "com.gotcha.OPEN_UPDATE"
internal fun notificationId(category: NotificationCategory): Int = 0x7100 + category.ordinal
@@ -111,6 +112,7 @@ class LocalNotifier(private val context: Context) {
putExtra(EXTRA_DRAFT_PROMPT, target.prompt)
putExtra(EXTRA_DRAFT_MODE, target.mode.name)
}
+ NotificationTarget.Update -> putExtra(EXTRA_OPEN_UPDATE, true)
NotificationTarget.Home -> Unit
}
}
diff --git a/app/src/main/java/com/gotcha/tools/GotchaSettingsUpdate.kt b/app/src/main/java/com/gotcha/tools/GotchaSettingsUpdate.kt
index bde043f..b5bff96 100644
--- a/app/src/main/java/com/gotcha/tools/GotchaSettingsUpdate.kt
+++ b/app/src/main/java/com/gotcha/tools/GotchaSettingsUpdate.kt
@@ -189,6 +189,13 @@ object GotchaSettingsUpdate {
setOf(SettingImpact.NOTIFICATIONS),
{ it.serverMessagesEnabled },
{ s, v -> s.copy(serverMessagesEnabled = v) }
+ ),
+ boolSpec(
+ "update_notifications",
+ "A notification when a new Gotcha version is released",
+ setOf(SettingImpact.NOTIFICATIONS),
+ { it.updateNotificationsEnabled },
+ { s, v -> s.copy(updateNotificationsEnabled = v) }
)
)
diff --git a/app/src/main/java/com/gotcha/ui/AboutScreen.kt b/app/src/main/java/com/gotcha/ui/AboutScreen.kt
index ef5f559..eb0b5c1 100644
--- a/app/src/main/java/com/gotcha/ui/AboutScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/AboutScreen.kt
@@ -44,7 +44,9 @@ import kotlinx.coroutines.launch
@Composable
fun AboutScreen(
onBack: () -> Unit,
- onOpenPage: (SettingsPage) -> Unit
+ onOpenPage: (SettingsPage) -> Unit,
+ checkUpdateOnOpen: Boolean = false,
+ onUpdateCheckStarted: () -> Unit = {}
) {
val overlay = rememberSettingsOverlayState()
@@ -58,7 +60,7 @@ fun AboutScreen(
)
}
HorizontalDivider(thickness = 1.dp)
- AppUpdateSection()
+ AppUpdateSection(checkOnOpen = checkUpdateOnOpen, onCheckStarted = onUpdateCheckStarted)
HorizontalDivider(thickness = 1.dp)
}
}
@@ -135,8 +137,13 @@ private val LINKS = listOf(
R.string.about_link_email to "mailto:[email protected]"
)
+/**
+ * Version, update check, download and install. [checkOnOpen] starts the check
+ * straight away, for an update notification's tap (issue #126), so the page
+ * opens on the offer rather than on a button; [onCheckStarted] clears it.
+ */
@Composable
-fun AppUpdateSection() {
+fun AppUpdateSection(checkOnOpen: Boolean = false, onCheckStarted: () -> Unit = {}) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val updateManager = remember { AppUpdateManager.shared }
@@ -144,6 +151,26 @@ fun AppUpdateSection() {
var busy by remember { mutableStateOf(false) }
val lifecycleOwner = LocalLifecycleOwner.current
+ fun check() {
+ if (busy) return
+ busy = true
+ scope.launch {
+ try {
+ status = UpdateStatus.Checking
+ status = updateManager.checkForUpdate()
+ } finally {
+ busy = false
+ }
+ }
+ }
+
+ LaunchedEffect(checkOnOpen) {
+ if (checkOnOpen) {
+ onCheckStarted()
+ check()
+ }
+ }
+
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME &&
@@ -177,18 +204,7 @@ fun AppUpdateSection() {
when (val currentStatus = status) {
is UpdateStatus.Idle -> {
- Button(onClick = {
- if (busy) return@Button
- busy = true
- scope.launch {
- try {
- status = UpdateStatus.Checking
- status = updateManager.checkForUpdate()
- } finally {
- busy = false
- }
- }
- }) {
+ Button(onClick = ::check) {
Text(stringResource(R.string.about_check_for_updates))
}
}
@@ -280,18 +296,7 @@ fun AppUpdateSection() {
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error
)
- Button(onClick = {
- if (busy) return@Button
- busy = true
- scope.launch {
- try {
- status = UpdateStatus.Checking
- status = updateManager.checkForUpdate()
- } finally {
- busy = false
- }
- }
- }) {
+ Button(onClick = ::check) {
Text(stringResource(R.string.about_retry_check))
}
}
diff --git a/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt b/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt
index 5907432..3eda412 100644
--- a/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt
@@ -65,6 +65,7 @@ fun NotificationsScreen(
var taskFinished by remember { mutableStateOf(initial.chatCompletionNotificationsEnabled) }
var taskPreview by remember { mutableStateOf(initial.chatCompletionPreview) }
var serverMessagesEnabled by remember { mutableStateOf(initial.serverMessagesEnabled) }
+ var updateNotifications by remember { mutableStateOf(initial.updateNotificationsEnabled) }
var lastFetched by remember { mutableStateOf(initial.serverMessagesLastFetchedAt) }
var isSyncing by remember { mutableStateOf(false) }
@@ -240,6 +241,36 @@ fun NotificationsScreen(
stringResource(R.string.notifications_last_synced, formatRelative(lastFetched)),
style = MaterialTheme.typography.bodySmall
)
+
+ Spacer(Modifier.height(16.dp))
+ Text(
+ stringResource(R.string.notifications_app_updates),
+ style = MaterialTheme.typography.titleMedium
+ )
+ Text(
+ stringResource(R.string.notifications_app_updates_description),
+ style = MaterialTheme.typography.bodySmall
+ )
+ SettingsToggleRow(
+ label = stringResource(R.string.notifications_notify_about_new_versions),
+ checked = updateNotifications,
+ onCheckedChange = {
+ updateNotifications = it
+ onSave { s -> s.copy(updateNotificationsEnabled = it) }
+ if (it && !canPost && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ notificationPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)
+ }
+ },
+ isLarge = true,
+ switchTestTag = "settings_update_notifications_enabled"
+ )
+ if (updateNotifications && !canPost) {
+ Text(
+ stringResource(R.string.notifications_notifications_are_blocked_for_gotcha),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error
+ )
+ }
}
}
diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
index ad46585..3bd22cd 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
@@ -144,7 +144,13 @@ fun SettingsScreen(
highlightField: String? = null,
onHighlightConsumed: () -> Unit = {},
/** Opens a page from a search result, pointed at the field the query named. */
- onOpenSearchResult: (SettingsPage, String?) -> Unit = { target, _ -> onPageChange(target) }
+ onOpenSearchResult: (SettingsPage, String?) -> Unit = { target, _ -> onPageChange(target) },
+ /**
+ * True when About should check for an update as it opens: an update
+ * notification was tapped (issue #126). Cleared through [onUpdateCheckStarted].
+ */
+ checkUpdateOnOpen: Boolean = false,
+ onUpdateCheckStarted: () -> Unit = {}
) {
// Back leaves the sub-page for whatever it hangs off — its hub if it has one,
// the home list otherwise. Only the list itself exits Settings.
@@ -264,7 +270,9 @@ fun SettingsScreen(
)
SettingsPage.ABOUT -> AboutScreen(
onBack = backToHome,
- onOpenPage = onPageChange
+ onOpenPage = onPageChange,
+ checkUpdateOnOpen = checkUpdateOnOpen,
+ onUpdateCheckStarted = onUpdateCheckStarted
)
SettingsPage.ABOUT_SAMOSA -> AboutSamosaScreen(
context = androidx.compose.ui.platform.LocalContext.current,
diff --git a/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt b/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt
index 27dd86d..2d32683 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt
@@ -270,12 +270,17 @@ private fun entryFor(page: SettingsPage): SettingsSearchEntry = when (page) {
"settings_server_messages_enabled",
R.string.settings_field_server_messages_enabled,
"announcements, sync"
+ ),
+ field(
+ "settings_update_notifications_enabled",
+ R.string.settings_field_update_notifications_enabled,
+ "update, updates, new version, release"
)
)
)
SettingsPage.ABOUT -> SettingsSearchEntry(
page,
- words("version, contact, support, company, samosa")
+ words("version, update, check for updates, contact, support, company, samosa")
)
SettingsPage.ABOUT_SAMOSA -> SettingsSearchEntry(
page,
diff --git a/app/src/main/java/com/gotcha/updater/UpdateNotifications.kt b/app/src/main/java/com/gotcha/updater/UpdateNotifications.kt
new file mode 100644
index 0000000..db65057
--- /dev/null
+++ b/app/src/main/java/com/gotcha/updater/UpdateNotifications.kt
@@ -0,0 +1,193 @@
+package com.gotcha.updater
+
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.content.SharedPreferences
+import android.net.ConnectivityManager
+import android.net.NetworkCapabilities
+import androidx.core.app.NotificationCompat
+import androidx.core.app.NotificationManagerCompat
+import com.gotcha.BuildConfig
+import com.gotcha.R
+import com.gotcha.data.SettingsRepository
+import com.gotcha.notifications.ChatCompletionNotifier
+import com.gotcha.notifications.LocalNotificationStore
+import com.gotcha.notifications.LocalNotifier
+import com.gotcha.notifications.LocalNotifier.Companion.putTargetExtras
+import com.gotcha.notifications.NotificationCategory
+import com.gotcha.notifications.NotificationTarget
+import com.gotcha.notifications.inQuietHours
+import java.time.Instant
+import java.time.ZoneId
+
+/** How often the background check fetches update.json: about twice a day (issue #126). */
+internal const val UPDATE_CHECK_INTERVAL_MS = 12L * 60L * 60L * 1000L
+
+/**
+ * Whether [remote] deserves a notification: it is newer than what is installed
+ * and than the last version already announced, and its download is one
+ * [AppUpdateManager.downloadUpdate] would accept. Announcing a release the
+ * About screen would then refuse to download helps nobody.
+ */
+internal fun shouldNotifyUpdate(
+ installedVersionCode: Int,
+ remote: AppUpdateInfo,
+ lastNotifiedVersionCode: Int,
+ trustedDownload: Boolean
+): Boolean = trustedDownload &&
+ remote.versionCode > installedVersionCode &&
+ remote.versionCode > lastNotifiedVersionCode
+
+/** True once [UPDATE_CHECK_INTERVAL_MS] has passed, or when the clock has gone back past the last check. */
+internal fun updateCheckDue(now: Long, lastCheckedAt: Long): Boolean =
+ now < lastCheckedAt || now - lastCheckedAt >= UPDATE_CHECK_INTERVAL_MS
+
+/** 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 }
+
+/** When the check last ran and which version was last announced. Not personal, so not encrypted. */
+internal class UpdateCheckStore(private val prefs: SharedPreferences) {
+
+ constructor(context: Context) : this(context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE))
+
+ var lastCheckedAt: Long
+ get() = prefs.getLong(KEY_LAST_CHECKED_AT, 0L)
+ set(value) {
+ // commit, not apply: the receiver's process may go as soon as it finishes.
+ prefs.edit().putLong(KEY_LAST_CHECKED_AT, value).commit()
+ }
+
+ var lastNotifiedVersionCode: Int
+ get() = prefs.getInt(KEY_LAST_NOTIFIED_VERSION, 0)
+ set(value) {
+ prefs.edit().putInt(KEY_LAST_NOTIFIED_VERSION, value).commit()
+ }
+
+ private companion object {
+ const val PREFS_FILE = "gotcha_update_check"
+ const val KEY_LAST_CHECKED_AT = "last_checked_at"
+ const val KEY_LAST_NOTIFIED_VERSION = "last_notified_version_code"
+ }
+}
+
+/**
+ * The background half of the in-app updater (issue #126): fetches update.json
+ * at most every [UPDATE_CHECK_INTERVAL_MS] and posts one notification per new
+ * version. It rides the reminder-check alarm and runs on app start, so it
+ * needs no scheduler of its own.
+ *
+ * Quiet by design: off, offline, quiet hours or a failed fetch post nothing and
+ * leave the next check to try again. Only a check that got an answer counts
+ * towards the interval, and only a posted notification marks its version as
+ * announced, so a blocked or failed post is retried rather than lost.
+ */
+internal suspend fun runUpdateCheck(
+ context: Context,
+ now: Long = System.currentTimeMillis(),
+ manager: AppUpdateManager = AppUpdateManager.shared,
+ manifestUrl: String = AppUpdateManager.DEFAULT_UPDATE_URL,
+ installedVersionCode: Int = BuildConfig.VERSION_CODE,
+ zone: ZoneId = ZoneId.systemDefault(),
+ isOnline: () -> Boolean = { hasValidatedNetwork(context) }
+): UpdateCheckOutcome {
+ val settings = SettingsRepository(context).load()
+ if (!settings.updateNotificationsEnabled) return UpdateCheckOutcome.OFF
+ val notifier = UpdateNotifier(context)
+ if (!notifier.canPost()) return UpdateCheckOutcome.CANNOT_POST
+ val store = UpdateCheckStore(context)
+ if (!updateCheckDue(now, store.lastCheckedAt)) return UpdateCheckOutcome.NOT_DUE
+ if (!isOnline()) return UpdateCheckOutcome.OFFLINE
+ val local = Instant.ofEpochMilli(now).atZone(zone)
+ if (settings.quietHoursEnabled &&
+ inQuietHours(local.hour * 60 + local.minute, settings.quietHoursStartMinute, settings.quietHoursEndMinute)
+ ) {
+ return UpdateCheckOutcome.QUIET_HOURS
+ }
+
+ val status = manager.checkForUpdate(
+ currentVersionCode = installedVersionCode,
+ manifestUrl = manifestUrl
+ )
+ if (status is UpdateStatus.Error) return UpdateCheckOutcome.FAILED
+ store.lastCheckedAt = now
+ val info = (status as? UpdateStatus.Available)?.info ?: return UpdateCheckOutcome.UP_TO_DATE
+ val notify = shouldNotifyUpdate(
+ installedVersionCode,
+ info,
+ store.lastNotifiedVersionCode,
+ manager.isTrustedDownloadUrl(info.downloadUrl)
+ )
+ if (!notify || !notifier.post(info, LocalNotificationStore(context))) return UpdateCheckOutcome.UP_TO_DATE
+ store.lastNotifiedVersionCode = info.versionCode
+ return UpdateCheckOutcome.NOTIFIED
+}
+
+/** An alarm has no network constraint, so the check asks for itself. */
+private fun hasValidatedNetwork(context: Context): Boolean {
+ val cm = context.getSystemService(ConnectivityManager::class.java) ?: return false
+ val caps = cm.getNetworkCapabilities(cm.activeNetwork) ?: return false
+ return caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
+}
+
+/**
+ * Posts the "new version" notification on a channel of its own, so it can be
+ * muted from Android's settings without silencing tips or reminders, and files
+ * it in Gotcha's inbox. A tap opens Settings ▸ About, which checks again and
+ * offers the download.
+ */
+class UpdateNotifier(private val context: Context) {
+
+ fun canPost(): Boolean = ChatCompletionNotifier(context).canPost()
+
+ @Suppress("MissingPermission") // canPost() checks it.
+ fun post(info: AppUpdateInfo, inbox: LocalNotificationStore): Boolean {
+ if (!canPost()) return false
+ ensureChannel()
+ val title = context.getString(R.string.update_notification_title, info.versionName)
+ val body = context.getString(R.string.update_notification_body)
+ val target = NotificationTarget.Update
+ val entryId = inbox.addEntry(NotificationCategory.APP_UPDATE, title, body, target)
+ val notifyId = LocalNotifier.notificationId(NotificationCategory.APP_UPDATE)
+ val intent = Intent(context, com.gotcha.MainActivity::class.java).apply {
+ action = LocalNotifier.ACTION_OPEN_LOCAL_NOTIFICATION
+ putExtra(LocalNotificationStore.EXTRA_INBOX_ENTRY_ID, entryId)
+ putTargetExtras(target)
+ flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
+ }
+ val notification = NotificationCompat.Builder(context, CHANNEL_ID)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setContentTitle(title)
+ .setContentText(body)
+ .setAutoCancel(true)
+ .setContentIntent(
+ PendingIntent.getActivity(
+ context,
+ notifyId,
+ intent,
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ )
+ )
+ .build()
+ NotificationManagerCompat.from(context).notify(notifyId, notification)
+ return true
+ }
+
+ private fun ensureChannel() {
+ val mgr = context.getSystemService(NotificationManager::class.java) ?: return
+ if (mgr.getNotificationChannel(CHANNEL_ID) != null) return
+ mgr.createNotificationChannel(
+ NotificationChannel(
+ CHANNEL_ID,
+ context.getString(R.string.channel_app_updates),
+ NotificationManager.IMPORTANCE_DEFAULT
+ ).apply { description = context.getString(R.string.channel_app_updates_description) }
+ )
+ }
+
+ companion object {
+ const val CHANNEL_ID = "gotcha_app_updates"
+ }
+}
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index 806d29f..253e5c6 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -1410,4 +1410,13 @@
<item>Sag mir, was du brauchst.</item>
<item>Zu Diensten – was kann ich tun?</item>
</string-array>
+ <string name="notification_category_app_update">App-Update</string>
+ <string name="channel_app_updates">App-Updates</string>
+ <string name="channel_app_updates_description">Eine Benachrichtigung, wenn eine neue Version von Gotcha erscheint</string>
+ <string name="update_notification_title">Gotcha %1$s ist verfügbar</string>
+ <string name="update_notification_body">Tippen, um es herunterzuladen und zu installieren.</string>
+ <string name="notifications_app_updates">App-Updates</string>
+ <string name="notifications_app_updates_description">Etwa zweimal am Tag lädt Gotcha eine kleine Datei von GitHub (raw.githubusercontent.com), um zu prüfen, ob eine neue Version erschienen ist. Die Anfrage enthält nichts über dich; GitHub sieht deine IP-Adresse, wie bei jedem Download.</string>
+ <string name="notifications_notify_about_new_versions">Über neue Versionen benachrichtigen</string>
+ <string name="settings_field_update_notifications_enabled">Update-Benachrichtigungen</string>
</resources>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 1429845..2c9d722 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -1429,4 +1429,13 @@
<item>Dime qué necesitas.</item>
<item>A tu servicio: ¿qué puedo hacer?</item>
</string-array>
+ <string name="notification_category_app_update">Actualización de la app</string>
+ <string name="channel_app_updates">Actualizaciones de la app</string>
+ <string name="channel_app_updates_description">Una notificación cuando se publica una nueva versión de Gotcha</string>
+ <string name="update_notification_title">Gotcha %1$s está disponible</string>
+ <string name="update_notification_body">Toca para descargarla e instalarla.</string>
+ <string name="notifications_app_updates">Actualizaciones de la app</string>
+ <string name="notifications_app_updates_description">Unas dos veces al día, Gotcha descarga un pequeño archivo de GitHub (raw.githubusercontent.com) para ver si hay una versión nueva. La solicitud no lleva nada sobre ti; GitHub ve tu dirección IP, como en cualquier descarga.</string>
+ <string name="notifications_notify_about_new_versions">Avisarme de nuevas versiones</string>
+ <string name="settings_field_update_notifications_enabled">Avisos de actualización</string>
</resources>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index 2375ba6..3bc93b7 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -1429,4 +1429,13 @@
<item>Dites-moi ce qu\'il vous faut.</item>
<item>À votre service : que puis-je faire ?</item>
</string-array>
+ <string name="notification_category_app_update">Mise à jour de l\'appli</string>
+ <string name="channel_app_updates">Mises à jour de l\'appli</string>
+ <string name="channel_app_updates_description">Une notification quand une nouvelle version de Gotcha est publiée</string>
+ <string name="update_notification_title">Gotcha %1$s est disponible</string>
+ <string name="update_notification_body">Touchez pour la télécharger et l\'installer.</string>
+ <string name="notifications_app_updates">Mises à jour de l\'appli</string>
+ <string name="notifications_app_updates_description">Environ deux fois par jour, Gotcha télécharge un petit fichier depuis GitHub (raw.githubusercontent.com) pour voir si une nouvelle version est sortie. La requête ne contient rien sur vous ; GitHub voit votre adresse IP, comme pour tout téléchargement.</string>
+ <string name="notifications_notify_about_new_versions">M\'avertir des nouvelles versions</string>
+ <string name="settings_field_update_notifications_enabled">Notifications de mise à jour</string>
</resources>
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index b9bc0dd..d13311f 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -1410,4 +1410,13 @@
<item>बताइए आपको क्या चाहिए।</item>
<item>आपकी सेवा में — मैं क्या करूँ?</item>
</string-array>
+ <string name="notification_category_app_update">ऐप अपडेट</string>
+ <string name="channel_app_updates">ऐप अपडेट</string>
+ <string name="channel_app_updates_description">Gotcha का नया वर्शन आने पर एक सूचना</string>
+ <string name="update_notification_title">Gotcha %1$s उपलब्ध है</string>
+ <string name="update_notification_body">डाउनलोड और इंस्टॉल करने के लिए टैप करें।</string>
+ <string name="notifications_app_updates">ऐप अपडेट</string>
+ <string name="notifications_app_updates_description">दिन में लगभग दो बार Gotcha यह देखने के लिए GitHub (raw.githubusercontent.com) से एक छोटी फ़ाइल डाउनलोड करता है कि नया वर्शन आया है या नहीं। इस अनुरोध में आपके बारे में कुछ नहीं होता; किसी भी डाउनलोड की तरह GitHub आपका IP पता देखता है।</string>
+ <string name="notifications_notify_about_new_versions">नए वर्शन के बारे में सूचित करें</string>
+ <string name="settings_field_update_notifications_enabled">अपडेट सूचनाएँ</string>
</resources>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index e8ee014..21dbcf2 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -1429,4 +1429,13 @@
<item>Dimmi cosa ti serve.</item>
<item>Al tuo servizio: cosa posso fare?</item>
</string-array>
+ <string name="notification_category_app_update">Aggiornamento dell\'app</string>
+ <string name="channel_app_updates">Aggiornamenti dell\'app</string>
+ <string name="channel_app_updates_description">Una notifica quando esce una nuova versione di Gotcha</string>
+ <string name="update_notification_title">Gotcha %1$s è disponibile</string>
+ <string name="update_notification_body">Tocca per scaricarla e installarla.</string>
+ <string name="notifications_app_updates">Aggiornamenti dell\'app</string>
+ <string name="notifications_app_updates_description">Circa due volte al giorno Gotcha scarica un piccolo file da GitHub (raw.githubusercontent.com) per vedere se è uscita una nuova versione. La richiesta non contiene nulla su di te; GitHub vede il tuo indirizzo IP, come per qualsiasi download.</string>
+ <string name="notifications_notify_about_new_versions">Avvisami delle nuove versioni</string>
+ <string name="settings_field_update_notifications_enabled">Notifiche di aggiornamento</string>
</resources>
diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml
index e4e8bb5..10eff14 100644
--- a/app/src/main/res/values-ja/strings.xml
+++ b/app/src/main/res/values-ja/strings.xml
@@ -1391,4 +1391,13 @@
<item>必要なことを教えてください。</item>
<item>何なりとお申し付けください。</item>
</string-array>
+ <string name="notification_category_app_update">アプリの更新</string>
+ <string name="channel_app_updates">アプリの更新</string>
+ <string name="channel_app_updates_description">Gotcha の新しいバージョンが公開されたときの通知</string>
+ <string name="update_notification_title">Gotcha %1$s が利用可能です</string>
+ <string name="update_notification_body">タップしてダウンロードとインストールを行います。</string>
+ <string name="notifications_app_updates">アプリの更新</string>
+ <string name="notifications_app_updates_description">Gotcha は 1 日に 2 回ほど、新しいバージョンが出ているかを確かめるために GitHub(raw.githubusercontent.com)から小さなファイルをダウンロードします。このリクエストにあなたに関する情報は含まれません。ほかのダウンロードと同じく、GitHub には IP アドレスが見えます。</string>
+ <string name="notifications_notify_about_new_versions">新しいバージョンを通知する</string>
+ <string name="settings_field_update_notifications_enabled">更新の通知</string>
</resources>
diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml
index 69d8034..801eea6 100644
--- a/app/src/main/res/values-pt-rBR/strings.xml
+++ b/app/src/main/res/values-pt-rBR/strings.xml
@@ -1429,4 +1429,13 @@
<item>Me diga do que você precisa.</item>
<item>Às ordens: o que posso fazer?</item>
</string-array>
+ <string name="notification_category_app_update">Atualização do app</string>
+ <string name="channel_app_updates">Atualizações do app</string>
+ <string name="channel_app_updates_description">Uma notificação quando uma nova versão do Gotcha é lançada</string>
+ <string name="update_notification_title">Gotcha %1$s está disponível</string>
+ <string name="update_notification_body">Toque para baixar e instalar.</string>
+ <string name="notifications_app_updates">Atualizações do app</string>
+ <string name="notifications_app_updates_description">Cerca de duas vezes por dia, o Gotcha baixa um pequeno arquivo do GitHub (raw.githubusercontent.com) para ver se saiu uma nova versão. A solicitação não leva nada sobre você; o GitHub vê seu endereço IP, como em qualquer download.</string>
+ <string name="notifications_notify_about_new_versions">Avisar sobre novas versões</string>
+ <string name="settings_field_update_notifications_enabled">Avisos de atualização</string>
</resources>
diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml
index d44f141..dc872f7 100644
--- a/app/src/main/res/values-zh-rCN/strings.xml
+++ b/app/src/main/res/values-zh-rCN/strings.xml
@@ -1391,4 +1391,13 @@
<item>告诉我你需要什么。</item>
<item>听你吩咐:我能做什么?</item>
</string-array>
+ <string name="notification_category_app_update">应用更新</string>
+ <string name="channel_app_updates">应用更新</string>
+ <string name="channel_app_updates_description">Gotcha 发布新版本时的通知</string>
+ <string name="update_notification_title">Gotcha %1$s 已推出</string>
+ <string name="update_notification_body">点按即可下载并安装。</string>
+ <string name="notifications_app_updates">应用更新</string>
+ <string name="notifications_app_updates_description">Gotcha 每天大约两次从 GitHub(raw.githubusercontent.com)下载一个小文件,查看是否有新版本。该请求不包含任何关于你的信息;与任何下载一样,GitHub 能看到你的 IP 地址。</string>
+ <string name="notifications_notify_about_new_versions">有新版本时通知我</string>
+ <string name="settings_field_update_notifications_enabled">更新通知</string>
</resources>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index f9640ad..1270302 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -1637,4 +1637,13 @@
<item quantity="one">\"%1$s\": %2$d system message imported as a note, not an instruction.</item>
<item quantity="other">\"%1$s\": %2$d system messages imported as notes, not instructions.</item>
</plurals>
+ <string name="notification_category_app_update">App update</string>
+ <string name="channel_app_updates">App updates</string>
+ <string name="channel_app_updates_description">A notification when a new version of Gotcha is released</string>
+ <string name="update_notification_title">Gotcha %1$s is available</string>
+ <string name="update_notification_body">Tap to download and install it.</string>
+ <string name="notifications_app_updates">App updates</string>
+ <string name="notifications_app_updates_description">About twice a day, Gotcha downloads a small file from GitHub (raw.githubusercontent.com) to see whether a new version is out. The request carries nothing about you; GitHub sees your IP address, as with any download.</string>
+ <string name="notifications_notify_about_new_versions">Notify me about new versions</string>
+ <string name="settings_field_update_notifications_enabled">Update notifications</string>
</resources>
diff --git a/app/src/test/java/com/gotcha/updater/UpdateNotificationsTest.kt b/app/src/test/java/com/gotcha/updater/UpdateNotificationsTest.kt
new file mode 100644
index 0000000..3af3308
--- /dev/null
+++ b/app/src/test/java/com/gotcha/updater/UpdateNotificationsTest.kt
@@ -0,0 +1,191 @@
+package com.gotcha.updater
+
+import android.Manifest
+import android.app.Application
+import android.app.NotificationManager
+import androidx.test.core.app.ApplicationProvider
+import com.gotcha.data.Settings
+import com.gotcha.data.SettingsRepository
+import com.gotcha.notifications.LocalNotificationStore
+import com.gotcha.notifications.LocalNotifier
+import com.gotcha.notifications.NotificationCategory
+import com.gotcha.notifications.NotificationTarget
+import com.gotcha.testsupport.FakeAndroidKeyStore
+import kotlinx.coroutines.runBlocking
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.MockWebServer
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.annotation.Config
+import java.time.LocalDate
+import java.time.ZoneId
+
+/** The background update check and its notification (issue #126). */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class UpdateNotificationsTest {
+
+ private val application: Application = ApplicationProvider.getApplicationContext()
+ private val manager = application.getSystemService(NotificationManager::class.java)
+ private val zone = ZoneId.systemDefault()
+ private val noon = LocalDate.now(zone).atTime(12, 0).atZone(zone).toInstant().toEpochMilli()
+ private val server = MockWebServer()
+
+ /** Past the interval and, unlike noon + 12 h, outside the default quiet hours. */
+ private val nextNoon = noon + 24L * 60L * 60L * 1000L
+
+ @Before
+ fun setUp() {
+ FakeAndroidKeyStore.setUp()
+ manager.cancelAll()
+ shadowOf(application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS)
+ SettingsRepository(application).save(Settings())
+ server.start()
+ }
+
+ @After
+ fun tearDown() = server.shutdown()
+
+ private fun manifest(versionCode: Int, url: String = trustedUrl(versionCode)) =
+ MockResponse().setBody(
+ """{"versionCode":$versionCode,"versionName":"1.$versionCode.0","downloadUrl":"$url"}"""
+ )
+
+ 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 {
+ runUpdateCheck(
+ application,
+ now = now,
+ manager = AppUpdateManager(),
+ manifestUrl = server.url("/update.json").toString(),
+ installedVersionCode = 7,
+ zone = zone,
+ isOnline = { online }
+ )
+ }
+
+ private fun posted() = shadowOf(manager).allNotifications
+
+ // ---- the pure rules ----
+
+ @Test
+ fun `notifies only for a trusted version newer than both installed and announced`() {
+ val info = AppUpdateInfo(versionCode = 8, versionName = "1.8.0", downloadUrl = trustedUrl(8))
+ assertTrue(shouldNotifyUpdate(7, info, lastNotifiedVersionCode = 0, trustedDownload = true))
+ assertFalse(shouldNotifyUpdate(8, info, 0, trustedDownload = true))
+ assertFalse(shouldNotifyUpdate(9, info, 0, trustedDownload = true))
+ assertFalse(shouldNotifyUpdate(7, info, lastNotifiedVersionCode = 8, trustedDownload = true))
+ assertFalse(shouldNotifyUpdate(7, info, 0, trustedDownload = false))
+ }
+
+ @Test
+ fun `a check is due after the interval, or when the clock went back`() {
+ assertTrue(updateCheckDue(now = noon, lastCheckedAt = 0L))
+ assertFalse(updateCheckDue(now = noon, lastCheckedAt = noon - UPDATE_CHECK_INTERVAL_MS + 1))
+ assertTrue(updateCheckDue(now = noon, lastCheckedAt = noon - UPDATE_CHECK_INTERVAL_MS))
+ assertTrue(updateCheckDue(now = noon, lastCheckedAt = noon + 60_000L))
+ }
+
+ // ---- the check ----
+
+ @Test
+ fun `a newer version is notified once, filed in the inbox, and opens the update`() {
+ server.enqueue(manifest(8))
+ server.enqueue(manifest(8))
+
+ assertEquals(UpdateCheckOutcome.NOTIFIED, check())
+ assertEquals(UpdateCheckOutcome.UP_TO_DATE, check(nextNoon))
+
+ assertEquals(1, posted().size)
+ val notification = posted().single()
+ assertEquals(UpdateNotifier.CHANNEL_ID, notification.channelId)
+ val tap = shadowOf(notification.contentIntent).savedIntent
+ assertTrue(tap.getBooleanExtra(LocalNotifier.EXTRA_OPEN_UPDATE, false))
+ val entry = LocalNotificationStore(application).entries().single()
+ assertEquals(NotificationCategory.APP_UPDATE, entry.categoryOrNull)
+ assertEquals(NotificationTarget.Update, entry.target)
+ }
+
+ @Test
+ fun `the next version is notified again`() {
+ server.enqueue(manifest(8))
+ server.enqueue(manifest(9))
+
+ assertEquals(UpdateCheckOutcome.NOTIFIED, check())
+ assertEquals(UpdateCheckOutcome.NOTIFIED, check(nextNoon))
+ assertEquals(2, LocalNotificationStore(application).entries().size)
+ }
+
+ @Test
+ fun `fetches at most once per interval`() {
+ server.enqueue(manifest(7))
+
+ assertEquals(UpdateCheckOutcome.UP_TO_DATE, check())
+ assertEquals(UpdateCheckOutcome.NOT_DUE, check(noon + UPDATE_CHECK_INTERVAL_MS - 1))
+ assertEquals(1, server.requestCount)
+ assertTrue(posted().isEmpty())
+ }
+
+ @Test
+ fun `switched off, nothing is fetched`() {
+ SettingsRepository(application).save(Settings(updateNotificationsEnabled = false))
+
+ assertEquals(UpdateCheckOutcome.OFF, check())
+ assertEquals(0, server.requestCount)
+ }
+
+ @Test
+ fun `without the notification permission, nothing is fetched or recorded`() {
+ shadowOf(application).denyPermissions(Manifest.permission.POST_NOTIFICATIONS)
+
+ assertEquals(UpdateCheckOutcome.CANNOT_POST, check())
+ assertEquals(0, server.requestCount)
+
+ // Granted later: the same version is still announced.
+ shadowOf(application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS)
+ server.enqueue(manifest(8))
+ assertEquals(UpdateCheckOutcome.NOTIFIED, check(noon + 1))
+ }
+
+ @Test
+ fun `offline or a failed fetch leaves the next check free to try`() {
+ assertEquals(UpdateCheckOutcome.OFFLINE, check(online = false))
+ assertEquals(0, server.requestCount)
+
+ server.enqueue(MockResponse().setResponseCode(500))
+ assertEquals(UpdateCheckOutcome.FAILED, check(noon + 1))
+
+ server.enqueue(manifest(8))
+ assertEquals(UpdateCheckOutcome.NOTIFIED, check(noon + 2))
+ }
+
+ @Test
+ fun `a download the updater would refuse is not announced`() {
+ server.enqueue(manifest(8, url = "https://evil.example.com/gotcha.apk"))
+
+ assertEquals(UpdateCheckOutcome.UP_TO_DATE, check())
+ assertTrue(posted().isEmpty())
+ }
+
+ @Test
+ fun `quiet hours hold the check until they end`() {
+ SettingsRepository(application).save(
+ Settings(quietHoursEnabled = true, quietHoursStartMinute = 11 * 60, quietHoursEndMinute = 13 * 60)
+ )
+
+ assertEquals(UpdateCheckOutcome.QUIET_HOURS, check())
+ assertEquals(0, server.requestCount)
+
+ server.enqueue(manifest(8))
+ assertEquals(UpdateCheckOutcome.NOTIFIED, check(noon + 2 * 60 * 60 * 1000L))
+ }
+}