fix(#518): review round 4 — silent channels read as silent, honest pick results, clearer failures

This commit is contained in:
makiolaj committed 2026-11-14 04:21:27 +01:00
1 parent 081675906b
commit d39ceb9ee0
6 files changed
+56 -28

No files matched your search

@@ -157,10 +157,20 @@ class ReminderChannels @Inject constructor(
/**
* 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.
* 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 <T> withChannel(calendarId: Long, block: (String) -> T): T? = channelFor(calendarId)?.let(block)
fun <T> 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<Long>): ReminderChannelStatus {
@@ -174,6 +184,10 @@ class ReminderChannels @Inject constructor(
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.
@@ -182,7 +196,7 @@ class ReminderChannels @Inject constructor(
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.sound }
byId[reminderChannelId(id, versions[id] ?: 0)]?.let { id to it.audibleSound() }
}.toMap()
}
@@ -200,7 +214,7 @@ class ReminderChannels @Inject constructor(
val floors = calendarIds
.filter { reminderChannelId(it, current[it] ?: 0) in existingIds }
.associateWith { (current[it] ?: 0) + 1 }
if (floors.isEmpty()) return true
if (floors.isEmpty()) return false
return recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound)
}
@@ -215,8 +229,12 @@ class ReminderChannels @Inject constructor(
val current = currentReminderChannelVersions(byId.keys, emptyMap())
var allApplied = true
versions.forEach { (calendarId, version) ->
val from = current[calendarId]?.takeIf { it < version } ?: return@forEach
val old = byId[reminderChannelId(calendarId, from)] ?: return@forEach
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) {
@@ -87,15 +87,10 @@ class ReminderNotifier @Inject constructor(
yesterdayLabel = context.getString(R.string.reminder_day_yesterday),
)
val text = listOfNotNull(time, alert.location).joinToString(" · ")
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
}
// 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, channelId, title, text) }
if (posted == null) {
Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone")
Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: no channel for calendar ${alert.calendarId}")
}
}
@@ -1,7 +1,6 @@
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
@@ -127,9 +126,11 @@ internal fun NotificationsScreen(
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 {
Toast.makeText(context, soundFailedMessage, Toast.LENGTH_LONG).show()
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.
@@ -157,7 +158,8 @@ internal fun NotificationsScreen(
// 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: ActivityNotFoundException) {
} 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)
}
@@ -140,3 +140,6 @@ data class SpecialDatesUiState(
/** 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 }
@@ -399,10 +399,10 @@ 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<Map<Long, ReminderSound>?> = _channelSounds.asStateFlow()
private val _soundFailed = Channel<Unit>(Channel.CONFLATED)
private val _soundFailed = Channel<SoundFailure>(Channel.CONFLATED)
/** Emits when a picked sound couldn't be applied to every calendar; kept until the screen collects it. */
val soundFailed: Flow<Unit> = _soundFailed.receiveAsFlow()
/** Emits when a picked sound couldn't be applied; kept until the screen collects it. */
val soundFailed: Flow<SoundFailure> = _soundFailed.receiveAsFlow()
private val soundTitles = mutableMapOf<Uri, String?>()
@@ -413,12 +413,18 @@ class SettingsViewModel @Inject constructor(
val sounds = onChannels { sounds(calendarIds) } ?: return@launch
_channelSounds.value = withContext(io) {
sounds.mapValues { (_, uri) ->
ReminderSound(uri, uri?.let { synchronized(soundTitles) { soundTitles.getOrPut(it) { appContext.ringtoneTitle(it) } } })
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)
@@ -445,17 +451,20 @@ class SettingsViewModel @Inject constructor(
/** 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 applied = withContext(io + NonCancellable) {
val failure = 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()
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)
false
SoundFailure.NotApplied
}
}
if (!applied) _soundFailed.trySend(Unit)
failure?.let(_soundFailed::trySend)
refreshChannelStatus(visibleCalendars.first().map { it.id })
}
}
+2 -1
View File
@@ -741,7 +741,8 @@
<!-- %1$s is the name of the device's default notification sound. -->
<string name="settings_notification_sound_default_named">Default (%1$s)</string>
<string name="settings_notification_sound_custom">Custom sound</string>
<string name="settings_notification_sound_failed">Couldn\'t change the sound for every calendar</string>
<string name="settings_notification_sound_failed">Couldn\'t change the notification sound</string>
<string name="settings_notification_sound_unreadable">Calendula can\'t play this sound. Pick another one.</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>