feat(#518): pick the reminder sound in the app via versioned channels

This commit is contained in:
makiolaj committed 2026-11-14 03:48:53 +01:00
1 parent 31ba82a295
commit 6b108fb585
11 files changed
+355 -38

No files matched your search

@@ -168,6 +168,7 @@ class SettingsPrefs @Inject constructor(
val remindersEnabled: Flow<Boolean> = prefs.flow(SettingsKeys.remindersEnabled)
val mutedReminderCalendarIds: Flow<Set<Long>> = prefs.flow(SettingsKeys.mutedReminderCalendarIds)
val notificationCategoryHintDismissed: Flow<Boolean> = prefs.flow(SettingsKeys.notificationCategoryHintDismissed)
val reminderChannelVersions: Flow<Map<Long, Int>> = prefs.flow(SettingsKeys.reminderChannelVersions)
val allowColorOnUnsupportedCalendars: Flow<Boolean> =
prefs.flow(SettingsKeys.allowColorOnUnsupportedCalendars)
val defaultReminderMinutes: Flow<List<Int>> = prefs.flow(SettingsKeys.defaultReminderMinutes)
@@ -275,6 +276,20 @@ class SettingsPrefs @Inject constructor(
suspend fun setRemindersEnabled(enabled: Boolean) = prefs.set(SettingsKeys.remindersEnabled, enabled)
/**
* Move [calendarId]'s reminder channel to a new version, at least [atLeast],
* and return it. Versions only grow: the system would restore a deleted
* channel's old settings if its id came back (#518).
*/
suspend fun bumpReminderChannelVersion(calendarId: Long, atLeast: Int): Int {
var next = 0
prefs.update(SettingsKeys.reminderChannelVersions) { current ->
next = maxOf((current[calendarId] ?: 0) + 1, atLeast)
current + (calendarId to next)
}
return next
}
suspend fun dismissNotificationCategoryHint() = prefs.set(SettingsKeys.notificationCategoryHintDismissed, true)
suspend fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) {
@@ -614,6 +629,14 @@ object SettingsKeys {
*/
val notificationCategoryHintDismissed: Pref<Boolean> = booleanPref("notification_category_hint_dismissed", false)
/**
* Each calendar's reminder channel version (#518): a sound picked in the app
* recreates the channel under the next one. Absent = 0, the unversioned id.
* Serialised as `id=version;id=version`.
*/
val reminderChannelVersions: Pref<Map<Long, Int>> =
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
@@ -997,6 +1020,18 @@ private fun parseDurationOverrides(stored: String?): Map<Long, Int> =
calendarId to minutes
}.toMap()
private fun parseChannelVersions(stored: String?): Map<Long, Int> =
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<Long, Int>.toStoredVersions(): String? =
if (isEmpty()) null else entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, v) -> "$id$KEY_VALUE_SEP$v" }
private fun Map<Long, Int>.toStoredDurations(): String =
entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, minutes) ->
"$id$KEY_VALUE_SEP$minutes"
@@ -10,8 +10,25 @@ 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<Long, Int>? {
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
}
/** Whether [channelId] is one of the per-calendar reminder channels. */
fun isReminderChannelId(channelId: String): Boolean = channelId.startsWith(CHANNEL_PREFIX)
@@ -43,6 +60,12 @@ data class ReminderChannelSpec(
* fires, so its channel only appears once something posts on it.
*/
val upFront: Boolean = true,
/**
* An older version of this calendar's channel to copy behaviour from when
* this one is missing, so a version bump that never got written loses no
* settings.
*/
val templateId: String? = null,
)
/** What a channel already looks like in the system, as far as the plan compares it. */
@@ -60,6 +83,8 @@ data class ReminderChannelPlan(
val groupsInUse: List<ReminderChannelGroupSpec>,
val staleChannelIds: List<String>,
val staleGroupIds: List<String>,
/** Stale channels kept for now, because a notification on them is still showing. */
val keptChannelIds: List<String> = emptyList(),
)
/**
@@ -75,6 +100,8 @@ fun planReminderChannels(
existingGroupIds: Collection<String>,
unnamed: String,
description: String,
versions: Map<Long, Int> = emptyMap(),
showingChannelIds: Set<String> = emptySet(),
): ReminderChannelPlan {
val (local, synced) = calendars.partition { it.isLocal }
val groups = buildList {
@@ -93,16 +120,24 @@ fun planReminderChannels(
)
}
}
val existingById = existing.associateBy { it.id }
val versionsByCalendar = existing.mapNotNull { parseReminderChannelId(it.id) }.groupBy({ it.first }, { it.second })
val channels = calendars.map { calendar ->
val version = versions[calendar.id] ?: 0
val id = reminderChannelId(calendar.id, version)
ReminderChannelSpec(
id = reminderChannelId(calendar.id),
id = id,
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,
templateId = versionsByCalendar[calendar.id]
?.filter { it != version }
?.maxOrNull()
?.let { reminderChannelId(calendar.id, it) }
?.takeIf { id !in existingById },
)
}
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 ->
@@ -117,13 +152,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,
)
}
@@ -150,12 +190,14 @@ fun reminderChannelStatus(
appEnabled: Boolean,
channels: Map<String, ReminderChannelState>,
blockedGroupIds: Set<String>,
versions: Map<Long, Int> = 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, blockedCalendarIds = blocked, groupBlockedCalendarIds = groupBlocked)
}
@@ -4,12 +4,17 @@ import android.app.NotificationChannel
import android.app.NotificationChannelGroup
import android.app.NotificationManager
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.ui.common.sourceAppLabel
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import java.util.Locale
import javax.inject.Inject
import javax.inject.Singleton
@@ -21,11 +26,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)
@@ -46,9 +54,10 @@ 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 = versions()
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 plan = plan(calendars, existing, groups.map { it.id }, versions, showingChannelIds())
plan.staleChannelIds.forEach(manager::deleteNotificationChannel)
plan.staleGroupIds.forEach(manager::deleteNotificationChannelGroup)
val groupNames = groups.associate { it.id to it.name?.toString() }
@@ -58,15 +67,32 @@ class ReminderChannels @Inject constructor(
existing = existing,
)
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<CalendarSource>, channelIds: Set<String>): Any = listOf(
private fun syncKey(calendars: List<CalendarSource>, channelIds: Set<String>, versions: Map<Long, Int>): Any = listOf(
calendars.map { listOf(it.id, it.displayName, it.accountName, it.accountType, it.isLocal, it.syncsEvents) },
Locale.getDefault(),
channelIds,
versions,
)
private fun versions(): Map<Long, Int> = runBlocking { settingsPrefs.reminderChannelVersions.first() }
/** Channels with a notification on screen; on failure every channel counts, so none is deleted. */
private fun showingChannelIds(): Set<String> = runCatching {
manager.activeNotifications.mapNotNullTo(HashSet()) { it.notification.channelId }
}.getOrElse { e ->
Log.w(TAG, "Could not read active notifications", e)
manager.notificationChannels.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. Should the
@@ -76,7 +102,8 @@ class ReminderChannels @Inject constructor(
*/
@Synchronized
fun channelFor(calendarId: Long): String? {
val id = reminderChannelId(calendarId)
val versions = versions()
val id = reminderChannelId(calendarId, versions[calendarId] ?: 0)
val manager = manager
if (manager.getNotificationChannel(id) != null) return id
val existing = manager.notificationChannels
@@ -91,7 +118,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 }
@@ -115,19 +142,67 @@ class ReminderChannels @Inject constructor(
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, versions())
}
/**
* 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<Long>): Map<Long, Uri?> {
val versions = versions()
val manager = manager
return calendarIds.mapNotNull { id ->
manager.getNotificationChannel(reminderChannelId(id, versions[id] ?: 0))?.let { id to it.sound }
}.toMap()
}
/**
* Give [calendarId]'s reminders [sound] (null = silent). A channel's sound is
* fixed once created, so this moves the calendar to a new channel version
* carrying over everything else, and retires the old one. Returns whether
* the calendar had a channel to move.
*/
suspend fun setSound(calendarId: Long, sound: Uri?): Boolean {
val oldId = channelFor(calendarId) ?: return false
val floor = manager.notificationChannels
.mapNotNull { parseReminderChannelId(it.id) }
.filter { it.first == calendarId }
.maxOfOrNull { it.second + 1 } ?: 1
val version = settingsPrefs.bumpReminderChannelVersion(calendarId, atLeast = floor)
return recreate(oldId, reminderChannelId(calendarId, version), sound)
}
@Synchronized
private fun recreate(oldId: String, newId: String, sound: Uri?): Boolean {
val manager = manager
val old = manager.getNotificationChannel(oldId) ?: return false
val channel = NotificationChannel(newId, old.name, old.importance).apply {
description = old.description
old.group?.let { group = it }
inheritFrom(old)
setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES)
}
manager.createNotificationChannel(channel)
if (oldId !in showingChannelIds()) manager.deleteNotificationChannel(oldId)
lastSync = null
return true
}
private fun plan(
calendars: List<CalendarSource>,
existing: List<NotificationChannel>,
existingGroupIds: List<String>,
versions: Map<Long, Int>,
showingChannelIds: Set<String> = 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(
@@ -142,11 +217,12 @@ class ReminderChannels @Inject constructor(
if (channels.isEmpty()) return
val byId = existing.associateBy { it.id }
val description = context.getString(R.string.reminder_channel_description)
val template = byId[LEGACY_REMINDER_CHANNEL_ID]
val legacy = byId[LEGACY_REMINDER_CHANNEL_ID]
// Importance only applies on creation; an existing channel keeps its own.
manager.createNotificationChannels(
channels.map { spec ->
val current = byId[spec.id]
val template = spec.templateId?.let(byId::get) ?: legacy
NotificationChannel(
spec.id,
spec.name,
@@ -203,6 +279,11 @@ class ReminderChannels @Inject constructor(
private companion object {
const val TAG = "ReminderChannels"
val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
}
}
@@ -1,11 +1,13 @@
package de.jeanlucmakiola.calendula.ui.settings
import android.Manifest
import android.content.ActivityNotFoundException
import android.content.Context
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 androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
@@ -29,6 +31,7 @@ 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
@@ -51,7 +54,9 @@ import de.jeanlucmakiola.calendula.ui.common.TimePickerAlert
import de.jeanlucmakiola.calendula.ui.common.durationLabel
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
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.ExpandIcon
import de.jeanlucmakiola.floret.components.GroupedRow
@@ -108,9 +113,36 @@ internal fun NotificationsScreen(
viewModel.refreshChannelStatus(calendarIds)
onPauseOrDispose { }
}
val openCalendarSound: (Long) -> Unit = { calendarId ->
val openCalendarSettings: (Long) -> Unit = { calendarId ->
scope.launch { context.openNotificationSettings(viewModel.soundSettingsChannel(calendarId)) }
}
val openAppSettings: () -> Unit = {
scope.launch {
viewModel.syncReminderChannels()
context.openNotificationSettings()
}
}
val sounds by viewModel.channelSounds.collectAsStateWithLifecycle()
// ALL_CALENDARS, a calendar id, or null when no pick is pending.
var soundTarget by rememberSaveable { mutableStateOf<Long?>(null) }
val soundPicker = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
val target = soundTarget
soundTarget = null
val picked = pickedSound(result.resultCode, result.data) ?: return@rememberLauncherForActivityResult
val ids = if (target == ALL_CALENDARS) calendarIds else listOfNotNull(target)
viewModel.setReminderSound(ids, picked.uri)
}
val pickSoundTitle = stringResource(R.string.settings_notification_sound)
val pickSound: (Long) -> Unit = { target ->
val current = if (target == ALL_CALENDARS) sharedSound(sounds, calendarIds)?.uri else sounds[target]?.uri
soundTarget = target
try {
soundPicker.launch(notificationSoundPickerIntent(current ?: DEFAULT_NOTIFICATION_URI, pickSoundTitle))
} catch (e: ActivityNotFoundException) {
soundTarget = null
if (target == ALL_CALENDARS) openAppSettings() else openCalendarSettings(target)
}
}
CollapsingScaffold(
title = stringResource(R.string.settings_section_notifications),
@@ -122,10 +154,7 @@ internal fun NotificationsScreen(
NotificationCategoryHint(
onOpen = {
viewModel.dismissNotificationCategoryHint()
scope.launch {
viewModel.syncReminderChannels()
context.openNotificationSettings()
}
openAppSettings()
},
onDismiss = viewModel::dismissNotificationCategoryHint,
)
@@ -138,8 +167,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 = globalSoundLabel(sounds, 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 {
@@ -147,12 +184,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),
@@ -252,8 +284,10 @@ internal fun NotificationsScreen(
state = state,
notifying = notifying,
blocked = blocked,
soundLabel = soundLabel(sounds[calendar.id]),
onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) },
onOpenSound = { openCalendarSound(calendar.id) },
onPickSound = { pickSound(calendar.id) },
onOpenSettings = { openCalendarSettings(calendar.id) },
onOpenSpecialDates = onOpenSpecialDates,
onEditOverride = { overrideDialog = it },
)
@@ -354,8 +388,10 @@ private fun CalendarNotificationRows(
state: SettingsUiState,
notifying: Boolean,
blocked: Boolean,
soundLabel: String,
onSetNotifying: (Boolean) -> Unit,
onOpenSound: () -> Unit,
onPickSound: () -> Unit,
onOpenSettings: () -> Unit,
onOpenSpecialDates: () -> Unit,
onEditOverride: (OverrideTarget) -> Unit,
) {
@@ -371,6 +407,12 @@ private fun CalendarNotificationRows(
)
GroupedRow(
title = stringResource(R.string.settings_notification_sound),
summary = soundLabel,
position = Position.Middle,
onClick = onPickSound,
)
GroupedRow(
title = stringResource(R.string.settings_notification_more),
summary = if (blocked) {
stringResource(R.string.settings_notifications_blocked_hint)
} else {
@@ -378,7 +420,7 @@ private fun CalendarNotificationRows(
},
position = if (managed || takesOverrides) Position.Middle else Position.Bottom,
trailing = { ExternalLinkIcon() },
onClick = onOpenSound,
onClick = onOpenSettings,
)
if (managed) {
GroupedRow(
@@ -413,6 +455,26 @@ private fun CalendarNotificationRows(
}
}
/** [soundTarget] meaning every calendar at once. */
private const val ALL_CALENDARS = Long.MIN_VALUE
/** The sound every one of [calendarIds] shares, or null when they differ or one has no channel yet. */
private fun sharedSound(sounds: Map<Long, ReminderSound>, calendarIds: List<Long>): ReminderSound? =
calendarIds.map { sounds[it] }.distinctBy { it?.uri }.singleOrNull()
@Composable
private 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)
else -> sound.title ?: stringResource(R.string.settings_notification_sound_default)
}
@Composable
private fun globalSoundLabel(sounds: Map<Long, ReminderSound>, calendarIds: List<Long>): String {
val shared = calendarIds.map { sounds[it] }.distinctBy { it?.uri }
return if (shared.size == 1) soundLabel(shared.single()) else stringResource(R.string.settings_notification_sound_mixed)
}
/** Samsung's One UI can start a new notification category switched off (#145). */
private val IS_SAMSUNG = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
@@ -1,5 +1,6 @@
package de.jeanlucmakiola.calendula.ui.settings
import android.net.Uri
import de.jeanlucmakiola.floret.reminders.ReminderOverride
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
@@ -136,3 +137,6 @@ 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?)
@@ -17,6 +17,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.floret.reminders.ReminderOverride
@@ -388,10 +389,37 @@ class SettingsViewModel @Inject constructor(
private var channelStatusJob: Job? = null
private val _channelSounds = MutableStateFlow<Map<Long, ReminderSound>>(emptyMap())
/** Each calendar's reminder sound (#518); a calendar without a channel yet is absent. */
val channelSounds: StateFlow<Map<Long, ReminderSound>> = _channelSounds.asStateFlow()
fun refreshChannelStatus(calendarIds: Collection<Long>) {
channelStatusJob?.cancel()
channelStatusJob = viewModelScope.launch {
onChannels { status(calendarIds) }?.let { _channelStatus.value = it }
val (status, sounds) = onChannels { status(calendarIds) to sounds(calendarIds) } ?: return@launch
_channelStatus.value = status
_channelSounds.value = withContext(io) {
sounds.mapValues { (_, uri) -> ReminderSound(uri, uri?.let { appContext.ringtoneTitle(it) }) }
}
}
}
/** Give [calendarIds]' reminders [sound] (null = silent), each on a fresh channel (#518). */
fun setReminderSound(calendarIds: Collection<Long>, sound: Uri?) {
viewModelScope.launch {
withContext(io) {
calendarIds.forEach { id ->
try {
reminderChannels.setSound(id, sound)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.w("SettingsViewModel", "Could not set the reminder sound of calendar $id", e)
}
}
}
refreshChannelStatus(state.value.reminderCalendars.map { it.id })
}
}
+6 -2
View File
@@ -736,12 +736,16 @@
<string name="settings_calendar_notifications_hint">Notify at this calendar\'s reminder times</string>
<string name="settings_calendar_notifications_off">Notifications off</string>
<string name="settings_notification_sound">Notification sound</string>
<string name="settings_notification_sound_hint">Sound, vibration and pop-ups for each calendar, in system settings</string>
<string name="settings_notification_sound_silent">Silent</string>
<string name="settings_notification_sound_default">Default</string>
<string name="settings_notification_sound_mixed">Differs per calendar</string>
<string name="settings_notification_more">More notification settings</string>
<string name="settings_notification_sound_hint">Vibration, pop-ups and more for each calendar, in system settings</string>
<string name="settings_notifications_blocked">Blocked in system settings</string>
<string name="settings_notifications_blocked_hint">Blocked in system settings — tap to allow</string>
<string name="settings_notification_category_hint">On Samsung phones, new notification categories can start switched off. If a calendar\'s reminders don\'t arrive, check that its category is on.</string>
<string name="settings_notification_category_hint_open">Open settings</string>
<string name="settings_calendar_notification_sound_hint">Sound, vibration and pop-ups for this calendar, in system settings</string>
<string name="settings_calendar_notification_sound_hint">Vibration, pop-ups and more for this calendar, in system settings</string>
<string name="settings_calendar_reminder_inherits">Default (%1$s)</string>
<string name="settings_reliable_delivery">Reliable delivery</string>
<string name="settings_reliable_delivery_hint">Android may delay reminders to save battery. Exempt Calendula so they arrive on time.</string>
@@ -614,6 +614,18 @@ class SettingsPrefsTest {
assertThat(prefs.mutedReminderCalendarIds.first()).containsExactly(9L)
}
@Test
fun `reminder channel versions only grow`(
@TempDir tempDir: Path,
) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.reminderChannelVersions.first()).isEmpty()
assertThat(prefs.bumpReminderChannelVersion(7L, atLeast = 1)).isEqualTo(1)
assertThat(prefs.bumpReminderChannelVersion(7L, atLeast = 1)).isEqualTo(2)
assertThat(prefs.bumpReminderChannelVersion(9L, atLeast = 5)).isEqualTo(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,
@@ -145,6 +145,48 @@ class ReminderChannelPlanTest {
assertThat(appOff.blockedCalendarIds).containsExactly(1L, 2L, 3L, 4L)
}
@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))
// A bump the recreate never wrote still inherits from the version before it.
assertThat(plan.channelsToWrite.map { it.templateId })
.containsExactly(reminderChannelId(1), reminderChannelId(2))
}
@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"
}
+10 -3
View File
@@ -402,9 +402,16 @@ 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 the calendar's next version
(`reminders.calendar.<id>.v<n>`, counter in `SettingsPrefs.reminderChannelVersions`
— it only grows, because a re-used id would bring back the deleted channel's
settings), copying everything else from the old one. The sync treats older
versions as stale, keeps one while a notification still shows on it, and a
version that was counted but never written inherits from the one before it.
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