Persistent reminders: keep records in DataStore, restore on every sync, scope forgets to the occurrence (#100)

This commit is contained in:
makiolaj committed 2026-11-17 00:45:38 +01:00
1 parent f999fb076c
commit 150f10eead
7 files changed
+162 -109

No files matched your search

@@ -5,14 +5,10 @@ import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.tasks.StartupGate
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
/**
@@ -25,9 +21,6 @@ class BootReceiver : BroadcastReceiver() {
@Inject lateinit var scheduler: ReminderScheduler
@Inject lateinit var snoozeScheduler: ReminderSnoozeScheduler
@Inject lateinit var notifier: TaskNotifier
@Inject lateinit var settingsPrefs: SettingsPrefs
@Inject lateinit var startupGate: StartupGate
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
@@ -56,16 +49,9 @@ class BootReceiver : BroadcastReceiver() {
val pending = goAsync()
scope.launch {
try {
// Before the sync, so a missed alarm it fires replaces an older restored occurrence, not the reverse.
if (afterReboot) {
runCatching {
val settings = settingsPrefs.settings.first()
startupGate.awaitReady()
withContext(Dispatchers.IO) { notifier.restorePersistent(settings) }
}
}
runCatching { scheduler.sync(afterReboot = afterReboot) }
if (afterReboot) runCatching { snoozeScheduler.rearm() }
// Also restores the persistent reminders the reboot took down.
runCatching { scheduler.sync(afterReboot = afterReboot) }
} finally {
pending.finish()
}
@@ -108,12 +108,14 @@ internal fun TasksDataSource.occurrence(taskId: Long, occurrenceStart: Long): Ta
*/
internal fun reminderIsStale(occurrenceStart: Long?, current: Task?, missingMeansGone: Boolean): Boolean {
if (current == null) return missingMeansGone
val same = when (occurrenceStart) {
null -> current.occurrenceStart == null
ScheduledReminder.NO_OCCURRENCE -> true
else -> current.occurrenceStart?.toEpochMilliseconds() == occurrenceStart
}
return same && current.isClosed
return current.isOccurrence(occurrenceStart) && current.isClosed
}
/** Whether this is the occurrence a reminder recorded; [ScheduledReminder.NO_OCCURRENCE] matches any. */
internal fun Task.isOccurrence(occurrenceStart: Long?): Boolean = when (occurrenceStart) {
null -> this.occurrenceStart == null
ScheduledReminder.NO_OCCURRENCE -> true
else -> this.occurrenceStart?.toEpochMilliseconds() == occurrenceStart
}
/**
@@ -121,10 +123,10 @@ internal fun reminderIsStale(occurrenceStart: Long?, current: Task?, missingMean
* once more: a completion landing between the read and the post may already
* have had its withdrawal pass, which ran before there was anything to withdraw.
* With [exact], a lookup that fell back to another occurrence posts nothing. A
* persistent reminder that won't come back is forgotten, unless the store just
* failed to find it.
* persistent reminder that won't come back is forgotten; one the store just
* failed to find counts a miss.
*/
internal fun TaskNotifier.postIfOpen(
internal suspend fun TaskNotifier.postIfOpen(
dataSource: TasksDataSource,
taskId: Long,
occurrenceStart: Long,
@@ -132,20 +134,18 @@ internal fun TaskNotifier.postIfOpen(
alert: Boolean = true,
exact: Boolean = false,
postedAt: Long? = null,
ifAbsent: Boolean = false,
) {
val task = dataSource.occurrence(taskId, occurrenceStart)
if (task == null) {
if (missingMeansGone()) forget(taskId)
if (missingMeansGone()) forget(taskId, occurrence = occurrenceStart) else missed(taskId, occurrenceStart)
return
}
if (task.isClosed || (exact && !task.isOccurrence(occurrenceStart))) {
forget(taskId)
forget(taskId, occurrence = occurrenceStart)
return
}
postDue(task, settings, alert, postedAt)
postDue(task, settings, alert, postedAt, ifAbsent)
val now = runCatching { dataSource.occurrence(taskId, occurrenceStart) }.getOrElse { return }
if (now == null || now.isClosed) cancel(taskId)
if ((now == null && missingMeansGone()) || now?.isClosed == true) cancel(taskId)
}
private fun Task.isOccurrence(occurrenceStart: Long): Boolean =
occurrenceStart == ScheduledReminder.NO_OCCURRENCE || this.occurrenceStart?.toEpochMilliseconds() == occurrenceStart
@@ -44,7 +44,7 @@ class ReminderActionReceiver : BroadcastReceiver() {
val taskId = intent.getLongExtra(EXTRA_TASK_ID, -1L).takeIf { it > 0L } ?: return
val occurrence = intent.getLongExtra(EXTRA_OCCURRENCE, ScheduledReminder.NO_OCCURRENCE)
val action = intent.action ?: return
if (action == ACTION_DONE || action == ACTION_SNOOZE) notifier.cancel(taskId)
if (action == ACTION_DONE || action == ACTION_SNOOZE) notifier.dismiss(taskId)
val pending = goAsync()
scope.launch {
try {
@@ -54,11 +54,14 @@ class ReminderActionReceiver : BroadcastReceiver() {
val anchor = occurrence.takeIf { it != ScheduledReminder.NO_OCCURRENCE }
?.let(Instant::fromEpochMilliseconds)
repository.setCompleted(taskId, anchor, completed = true)
notifier.forget(taskId, occurrence = occurrence)
}
ACTION_SNOOZE -> runCatching {
val minutes = settingsPrefs.settings.first().snoozeMinutes
snoozeScheduler.schedule(taskId, occurrence, System.currentTimeMillis() + minutes * 60_000L)
startupGate.awaitReady()
notifier.forget(taskId, occurrence = occurrence)
}
ACTION_SHOW -> runCatching {
@@ -74,7 +77,7 @@ class ReminderActionReceiver : BroadcastReceiver() {
val settings = settingsPrefs.settings.first()
startupGate.awaitReady()
if (!settings.remindersEnabled || !settings.persistentReminders || !notifier.isCurrentStore(store)) {
notifier.forget(taskId, store)
if (store != null) notifier.forget(taskId, store, occurrence)
return@runCatching
}
notifier.postIfOpen(
@@ -8,7 +8,6 @@ import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
import de.jeanlucmakiola.agendula.data.tasks.TaskQuery
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
import kotlinx.coroutines.CoroutineDispatcher
@@ -72,7 +71,10 @@ class ReminderScheduler @Inject constructor(
if (!settings.remindersEnabled || !readable) {
clearAll()
// Switched off, a reminder already up still goes when its task does.
if (readable) withdrawStale()
if (readable) {
withdrawStale()
runCatching { notifier.restorePersistent(settings) }
}
return
}
val tasks = runCatching { dataSource.tasks(TaskQuery(includeCompleted = false)) }
@@ -112,15 +114,15 @@ class ReminderScheduler @Inject constructor(
val armed = diff.arm.filter { schedule(it) }
store.replace(diff.keep + armed, fired = fired, exact = canExact)
withdrawStale()
runCatching { notifier.restorePersistent(settings) }
}
/**
* A reminder already on screen outlives its alarm: completing the task in
* the list, on a widget or on another device has to take it down too.
*/
private fun withdrawStale() {
// Only our own store tells a deleted task from a failed read.
val missingMeansGone = providerResolver.mode() == StorageMode.OWN
private suspend fun withdrawStale() {
val missingMeansGone = notifier.missingMeansGone()
runCatching {
notifier.withdrawStale { taskId, occurrence ->
runCatching {
@@ -18,6 +18,10 @@ import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringSetPreferencesKey
import de.jeanlucmakiola.agendula.MainActivity
import de.jeanlucmakiola.agendula.R
import de.jeanlucmakiola.agendula.data.prefs.ReminderDescription
@@ -33,7 +37,10 @@ import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.calendarDate
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.text.BreakIterator
import java.time.Instant as JInstant
import java.time.LocalDate
@@ -60,12 +67,15 @@ class TaskNotifier @Inject constructor(
private val dataSource: TasksDataSource,
private val startupGate: StartupGate,
@ApplicationScope private val scope: CoroutineScope,
private val dataStore: DataStore<Preferences>,
) {
private val manager get() = context.getSystemService(NotificationManager::class.java)
private val channelPrefs get() = context.getSharedPreferences(CHANNEL_PREFS, Context.MODE_PRIVATE)
private val persistentPrefs get() = context.getSharedPreferences(PERSISTENT_PREFS, Context.MODE_PRIVATE)
private val currentStore get() = resolver.mode().name.lowercase()
/** Keeps a post and a restyle from overwriting each other with a stale snapshot. */
private val postLock = Mutex()
fun canPost(): Boolean {
val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) ==
@@ -73,10 +83,23 @@ class TaskNotifier @Inject constructor(
return granted && NotificationManagerCompat.from(context).areNotificationsEnabled()
}
suspend fun postDue(
task: Task,
settings: Settings,
alert: Boolean = true,
postedAt: Long? = null,
ifAbsent: Boolean = false,
) {
if (!canPost()) return
postLock.withLock {
if (ifAbsent && postedReminders().any { it.taskId == task.taskId }) return
post(task, settings, alert, postedAt)
}
}
// canPost() checks POST_NOTIFICATIONS before we ever call notify().
@SuppressLint("MissingPermission")
fun postDue(task: Task, settings: Settings, alert: Boolean = true, postedAt: Long? = null) {
if (!canPost()) return
private suspend fun post(task: Task, settings: Settings, alert: Boolean, postedAt: Long?) {
val persistent = settings.persistentReminders
val occurrence = task.occurrenceStart?.toEpochMilliseconds() ?: ScheduledReminder.NO_OCCURRENCE
val shownAt = postedAt ?: System.currentTimeMillis()
@@ -134,11 +157,18 @@ class TaskNotifier @Inject constructor(
remember(task.taskId, occurrence, shownAt, persistent)
}
private fun remember(taskId: Long, occurrence: Long, postedAt: Long, persistent: Boolean) {
if (persistent) {
persistentPrefs.edit { putString(persistentKey(currentStore, taskId), encodePersistent(occurrence, postedAt)) }
} else {
forget(taskId)
private suspend fun remember(taskId: Long, occurrence: Long, postedAt: Long, persistent: Boolean) {
if (!persistent) return forget(taskId)
val store = currentStore
editRecords { records ->
records.filterNot { it.store == store && it.taskId == taskId } + PersistentRecord(store, taskId, occurrence, postedAt)
}
}
private suspend fun editRecords(transform: (List<PersistentRecord>) -> List<PersistentRecord>) {
dataStore.edit { p ->
p[PERSISTENT_KEY] = transform(p[PERSISTENT_KEY].orEmpty().mapNotNull(PersistentRecord::decode))
.mapTo(HashSet()) { it.encode() }
}
}
@@ -152,15 +182,35 @@ class TaskNotifier @Inject constructor(
)
}
fun cancel(taskId: Long) {
/** Takes [taskId]'s reminder down without touching its record; safe before the startup gate. */
fun dismiss(taskId: Long) {
NotificationManagerCompat.from(context).cancel(taskId.toString(), NOTIFICATION_ID)
}
suspend fun cancel(taskId: Long) {
dismiss(taskId)
forget(taskId)
}
/** Drops [taskId] from the persistent reminders remembered for [store], the current one by default. */
fun forget(taskId: Long, store: String? = null) {
val key = persistentKey(store ?: currentStore, taskId)
if (persistentPrefs.contains(key)) persistentPrefs.edit { remove(key) }
/**
* Drops [taskId]'s remembered persistent reminder in [store]; with
* [occurrence], only when it is that occurrence's.
*/
suspend fun forget(taskId: Long, store: String = currentStore, occurrence: Long? = null) {
editRecords { records ->
records.filterNot { it.store == store && it.taskId == taskId && (occurrence == null || it.occurrence == occurrence) }
}
}
/** Counts a failed lookup of a remembered reminder, dropping it after [MAX_MISSES] in a row. */
suspend fun missed(taskId: Long, occurrence: Long) {
val store = currentStore
editRecords { records ->
records.mapNotNull { record ->
if (record.store != store || record.taskId != taskId || record.occurrence != occurrence) return@mapNotNull record
record.copy(misses = record.misses + 1).takeIf { it.misses < MAX_MISSES }
}
}
}
fun isCurrentStore(store: String?): Boolean = store == currentStore
@@ -173,18 +223,18 @@ class TaskNotifier @Inject constructor(
* cancelled or deleted since it went off, here or on another device. The
* occurrence is null for a reminder posted before it was recorded.
*/
fun withdrawStale(isStale: (taskId: Long, occurrenceStart: Long?) -> Boolean) {
postedReminders().forEach { if (isStale(it.taskId, it.occurrence)) cancel(it.taskId) }
suspend fun withdrawStale(isStale: (taskId: Long, occurrenceStart: Long?) -> Boolean) {
postedReminders().filter { isStale(it.taskId, it.occurrence) }.forEach { cancel(it.taskId) }
}
/**
* Turns the shown reminders persistent or back, in place: the update doesn't
* alert again and keeps each reminder's content and time.
* alert again and keeps each reminder's content and time. One posted before
* occurrences were recorded is left alone, as a re-post can't find its occurrence.
*/
@Synchronized
fun restyleActive(persistent: Boolean) {
suspend fun restyleActive(persistent: Boolean) = postLock.withLock {
postedReminders().forEach { posted ->
val occurrence = posted.occurrence ?: ScheduledReminder.NO_OCCURRENCE
val occurrence = posted.occurrence ?: return@forEach
val notification = Notification.Builder.recoverBuilder(context, posted.notification)
.setAutoCancel(!persistent)
.setOnlyAlertOnce(true)
@@ -197,24 +247,33 @@ class TaskNotifier @Inject constructor(
}
/**
* Brings back the persistent reminders a reboot took down, silently and at
* their old time. Another store's are dropped: their ids name other tasks here.
* Brings back, silently and at their old time, the persistent reminders no
* longer shown: taken down by a reboot or a force-stop, or by a swipe whose
* re-post couldn't read the task. Another store's are dropped: their ids name
* other tasks here.
*/
fun restorePersistent(settings: Settings) {
val remembered = persistentPrefs.all.mapNotNull { (key, value) ->
decodePersistentKey(key)?.let { (store, taskId) -> Triple(store, taskId, decodePersistent(value as? String)) }
}
suspend fun restorePersistent(settings: Settings) {
if (!settings.remindersEnabled || !settings.persistentReminders) {
persistentPrefs.edit { clear() }
dataStore.edit { it.remove(PERSISTENT_KEY) }
return
}
remembered.forEach { (store, taskId, shown) ->
if (store != currentStore || shown == null) {
forget(taskId, store)
return@forEach
}
runCatching {
postIfOpen(dataSource, taskId, shown.first, settings, alert = false, exact = true, postedAt = shown.second)
val store = currentStore
val shown = postedReminders().mapTo(HashSet()) { it.taskId }
dataStore.data.first()[PERSISTENT_KEY].orEmpty().mapNotNull(PersistentRecord::decode).forEach { record ->
when {
record.store != store -> forget(record.taskId, record.store)
record.taskId !in shown -> runCatching {
postIfOpen(
dataSource,
record.taskId,
record.occurrence,
settings,
alert = false,
exact = true,
postedAt = record.postedAt,
ifAbsent = true,
)
}
}
}
}
@@ -318,7 +377,8 @@ class TaskNotifier @Inject constructor(
private const val EXTRA_OCCURRENCE = "de.jeanlucmakiola.agendula.extra.OCCURRENCE_START"
private const val CHANNEL_PREFS = "reminder_channels"
private const val KEY_LEGACY_IMPORTANCE = "legacy_importance"
private const val PERSISTENT_PREFS = "persistent_reminders"
private val PERSISTENT_KEY = stringSetPreferencesKey("persistent_reminders")
private const val MAX_MISSES = 3
private const val PERSISTENT_GROUP_PREFIX = "reminder_"
/**
@@ -333,22 +393,31 @@ class TaskNotifier @Inject constructor(
}
}
internal fun persistentKey(store: String, taskId: Long): String = "$store|$taskId"
/**
* A persistent reminder remembered past a reboot: its store and task, the
* occurrence and time it was first shown, and how many lookups in a row failed.
*/
internal data class PersistentRecord(
val store: String,
val taskId: Long,
val occurrence: Long,
val postedAt: Long,
val misses: Int = 0,
) {
fun encode(): String = "$store|$taskId|$occurrence|$postedAt|$misses"
internal fun decodePersistentKey(key: String): Pair<String, Long>? {
val store = key.substringBefore('|', "").ifEmpty { return null }
val taskId = key.substringAfter('|').toLongOrNull() ?: return null
return store to taskId
}
internal fun encodePersistent(occurrence: Long, postedAt: Long): String = "$occurrence|$postedAt"
/** A remembered persistent reminder as its occurrence and the time it was first shown. */
internal fun decodePersistent(value: String?): Pair<Long, Long>? {
val parts = value?.split('|')?.takeIf { it.size == 2 } ?: return null
val occurrence = parts[0].toLongOrNull() ?: return null
val postedAt = parts[1].toLongOrNull() ?: return null
return occurrence to postedAt
companion object {
fun decode(value: String): PersistentRecord? {
val parts = value.split('|').takeIf { it.size == 5 } ?: return null
return PersistentRecord(
store = parts[0].ifEmpty { return null },
taskId = parts[1].toLongOrNull() ?: return null,
occurrence = parts[2].toLongOrNull() ?: return null,
postedAt = parts[3].toLongOrNull() ?: return null,
misses = parts[4].toIntOrNull() ?: return null,
)
}
}
}
/** The words a reminder uses for the days either side of today. */
@@ -259,6 +259,7 @@ class SettingsViewModel @Inject constructor(
fun setRemindersEnabled(enabled: Boolean) = viewModelScope.launch {
prefs.setRemindersEnabled(enabled)
restyleReminders()
resyncReminders()
}
fun setAutofocusTitle(enabled: Boolean) = viewModelScope.launch { prefs.setAutofocusTitle(enabled) }
@@ -268,7 +269,11 @@ class SettingsViewModel @Inject constructor(
fun setReminderDescription(pref: ReminderDescription) = viewModelScope.launch { prefs.setReminderDescription(pref) }
fun setPersistentReminders(enabled: Boolean) = viewModelScope.launch {
prefs.setPersistentReminders(enabled)
// Under the lock the latest setting wins, however fast it is flipped.
restyleReminders()
}
/** Makes the shown reminders match the settings; under the lock the latest wins, however fast they flip. */
private suspend fun restyleReminders() {
restyleLock.withLock {
val settings = prefs.settings.first()
withContext(io) {
@@ -6,28 +6,16 @@ import org.junit.jupiter.api.Test
class PersistentRecordTest {
@Test
fun `key round-trips store and task id`() {
assertThat(decodePersistentKey(persistentKey("own", 42L))).isEqualTo("own" to 42L)
fun `record round-trips`() {
val record = PersistentRecord("own", 42L, ScheduledReminder.NO_OCCURRENCE, 1_700_000_000_000L, misses = 2)
assertThat(PersistentRecord.decode(record.encode())).isEqualTo(record)
}
@Test
fun `malformed keys decode to null`() {
assertThat(decodePersistentKey("42")).isNull()
assertThat(decodePersistentKey("|42")).isNull()
assertThat(decodePersistentKey("own|x")).isNull()
}
@Test
fun `value round-trips occurrence and post time`() {
val value = encodePersistent(ScheduledReminder.NO_OCCURRENCE, 1_700_000_000_000L)
assertThat(decodePersistent(value)).isEqualTo(ScheduledReminder.NO_OCCURRENCE to 1_700_000_000_000L)
}
@Test
fun `malformed values decode to null`() {
assertThat(decodePersistent(null)).isNull()
assertThat(decodePersistent("12")).isNull()
assertThat(decodePersistent("12|x")).isNull()
assertThat(decodePersistent("1|2|3")).isNull()
fun `malformed records decode to null`() {
assertThat(PersistentRecord.decode("own|42|1|2")).isNull()
assertThat(PersistentRecord.decode("|42|1|2|0")).isNull()
assertThat(PersistentRecord.decode("own|x|1|2|0")).isNull()
assertThat(PersistentRecord.decode("own|42|1|2|0|9")).isNull()
}
}