Tell external providers apart in persistent reminders and reminder actions, skip restoring with nothing remembered (#100)

This commit is contained in:
makiolaj committed 2026-11-20 12:58:05 +01:00
1 parent a5accc5fef
commit 5e204a43f4
5 files changed
+154 -30

No files matched your search

@@ -40,6 +40,7 @@ import de.jeanlucmakiola.floret.reminders.normalizeReminders
import de.jeanlucmakiola.floret.reminders.reminderLeadsFor
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import java.time.DayOfWeek
import java.time.ZoneId
import java.time.LocalDate
@@ -494,6 +495,25 @@ class SettingsPrefs @Inject constructor(
private fun withAuthority(store: StorageMode): Pair<StorageMode, String?> =
store to if (store == StorageMode.EXTERNAL) resolver.resolveExternal()?.authority else null
/**
* What tells the current store's task ids apart from another store's or
* provider's, as persistent reminders and reminder actions record it: the
* list scope, lower-cased, so the bare `own` and `external` of earlier
* versions stay their store's.
*/
suspend fun storeScope(): String = scopeOf(dataStore.data.first()).lowercase()
/** [storeScope], first making the current provider the owner of the bare external entries if none is yet. */
suspend fun claimStoreScope(): String {
val p = dataStore.data.first()
if (p[EXTERNAL_LISTS_OWNER] != null) return scopeOf(p).lowercase()
val store = activeIn(p)
if (store.first != StorageMode.EXTERNAL || store.second == null) return store.first.name.lowercase()
var scope = ""
dataStore.edit { scope = claimedScope(it, store) }
return scope.lowercase()
}
suspend fun setStorageMode(mode: StorageMode) = dataStore.edit { it[STORAGE_MODE] = mode.name }
/**
@@ -133,7 +133,7 @@ class ReminderActionReceiver : BroadcastReceiver() {
* Whether a reminder posted from [postedIn] may act on its task id in the
* current store; one from before the store was recorded may.
*/
internal fun actsHere(postedIn: String?, isCurrentStore: (String) -> Boolean): Boolean =
internal suspend fun actsHere(postedIn: String?, isCurrentStore: suspend (String) -> Boolean): Boolean =
postedIn == null || isCurrentStore(postedIn)
/**
@@ -67,7 +67,8 @@ class TaskNotifier @Inject constructor(
) {
private val manager get() = context.getSystemService(NotificationManager::class.java)
private val channelPrefs get() = context.getSharedPreferences(CHANNEL_PREFS, Context.MODE_PRIVATE)
private val currentStore get() = resolver.mode().name.lowercase()
/** The store the channels belong to; records and actions tell providers apart too, see [SettingsPrefs.storeScope]. */
private val channelStore get() = resolver.mode().name.lowercase()
/** Keeps a post and a restyle from overwriting each other with a stale snapshot. */
private val postLock = Mutex()
@@ -107,6 +108,7 @@ class TaskNotifier @Inject constructor(
// canPost() checks POST_NOTIFICATIONS before we ever call notify().
@SuppressLint("MissingPermission")
private suspend fun post(task: Task, settings: Settings, alert: Boolean, postedAt: Long?, persistent: Boolean) {
val store = settingsPrefs.claimStoreScope()
val occurrence = task.occurrenceStart?.toEpochMilliseconds() ?: ScheduledReminder.NO_OCCURRENCE
val shownAt = postedAt ?: System.currentTimeMillis()
val channelId = ensureListChannel(task.listId, task.listName)
@@ -148,7 +150,7 @@ class TaskNotifier @Inject constructor(
.setAutoCancel(!persistent)
.setSilent(!alert)
.apply { groupFor(task.taskId, persistent, alert)?.let(::setGroup) }
.setDeleteIntent(if (persistent) dismissedIntent(task.taskId, occurrence) else null)
.setDeleteIntent(if (persistent) dismissedIntent(task.taskId, occurrence, store) else null)
.setContentIntent(tapIntent)
.addExtras(
Bundle().apply {
@@ -156,19 +158,19 @@ class TaskNotifier @Inject constructor(
putLong(EXTRA_DUE, task.due?.toEpochMilliseconds() ?: NO_DUE)
},
)
.addAction(0, context.getString(R.string.reminder_action_done), actionIntent(task, ReminderActionReceiver.ACTION_DONE))
.addAction(0, context.getString(R.string.reminder_action_done), actionIntent(task, ReminderActionReceiver.ACTION_DONE, store))
.addAction(
0,
context.getString(R.string.reminder_action_snooze, settings.snoozeMinutes),
actionIntent(task, ReminderActionReceiver.ACTION_SNOOZE),
actionIntent(task, ReminderActionReceiver.ACTION_SNOOZE, store),
)
.build()
NotificationManagerCompat.from(context).notify(task.taskId.toString(), NOTIFICATION_ID, notification)
remember(task.taskId, occurrence, task.due?.toEpochMilliseconds(), shownAt, persistent)
remember(store, task.taskId, occurrence, task.due?.toEpochMilliseconds(), shownAt, persistent)
}
private suspend fun remember(taskId: Long, occurrence: Long, due: Long?, postedAt: Long, persistent: Boolean) {
if (persistent) records.put(PersistentRecord(currentStore, taskId, occurrence, due, postedAt)) else forget(taskId)
private suspend fun remember(store: String, taskId: Long, occurrence: Long, due: Long?, postedAt: Long, persistent: Boolean) {
if (persistent) records.put(PersistentRecord(store, taskId, occurrence, due, postedAt)) else forget(taskId, store)
}
/** Characters per line of an expanded notification on this screen, at the user's font size. */
@@ -195,15 +197,16 @@ class TaskNotifier @Inject constructor(
* 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) {
records.removeIf { it.store == store && it.taskId == taskId && (occurrence == null || it.occurrence == occurrence) }
suspend fun forget(taskId: Long, store: String? = null, occurrence: Long? = null) {
val from = store ?: settingsPrefs.storeScope()
records.removeIf { it.store == from && it.taskId == taskId && (occurrence == null || it.occurrence == occurrence) }
}
/** Notes that a remembered reminder's task wasn't found; one gone long enough is dropped. */
suspend fun missed(taskId: Long, occurrence: Long) =
records.missed(currentStore, taskId, occurrence, System.currentTimeMillis())
records.missed(settingsPrefs.storeScope(), taskId, occurrence, System.currentTimeMillis())
fun isCurrentStore(store: String?): Boolean = store == currentStore
suspend fun isCurrentStore(store: String?): Boolean = store == settingsPrefs.storeScope()
/** Whether a task the store can't find is really gone; an external provider that fails a read finds nothing too. */
fun missingMeansGone(): Boolean = resolver.mode() == StorageMode.OWN
@@ -227,8 +230,10 @@ class TaskNotifier @Inject constructor(
* was posted in; one already styled right is left alone.
*/
suspend fun restyleActive(taskLists: Map<Long, Long> = emptyMap()) = postLock.withLock {
val shown = postedReminders().ifEmpty { return@withLock }
val settings = settingsPrefs.settings.first()
postedReminders().forEach { posted ->
val store = settingsPrefs.claimStoreScope()
shown.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
@@ -239,10 +244,10 @@ class TaskNotifier @Inject constructor(
.setAutoCancel(!persistent)
.setOnlyAlertOnce(true)
.setGroup(groupFor(posted.taskId, persistent, alert = true))
.setDeleteIntent(if (persistent) dismissedIntent(posted.taskId, occurrence) else null)
.setDeleteIntent(if (persistent) dismissedIntent(posted.taskId, occurrence, store) else null)
.build()
manager.notify(posted.taskId.toString(), NOTIFICATION_ID, notification)
remember(posted.taskId, occurrence, due, posted.postedAt, persistent)
remember(store, posted.taskId, occurrence, due, posted.postedAt, persistent)
}
}
@@ -259,7 +264,7 @@ class TaskNotifier @Inject constructor(
/** Re-posts [taskId]'s persistent reminder after a swipe, if it is still remembered. */
suspend fun repostRemembered(taskId: Long, occurrence: Long) {
val record = records.find(currentStore, taskId, occurrence) ?: return
val record = records.find(settingsPrefs.storeScope(), taskId, occurrence) ?: return
repost(record)
}
@@ -276,17 +281,18 @@ class TaskNotifier @Inject constructor(
/**
* 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.
* re-post couldn't read the task. Another store's or provider's are dropped:
* their ids name other tasks here.
*/
suspend fun restorePersistent(settings: Settings) {
if (records.all().isEmpty()) return
if (!settings.anyPersistentReminders) return records.clear()
// Before it, the store is a guess, and a wrong one would drop every record.
startupGate.awaitReady()
// A list deleted elsewhere leaves its setting behind; a read finding no list proves nothing.
val lists = runCatching { dataSource.taskLists().mapTo(HashSet()) { it.id } }.getOrNull()?.takeIf { it.isNotEmpty() }
if (lists != null && !settings.anyPersistentReminders(lists)) return records.clear()
val store = currentStore
val store = settingsPrefs.storeScope()
records.removeIf { it.store != store }
// Nothing could be shown; trying anyway would re-read every record on each sync.
if (!canPost()) return
@@ -307,7 +313,7 @@ class TaskNotifier @Inject constructor(
/** The current store's posted reminders; another store's ids name other tasks. */
private fun postedReminders(): List<Posted> {
val prefix = "$LIST_CHANNEL_PREFIX${currentStore}_"
val prefix = "$LIST_CHANNEL_PREFIX${channelStore}_"
return manager.activeNotifications
.filter { it.id == NOTIFICATION_ID && it.notification.channelId?.startsWith(prefix) == true }
.mapNotNull { posted ->
@@ -330,17 +336,17 @@ class TaskNotifier @Inject constructor(
else -> SILENT_GROUP
}
private fun dismissedIntent(taskId: Long, occurrence: Long): PendingIntent =
broadcast(taskId, ReminderActionReceiver.dismissedIntent(context, taskId, occurrence, currentStore))
private fun dismissedIntent(taskId: Long, occurrence: Long, store: String): PendingIntent =
broadcast(taskId, ReminderActionReceiver.dismissedIntent(context, taskId, occurrence, store))
private fun actionIntent(task: Task, action: String): PendingIntent = broadcast(
private fun actionIntent(task: Task, action: String, store: String): PendingIntent = broadcast(
task.taskId,
ReminderActionReceiver.intent(
context,
action,
task.taskId,
task.occurrenceStart?.toEpochMilliseconds() ?: ScheduledReminder.NO_OCCURRENCE,
store = currentStore,
store = store,
),
)
@@ -359,7 +365,7 @@ class TaskNotifier @Inject constructor(
*/
fun ensureListChannel(listId: Long, listName: String?): String {
ensureGroup()
val id = "$LIST_CHANNEL_PREFIX${currentStore}_$listId"
val id = "$LIST_CHANNEL_PREFIX${channelStore}_$listId"
val importance = manager.getNotificationChannel(id)?.importance ?: legacyImportance()
manager.createNotificationChannel(
NotificationChannel(
@@ -394,7 +400,7 @@ class TaskNotifier @Inject constructor(
startupGate.awaitReady()
val lists = dataSource.taskLists()
lists.forEach { ensureListChannel(it.id, it.name) }
val prefix = "$LIST_CHANNEL_PREFIX${currentStore}_"
val prefix = "$LIST_CHANNEL_PREFIX${channelStore}_"
val live = lists.map { "$prefix${it.id}" }.toSet()
manager.notificationChannels
.filter { it.id.startsWith(prefix) && it.id !in live }
@@ -0,0 +1,98 @@
package de.jeanlucmakiola.agendula.data.reminders
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.emptyPreferences
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.tasks.ProviderEnvironment
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Test
/** Persistent reminders and reminder actions of one external provider never reach another's task with the same id. */
class ProviderScopeTest {
private class MemoryDataStore : DataStore<Preferences> {
override val data = MutableStateFlow(emptyPreferences())
override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences) =
transform(data.value).also { data.value = it }
}
/** One provider installed at a time, its permissions held. */
private class SwitchingEnvironment(var authority: String) : ProviderEnvironment {
var lookups = 0
override fun packageDeclaring(authority: String): String? {
lookups++
return authority.takeIf { it == this.authority }
}
override fun isGranted(permission: String) = true
override fun appLabel(packageName: String): String? = packageName
}
private val environment = SwitchingEnvironment(OPEN_TASKS)
private val dataStore = MemoryDataStore()
private val prefs = SettingsPrefs(dataStore, ProviderResolver(environment).apply { storageMode = StorageMode.EXTERNAL })
private val records = PersistentReminderStore(dataStore)
@Test
fun `another provider's reminder neither acts nor is restored`() = runBlocking<Unit> {
prefs.setStorageMode(StorageMode.EXTERNAL)
val first = prefs.claimStoreScope()
assertThat(first).isEqualTo("external")
records.put(PersistentRecord(first, taskId = 5, occurrence = 0, due = null, postedAt = 1))
environment.authority = TASKS_ORG
val second = prefs.storeScope()
assertThat(second).isEqualTo("external@$TASKS_ORG")
assertThat(ReminderActionReceiver.actsHere(first) { it == prefs.storeScope() }).isFalse()
assertThat(ReminderActionReceiver.actsHere(second) { it == prefs.storeScope() }).isTrue()
records.put(PersistentRecord(second, taskId = 5, occurrence = 0, due = null, postedAt = 2))
val current = prefs.storeScope()
records.removeIf { it.store != current }
assertThat(records.all().map { it.store to it.postedAt }).containsExactly(second to 2L)
}
@Test
fun `reminders recorded before providers were told apart belong to the one that owns the bare entries`() = runBlocking<Unit> {
prefs.setStorageMode(StorageMode.EXTERNAL)
records.put(PersistentRecord("external", taskId = 5, occurrence = 0, due = null, postedAt = 1))
assertThat(prefs.claimStoreScope()).isEqualTo("external")
environment.authority = TASKS_ORG
assertThat(ReminderActionReceiver.actsHere("external") { it == prefs.storeScope() }).isFalse()
environment.authority = OPEN_TASKS
assertThat(ReminderActionReceiver.actsHere("external") { it == prefs.storeScope() }).isTrue()
assertThat(records.find(prefs.storeScope(), 5, 0)).isNotNull()
}
@Test
fun `the settings ask for the provider only once its entries are kept apart`() = runBlocking<Unit> {
prefs.setStorageMode(StorageMode.EXTERNAL)
environment.lookups = 0
prefs.settings.first()
assertThat(environment.lookups).isEqualTo(0)
prefs.claimStoreScope()
prefs.setSnoozeMinutes(5)
environment.lookups = 0
prefs.settings.first()
assertThat(environment.lookups).isEqualTo(1)
}
@Test
fun `our own store keeps its bare name`() = runBlocking<Unit> {
prefs.setStorageMode(StorageMode.OWN)
assertThat(prefs.claimStoreScope()).isEqualTo("own")
assertThat(prefs.storeScope()).isEqualTo("own")
}
private companion object {
const val OPEN_TASKS = "org.dmfs.tasks"
const val TASKS_ORG = "org.tasks.opentasks"
}
}
@@ -6,20 +6,20 @@ import org.junit.jupiter.api.Test
class ReminderActionStoreTest {
private val current = { store: String -> store == "own" }
private val current: suspend (String) -> Boolean = { store -> store == "own" }
@Test
fun `a reminder from the current store acts on its task`() {
fun `a reminder from the current store acts on its task`() = runBlocking {
assertThat(ReminderActionReceiver.actsHere("own", current)).isTrue()
}
@Test
fun `a reminder from another store leaves the task with its id alone`() {
fun `a reminder from another store leaves the task with its id alone`() = runBlocking {
assertThat(ReminderActionReceiver.actsHere("provider", current)).isFalse()
}
@Test
fun `a reminder posted before the store was recorded still acts`() {
fun `a reminder posted before the store was recorded still acts`() = runBlocking {
assertThat(ReminderActionReceiver.actsHere(null, current)).isTrue()
}