diff --git a/app/src/main/java/com/nextcloud/talk/jobs/NotificationWorker.kt b/app/src/main/java/com/nextcloud/talk/jobs/NotificationWorker.kt index 6da846891d8..26e8e474a72 100644 --- a/app/src/main/java/com/nextcloud/talk/jobs/NotificationWorker.kt +++ b/app/src/main/java/com/nextcloud/talk/jobs/NotificationWorker.kt @@ -327,7 +327,7 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor ) val soundUri = getCallRingtoneUri(applicationContext, appPreferences) - val notificationChannelId = NotificationUtils.NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name + val notificationChannelId = NotificationUtils.getCallsNotificationChannelId(applicationContext) val uri = user.baseUrl!!.toUri() val baseUrl = uri.host @@ -771,7 +771,7 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor TYPE_ADMIN_NOTIFICATIONS, TYPE_REMOTE_TALK_SHARE -> { notificationBuilder.setChannelId( - NotificationUtils.NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name + NotificationUtils.getMessagesNotificationChannelId(applicationContext) ) } } @@ -1231,8 +1231,7 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor if (isOngoingCallNotificationVisible) { val notificationBuilder = NotificationCompat.Builder( context!!, - NotificationUtils.NotificationChannels - .NOTIFICATION_CHANNEL_MESSAGES_V4.name + NotificationUtils.getMessagesNotificationChannelId(context!!) ) val intent = createContentIntent() diff --git a/app/src/main/java/com/nextcloud/talk/settings/DeviceStateReader.kt b/app/src/main/java/com/nextcloud/talk/settings/DeviceStateReader.kt index 9cad25dd89d..531c2e50083 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/DeviceStateReader.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/DeviceStateReader.kt @@ -83,8 +83,11 @@ class DeviceStateReader @Inject constructor( ringtoneUri == null -> RingtoneState.Silent ringtoneUri.toString() == NotificationUtils.DEFAULT_CALL_RINGTONE_URI || ringtoneUri.toString() == NotificationUtils.DEFAULT_MESSAGE_RINGTONE_URI -> RingtoneState.Default - else -> RingtoneManager.getRingtone(context, ringtoneUri)?.getTitle(context) - ?.let { RingtoneState.Custom(it) } - ?: RingtoneState.Default + else -> RingtoneState.Custom( + title = RingtoneManager.getRingtone(context, ringtoneUri)?.getTitle(context) + ?: ringtoneUri.lastPathSegment + ?: ringtoneUri.toString(), + uri = ringtoneUri.toString() + ) } } diff --git a/app/src/main/java/com/nextcloud/talk/settings/NotificationSoundUpdater.kt b/app/src/main/java/com/nextcloud/talk/settings/NotificationSoundUpdater.kt new file mode 100644 index 00000000000..e8586e067f7 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/NotificationSoundUpdater.kt @@ -0,0 +1,31 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.settings + +import android.content.Context +import androidx.annotation.WorkerThread +import androidx.core.net.toUri +import com.nextcloud.talk.utils.NotificationUtils +import com.nextcloud.talk.utils.preferences.AppPreferences +import javax.inject.Inject + +/** Changes the sound of a notification channel, which recreates the channel. */ +class NotificationSoundUpdater @Inject constructor( + private val context: Context, + private val appPreferences: AppPreferences +) { + /** + * @param uri null for no sound + * @return false if the sound could not be set + */ + @WorkerThread + fun update(sound: NotificationSound, uri: String?): Boolean = + when (sound) { + NotificationSound.CALL -> NotificationUtils.updateCallRingtone(context, appPreferences, uri?.toUri()) + NotificationSound.MESSAGE -> NotificationUtils.updateMessageRingtone(context, appPreferences, uri?.toUri()) + } +} diff --git a/app/src/main/java/com/nextcloud/talk/settings/PickSoundContract.kt b/app/src/main/java/com/nextcloud/talk/settings/PickSoundContract.kt new file mode 100644 index 00000000000..031d82ef25b --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/PickSoundContract.kt @@ -0,0 +1,56 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.settings + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.media.RingtoneManager +import android.net.Uri +import android.provider.Settings +import androidx.activity.result.contract.ActivityResultContract +import androidx.core.content.IntentCompat +import androidx.core.net.toUri + +/** Opens the system ringtone picker. */ +class PickSoundContract : ActivityResultContract() { + + /** + * @param existingUri the sound selected in the picker, null for no sound + */ + data class Request(val sound: NotificationSound, val title: String, val existingUri: String?) + + /** @param uri the picked sound, null for no sound */ + data class Result(val uri: String?) + + override fun createIntent(context: Context, input: Request): Intent { + val (ringtoneType, systemDefaultUri) = when (input.sound) { + NotificationSound.CALL -> RingtoneManager.TYPE_RINGTONE to Settings.System.DEFAULT_RINGTONE_URI + NotificationSound.MESSAGE -> RingtoneManager.TYPE_NOTIFICATION to Settings.System.DEFAULT_NOTIFICATION_URI + } + return Intent(RingtoneManager.ACTION_RINGTONE_PICKER) + .putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, ringtoneType) + .putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, input.title) + .putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true) + .putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, systemDefaultUri) + .putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true) + .putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, input.existingUri?.toUri()) + } + + /** @return null if nothing was picked; a missing extra must not be treated as "no sound" */ + override fun parseResult(resultCode: Int, intent: Intent?): Result? { + if (resultCode != Activity.RESULT_OK || intent?.hasExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI) != true) { + return null + } + val pickedUri = IntentCompat.getParcelableExtra( + intent, + RingtoneManager.EXTRA_RINGTONE_PICKED_URI, + Uri::class.java + ) + return Result(pickedUri?.toString()) + } +} diff --git a/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt b/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt index 088e53e6eb7..3f7710e0a67 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt @@ -47,6 +47,8 @@ import com.nextcloud.talk.settings.ui.ProxyCallbacks import com.nextcloud.talk.settings.ui.SettingsScreen import com.nextcloud.talk.settings.ui.SettingsScreenCallbacks import com.nextcloud.talk.settings.ui.SystemSettingsScreen +import com.nextcloud.talk.settings.ui.systemSettingsScreen +import com.nextcloud.talk.settings.ui.titleRes import com.nextcloud.talk.utils.LoggingUtils.sendMailWithAttachment import com.nextcloud.talk.utils.NotificationUtils import com.nextcloud.talk.utils.UnifiedPushUtils @@ -101,6 +103,10 @@ class SettingsActivity : BaseActivity() { } } + private val callSoundPickerLauncher = registerSoundPicker(NotificationSound.CALL) + + private val messageSoundPickerLauncher = registerSoundPicker(NotificationSound.MESSAGE) + private val contactsPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { results -> if (results.isNotEmpty() && results.values.all { it }) { @@ -157,6 +163,8 @@ class SettingsActivity : BaseActivity() { }, onOpenSystemSettings = ::openSystemSettings, onOpenDiagnosis = { startActivity(intentForAccount(DiagnosisActivity::class.java)) }, + onPickNotificationSound = ::pickNotificationSound, + onNotificationSoundChange = viewModel::setNotificationSound, onShowNotificationWarningChange = viewModel::setShowNotificationWarning, onScreenLockChange = viewModel::setScreenLock, onScreenLockTimeoutChange = viewModel::setScreenLockTimeout, @@ -267,11 +275,9 @@ class SettingsActivity : BaseActivity() { Intent(Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT, "package:$packageName".toUri()) } SystemSettingsScreen.CALL_NOTIFICATIONS -> - notificationChannelSettingsIntent(NotificationUtils.NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5) + notificationChannelSettingsIntent(NotificationUtils.getCallsNotificationChannelId(this)) SystemSettingsScreen.MESSAGE_NOTIFICATIONS -> - notificationChannelSettingsIntent( - NotificationUtils.NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4 - ) + notificationChannelSettingsIntent(NotificationUtils.getMessagesNotificationChannelId(this)) } openSystemSettings(intent) } @@ -284,10 +290,28 @@ class SettingsActivity : BaseActivity() { } } - private fun notificationChannelSettingsIntent(channel: NotificationUtils.NotificationChannels): Intent = + private fun notificationChannelSettingsIntent(channelId: String): Intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS) .putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID) - .putExtra(Settings.EXTRA_CHANNEL_ID, channel.name) + .putExtra(Settings.EXTRA_CHANNEL_ID, channelId) + + private fun registerSoundPicker(sound: NotificationSound) = + registerForActivityResult(PickSoundContract()) { result -> + result?.let { viewModel.setNotificationSound(sound, it.uri) } + } + + private fun pickNotificationSound(sound: NotificationSound, current: RingtoneState) { + val launcher = when (sound) { + NotificationSound.CALL -> callSoundPickerLauncher + NotificationSound.MESSAGE -> messageSoundPickerLauncher + } + try { + launcher.launch(PickSoundContract.Request(sound, getString(sound.titleRes), sound.uriOf(current))) + } catch (e: ActivityNotFoundException) { + Log.w(TAG, "No ringtone picker available, opening the notification channel settings instead", e) + openSystemSettings(sound.systemSettingsScreen) + } + } private fun openLogs() { startActivity(Intent(this, LogsActivity::class.java)) diff --git a/app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt b/app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt index eb060b40398..fafcb51da7d 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt @@ -7,6 +7,7 @@ package com.nextcloud.talk.settings import androidx.compose.runtime.Immutable +import com.nextcloud.talk.utils.NotificationUtils @Immutable data class SettingsUiState( @@ -91,8 +92,24 @@ sealed interface RingtoneState { /** The notification channel is turned off. */ data object Disabled : RingtoneState data object Silent : RingtoneState + + /** The sound bundled with the app, which the system ringtone picker doesn't list. */ data object Default : RingtoneState - data class Custom(val title: String) : RingtoneState + data class Custom(val title: String, val uri: String) : RingtoneState +} + +/** The notification sounds that can be chosen on the settings screen. */ +enum class NotificationSound(private val bundledUri: String, val audioUsage: Int) { + CALL(NotificationUtils.DEFAULT_CALL_RINGTONE_URI, NotificationUtils.CALLS_AUDIO_USAGE), + MESSAGE(NotificationUtils.DEFAULT_MESSAGE_RINGTONE_URI, NotificationUtils.MESSAGES_AUDIO_USAGE); + + /** The uri of the sound that [ringtone] stands for, null for no sound. */ + fun uriOf(ringtone: RingtoneState): String? = + when (ringtone) { + RingtoneState.Default -> bundledUri + is RingtoneState.Custom -> ringtone.uri + RingtoneState.Silent, RingtoneState.Disabled -> null + } } @Immutable diff --git a/app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt b/app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt index b276561cbf7..e90e7adab75 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt @@ -59,6 +59,7 @@ class SettingsViewModel @AssistedInject constructor( private val settingsRepository: SettingsRepository, private val logsRepository: LogsRepository, private val deviceStateReader: DeviceStateReader, + private val notificationSoundUpdater: NotificationSoundUpdater, private val accountRemover: AccountRemover, private val workManager: WorkManager, private val logger: Logger, @@ -207,6 +208,17 @@ class SettingsViewModel @AssistedInject constructor( } } + /** @param uri null for no sound */ + fun setNotificationSound(sound: NotificationSound, uri: String?) { + viewModelScope.launch { + val updated = withContext(preferenceWriter) { notificationSoundUpdater.update(sound, uri) } + if (!updated) { + _events.send(SettingsEvent.ShowMessage(R.string.nc_common_error_sorry)) + } + refreshDeviceState() + } + } + fun setShowNotificationWarning(show: Boolean) { _uiState.update { it.copy(notifications = it.notifications.copy(showNotificationWarning = show)) } persist { prefs -> diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsDialogs.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsDialogs.kt index 19bf9f92dbe..41b52b5a2d4 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsDialogs.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsDialogs.kt @@ -114,12 +114,12 @@ internal fun MediaQualityDialog(reducedQuality: Boolean, onSelect: (Boolean) -> style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(bottom = 8.dp) ) - MediaQualityOption( + RadioOption( label = stringResource(R.string.nc_media_quality_original), selected = !reducedQuality, onClick = { onSelect(false) } ) - MediaQualityOption( + RadioOption( label = stringResource(R.string.nc_media_quality_reduced), selected = reducedQuality, onClick = { onSelect(true) } @@ -134,7 +134,7 @@ internal fun MediaQualityDialog(reducedQuality: Boolean, onSelect: (Boolean) -> } @Composable -private fun MediaQualityOption(label: String, selected: Boolean, onClick: () -> Unit) { +internal fun RadioOption(label: String, selected: Boolean, onClick: () -> Unit) { Row( modifier = Modifier .fillMaxWidth() diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsNotificationsSection.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsNotificationsSection.kt index 56c7971a636..744ce7429c1 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsNotificationsSection.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsNotificationsSection.kt @@ -7,6 +7,7 @@ package com.nextcloud.talk.settings.ui import android.content.res.Configuration +import androidx.annotation.StringRes import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Column import androidx.compose.material3.MaterialTheme @@ -23,6 +24,7 @@ import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import com.nextcloud.talk.R +import com.nextcloud.talk.settings.NotificationSound import com.nextcloud.talk.settings.NotificationsUiState import com.nextcloud.talk.settings.PushAvailability import com.nextcloud.talk.settings.RingtoneState @@ -203,22 +205,53 @@ private fun TroubleshootingDialog(onOpenDiagnosis: () -> Unit, onDismiss: () -> @Composable private fun RingtoneItems(state: NotificationsUiState, highlightIssues: Boolean, callbacks: SettingsScreenCallbacks) { - RingtoneItem( - title = stringResource(R.string.nc_settings_call_ringtone), - ringtone = state.callRingtone, - enabled = state.ringtoneSettingsEnabled, - highlight = highlightIssues, - onClick = { callbacks.onOpenSystemSettings(SystemSettingsScreen.CALL_NOTIFICATIONS) } - ) - RingtoneItem( - title = stringResource(R.string.nc_settings_other_notifications_ringtone), - ringtone = state.messageRingtone, - enabled = state.ringtoneSettingsEnabled, - highlight = highlightIssues, - onClick = { callbacks.onOpenSystemSettings(SystemSettingsScreen.MESSAGE_NOTIFICATIONS) } - ) + var soundDialog by rememberSaveable { mutableStateOf(null) } + + NotificationSound.entries.forEach { sound -> + val ringtone = state.ringtone(sound) + RingtoneItem( + title = stringResource(sound.titleRes), + ringtone = ringtone, + enabled = state.ringtoneSettingsEnabled, + highlight = highlightIssues, + onClick = { + if (ringtone == RingtoneState.Disabled) { + callbacks.onOpenSystemSettings(sound.systemSettingsScreen) + } else { + soundDialog = sound + } + } + ) + } + + soundDialog?.let { sound -> + SoundDialog( + sound = sound, + current = state.ringtone(sound), + callbacks = callbacks, + onDismiss = { soundDialog = null } + ) + } } +private fun NotificationsUiState.ringtone(sound: NotificationSound): RingtoneState = + when (sound) { + NotificationSound.CALL -> callRingtone + NotificationSound.MESSAGE -> messageRingtone + } + +internal val NotificationSound.systemSettingsScreen: SystemSettingsScreen + get() = when (this) { + NotificationSound.CALL -> SystemSettingsScreen.CALL_NOTIFICATIONS + NotificationSound.MESSAGE -> SystemSettingsScreen.MESSAGE_NOTIFICATIONS + } + +internal val NotificationSound.titleRes: Int + @StringRes get() = when (this) { + NotificationSound.CALL -> R.string.nc_settings_call_ringtone + NotificationSound.MESSAGE -> R.string.nc_settings_other_notifications_ringtone + } + @Composable private fun RingtoneItem( title: String, diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsScreen.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsScreen.kt index 29401b7a955..5aa7fd02f87 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsScreen.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsScreen.kt @@ -44,6 +44,7 @@ import com.nextcloud.talk.components.ColoredStatusBar import com.nextcloud.talk.components.IncognitoKeyboard import com.nextcloud.talk.components.StandardAppBar import com.nextcloud.talk.settings.AccountUiState +import com.nextcloud.talk.settings.NotificationSound import com.nextcloud.talk.settings.NotificationsUiState import com.nextcloud.talk.settings.PrivacyUiState import com.nextcloud.talk.settings.ProxyUiState @@ -72,6 +73,11 @@ data class SettingsScreenCallbacks( val onRequestNotificationPermission: () -> Unit = {}, val onOpenSystemSettings: (SystemSettingsScreen) -> Unit = {}, val onOpenDiagnosis: () -> Unit = {}, + /** Opens the system ringtone picker, with the current sound selected. */ + val onPickNotificationSound: (NotificationSound, RingtoneState) -> Unit = { _, _ -> }, + + /** Sets the sound by its uri, null for no sound. */ + val onNotificationSoundChange: (NotificationSound, String?) -> Unit = { _, _ -> }, val onShowNotificationWarningChange: (Boolean) -> Unit = {}, val onScreenLockChange: (Boolean) -> Unit = {}, val onScreenLockTimeoutChange: (String) -> Unit = {}, diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsSoundDialog.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsSoundDialog.kt new file mode 100644 index 00000000000..81b6a7e7e07 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsSoundDialog.kt @@ -0,0 +1,154 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.settings.ui + +import android.content.Context +import android.content.res.Configuration +import android.media.AudioAttributes +import android.media.Ringtone +import android.media.RingtoneManager +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.core.net.toUri +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect +import com.nextcloud.talk.R +import com.nextcloud.talk.settings.NotificationSound +import com.nextcloud.talk.settings.RingtoneState + +/** + * Lets the user choose the sound of [sound]. Besides the current sound and no sound, it offers the sound bundled with + * the app, which the system ringtone picker doesn't list. + */ +@Composable +internal fun SoundDialog( + sound: NotificationSound, + current: RingtoneState, + callbacks: SettingsScreenCallbacks, + onDismiss: () -> Unit +) { + val options = listOfNotNull(RingtoneState.Default, current as? RingtoneState.Custom, RingtoneState.Silent) + var selectedIndex by rememberSaveable { mutableIntStateOf(options.indexOf(current)) } + val previewPlayer = rememberSoundPreviewPlayer() + + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(sound.titleRes)) }, + text = { + Column(modifier = Modifier.selectableGroup().verticalScroll(rememberScrollState())) { + options.forEachIndexed { index, option -> + RadioOption(label = soundLabel(option), selected = index == selectedIndex, onClick = { + selectedIndex = index + previewPlayer.stop() + sound.uriOf(option)?.let { previewPlayer.play(it, sound.audioUsage) } + }) + } + RadioOption(label = stringResource(R.string.nc_settings_other_sound), selected = false, onClick = { + previewPlayer.stop() + onDismiss() + callbacks.onPickNotificationSound(sound, current) + }) + } + }, + confirmButton = { + TextButton(onClick = { + onDismiss() + val selected = options.getOrNull(selectedIndex) + if (selected != null && selected != current) { + callbacks.onNotificationSoundChange(sound, sound.uriOf(selected)) + } + }) { Text(stringResource(R.string.nc_ok)) } + }, + dismissButton = { + Row { + TextButton(onClick = { + onDismiss() + callbacks.onOpenSystemSettings(sound.systemSettingsScreen) + }) { + Text(stringResource(R.string.nc_notification_settings)) + } + TextButton(onClick = onDismiss) { Text(stringResource(R.string.nc_cancel)) } + } + } + ) +} + +@Composable +private fun soundLabel(ringtone: RingtoneState): String = + when (ringtone) { + RingtoneState.Default -> stringResource(R.string.nc_settings_default_ringtone) + RingtoneState.Silent, RingtoneState.Disabled -> stringResource(R.string.nc_settings_no_ringtone) + is RingtoneState.Custom -> ringtone.title + } + +/** Plays one sound at a time, to preview it. */ +internal class SoundPreviewPlayer(private val context: Context) { + private var ringtone: Ringtone? = null + + fun play(uri: String, audioUsage: Int) { + stop() + ringtone = RingtoneManager.getRingtone(context, uri.toUri())?.apply { + audioAttributes = AudioAttributes.Builder() + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .setUsage(audioUsage) + .build() + play() + } + } + + fun stop() { + ringtone?.stop() + ringtone = null + } +} + +/** A [SoundPreviewPlayer] that stops when it leaves the composition or the screen is paused. */ +@Composable +internal fun rememberSoundPreviewPlayer(): SoundPreviewPlayer { + val context = LocalContext.current + val player = remember(context) { SoundPreviewPlayer(context) } + DisposableEffect(player) { + onDispose { player.stop() } + } + LifecycleEventEffect(Lifecycle.Event.ON_PAUSE) { player.stop() } + return player +} + +@Preview(name = "Light") +@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES) +@Composable +private fun SoundDialogPreview() { + MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) { + SoundDialog( + sound = NotificationSound.CALL, + current = RingtoneState.Custom("Ring", "content://media/internal/audio/media/1"), + callbacks = SettingsScreenCallbacks(), + onDismiss = {} + ) + } +} diff --git a/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt b/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt index 62332359bed..2ef17ab79e3 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt +++ b/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt @@ -66,11 +66,21 @@ object NotificationUtils { private const val BITMAP_COMPRESSION_QUALITY = 100 + /** + * Separates a channel base id from a timestamp, e.g. "NOTIFICATION_CHANNEL_CALLS_V5__1762950000000". The app + * can't change the sound of an existing channel, so the channel is replaced under a new id, see [replaceChannel]. + */ + private const val CHANNEL_ID_VERSION_SEPARATOR = "__" + + const val CALLS_AUDIO_USAGE = AudioAttributes.USAGE_NOTIFICATION_RINGTONE + const val MESSAGES_AUDIO_USAGE = AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT + private fun createNotificationChannel( context: Context, notificationChannel: Channel, sound: Uri?, - audioAttributes: AudioAttributes? + audioAttributes: AudioAttributes?, + copySettingsFrom: NotificationChannel? = null ) { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager @@ -94,32 +104,141 @@ object NotificationUtils { channel.lightColor = R.color.colorPrimary channel.setSound(sound, audioAttributes) channel.setBypassDnd(false) + copySettingsFrom?.let { copyUserSettings(it, channel) } notificationManager.createNotificationChannel(channel) } } - private fun createCallsNotificationChannel(context: Context, appPreferences: AppPreferences) { + /** + * Keeps the settings the user may have changed for [from] in the system settings, except the sound. The system + * ignores some of them for new channels, e.g. bypassing Do Not Disturb without policy access. + */ + private fun copyUserSettings(from: NotificationChannel, to: NotificationChannel) { + to.importance = from.importance + to.enableLights(from.shouldShowLights()) + to.lightColor = from.lightColor + // setting the pattern also changes the vibration flag, so the flag is set afterwards + to.vibrationPattern = from.vibrationPattern + to.enableVibration(from.shouldVibrate()) + to.setShowBadge(from.canShowBadge()) + to.lockscreenVisibility = from.lockscreenVisibility + to.setBypassDnd(from.canBypassDnd()) + } + + private fun createCallsNotificationChannel( + context: Context, + channelId: String, + soundUri: Uri?, + copySettingsFrom: NotificationChannel? = null + ) { val audioAttributes = AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE) + .setUsage(CALLS_AUDIO_USAGE) .build() - val soundUri = getCallRingtoneUri(context, appPreferences) createNotificationChannel( context, Channel( - NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name, + channelId, context.resources.getString(R.string.nc_notification_channel_calls), context.resources.getString(R.string.nc_notification_channel_calls_description), true ), soundUri, - audioAttributes + audioAttributes, + copySettingsFrom ) } + private fun channelVersion(channelId: String, baseId: String): Long? = + when { + channelId == baseId -> 0L + channelId.startsWith(baseId + CHANNEL_ID_VERSION_SEPARATOR) -> + channelId.removePrefix(baseId + CHANNEL_ID_VERSION_SEPARATOR).toLongOrNull() + else -> null + } + + private fun getVersionedChannelId(context: Context, baseId: String): String { + val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + return notificationManager.notificationChannels + .mapNotNull { channel -> channelVersion(channel.id, baseId)?.let { version -> version to channel.id } } + .maxByOrNull { it.first } + ?.second + ?: baseId + } + + fun getCallsNotificationChannelId(context: Context): String = + getVersionedChannelId(context, NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name) + + fun getMessagesNotificationChannelId(context: Context): String = + getVersionedChannelId(context, NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name) + + /** + * @param ringtoneUri null for silent + * @return false if the ringtone could not be set + */ + fun updateCallRingtone(context: Context, appPreferences: AppPreferences, ringtoneUri: Uri?): Boolean { + val baseId = NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name + val replaced = replaceChannel(context, baseId, ringtoneUri) { channelId, currentChannel -> + createCallsNotificationChannel(context, channelId, ringtoneUri, currentChannel) + } + if (replaced) { + appPreferences.callRingtoneUri = LoganSquare.serialize(RingtoneSettings(ringtoneUri, null)) + } + return replaced + } + + /** + * @param ringtoneUri null for silent + * @return false if the sound could not be set + */ + fun updateMessageRingtone(context: Context, appPreferences: AppPreferences, ringtoneUri: Uri?): Boolean { + val baseId = NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name + val replaced = replaceChannel(context, baseId, ringtoneUri) { channelId, currentChannel -> + createMessagesNotificationChannel(context, channelId, ringtoneUri, currentChannel) + } + if (replaced) { + appPreferences.messageRingtoneUri = LoganSquare.serialize(RingtoneSettings(ringtoneUri, null)) + } + return replaced + } + + /** + * Creates a new channel with a new id, based on the settings of the current channel, and then deletes the old + * ones. + */ + @Suppress("TooGenericExceptionCaught") + private fun replaceChannel( + context: Context, + baseId: String, + sound: Uri?, + createChannel: (channelId: String, currentChannel: NotificationChannel?) -> Unit + ): Boolean { + val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + val oldChannels = notificationManager.notificationChannels.filter { channelVersion(it.id, baseId) != null } + if (oldChannels.size == 1 && oldChannels.first().sound == sound) { + return true + } + + val currentChannel = oldChannels.maxByOrNull { channelVersion(it.id, baseId) ?: 0L } + val newChannelId = baseId + CHANNEL_ID_VERSION_SEPARATOR + System.currentTimeMillis() + val created = try { + createChannel(newChannelId, currentChannel) + true + } catch (e: RuntimeException) { + // e.g. SecurityException for sounds the app is not allowed to read, or invalid sound uris + Log.e(TAG, "Failed to create channel $newChannelId with sound $sound", e) + false + } + if (created) { + oldChannels.forEach { notificationManager.deleteNotificationChannel(it.id) } + Log.i(TAG, "Replaced channels ${oldChannels.map { it.id }} with $newChannelId") + } + return created + } + /** * Separate from [NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5] (the incoming-ring channel, * which must stay IMPORTANCE_HIGH) so the persistent "call in progress" foreground-service @@ -139,24 +258,29 @@ object NotificationUtils { ) } - private fun createMessagesNotificationChannel(context: Context, appPreferences: AppPreferences) { + private fun createMessagesNotificationChannel( + context: Context, + channelId: String, + soundUri: Uri?, + copySettingsFrom: NotificationChannel? = null + ) { val audioAttributes = AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT) + .setUsage(MESSAGES_AUDIO_USAGE) .build() - val soundUri = getMessageRingtoneUri(context, appPreferences) createNotificationChannel( context, Channel( - NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name, + channelId, context.resources.getString(R.string.nc_notification_channel_messages), context.resources.getString(R.string.nc_notification_channel_messages_description), true ), soundUri, - audioAttributes + audioAttributes, + copySettingsFrom ) } @@ -175,9 +299,17 @@ object NotificationUtils { } fun registerNotificationChannels(context: Context, appPreferences: AppPreferences) { - createCallsNotificationChannel(context, appPreferences) + createCallsNotificationChannel( + context, + getCallsNotificationChannelId(context), + getCallRingtoneUri(context, appPreferences) + ) createOngoingCallNotificationChannel(context) - createMessagesNotificationChannel(context, appPreferences) + createMessagesNotificationChannel( + context, + getMessagesNotificationChannelId(context), + getMessageRingtoneUri(context, appPreferences) + ) createUploadsNotificationChannel(context) } @@ -193,7 +325,7 @@ object NotificationUtils { // Delete all notification channels created by previous versions for (channel in notificationManager.notificationChannels) { - if (!channelsToKeep.contains(channel.id)) { + if (channelsToKeep.none { channelVersion(channel.id, it) != null }) { notificationManager.deleteNotificationChannel(channel.id) } } @@ -286,7 +418,7 @@ object NotificationUtils { } fun isCallsNotificationChannelEnabled(context: Context): Boolean { - val channel = getNotificationChannel(context, NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name) + val channel = getNotificationChannel(context, getCallsNotificationChannelId(context)) if (channel != null) { return isNotificationChannelEnabled(channel) } @@ -294,7 +426,7 @@ object NotificationUtils { } fun isMessagesNotificationChannelEnabled(context: Context): Boolean { - val channel = getNotificationChannel(context, NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name) + val channel = getNotificationChannel(context, getMessagesNotificationChannelId(context)) if (channel != null) { return isNotificationChannelEnabled(channel) } @@ -340,7 +472,7 @@ object NotificationUtils { context, appPreferences.callRingtoneUri, DEFAULT_CALL_RINGTONE_URI, - NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name + getCallsNotificationChannelId(context) ) fun getMessageRingtoneUri(context: Context, appPreferences: AppPreferences): Uri? = @@ -348,7 +480,7 @@ object NotificationUtils { context, appPreferences.messageRingtoneUri, DEFAULT_MESSAGE_RINGTONE_URI, - NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name + getMessagesNotificationChannelId(context) ) fun loadAvatarSync(avatarUrl: String, context: Context, credentials: String? = null): IconCompat? { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index b8aa0a54909..5cfe6ce51e1 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -129,6 +129,7 @@ How to translate with transifex: Messages Librem by feandesign No sound + Other sound… Server notifications app not installed Please contact the administrator of Battery settings diff --git a/app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt b/app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt index de3f9ce826d..d35d2f0f19a 100644 --- a/app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt +++ b/app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt @@ -83,6 +83,7 @@ class SettingsViewModelTest { private lateinit var context: Context private val repository = FakeSettingsRepository() private val accountRemover = mock() + private val notificationSoundUpdater = mock() private var deviceState = DEVICE_STATE @Before @@ -132,6 +133,7 @@ class SettingsViewModelTest { settingsRepository = repository, logsRepository = logsRepository, deviceStateReader = mock { on { read() } doAnswer { deviceState } }, + notificationSoundUpdater = notificationSoundUpdater, accountRemover = accountRemover, workManager = workManager, logger = mock(), @@ -387,6 +389,33 @@ class SettingsViewModelTest { assertEquals("60", privacy.screenLockTimeout) } + @Test + fun `changed notification sound is shown`() { + whenever(notificationSoundUpdater.update(NotificationSound.CALL, SOUND_URI)) doAnswer { + deviceState = DEVICE_STATE.copy(callRingtone = RingtoneState.Custom("Ring", SOUND_URI)) + true + } + val viewModel = createViewModel() + + viewModel.setNotificationSound(NotificationSound.CALL, SOUND_URI) + dispatcher.scheduler.advanceUntilIdle() + + verify(notificationSoundUpdater).update(NotificationSound.CALL, SOUND_URI) + assertEquals(RingtoneState.Custom("Ring", SOUND_URI), viewModel.uiState.value.notifications.callRingtone) + } + + @Test + fun `failed notification sound change shows an error`() = + runTest(dispatcher) { + whenever(notificationSoundUpdater.update(NotificationSound.MESSAGE, null)) doReturn false + val viewModel = createViewModel() + + viewModel.setNotificationSound(NotificationSound.MESSAGE, null) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals(SettingsEvent.ShowMessage(R.string.nc_common_error_sorry), viewModel.events.first()) + } + @Test fun `cancelled certificate choice keeps the stored certificate`() { val viewModel = createViewModel(user.copy(clientCertificate = "alias")) @@ -471,6 +500,7 @@ class SettingsViewModelTest { private const val USER_ID = 1L private const val NO_PROXY = "No proxy" private const val TIMEOUT_MS = 1000L + private const val SOUND_URI = "content://media/internal/audio/media/1" private val DEVICE_STATE = DeviceState( isGooglePlayServicesAvailable = true, hasEmbeddedDistributor = false,