From 515c7c3d261d666fd1016b615e9ed54c9589792b Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 16:29:34 +0100 Subject: [PATCH] =?UTF-8?q?fix(#145):=20review=20round=202=20=E2=80=94=20g?= =?UTF-8?q?uard=20empty=20snapshots=20and=20the=20post=20path,=20skip=20mu?= =?UTF-8?q?ted=20calendars=20in=20the=20scan?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../data/reminders/ReminderChannelPlan.kt | 11 ++-- .../data/reminders/ReminderChannels.kt | 60 +++++++++++++++---- .../data/reminders/ReminderNotifier.kt | 7 ++- .../data/reminders/ReminderScanner.kt | 5 +- .../ui/settings/NotificationSettings.kt | 7 ++- .../calendula/ui/settings/SettingsUiState.kt | 2 +- .../ui/settings/SettingsViewModel.kt | 23 ++++++- .../data/reminders/ReminderChannelPlanTest.kt | 20 +++++-- docs/ARCHITECTURE.md | 16 +++-- 9 files changed, 117 insertions(+), 34 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt index cb59e17b..bf00c6eb 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt @@ -35,18 +35,18 @@ data class ReminderChannelGroupSpec( data class ReminderChannelSpec( val id: String, val calendarId: Long, - /** The calendar's display name; blank when it has none. */ val name: String, - val groupId: String, + /** Null only for a channel created before its calendar could be looked up. */ + val groupId: String?, ) /** What a channel already looks like in the system, as far as the plan compares it. */ -data class ExistingReminderChannel(val id: String, val name: String) +data class ExistingReminderChannel(val id: String, val name: String, val description: String?) data class ReminderChannelPlan( val groups: List, val channels: List, - /** The [channels] that are missing or whose name changed. */ + /** The [channels] that are missing, or whose name or (localized) description changed. */ val channelsToWrite: List, val staleChannelIds: List, val staleGroupIds: List, @@ -64,6 +64,7 @@ fun planReminderChannels( existing: Collection, existingGroupIds: Collection, unnamed: String, + description: String, ): ReminderChannelPlan { val (local, synced) = calendars.partition { it.isLocal } val groups = buildList { @@ -98,7 +99,7 @@ fun planReminderChannels( channels = channels, channelsToWrite = channels.filter { spec -> val current = existingById[spec.id] - current == null || current.name != spec.name + current == null || current.name != spec.name || current.description != description }, staleChannelIds = existingById.keys.filter { isReminderChannelId(it) && it !in wantedChannels }, staleGroupIds = existingGroupIds.filter { isReminderGroupId(it) && it !in wantedGroups }, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt index a7f8f004..4fdecf95 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt @@ -8,7 +8,9 @@ import android.util.Log import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource +import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.ui.common.sourceAppLabel +import java.util.Locale import javax.inject.Inject import javax.inject.Singleton @@ -28,32 +30,61 @@ class ReminderChannels @Inject constructor( private val manager: NotificationManager get() = context.getSystemService(NotificationManager::class.java) - /** Bring the channels in line with the provider's calendars. */ + /** What the last [sync] saw, so an unchanged provider costs no channel writes. */ + @Volatile + private var lastSync: Any? = null + + /** + * Bring the channels in line with the provider's calendars. A calendar that + * syncs no events gets none, and an empty snapshot changes nothing: that is + * a provider hiccup far more often than every calendar gone at once. + */ fun sync() { + val calendars = calendarDataSource.calendars().filter { it.isLocal || it.syncsEvents } + if (calendars.isEmpty()) return val manager = manager val existing = manager.notificationChannels - val plan = plan(existing) + val key = syncKey(calendars, existing) + if (key == lastSync && existing.none { it.id == LEGACY_REMINDER_CHANNEL_ID }) return + val groups = manager.notificationChannelGroups + val plan = plan(calendars, existing, groups.map { it.id }) plan.staleChannelIds.forEach(manager::deleteNotificationChannel) plan.staleGroupIds.forEach(manager::deleteNotificationChannelGroup) - val groupNames = manager.notificationChannelGroups.associate { it.id to it.name?.toString() } + val groupNames = groups.associate { it.id to it.name?.toString() } write( groups = plan.groups.filter { groupNames[it.id] != groupLabel(it) }, channels = plan.channelsToWrite, existing = existing, ) - if (plan.channels.isNotEmpty()) retireLegacyChannel() + retireLegacyChannel() + lastSync = syncKey(calendars, manager.notificationChannels) } + private fun syncKey(calendars: List, channels: List): Any = listOf( + calendars.map { listOf(it.id, it.displayName, it.accountName, it.accountType, it.isLocal) }, + Locale.getDefault(), + channels.mapTo(HashSet()) { it.id }, + ) + /** * The channel to post [calendarId]'s reminder on, created first if a sync - * has not got to it yet. Null when the calendar no longer exists. + * has not got to it yet. Null when the calendar no longer exists. Should the + * calendar lookup fail, the channel is still created, plainly named and + * ungrouped, for the next sync to name and file — a reminder is never lost + * to its channel. */ fun channelFor(calendarId: Long): String? { val id = reminderChannelId(calendarId) val manager = manager if (manager.getNotificationChannel(id) != null) return id val existing = manager.notificationChannels - val plan = plan(existing) + val plan = try { + plan(calendarDataSource.calendars(), existing, emptyList()) + } catch (e: Exception) { + Log.w(TAG, "Could not look up calendar $calendarId for its channel", e) + write(emptyList(), listOf(ReminderChannelSpec(id, calendarId, context.getString(R.string.reminder_channel_name), null)), existing) + return id + } val spec = plan.channels.firstOrNull { it.calendarId == calendarId } ?: return null val knownGroups = manager.notificationChannelGroups.mapTo(HashSet()) { it.id } write( @@ -64,11 +95,16 @@ class ReminderChannels @Inject constructor( return id } - private fun plan(existing: List): ReminderChannelPlan = planReminderChannels( - calendars = calendarDataSource.calendars(), - existing = existing.map { ExistingReminderChannel(it.id, it.name.toString()) }, - existingGroupIds = manager.notificationChannelGroups.map { it.id }, + private fun plan( + calendars: List, + existing: List, + existingGroupIds: List, + ): ReminderChannelPlan = planReminderChannels( + calendars = calendars, + existing = existing.map { ExistingReminderChannel(it.id, it.name.toString(), it.description) }, + existingGroupIds = existingGroupIds, unnamed = context.getString(R.string.calendar_unnamed), + description = context.getString(R.string.reminder_channel_description), ) private fun write( @@ -94,7 +130,7 @@ class ReminderChannels @Inject constructor( current?.importance ?: template?.importance ?: NotificationManager.IMPORTANCE_HIGH, ).apply { description = context.getString(R.string.reminder_channel_description) - group = spec.groupId + spec.groupId?.let { group = it } if (current == null && template != null) inheritFrom(template) } }, @@ -114,6 +150,8 @@ class ReminderChannels @Inject constructor( lightColor = template.lightColor lockscreenVisibility = template.lockscreenVisibility setShowBadge(template.canShowBadge()) + // Only honoured with Do Not Disturb access, so usually left to the user. + setBypassDnd(template.canBypassDnd()) } /** diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index ec6f8c89..3631482e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt @@ -65,7 +65,12 @@ class ReminderNotifier @Inject constructor( /** Post [alert], unless its calendar is silenced or gone. */ suspend fun post(alert: ReminderAlert) { if (isSilenced(alert.calendarId)) return - val channelId = channels.channelFor(alert.calendarId) ?: return + val channelId = try { + channels.channelFor(alert.calendarId) + } catch (e: Exception) { + Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e) + null + } ?: return val title = displayTitle(alert) val is24Hour = settingsPrefs.timeFormat.first() .is24Hour(android.text.format.DateFormat.is24HourFormat(context)) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderScanner.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderScanner.kt index 92845523..f50e2728 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderScanner.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderScanner.kt @@ -90,7 +90,10 @@ class ReminderScanner @Inject constructor( val lookahead = reminderQueryHorizon(LOOKAHEAD_MILLIS, source.longestReminderMinutes()) // Reach into the past too: an all-day "at time of event" encodes to a // negative offset, and a catch-up pass needs the occurrences it missed. + // Calendars muted in-app (#272) plan nothing, so they arm no wake-ups. + val muted = settingsPrefs.mutedReminderCalendarIds.first() val occurrences = source.occurrences(now - PAST_WINDOW_MILLIS, now + lookahead) + .filter { it.calendarId !in muted } val planned = planReminders( instances = occurrences, minutesByEvent = source.reminderMinutes(occurrences.map { it.eventId }) @@ -127,8 +130,6 @@ class ReminderScanner @Inject constructor( private fun syncChannels() { try { channels.sync() - } catch (e: SecurityException) { - throw e } catch (e: Exception) { Log.w(TAG, "Reminder channel sync failed", e) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt index 0dcd416b..b87b4b9c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt @@ -114,7 +114,12 @@ internal fun NotificationsScreen( summary = stringResource(R.string.settings_notification_sound_hint), position = Position.Middle, trailing = { ExternalLinkIcon() }, - onClick = { context.openNotificationSettings() }, + onClick = { + scope.launch { + viewModel.syncReminderChannels() + context.openNotificationSettings() + } + }, ) GroupedRow( title = stringResource(R.string.settings_default_reminder), diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt index 3944032c..43a8edce 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt @@ -96,7 +96,7 @@ data class SettingsUiState( val perCalendarReminderOverride: Map> = emptyMap(), /** Per-calendar overrides of [defaultAllDayReminderMinutes] for all-day events. */ val perCalendarAllDayReminderOverride: Map> = emptyMap(), - /** Writable calendars, shown as per-calendar reminder-override rows. */ + /** Switched-on calendars you can edit: the per-calendar duration and reminder-override rows. */ val writableCalendars: List = emptyList(), /** Switched-on calendars, each with its own notification switch and channel (#145, #272). */ val reminderCalendars: List = emptyList(), diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt index dad8f8bf..af7ff478 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt @@ -46,6 +46,7 @@ import de.jeanlucmakiola.calendula.ui.common.TimelineScale import de.jeanlucmakiola.calendula.ui.month.MonthViewStyle import de.jeanlucmakiola.calendula.ui.theme.AppFontSettings import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow @@ -364,8 +365,26 @@ class SettingsViewModel @Inject constructor( save { setCalendarRemindersEnabled(calendarId, enabled) } /** [calendarId]'s reminder channel, created if needed so its system settings can open (#340). */ - suspend fun reminderChannelFor(calendarId: Long): String? = - withContext(io) { runCatching { reminderChannels.channelFor(calendarId) }.getOrNull() } + suspend fun reminderChannelFor(calendarId: Long): String? = withContext(io) { + try { + reminderChannels.channelFor(calendarId) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + null + } + } + + /** Create the per-calendar channels before showing the app's channel list, even with reminders off. */ + suspend fun syncReminderChannels() = withContext(io) { + try { + reminderChannels.sync() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Unit + } + } fun setAutofocusEventTitle(enabled: Boolean) = save { setAutofocusEventTitle(enabled) } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt index 4227de86..d18fa12d 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt @@ -27,6 +27,7 @@ class ReminderChannelPlanTest { existing = emptyList(), existingGroupIds = emptyList(), unnamed = "Unnamed", + description = DESC, ) assertThat(plan.groups).hasSize(2) assertThat(plan.channels.map { it.id }) @@ -46,6 +47,7 @@ class ReminderChannelPlanTest { existing = emptyList(), existingGroupIds = emptyList(), unnamed = "Unnamed", + description = DESC, ) assertThat(plan.groups).hasSize(1) assertThat(plan.groups.single().isLocal).isTrue() @@ -62,6 +64,7 @@ class ReminderChannelPlanTest { existing = emptyList(), existingGroupIds = emptyList(), unnamed = "Unnamed", + description = DESC, ) assertThat(plan.groups.filter { it.ambiguous }.map { it.accountType }) .containsExactly("com.google", "bitfire.at.davdroid") @@ -72,7 +75,7 @@ class ReminderChannelPlanTest { fun `stale reminder channels and groups go, foreign ones stay`() { val current = calendar(1, "me@example.org", "com.google") fun plan(calendars: List, existing: List = emptyList(), groups: List = emptyList()) = - planReminderChannels(calendars, existing.map { ExistingReminderChannel(it, "Cal ${it.last()}") }, groups, "Unnamed") + planReminderChannels(calendars, existing.map { ExistingReminderChannel(it, "Cal ${it.last()}", DESC) }, groups, "Unnamed", DESC) val keptGroup = plan(listOf(current)).groups.single().id val goneGroup = plan(listOf(calendar(9, "old", "com.google"))).groups.single().id val result = plan( @@ -91,15 +94,22 @@ class ReminderChannelPlanTest { calendar(1, "a", "com.google"), calendar(2, "a", "com.google"), calendar(3, "a", "com.google").copy(displayName = ""), + calendar(4, "a", "com.google"), ), existing = listOf( - ExistingReminderChannel(reminderChannelId(1), "Cal 1"), - ExistingReminderChannel(reminderChannelId(2), "Old name"), + ExistingReminderChannel(reminderChannelId(1), "Cal 1", DESC), + ExistingReminderChannel(reminderChannelId(4), "Cal 4", "Old description"), + ExistingReminderChannel(reminderChannelId(2), "Old name", DESC), ), existingGroupIds = emptyList(), unnamed = "Unnamed", + description = DESC, ) - assertThat(plan.channelsToWrite.map { it.calendarId }).containsExactly(2L, 3L) - assertThat(plan.channelsToWrite.last().name).isEqualTo("Unnamed") + assertThat(plan.channelsToWrite.map { it.calendarId }).containsExactly(2L, 3L, 4L) + assertThat(plan.channelsToWrite.single { it.calendarId == 3L }.name).isEqualTo("Unnamed") + } + + private companion object { + const val DESC = "Reminders" } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 503c49f6..9e8e4a2a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -392,16 +392,20 @@ switched off. The drawer's filter sheet (`CalendarPrefs.hiddenCalendarIds`) is a separate in-app declutter that never touches reminders. **A channel per calendar (#145).** `ReminderChannels` keeps one notification -channel per calendar, grouped by account, so a calendar can be muted or given -its own sound in the system settings before it ever fires. Every scan with -reminders on syncs them: missing channels are created, renamed ones updated, and -channels of deleted calendars removed. Switched-off calendars keep theirs, so -toggling one never cancels a showing reminder or loses its settings. A new channel copies the sound, vibration and +channel per calendar that syncs events, grouped by account, so a calendar can be +muted or given its own sound in the system settings before it ever fires. Every +scan with reminders on syncs them (skipped when nothing changed): missing +channels are created, renamed ones updated, and channels of deleted calendars +removed — but never on an empty snapshot, which is a provider hiccup more often +than every calendar gone. Switched-off calendars keep theirs, so toggling one +never cancels a showing reminder or loses its settings. `post` creates a missing +channel itself, so a reminder never waits on a sync. A new channel copies the sound, vibration and importance of the pre-#145 single `reminders` channel, which is deleted once nothing showing still sits on it. Settings → Notifications only deep-links into the system's channel screens (#340); the app never sets a sound itself. Separate from both, `SettingsPrefs.mutedReminderCalendarIds` is the in-app per-calendar -off switch (#272), checked in `ReminderNotifier.post` alongside visibility. +off switch (#272): the scan plans nothing for those calendars (so they arm no +wake-ups), and `ReminderNotifier.post` checks it again for snoozes. Deliberately absent: a fallback to the provider's `EVENT_REMINDER` broadcast. Keeping both would double-post wherever the provider works, and Etar's way out —