Persistent reminders: one place decides persistence (#100)

This commit is contained in:
makiolaj committed 2026-11-17 16:38:27 +01:00
1 parent 8138ae4454
commit fc72aaf561
6 files changed
+51 -66

No files matched your search

@@ -5,7 +5,6 @@ import android.content.Context
import android.content.Intent
import androidx.core.net.toUri
import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.agendula.data.prefs.Settings
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.tasks.StartupGate
import de.jeanlucmakiola.agendula.data.tasks.TaskQuery
@@ -50,7 +49,7 @@ class DueReminderReceiver : BroadcastReceiver() {
if (!settings.remindersEnabled) return@launch
runCatching {
startupGate.awaitReady()
notifier.postIfOpen(dataSource, taskId, occurrence, settings)
notifier.postIfOpen(dataSource, taskId, occurrence)
}
} finally {
pending.finish()
@@ -125,14 +124,14 @@ internal fun Task.isOccurrence(occurrenceStart: Long?): Boolean = when (occurren
* With [exact], a lookup that fell back to another occurrence posts nothing.
*
* [restoring] brings back a persistent reminder, unless its task was moved to a
* later due since (or, see [TaskNotifier.postDue], its list stopped being persistent). A persistent reminder that won't come back is forgotten; one
* whose task an external store just failed to find is kept for a while.
* later due since or its list stopped being persistent (see [TaskNotifier.postDue]).
* A persistent reminder that won't come back is forgotten; one whose task an
* external store just failed to find is kept for a while.
*/
internal suspend fun TaskNotifier.postIfOpen(
dataSource: TasksDataSource,
taskId: Long,
occurrenceStart: Long,
settings: Settings,
alert: Boolean = true,
exact: Boolean = false,
postedAt: Long? = null,
@@ -148,7 +147,7 @@ internal suspend fun TaskNotifier.postIfOpen(
if (task.taskId != taskId) forget(task.taskId, occurrence = occurrenceStart)
return
}
postDue(task, settings, alert, postedAt, restoring)
postDue(task, alert, postedAt, restoring)
// An edited occurrence is a row of its own, posted and remembered under its own id.
if (task.taskId != taskId) forget(taskId, occurrence = occurrenceStart)
val now = runCatching { dataSource.occurrence(taskId, occurrenceStart) }.getOrElse { return }
@@ -69,18 +69,16 @@ class ReminderActionReceiver : BroadcastReceiver() {
val settings = settingsPrefs.settings.first()
if (!settings.remindersEnabled) return@runCatching
startupGate.awaitReady()
notifier.postIfOpen(dataSource, taskId, occurrence, settings)
notifier.postIfOpen(dataSource, taskId, occurrence)
}
ACTION_DISMISSED -> runCatching {
if (store == null) return@runCatching
val settings = settingsPrefs.settings.first()
startupGate.awaitReady()
val listId = intent.getLongExtra(EXTRA_LIST_ID, -1L).takeIf { it > 0L }
// An intent without a list predates it; the re-post checks the task's list anyway.
val persistent = listId?.let(settings::persistentRemindersFor) ?: settings.anyPersistentReminders
if (persistent && notifier.isCurrentStore(store)) {
notifier.repostRemembered(taskId, occurrence, settings)
// Whether its list is still persistent is the re-post's call, on the task's list.
if (settings.anyPersistentReminders && notifier.isCurrentStore(store)) {
notifier.repostRemembered(taskId, occurrence)
} else {
notifier.forget(taskId, store, occurrence)
}
@@ -108,7 +106,6 @@ class ReminderActionReceiver : BroadcastReceiver() {
private const val EXTRA_TASK_ID = "de.jeanlucmakiola.agendula.extra.TASK_ID"
private const val EXTRA_OCCURRENCE = "de.jeanlucmakiola.agendula.extra.OCCURRENCE_START"
private const val EXTRA_STORE = "de.jeanlucmakiola.agendula.extra.STORE"
private const val EXTRA_LIST_ID = "de.jeanlucmakiola.agendula.extra.LIST_ID"
/**
* The data URI is what keeps two reminders' PendingIntents apart —
@@ -122,8 +119,8 @@ class ReminderActionReceiver : BroadcastReceiver() {
.putExtra(EXTRA_OCCURRENCE, occurrenceStart)
.apply { if (store != null) putExtra(EXTRA_STORE, store) }
/** A persistent reminder's delete intent, naming the store its task id belongs to and its list. */
fun dismissedIntent(context: Context, taskId: Long, occurrenceStart: Long, store: String, listId: Long): Intent =
intent(context, ACTION_DISMISSED, taskId, occurrenceStart, store).putExtra(EXTRA_LIST_ID, listId)
/** A persistent reminder's delete intent, naming the store its task id belongs to. */
fun dismissedIntent(context: Context, taskId: Long, occurrenceStart: Long, store: String): Intent =
intent(context, ACTION_DISMISSED, taskId, occurrenceStart, store)
}
}
@@ -114,6 +114,8 @@ class ReminderScheduler @Inject constructor(
val armed = diff.arm.filter { schedule(it) }
store.replace(diff.keep + armed, fired = fired, exact = canExact)
withdrawStale()
// Catches a task moved to a list that is persistent differently.
runCatching { notifier.restyleActive(tasks.associate { it.taskId to it.listId }) }
runCatching { notifier.restorePersistent(settings) }
}
@@ -33,7 +33,6 @@ import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.calendarDate
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
@@ -55,8 +54,9 @@ import kotlin.time.Instant
* Posts one notification per due task on its list's channel, so each list can
* have its own sound and importance. The tag is the task id, so a re-fired alarm
* replaces rather than duplicates. Tapping opens the task's detail screen (see
* [MainActivity.taskIntent]). With [Settings.persistentRemindersFor] its list a reminder
* re-posts silently when swiped away and is remembered so a reboot brings it back.
* [MainActivity.taskIntent]). A reminder whose list is persistent (see
* [Settings.persistentRemindersFor]) re-posts silently when swiped away and is
* remembered so a reboot brings it back.
*/
@Singleton
class TaskNotifier @Inject constructor(
@@ -82,26 +82,30 @@ class TaskNotifier @Inject constructor(
return granted && NotificationManagerCompat.from(context).areNotificationsEnabled()
}
/**
* Posts [task]'s reminder with the settings read under the lock, so a list
* that just stopped being persistent is never posted persistent. This is
* where a restore of a no longer persistent reminder is forgotten.
*/
suspend fun postDue(
task: Task,
settings: Settings,
alert: Boolean = true,
postedAt: Long? = null,
restoring: PersistentRecord? = null,
) {
if (!canPost()) return
postLock.withLock {
val settings = settingsPrefs.settings.first()
val persistent = settings.persistentRemindersFor(task.listId)
if (restoring != null && !persistent) {
forget(restoring.taskId, restoring.store, restoring.occurrence)
return
}
if (!canPost()) return
// A restore yields to a reminder already up and to a Done or Snooze that dropped the record meanwhile.
if (restoring != null) {
if (postedReminders().any { it.taskId == task.taskId }) return
records.find(restoring.store, restoring.taskId, restoring.occurrence) ?: return
}
// The one place persistence is decided, on the latest settings: a list may have just changed.
val persistent = settingsPrefs.settings.first().persistentRemindersFor(task.listId)
if (restoring != null && !persistent) {
forget(restoring.taskId, restoring.store, restoring.occurrence)
return
}
post(task, settings, alert, postedAt, persistent)
}
}
@@ -151,7 +155,7 @@ class TaskNotifier @Inject constructor(
.setSilent(!alert)
// A group of its own, so a silent re-post doesn't land in NotificationCompat's shared "silent" group.
.apply { if (persistent) setGroup("$PERSISTENT_GROUP_PREFIX${task.taskId}") }
.setDeleteIntent(if (persistent) dismissedIntent(task.taskId, occurrence, task.listId) else null)
.setDeleteIntent(if (persistent) dismissedIntent(task.taskId, occurrence) else null)
.setContentIntent(tapIntent)
.addExtras(
Bundle().apply {
@@ -225,36 +229,24 @@ class TaskNotifier @Inject constructor(
* alert again and keeps each reminder's content and time. One posted before
* occurrence and due were recorded is left alone, as a re-post couldn't tell
* its occurrence. Reads the settings under the lock, so the latest wins
* however fast they flip. Each goes by its task's list now, like a re-post,
* falling back to the list it was posted in.
* however fast they flip. Each goes by its list in [taskLists] when known
* (a sync passes the tasks it read, catching moves), else by the list it
* was posted in; one already styled right is left alone.
*/
suspend fun restyleActive() {
startupGate.awaitReady()
// Read before the lock, so posts don't wait on the store.
val taskLists = postedReminders().filter { it.restylable }.associate { posted ->
posted.taskId to try {
dataSource.occurrence(posted.taskId, posted.occurrence!!)?.listId
} catch (e: CancellationException) {
throw e
} catch (_: Exception) {
null
}
}
postLock.withLock { restyleLocked(taskLists) }
}
private suspend fun restyleLocked(taskLists: Map<Long, Long?>) {
suspend fun restyleActive(taskLists: Map<Long, Long> = emptyMap()) = postLock.withLock {
val settings = settingsPrefs.settings.first()
postedReminders().filter { it.restylable }.forEach { posted ->
postedReminders().forEach { posted ->
val occurrence = posted.occurrence ?: return@forEach
if (!posted.notification.extras.containsKey(EXTRA_DUE)) return@forEach
val listId = taskLists[posted.taskId] ?: posted.listId ?: return@forEach
val persistent = settings.persistentRemindersFor(listId)
if ((posted.notification.deleteIntent != null) == persistent) return@forEach
val due = posted.notification.extras.getLong(EXTRA_DUE).takeIf { it != NO_DUE }
val notification = Notification.Builder.recoverBuilder(context, posted.notification)
.setAutoCancel(!persistent)
.setOnlyAlertOnce(true)
.setGroup(if (persistent) "$PERSISTENT_GROUP_PREFIX${posted.taskId}" else null)
.setDeleteIntent(if (persistent) dismissedIntent(posted.taskId, occurrence, listId) else null)
.setDeleteIntent(if (persistent) dismissedIntent(posted.taskId, occurrence) else null)
.build()
manager.notify(posted.taskId.toString(), NOTIFICATION_ID, notification)
remember(posted.taskId, occurrence, due, posted.postedAt, persistent)
@@ -262,27 +254,26 @@ class TaskNotifier @Inject constructor(
}
/** Re-posts the shown reminders silently, so a changed snooze length or description shows on them. */
suspend fun refreshShown(settings: Settings) {
suspend fun refreshShown() {
startupGate.awaitReady()
postedReminders().forEach { posted ->
val occurrence = posted.occurrence ?: return@forEach
runCatching {
postIfOpen(dataSource, posted.taskId, occurrence, settings, alert = false, exact = true, postedAt = posted.postedAt)
postIfOpen(dataSource, posted.taskId, occurrence, alert = false, exact = true, postedAt = posted.postedAt)
}
}
}
/** Re-posts [taskId]'s persistent reminder after a swipe, if it is still remembered. */
suspend fun repostRemembered(taskId: Long, occurrence: Long, settings: Settings) {
suspend fun repostRemembered(taskId: Long, occurrence: Long) {
val record = records.find(currentStore, taskId, occurrence) ?: return
repost(record, settings)
repost(record)
}
private suspend fun repost(record: PersistentRecord, settings: Settings) = postIfOpen(
private suspend fun repost(record: PersistentRecord) = postIfOpen(
dataSource,
record.taskId,
record.occurrence,
settings,
alert = false,
exact = true,
postedAt = record.postedAt,
@@ -304,7 +295,7 @@ class TaskNotifier @Inject constructor(
// Nothing could be shown; trying anyway would re-read every record on each sync.
if (!canPost()) return
val shown = postedReminders().mapTo(HashSet()) { it.taskId }
records.all().filter { it.taskId !in shown }.forEach { runCatching { repost(it, settings) } }
records.all().filter { it.taskId !in shown }.forEach { runCatching { repost(it) } }
}
private class Posted(
@@ -313,10 +304,7 @@ class TaskNotifier @Inject constructor(
val occurrence: Long?,
val postedAt: Long,
val notification: Notification,
) {
/** Posted with occurrence and due, so a restyle can keep both. */
val restylable: Boolean get() = occurrence != null && notification.extras.containsKey(EXTRA_DUE)
}
)
/** The current store's posted reminders; another store's ids name other tasks. */
private fun postedReminders(): List<Posted> {
@@ -332,8 +320,8 @@ class TaskNotifier @Inject constructor(
}
}
private fun dismissedIntent(taskId: Long, occurrence: Long, listId: Long): PendingIntent =
broadcast(taskId, ReminderActionReceiver.dismissedIntent(context, taskId, occurrence, currentStore, listId))
private fun dismissedIntent(taskId: Long, occurrence: Long): PendingIntent =
broadcast(taskId, ReminderActionReceiver.dismissedIntent(context, taskId, occurrence, currentStore))
private fun actionIntent(task: Task, action: String): PendingIntent = broadcast(
task.taskId,
@@ -215,7 +215,7 @@ internal fun NotificationsScreen(
)
GroupedSwitchRow(
title = stringResource(R.string.settings_persistent_reminders),
summary = withOwnCount(stringResource(R.string.settings_persistent_reminders_hint), ownPersistence),
summary = stringResource(R.string.settings_persistent_reminders_hint),
checked = state.settings.persistentReminders,
onCheckedChange = viewModel::setPersistentReminders,
position = Position.Middle,
@@ -461,7 +461,8 @@ private fun withOwnCount(label: String, own: Int): String =
private fun listSourceSummary(own: Boolean, persistence: ListPersistence): AnnotatedString {
val ownText = stringResource(R.string.settings_list_reminder_own)
val followsText = stringResource(R.string.settings_list_reminder_follows)
val persistenceText = if (persistence == ListPersistence.INHERIT) null else listPersistenceLabel(persistence)
// Spelled out, so it doesn't read as a reply to "Follows the default", which is about reminder times.
val persistenceText = listPersistenceOptionSummary(persistence, appWide = false).takeIf { persistence != ListPersistence.INHERIT }
val primary = MaterialTheme.colorScheme.primary
return buildAnnotatedString {
if (own) withStyle(SpanStyle(color = primary)) { append(ownText) } else append(followsText)
@@ -34,7 +34,6 @@ import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
@@ -279,8 +278,7 @@ class SettingsViewModel @Inject constructor(
}
private suspend fun refreshShownReminders() {
val settings = prefs.settings.first()
withContext(io) { runCatching { taskNotifier.refreshShown(settings) } }
withContext(io) { runCatching { taskNotifier.refreshShown() } }
}
private suspend fun restyleReminders() {