diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt index 0e0266a5..14a5a91c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt @@ -177,6 +177,7 @@ class SettingsPrefs @Inject constructor( val mutedReminderCalendarIds: Flow> = prefs.flow(SettingsKeys.mutedReminderCalendarIds) val reminderAlertStyles: Flow> = prefs.flow(SettingsKeys.reminderAlertStyles) val notificationCategoryHintDismissed: Flow = prefs.flow(SettingsKeys.notificationCategoryHintDismissed) + val reminderChannelVersions: Flow> = prefs.flow(SettingsKeys.reminderChannelVersions) val allowColorOnUnsupportedCalendars: Flow = prefs.flow(SettingsKeys.allowColorOnUnsupportedCalendars) val defaultReminderMinutes: Flow> = prefs.flow(SettingsKeys.defaultReminderMinutes) @@ -298,6 +299,19 @@ class SettingsPrefs @Inject constructor( suspend fun setRemindersEnabled(enabled: Boolean) = prefs.set(SettingsKeys.remindersEnabled, enabled) + /** + * Reserve a new reminder channel version for each calendar in [floors], above + * both its stored high-water mark and its floor, and return them. Versions + * only grow: the system would restore a deleted channel's old settings if + * its id came back (#518). + */ + suspend fun reserveReminderChannelVersions(floors: Map): Map { + val stored = prefs.update(SettingsKeys.reminderChannelVersions) { current -> + current + floors.mapValues { (id, floor) -> maxOf((current[id] ?: 0) + 1, floor) } + } + return floors.keys.associateWith { stored.getValue(it) } + } + suspend fun dismissNotificationCategoryHint() = prefs.set(SettingsKeys.notificationCategoryHintDismissed, true) suspend fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) { @@ -717,6 +731,15 @@ object SettingsKeys { */ val notificationCategoryHintDismissed: Pref = booleanPref("notification_category_hint_dismissed", false) + /** + * The highest reminder channel version handed out per calendar (#518): a + * sound picked in the app recreates the channel under a new one. The + * channels themselves say which version is current; this only keeps ids + * from being reused. Serialised as `id=version;id=version`. + */ + val reminderChannelVersions: Pref> = + nullableStringPref("reminder_channel_versions").map(::parseChannelVersions) { it.toStoredVersions() } + /** * Whether to offer a custom event colour on calendars that publish no colour * palette; synced ones without a palette (some CalDAV) may drop or overwrite @@ -1193,6 +1216,18 @@ private fun parseDurationOverrides(stored: String?): Map = calendarId to minutes }.toMap() +private fun parseChannelVersions(stored: String?): Map = + stored?.split(ENTRY_SEP).orEmpty().mapNotNull { entry -> + val parts = entry.split(KEY_VALUE_SEP) + if (parts.size != 2) return@mapNotNull null + val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null + val version = parts[1].trim().toIntOrNull()?.takeIf { it > 0 } ?: return@mapNotNull null + calendarId to version + }.toMap() + +private fun Map.toStoredVersions(): String? = + if (isEmpty()) null else entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, v) -> "$id$KEY_VALUE_SEP$v" } + private fun Map.toStoredDurations(): String = entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, minutes) -> "$id$KEY_VALUE_SEP$minutes" 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 aa3a6b68..57b70487 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 @@ -13,8 +13,37 @@ private const val CHANNEL_PREFIX = "reminders.calendar." private const val GROUP_PREFIX = "reminders.account." private const val LOCAL_GROUP_ID = GROUP_PREFIX + "local" -/** The notification channel [calendarId]'s reminders post on. */ -fun reminderChannelId(calendarId: Long): String = CHANNEL_PREFIX + calendarId +private const val VERSION_SEPARATOR = ".v" + +/** + * The notification channel [calendarId]'s reminders post on. A sound picked in + * the app moves it to a new [version] (#518), since a channel's sound is fixed + * once created; version 0 is the unversioned id #145 introduced. + */ +fun reminderChannelId(calendarId: Long, version: Int = 0): String = + if (version == 0) "$CHANNEL_PREFIX$calendarId" else "$CHANNEL_PREFIX$calendarId$VERSION_SEPARATOR$version" + +/** The calendar and version a reminder channel id names, or null for any other id. */ +fun parseReminderChannelId(channelId: String): Pair? { + if (!isReminderChannelId(channelId)) return null + val rest = channelId.removePrefix(CHANNEL_PREFIX) + val calendar = rest.substringBefore(VERSION_SEPARATOR).toLongOrNull() ?: return null + if (VERSION_SEPARATOR !in rest) return calendar to 0 + val version = rest.substringAfter(VERSION_SEPARATOR).toIntOrNull()?.takeIf { it > 0 } ?: return null + return calendar to version +} + +/** + * Each calendar's current channel version: the highest one that exists, so a + * new version only takes over once it is written. A calendar with none falls + * back to its [highWater] mark — re-creating that id restores its own settings. + */ +fun currentReminderChannelVersions(existingChannelIds: Collection, highWater: Map): Map { + val existing = existingChannelIds.mapNotNull(::parseReminderChannelId) + .groupBy({ it.first }, { it.second }) + .mapValues { (_, versions) -> versions.max() } + return highWater + existing +} /** Whether [channelId] is one of the per-calendar reminder channels. */ fun isReminderChannelId(channelId: String): Boolean = channelId.startsWith(CHANNEL_PREFIX) @@ -63,6 +92,8 @@ data class ReminderChannelPlan( val groupsInUse: List, val staleChannelIds: List, val staleGroupIds: List, + /** Stale channels kept for now, because a notification on them is still showing. */ + val keptChannelIds: List = emptyList(), ) /** @@ -78,6 +109,8 @@ fun planReminderChannels( existingGroupIds: Collection, unnamed: String, description: String, + versions: Map = emptyMap(), + showingChannelIds: Set = emptySet(), ): ReminderChannelPlan { val (local, synced) = calendars.partition { it.isLocal } val groups = buildList { @@ -96,16 +129,16 @@ fun planReminderChannels( ) } } + val existingById = existing.associateBy { it.id } val channels = calendars.map { calendar -> ReminderChannelSpec( - id = reminderChannelId(calendar.id), + id = reminderChannelId(calendar.id, versions[calendar.id] ?: 0), calendarId = calendar.id, name = calendar.displayName.ifBlank { unnamed }, groupId = if (calendar.isLocal) LOCAL_GROUP_ID else accountGroupId(calendar.accountType, calendar.accountName), upFront = calendar.isLocal || calendar.syncsEvents, ) } - val existingById = existing.associateBy { it.id } val wantedChannels = channels.mapTo(HashSet()) { it.id } val wantedGroups = groups.mapTo(HashSet()) { it.id } val toWrite = channels.filter { spec -> @@ -120,13 +153,18 @@ fun planReminderChannels( val usedGroupIds = channels .filter { it.id in existingById || it in toWrite } .mapNotNullTo(HashSet()) { it.groupId } + val (kept, stale) = existingById.keys + .filter { isReminderChannelId(it) && it !in wantedChannels } + .partition { it in showingChannelIds } + val keptGroups = kept.mapNotNullTo(HashSet()) { existingById.getValue(it).groupId } return ReminderChannelPlan( groups = groups, channels = channels, channelsToWrite = toWrite, groupsInUse = groups.filter { it.id in usedGroupIds }, - staleChannelIds = existingById.keys.filter { isReminderChannelId(it) && it !in wantedChannels }, - staleGroupIds = existingGroupIds.filter { isReminderGroupId(it) && it !in wantedGroups }, + staleChannelIds = stale, + staleGroupIds = existingGroupIds.filter { isReminderGroupId(it) && it !in wantedGroups && it !in keptGroups }, + keptChannelIds = kept, ) } @@ -155,12 +193,14 @@ fun reminderChannelStatus( appEnabled: Boolean, channels: Map, blockedGroupIds: Set, + versions: Map = emptyMap(), ): ReminderChannelStatus { - val groupBlocked = calendarIds.filterTo(HashSet()) { channels[reminderChannelId(it)]?.groupId in blockedGroupIds } + fun channel(calendarId: Long) = channels[reminderChannelId(calendarId, versions[calendarId] ?: 0)] + val groupBlocked = calendarIds.filterTo(HashSet()) { channel(it)?.groupId in blockedGroupIds } val blocked = if (!appEnabled) { calendarIds.toSet() } else { - calendarIds.filterTo(HashSet()) { channels[reminderChannelId(it)]?.blocked == true } + groupBlocked + calendarIds.filterTo(HashSet()) { channel(it)?.blocked == true } + groupBlocked } return ReminderChannelStatus( appBlocked = !appEnabled, 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 20ec0453..be7b2a5c 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 @@ -4,14 +4,22 @@ import android.app.Notification import android.app.NotificationChannel import android.app.NotificationChannelGroup import android.app.NotificationManager +import android.app.NotificationManager.IMPORTANCE_DEFAULT +import android.app.NotificationManager.IMPORTANCE_LOW +import android.app.NotificationManager.IMPORTANCE_MIN import android.content.Context +import android.media.AudioAttributes +import android.net.Uri 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.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle import de.jeanlucmakiola.calendula.ui.common.sourceAppLabel +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking import java.util.Locale import javax.inject.Inject import javax.inject.Singleton @@ -23,11 +31,14 @@ import javax.inject.Singleton * * A channel the user has touched keeps their settings; [sync] only creates the * missing ones, renames changed ones, and deletes those whose calendar is gone. + * A sound picked in the app ([setSound], #518) recreates the channel under the + * calendar's next version; the old one goes once nothing shows on it. */ @Singleton class ReminderChannels @Inject constructor( @ApplicationContext private val context: Context, private val calendarDataSource: CalendarDataSource, + private val settingsPrefs: SettingsPrefs, ) { private val manager: NotificationManager get() = context.getSystemService(NotificationManager::class.java) @@ -48,9 +59,14 @@ class ReminderChannels @Inject constructor( val manager = manager val existing = manager.notificationChannels val existingIds = existing.mapTo(HashSet()) { it.id } - if (syncKey(calendars, existingIds) == lastSync && LEGACY_REMINDER_CHANNEL_ID !in existingIds) return + val versions = currentVersions(existingIds).also { knownVersions = it } + if (syncKey(calendars, existingIds, versions) == lastSync && LEGACY_REMINDER_CHANNEL_ID !in existingIds) return val groups = manager.notificationChannelGroups - val plan = plan(calendars, existing, groups.map { it.id }) + val groupIds = groups.map { it.id } + // Active notifications are only read when there is something stale to protect. + val plan = plan(calendars, existing, groupIds, versions).let { draft -> + if (draft.staleChannelIds.isEmpty()) draft else plan(calendars, existing, groupIds, versions, showingChannelIds(draft.staleChannelIds)) + } plan.staleChannelIds.forEach(manager::deleteNotificationChannel) plan.staleGroupIds.forEach(manager::deleteNotificationChannelGroup) val groupNames = groups.associate { it.id to it.name?.toString() } @@ -61,15 +77,41 @@ class ReminderChannels @Inject constructor( ) if (RING_CHANNEL_ID in existingIds) ensureRingChannel() val ids = existingIds - plan.staleChannelIds.toSet() + plan.channelsToWrite.map { it.id } - lastSync = syncKey(calendars, if (retireLegacyChannel()) ids - LEGACY_REMINDER_CHANNEL_ID else ids) + val legacyGone = retireLegacyChannel() + // A kept channel still has to go once its notification does, so don't cache. + lastSync = if (plan.keptChannelIds.isEmpty()) { + syncKey(calendars, if (legacyGone) ids - LEGACY_REMINDER_CHANNEL_ID else ids, versions) + } else { + null + } } - private fun syncKey(calendars: List, channelIds: Set): Any = listOf( + private fun syncKey(calendars: List, channelIds: Set, versions: Map): Any = listOf( calendars.map { listOf(it.id, it.displayName, it.accountName, it.accountType, it.isLocal, it.syncsEvents) }, Locale.getDefault(), channelIds, + versions, ) + /** + * The current versions last resolved under the lock ([sync], [channelFor]). + * Only [recreate], under the same lock, moves a calendar higher and updates + * it, so a hit whose channel still exists is current. + */ + @Volatile + private var knownVersions: Map = emptyMap() + + private fun currentVersions(existingChannelIds: Collection): Map = + currentReminderChannelVersions(existingChannelIds, runBlocking { settingsPrefs.reminderChannelVersions.first() }) + + /** Channels with a notification on screen; on failure all of [candidates] count, so none is deleted. */ + private fun showingChannelIds(candidates: Collection): Set = runCatching { + manager.activeNotifications.mapNotNullTo(HashSet()) { it.notification.channelId } + }.getOrElse { e -> + Log.w(TAG, "Could not read active notifications", e) + candidates.toSet() + } + /** * 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. Should the @@ -133,10 +175,15 @@ class ReminderChannels @Inject constructor( } private fun calendarChannelFor(calendarId: Long): String? { - val id = reminderChannelId(calendarId) val manager = manager - if (manager.getNotificationChannel(id) != null) return id + knownVersions[calendarId]?.let { version -> + val known = reminderChannelId(calendarId, version) + if (manager.getNotificationChannel(known) != null) return known + } val existing = manager.notificationChannels + val versions = currentVersions(existing.map { it.id }).also { knownVersions = it } + val id = reminderChannelId(calendarId, versions[calendarId] ?: 0) + if (existing.any { it.id == id }) return id val calendars = try { calendarDataSource.calendars() } catch (e: Exception) { @@ -148,7 +195,7 @@ class ReminderChannels @Inject constructor( write(emptyList(), listOf(fallback), existing) return id } - val plan = plan(calendars, existing, emptyList()) + val plan = plan(calendars, existing, emptyList(), versions) val spec = plan.channels.firstOrNull { it.calendarId == calendarId } ?: return null try { val knownGroups = manager.notificationChannelGroups.mapTo(HashSet()) { it.id } @@ -164,27 +211,132 @@ class ReminderChannels @Inject constructor( return id } + /** + * Run [block] with [calendarId]'s channel held: no sound pick or sync can + * move or retire it until [block] returns. Null, without running [block], + * when the calendar is gone or its channel can't be made; [block]'s own + * failures propagate. + */ + @Synchronized + fun withChannel(calendarId: Long, block: (String) -> T): T? { + val channelId = try { + channelFor(calendarId) + } catch (e: Exception) { + Log.w(TAG, "No channel for calendar $calendarId", e) + null + } + return channelId?.let(block) + } + /** What the system currently lets through for [calendarIds]' reminders (#145). */ fun status(calendarIds: Collection): ReminderChannelStatus { val manager = manager val appEnabled = manager.areNotificationsEnabled() - val channels = manager.notificationChannels.associate { + val existing = manager.notificationChannels + val channels = existing.associate { it.id to ReminderChannelState(it.importance == NotificationManager.IMPORTANCE_NONE, it.group) } val blockedGroups = manager.notificationChannelGroups.filter { it.isBlocked }.mapTo(HashSet()) { it.id } - return reminderChannelStatus(calendarIds, appEnabled, channels, blockedGroups) + return reminderChannelStatus(calendarIds, appEnabled, channels, blockedGroups, currentVersions(channels.keys)) + } + + /** A "Silent" (low) channel keeps its sound but never plays it. */ + private fun NotificationChannel.audibleSound(): Uri? = + sound.takeUnless { importance in IMPORTANCE_MIN..IMPORTANCE_LOW } + + /** + * The sound each of [calendarIds]' channels plays; null is silent. A + * calendar whose channel doesn't exist yet is left out. + */ + fun sounds(calendarIds: Collection): Map { + val byId = manager.notificationChannels.associateBy { it.id } + val versions = currentVersions(byId.keys) + return calendarIds.mapNotNull { id -> + byId[reminderChannelId(id, versions[id] ?: 0)]?.let { id to it.audibleSound() } + }.toMap() + } + + /** + * Give [calendarIds]' reminders [sound] (null = silent). A channel's sound is + * fixed once created, so each moves to a new channel version carrying over + * everything else, and the old one retires in the sync that follows (#518). Calendars without a + * channel are skipped unless [createMissing]. Returns whether every move + * went through. + */ + suspend fun setSound(calendarIds: Collection, sound: Uri?, createMissing: Boolean): Boolean { + if (createMissing) calendarIds.forEach(::channelFor) + val existingIds = manager.notificationChannels.mapTo(HashSet()) { it.id } + val current = currentVersions(existingIds) + val floors = calendarIds + .filter { reminderChannelId(it, current[it] ?: 0) in existingIds } + .associateWith { (current[it] ?: 0) + 1 } + if (floors.isEmpty()) return false + val applied = recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound) + // Retire the old versions now, or each calendar shows twice in system settings until the next scan. + try { + sync() + } catch (e: RuntimeException) { + Log.w(TAG, "Old channel versions left to the next sync", e) + } + return applied + } + + /** + * Create each calendar's [versions] from its current channel. The old one is + * left to the next [sync], which retires it once nothing shows on it. + */ + @Synchronized + private fun recreate(versions: Map, sound: Uri?): Boolean { + val manager = manager + val byId = manager.notificationChannels.associateBy { it.id } + val current = currentReminderChannelVersions(byId.keys, emptyMap()) + var allApplied = true + versions.forEach { (calendarId, version) -> + val from = current[calendarId]?.takeIf { it < version } + val old = from?.let { byId[reminderChannelId(calendarId, it)] } + if (old == null) { + allApplied = false + return@forEach + } + try { + // Picking a sound asks for one, which a "Silent" (low) channel would never play. + val importance = if (sound != null && old.importance in IMPORTANCE_MIN..IMPORTANCE_LOW) { + IMPORTANCE_DEFAULT + } else { + old.importance + } + manager.createNotificationChannel( + NotificationChannel(reminderChannelId(calendarId, version), old.name, importance).apply { + description = old.description + old.group?.let { group = it } + inheritFrom(old) + setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES) + }, + ) + knownVersions = knownVersions + (calendarId to version) + } catch (e: RuntimeException) { + Log.w(TAG, "Could not move calendar $calendarId to a new sound", e) + allApplied = false + } + } + lastSync = null + return allApplied } private fun plan( calendars: List, existing: List, existingGroupIds: List, + versions: Map, + showingChannelIds: Set = emptySet(), ): ReminderChannelPlan = planReminderChannels( calendars = calendars, existing = existing.map { ExistingReminderChannel(it.id, it.name.toString(), it.description, it.group) }, existingGroupIds = existingGroupIds, unnamed = context.getString(R.string.calendar_unnamed), description = context.getString(R.string.reminder_channel_description), + versions = versions, + showingChannelIds = showingChannelIds, ) private fun write( @@ -218,8 +370,10 @@ class ReminderChannels @Inject constructor( } /** - * Carry the old single channel's sound, vibration, lights and badge over to - * a new per-calendar one (the system resets lock-screen visibility itself), so an upgrade keeps how reminders sounded. + * Carry a channel's sound, vibration, lights and badge over to a new one: the + * legacy channel to a per-calendar one on upgrade, or a calendar's channel to + * its next version (#518). Lock-screen visibility and a DND override can't + * follow: the system resets both on channels an app creates. */ private fun NotificationChannel.inheritFrom(template: NotificationChannel) { setSound(template.sound, template.audioAttributes) @@ -241,12 +395,7 @@ class ReminderChannels @Inject constructor( private fun retireLegacyChannel(): Boolean { val manager = manager if (manager.getNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) == null) return true - val showing = runCatching { - manager.activeNotifications.any { it.notification.channelId == LEGACY_REMINDER_CHANNEL_ID } - }.getOrElse { e -> - Log.w(TAG, "Could not read active notifications", e) - true - } + val showing = LEGACY_REMINDER_CHANNEL_ID in showingChannelIds(listOf(LEGACY_REMINDER_CHANNEL_ID)) if (!showing) manager.deleteNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) return !showing } @@ -260,6 +409,8 @@ class ReminderChannels @Inject constructor( private companion object { const val TAG = "ReminderChannels" + + val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = Notification.AUDIO_ATTRIBUTES_DEFAULT } } 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 5d6582e6..8c18a0d4 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 @@ -85,32 +85,32 @@ class ReminderNotifier @Inject constructor( } // Rung already and handed back to the shade: a catch-up post leaves it there. if (style == ReminderAlertStyle.FullScreenRing && (isShowing(alert) || alerts.isPending(alert))) return - val channelId = channelFor(alert, style) - // The ring channel could not be made: still full-screen, sounding once. - ?: if (style == ReminderAlertStyle.FullScreenRing) { - style = ReminderAlertStyle.FullScreen - channelFor(alert, style) ?: return - } else { - return - } val title = displayTitle(alert) val text = contentText(alert) if (style == ReminderAlertStyle.FullScreenRing) { - if (ReminderRingService.start(context, alerts, alert, build(alert, channelId, title, text, style, quiet = false))) { + val ringChannel = channelFor(alert, style) + if (ringChannel != null && + ReminderRingService.start(context, alerts, alert, build(alert, ringChannel, title, text, style, quiet = false)) + ) { // An earlier reminder for this occurrence gives way to the ring. NotificationManagerCompat.from(context).cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID) cancelLegacy(alert) return } - // Android refused the ring: still full-screen, sounding once on the calendar's channel. + // No ring channel, or Android refused the ring: still full-screen, sounding once on the calendar's channel. + if (ringChannel != null) stopRing(RingMatch.Occurrence(alert.occurrenceKey)) + style = ReminderAlertStyle.FullScreen + } else if (ring) { + // A fresh reminder replaces a ring for its occurrence from before the style changed. stopRing(RingMatch.Occurrence(alert.occurrenceKey)) - val fallback = channelFor(alert, ReminderAlertStyle.FullScreen) ?: return - notify(alert, build(alert, fallback, title, text, ReminderAlertStyle.FullScreen, quiet = false)) - return } - // A fresh reminder replaces a ring for its occurrence from before the style changed. - if (ring) stopRing(RingMatch.Occurrence(alert.occurrenceKey)) - notify(alert, build(alert, channelId, title, text, style, quiet)) + // Under the channel lock, so a sound picked meanwhile (#518) can't move it mid-post. + val posted = channels.withChannel(alert.calendarId) { channelId -> + notify(alert, build(alert, channelId, title, text, style, quiet)) + } + if (posted == null) { + Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: no channel for calendar ${alert.calendarId}") + } } /** Whether a ring for [alert] should go on, now that settings may have changed since it started. */ diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt index 68b1914f..827a91f0 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt @@ -13,12 +13,11 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.LifecycleResumeEffect @@ -38,8 +37,8 @@ import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle import de.jeanlucmakiola.calendula.ui.common.groupByAccount import de.jeanlucmakiola.calendula.ui.common.orUnnamed -import de.jeanlucmakiola.floret.android.openNotificationSettings import de.jeanlucmakiola.floret.components.CollapsingScaffold +import de.jeanlucmakiola.floret.android.openNotificationSettings import de.jeanlucmakiola.floret.components.ExpandIcon import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.GroupedRow @@ -54,7 +53,6 @@ import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.floret.reminders.reminderOverrideFor import de.jeanlucmakiola.floret.ring.canUseFullScreenIntent import de.jeanlucmakiola.floret.ring.openFullScreenIntentSettings -import kotlinx.coroutines.launch /** * Per-calendar notifications and reminder overrides (#145, #272), reached from @@ -69,16 +67,16 @@ internal fun CalendarRemindersScreen( onOpenSpecialDates: () -> Unit, visible: Boolean = true, ) { - val context = LocalContext.current - val scope = rememberCoroutineScope() var expandedCalendars by rememberSaveable { mutableStateOf(emptyList()) } var overrideDialog by remember { mutableStateOf(null) } var alertStylePicker by remember { mutableStateOf(null) } var alertSoundPicker by remember { mutableStateOf(null) } val canFullScreen = rememberCanUseFullScreenIntent() + val context = LocalContext.current var fixedOverrideFor by remember { mutableStateOf(null) } val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle() val calendarIds = state.reminderCalendars.map { it.id } + val soundPicker = rememberReminderSoundPicker(viewModel, calendarIds) LifecycleResumeEffect(calendarIds) { viewModel.refreshChannelStatus(calendarIds) onPauseOrDispose { } @@ -121,11 +119,9 @@ internal fun CalendarRemindersScreen( } }, onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) }, - onOpenSound = { - scope.launch { - context.openNotificationSettings(viewModel.soundSettingsChannel(calendar.id)) - } - }, + soundLabel = soundPicker.loadedSounds?.let { soundLabel(it[calendar.id]) }, + onPickSound = { soundPicker.pick(calendar.id) }, + onOpenSettings = { soundPicker.openCalendarSettings(calendar.id) }, onOpenRingSettings = { context.openNotificationSettings(RING_CHANNEL_ID) }, onEditAlertStyle = { alertStylePicker = calendar.id }, onEditAlertSound = { alertSoundPicker = calendar.id }, @@ -245,7 +241,9 @@ private fun CalendarReminderEntry( heldBack: FullScreenHeldBack, onToggleExpand: () -> Unit, onSetNotifying: (Boolean) -> Unit, - onOpenSound: () -> Unit, + soundLabel: String?, + onPickSound: () -> Unit, + onOpenSettings: () -> Unit, onOpenRingSettings: () -> Unit, onEditAlertStyle: () -> Unit, onEditAlertSound: () -> Unit, @@ -299,16 +297,22 @@ private fun CalendarReminderEntry( ) GroupedRow( title = stringResource(R.string.settings_notification_sound), - summary = when { - blocked -> stringResource(R.string.settings_notifications_blocked_hint) - alertStyle == ReminderAlertStyle.FullScreenRing -> - stringResource(R.string.settings_calendar_notification_sound_ring_hint) - else -> stringResource(R.string.settings_calendar_notification_sound_hint) + summary = soundLabel, + position = Position.Middle, + container = nested, + onClick = onPickSound, + ) + GroupedRow( + title = stringResource(R.string.settings_notification_more), + summary = if (blocked) { + stringResource(R.string.settings_notifications_blocked_hint) + } else { + stringResource(R.string.settings_calendar_notification_sound_hint) }, position = Position.Middle, container = nested, trailing = { ExternalLinkIcon() }, - onClick = onOpenSound, + onClick = onOpenSettings, ) val lastAlertRow = !(managed || takesOverrides || digestOn) GroupedRow( 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 dfc2f4f5..755fb51f 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 @@ -10,6 +10,8 @@ import android.content.Intent import android.os.Build import android.os.PowerManager import android.provider.Settings +import android.provider.Settings.System.DEFAULT_NOTIFICATION_URI +import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Arrangement @@ -26,10 +28,13 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -52,7 +57,9 @@ import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker import de.jeanlucmakiola.calendula.ui.common.TimePickerAlert import de.jeanlucmakiola.calendula.ui.common.durationLabel import de.jeanlucmakiola.floret.android.hasPermission +import de.jeanlucmakiola.floret.android.notificationSoundPickerIntent import de.jeanlucmakiola.floret.android.openNotificationSettings +import de.jeanlucmakiola.floret.android.pickedSound import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSwitchRow @@ -110,6 +117,10 @@ internal fun NotificationsScreen( viewModel.refreshChannelStatus(calendarIds) onPauseOrDispose { } } + val soundPicker = rememberReminderSoundPicker(viewModel, calendarIds) + val openAppSettings = soundPicker.openAppSettings + val loadedSounds = soundPicker.loadedSounds + val pickSound = soundPicker.pick CollapsingScaffold( title = stringResource(R.string.settings_section_notifications), @@ -121,12 +132,7 @@ internal fun NotificationsScreen( NotificationCategoryHint( onOpen = { viewModel.dismissNotificationCategoryHint() - scope.launch { - viewModel.syncReminderChannels() - // The summary's category too, so it is on the list to check. - if (state.dailyDigest.enabled) viewModel.digestChannel() - context.openNotificationSettings() - } + openAppSettings() }, onDismiss = viewModel::dismissNotificationCategoryHint, ) @@ -139,8 +145,16 @@ internal fun NotificationsScreen( summary = stringResource(R.string.settings_reminders_hint), position = Position.Top, ) + if (calendarIds.isNotEmpty()) { + GroupedRow( + title = stringResource(R.string.settings_notification_sound), + summary = loadedSounds?.let { globalSoundLabel(it, calendarIds) }, + position = Position.Middle, + onClick = { pickSound(ALL_CALENDARS) }, + ) + } GroupedRow( - title = stringResource(R.string.settings_notification_sound), + title = stringResource(R.string.settings_notification_more), summary = if (channelStatus.appBlocked) { stringResource(R.string.settings_notifications_blocked_hint) } else { @@ -148,12 +162,7 @@ internal fun NotificationsScreen( }, position = Position.Middle, trailing = { ExternalLinkIcon() }, - onClick = { - scope.launch { - viewModel.syncReminderChannels() - context.openNotificationSettings() - } - }, + onClick = openAppSettings, ) GroupedRow( title = stringResource(R.string.settings_default_reminder), @@ -375,6 +384,43 @@ private fun DailyDigestRows( } } +/** [soundTarget] meaning every calendar at once. */ +internal const val ALL_CALENDARS = Long.MIN_VALUE + +/** What the calendars that have a channel share, sound-wise. */ +private sealed interface SharedSound { + data object None : SharedSound + data object Mixed : SharedSound + data class Same(val sound: ReminderSound) : SharedSound +} + +private fun sharedSound(sounds: Map, calendarIds: List): SharedSound { + val distinct = calendarIds.mapNotNull { sounds[it] }.distinctBy { it.uri } + return when (distinct.size) { + 0 -> SharedSound.None + 1 -> SharedSound.Same(distinct.single()) + else -> SharedSound.Mixed + } +} + +@Composable +internal fun soundLabel(sound: ReminderSound?): String = when { + sound == null -> stringResource(R.string.settings_notification_sound_default) + sound.uri == null -> stringResource(R.string.settings_notification_sound_silent) + sound.uri == DEFAULT_NOTIFICATION_URI -> sound.title + ?.let { stringResource(R.string.settings_notification_sound_default_named, it) } + ?: stringResource(R.string.settings_notification_sound_default) + else -> sound.title ?: stringResource(R.string.settings_notification_sound_custom) +} + +@Composable +private fun globalSoundLabel(sounds: Map, calendarIds: List): String = + when (val shared = sharedSound(sounds, calendarIds)) { + SharedSound.None -> soundLabel(null) + SharedSound.Mixed -> stringResource(R.string.settings_notification_sound_mixed) + is SharedSound.Same -> soundLabel(shared.sound) + } + /** Samsung's One UI can start a new notification category switched off (#145). */ private val IS_SAMSUNG = Build.MANUFACTURER.equals("samsung", ignoreCase = true) @@ -462,3 +508,68 @@ private fun openBatteryOptimizationSettings(context: Context) { } } } + +/** The reminder-sound picker (#518) shared by Notifications (all calendars) and the per-calendar page. */ +internal class ReminderSoundPicker( + val loadedSounds: Map?, + val pick: (Long) -> Unit, + val openAppSettings: () -> Unit, + val openCalendarSettings: (Long) -> Unit, +) + +@Composable +internal fun rememberReminderSoundPicker(viewModel: SettingsViewModel, calendarIds: List): ReminderSoundPicker { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val openCalendarSettings: (Long) -> Unit = { calendarId -> + scope.launch { context.openNotificationSettings(viewModel.soundSettingsChannel(calendarId)) } + } + val openAppSettings: () -> Unit = { + scope.launch { + viewModel.syncReminderChannels() + context.openNotificationSettings() + } + } + val loadedSounds by viewModel.channelSounds.collectAsStateWithLifecycle() + val sounds = loadedSounds.orEmpty() + val soundFailedMessage = stringResource(R.string.settings_notification_sound_failed) + val soundUnreadableMessage = stringResource(R.string.settings_notification_sound_unreadable) + LaunchedEffect(Unit) { + viewModel.soundFailed.collect { failure -> + val message = if (failure == SoundFailure.Unreadable) soundUnreadableMessage else soundFailedMessage + Toast.makeText(context, message, Toast.LENGTH_LONG).show() + } + } + // ALL_CALENDARS, a calendar id, or null when no pick is pending. + var soundTarget by rememberSaveable { mutableStateOf(null) } + val soundPicker = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + val target = soundTarget + soundTarget = null + val picked = pickedSound(result.resultCode, result.data) ?: return@rememberLauncherForActivityResult + when (target) { + null -> Unit + ALL_CALENDARS -> viewModel.setReminderSoundForAll(picked.uri) + else -> viewModel.setReminderSound(target, picked.uri) + } + } + val pickSoundTitle = stringResource(R.string.settings_notification_sound) + val pickSound: (Long) -> Unit = pick@{ target -> + if (soundTarget != null) return@pick + val current = if (target == ALL_CALENDARS) { + (sharedSound(sounds, calendarIds) as? SharedSound.Same)?.sound + } else { + sounds[target] + } + soundTarget = target + try { + // A missing or mixed sound preselects Default; a silent one, Silent. + val preselect = if (current == null) DEFAULT_NOTIFICATION_URI else current.uri + soundPicker.launch(notificationSoundPickerIntent(preselect, pickSoundTitle)) + } catch (e: RuntimeException) { + // No picker, or one that refuses to start: the system screen still has the sound. + soundTarget = null + if (target == ALL_CALENDARS) openAppSettings() else openCalendarSettings(target) + } + } + return ReminderSoundPicker(loadedSounds, pickSound, openAppSettings, openCalendarSettings) +} 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 d2c72557..4c129ea0 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 @@ -3,6 +3,7 @@ package de.jeanlucmakiola.calendula.ui.settings import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder +import android.net.Uri import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs @@ -147,3 +148,9 @@ data class SpecialDatesUiState( /** Epoch millis of the last sync, or 0 if it has never run. */ val lastRun: Long = 0L, ) + +/** A reminder channel's sound: null [uri] is silent; [title] is null when it can't be resolved. */ +data class ReminderSound(val uri: Uri?, val title: String?) + +/** Why a picked reminder sound wasn't applied. */ +enum class SoundFailure { NotApplied, Unreadable } 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 8bf6a149..63afa1cc 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 @@ -3,6 +3,7 @@ package de.jeanlucmakiola.calendula.ui.settings import android.content.Context import android.net.Uri import android.os.Build +import android.provider.Settings import android.util.Log import androidx.datastore.preferences.core.Preferences import androidx.lifecycle.ViewModel @@ -17,6 +18,7 @@ import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncEngine import de.jeanlucmakiola.calendula.data.contacts.resolveTitleTemplate import de.jeanlucmakiola.calendula.data.fonts.CustomFontStore +import de.jeanlucmakiola.floret.android.ringtoneTitle import de.jeanlucmakiola.floret.android.stateWhileSubscribed import de.jeanlucmakiola.floret.di.IoDispatcher import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride @@ -61,6 +63,9 @@ import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow @@ -69,6 +74,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -421,11 +427,79 @@ class SettingsViewModel @Inject constructor( private var channelStatusJob: Job? = null + private val _channelSounds = MutableStateFlow?>(null) + + /** Each calendar's reminder sound (#518), null until first read; a calendar without a channel yet is absent. */ + val channelSounds: StateFlow?> = _channelSounds.asStateFlow() + + private val _soundFailed = Channel(Channel.CONFLATED) + + /** Emits when a picked sound couldn't be applied; kept until the screen collects it. */ + val soundFailed: Flow = _soundFailed.receiveAsFlow() + + private val soundTitles = mutableMapOf() + fun refreshChannelStatus(calendarIds: Collection) { channelStatusJob?.cancel() channelStatusJob = viewModelScope.launch { onChannels { status(calendarIds) }?.let { _channelStatus.value = it } _digestBlocked.value = withContext(io) { runCatching { digestNotifier.isChannelOff() }.getOrDefault(false) } + val sounds = onChannels { sounds(calendarIds) } ?: return@launch + _channelSounds.value = withContext(io) { + sounds.mapValues { (_, uri) -> + ReminderSound(uri, uri?.let(::soundTitle)) + } + } + } + } + + /** A sound's title, cached unless it is a "default" alias whose target can change. */ + private fun soundTitle(uri: Uri): String? { + if (uri.authority == Settings.AUTHORITY) return appContext.ringtoneTitle(uri) + return synchronized(soundTitles) { soundTitles.getOrPut(uri) { appContext.ringtoneTitle(uri) } } + } + + /** Give [calendarId]'s reminders [sound] (null = silent), on a fresh channel (#518). */ + fun setReminderSound(calendarId: Long, sound: Uri?) = applySound(sound) { + setSound(listOf(calendarId), sound, createMissing = true) + } + + /** + * Give every switched-on calendar's reminders [sound]. Reads the calendars + * itself, so a pick returning after process death still finds them; those + * that only get a channel when something posts are left alone. + */ + fun setReminderSoundForAll(sound: Uri?) = applySound(sound) { + try { + sync() + } catch (e: Exception) { + Log.w("SettingsViewModel", "Channel sync before a sound pick failed", e) + } + val ids = visibleCalendars.first().map { it.id } + ids.isNotEmpty() && setSound(ids, sound, createMissing = false) + } + + private fun canRead(uri: Uri): Boolean = uri.authority == Settings.AUTHORITY || + runCatching { appContext.contentResolver.openAssetFileDescriptor(uri, "r")?.close() != null }.getOrDefault(false) + + /** Runs to completion even if the screen closes meanwhile, so a pick is never half-applied. */ + private fun applySound(sound: Uri?, block: suspend ReminderChannels.() -> Boolean) { + viewModelScope.launch { + val failure = withContext(io + NonCancellable) { + try { + // The system plays the sound but checks that Calendula could read it. + when { + sound != null && !canRead(sound) -> SoundFailure.Unreadable + reminderChannels.block() -> null + else -> SoundFailure.NotApplied + } + } catch (e: Exception) { + Log.w("SettingsViewModel", "Could not set the reminder sound", e) + SoundFailure.NotApplied + } + } + failure?.let(_soundFailed::trySend) + refreshChannelStatus(visibleCalendars.first().map { it.id }) } } @@ -450,13 +524,17 @@ class SettingsViewModel @Inject constructor( channelId.takeUnless { status.appBlocked || calendarId in status.groupBlockedCalendarIds } } - /** Create the per-calendar channels before showing the app's channel list, even with reminders off. */ + /** + * Create the per-calendar channels before showing the app's channel list, even with reminders off, + * plus the ring and daily summary ones in use, so they are on the list to check. + */ suspend fun syncReminderChannels() { val ringing = state.value.reminderAlertStyles.containsValue(ReminderAlertStyle.FullScreenRing) onChannels { sync() if (ringing) ensureRingChannel() } + if (state.value.dailyDigest.enabled) digestChannel() } private suspend fun onChannels(block: ReminderChannels.() -> T): T? = withContext(io) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 36aa0550..3bc81fa0 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -740,12 +740,21 @@ Notifications off Reminders off Notification sound - Sound, vibration and pop-ups for each calendar, in system settings + Silent + Default + + Default (%1$s) + Custom sound + Couldn\'t change the notification sound + Calendula can\'t play this sound. Pick another one. + Differs per calendar + More notification settings + Vibration, pop-ups and more for each calendar, in system settings Blocked in system settings Blocked in system settings — tap to allow On Samsung phones, new notification categories can start switched off. If a calendar\'s reminders don\'t arrive, check that its category is on. Open settings - Sound, vibration and pop-ups for this calendar, in system settings + Vibration, pop-ups and more for this calendar, in system settings Alert style Notification A notification that pops up and waits in the shade @@ -756,7 +765,6 @@ This calendar\'s notification sound, once Ring until dismissed Your alarm sound and vibration, like an alarm, also in Do Not Disturb when alarms may sound - Ringing reminders use your alarm sound. This sets the sound of the ones handed back to the shade. Full-screen alerts held back Blocked in system settings, so this calendar\'s reminders only sound once — tap to allow Allow full-screen alerts diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt index f113bb92..0a3aec94 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt @@ -630,6 +630,17 @@ class SettingsPrefsTest { assertThat(prefs.reminderAlertStyles.first()).containsExactly(7L, ReminderAlertStyle.FullScreenRing) } + @Test + fun `reminder channel versions only grow`( + @TempDir tempDir: Path, + ) = runTest { + val prefs = testSettings(tempDir) + assertThat(prefs.reminderChannelVersions.first()).isEmpty() + assertThat(prefs.reserveReminderChannelVersions(mapOf(7L to 1))).containsExactly(7L, 1) + assertThat(prefs.reserveReminderChannelVersions(mapOf(7L to 1, 9L to 5))).containsExactly(7L, 2, 9L, 5) + assertThat(prefs.reminderChannelVersions.first()).containsExactly(7L, 2, 9L, 5) + } + @Test fun `garbage per-calendar duration entries are dropped, the rest survive`( @TempDir tempDir: Path, 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 af4bb15e..e1f3ad93 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 @@ -153,6 +153,55 @@ class ReminderChannelPlanTest { assertThat(reminderChannelStatus(listOf(1L), appEnabled = true, emptyMap(), emptySet()).ringBlocked).isFalse() } + @Test + fun `channel ids round-trip with versions`() { + assertThat(parseReminderChannelId(reminderChannelId(7))).isEqualTo(7L to 0) + assertThat(parseReminderChannelId(reminderChannelId(7, 3))).isEqualTo(7L to 3) + assertThat(parseReminderChannelId("reminders.calendar.7.v0")).isNull() + assertThat(parseReminderChannelId("reminders.calendar.x")).isNull() + assertThat(parseReminderChannelId(LEGACY_REMINDER_CHANNEL_ID)).isNull() + } + + @Test + fun `a version bump retires the old channel unless it is showing`() { + val existing = listOf( + ExistingReminderChannel(reminderChannelId(1), "Cal 1", DESC, "g"), + ExistingReminderChannel(reminderChannelId(2), "Cal 2", DESC, "g"), + ) + val plan = planReminderChannels( + calendars = listOf(calendar(1, "a", "com.google"), calendar(2, "a", "com.google")), + existing = existing, + existingGroupIds = emptyList(), + unnamed = "Unnamed", + description = DESC, + versions = mapOf(1L to 2, 2L to 1), + showingChannelIds = setOf(reminderChannelId(2)), + ) + assertThat(plan.channels.map { it.id }).containsExactly(reminderChannelId(1, 2), reminderChannelId(2, 1)) + assertThat(plan.staleChannelIds).containsExactly(reminderChannelId(1)) + assertThat(plan.keptChannelIds).containsExactly(reminderChannelId(2)) + } + + @Test + fun `the current version is the highest that exists, else the high-water mark`() { + val versions = currentReminderChannelVersions( + existingChannelIds = listOf(reminderChannelId(1), reminderChannelId(1, 2), reminderChannelId(3), "backup"), + highWater = mapOf(1L to 5, 2L to 4), + ) + // Calendar 1 reserved v5 but never wrote it, so v2 stays current. + assertThat(versions).containsExactly(1L, 2, 2L, 4, 3L, 0) + } + + @Test + fun `status reads the current channel version`() { + val channels = mapOf( + reminderChannelId(1) to ReminderChannelState(blocked = true, groupId = null), + reminderChannelId(1, 2) to ReminderChannelState(blocked = false, groupId = null), + ) + val status = reminderChannelStatus(listOf(1L), true, channels, emptySet(), versions = mapOf(1L to 2)) + assertThat(status.blockedCalendarIds).isEmpty() + } + private companion object { const val DESC = "Reminders" } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 6e419915..efa2b1df 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -402,9 +402,19 @@ 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 +nothing showing still sits on it. Settings → Notifications deep-links into the +system's channel screens for everything but the sound (#340). A sound picked in +the app (#518) can't be set on an existing channel, so +`ReminderChannels.setSound` recreates it under a new version +(`reminders.calendar..v`), copying everything else from the old one. The +current version is simply the highest channel that exists, so the new one only +takes over once written; `SettingsPrefs.reminderChannelVersions` is just a +high-water mark that keeps ids from being reused (a re-used id would bring back +the deleted channel's settings). `setSound` leaves the old version to the sync, +which treats older versions as stale and keeps one while a notification still +shows on it; `ReminderNotifier.post` resolves and posts under the channel lock +(`withChannel`), so a pick never moves a channel mid-post. +Separate from the channels, `SettingsPrefs.mutedReminderCalendarIds` is the in-app per-calendar off switch (#272): the scan plans nothing for those calendars (so they arm no wake-ups; toggling it re-scans), and `ReminderNotifier.post` checks it again for snoozes. The settings screen re-reads `ReminderChannels.status` on every