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 3ef3f2a4..4cd51d44 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 @@ -1,8 +1,12 @@ package de.jeanlucmakiola.calendula.data.reminders +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 @@ -57,7 +61,11 @@ class ReminderChannels @Inject constructor( 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 }, versions, showingChannelIds()) + 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() } @@ -94,12 +102,12 @@ class ReminderChannels @Inject constructor( private fun currentVersions(existingChannelIds: Collection): Map = currentReminderChannelVersions(existingChannelIds, runBlocking { settingsPrefs.reminderChannelVersions.first() }) - /** Channels with a notification on screen; on failure every channel counts, so none is deleted. */ - private fun showingChannelIds(): Set = runCatching { + /** 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) - manager.notificationChannels.mapTo(HashSet()) { it.id } + candidates.toSet() } /** @@ -147,6 +155,13 @@ 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 when the calendar is gone. + */ + @Synchronized + fun withChannel(calendarId: Long, block: (String) -> T): T? = channelFor(calendarId)?.let(block) + /** What the system currently lets through for [calendarIds]' reminders (#145). */ fun status(calendarIds: Collection): ReminderChannelStatus { val manager = manager @@ -174,7 +189,7 @@ class ReminderChannels @Inject constructor( /** * 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 (#518). Calendars without a + * everything else, and the old one retires on the next sync (#518). Calendars without a * channel are skipped unless [createMissing]. Returns whether every move * went through. */ @@ -189,20 +204,28 @@ class ReminderChannels @Inject constructor( return recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound) } - /** Create each calendar's [versions] from its current channel, then retire the old one. */ + /** + * 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()) - val showing = showingChannelIds() var allApplied = true versions.forEach { (calendarId, version) -> val from = current[calendarId]?.takeIf { it < version } ?: return@forEach val old = byId[reminderChannelId(calendarId, from)] ?: 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, old.importance).apply { + NotificationChannel(reminderChannelId(calendarId, version), old.name, importance).apply { description = old.description old.group?.let { group = it } inheritFrom(old) @@ -210,7 +233,6 @@ class ReminderChannels @Inject constructor( }, ) knownVersions = knownVersions + (calendarId to version) - if (old.id !in showing) manager.deleteNotificationChannel(old.id) } catch (e: RuntimeException) { Log.w(TAG, "Could not move calendar $calendarId to a new sound", e) allApplied = false @@ -292,7 +314,7 @@ class ReminderChannels @Inject constructor( private fun retireLegacyChannel(): Boolean { val manager = manager if (manager.getNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) == null) return true - val showing = LEGACY_REMINDER_CHANNEL_ID in showingChannelIds() + val showing = LEGACY_REMINDER_CHANNEL_ID in showingChannelIds(listOf(LEGACY_REMINDER_CHANNEL_ID)) if (!showing) manager.deleteNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) return !showing } @@ -307,10 +329,7 @@ class ReminderChannels @Inject constructor( private companion object { const val TAG = "ReminderChannels" - val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = AudioAttributes.Builder() - .setUsage(AudioAttributes.USAGE_NOTIFICATION) - .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .build() + 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 47bd2cd7..d9b196ae 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 @@ -87,16 +87,19 @@ class ReminderNotifier @Inject constructor( yesterdayLabel = context.getString(R.string.reminder_day_yesterday), ) val text = listOfNotNull(time, alert.location).joinToString(" ยท ") - // Resolved last, so a sound picked meanwhile (#518) can't retire it before notify. - val channelId = try { - channels.channelFor(alert.calendarId) ?: run { - Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone") - return - } + val posted = try { + // Under the channel lock, so a sound picked meanwhile (#518) can't move it mid-post. + channels.withChannel(alert.calendarId) { channelId -> notify(alert, channelId, title, text) } } catch (e: Exception) { Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e) return } + if (posted == null) { + Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone") + } + } + + private fun notify(alert: ReminderAlert, channelId: String, title: String, text: String) { val notification = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) 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 f4bf87b6..56cb4ed5 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 @@ -54,6 +55,8 @@ 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 @@ -396,10 +399,12 @@ class SettingsViewModel @Inject constructor( /** 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 = MutableSharedFlow(extraBufferCapacity = 1) + private val _soundFailed = Channel(Channel.CONFLATED) - /** Emits when a picked sound couldn't be applied to every calendar. */ - val soundFailed: SharedFlow = _soundFailed + /** Emits when a picked sound couldn't be applied to every calendar; kept until the screen collects it. */ + val soundFailed: Flow = _soundFailed.receiveAsFlow() + + private val soundTitles = mutableMapOf() fun refreshChannelStatus(calendarIds: Collection) { channelStatusJob?.cancel() @@ -407,41 +412,50 @@ class SettingsViewModel @Inject constructor( onChannels { status(calendarIds) }?.let { _channelStatus.value = it } val sounds = onChannels { sounds(calendarIds) } ?: return@launch _channelSounds.value = withContext(io) { - val titles = sounds.values.filterNotNull().distinct().associateWith { appContext.ringtoneTitle(it) } - sounds.mapValues { (_, uri) -> ReminderSound(uri, uri?.let(titles::get)) } + sounds.mapValues { (_, uri) -> + ReminderSound(uri, uri?.let { synchronized(soundTitles) { soundTitles.getOrPut(it) { appContext.ringtoneTitle(it) } } }) + } } } } /** Give [calendarId]'s reminders [sound] (null = silent), on a fresh channel (#518). */ - fun setReminderSound(calendarId: Long, sound: Uri?) = applySound { setSound(listOf(calendarId), sound, createMissing = true) } + 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 { + fun setReminderSoundForAll(sound: Uri?) = applySound(sound) { try { sync() } catch (e: Exception) { Log.w("SettingsViewModel", "Channel sync before a sound pick failed", e) } - setSound(visibleCalendars.first().map { it.id }, sound, createMissing = false) + 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(block: suspend ReminderChannels.() -> Boolean) { + private fun applySound(sound: Uri?, block: suspend ReminderChannels.() -> Boolean) { viewModelScope.launch { val applied = withContext(io + NonCancellable) { try { + // The system plays the sound but checks that Calendula could read it. + if (sound != null && !canRead(sound)) return@withContext false reminderChannels.block() } catch (e: Exception) { Log.w("SettingsViewModel", "Could not set the reminder sound", e) false } } - if (!applied) _soundFailed.tryEmit(Unit) + if (!applied) _soundFailed.trySend(Unit) refreshChannelStatus(visibleCalendars.first().map { it.id }) } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index e9ca44e5..a15dfbc9 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -410,8 +410,10 @@ the app (#518) can't be set on an existing channel, so 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). The sync treats older versions as stale and -keeps one while a notification still shows on it. +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