fix(#145): review round 2 — guard empty snapshots and the post path, skip muted calendars in the scan

This commit is contained in:
makiolaj committed 2026-11-13 16:29:34 +01:00
1 parent 9b5880b719
commit 515c7c3d26
9 files changed
+117 -34

No files matched your search

@@ -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<ReminderChannelGroupSpec>,
val channels: List<ReminderChannelSpec>,
/** The [channels] that are missing or whose name changed. */
/** The [channels] that are missing, or whose name or (localized) description changed. */
val channelsToWrite: List<ReminderChannelSpec>,
val staleChannelIds: List<String>,
val staleGroupIds: List<String>,
@@ -64,6 +64,7 @@ fun planReminderChannels(
existing: Collection<ExistingReminderChannel>,
existingGroupIds: Collection<String>,
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 },
@@ -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<CalendarSource>, channels: List<NotificationChannel>): 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<NotificationChannel>): 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<CalendarSource>,
existing: List<NotificationChannel>,
existingGroupIds: List<String>,
): 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())
}
/**
@@ -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))
@@ -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)
}
@@ -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),
@@ -96,7 +96,7 @@ data class SettingsUiState(
val perCalendarReminderOverride: Map<Long, List<Int>> = emptyMap(),
/** Per-calendar overrides of [defaultAllDayReminderMinutes] for all-day events. */
val perCalendarAllDayReminderOverride: Map<Long, List<Int>> = 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<CalendarSource> = emptyList(),
/** Switched-on calendars, each with its own notification switch and channel (#145, #272). */
val reminderCalendars: List<CalendarSource> = emptyList(),
@@ -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) }
@@ -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<CalendarSource>, existing: List<String> = emptyList(), groups: List<String> = 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"
}
}
+10 -6
View File
@@ -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 —