From 915a9665ed4f178903121a2dd3fa9c5746b208c7 Mon Sep 17 00:00:00 2001 From: Marcel Hibbe Date: Mon, 16 Nov 2026 21:24:52 +0100 Subject: [PATCH 1/5] refactor(settings): migrate settings screen to Compose and coroutines Replace the view based SettingsActivity with a Compose screen backed by SettingsViewModel, which exposes a single StateFlow and one-off events. Server calls move to SettingsRepository using NcApiCoroutines, device state is read off the main thread by DeviceStateReader, and the account is observed via UserManager.userFlow instead of LiveData and RxJava. - Replace SetPhoneNumberDialogFragment and the MaterialAlertDialogs with Compose dialogs; the phone number dialog now shows the error instead of closing - Request permissions with Activity Result APIs - Show the intended "wrong account" message for servers without Talk - Remove the now unused read/typing privacy preferences, blinkDrawable, ContactAddressBookWorker.checkPermission and unused strings - Add SettingsViewModel unit tests Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marcel Hibbe --- .../com/nextcloud/talk/api/NcApiCoroutines.kt | 9 + .../talk/dagger/modules/RepositoryModule.kt | 6 + .../talk/dagger/modules/UtilsModule.kt | 4 + .../talk/jobs/ContactAddressBookWorker.kt | 44 +- .../talk/settings/DeviceStateReader.kt | 90 + .../talk/settings/SettingsActivity.kt | 1823 ++--------------- .../talk/settings/SettingsUiState.kt | 146 ++ .../talk/settings/SettingsViewModel.kt | 622 ++++++ .../talk/settings/data/SettingsRepository.kt | 24 + .../settings/data/SettingsRepositoryImpl.kt | 72 + .../settings/ui/SettingsAccountSection.kt | 214 ++ .../talk/settings/ui/SettingsComponents.kt | 244 +++ .../talk/settings/ui/SettingsDialogs.kt | 221 ++ .../settings/ui/SettingsGeneralSections.kt | 166 ++ .../ui/SettingsNotificationsSection.kt | 265 +++ .../settings/ui/SettingsPrivacySection.kt | 109 + .../talk/settings/ui/SettingsProxySection.kt | 134 ++ .../talk/settings/ui/SettingsScreen.kt | 214 ++ .../ui/dialog/SetPhoneNumberDialogFragment.kt | 103 - .../com/nextcloud/talk/utils/DrawableUtils.kt | 28 - .../utils/preferences/AppPreferences.java | 8 - .../utils/preferences/AppPreferencesImpl.kt | 26 - app/src/main/res/layout/activity_settings.xml | 1127 ---------- .../res/layout/dialog_set_phone_number.xml | 29 - app/src/main/res/values/strings.xml | 3 - .../talk/settings/SettingsViewModelTest.kt | 359 ++++ 26 files changed, 3096 insertions(+), 2994 deletions(-) create mode 100644 app/src/main/java/com/nextcloud/talk/settings/DeviceStateReader.kt create mode 100644 app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt create mode 100644 app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt create mode 100644 app/src/main/java/com/nextcloud/talk/settings/data/SettingsRepository.kt create mode 100644 app/src/main/java/com/nextcloud/talk/settings/data/SettingsRepositoryImpl.kt create mode 100644 app/src/main/java/com/nextcloud/talk/settings/ui/SettingsAccountSection.kt create mode 100644 app/src/main/java/com/nextcloud/talk/settings/ui/SettingsComponents.kt create mode 100644 app/src/main/java/com/nextcloud/talk/settings/ui/SettingsDialogs.kt create mode 100644 app/src/main/java/com/nextcloud/talk/settings/ui/SettingsGeneralSections.kt create mode 100644 app/src/main/java/com/nextcloud/talk/settings/ui/SettingsNotificationsSection.kt create mode 100644 app/src/main/java/com/nextcloud/talk/settings/ui/SettingsPrivacySection.kt create mode 100644 app/src/main/java/com/nextcloud/talk/settings/ui/SettingsProxySection.kt create mode 100644 app/src/main/java/com/nextcloud/talk/settings/ui/SettingsScreen.kt delete mode 100644 app/src/main/java/com/nextcloud/talk/ui/dialog/SetPhoneNumberDialogFragment.kt delete mode 100644 app/src/main/res/layout/activity_settings.xml delete mode 100644 app/src/main/res/layout/dialog_set_phone_number.xml create mode 100644 app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt diff --git a/app/src/main/java/com/nextcloud/talk/api/NcApiCoroutines.kt b/app/src/main/java/com/nextcloud/talk/api/NcApiCoroutines.kt index 82b7e5a112c..46cac207bcb 100644 --- a/app/src/main/java/com/nextcloud/talk/api/NcApiCoroutines.kt +++ b/app/src/main/java/com/nextcloud/talk/api/NcApiCoroutines.kt @@ -629,6 +629,15 @@ interface NcApiCoroutines { @GET suspend fun getUserProfile(@Header("Authorization") authorization: String, @Url url: String): UserProfileOverall + @FormUrlEncoded + @PUT + suspend fun setUserData( + @Header("Authorization") authorization: String, + @Url url: String, + @Field("key") key: String, + @Field("value") value: String + ): GenericOverall + @GET suspend fun getReminder(@Header("Authorization") authorization: String, @Url url: String): ReminderOverall diff --git a/app/src/main/java/com/nextcloud/talk/dagger/modules/RepositoryModule.kt b/app/src/main/java/com/nextcloud/talk/dagger/modules/RepositoryModule.kt index 5feb861546a..38611c91c24 100644 --- a/app/src/main/java/com/nextcloud/talk/dagger/modules/RepositoryModule.kt +++ b/app/src/main/java/com/nextcloud/talk/dagger/modules/RepositoryModule.kt @@ -66,6 +66,8 @@ import com.nextcloud.talk.repositories.reactions.ReactionsRepository import com.nextcloud.talk.repositories.reactions.ReactionsRepositoryImpl import com.nextcloud.talk.repositories.unifiedsearch.UnifiedSearchRepository import com.nextcloud.talk.repositories.unifiedsearch.UnifiedSearchRepositoryImpl +import com.nextcloud.talk.settings.data.SettingsRepository +import com.nextcloud.talk.settings.data.SettingsRepositoryImpl import com.nextcloud.talk.shareditems.repositories.SharedItemsRepository import com.nextcloud.talk.shareditems.repositories.SharedItemsRepositoryImpl import com.nextcloud.talk.threadsoverview.data.ThreadsRepository @@ -225,6 +227,10 @@ class RepositoryModule { fun provideContactsRepository(ncApiCoroutines: NcApiCoroutines): ContactsRepository = ContactsRepositoryImpl(ncApiCoroutines) + @Provides + fun provideSettingsRepository(ncApiCoroutines: NcApiCoroutines): SettingsRepository = + SettingsRepositoryImpl(ncApiCoroutines) + @Provides fun provideConversationCreationRepository(ncApiCoroutines: NcApiCoroutines): ConversationCreationRepository = ConversationCreationRepositoryImpl(ncApiCoroutines) diff --git a/app/src/main/java/com/nextcloud/talk/dagger/modules/UtilsModule.kt b/app/src/main/java/com/nextcloud/talk/dagger/modules/UtilsModule.kt index 6d5723bd16f..ee7a87c1326 100644 --- a/app/src/main/java/com/nextcloud/talk/dagger/modules/UtilsModule.kt +++ b/app/src/main/java/com/nextcloud/talk/dagger/modules/UtilsModule.kt @@ -8,6 +8,7 @@ package com.nextcloud.talk.dagger.modules import android.content.Context +import androidx.work.WorkManager import com.nextcloud.talk.logger.FileLogHandler import com.nextcloud.talk.logger.Level import com.nextcloud.talk.logger.Logger @@ -40,6 +41,9 @@ class UtilsModule { @Reusable fun provideMessageUtils(context: Context): MessageUtils = MessageUtils(context) + @Provides + fun provideWorkManager(context: Context): WorkManager = WorkManager.getInstance(context) + @Provides @Singleton fun provideLoggerImpl(context: Context): LoggerImpl { diff --git a/app/src/main/java/com/nextcloud/talk/jobs/ContactAddressBookWorker.kt b/app/src/main/java/com/nextcloud/talk/jobs/ContactAddressBookWorker.kt index 30abc74e850..1008f2400b4 100644 --- a/app/src/main/java/com/nextcloud/talk/jobs/ContactAddressBookWorker.kt +++ b/app/src/main/java/com/nextcloud/talk/jobs/ContactAddressBookWorker.kt @@ -9,7 +9,6 @@ package com.nextcloud.talk.jobs import android.Manifest import android.accounts.Account import android.accounts.AccountManager -import android.app.Activity import android.content.ContentProviderOperation import android.content.Context import android.content.OperationApplicationException @@ -454,7 +453,6 @@ class ContactAddressBookWorker(val context: Context, workerParameters: WorkerPar companion object { const val TAG = "ContactAddressBook" - const val REQUEST_PERMISSION = 231 const val KEY_FORCE = "KEY_FORCE" const val DELETE_ALL = "DELETE_ALL" private const val HTTP_CODE_TOO_MANY_REQUESTS: Int = 429 @@ -472,37 +470,21 @@ class ContactAddressBookWorker(val context: Context, workerParameters: WorkerPar } } - fun checkPermission(activity: Activity, context: Context): Boolean { - if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CONTACTS) != - PackageManager.PERMISSION_GRANTED || - ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) != - PackageManager.PERMISSION_GRANTED - ) { - activity.requestPermissions( - arrayOf(Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS), - REQUEST_PERMISSION - ) - return false - } else { - WorkManager - .getInstance() - .enqueue( - OneTimeWorkRequest.Builder(ContactAddressBookWorker::class.java) - .setInputData(Data.Builder().putBoolean(KEY_FORCE, true).build()) - .build() - ) - return true - } + /** Synchronizes the address book now, regardless of when it was synchronized last. */ + fun syncNow(workManager: WorkManager) { + workManager.enqueue( + OneTimeWorkRequest.Builder(ContactAddressBookWorker::class.java) + .setInputData(Data.Builder().putBoolean(KEY_FORCE, true).build()) + .build() + ) } - fun deleteAll() { - WorkManager - .getInstance() - .enqueue( - OneTimeWorkRequest.Builder(ContactAddressBookWorker::class.java) - .setInputData(Data.Builder().putBoolean(DELETE_ALL, true).build()) - .build() - ) + fun deleteAll(workManager: WorkManager) { + workManager.enqueue( + OneTimeWorkRequest.Builder(ContactAddressBookWorker::class.java) + .setInputData(Data.Builder().putBoolean(DELETE_ALL, true).build()) + .build() + ) } } } diff --git a/app/src/main/java/com/nextcloud/talk/settings/DeviceStateReader.kt b/app/src/main/java/com/nextcloud/talk/settings/DeviceStateReader.kt new file mode 100644 index 00000000000..9cad25dd89d --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/DeviceStateReader.kt @@ -0,0 +1,90 @@ +/* + * 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.KeyguardManager +import android.app.NotificationManager +import android.content.Context +import android.media.RingtoneManager +import android.net.Uri +import android.os.Build +import androidx.annotation.WorkerThread +import com.nextcloud.talk.utils.ClosedInterfaceImpl +import com.nextcloud.talk.utils.NotificationUtils +import com.nextcloud.talk.utils.UnifiedPushUtils +import com.nextcloud.talk.utils.permissions.PlatformPermissionUtil +import com.nextcloud.talk.utils.power.PowerManagerUtils +import com.nextcloud.talk.utils.preferences.AppPreferences +import org.unifiedpush.android.connector.UnifiedPush +import javax.inject.Inject + +/** State of the device and its system settings that the settings screen shows. */ +data class DeviceState( + val isGooglePlayServicesAvailable: Boolean, + val hasEmbeddedDistributor: Boolean, + val externalDistributorCount: Int, + val acknowledgedDistributor: String?, + val notificationPermissionGranted: Boolean?, + val batteryOptimizationIgnored: Boolean, + val fullScreenIntentGranted: Boolean?, + val callRingtone: RingtoneState, + val messageRingtone: RingtoneState, + val isKeyguardSecure: Boolean +) + +/** Reads the [DeviceState], which can change any time the app is in the background. */ +class DeviceStateReader @Inject constructor( + private val context: Context, + private val appPreferences: AppPreferences, + private val platformPermissionUtil: PlatformPermissionUtil +) { + @WorkerThread + fun read(): DeviceState = + DeviceState( + isGooglePlayServicesAvailable = ClosedInterfaceImpl().isGooglePlayServicesAvailable, + hasEmbeddedDistributor = UnifiedPushUtils.hasEmbeddedDistributor(context), + externalDistributorCount = UnifiedPushUtils.getExternalDistributors(context).size, + acknowledgedDistributor = UnifiedPush.getAckDistributor(context), + notificationPermissionGranted = readNotificationPermission(), + batteryOptimizationIgnored = PowerManagerUtils().isIgnoringBatteryOptimizations(), + fullScreenIntentGranted = readFullScreenIntentPermission(), + callRingtone = readRingtone( + NotificationUtils.isCallsNotificationChannelEnabled(context), + NotificationUtils.getCallRingtoneUri(context, appPreferences) + ), + messageRingtone = readRingtone( + NotificationUtils.isMessagesNotificationChannelEnabled(context), + NotificationUtils.getMessageRingtoneUri(context, appPreferences) + ), + isKeyguardSecure = context.getSystemService(KeyguardManager::class.java).isKeyguardSecure + ) + + private fun readNotificationPermission(): Boolean? = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + platformPermissionUtil.isPostNotificationsPermissionGranted() + } else { + null + } + + private fun readFullScreenIntentPermission(): Boolean? = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + context.getSystemService(NotificationManager::class.java).canUseFullScreenIntent() + } else { + null + } + + private fun readRingtone(channelEnabled: Boolean, ringtoneUri: Uri?): RingtoneState = + when { + !channelEnabled -> RingtoneState.Disabled + 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 + } +} 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 a78db86faaa..eff10417f24 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt @@ -11,134 +11,73 @@ package com.nextcloud.talk.settings import android.Manifest -import android.animation.Animator -import android.animation.AnimatorListenerAdapter -import android.annotation.SuppressLint -import android.app.KeyguardManager -import android.app.NotificationManager -import android.content.Context -import android.content.DialogInterface +import android.content.ActivityNotFoundException import android.content.Intent -import android.content.pm.PackageManager -import android.graphics.PorterDuff -import android.media.RingtoneManager -import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.Settings import android.security.KeyChain -import android.text.TextUtils import android.util.Log -import android.view.View import android.view.WindowManager import android.widget.Toast +import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts -import androidx.appcompat.app.AlertDialog -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.mutableStateOf -import androidx.core.content.ContextCompat -import androidx.core.content.res.ResourcesCompat -import androidx.core.graphics.drawable.toDrawable +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SnackbarHostState import androidx.core.net.toUri -import androidx.core.view.ViewCompat +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.lifecycleScope -import androidx.work.OneTimeWorkRequest -import com.nextcloud.talk.utils.AppTasks -import com.nextcloud.talk.utils.bundle.BundleKeys -import com.nextcloud.talk.utils.setExpeditedIfSupported -import androidx.work.WorkInfo -import androidx.work.WorkManager +import androidx.lifecycle.repeatOnLifecycle import autodagger.AutoInjector -import com.google.android.material.dialog.MaterialAlertDialogBuilder -import com.google.android.material.snackbar.Snackbar -import com.google.android.material.textfield.TextInputLayout -import com.nextcloud.android.common.ui.theme.utils.ColorRole import com.nextcloud.talk.BuildConfig import com.nextcloud.talk.R import com.nextcloud.talk.activities.BaseActivity -import com.nextcloud.talk.api.NcApi -import com.nextcloud.talk.api.NcApiCoroutines import com.nextcloud.talk.application.NextcloudTalkApplication import com.nextcloud.talk.application.NextcloudTalkApplication.Companion.setAppTheme -import com.nextcloud.talk.conversationlist.ConversationsListActivity -import com.nextcloud.talk.conversationlist.ConversationsListActivity.Companion.NOTIFICATION_WARNING_DATE_NOT_SET -import com.nextcloud.talk.data.network.NetworkMonitor +import com.nextcloud.talk.dagger.modules.assistedViewModels import com.nextcloud.talk.data.user.model.User -import com.nextcloud.talk.databinding.ActivitySettingsBinding import com.nextcloud.talk.diagnosis.DiagnosisActivity import com.nextcloud.talk.diagnosis.buildDiagnosisReportText import com.nextcloud.talk.diagnosis.showShareReportDialog import com.nextcloud.talk.errorhandling.saveLogsAsZip -import com.nextcloud.talk.logger.Level import com.nextcloud.talk.logger.LogsRepository import com.nextcloud.talk.logger.ui.LogsActivity -import com.nextcloud.talk.jobs.AccountRemovalWorker -import com.nextcloud.talk.jobs.CapabilitiesSyncWorker -import com.nextcloud.talk.jobs.ContactAddressBookWorker -import com.nextcloud.talk.jobs.ContactAddressBookWorker.Companion.checkPermission -import com.nextcloud.talk.jobs.ContactAddressBookWorker.Companion.deleteAll -import com.nextcloud.talk.models.json.generic.GenericOverall -import com.nextcloud.talk.models.json.userprofile.UserProfileOverall import com.nextcloud.talk.profile.ProfileActivity -import com.nextcloud.talk.ui.dialog.SetPhoneNumberDialogFragment -import com.nextcloud.talk.utils.ApiUtils -import com.nextcloud.talk.utils.CapabilitiesUtil -import com.nextcloud.talk.utils.ClosedInterfaceImpl -import com.nextcloud.talk.utils.DisplayUtils -import com.nextcloud.talk.utils.DrawableUtils +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.utils.AppTasks import com.nextcloud.talk.utils.LoggingUtils.sendMailWithAttachment import com.nextcloud.talk.utils.NotificationUtils -import com.nextcloud.talk.utils.NotificationUtils.getCallRingtoneUri -import com.nextcloud.talk.utils.NotificationUtils.getMessageRingtoneUri -import com.nextcloud.talk.utils.SecurityUtils -import com.nextcloud.talk.utils.SpreedFeatures import com.nextcloud.talk.utils.UnifiedPushUtils +import com.nextcloud.talk.utils.bundle.BundleKeys import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_SCROLL_TO_NOTIFICATION_CATEGORY -import com.nextcloud.talk.utils.permissions.PlatformPermissionUtil -import com.nextcloud.talk.utils.power.PowerManagerUtils -import com.nextcloud.talk.utils.preferences.AppPreferencesImpl -import com.nextcloud.talk.utils.singletons.ApplicationWideMessageHolder -import io.reactivex.Observer -import io.reactivex.android.schedulers.AndroidSchedulers -import io.reactivex.disposables.Disposable -import io.reactivex.schedulers.Schedulers -import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withContext -import okhttp3.MediaType.Companion.toMediaTypeOrNull -import okhttp3.RequestBody.Companion.toRequestBody -import org.unifiedpush.android.connector.UnifiedPush -import retrofit2.HttpException import java.net.URI import java.net.URISyntaxException -import java.util.Locale import javax.inject.Inject -@Suppress("LargeClass", "TooManyFunctions") @AutoInjector(NextcloudTalkApplication::class) -class SettingsActivity : - BaseActivity(), - SetPhoneNumberDialogFragment.SetPhoneNumberDialogClickListener { - private lateinit var binding: ActivitySettingsBinding +class SettingsActivity : BaseActivity() { @Inject - lateinit var ncApi: NcApi + lateinit var viewModelFactory: SettingsViewModel.Factory @Inject - lateinit var networkMonitor: NetworkMonitor + lateinit var logsRepository: LogsRepository - @Inject - lateinit var ncApiCoroutines: NcApiCoroutines + private lateinit var user: User - @Inject - lateinit var platformPermissionUtil: PlatformPermissionUtil + private val viewModel: SettingsViewModel by assistedViewModels { + viewModelFactory.build(user, intent.getBooleanExtra(KEY_SCROLL_TO_NOTIFICATION_CATEGORY, false)) + } - @Inject - lateinit var logsRepository: LogsRepository + private val snackbarHostState = SnackbarHostState() private val saveZipLauncher = registerForActivityResult(ActivityResultContracts.CreateDocument("application/zip")) { uri -> @@ -152,1615 +91,221 @@ class SettingsActivity : } } - private var currentUser: User? = null - private var credentials: String? = null - private lateinit var proxyTypeFlow: Flow - private lateinit var proxyCredentialFlow: Flow - private lateinit var screenSecurityFlow: Flow - private lateinit var screenLockFlow: Flow - private lateinit var screenLockTimeoutFlow: Flow - private lateinit var themeFlow: Flow - private lateinit var readPrivacyFlow: Flow - private lateinit var typingStatusFlow: Flow - private lateinit var phoneBookIntegrationFlow: Flow - private var profileQueryDisposable: Disposable? = null - private var dbQueryDisposable: Disposable? = null - private var openedByNotificationWarning: Boolean = false - private var isOnline: MutableState = mutableStateOf(false) - - @SuppressLint("StringFormatInvalid") - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - NextcloudTalkApplication.sharedApplication!!.componentApplication.inject(this) - setCurrentUser(setUpBoundUserOrFinish() ?: return) - networkMonitor.isOnlineLiveData.observe(this) { online -> - isOnline.value = online - handleNetworkChange(isOnline.value) - } - - binding = ActivitySettingsBinding.inflate(layoutInflater) - setupActionBar() - setContentView(binding.root) - initSystemBars() - - binding.avatarImage.let { ViewCompat.setTransitionName(it, "userAvatar.transitionTag") } - - handleIntent(intent) - - setupLicenceSetting(isOnline.value) - - binding.settingsScreenLockSummary.text = String.format( - Locale.getDefault(), - resources!!.getString(R.string.nc_settings_screen_lock_desc), - resources!!.getString(R.string.nc_app_product_name) - ) - - setupDiagnosis() - - setupPrivacyUrl(isOnline.value) - setupSourceCodeUrl(isOnline.value) - - binding.settingsVersionSummary.text = String.format("v" + BuildConfig.VERSION_NAME) - - setupPhoneBookIntegration(isOnline.value) - - setupClientCertView() - showSetupClientCertView(isOnline.value) - } - - private fun handleNetworkChange(isOnline: Boolean) { - setupLicenceSetting(isOnline) - setupPrivacyUrl(isOnline) - setupSourceCodeUrl(isOnline) - setupPhoneBookIntegration(isOnline) - setupCheckables(isOnline) - showSetupClientCertView(isOnline) - } - - private fun handleIntent(intent: Intent) { - val extras: Bundle? = intent.extras - openedByNotificationWarning = extras?.getBoolean(KEY_SCROLL_TO_NOTIFICATION_CATEGORY) ?: false - } - - override fun onResume() { - super.onResume() - supportActionBar?.show() - dispose(null) - - binding.logsSubtitle.setText( - when { - logsRepository.minimumLevel == Level.NONE -> R.string.nc_logs_logging_disabled_note - logsRepository.minimumLevel <= Level.DEBUG -> R.string.nc_logs_advanced_logging_enabled_warning - else -> R.string.nc_logs_logging_enabled + private val notificationPermissionLauncher = + registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + if (granted) { + viewModel.refreshDeviceState() + } else { + openSystemSettings( + Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS) + .putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID) + ) } - ) - - loadCapabilitiesAndUpdateSettings(isOnline.value) - - binding.settingsVersion.setOnClickListener { - sendLogs() - } - - if (!TextUtils.isEmpty(currentUser!!.clientCertificate)) { - binding.settingsClientCertTitle.setText(R.string.nc_client_cert_change) - } else { - binding.settingsClientCertTitle.setText(R.string.nc_client_cert_setup) } - setupCheckables(isOnline.value) - setupEcosystemSetting() - setupScreenLockSetting() - setupNotificationSettings() - setupProxyTypeSettings() - setupProxyCredentialSettings() - registerChangeListeners() - - if (currentUser != null) { - binding.domainText.text = currentUser!!.baseUrl!!.toUri().host - setupServerAgeWarning() - if (currentUser!!.displayName != null) { - binding.nameText.text = currentUser!!.displayName - } - DisplayUtils.loadAvatarImage(currentUser, binding.avatarImage, false) - - setupProfileQueryDisposable() - - binding.settingsRemoveAccount.setOnClickListener { - showRemoveAccountWarning() + private val contactsPermissionLauncher = + registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { results -> + if (results.isNotEmpty() && results.values.all { it }) { + viewModel.enablePhoneBookIntegration() + } else { + viewModel.onContactsPermissionDenied() } } - setupMessageView() - - binding.settingsName.visibility = View.VISIBLE - binding.settingsName.setOnClickListener { - val intent = Intent(this, ProfileActivity::class.java) - intent.putExtra(BundleKeys.KEY_INTERNAL_USER_ID, currentUser!!.id) - startActivity(intent) - } - - themeTitles() - themeSwitchPreferences() - - if (openedByNotificationWarning) { - scrollToNotificationCategory() - } - } - - private fun setupEcosystemSetting() { - if (getResources().getBoolean(R.bool.is_branded_client)) { - binding.settingsShowEcosystem.visibility = View.GONE - } else { - binding.settingsShowEcosystem.visibility = View.VISIBLE - } - } - - @Suppress("MagicNumber") - private fun scrollToNotificationCategory() { - binding.scrollView.post { - val scrollViewLocation = IntArray(2) - val targetLocation = IntArray(2) - binding.scrollView.getLocationOnScreen(scrollViewLocation) - binding.settingsNotificationsCategory.getLocationOnScreen(targetLocation) - val offset = targetLocation[1] - scrollViewLocation[1] - binding.scrollView.scrollBy(0, offset) - } - } - private fun loadCapabilitiesAndUpdateSettings(isOnline: Boolean) { - val capabilitiesWork = OneTimeWorkRequest.Builder(CapabilitiesSyncWorker::class.java) - .setExpeditedIfSupported() - .build() - WorkManager.getInstance(context).enqueue(capabilitiesWork) + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + NextcloudTalkApplication.sharedApplication!!.componentApplication.inject(this) + user = setUpBoundUserOrFinish() ?: return - WorkManager.getInstance(context).getWorkInfoByIdLiveData(capabilitiesWork.id) - .observe(this) { workInfo -> - if (workInfo?.state == WorkInfo.State.SUCCEEDED && reloadCurrentUser()) { - setupCheckables(isOnline) - } + val colorScheme = viewThemeUtils.getColorScheme(this) + val callbacks = createCallbacks() + setContent { + MaterialTheme(colorScheme = colorScheme) { + val state = viewModel.uiState.collectAsStateWithLifecycle().value + SettingsScreen(state = state, callbacks = callbacks, snackbarHostState = snackbarHostState) } - } - - private fun setupActionBar() { - setSupportActionBar(binding.settingsToolbar) - binding.settingsToolbar.setNavigationOnClickListener { - onBackPressedDispatcher.onBackPressed() } - supportActionBar?.setDisplayHomeAsUpEnabled(true) - supportActionBar?.setDisplayShowHomeEnabled(true) - supportActionBar?.setIcon(resources!!.getColor(android.R.color.transparent, null).toDrawable()) - supportActionBar?.title = context.getString(R.string.nc_settings) - viewThemeUtils.material.themeToolbar(binding.settingsToolbar) - } - private fun setCurrentUser(user: User) { - currentUser = user - credentials = ApiUtils.getCredentials(user.username, user.token) - } - - /** - * Loads the account of this screen again, e.g. for updated capabilities. Finishes the activity and returns false - * if it was removed meanwhile. - */ - private fun reloadCurrentUser(): Boolean { - val user = runBlocking { userManager.getUserWithInternalId(resolveUserIdFromIntent()) } ?: run { - finish() - return false - } - setCurrentUser(user) - return true + collectEvents() + applySecureWindowFlag() } - private fun setupPhoneBookIntegration(isOnline: Boolean) { - if (CapabilitiesUtil.hasSpreedFeatureCapability( - currentUser?.capabilities?.spreedCapability, - SpreedFeatures.PHONEBOOK_SEARCH - ) && - isOnline - ) { - binding.settingsPhoneBookIntegration.visibility = View.VISIBLE - } else { - binding.settingsPhoneBookIntegration.visibility = View.GONE - } - } - - private fun setupNotificationSettings() { - setupUnifiedPushSettings() - setupNotificationSoundsSettings() - setupNotificationPermissionSettings() - setupFullScreenIntentPermissionSetting() - setupServerNotificationAppCheck() - } - - private fun showUnifiedPushToggle(): Boolean = - UnifiedPushUtils.getExternalDistributors(this).isNotEmpty() && - runBlocking { userManager.getUsers() }.all { it.hasWebPushCapability } - - private fun setupUnifiedPushSettings() { - // If any user doesn't support web push, or there is no UnifiedPush - // service (distributor) available: hide the feature. - // - // We could provide the feature as soon as one user supports web push, - // but for simplicity (UX & dev), and at least in a first step: - // we require that all the users support webpush - if (!showUnifiedPushToggle()) { - binding.settingsUnifiedpush.visibility = View.GONE - binding.settingsUnifiedpushService.visibility = View.GONE - } else { - val nDistrib = UnifiedPushUtils.getExternalDistributors(context).size - binding.settingsUnifiedpush.visibility = View.VISIBLE - binding.settingsUnifiedpushSwitch.isChecked = appPreferences.useUnifiedPush - binding.settingsUnifiedpush.setOnClickListener { - val checked = !appPreferences.useUnifiedPush - appPreferences.useUnifiedPush = checked - binding.settingsUnifiedpushSwitch.isChecked = checked - setupNotificationPermissionSettings() - setupUnifiedPushServiceSelectionVisibility(nDistrib) - if (checked) { - UnifiedPushUtils.useDefaultDistributor(this) { distrib -> - Log.d(TAG, "Registered to $distrib") - binding.settingsUnifiedpushServiceSummary.text = distrib - } - } else { - UnifiedPushUtils.disableExternalUnifiedPush(this) - } - } - // To use non-default service - binding.settingsUnifiedpushService.setOnClickListener { - UnifiedPushUtils.pickDistributor(this) { distrib -> - Log.d(TAG, "Registered to $distrib") - binding.settingsUnifiedpushServiceSummary.text = distrib - } - } - // For the init only - if (binding.settingsUnifiedpushServiceSummary.text.isBlank()) { - binding.settingsUnifiedpushServiceSummary.text = UnifiedPush.getAckDistributor(context) ?: "" - } - setupUnifiedPushServiceSelectionVisibility(nDistrib) - } - } - - private fun setupUnifiedPushServiceSelectionVisibility(nDistrib: Int) { - // We offer the option to use non-default service, only if UnifiedPush - // is enabled and there are more than one service - if (binding.settingsUnifiedpushSwitch.isChecked && nDistrib > 1) { - binding.settingsUnifiedpushService.visibility = View.VISIBLE - } else { - binding.settingsUnifiedpushService.visibility = View.GONE - } + override fun onResume() { + super.onResume() + viewModel.onResume() } - @SuppressLint("StringFormatInvalid") @Suppress("LongMethod") - private fun setupNotificationPermissionSettings() { - if (ClosedInterfaceImpl().isGooglePlayServicesAvailable || - appPreferences.useUnifiedPush || - UnifiedPushUtils.hasEmbeddedDistributor(context) - ) { - binding.settingsPushOnlyWrapper.visibility = View.VISIBLE - binding.settingsGplayNotAvailable.visibility = View.GONE - binding.settingsPushNotAvailable.visibility = View.GONE - - setTroubleshootingClickListenersIfNecessary() - - if (PowerManagerUtils().isIgnoringBatteryOptimizations()) { - binding.batteryOptimizationIgnored.text = - resources!!.getString(R.string.battery_optimization_ignored) - binding.batteryOptimizationIgnored.setTextColor( - resources.getColor(R.color.high_emphasis_text, null) - ) - } else { - binding.batteryOptimizationIgnored.text = - resources!!.getString(R.string.battery_optimization_not_ignored) - binding.batteryOptimizationIgnored.setTextColor(resources.getColor(R.color.nc_darkRed, null)) - - if (openedByNotificationWarning) { - DrawableUtils.blinkDrawable(binding.settingsBatteryOptimizationWrapper.background) - } - - binding.settingsBatteryOptimizationWrapper.setOnClickListener { - val dialogText = String.format( - context.resources.getString(R.string.nc_ignore_battery_optimization_dialog_text), - context.resources.getString(R.string.nc_app_name) - ) - - val dialogBuilder = MaterialAlertDialogBuilder(this) - .setTitle(R.string.nc_ignore_battery_optimization_dialog_title) - .setMessage(dialogText) - .setPositiveButton(R.string.nc_ok) { _, _ -> - startActivity( - Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS) - ) - } - .setNegativeButton(R.string.nc_common_dismiss, null) - viewThemeUtils.dialog.colorMaterialAlertDialogBackground(this, dialogBuilder) - val dialog = dialogBuilder.show() - viewThemeUtils.platform.colorTextButtons( - dialog.getButton(AlertDialog.BUTTON_POSITIVE), - dialog.getButton(AlertDialog.BUTTON_NEGATIVE) - ) - } - } - - // handle notification permission on API level >= 33 - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - if (platformPermissionUtil.isPostNotificationsPermissionGranted()) { - binding.ncDiagnosisNotificationPermissionSubtitle.text = - resources.getString(R.string.nc_settings_notifications_granted) - binding.ncDiagnosisNotificationPermissionSubtitle.setTextColor( - resources.getColor(R.color.high_emphasis_text, null) - ) - binding.settingsCallSound.isEnabled = true - binding.settingsCallSound.alpha = ENABLED_ALPHA - binding.settingsMessageSound.isEnabled = true - binding.settingsMessageSound.alpha = ENABLED_ALPHA + private fun createCallbacks() = + SettingsScreenCallbacks( + onProfileClick = { startActivity(intentForAccount(ProfileActivity::class.java)) }, + onAccountMessageShown = viewModel::dismissAccountMessage, + onRemoveAccount = viewModel::removeAccount, + onThemeChange = { theme -> + viewModel.setTheme(theme) + setAppTheme(theme) + }, + onShowEcosystemChange = viewModel::setShowEcosystem, + onUnifiedPushChange = ::setUseUnifiedPush, + onPickDistributor = { + UnifiedPushUtils.pickDistributor(this) { distributor -> + distributor?.let { runOnUiThread { viewModel.onDistributorChanged(it) } } + } + }, + onRequestNotificationPermission = { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) + } + }, + onOpenSystemSettings = ::openSystemSettings, + onOpenDiagnosis = { startActivity(intentForAccount(DiagnosisActivity::class.java)) }, + onShowNotificationWarningChange = viewModel::setShowNotificationWarning, + onScreenLockChange = viewModel::setScreenLock, + onScreenLockTimeoutChange = viewModel::setScreenLockTimeout, + onScreenSecurityChange = viewModel::setScreenSecurity, + onIncognitoKeyboardChange = viewModel::setIncognitoKeyboard, + onPhoneBookIntegrationChange = { enabled -> + if (enabled) { + contactsPermissionLauncher.launch(CONTACTS_PERMISSIONS) } else { - binding.ncDiagnosisNotificationPermissionSubtitle.text = - resources.getString(R.string.nc_settings_notifications_declined) - binding.ncDiagnosisNotificationPermissionSubtitle.setTextColor( - resources.getColor(R.color.nc_darkRed, null) - ) - - if (openedByNotificationWarning) { - DrawableUtils.blinkDrawable(binding.settingsNotificationsPermissionWrapper.background) - } - - binding.settingsCallSound.isEnabled = false - binding.settingsCallSound.alpha = DISABLED_ALPHA - binding.settingsMessageSound.isEnabled = false - binding.settingsMessageSound.alpha = DISABLED_ALPHA - - binding.settingsNotificationsPermissionWrapper.setOnClickListener { - requestPermissions( - arrayOf(Manifest.permission.POST_NOTIFICATIONS), - ConversationsListActivity.REQUEST_POST_NOTIFICATIONS_PERMISSION - ) - } - } - } else { - binding.settingsNotificationsPermissionWrapper.visibility = View.GONE - } - } else { - binding.settingsPushOnlyWrapper.visibility = View.GONE - // Shows "UnifiedPush is disabled and Google Play services are not available." if we offer UnifiedPush - // Else "Google Play services are not available" (if any account doesn't support webpush yet, or no - // distrib are installed) - if (showUnifiedPushToggle()) { - binding.settingsGplayNotAvailable.visibility = View.GONE - binding.settingsPushNotAvailable.visibility = View.VISIBLE - } else { - binding.settingsGplayNotAvailable.visibility = View.VISIBLE - binding.settingsPushNotAvailable.visibility = View.GONE - } - } - } - - private fun setupFullScreenIntentPermissionSetting() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { - val notificationManager = getSystemService(NotificationManager::class.java) - if (notificationManager.canUseFullScreenIntent()) { - binding.fullScreenIntentPermissionSubtitle.text = - resources.getString(R.string.full_screen_intent_permission_granted) - binding.fullScreenIntentPermissionSubtitle.setTextColor( - resources.getColor(R.color.high_emphasis_text, null) - ) - } else { - binding.fullScreenIntentPermissionSubtitle.text = - resources.getString(R.string.full_screen_intent_permission_not_granted) - binding.fullScreenIntentPermissionSubtitle.setTextColor( - resources.getColor(R.color.nc_darkRed, null) - ) - - if (openedByNotificationWarning) { - DrawableUtils.blinkDrawable(binding.settingsFullScreenIntentWrapper.background) - } - } - binding.settingsFullScreenIntentWrapper.setOnClickListener { - val intent = Intent(Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT).apply { - data = "package:$packageName".toUri() + viewModel.disablePhoneBookIntegration() + } + }, + onReadStatusChange = viewModel::setReadStatusShared, + onTypingStatusChange = viewModel::setTypingStatusShared, + onPhoneNumberChange = viewModel::clearPhoneNumberError, + onSubmitPhoneNumber = viewModel::submitPhoneNumber, + onDismissPhoneNumberDialog = viewModel::dismissPhoneNumberDialog, + onOpenLogs = ::openLogs, + onShareReport = { + showShareReportDialog(this, userManager, appPreferences, logsRepository, saveZipLauncher) + }, + onMediaQualityChange = viewModel::setMediaQualityReduced, + onClientCertificateClick = ::chooseClientCertificate, + proxy = ProxyCallbacks( + onTypeChange = viewModel::setProxyType, + onHostChange = viewModel::setProxyHost, + onPortChange = viewModel::setProxyPort, + onUseCredentialsChange = viewModel::setProxyUseCredentials, + onUsernameChange = viewModel::setProxyUsername, + onPasswordChange = viewModel::setProxyPassword + ), + onVersionClick = { + if (resources.getBoolean(R.bool.nc_is_debug)) { + sendMailWithAttachment(this) } - startActivity(intent) - } - } else { - binding.settingsFullScreenIntentWrapper.visibility = View.GONE - } - } - - private fun setupNotificationSoundsSettings() { - if (NotificationUtils.isCallsNotificationChannelEnabled(this)) { - val callRingtoneUri = getCallRingtoneUri(context, (appPreferences)) - - binding.callsRingtone.setTextColor(resources.getColor(R.color.high_emphasis_text, null)) - binding.callsRingtone.text = getRingtoneName(context, callRingtoneUri) - } else { - binding.callsRingtone.setTextColor( - ResourcesCompat.getColor(context.resources, R.color.nc_darkRed, null) - ) - binding.callsRingtone.text = resources!!.getString(R.string.nc_common_disabled) - - if (openedByNotificationWarning) { - DrawableUtils.blinkDrawable(binding.settingsCallSound.background) - } - } - - if (NotificationUtils.isMessagesNotificationChannelEnabled(this)) { - val messageRingtoneUri = getMessageRingtoneUri(context, (appPreferences)) - binding.messagesRingtone.setTextColor(resources.getColor(R.color.high_emphasis_text, null)) - binding.messagesRingtone.text = getRingtoneName(context, messageRingtoneUri) - } else { - binding.messagesRingtone.setTextColor( - ResourcesCompat.getColor(context.resources, R.color.nc_darkRed, null) - ) - binding.messagesRingtone.text = resources!!.getString(R.string.nc_common_disabled) - - if (openedByNotificationWarning) { - DrawableUtils.blinkDrawable(binding.settingsMessageSound.background) - } - } - - binding.settingsCallSound.setOnClickListener { - val intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS) - intent.putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID) - intent.putExtra( - Settings.EXTRA_CHANNEL_ID, - NotificationUtils.NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name - ) - - startActivity(intent) - } - binding.settingsMessageSound.setOnClickListener { - val intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS) - intent.putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID) - intent.putExtra( - Settings.EXTRA_CHANNEL_ID, - NotificationUtils.NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name - ) - startActivity(intent) - } - } - - private fun setTroubleshootingClickListenersIfNecessary() { - fun click() { - val dialogBuilder = MaterialAlertDialogBuilder(this) - .setTitle(R.string.nc_notifications_troubleshooting_dialog_title) - .setMessage(R.string.nc_notifications_troubleshooting_dialog_text) - .setNegativeButton(R.string.nc_diagnosis_dialog_open_checklist) { _, _ -> - startActivity( - Intent( - Intent.ACTION_VIEW, - resources.getString(R.string.notification_checklist_url).toUri() - ) - ) - } - .setPositiveButton(R.string.nc_diagnosis_dialog_open_dontkillmyapp_website) { _, _ -> - startActivity( - Intent( - Intent.ACTION_VIEW, - resources.getString(R.string.dontkillmyapp_url).toUri() - ) - ) - } - .setNeutralButton(R.string.nc_diagnosis_dialog_open_diagnosis) { _, _ -> - val intent = Intent(context, DiagnosisActivity::class.java) - intent.putExtra(BundleKeys.KEY_INTERNAL_USER_ID, currentUser!!.id) - startActivity(intent) - } - viewThemeUtils.dialog.colorMaterialAlertDialogBackground(this, dialogBuilder) - val dialog = dialogBuilder.show() - viewThemeUtils.platform.colorTextButtons( - dialog.getButton(AlertDialog.BUTTON_POSITIVE), - dialog.getButton(AlertDialog.BUTTON_NEGATIVE), - dialog.getButton(AlertDialog.BUTTON_NEUTRAL) - ) - } - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - if (platformPermissionUtil.isPostNotificationsPermissionGranted() && - PowerManagerUtils().isIgnoringBatteryOptimizations() - ) { - binding.settingsNotificationsPermissionWrapper.setOnClickListener { click() } - binding.settingsBatteryOptimizationWrapper.setOnClickListener { click() } - } - } else if (PowerManagerUtils().isIgnoringBatteryOptimizations()) { - binding.settingsBatteryOptimizationWrapper.setOnClickListener { click() } - } - } - - private fun setupServerNotificationAppCheck() { - val serverNotificationAppInstalled = - currentUser!! - .capabilities?.notificationsCapability?.features?.isNotEmpty() - ?: false - if (!serverNotificationAppInstalled) { - binding.settingsServerNotificationAppWrapper.visibility = View.VISIBLE - - val description = context.getString(R.string.nc_settings_contact_admin_of) + LINEBREAK + - currentUser!!.baseUrl!! - - binding.settingsServerNotificationAppDescription.text = description - if (openedByNotificationWarning) { - DrawableUtils.blinkDrawable(binding.settingsServerNotificationAppWrapper.background) - } - } else { - binding.settingsServerNotificationAppWrapper.visibility = View.GONE - } - } - - private fun setupSourceCodeUrl(isOnline: Boolean) { - if (!TextUtils.isEmpty(resources!!.getString(R.string.nc_source_code_url)) && isOnline) { - binding.settingsSourceCode.visibility = View.VISIBLE - binding.settingsSourceCode.setOnClickListener { - startActivity( - Intent( - Intent.ACTION_VIEW, - resources!!.getString(R.string.nc_source_code_url).toUri() - ) - ) - } - } else { - binding.settingsSourceCode.visibility = View.GONE - } - } - - private fun setupDiagnosis() { - binding.diagnosisWrapper.setOnClickListener { - val intent = Intent(context, DiagnosisActivity::class.java) - intent.putExtra(BundleKeys.KEY_INTERNAL_USER_ID, currentUser!!.id) - startActivity(intent) - } - binding.logsWrapper.setOnClickListener { - startActivity(Intent(context, LogsActivity::class.java)) - } - binding.shareReportWrapper.setOnClickListener { - showShareReportDialog(this, userManager, appPreferences, logsRepository, saveZipLauncher) - } - } - - private fun setupPrivacyUrl(isOnline: Boolean) { - if (!TextUtils.isEmpty(resources!!.getString(R.string.nc_privacy_url)) && isOnline) { - binding.settingsPrivacy.visibility = View.VISIBLE - binding.settingsPrivacy.setOnClickListener { - startActivity( - Intent( - Intent.ACTION_VIEW, - resources!!.getString(R.string.nc_privacy_url).toUri() - ) - ) } - } else { - binding.settingsPrivacy.visibility = View.GONE - } - } - - private fun setupLicenceSetting(isOnline: Boolean) { - if (!TextUtils.isEmpty(resources!!.getString(R.string.nc_gpl3_url)) && isOnline) { - binding.settingsLicence.visibility = View.VISIBLE - binding.settingsLicence.setOnClickListener { - startActivity( - Intent( - Intent.ACTION_VIEW, - resources!!.getString(R.string.nc_gpl3_url).toUri() - ) - ) - } - } else { - binding.settingsLicence.visibility = View.GONE - } - } - - private fun showSetupClientCertView(isOnline: Boolean) { - if (isOnline) { - binding.settingsClientCert.visibility = View.VISIBLE - binding.settingsProxyGroup.visibility = View.VISIBLE - } else { - binding.settingsClientCert.visibility = View.GONE - binding.settingsProxyGroup.visibility = View.GONE - } - } - - private fun setupClientCertView() { - var host: String? = null - var port = -1 - val uri: URI - try { - uri = URI(currentUser!!.baseUrl!!) - host = uri.host - port = uri.port - Log.d(TAG, "uri is $uri") - } catch (e: URISyntaxException) { - Log.e(TAG, "Failed to create uri") - } - - binding.settingsClientCert.setOnClickListener { - KeyChain.choosePrivateKeyAlias( - this, - { alias: String? -> - var finalAlias: String? = alias - - runOnUiThread { - if (finalAlias != null) { - binding.settingsClientCertTitle.setText(R.string.nc_client_cert_change) - } else { - binding.settingsClientCertTitle.setText(R.string.nc_client_cert_setup) - } - } - - if (finalAlias == null) { - finalAlias = "" - } - Log.d(TAG, "host: $host and port: $port") - currentUser!!.clientCertificate = finalAlias - val userId = currentUser!!.id!! - lifecycleScope.launch { - userManager.updateClientCertificate(userId, finalAlias) - } - }, - arrayOf("RSA", "EC"), - null, - host, - port, - currentUser!!.clientCertificate - ) - } - } - - @OptIn(ExperimentalCoroutinesApi::class) - private fun registerChangeListeners() { - val appPreferences = AppPreferencesImpl(context) - proxyTypeFlow = appPreferences.readString(AppPreferencesImpl.PROXY_TYPE) - proxyCredentialFlow = appPreferences.readBoolean(AppPreferencesImpl.PROXY_CRED) - screenSecurityFlow = appPreferences.readBoolean(AppPreferencesImpl.SCREEN_SECURITY) - screenLockFlow = appPreferences.readBoolean(AppPreferencesImpl.SCREEN_LOCK) - screenLockTimeoutFlow = appPreferences.readString(AppPreferencesImpl.SCREEN_LOCK_TIMEOUT) - - val themeKey = context.resources.getString(R.string.nc_settings_theme_key) - themeFlow = appPreferences.readString(themeKey) - - val privacyKey = context.resources.getString(R.string.nc_settings_read_privacy_key) - readPrivacyFlow = appPreferences.readBoolean(privacyKey) - - typingStatusFlow = appPreferences.readBoolean(AppPreferencesImpl.TYPING_STATUS) - phoneBookIntegrationFlow = appPreferences.readBoolean(AppPreferencesImpl.PHONE_BOOK_INTEGRATION) - - var pos = resources.getStringArray(R.array.screen_lock_timeout_entry_values).indexOf( - appPreferences.screenLockTimeout ) - binding.settingsScreenLockTimeoutLayoutDropdown.setText( - resources.getStringArray(R.array.screen_lock_timeout_descriptions)[pos] - ) - - binding.settingsScreenLockTimeoutLayoutDropdown.setSimpleItems(R.array.screen_lock_timeout_descriptions) - binding.settingsScreenLockTimeoutLayoutDropdown.setOnItemClickListener { _, _, position, _ -> - val entryVal: String = resources.getStringArray(R.array.screen_lock_timeout_entry_values)[position] - appPreferences.screenLockTimeout = entryVal - SecurityUtils.createKey(entryVal) - } - pos = resources.getStringArray(R.array.theme_entry_values).indexOf(appPreferences.theme) - binding.settingsTheme.setText(resources.getStringArray(R.array.theme_descriptions)[pos]) - - binding.settingsTheme.setSimpleItems(R.array.theme_descriptions) - binding.settingsTheme.setOnItemClickListener { _, _, position, _ -> - val entryVal: String = resources.getStringArray(R.array.theme_entry_values)[position] - appPreferences.theme = entryVal - } - - observeProxyType() - observeProxyCredential() - observeScreenSecurity() - observeScreenLock() - observeTheme() - observeReadPrivacy() - observeTypingStatus() - } - fun sendLogs() { - if (resources!!.getBoolean(R.bool.nc_is_debug)) { - sendMailWithAttachment((context)) - } - } - - private fun showRemoveAccountWarning() { - binding.messageText.context?.let { - val materialAlertDialogBuilder = MaterialAlertDialogBuilder(it) - .setTitle(R.string.nc_settings_remove_account) - .setMessage(R.string.nc_settings_remove_confirmation) - .setPositiveButton(R.string.nc_settings_remove) { _, _ -> - removeCurrentAccount() - } - .setNegativeButton(R.string.nc_cancel) { _, _ -> - // unused atm - } - - viewThemeUtils.dialog.colorMaterialAlertDialogBackground( - it, - materialAlertDialogBuilder - ) - - val dialog = materialAlertDialogBuilder.show() - - viewThemeUtils.platform.colorTextButtons( - dialog.getButton(AlertDialog.BUTTON_POSITIVE), - dialog.getButton(AlertDialog.BUTTON_NEGATIVE) - ) - } - } - - @SuppressLint("StringFormatInvalid") - private fun removeCurrentAccount() { + private fun collectEvents() { lifecycleScope.launch { - userManager.scheduleUserForDeletionWithId(currentUser!!.id!!) - val accountRemovalWork = OneTimeWorkRequest.Builder(AccountRemovalWorker::class.java) - .setExpeditedIfSupported() - .build() - WorkManager.getInstance(applicationContext).enqueue(accountRemovalWork) - - WorkManager.getInstance(context).getWorkInfoByIdLiveData(accountRemovalWork.id) - .observeForever { workInfo: WorkInfo? -> - - when (workInfo?.state) { - WorkInfo.State.SUCCEEDED -> { - val text = String.format( - context.resources.getString(R.string.nc_deleted_user), - currentUser!!.displayName - ) - Toast.makeText( - context, - text, - Toast.LENGTH_LONG - ).show() - restartApp() - } - - WorkInfo.State.FAILED, WorkInfo.State.CANCELLED -> { - Toast.makeText( - context, - context.resources.getString(R.string.nc_common_error_sorry), - Toast.LENGTH_LONG - ).show() - logger.e(TAG, "something went wrong when deleting user with id " + currentUser!!.userId) - restartApp() - } - - else -> {} - } - } - } - } - - private fun restartApp() { - startActivity(AppTasks.createRestartIntent(context)) - } - - private fun getRingtoneName(context: Context, ringtoneUri: Uri?): String = - if (ringtoneUri == null) { - resources!!.getString(R.string.nc_settings_no_ringtone) - } else if ((NotificationUtils.DEFAULT_CALL_RINGTONE_URI == ringtoneUri.toString()) || - (NotificationUtils.DEFAULT_MESSAGE_RINGTONE_URI == ringtoneUri.toString()) - ) { - resources!!.getString(R.string.nc_settings_default_ringtone) - } else { - val r = RingtoneManager.getRingtone(context, ringtoneUri) - r.getTitle(context) - } - - private fun themeSwitchPreferences() { - binding.run { - listOf( - settingsShowEcosystemSwitch, - settingsShowNotificationWarningSwitch, - settingsUnifiedpushSwitch, - settingsScreenLockSwitch, - settingsScreenSecuritySwitch, - settingsIncognitoKeyboardSwitch, - settingsPhoneBookIntegrationSwitch, - settingsReadPrivacySwitch, - settingsTypingStatusSwitch, - settingsProxyUseCredentialsSwitch - ).forEach(viewThemeUtils.talk::colorSwitch) - } - } - - private fun themeTitles() { - binding.run { - listOf( - settingsNotificationsTitle, - settingsAboutTitle, - settingsDiagnosisTitle, - settingsAdvancedTitle, - settingsAppearanceTitle, - settingsPrivacyTitle - ).forEach(viewThemeUtils.platform::colorTextView) - } - } - - private fun setupProxyTypeSettings() { - if (appPreferences.proxyType == null) { - appPreferences.proxyType = resources.getString(R.string.nc_no_proxy) - } - binding.settingsProxyChoice.setText(appPreferences.proxyType) - binding.settingsProxyChoice.setSimpleItems(R.array.proxy_type_descriptions) - binding.settingsProxyChoice.setOnItemClickListener { _, _, position, _ -> - val entryVal = resources.getStringArray(R.array.proxy_type_descriptions)[position] - appPreferences.proxyType = entryVal - } - - binding.settingsProxyHostEdit.setText(appPreferences.proxyHost) - binding.settingsProxyHostEdit.setOnFocusChangeListener { _, hasFocus -> - if (!hasFocus) { - appPreferences.proxyHost = binding.settingsProxyHostEdit.text.toString() - } - } - - binding.settingsProxyPortEdit.setText(appPreferences.proxyPort) - binding.settingsProxyPortEdit.setOnFocusChangeListener { _, hasFocus -> - if (!hasFocus) { - appPreferences.proxyPort = binding.settingsProxyPortEdit.text.toString() - } - } - binding.settingsProxyUsernameEdit.setText(appPreferences.proxyUsername) - binding.settingsProxyUsernameEdit.setOnFocusChangeListener { _, hasFocus -> - if (!hasFocus) { - appPreferences.proxyUsername = binding.settingsProxyUsernameEdit.text.toString() - } - } - binding.settingsProxyPasswordEdit.setText(appPreferences.proxyPassword) - binding.settingsProxyPasswordEdit.setOnFocusChangeListener { _, hasFocus -> - if (!hasFocus) { - appPreferences.proxyPassword = binding.settingsProxyPasswordEdit.text.toString() - } - } - - if (((context.resources.getString(R.string.nc_no_proxy)) == appPreferences.proxyType) || - appPreferences.proxyType == null - ) { - hideProxySettings() - } else { - showProxySettings() - } - } - - private fun setupProxyCredentialSettings() { - if (appPreferences.proxyCredentials) { - showProxyCredentials() - } else { - hideProxyCredentials() - } - } - - private fun setupMessageView() { - if (ApplicationWideMessageHolder.getInstance().messageType != null) { - when (ApplicationWideMessageHolder.getInstance().messageType) { - ApplicationWideMessageHolder.MessageType.ACCOUNT_UPDATED_NOT_ADDED -> { - binding.messageText.let { - viewThemeUtils.platform.colorTextView(it, ColorRole.PRIMARY) - it.text = resources!!.getString(R.string.nc_settings_account_updated) - binding.messageText.visibility = View.VISIBLE - } - } - - ApplicationWideMessageHolder.MessageType.SERVER_WITHOUT_TALK -> { - binding.messageText.let { - it.setTextColor(resources!!.getColor(R.color.nc_darkRed, null)) - it.text = resources!!.getString(R.string.nc_settings_wrong_account) - binding.messageText.visibility = View.VISIBLE - viewThemeUtils.platform.colorTextView(it, ColorRole.PRIMARY) - it.text = resources!!.getString(R.string.nc_Server_account_imported) - binding.messageText.visibility = View.VISIBLE - } - } - - ApplicationWideMessageHolder.MessageType.ACCOUNT_WAS_IMPORTED -> { - binding.messageText.let { - viewThemeUtils.platform.colorTextView(it, ColorRole.PRIMARY) - it.text = resources!!.getString(R.string.nc_Server_account_imported) - binding.messageText.visibility = View.VISIBLE - } - } - - ApplicationWideMessageHolder.MessageType.FAILED_TO_IMPORT_ACCOUNT -> { - binding.messageText.let { - it.setTextColor(resources!!.getColor(R.color.nc_darkRed, null)) - it.text = resources!!.getString(R.string.nc_server_failed_to_import_account) - binding.messageText.visibility = View.VISIBLE - } - } - - else -> binding.messageText.visibility = View.GONE - } - ApplicationWideMessageHolder.getInstance().messageType = null - binding.messageText.animate() - ?.translationY(0f) - ?.alpha(0.0f) - ?.setDuration(DURATION) - ?.setStartDelay(START_DELAY) - ?.setListener(object : AnimatorListenerAdapter() { - override fun onAnimationEnd(animation: Animator) { - super.onAnimationEnd(animation) - binding.messageText.visibility = View.GONE - } - }) - } else { - binding.messageText.visibility = View.GONE - } - } - - private fun setupProfileQueryDisposable() { - profileQueryDisposable = ncApi.getUserProfile( - credentials, - ApiUtils.getUrlForUserProfile(currentUser!!.baseUrl!!) - ) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe( - { userProfileOverall: UserProfileOverall -> - var displayName: String? = null - if (!TextUtils.isEmpty( - userProfileOverall.ocs!!.data!!.displayName - ) - ) { - displayName = userProfileOverall.ocs!!.data!!.displayName - } else if (!TextUtils.isEmpty( - userProfileOverall.ocs!!.data!!.displayNameAlt - ) - ) { - displayName = userProfileOverall.ocs!!.data!!.displayNameAlt - } - if ((!TextUtils.isEmpty(displayName) && !(displayName == currentUser!!.displayName))) { - currentUser!!.displayName = displayName - val userId = currentUser!!.id!! - lifecycleScope.launch { - userManager.updateDisplayName(userId, displayName) - } - binding.nameText.text = currentUser!!.displayName - } - }, - { dispose(profileQueryDisposable) }, - { dispose(profileQueryDisposable) } - ) - } - - private fun setupServerAgeWarning() { - when { - CapabilitiesUtil.isServerEOL(currentUser!!.serverVersion?.major) -> { - binding.serverAgeWarningText.setTextColor(ContextCompat.getColor((context), R.color.nc_darkRed)) - binding.serverAgeWarningText.setText(R.string.nc_settings_server_eol) - binding.serverAgeWarningIcon.setColorFilter( - ContextCompat.getColor((context), R.color.nc_darkRed), - PorterDuff.Mode.SRC_IN - ) - } - - CapabilitiesUtil.isServerAlmostEOL(currentUser!!.serverVersion?.major) -> { - binding.serverAgeWarningText.setTextColor( - ContextCompat.getColor((context), R.color.nc_darkYellow) - ) - binding.serverAgeWarningText.setText(R.string.nc_settings_server_almost_eol) - binding.serverAgeWarningIcon.setColorFilter( - ContextCompat.getColor((context), R.color.nc_darkYellow), - PorterDuff.Mode.SRC_IN - ) - } - - else -> { - binding.serverAgeWarningTextCard.visibility = View.GONE + repeatOnLifecycle(Lifecycle.State.STARTED) { + viewModel.events.collect(::handleEvent) } } } - private fun setupCheckables(isOnline: Boolean) { - setupShowEcosystemCheckable() - - binding.settingsShowNotificationWarningSwitch.isChecked = - appPreferences.showRegularNotificationWarning - - if (ClosedInterfaceImpl().isGooglePlayServicesAvailable) { - binding.settingsShowNotificationWarning.setOnClickListener { - val isChecked = binding.settingsShowNotificationWarningSwitch.isChecked - binding.settingsShowNotificationWarningSwitch.isChecked = !isChecked - appPreferences.setShowRegularNotificationWarning(!isChecked) - if (!isChecked) { - appPreferences.setNotificationWarningLastPostponedDate(NOTIFICATION_WARNING_DATE_NOT_SET) - } + private suspend fun handleEvent(event: SettingsEvent) { + when (event) { + is SettingsEvent.ShowMessage -> snackbarHostState.showSnackbar(getString(event.messageRes)) + is SettingsEvent.AccountRemoved -> { + Toast.makeText(this, getString(R.string.nc_deleted_user, event.displayName), Toast.LENGTH_LONG).show() + startActivity(AppTasks.createRestartIntent(this)) } - } else { - binding.settingsShowNotificationWarning.visibility = View.GONE - } - - if (CapabilitiesUtil.isReadStatusAvailable(currentUser?.capabilities?.spreedCapability) && - isOnline - ) { - binding.settingsReadPrivacy.visibility = View.VISIBLE - binding.settingsReadPrivacySwitch.isChecked = !CapabilitiesUtil.isReadStatusPrivate(currentUser!!) - } else { - binding.settingsReadPrivacy.visibility = View.GONE - } - - setupTypingStatusSetting(isOnline) - setupProxyUseSetting() - - binding.settingsScreenLockSwitch.isChecked = appPreferences.isScreenLocked - binding.settingsScreenLock.setOnClickListener { - val isChecked = binding.settingsScreenLockSwitch.isChecked - binding.settingsScreenLockSwitch.isChecked = !isChecked - appPreferences.setScreenLock(!isChecked) - if (!isChecked) { - SecurityUtils.createKey(appPreferences.screenLockTimeout) - appPreferences.setLockTimestamp(System.currentTimeMillis()) + SettingsEvent.AccountRemovalFailed -> { + Toast.makeText(this, R.string.nc_common_error_sorry, Toast.LENGTH_LONG).show() + startActivity(AppTasks.createRestartIntent(this)) } + SettingsEvent.AccountUnavailable -> finish() } - - binding.settingsReadPrivacy.setOnClickListener { - val isChecked = binding.settingsReadPrivacySwitch.isChecked - binding.settingsReadPrivacySwitch.isChecked = !isChecked - appPreferences.setReadPrivacy(!isChecked) - } - - binding.settingsIncognitoKeyboardSwitch.isChecked = appPreferences.isKeyboardIncognito - binding.settingsIncognitoKeyboard.setOnClickListener { - val isChecked = binding.settingsIncognitoKeyboardSwitch.isChecked - binding.settingsIncognitoKeyboardSwitch.isChecked = !isChecked - appPreferences.setIncognitoKeyboard(!isChecked) - } - - setupMediaQualitySetting() - setupPhoneBookIntegrationSetting() - - binding.settingsScreenSecuritySwitch.isChecked = appPreferences.isScreenSecured - binding.settingsScreenSecurity.setOnClickListener { - val isChecked = binding.settingsScreenSecuritySwitch.isChecked - binding.settingsScreenSecuritySwitch.isChecked = !isChecked - appPreferences.setScreenSecurity(!isChecked) - } - - binding.settingsTypingStatus.setOnClickListener { - val isChecked = binding.settingsTypingStatusSwitch.isChecked - binding.settingsTypingStatusSwitch.isChecked = !isChecked - appPreferences.setTypingStatus(!isChecked) - } - } - - private fun setupShowEcosystemCheckable() { - binding.settingsShowEcosystemSwitch.isChecked = appPreferences.isShowEcosystem - binding.settingsShowEcosystem.setOnClickListener { - val isChecked = binding.settingsShowEcosystemSwitch.isChecked - binding.settingsShowEcosystemSwitch.isChecked = !isChecked - appPreferences.setShowEcosystem(!isChecked) - } - } - - private fun setupMediaQualitySetting() { - updateMediaQualitySummary() - binding.settingsMediaQuality.setOnClickListener { - showMediaQualityDialog() - } - } - - private fun updateMediaQualitySummary() { - binding.settingsMediaQualityDesc.text = if (appPreferences.compressUploadImages) { - getString(R.string.nc_media_quality_reduced) - } else { - getString(R.string.nc_media_quality_original) - } - } - - private fun showMediaQualityDialog() { - var dialog: AlertDialog? = null - val view = buildMediaQualityDialogContentView { reducedQuality -> - appPreferences.setCompressUploadImages(reducedQuality) - updateMediaQualitySummary() - dialog?.dismiss() - } - val dialogBuilder = MaterialAlertDialogBuilder(this) - .setTitle(R.string.nc_settings_media_quality_title) - .setView(view) - viewThemeUtils.dialog.colorMaterialAlertDialogBackground(this, dialogBuilder) - dialog = dialogBuilder.show() } - // AlertDialog/MaterialAlertDialogBuilder doesn't reliably render both setMessage(...) and - // setSingleChoiceItems(...) together (the list ends up empty), so the hint and the two - // options are laid out manually here instead, mirroring buildShareDialogContentView's style. - private fun buildMediaQualityDialogContentView( - onSelect: (reducedQuality: Boolean) -> Unit - ): android.widget.LinearLayout { - val density = resources.displayMetrics.density - fun dp(value: Int) = (value * density).toInt() - val selectableBackground = with(android.util.TypedValue()) { - theme.resolveAttribute(android.R.attr.selectableItemBackground, this, true) - resourceId - } - - fun optionRow(label: String, reducedQuality: Boolean) = - android.widget.LinearLayout(this).apply { - orientation = android.widget.LinearLayout.HORIZONTAL - gravity = android.view.Gravity.CENTER_VERTICAL - val h = dp(DIALOG_PADDING_H_DP) - val v = dp(DIALOG_PADDING_V_DP) - setPadding(h, v, h, v) - setBackgroundResource(selectableBackground) - isClickable = true - isFocusable = true - addView( - android.widget.RadioButton(context).apply { - isChecked = appPreferences.compressUploadImages == reducedQuality - isClickable = false - } - ) - addView( - android.widget.TextView(context).apply { - text = label - setPadding(dp(DIALOG_SPACING_DP), 0, 0, 0) - setTextAppearance(com.google.android.material.R.style.TextAppearance_Material3_BodyLarge) - } - ) - setOnClickListener { onSelect(reducedQuality) } - } - - return android.widget.LinearLayout(this).apply { - orientation = android.widget.LinearLayout.VERTICAL - addView( - android.widget.TextView(context).apply { - text = getString(R.string.nc_media_quality_original_hint) - val h = dp(DIALOG_PADDING_H_DP) - val v = dp(DIALOG_PADDING_V_DP) - setPadding(h, v, h, v) - setTextAppearance(com.google.android.material.R.style.TextAppearance_Material3_BodyMedium) - } - ) - addView(optionRow(getString(R.string.nc_media_quality_original), reducedQuality = false)) - addView(optionRow(getString(R.string.nc_media_quality_reduced), reducedQuality = true)) - } - } - - private fun setupPhoneBookIntegrationSetting() { - binding.settingsPhoneBookIntegrationSwitch.isChecked = appPreferences.isPhoneBookIntegrationEnabled - binding.settingsPhoneBookIntegration.setOnClickListener { - val isChecked = binding.settingsPhoneBookIntegrationSwitch.isChecked - binding.settingsPhoneBookIntegrationSwitch.isChecked = !isChecked - appPreferences.setPhoneBookIntegration(!isChecked) - if (!isChecked) { - if (checkPermission(this@SettingsActivity, (context))) { - checkForPhoneNumber() - } - } else { - deleteAll() - } - } - } - - private fun setupProxyUseSetting() { - binding.settingsProxyUseCredentialsSwitch.isChecked = appPreferences.proxyCredentials - binding.settingsProxyUseCredentials.setOnClickListener { - val isChecked = binding.settingsProxyUseCredentialsSwitch.isChecked - binding.settingsProxyUseCredentialsSwitch.isChecked = !isChecked - appPreferences.setProxyNeedsCredentials(!isChecked) - } - } - - private fun setupTypingStatusSetting(isOnline: Boolean) { - if (currentUser!!.externalSignalingServer?.externalSignalingServer?.isNotEmpty() == true) { - binding.settingsTypingStatusOnlyWithHpb.visibility = View.GONE - Log.i(TAG, "Typing Status Available: ${CapabilitiesUtil.isTypingStatusAvailable(currentUser!!)}") - - if (CapabilitiesUtil.isTypingStatusAvailable(currentUser!!) && isOnline) { - binding.settingsTypingStatus.visibility = View.VISIBLE - binding.settingsTypingStatusSwitch.isChecked = !CapabilitiesUtil.isTypingStatusPrivate(currentUser!!) - } else { - binding.settingsTypingStatus.visibility = View.GONE - } - } else { - Log.i(TAG, "Typing Status not Available") - binding.settingsTypingStatusSwitch.isChecked = false - binding.settingsTypingStatusOnlyWithHpb.visibility = View.VISIBLE - binding.settingsTypingStatus.isEnabled = false - binding.settingsTypingStatus.alpha = DISABLED_ALPHA - } - } - - private fun setupScreenLockSetting() { - val keyguardManager = context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager - if (keyguardManager.isKeyguardSecure) { - binding.settingsScreenLock.isEnabled = true - binding.settingsScreenLockTimeout.isEnabled = true - binding.settingsScreenLockSwitch.isChecked = appPreferences.isScreenLocked - binding.settingsScreenLockTimeoutLayoutDropdown.isEnabled = appPreferences.isScreenLocked - if (appPreferences.isScreenLocked) { - binding.settingsScreenLockTimeout.alpha = ENABLED_ALPHA - } else { - binding.settingsScreenLockTimeout.alpha = DISABLED_ALPHA - } - binding.settingsScreenLock.alpha = ENABLED_ALPHA - } else { - binding.settingsScreenLock.isEnabled = false - binding.settingsScreenLockTimeoutLayoutDropdown.isEnabled = false - appPreferences.removeScreenLock() - appPreferences.removeScreenLockTimeout() - binding.settingsScreenLockSwitch.isChecked = false - binding.settingsScreenLock.alpha = DISABLED_ALPHA - binding.settingsScreenLockTimeout.alpha = DISABLED_ALPHA - } - } - - public override fun onDestroy() { - // appPreferences.unregisterProxyTypeListener(proxyTypeChangeListener) - // appPreferences.unregisterProxyCredentialsListener(proxyCredentialsChangeListener) - // appPreferences.unregisterScreenSecurityListener(screenSecurityChangeListener) - // appPreferences.unregisterScreenLockListener(screenLockChangeListener) - // appPreferences.unregisterScreenLockTimeoutListener(screenLockTimeoutChangeListener) - // appPreferences.unregisterThemeChangeListener(themeChangeListener) - // appPreferences.unregisterReadPrivacyChangeListener(readPrivacyChangeListener) - // appPreferences.unregisterTypingStatusChangeListener(typingStatusChangeListener) - // appPreferences.unregisterPhoneBookIntegrationChangeListener(phoneBookIntegrationChangeListener) - - super.onDestroy() - } - - private fun hideProxySettings() { - appPreferences.removeProxyHost() - appPreferences.removeProxyPort() - appPreferences.removeProxyCredentials() - appPreferences.removeProxyUsername() - appPreferences.removeProxyPassword() - binding.settingsProxyHostLayout.visibility = View.GONE - binding.settingsProxyPortLayout.visibility = View.GONE - binding.settingsProxyUseCredentials.visibility = View.GONE - hideProxyCredentials() - } - - private fun showProxySettings() { - binding.settingsProxyHostLayout.visibility = - View.VISIBLE - binding.settingsProxyPortLayout.visibility = - View.VISIBLE - binding.settingsProxyUseCredentials.visibility = - View.VISIBLE - if (binding.settingsProxyUseCredentialsSwitch.isChecked) showProxyCredentials() - } - - private fun showProxyCredentials() { - binding.settingsProxyUsernameLayout.visibility = - View.VISIBLE - binding.settingsProxyPasswordLayout.visibility = - View.VISIBLE - } - - private fun hideProxyCredentials() { - appPreferences.removeProxyUsername() - appPreferences.removeProxyPassword() - binding.settingsProxyUsernameLayout.visibility = View.GONE - binding.settingsProxyPasswordLayout.visibility = View.GONE - } - - private fun dispose(disposable: Disposable?) { - if (disposable != null && !disposable.isDisposed) { - disposable.dispose() - } else if (disposable == null) { - disposeProfileQueryDisposable() - disposeDbQueryDisposable() - } - } - - private fun disposeDbQueryDisposable() { - if (dbQueryDisposable != null && !dbQueryDisposable!!.isDisposed) { - dbQueryDisposable!!.dispose() - dbQueryDisposable = null - } else if (dbQueryDisposable != null) { - dbQueryDisposable = null - } - } - - private fun disposeProfileQueryDisposable() { - if (profileQueryDisposable != null && !profileQueryDisposable!!.isDisposed) { - profileQueryDisposable!!.dispose() - profileQueryDisposable = null - } else if (profileQueryDisposable != null) { - profileQueryDisposable = null - } - } - - @Suppress("Detekt.TooGenericExceptionCaught") - override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { - super.onRequestPermissionsResult(requestCode, permissions, grantResults) - - when (requestCode) { - ContactAddressBookWorker.REQUEST_PERMISSION -> { - if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - WorkManager - .getInstance(this) - .enqueue(OneTimeWorkRequest.Builder(ContactAddressBookWorker::class.java).build()) - checkForPhoneNumber() - } else { - appPreferences.setPhoneBookIntegration(false) - binding.settingsPhoneBookIntegrationSwitch.isChecked = appPreferences.isPhoneBookIntegrationEnabled - Snackbar.make( - binding.root, - context.resources.getString(R.string.no_phone_book_integration_due_to_permissions), - Snackbar.LENGTH_LONG - ).show() - } - } - - ConversationsListActivity.REQUEST_POST_NOTIFICATIONS_PERMISSION -> { - if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_DENIED) { - try { - val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS) - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - intent.putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID) - startActivity(intent) - } catch (e: Exception) { - Log.e(TAG, "Failed to open notification settings as fallback", e) - } - } - } - } - } - - private fun observeScreenLock() { - CoroutineScope(Dispatchers.Main).launch { - var state = appPreferences.isScreenLocked - screenLockFlow.collect { newBoolean -> - if (newBoolean != state) { - state = newBoolean - binding.settingsScreenLockTimeout.isEnabled = newBoolean - binding.settingsScreenLockTimeoutLayoutDropdown.isEnabled = newBoolean - if (newBoolean) { - binding.settingsScreenLockTimeout.alpha = ENABLED_ALPHA - } else { - binding.settingsScreenLockTimeout.alpha = DISABLED_ALPHA - } - } - } - } - } - - private fun observeScreenSecurity() { - CoroutineScope(Dispatchers.Main).launch { - var state = appPreferences.isScreenSecured - screenSecurityFlow.collect { newBoolean -> - if (newBoolean != state) { - state = newBoolean - if (newBoolean) { + /** Keeps screenshots and the preview in the recent apps off while screen security or the app lock is on. */ + private fun applySecureWindowFlag() { + lifecycleScope.launch { + viewModel.uiState + .map { it.privacy.screenSecurity || it.privacy.screenLock } + .distinctUntilChanged() + .collect { secure -> + if (secure) { window.addFlags(WindowManager.LayoutParams.FLAG_SECURE) } else { window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) } } - } } } - private fun observeProxyCredential() { - CoroutineScope(Dispatchers.Main).launch { - var state = appPreferences.proxyCredentials - proxyCredentialFlow.collect { newBoolean -> - if (newBoolean != state) { - state = newBoolean - if (newBoolean) { - showProxyCredentials() - } else { - hideProxyCredentials() - } - } + private fun setUseUnifiedPush(enabled: Boolean) { + viewModel.setUseUnifiedPush(enabled) + if (enabled) { + UnifiedPushUtils.useDefaultDistributor(this) { distributor -> + Log.d(TAG, "Registered to $distributor") + distributor?.let { runOnUiThread { viewModel.onDistributorChanged(it) } } } + } else { + UnifiedPushUtils.disableExternalUnifiedPush(this) } } - private fun observeProxyType() { - CoroutineScope(Dispatchers.Main).launch { - var state = appPreferences.proxyType - proxyTypeFlow.collect { newString -> - if (newString != state) { - state = newString - if (((context.resources.getString(R.string.nc_no_proxy)) == newString) || newString.isEmpty()) { - hideProxySettings() - } else { - when (newString) { - "HTTP" -> { - binding.settingsProxyPortEdit.setText(getString(R.string.nc_settings_http_value)) - appPreferences.proxyPort = getString(R.string.nc_settings_http_value) - } - - "DIRECT" -> { - binding.settingsProxyPortEdit.setText(getString(R.string.nc_settings_direct_value)) - appPreferences.proxyPort = getString(R.string.nc_settings_direct_value) - } - - "SOCKS" -> { - binding.settingsProxyPortEdit.setText(getString(R.string.nc_settings_socks_value)) - appPreferences.proxyPort = getString(R.string.nc_settings_socks_value) - } - - else -> { - } - } - showProxySettings() - } - } - } - } + private fun chooseClientCertificate() { + val uri = try { + URI(user.baseUrl!!) + } catch (e: URISyntaxException) { + Log.e(TAG, "Failed to parse the server address", e) + null + } + KeyChain.choosePrivateKeyAlias( + this, + { alias -> runOnUiThread { viewModel.onClientCertificateChosen(alias) } }, + arrayOf("RSA", "EC"), + null, + uri?.host, + uri?.port ?: -1, + viewModel.clientCertificateAlias + ) } - private fun observeTheme() { - CoroutineScope(Dispatchers.Main).launch { - var state = appPreferences.theme - themeFlow.collect { newString -> - if (newString != state) { - state = newString - setAppTheme(newString) - } + private fun openSystemSettings(screen: SystemSettingsScreen) { + val intent = when (screen) { + SystemSettingsScreen.BATTERY_OPTIMIZATION -> Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS) + SystemSettingsScreen.FULL_SCREEN_INTENT -> { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return + Intent(Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT, "package:$packageName".toUri()) } + SystemSettingsScreen.CALL_NOTIFICATIONS -> + notificationChannelSettingsIntent(NotificationUtils.NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5) + SystemSettingsScreen.MESSAGE_NOTIFICATIONS -> + notificationChannelSettingsIntent( + NotificationUtils.NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4 + ) } + openSystemSettings(intent) } - private fun checkForPhoneNumber() { - ncApi.getUserData( - ApiUtils.getCredentials(currentUser!!.username, currentUser!!.token), - ApiUtils.getUrlForUserProfile(currentUser!!.baseUrl!!) - ).subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(object : Observer { - override fun onSubscribe(d: Disposable) { - // unused atm - } - - override fun onNext(userProfileOverall: UserProfileOverall) { - if (userProfileOverall.ocs!!.data!!.phone?.isEmpty() == true) { - askForPhoneNumber() - } else { - Log.d(TAG, "phone number already set") - } - } - - override fun onError(e: Throwable) { - // unused atm - } - - override fun onComplete() { - // unused atm - } - }) - } - - private fun askForPhoneNumber() { - val dialog = SetPhoneNumberDialogFragment.newInstance() - dialog.show(supportFragmentManager, SetPhoneNumberDialogFragment.TAG) - } - - override fun onSubmitClick(textInputLayout: TextInputLayout, dialog: DialogInterface) { - setPhoneNumber(textInputLayout, dialog) + private fun openSystemSettings(intent: Intent) { + try { + startActivity(intent) + } catch (e: ActivityNotFoundException) { + Log.e(TAG, "Failed to open the system settings", e) + } } - private fun setPhoneNumber(textInputLayout: TextInputLayout, dialog: DialogInterface) { - val phoneNumber = textInputLayout.editText!!.text.toString() - ncApi.setUserData( - ApiUtils.getCredentials(currentUser!!.username, currentUser!!.token), - ApiUtils.getUrlForUserData(currentUser!!.baseUrl!!, currentUser!!.userId!!), - "phone", - phoneNumber - ).subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(object : Observer { - override fun onSubscribe(d: Disposable) { - // unused atm - } - - override fun onNext(genericOverall: GenericOverall) { - when (val statusCode = genericOverall.ocs?.meta?.statusCode) { - HTTP_CODE_OK -> { - dialog.dismiss() - Snackbar.make( - binding.root, - getString( - R.string.nc_settings_phone_book_integration_phone_number_dialog_success - ), - Snackbar.LENGTH_LONG - ).show() - } - - else -> { - textInputLayout.helperText = getString( - R.string.nc_settings_phone_book_integration_phone_number_dialog_invalid - ) - Log.d(TAG, "failed to set phoneNumber. statusCode=$statusCode") - } - } - } - - override fun onError(e: Throwable) { - textInputLayout.helperText = getString( - R.string.nc_settings_phone_book_integration_phone_number_dialog_invalid - ) - Log.e(SetPhoneNumberDialogFragment.TAG, "setPhoneNumber error", e) - } - - override fun onComplete() { - // unused atm - } - }) - } + private fun notificationChannelSettingsIntent(channel: NotificationUtils.NotificationChannels): Intent = + Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS) + .putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID) + .putExtra(Settings.EXTRA_CHANNEL_ID, channel.name) - @Suppress("Detekt.TooGenericExceptionCaught") - private fun observeReadPrivacy() { - lifecycleScope.launch { - var state = appPreferences.readPrivacy - readPrivacyFlow.collect { newBoolean -> - if (state != newBoolean) { - state = newBoolean - val booleanValue = if (newBoolean) "0" else "1" - val json = "{\"key\": \"read_status_privacy\", \"value\" : $booleanValue}" - withContext(Dispatchers.IO) { - try { - credentials?.let { credentials -> - ncApiCoroutines.setReadStatusPrivacy( - credentials, - ApiUtils.getUrlForUserSettings(currentUser!!.baseUrl!!), - json.toRequestBody("application/json".toMediaTypeOrNull()) - ) - Log.i(TAG, "reading status set") - } - } catch (e: Exception) { - withContext(Dispatchers.Main) { - appPreferences.setReadPrivacy(!newBoolean) - binding.settingsReadPrivacySwitch.isChecked = !newBoolean - } - if (e is HttpException && e.code() == HTTP_ERROR_CODE_BAD_REQUEST) { - Log.e(TAG, "read_status_privacy : Key or value is invalid") - } else { - Log.e(TAG, "Error setting read status", e) - } - } - } - } - } - } + private fun openLogs() { + startActivity(Intent(this, LogsActivity::class.java)) } - @Suppress("Detekt.TooGenericExceptionCaught") - private fun observeTypingStatus() { - lifecycleScope.launch { - var state = appPreferences.typingStatus - typingStatusFlow.collect { newBoolean -> - if (state != newBoolean) { - state = newBoolean - val booleanValue = if (newBoolean) "0" else "1" - val json = "{\"key\": \"typing_privacy\", \"value\" : $booleanValue}" - withContext(Dispatchers.IO) { - try { - credentials?.let { credentials -> - ncApiCoroutines.setTypingStatusPrivacy( - credentials, - ApiUtils.getUrlForUserSettings(currentUser!!.baseUrl!!), - json.toRequestBody("application/json".toMediaTypeOrNull()) - ) - } - } catch (e: Exception) { - withContext(Dispatchers.Main) { - appPreferences.typingStatus = !newBoolean - binding.settingsTypingStatusSwitch.isChecked = !newBoolean - } - if (e is HttpException && e.code() == HTTP_ERROR_CODE_BAD_REQUEST) { - Log.e(TAG, "typing_privacy : Key or value is invalid") - } else { - Log.e(TAG, "Error setting typing status", e) - } - } - } - } - } - } - } + private fun intentForAccount(activity: Class<*>): Intent = + Intent(this, activity).putExtra(BundleKeys.KEY_INTERNAL_USER_ID, user.id) companion object { private val TAG = SettingsActivity::class.java.simpleName - private const val DURATION: Long = 2500 - private const val START_DELAY: Long = 5000 - private const val DISABLED_ALPHA: Float = 0.38f - private const val ENABLED_ALPHA: Float = 1.0f - private const val LINEBREAK = "\n" - const val HTTP_CODE_OK: Int = 200 - const val HTTP_ERROR_CODE_BAD_REQUEST: Int = 400 - const val NO_NOTIFICATION_REMINDER_WANTED = 0L - private const val DIALOG_PADDING_H_DP = 24 - private const val DIALOG_PADDING_V_DP = 16 - private const val DIALOG_SPACING_DP = 8 + private val CONTACTS_PERMISSIONS = + arrayOf(Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS) } } diff --git a/app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt b/app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt new file mode 100644 index 00000000000..2fa51a92316 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt @@ -0,0 +1,146 @@ +/* + * 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 androidx.compose.runtime.Immutable + +@Immutable +data class SettingsUiState( + val isOnline: Boolean = false, + val account: AccountUiState = AccountUiState(), + val accountMessage: AccountMessage? = null, + val appearance: AppearanceUiState = AppearanceUiState(), + val notifications: NotificationsUiState = NotificationsUiState(), + val privacy: PrivacyUiState = PrivacyUiState(), + val loggingStatus: LoggingStatus = LoggingStatus.ENABLED, + val mediaQualityReduced: Boolean = false, + val clientCertificateSet: Boolean = false, + val proxy: ProxyUiState = ProxyUiState(), + /** Whether the screen was opened to fix the notification setup, so that problems there are highlighted. */ + val highlightNotificationIssues: Boolean = false, + val showPhoneNumberDialog: Boolean = false, + val phoneNumberError: Boolean = false +) + +@Immutable +data class AccountUiState( + val displayName: String = "", + val baseUrl: String = "", + val avatarId: String = "", + val serverAgeWarning: ServerAgeWarning = ServerAgeWarning.NONE +) + +enum class ServerAgeWarning { + NONE, + ALMOST_END_OF_LIFE, + END_OF_LIFE +} + +enum class AccountMessage { + ACCOUNT_UPDATED, + SERVER_WITHOUT_TALK, + ACCOUNT_IMPORTED, + ACCOUNT_IMPORT_FAILED +} + +@Immutable +data class AppearanceUiState( + /** Entry value of `R.array.theme_entry_values`. */ + val theme: String = "", + val showEcosystemSetting: Boolean = true, + val showEcosystem: Boolean = false +) + +@Immutable +data class NotificationsUiState( + /** Null if UnifiedPush can't be used, as no distributor is installed or an account doesn't support web push. */ + val unifiedPush: UnifiedPushUiState? = null, + val pushAvailability: PushAvailability = PushAvailability.AVAILABLE, + val serverNotificationAppMissing: Boolean = false, + /** Null on devices that don't need the permission. */ + val notificationPermissionGranted: Boolean? = null, + val batteryOptimizationIgnored: Boolean = true, + /** Null on devices that don't need the permission. */ + val fullScreenIntentGranted: Boolean? = null, + val callRingtone: RingtoneState = RingtoneState.Default, + val messageRingtone: RingtoneState = RingtoneState.Default, + val showNotificationWarningSetting: Boolean = false, + val showNotificationWarning: Boolean = false +) { + val ringtoneSettingsEnabled: Boolean + get() = notificationPermissionGranted != false +} + +@Immutable +data class UnifiedPushUiState(val enabled: Boolean, val distributor: String, val canPickDistributor: Boolean) + +enum class PushAvailability { + AVAILABLE, + GOOGLE_PLAY_SERVICES_UNAVAILABLE, + UNIFIED_PUSH_DISABLED_AND_GOOGLE_PLAY_SERVICES_UNAVAILABLE +} + +@Immutable +sealed interface RingtoneState { + /** The notification channel is turned off. */ + data object Disabled : RingtoneState + data object Silent : RingtoneState + data object Default : RingtoneState + data class Custom(val title: String) : RingtoneState +} + +@Immutable +data class PrivacyUiState( + /** The app lock requires a secure lock screen of the device. */ + val screenLockAvailable: Boolean = false, + val screenLock: Boolean = false, + /** Entry value of `R.array.screen_lock_timeout_entry_values`. */ + val screenLockTimeout: String = "", + val screenSecurity: Boolean = false, + val incognitoKeyboard: Boolean = false, + val phoneBookIntegrationAvailable: Boolean = false, + val phoneBookIntegration: Boolean = false, + val readStatusAvailable: Boolean = false, + val readStatusShared: Boolean = false, + val typingStatus: TypingStatusUiState = TypingStatusUiState.Hidden +) + +@Immutable +sealed interface TypingStatusUiState { + data object Hidden : TypingStatusUiState + + /** Typing status requires the high performance backend, which the server doesn't use. */ + data object RequiresHighPerformanceBackend : TypingStatusUiState + data class Available(val shared: Boolean) : TypingStatusUiState +} + +enum class LoggingStatus { + DISABLED, + ENABLED, + ADVANCED +} + +@Immutable +data class ProxyUiState( + /** One of `R.array.proxy_type_descriptions`. */ + val type: String = "", + val host: String = "", + val port: String = "", + val useCredentials: Boolean = false, + val username: String = "", + val password: String = "" +) + +/** One-off effects of the settings screen that the activity performs. */ +sealed interface SettingsEvent { + data class ShowMessage(val messageRes: Int) : SettingsEvent + data class AccountRemoved(val displayName: String) : SettingsEvent + data object AccountRemovalFailed : SettingsEvent + + /** The account of the screen doesn't exist anymore. */ + data object AccountUnavailable : SettingsEvent +} diff --git a/app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt b/app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt new file mode 100644 index 00000000000..7ee773ed40d --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt @@ -0,0 +1,622 @@ +/* + * 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.annotation.SuppressLint +import android.content.Context +import androidx.annotation.VisibleForTesting +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import androidx.work.OneTimeWorkRequest +import androidx.work.WorkInfo +import androidx.work.WorkManager +import com.nextcloud.talk.R +import com.nextcloud.talk.conversationlist.ConversationsListActivity.Companion.NOTIFICATION_WARNING_DATE_NOT_SET +import com.nextcloud.talk.dagger.modules.ApplicationScope +import com.nextcloud.talk.data.network.NetworkMonitor +import com.nextcloud.talk.data.user.model.User +import com.nextcloud.talk.jobs.AccountRemovalWorker +import com.nextcloud.talk.jobs.CapabilitiesSyncWorker +import com.nextcloud.talk.jobs.ContactAddressBookWorker +import com.nextcloud.talk.logger.Level +import com.nextcloud.talk.logger.Logger +import com.nextcloud.talk.logger.LogsRepository +import com.nextcloud.talk.settings.data.SettingsRepository +import com.nextcloud.talk.users.UserManager +import com.nextcloud.talk.utils.CapabilitiesUtil +import com.nextcloud.talk.utils.SecurityUtils +import com.nextcloud.talk.utils.SpreedFeatures +import com.nextcloud.talk.utils.preferences.AppPreferences +import com.nextcloud.talk.utils.setExpeditedIfSupported +import com.nextcloud.talk.utils.singletons.ApplicationWideMessageHolder +import dagger.assisted.Assisted +import dagger.assisted.AssistedFactory +import dagger.assisted.AssistedInject +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import retrofit2.HttpException +import java.io.IOException + +@Suppress("LongParameterList", "TooManyFunctions") +class SettingsViewModel @AssistedInject constructor( + private val appPreferences: AppPreferences, + private val userManager: UserManager, + private val settingsRepository: SettingsRepository, + private val logsRepository: LogsRepository, + private val deviceStateReader: DeviceStateReader, + private val workManager: WorkManager, + private val logger: Logger, + networkMonitor: NetworkMonitor, + @ApplicationScope private val appScope: CoroutineScope, + // Dagger provides the application context, which cannot leak an Activity + @field:SuppressLint("StaticFieldLeak") private val context: Context, + @Assisted initialUser: User, + @Assisted highlightNotificationIssues: Boolean +) : ViewModel() { + + @VisibleForTesting + internal var ioDispatcher: CoroutineDispatcher = Dispatchers.IO + + // preferences are written in the order they were changed, and also after the screen was closed + private val preferenceWriter by lazy { ioDispatcher.limitedParallelism(1) } + + private val userId = initialUser.id!! + private val user = MutableStateFlow(initialUser) + private val noProxy = context.getString(R.string.nc_no_proxy) + + // The last values in the stored account, which are only updated with the capabilities. A change is shown until + // they change, so that an update of e.g. the display name doesn't revert it. + private var serverReadStatusShared: Boolean? = null + private var serverTypingStatusShared: Boolean? = null + + private var allAccountsSupportWebPush = false + private var unifiedPushPreference = false + private var deviceState: DeviceState? = null + private var isRemovingAccount = false + + private val _uiState = MutableStateFlow(initialState(initialUser, highlightNotificationIssues)) + val uiState: StateFlow = _uiState.asStateFlow() + + private val _events = Channel(Channel.BUFFERED) + val events: Flow = _events.receiveAsFlow() + + val clientCertificateAlias: String? + get() = user.value.clientCertificate?.takeIf { it.isNotEmpty() } + + init { + clearDisabledProxySettings() + viewModelScope.launch { + userManager.userFlow(userId).collect { updatedUser -> + if (updatedUser == null || (updatedUser.scheduledForDeletion && !isRemovingAccount)) { + _events.send(SettingsEvent.AccountUnavailable) + } else { + user.value = updatedUser + } + } + } + viewModelScope.launch { + combine(user, networkMonitor.isOnline, ::Pair).collect { (currentUser, isOnline) -> + _uiState.update { it.withUser(currentUser, isOnline) } + } + } + } + + /** Refreshes everything that may have changed while the screen was in the background. */ + fun onResume() { + _uiState.update { it.copy(loggingStatus = loggingStatus(), accountMessage = consumeAccountMessage()) } + refreshDeviceState() + refreshUserProfile() + workManager.enqueue( + OneTimeWorkRequest.Builder(CapabilitiesSyncWorker::class.java).setExpeditedIfSupported().build() + ) + } + + fun refreshDeviceState() { + viewModelScope.launch { + allAccountsSupportWebPush = userManager.getUsers().all { it.hasWebPushCapability } + val (useUnifiedPush, state) = withContext(ioDispatcher) { + appPreferences.useUnifiedPush to deviceStateReader.read() + } + unifiedPushPreference = useUnifiedPush + deviceState = state + if (!state.isKeyguardSecure) { + persist { prefs -> + prefs.removeScreenLock() + prefs.removeScreenLockTimeout() + } + } + _uiState.update { + it.copy( + notifications = notificationsState(state), + privacy = it.privacy.copy( + screenLockAvailable = state.isKeyguardSecure, + screenLock = state.isKeyguardSecure && it.privacy.screenLock + ) + ) + } + } + } + + fun dismissAccountMessage() { + _uiState.update { it.copy(accountMessage = null) } + } + + fun setTheme(theme: String) { + _uiState.update { it.copy(appearance = it.appearance.copy(theme = theme)) } + persist { prefs -> prefs.theme = theme } + } + + fun setShowEcosystem(show: Boolean) { + _uiState.update { it.copy(appearance = it.appearance.copy(showEcosystem = show)) } + persist { prefs -> prefs.setShowEcosystem(show) } + } + + fun setUseUnifiedPush(enabled: Boolean) { + val state = deviceState ?: return + unifiedPushPreference = enabled + persist { prefs -> prefs.useUnifiedPush = enabled } + _uiState.update { it.copy(notifications = notificationsState(state)) } + } + + fun onDistributorChanged(distributor: String?) { + _uiState.update { + val unifiedPush = it.notifications.unifiedPush ?: return@update it + val updated = unifiedPush.copy(distributor = distributor.orEmpty()) + it.copy(notifications = it.notifications.copy(unifiedPush = updated)) + } + } + + fun setShowNotificationWarning(show: Boolean) { + _uiState.update { it.copy(notifications = it.notifications.copy(showNotificationWarning = show)) } + persist { prefs -> + prefs.setShowRegularNotificationWarning(show) + if (show) { + prefs.setNotificationWarningLastPostponedDate(NOTIFICATION_WARNING_DATE_NOT_SET) + } + } + } + + fun setScreenLock(enabled: Boolean) { + _uiState.update { it.copy(privacy = it.privacy.copy(screenLock = enabled)) } + val timeout = _uiState.value.privacy.screenLockTimeout + persist { prefs -> + prefs.setScreenLock(enabled) + if (enabled) { + SecurityUtils.createKey(timeout) + prefs.lockTimestamp = System.currentTimeMillis() + } + } + } + + fun setScreenLockTimeout(timeout: String) { + _uiState.update { it.copy(privacy = it.privacy.copy(screenLockTimeout = timeout)) } + persist { prefs -> + prefs.screenLockTimeout = timeout + SecurityUtils.createKey(timeout) + } + } + + fun setScreenSecurity(enabled: Boolean) { + _uiState.update { it.copy(privacy = it.privacy.copy(screenSecurity = enabled)) } + persist { prefs -> prefs.setScreenSecurity(enabled) } + } + + fun setIncognitoKeyboard(enabled: Boolean) { + _uiState.update { it.copy(privacy = it.privacy.copy(incognitoKeyboard = enabled)) } + persist { prefs -> prefs.setIncognitoKeyboard(enabled) } + } + + /** Enables the phone book integration, for which the contacts permissions must be granted. */ + fun enablePhoneBookIntegration() { + setPhoneBookIntegrationState(true) + persist { prefs -> prefs.setPhoneBookIntegration(true) } + ContactAddressBookWorker.syncNow(workManager) + viewModelScope.launch { + try { + if (settingsRepository.getUserProfile(user.value)?.phone.isNullOrEmpty()) { + _uiState.update { it.copy(showPhoneNumberDialog = true, phoneNumberError = false) } + } + } catch (e: IOException) { + logger.w(TAG, "Failed to check for the phone number", e) + } catch (e: HttpException) { + logger.w(TAG, "Failed to check for the phone number", e) + } + } + } + + fun disablePhoneBookIntegration() { + setPhoneBookIntegrationState(false) + persist { prefs -> prefs.setPhoneBookIntegration(false) } + ContactAddressBookWorker.deleteAll(workManager) + } + + fun onContactsPermissionDenied() { + setPhoneBookIntegrationState(false) + persist { prefs -> prefs.setPhoneBookIntegration(false) } + _events.trySend(SettingsEvent.ShowMessage(R.string.no_phone_book_integration_due_to_permissions)) + } + + fun submitPhoneNumber(phoneNumber: String) { + viewModelScope.launch { + val accepted = try { + settingsRepository.setPhoneNumber(user.value, phoneNumber) + } catch (e: IOException) { + logger.e(TAG, "Failed to set the phone number", e) + false + } catch (e: HttpException) { + logger.e(TAG, "Failed to set the phone number", e) + false + } + if (accepted) { + _uiState.update { it.copy(showPhoneNumberDialog = false, phoneNumberError = false) } + _events.send( + SettingsEvent.ShowMessage(R.string.nc_settings_phone_book_integration_phone_number_dialog_success) + ) + } else { + _uiState.update { it.copy(phoneNumberError = true) } + } + } + } + + fun clearPhoneNumberError() { + _uiState.update { it.copy(phoneNumberError = false) } + } + + fun dismissPhoneNumberDialog() { + _uiState.update { it.copy(showPhoneNumberDialog = false, phoneNumberError = false) } + } + + fun setReadStatusShared(shared: Boolean) { + updatePrivacySetting( + apply = { state, value -> state.copy(readStatusShared = value) }, + shared = shared, + request = { settingsRepository.setReadStatusShared(user.value, shared) } + ) + } + + fun setTypingStatusShared(shared: Boolean) { + updatePrivacySetting( + apply = { state, value -> + if (state.typingStatus is TypingStatusUiState.Available) { + state.copy(typingStatus = TypingStatusUiState.Available(value)) + } else { + state + } + }, + shared = shared, + request = { settingsRepository.setTypingStatusShared(user.value, shared) } + ) + } + + fun setMediaQualityReduced(reduced: Boolean) { + _uiState.update { it.copy(mediaQualityReduced = reduced) } + persist { prefs -> prefs.setCompressUploadImages(reduced) } + } + + /** Stores the alias of the chosen client certificate, or removes it if [alias] is null. */ + fun onClientCertificateChosen(alias: String?) { + _uiState.update { it.copy(clientCertificateSet = alias != null) } + viewModelScope.launch { + userManager.updateClientCertificate(userId, alias.orEmpty()) + } + } + + fun setProxyType(type: String) { + if (!isProxyEnabled(type)) { + _uiState.update { it.copy(proxy = ProxyUiState(type = type)) } + persist { prefs -> prefs.proxyType = type } + clearProxySettings() + return + } + val port = defaultProxyPort(type) ?: _uiState.value.proxy.port + _uiState.update { it.copy(proxy = it.proxy.copy(type = type, port = port)) } + persist { prefs -> + prefs.proxyType = type + prefs.proxyPort = port + } + } + + fun setProxyHost(host: String) { + _uiState.update { it.copy(proxy = it.proxy.copy(host = host)) } + persist { prefs -> prefs.proxyHost = host } + } + + fun setProxyPort(port: String) { + _uiState.update { it.copy(proxy = it.proxy.copy(port = port)) } + persist { prefs -> prefs.proxyPort = port } + } + + fun setProxyUseCredentials(useCredentials: Boolean) { + _uiState.update { + it.copy( + proxy = if (useCredentials) { + it.proxy.copy(useCredentials = true) + } else { + it.proxy.copy(useCredentials = false, username = "", password = "") + } + ) + } + persist { prefs -> + prefs.setProxyNeedsCredentials(useCredentials) + if (!useCredentials) { + prefs.removeProxyUsername() + prefs.removeProxyPassword() + } + } + } + + fun setProxyUsername(username: String) { + _uiState.update { it.copy(proxy = it.proxy.copy(username = username)) } + persist { prefs -> prefs.proxyUsername = username } + } + + fun setProxyPassword(password: String) { + _uiState.update { it.copy(proxy = it.proxy.copy(password = password)) } + persist { prefs -> prefs.proxyPassword = password } + } + + fun removeAccount() { + if (isRemovingAccount) return + isRemovingAccount = true + val displayName = _uiState.value.account.displayName + viewModelScope.launch { + userManager.scheduleUserForDeletionWithId(userId) + val request = OneTimeWorkRequest.Builder(AccountRemovalWorker::class.java) + .setExpeditedIfSupported() + .build() + workManager.enqueue(request) + val result = workManager.getWorkInfoByIdFlow(request.id).first { it?.state?.isFinished == true } + if (result?.state == WorkInfo.State.SUCCEEDED) { + _events.send(SettingsEvent.AccountRemoved(displayName)) + } else { + logger.e(TAG, "Failed to remove the account with id $userId") + _events.send(SettingsEvent.AccountRemovalFailed) + } + } + } + + private fun initialState(initialUser: User, highlightNotificationIssues: Boolean): SettingsUiState { + val proxyType = appPreferences.proxyType.ifEmpty { noProxy } + val useCredentials = isProxyEnabled(proxyType) && appPreferences.proxyCredentials + return SettingsUiState( + account = accountState(initialUser), + appearance = AppearanceUiState( + theme = appPreferences.theme, + showEcosystemSetting = !context.resources.getBoolean(R.bool.is_branded_client), + showEcosystem = appPreferences.isShowEcosystem + ), + notifications = NotificationsUiState( + showNotificationWarning = appPreferences.showRegularNotificationWarning == true + ), + privacy = PrivacyUiState( + screenLock = appPreferences.isScreenLocked, + screenLockTimeout = appPreferences.screenLockTimeout, + screenSecurity = appPreferences.isScreenSecured, + incognitoKeyboard = appPreferences.isKeyboardIncognito, + phoneBookIntegration = appPreferences.isPhoneBookIntegrationEnabled + ), + loggingStatus = loggingStatus(), + mediaQualityReduced = appPreferences.compressUploadImages, + clientCertificateSet = !initialUser.clientCertificate.isNullOrEmpty(), + proxy = if (isProxyEnabled(proxyType)) { + ProxyUiState( + type = proxyType, + host = appPreferences.proxyHost, + port = appPreferences.proxyPort, + useCredentials = useCredentials, + username = if (useCredentials) appPreferences.proxyUsername else "", + password = if (useCredentials) appPreferences.proxyPassword else "" + ) + } else { + ProxyUiState(type = proxyType) + }, + highlightNotificationIssues = highlightNotificationIssues + ) + } + + private fun SettingsUiState.withUser(currentUser: User, isOnline: Boolean): SettingsUiState { + val readStatusShared = !CapabilitiesUtil.isReadStatusPrivate(currentUser) + val typingStatusShared = !CapabilitiesUtil.isTypingStatusPrivate(currentUser) + val readStatusChangedOnServer = readStatusShared != serverReadStatusShared + val typingStatusChangedOnServer = typingStatusShared != serverTypingStatusShared + serverReadStatusShared = readStatusShared + serverTypingStatusShared = typingStatusShared + + val spreedCapability = currentUser.capabilities?.spreedCapability + val typingStatus = when { + currentUser.externalSignalingServer?.externalSignalingServer.isNullOrEmpty() -> + TypingStatusUiState.RequiresHighPerformanceBackend + !isOnline || !CapabilitiesUtil.isTypingStatusAvailable(currentUser) -> TypingStatusUiState.Hidden + typingStatusChangedOnServer || privacy.typingStatus !is TypingStatusUiState.Available -> + TypingStatusUiState.Available(typingStatusShared) + else -> privacy.typingStatus + } + return copy( + isOnline = isOnline, + account = accountState(currentUser), + notifications = notifications.copy( + serverNotificationAppMissing = + currentUser.capabilities?.notificationsCapability?.features.isNullOrEmpty() + ), + privacy = privacy.copy( + phoneBookIntegrationAvailable = isOnline && + CapabilitiesUtil.hasSpreedFeatureCapability(spreedCapability, SpreedFeatures.PHONEBOOK_SEARCH), + readStatusAvailable = isOnline && CapabilitiesUtil.isReadStatusAvailable(spreedCapability), + readStatusShared = if (readStatusChangedOnServer) readStatusShared else privacy.readStatusShared, + typingStatus = typingStatus + ) + ) + } + + private fun accountState(currentUser: User): AccountUiState { + val serverVersion = currentUser.serverVersion?.major + return AccountUiState( + displayName = currentUser.displayName.orEmpty(), + baseUrl = currentUser.baseUrl.orEmpty(), + avatarId = currentUser.userId?.takeIf { it.isNotEmpty() } ?: currentUser.username.orEmpty(), + serverAgeWarning = when { + CapabilitiesUtil.isServerEOL(serverVersion) -> ServerAgeWarning.END_OF_LIFE + CapabilitiesUtil.isServerAlmostEOL(serverVersion) -> ServerAgeWarning.ALMOST_END_OF_LIFE + else -> ServerAgeWarning.NONE + } + ) + } + + private fun notificationsState(state: DeviceState): NotificationsUiState { + val current = _uiState.value.notifications + // UnifiedPush is only offered if every account supports web push + val unifiedPushOffered = state.externalDistributorCount > 0 && allAccountsSupportWebPush + val unifiedPushEnabled = unifiedPushOffered && unifiedPushPreference + val unifiedPush = if (unifiedPushOffered) { + UnifiedPushUiState( + enabled = unifiedPushEnabled, + distributor = current.unifiedPush?.distributor?.takeIf { it.isNotEmpty() } + ?: state.acknowledgedDistributor.orEmpty(), + canPickDistributor = unifiedPushEnabled && state.externalDistributorCount > 1 + ) + } else { + null + } + val pushAvailability = when { + state.isGooglePlayServicesAvailable || unifiedPushPreference || state.hasEmbeddedDistributor -> + PushAvailability.AVAILABLE + unifiedPushOffered -> PushAvailability.UNIFIED_PUSH_DISABLED_AND_GOOGLE_PLAY_SERVICES_UNAVAILABLE + else -> PushAvailability.GOOGLE_PLAY_SERVICES_UNAVAILABLE + } + return current.copy( + unifiedPush = unifiedPush, + pushAvailability = pushAvailability, + notificationPermissionGranted = state.notificationPermissionGranted, + batteryOptimizationIgnored = state.batteryOptimizationIgnored, + fullScreenIntentGranted = state.fullScreenIntentGranted, + callRingtone = state.callRingtone, + messageRingtone = state.messageRingtone, + showNotificationWarningSetting = state.isGooglePlayServicesAvailable + ) + } + + private fun updatePrivacySetting( + apply: (PrivacyUiState, Boolean) -> PrivacyUiState, + shared: Boolean, + request: suspend () -> Unit + ) { + _uiState.update { it.copy(privacy = apply(it.privacy, shared)) } + viewModelScope.launch { + try { + request() + } catch (e: IOException) { + logger.e(TAG, "Failed to change a privacy setting", e) + _uiState.update { it.copy(privacy = apply(it.privacy, !shared)) } + } catch (e: HttpException) { + logger.e(TAG, "Failed to change a privacy setting", e) + _uiState.update { it.copy(privacy = apply(it.privacy, !shared)) } + } + } + } + + private fun setPhoneBookIntegrationState(enabled: Boolean) { + _uiState.update { it.copy(privacy = it.privacy.copy(phoneBookIntegration = enabled)) } + } + + private fun loggingStatus(): LoggingStatus = + when { + logsRepository.minimumLevel == Level.NONE -> LoggingStatus.DISABLED + logsRepository.minimumLevel <= Level.DEBUG -> LoggingStatus.ADVANCED + else -> LoggingStatus.ENABLED + } + + private fun consumeAccountMessage(): AccountMessage? { + val holder = ApplicationWideMessageHolder.getInstance() + val message = when (holder.messageType) { + ApplicationWideMessageHolder.MessageType.ACCOUNT_UPDATED_NOT_ADDED -> AccountMessage.ACCOUNT_UPDATED + ApplicationWideMessageHolder.MessageType.SERVER_WITHOUT_TALK -> AccountMessage.SERVER_WITHOUT_TALK + ApplicationWideMessageHolder.MessageType.ACCOUNT_WAS_IMPORTED -> AccountMessage.ACCOUNT_IMPORTED + ApplicationWideMessageHolder.MessageType.FAILED_TO_IMPORT_ACCOUNT -> AccountMessage.ACCOUNT_IMPORT_FAILED + else -> null + } + holder.messageType = null + return message ?: _uiState.value.accountMessage + } + + private fun refreshUserProfile() { + viewModelScope.launch { + val profile = try { + settingsRepository.getUserProfile(user.value) + } catch (e: IOException) { + logger.w(TAG, "Failed to load the user profile", e) + null + } catch (e: HttpException) { + logger.w(TAG, "Failed to load the user profile", e) + null + } + val displayName = profile?.displayName?.takeIf { it.isNotEmpty() } + ?: profile?.displayNameAlt?.takeIf { it.isNotEmpty() } + if (displayName != null && displayName != user.value.displayName) { + userManager.updateDisplayName(userId, displayName) + } + } + } + + private fun isProxyEnabled(type: String): Boolean = type.isNotEmpty() && type != noProxy + + private fun defaultProxyPort(type: String): String? = + when (type) { + PROXY_TYPE_HTTP -> context.getString(R.string.nc_settings_http_value) + PROXY_TYPE_DIRECT -> context.getString(R.string.nc_settings_direct_value) + PROXY_TYPE_SOCKS -> context.getString(R.string.nc_settings_socks_value) + else -> null + } + + private fun clearDisabledProxySettings() { + val proxy = _uiState.value.proxy + when { + !isProxyEnabled(proxy.type) -> clearProxySettings() + !proxy.useCredentials -> persist { prefs -> + prefs.removeProxyUsername() + prefs.removeProxyPassword() + } + } + } + + private fun clearProxySettings() { + persist { prefs -> + prefs.removeProxyHost() + prefs.removeProxyPort() + prefs.removeProxyCredentials() + prefs.removeProxyUsername() + prefs.removeProxyPassword() + } + } + + private fun persist(write: (AppPreferences) -> Unit) { + appScope.launch(preferenceWriter) { write(appPreferences) } + } + + @AssistedFactory + interface Factory { + fun build(user: User, highlightNotificationIssues: Boolean): SettingsViewModel + } + + companion object { + private val TAG = SettingsViewModel::class.java.simpleName + private const val PROXY_TYPE_HTTP = "HTTP" + private const val PROXY_TYPE_DIRECT = "DIRECT" + private const val PROXY_TYPE_SOCKS = "SOCKS" + } +} diff --git a/app/src/main/java/com/nextcloud/talk/settings/data/SettingsRepository.kt b/app/src/main/java/com/nextcloud/talk/settings/data/SettingsRepository.kt new file mode 100644 index 00000000000..8eb260d6c54 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/data/SettingsRepository.kt @@ -0,0 +1,24 @@ +/* + * 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.data + +import com.nextcloud.talk.data.user.model.User +import com.nextcloud.talk.models.json.userprofile.UserProfileDataDto + +/** + * Server side account settings shown on the settings screen. All functions throw on network or server errors. + */ +interface SettingsRepository { + suspend fun getUserProfile(user: User): UserProfileDataDto? + + /** Returns whether the server accepted [phoneNumber]. */ + suspend fun setPhoneNumber(user: User, phoneNumber: String): Boolean + + suspend fun setReadStatusShared(user: User, shared: Boolean) + + suspend fun setTypingStatusShared(user: User, shared: Boolean) +} diff --git a/app/src/main/java/com/nextcloud/talk/settings/data/SettingsRepositoryImpl.kt b/app/src/main/java/com/nextcloud/talk/settings/data/SettingsRepositoryImpl.kt new file mode 100644 index 00000000000..7b3e046b310 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/data/SettingsRepositoryImpl.kt @@ -0,0 +1,72 @@ +/* + * 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.data + +import com.nextcloud.talk.api.NcApiCoroutines +import com.nextcloud.talk.data.user.model.User +import com.nextcloud.talk.models.json.userprofile.UserProfileDataDto +import com.nextcloud.talk.utils.ApiUtils +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody +import okhttp3.RequestBody.Companion.toRequestBody +import org.json.JSONObject +import javax.inject.Inject + +class SettingsRepositoryImpl @Inject constructor(private val ncApiCoroutines: NcApiCoroutines) : SettingsRepository { + + override suspend fun getUserProfile(user: User): UserProfileDataDto? = + ncApiCoroutines.getUserProfile( + user.credentials(), + ApiUtils.getUrlForUserProfile(user.baseUrl!!) + ).ocs?.data + + override suspend fun setPhoneNumber(user: User, phoneNumber: String): Boolean { + val response = ncApiCoroutines.setUserData( + user.credentials(), + ApiUtils.getUrlForUserData(user.baseUrl!!, user.userId!!), + KEY_PHONE, + phoneNumber + ) + return response.ocs?.meta?.statusCode == HTTP_OK + } + + override suspend fun setReadStatusShared(user: User, shared: Boolean) { + ncApiCoroutines.setReadStatusPrivacy( + user.credentials(), + ApiUtils.getUrlForUserSettings(user.baseUrl!!), + privacySettingBody(KEY_READ_STATUS_PRIVACY, shared) + ) + } + + override suspend fun setTypingStatusShared(user: User, shared: Boolean) { + ncApiCoroutines.setTypingStatusPrivacy( + user.credentials(), + ApiUtils.getUrlForUserSettings(user.baseUrl!!), + privacySettingBody(KEY_TYPING_PRIVACY, shared) + ) + } + + private fun User.credentials(): String = ApiUtils.getCredentials(username, token).orEmpty() + + /** The server expects 0 for public and 1 for private. */ + private fun privacySettingBody(key: String, shared: Boolean): RequestBody = + JSONObject() + .put("key", key) + .put("value", if (shared) PRIVACY_PUBLIC else PRIVACY_PRIVATE) + .toString() + .toRequestBody(JSON_MEDIA_TYPE) + + companion object { + private const val KEY_PHONE = "phone" + private const val KEY_READ_STATUS_PRIVACY = "read_status_privacy" + private const val KEY_TYPING_PRIVACY = "typing_privacy" + private const val PRIVACY_PUBLIC = 0 + private const val PRIVACY_PRIVATE = 1 + private const val HTTP_OK = 200 + private val JSON_MEDIA_TYPE = "application/json".toMediaType() + } +} diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsAccountSection.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsAccountSection.kt new file mode 100644 index 00000000000..57028f41a59 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsAccountSection.kt @@ -0,0 +1,214 @@ +/* + * 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.res.Configuration +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.clickable +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.material3.Card +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalInspectionMode +import androidx.compose.ui.res.colorResource +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.core.net.toUri +import coil.compose.AsyncImage +import com.nextcloud.talk.R +import com.nextcloud.talk.contacts.loadImage +import com.nextcloud.talk.settings.AccountMessage +import com.nextcloud.talk.settings.AccountUiState +import com.nextcloud.talk.settings.ServerAgeWarning +import com.nextcloud.talk.settings.SettingsUiState +import com.nextcloud.talk.utils.ApiUtils +import kotlinx.coroutines.delay + +private const val ACCOUNT_MESSAGE_DURATION_MS = 5000L +private const val ACCOUNT_MESSAGE_FADE_OUT_MS = 2500 + +@Composable +internal fun AccountSection(state: SettingsUiState, callbacks: SettingsScreenCallbacks) { + var showRemoveAccountDialog by rememberSaveable { mutableStateOf(false) } + Column { + AccountMessageBanner(message = state.accountMessage, onShown = callbacks.onAccountMessageShown) + AccountHeader(account = state.account, onClick = callbacks.onProfileClick) + if (state.account.serverAgeWarning != ServerAgeWarning.NONE) { + ServerAgeWarningCard(state.account.serverAgeWarning) + } + Text( + text = stringResource(R.string.nc_settings_remove_account), + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.error, + modifier = Modifier + .fillMaxWidth() + .clickable { showRemoveAccountDialog = true } + .padding(16.dp) + ) + } + if (showRemoveAccountDialog) { + RemoveAccountDialog( + onConfirm = { + showRemoveAccountDialog = false + callbacks.onRemoveAccount() + }, + onDismiss = { showRemoveAccountDialog = false } + ) + } +} + +/** Shows [message] for a while and fades it out, then reports it as shown. */ +@Composable +private fun AccountMessageBanner(message: AccountMessage?, onShown: () -> Unit) { + var visible by remember(message) { mutableStateOf(message != null) } + LaunchedEffect(message) { + if (message != null) { + delay(ACCOUNT_MESSAGE_DURATION_MS) + visible = false + delay(ACCOUNT_MESSAGE_FADE_OUT_MS.toLong()) + onShown() + } + } + AnimatedVisibility(visible = visible, exit = fadeOut(tween(ACCOUNT_MESSAGE_FADE_OUT_MS))) { + val (text, color) = when (message) { + AccountMessage.ACCOUNT_UPDATED -> + stringResource(R.string.nc_settings_account_updated) to MaterialTheme.colorScheme.primary + AccountMessage.SERVER_WITHOUT_TALK -> + stringResource(R.string.nc_settings_wrong_account) to MaterialTheme.colorScheme.error + AccountMessage.ACCOUNT_IMPORTED -> + stringResource(R.string.nc_Server_account_imported) to MaterialTheme.colorScheme.primary + AccountMessage.ACCOUNT_IMPORT_FAILED -> + stringResource(R.string.nc_server_failed_to_import_account) to MaterialTheme.colorScheme.error + null -> "" to Color.Unspecified + } + Text( + text = text, + color = color, + textAlign = TextAlign.Center, + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) + ) + } +} + +@Composable +private fun AccountHeader(account: AccountUiState, onClick: () -> Unit) { + Column( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(16.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + AccountAvatar(account) + Text( + text = account.displayName, + style = MaterialTheme.typography.titleLarge, + textAlign = TextAlign.Center, + modifier = Modifier.padding(top = 8.dp) + ) + Text( + text = remember(account.baseUrl) { account.baseUrl.toUri().host.orEmpty() }, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + modifier = Modifier.padding(top = 4.dp) + ) + } +} + +@Composable +private fun AccountAvatar(account: AccountUiState) { + val modifier = Modifier.size(avatarSize) + if (LocalInspectionMode.current) { + Icon( + painter = painterResource(R.drawable.account_circle_96dp), + contentDescription = stringResource(R.string.avatar), + modifier = modifier + ) + return + } + val context = LocalContext.current + val isDarkTheme = isSystemInDarkTheme() + val request = remember(account.baseUrl, account.avatarId, isDarkTheme) { + loadImage( + ApiUtils.getUrlForAvatar(account.baseUrl, account.avatarId, true, isDarkTheme), + context, + R.drawable.account_circle_96dp + ) + } + AsyncImage(model = request, contentDescription = stringResource(R.string.avatar), modifier = modifier) +} + +@Composable +private fun ServerAgeWarningCard(warning: ServerAgeWarning) { + val (text, color) = if (warning == ServerAgeWarning.END_OF_LIFE) { + stringResource(R.string.nc_settings_server_eol) to MaterialTheme.colorScheme.error + } else { + stringResource(R.string.nc_settings_server_almost_eol) to colorResource(R.color.nc_darkYellow) + } + Card( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) + ) { + Row(modifier = Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) { + Icon( + painter = painterResource(R.drawable.ic_warning_white), + contentDescription = stringResource(R.string.nc_settings_warning), + tint = color + ) + Spacer(modifier = Modifier.width(16.dp)) + Text(text = text, color = color, style = MaterialTheme.typography.bodyMedium) + } + } +} + +private val avatarSize = 96.dp + +@Preview(name = "Light") +@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES) +@Preview(name = "RTL Arabic", locale = "ar") +@Composable +private fun AccountSectionPreview() { + MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) { + Surface { + AccountSection( + state = previewSettingsState().copy(accountMessage = AccountMessage.ACCOUNT_IMPORTED), + callbacks = SettingsScreenCallbacks() + ) + } + } +} diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsComponents.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsComponents.kt new file mode 100644 index 00000000000..4859301723f --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsComponents.kt @@ -0,0 +1,244 @@ +/* + * 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.res.Configuration +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.selection.toggleable +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExposedDropdownMenuAnchorType +import androidx.compose.material3.ExposedDropdownMenuBox +import androidx.compose.material3.ExposedDropdownMenuDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.delay + +private const val DISABLED_ALPHA = 0.38f +private const val HIGHLIGHT_ALPHA = 0.24f +private const val HIGHLIGHT_START_DELAY_MS = 1000L +private const val HIGHLIGHT_BLINK_DURATION_MS = 250 +private const val HIGHLIGHT_BLINK_COUNT = 3 + +@Composable +internal fun SettingsSectionHeader(title: String, modifier: Modifier = Modifier) { + Text( + text = title, + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.primary, + modifier = modifier + .fillMaxWidth() + .padding(start = 16.dp, end = 16.dp, top = 24.dp, bottom = 8.dp) + ) +} + +/** + * A setting with a [title] and an optional [summary]. Clickable if [onClick] is given and it is [enabled]. With + * [highlight], it blinks to draw attention to it. + */ +@Suppress("LongParameterList") +@Composable +internal fun SettingsItem( + title: String, + modifier: Modifier = Modifier, + summary: String? = null, + summaryColor: Color = Color.Unspecified, + enabled: Boolean = true, + highlight: Boolean = false, + onClick: (() -> Unit)? = null +) { + Column( + modifier = modifier + .fillMaxWidth() + .blinkingHighlight(highlight) + .then(if (onClick != null) Modifier.clickable(enabled = enabled, onClick = onClick) else Modifier) + .alpha(if (enabled) 1f else DISABLED_ALPHA) + .padding(horizontal = 16.dp, vertical = 12.dp) + ) { + Text(text = title, style = MaterialTheme.typography.bodyLarge) + if (summary != null) { + Text( + text = summary, + style = MaterialTheme.typography.bodyMedium, + color = if (summaryColor == Color.Unspecified) { + MaterialTheme.colorScheme.onSurfaceVariant + } else { + summaryColor + } + ) + } + } +} + +/** A setting that is turned on and off by clicking anywhere on it. */ +@Suppress("LongParameterList") +@Composable +internal fun SettingsSwitchItem( + title: String, + checked: Boolean, + onCheckedChange: (Boolean) -> Unit, + modifier: Modifier = Modifier, + summary: String? = null, + enabled: Boolean = true, + supportingText: String? = null +) { + Row( + modifier = modifier + .fillMaxWidth() + .toggleable(value = checked, enabled = enabled, role = Role.Switch, onValueChange = onCheckedChange) + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Column( + modifier = Modifier + .weight(1f) + .alpha(if (enabled) 1f else DISABLED_ALPHA) + ) { + Text(text = title, style = MaterialTheme.typography.bodyLarge) + if (summary != null) { + Text( + text = summary, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + if (supportingText != null) { + Text( + text = supportingText, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 8.dp) + ) + } + } + Spacer(modifier = Modifier.width(16.dp)) + Switch(checked = checked, onCheckedChange = null, enabled = enabled) + } +} + +/** A choice of one of [options], given as pairs of the stored value and its label. */ +@Suppress("LongParameterList") +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun SettingsDropdown( + label: String, + options: List>, + selectedValue: String, + onValueSelected: (String) -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true +) { + var expanded by rememberSaveable { mutableStateOf(false) } + ExposedDropdownMenuBox( + expanded = expanded && enabled, + onExpandedChange = { expanded = it }, + modifier = modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp) + ) { + OutlinedTextField( + value = options.firstOrNull { it.first == selectedValue }?.second.orEmpty(), + onValueChange = {}, + readOnly = true, + enabled = enabled, + singleLine = true, + label = { Text(label) }, + trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded && enabled) }, + modifier = Modifier + .fillMaxWidth() + .menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable, enabled) + ) + ExposedDropdownMenu(expanded = expanded && enabled, onDismissRequest = { expanded = false }) { + options.forEach { (value, optionLabel) -> + DropdownMenuItem( + text = { Text(optionLabel) }, + onClick = { + expanded = false + onValueSelected(value) + }, + contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding + ) + } + } + } +} + +/** Blinks the background a few times when [enabled], like a repeated ripple. */ +@Composable +private fun Modifier.blinkingHighlight(enabled: Boolean): Modifier { + if (!enabled) return this + val alpha = remember { Animatable(0f) } + LaunchedEffect(Unit) { + delay(HIGHLIGHT_START_DELAY_MS) + repeat(HIGHLIGHT_BLINK_COUNT) { + alpha.animateTo(HIGHLIGHT_ALPHA, tween(HIGHLIGHT_BLINK_DURATION_MS)) + alpha.animateTo(0f, tween(HIGHLIGHT_BLINK_DURATION_MS)) + } + } + return background(MaterialTheme.colorScheme.onSurface.copy(alpha = alpha.value)) +} + +@Preview(name = "Light") +@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES) +@Preview(name = "RTL Arabic", locale = "ar") +@Composable +private fun SettingsComponentsPreview() { + MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) { + Surface { + Column { + SettingsSectionHeader(title = "Privacy") + SettingsItem(title = "Plain setting", summary = "Some detail text", onClick = {}) + SettingsItem(title = "Disabled", summary = "Not available", enabled = false, onClick = {}) + SettingsSwitchItem(title = "Toggle", summary = "Turned on", checked = true, onCheckedChange = {}) + SettingsSwitchItem( + title = "Unavailable toggle", + checked = false, + enabled = false, + supportingText = "Requires something", + onCheckedChange = {} + ) + SettingsDropdown( + label = "Theme", + options = listOf("light" to "Light", "dark" to "Dark"), + selectedValue = "dark", + onValueSelected = {} + ) + } + } + } +} 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 new file mode 100644 index 00000000000..424c0dcaffd --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsDialogs.kt @@ -0,0 +1,221 @@ +/* + * 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.res.Configuration +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.RadioButton +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.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import com.nextcloud.talk.R + +@Composable +internal fun RemoveAccountDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.nc_settings_remove_account)) }, + text = { Text(stringResource(R.string.nc_settings_remove_confirmation)) }, + confirmButton = { + TextButton(onClick = onConfirm) { Text(stringResource(R.string.nc_settings_remove)) } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.nc_cancel)) } + } + ) +} + +@Composable +internal fun BatteryOptimizationDialog(onOpenSettings: () -> Unit, onDismiss: () -> Unit) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.nc_ignore_battery_optimization_dialog_title)) }, + text = { + Text( + stringResource( + R.string.nc_ignore_battery_optimization_dialog_text, + stringResource(R.string.nc_app_name) + ) + ) + }, + confirmButton = { + TextButton(onClick = onOpenSettings) { Text(stringResource(R.string.nc_ok)) } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.nc_common_dismiss)) } + } + ) +} + +@Composable +internal fun NotificationTroubleshootingDialog( + onOpenChecklist: () -> Unit, + onOpenDontKillMyApp: () -> Unit, + onOpenDiagnosis: () -> Unit, + onDismiss: () -> Unit +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.nc_notifications_troubleshooting_dialog_title)) }, + text = { Text(stringResource(R.string.nc_notifications_troubleshooting_dialog_text)) }, + confirmButton = { + Column(horizontalAlignment = Alignment.End) { + TextButton(onClick = onOpenDontKillMyApp) { + Text(stringResource(R.string.nc_diagnosis_dialog_open_dontkillmyapp_website)) + } + TextButton(onClick = onOpenChecklist) { + Text(stringResource(R.string.nc_diagnosis_dialog_open_checklist)) + } + TextButton(onClick = onOpenDiagnosis) { + Text(stringResource(R.string.nc_diagnosis_dialog_open_diagnosis)) + } + } + } + ) +} + +@Composable +internal fun MediaQualityDialog(reducedQuality: Boolean, onSelect: (Boolean) -> Unit, onDismiss: () -> Unit) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.nc_settings_media_quality_title)) }, + text = { + Column(modifier = Modifier.selectableGroup()) { + Text( + text = stringResource(R.string.nc_media_quality_original_hint), + style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.padding(bottom = 8.dp) + ) + MediaQualityOption( + label = stringResource(R.string.nc_media_quality_original), + selected = !reducedQuality, + onClick = { onSelect(false) } + ) + MediaQualityOption( + label = stringResource(R.string.nc_media_quality_reduced), + selected = reducedQuality, + onClick = { onSelect(true) } + ) + } + }, + confirmButton = {} + ) +} + +@Composable +private fun MediaQualityOption(label: String, selected: Boolean, onClick: () -> Unit) { + Row( + modifier = Modifier + .fillMaxWidth() + .selectable(selected = selected, role = Role.RadioButton, onClick = onClick) + .padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + RadioButton(selected = selected, onClick = null) + Text( + text = label, + style = MaterialTheme.typography.bodyLarge, + modifier = Modifier.padding(start = 16.dp) + ) + } +} + +/** Asks for the phone number of the account, which the phone book integration needs. */ +@Composable +internal fun PhoneNumberDialog( + isError: Boolean, + onPhoneNumberChange: () -> Unit, + onSubmit: (String) -> Unit, + onDismiss: () -> Unit +) { + var phoneNumber by rememberSaveable { mutableStateOf("") } + val phoneNumberHint = stringResource(R.string.nc_settings_phone_book_integration_phone_number_dialog_edit_text_hint) + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.nc_settings_phone_book_integration_phone_number_dialog_title)) }, + text = { + Column { + Text( + text = stringResource(R.string.nc_settings_phone_book_integration_phone_number_dialog_description), + modifier = Modifier.padding(bottom = 16.dp) + ) + OutlinedTextField( + value = phoneNumber, + onValueChange = { + phoneNumber = it + onPhoneNumberChange() + }, + label = { Text(phoneNumberHint) }, + prefix = { Text("+") }, + singleLine = true, + isError = isError, + supportingText = if (isError) { + { + Text( + stringResource(R.string.nc_settings_phone_book_integration_phone_number_dialog_invalid) + ) + } + } else { + null + }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone, imeAction = ImeAction.Done), + modifier = Modifier.fillMaxWidth() + ) + } + }, + confirmButton = { + TextButton(onClick = { onSubmit(phoneNumber) }, enabled = phoneNumber.isNotBlank()) { + Text(stringResource(R.string.nc_common_set)) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.nc_common_skip)) } + } + ) +} + +@Preview(name = "Light") +@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES) +@Composable +private fun MediaQualityDialogPreview() { + MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) { + MediaQualityDialog(reducedQuality = true, onSelect = {}, onDismiss = {}) + } +} + +@Preview(name = "Light") +@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES) +@Composable +private fun PhoneNumberDialogPreview() { + MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) { + PhoneNumberDialog(isError = true, onPhoneNumberChange = {}, onSubmit = {}, onDismiss = {}) + } +} diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsGeneralSections.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsGeneralSections.kt new file mode 100644 index 00000000000..9a5a315f623 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsGeneralSections.kt @@ -0,0 +1,166 @@ +/* + * 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.res.Configuration +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Column +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.res.stringArrayResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import com.nextcloud.talk.BuildConfig +import com.nextcloud.talk.R +import com.nextcloud.talk.settings.AppearanceUiState +import com.nextcloud.talk.settings.LoggingStatus +import com.nextcloud.talk.settings.SettingsUiState + +@Composable +internal fun AppearanceSection(state: AppearanceUiState, callbacks: SettingsScreenCallbacks) { + Column { + SettingsSectionHeader(stringResource(R.string.nc_settings_appearance)) + SettingsDropdown( + label = stringResource(R.string.nc_settings_theme_title), + options = stringArrayResource(R.array.theme_entry_values) + .zip(stringArrayResource(R.array.theme_descriptions)), + selectedValue = state.theme, + onValueSelected = callbacks.onThemeChange + ) + if (state.showEcosystemSetting) { + SettingsSwitchItem( + title = stringResource(R.string.nc_show_ecosystem_title), + summary = stringResource(R.string.nc_show_ecosystem_description), + checked = state.showEcosystem, + onCheckedChange = callbacks.onShowEcosystemChange + ) + } + } +} + +@Composable +internal fun DiagnosisSection(loggingStatus: LoggingStatus, callbacks: SettingsScreenCallbacks) { + Column { + SettingsSectionHeader(stringResource(R.string.nc_settings_diagnosis_logs_section_title)) + SettingsItem( + title = stringResource(R.string.nc_settings_diagnosis_title), + summary = stringResource(R.string.nc_settings_diagnosis_subtitle), + onClick = callbacks.onOpenDiagnosis + ) + SettingsItem( + title = stringResource(R.string.nc_settings_logs_title), + summary = stringResource( + when (loggingStatus) { + LoggingStatus.DISABLED -> R.string.nc_logs_logging_disabled_note + LoggingStatus.ENABLED -> R.string.nc_logs_logging_enabled + LoggingStatus.ADVANCED -> R.string.nc_logs_advanced_logging_enabled_warning + } + ), + onClick = callbacks.onOpenLogs + ) + SettingsItem( + title = stringResource(R.string.nc_settings_share_report_title), + summary = stringResource(R.string.nc_settings_share_report_subtitle), + onClick = callbacks.onShareReport + ) + } +} + +@Composable +internal fun AdvancedSection(state: SettingsUiState, callbacks: SettingsScreenCallbacks) { + var showMediaQualityDialog by rememberSaveable { mutableStateOf(false) } + Column { + SettingsSectionHeader(stringResource(R.string.nc_settings_advanced_title)) + SettingsItem( + title = stringResource(R.string.nc_settings_media_quality_title), + summary = stringResource( + if (state.mediaQualityReduced) R.string.nc_media_quality_reduced else R.string.nc_media_quality_original + ), + onClick = { showMediaQualityDialog = true } + ) + if (state.isOnline) { + SettingsItem( + title = stringResource( + if (state.clientCertificateSet) R.string.nc_client_cert_change else R.string.nc_client_cert_setup + ), + onClick = callbacks.onClientCertificateClick + ) + ProxySettings(state.proxy, callbacks.proxy) + } + } + if (showMediaQualityDialog) { + MediaQualityDialog( + reducedQuality = state.mediaQualityReduced, + onSelect = { + showMediaQualityDialog = false + callbacks.onMediaQualityChange(it) + }, + onDismiss = { showMediaQualityDialog = false } + ) + } +} + +@Composable +internal fun AboutSection(isOnline: Boolean, callbacks: SettingsScreenCallbacks) { + val uriHandler = LocalUriHandler.current + val privacyUrl = stringResource(R.string.nc_privacy_url) + val sourceCodeUrl = stringResource(R.string.nc_source_code_url) + val licenseUrl = stringResource(R.string.nc_gpl3_url) + Column { + SettingsSectionHeader(stringResource(R.string.nc_about)) + if (isOnline && privacyUrl.isNotEmpty()) { + SettingsItem( + title = stringResource(R.string.nc_settings_privacy), + onClick = { uriHandler.openUri(privacyUrl) } + ) + } + if (isOnline && sourceCodeUrl.isNotEmpty()) { + SettingsItem( + title = stringResource(R.string.nc_get_source_code), + onClick = { uriHandler.openUri(sourceCodeUrl) } + ) + } + if (isOnline && licenseUrl.isNotEmpty()) { + SettingsItem( + title = stringResource(R.string.nc_license_title), + summary = stringResource(R.string.nc_license_summary), + onClick = { uriHandler.openUri(licenseUrl) } + ) + } + SettingsItem( + title = stringResource(R.string.nc_app_product_name), + summary = "v" + BuildConfig.VERSION_NAME, + onClick = callbacks.onVersionClick + ) + } +} + +@Preview(name = "Light") +@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES) +@Preview(name = "RTL Arabic", locale = "ar") +@Composable +private fun GeneralSectionsPreview() { + val state = previewSettingsState() + MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) { + Surface { + Column { + AppearanceSection(state.appearance, SettingsScreenCallbacks()) + DiagnosisSection(state.loggingStatus, SettingsScreenCallbacks()) + AdvancedSection(state, SettingsScreenCallbacks()) + AboutSection(state.isOnline, SettingsScreenCallbacks()) + } + } + } +} 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 new file mode 100644 index 00000000000..56c7971a636 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsNotificationsSection.kt @@ -0,0 +1,265 @@ +/* + * 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.res.Configuration +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Column +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.Color +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.NotificationsUiState +import com.nextcloud.talk.settings.PushAvailability +import com.nextcloud.talk.settings.RingtoneState +import com.nextcloud.talk.settings.UnifiedPushUiState + +@Composable +internal fun NotificationsSection( + state: NotificationsUiState, + baseUrl: String, + highlightIssues: Boolean, + callbacks: SettingsScreenCallbacks +) { + Column { + SettingsSectionHeader(stringResource(R.string.nc_settings_notification_sounds_post_oreo)) + state.unifiedPush?.let { UnifiedPushItems(it, callbacks) } + when (state.pushAvailability) { + PushAvailability.AVAILABLE -> PushSetupItems(state, baseUrl, highlightIssues, callbacks) + PushAvailability.GOOGLE_PLAY_SERVICES_UNAVAILABLE -> + SettingsItem(title = stringResource(R.string.gplay_available_no)) + PushAvailability.UNIFIED_PUSH_DISABLED_AND_GOOGLE_PLAY_SERVICES_UNAVAILABLE -> + SettingsItem(title = stringResource(R.string.nc_diagnosis_push_available_no)) + } + state.fullScreenIntentGranted?.let { granted -> + SettingsItem( + title = stringResource(R.string.full_screen_intent_permission_title), + summary = stringResource( + if (granted) { + R.string.full_screen_intent_permission_granted + } else { + R.string.full_screen_intent_permission_not_granted + } + ), + summaryColor = statusColor(granted), + highlight = highlightIssues && !granted, + onClick = { callbacks.onOpenSystemSettings(SystemSettingsScreen.FULL_SCREEN_INTENT) } + ) + } + RingtoneItems(state, highlightIssues, callbacks) + if (state.showNotificationWarningSetting) { + SettingsSwitchItem( + title = stringResource(R.string.nc_show_notification_warning_title), + summary = stringResource(R.string.nc_show_notification_warning_description), + checked = state.showNotificationWarning, + onCheckedChange = callbacks.onShowNotificationWarningChange + ) + } + } +} + +@Composable +private fun UnifiedPushItems(state: UnifiedPushUiState, callbacks: SettingsScreenCallbacks) { + SettingsSwitchItem( + title = stringResource(R.string.nc_settings_screen_enable_unifiedpush_title), + summary = stringResource(R.string.nc_settings_screen_enable_unifiedpush_desc), + checked = state.enabled, + onCheckedChange = callbacks.onUnifiedPushChange + ) + if (state.canPickDistributor) { + SettingsItem( + title = stringResource(R.string.nc_settings_screen_unifiedpush_service_title), + summary = state.distributor, + onClick = callbacks.onPickDistributor + ) + } +} + +/** The settings that push notifications depend on, shown if push notifications are available at all. */ +@Composable +private fun PushSetupItems( + state: NotificationsUiState, + baseUrl: String, + highlightIssues: Boolean, + callbacks: SettingsScreenCallbacks +) { + var showBatteryOptimizationDialog by rememberSaveable { mutableStateOf(false) } + var showTroubleshootingDialog by rememberSaveable { mutableStateOf(false) } + val permissionGranted = state.notificationPermissionGranted + + if (state.serverNotificationAppMissing) { + SettingsItem( + title = stringResource(R.string.nc_settings_server_notification_app_not_installed_title), + summary = stringResource(R.string.nc_settings_contact_admin_of) + "\n" + baseUrl, + summaryColor = MaterialTheme.colorScheme.error, + highlight = highlightIssues + ) + } + if (permissionGranted != null) { + NotificationPermissionItem( + granted = permissionGranted, + highlight = highlightIssues && !permissionGranted, + onClick = when { + !permissionGranted -> callbacks.onRequestNotificationPermission + state.batteryOptimizationIgnored -> { + { showTroubleshootingDialog = true } + } + else -> null + } + ) + } + BatteryOptimizationItem( + ignored = state.batteryOptimizationIgnored, + highlight = highlightIssues && !state.batteryOptimizationIgnored, + onClick = when { + !state.batteryOptimizationIgnored -> { + { showBatteryOptimizationDialog = true } + } + permissionGranted != false -> { + { showTroubleshootingDialog = true } + } + else -> null + } + ) + + if (showBatteryOptimizationDialog) { + BatteryOptimizationDialog( + onOpenSettings = { + showBatteryOptimizationDialog = false + callbacks.onOpenSystemSettings(SystemSettingsScreen.BATTERY_OPTIMIZATION) + }, + onDismiss = { showBatteryOptimizationDialog = false } + ) + } + if (showTroubleshootingDialog) { + TroubleshootingDialog( + onOpenDiagnosis = callbacks.onOpenDiagnosis, + onDismiss = { showTroubleshootingDialog = false } + ) + } +} + +@Composable +private fun NotificationPermissionItem(granted: Boolean, highlight: Boolean, onClick: (() -> Unit)?) { + SettingsItem( + title = stringResource(R.string.notification_permission), + summary = stringResource( + if (granted) R.string.nc_settings_notifications_granted else R.string.nc_settings_notifications_declined + ), + summaryColor = statusColor(granted), + highlight = highlight, + onClick = onClick + ) +} + +@Composable +private fun BatteryOptimizationItem(ignored: Boolean, highlight: Boolean, onClick: (() -> Unit)?) { + SettingsItem( + title = stringResource(R.string.battery_optimization_title), + summary = stringResource( + if (ignored) R.string.battery_optimization_ignored else R.string.battery_optimization_not_ignored + ), + summaryColor = statusColor(ignored), + highlight = highlight, + onClick = onClick + ) +} + +@Composable +private fun TroubleshootingDialog(onOpenDiagnosis: () -> Unit, onDismiss: () -> Unit) { + val uriHandler = LocalUriHandler.current + val checklistUrl = stringResource(R.string.notification_checklist_url) + val dontKillMyAppUrl = stringResource(R.string.dontkillmyapp_url) + NotificationTroubleshootingDialog( + onOpenChecklist = { + onDismiss() + uriHandler.openUri(checklistUrl) + }, + onOpenDontKillMyApp = { + onDismiss() + uriHandler.openUri(dontKillMyAppUrl) + }, + onOpenDiagnosis = { + onDismiss() + onOpenDiagnosis() + }, + onDismiss = 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) } + ) +} + +@Composable +private fun RingtoneItem( + title: String, + ringtone: RingtoneState, + enabled: Boolean, + highlight: Boolean, + onClick: () -> Unit +) { + val disabled = ringtone == RingtoneState.Disabled + SettingsItem( + title = title, + summary = when (ringtone) { + RingtoneState.Disabled -> stringResource(R.string.nc_common_disabled) + RingtoneState.Silent -> stringResource(R.string.nc_settings_no_ringtone) + RingtoneState.Default -> stringResource(R.string.nc_settings_default_ringtone) + is RingtoneState.Custom -> ringtone.title + }, + summaryColor = statusColor(!disabled), + enabled = enabled, + highlight = highlight && disabled, + onClick = onClick + ) +} + +@Composable +private fun statusColor(ok: Boolean): Color = + if (ok) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.error + +@Preview(name = "Light") +@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES) +@Preview(name = "RTL Arabic", locale = "ar") +@Composable +private fun NotificationsSectionPreview() { + MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) { + Surface { + NotificationsSection( + state = previewSettingsState().notifications.copy(serverNotificationAppMissing = true), + baseUrl = "https://cloud.example.com", + highlightIssues = false, + callbacks = SettingsScreenCallbacks() + ) + } + } +} diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsPrivacySection.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsPrivacySection.kt new file mode 100644 index 00000000000..eda94dd229e --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsPrivacySection.kt @@ -0,0 +1,109 @@ +/* + * 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.res.Configuration +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Column +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringArrayResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import com.nextcloud.talk.R +import com.nextcloud.talk.settings.PrivacyUiState +import com.nextcloud.talk.settings.TypingStatusUiState + +@Composable +internal fun PrivacySection(state: PrivacyUiState, callbacks: SettingsScreenCallbacks) { + Column { + SettingsSectionHeader(stringResource(R.string.nc_settings_privacy)) + SettingsSwitchItem( + title = stringResource(R.string.nc_settings_screen_lock_title), + summary = stringResource( + R.string.nc_settings_screen_lock_desc, + stringResource(R.string.nc_app_product_name) + ), + checked = state.screenLock, + enabled = state.screenLockAvailable, + onCheckedChange = callbacks.onScreenLockChange + ) + SettingsDropdown( + label = stringResource(R.string.nc_settings_screen_lock_timeout_title), + options = stringArrayResource(R.array.screen_lock_timeout_entry_values) + .zip(stringArrayResource(R.array.screen_lock_timeout_descriptions)), + selectedValue = state.screenLockTimeout, + enabled = state.screenLockAvailable && state.screenLock, + onValueSelected = callbacks.onScreenLockTimeoutChange + ) + SettingsSwitchItem( + title = stringResource(R.string.nc_settings_screen_security_title), + summary = stringResource(R.string.nc_settings_screen_security_desc), + checked = state.screenSecurity, + onCheckedChange = callbacks.onScreenSecurityChange + ) + SettingsSwitchItem( + title = stringResource(R.string.nc_settings_incognito_keyboard_title), + summary = stringResource(R.string.nc_settings_incognito_keyboard_desc), + checked = state.incognitoKeyboard, + onCheckedChange = callbacks.onIncognitoKeyboardChange + ) + if (state.phoneBookIntegrationAvailable) { + SettingsSwitchItem( + title = stringResource(R.string.nc_settings_phone_book_integration_title), + summary = stringResource(R.string.nc_settings_phone_book_integration_desc), + checked = state.phoneBookIntegration, + onCheckedChange = callbacks.onPhoneBookIntegrationChange + ) + } + if (state.readStatusAvailable) { + SettingsSwitchItem( + title = stringResource(R.string.nc_settings_read_privacy_title), + summary = stringResource(R.string.nc_settings_read_privacy_desc), + checked = state.readStatusShared, + onCheckedChange = callbacks.onReadStatusChange + ) + } + TypingStatusItem(state.typingStatus, callbacks.onTypingStatusChange) + } +} + +@Composable +private fun TypingStatusItem(state: TypingStatusUiState, onTypingStatusChange: (Boolean) -> Unit) { + when (state) { + TypingStatusUiState.Hidden -> Unit + TypingStatusUiState.RequiresHighPerformanceBackend -> SettingsSwitchItem( + title = stringResource(R.string.nc_settings_typing_status_title), + summary = stringResource(R.string.nc_settings_typing_status_desc), + supportingText = stringResource(R.string.nc_settings_typing_status_hpb_description), + checked = false, + enabled = false, + onCheckedChange = onTypingStatusChange + ) + is TypingStatusUiState.Available -> SettingsSwitchItem( + title = stringResource(R.string.nc_settings_typing_status_title), + summary = stringResource(R.string.nc_settings_typing_status_desc), + checked = state.shared, + onCheckedChange = onTypingStatusChange + ) + } +} + +@Preview(name = "Light") +@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES) +@Preview(name = "RTL Arabic", locale = "ar") +@Composable +private fun PrivacySectionPreview() { + MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) { + Surface { + PrivacySection(state = previewSettingsState().privacy, callbacks = SettingsScreenCallbacks()) + } + } +} diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsProxySection.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsProxySection.kt new file mode 100644 index 00000000000..2efb2eff4da --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsProxySection.kt @@ -0,0 +1,134 @@ +/* + * 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.res.Configuration +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringArrayResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.input.VisualTransformation +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import com.nextcloud.talk.R +import com.nextcloud.talk.settings.ProxyUiState + +@Composable +internal fun ProxySettings(state: ProxyUiState, callbacks: ProxyCallbacks) { + val proxyTypes = stringArrayResource(R.array.proxy_type_descriptions) + val proxyEnabled = state.type.isNotEmpty() && state.type != proxyTypes.first() + Column { + SettingsDropdown( + label = stringResource(R.string.nc_settings_proxy_type_title), + options = proxyTypes.map { it to it }, + selectedValue = state.type, + onValueSelected = callbacks.onTypeChange + ) + if (proxyEnabled) { + ProxyTextField( + label = stringResource(R.string.nc_settings_proxy_host_title), + initialValue = state.host, + keyboardType = KeyboardType.Uri, + onValueChange = callbacks.onHostChange + ) + // the port is replaced by the default port of a newly selected type + ProxyTextField( + label = stringResource(R.string.nc_settings_proxy_port_title), + initialValue = state.port, + resetKey = state.type, + keyboardType = KeyboardType.Number, + onValueChange = callbacks.onPortChange + ) + SettingsSwitchItem( + title = stringResource(R.string.nc_settings_use_credentials_title), + checked = state.useCredentials, + onCheckedChange = callbacks.onUseCredentialsChange + ) + if (state.useCredentials) { + ProxyTextField( + label = stringResource(R.string.nc_settings_proxy_username_title), + initialValue = state.username, + keyboardType = KeyboardType.Text, + onValueChange = callbacks.onUsernameChange + ) + ProxyTextField( + label = stringResource(R.string.nc_settings_proxy_password_title), + initialValue = state.password, + keyboardType = KeyboardType.Password, + onValueChange = callbacks.onPasswordChange + ) + } + } + } +} + +/** + * A text field that keeps its text locally, so that typing isn't delayed by the round trip through the view model. The + * text is reset to [initialValue] when [resetKey] changes. + */ +@Composable +private fun ProxyTextField( + label: String, + initialValue: String, + keyboardType: KeyboardType, + onValueChange: (String) -> Unit, + resetKey: Any? = null +) { + var text by rememberSaveable(resetKey) { mutableStateOf(initialValue) } + OutlinedTextField( + value = text, + onValueChange = { + text = it + onValueChange(it) + }, + label = { Text(label) }, + singleLine = true, + visualTransformation = if (keyboardType == KeyboardType.Password) { + PasswordVisualTransformation() + } else { + VisualTransformation.None + }, + keyboardOptions = KeyboardOptions( + autoCorrectEnabled = false, + keyboardType = keyboardType, + imeAction = ImeAction.Next + ), + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp) + ) +} + +@Preview(name = "Light") +@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES) +@Preview(name = "RTL Arabic", locale = "ar") +@Composable +private fun ProxySettingsPreview() { + MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) { + Surface { + ProxySettings(state = previewSettingsState().proxy, callbacks = ProxyCallbacks()) + } + } +} 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 new file mode 100644 index 00000000000..b794cc23083 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsScreen.kt @@ -0,0 +1,214 @@ +/* + * 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.res.Configuration +import androidx.compose.foundation.background +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.consumeWindowInsets +import androidx.compose.foundation.layout.displayCutoutPadding +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +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.res.colorResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import com.nextcloud.talk.R +import com.nextcloud.talk.components.ColoredStatusBar +import com.nextcloud.talk.components.StandardAppBar +import com.nextcloud.talk.settings.AccountUiState +import com.nextcloud.talk.settings.NotificationsUiState +import com.nextcloud.talk.settings.PrivacyUiState +import com.nextcloud.talk.settings.ProxyUiState +import com.nextcloud.talk.settings.RingtoneState +import com.nextcloud.talk.settings.ServerAgeWarning +import com.nextcloud.talk.settings.SettingsUiState +import com.nextcloud.talk.settings.TypingStatusUiState +import com.nextcloud.talk.settings.UnifiedPushUiState + +/** System settings screens of the app that the settings screen links to. */ +enum class SystemSettingsScreen { + BATTERY_OPTIMIZATION, + FULL_SCREEN_INTENT, + CALL_NOTIFICATIONS, + MESSAGE_NOTIFICATIONS +} + +data class SettingsScreenCallbacks( + val onProfileClick: () -> Unit = {}, + val onAccountMessageShown: () -> Unit = {}, + val onRemoveAccount: () -> Unit = {}, + val onThemeChange: (String) -> Unit = {}, + val onShowEcosystemChange: (Boolean) -> Unit = {}, + val onUnifiedPushChange: (Boolean) -> Unit = {}, + val onPickDistributor: () -> Unit = {}, + val onRequestNotificationPermission: () -> Unit = {}, + val onOpenSystemSettings: (SystemSettingsScreen) -> Unit = {}, + val onOpenDiagnosis: () -> Unit = {}, + val onShowNotificationWarningChange: (Boolean) -> Unit = {}, + val onScreenLockChange: (Boolean) -> Unit = {}, + val onScreenLockTimeoutChange: (String) -> Unit = {}, + val onScreenSecurityChange: (Boolean) -> Unit = {}, + val onIncognitoKeyboardChange: (Boolean) -> Unit = {}, + val onPhoneBookIntegrationChange: (Boolean) -> Unit = {}, + val onReadStatusChange: (Boolean) -> Unit = {}, + val onTypingStatusChange: (Boolean) -> Unit = {}, + val onPhoneNumberChange: () -> Unit = {}, + val onSubmitPhoneNumber: (String) -> Unit = {}, + val onDismissPhoneNumberDialog: () -> Unit = {}, + val onOpenLogs: () -> Unit = {}, + val onShareReport: () -> Unit = {}, + val onMediaQualityChange: (Boolean) -> Unit = {}, + val onClientCertificateClick: () -> Unit = {}, + val proxy: ProxyCallbacks = ProxyCallbacks(), + val onVersionClick: () -> Unit = {} +) + +data class ProxyCallbacks( + val onTypeChange: (String) -> Unit = {}, + val onHostChange: (String) -> Unit = {}, + val onPortChange: (String) -> Unit = {}, + val onUseCredentialsChange: (Boolean) -> Unit = {}, + val onUsernameChange: (String) -> Unit = {}, + val onPasswordChange: (String) -> Unit = {} +) + +private enum class SettingsSection { + ACCOUNT, + APPEARANCE, + NOTIFICATIONS, + PRIVACY, + DIAGNOSIS, + ADVANCED, + ABOUT +} + +@Composable +fun SettingsScreen( + state: SettingsUiState, + callbacks: SettingsScreenCallbacks, + snackbarHostState: SnackbarHostState = remember { SnackbarHostState() } +) { + ColoredStatusBar() + Scaffold( + modifier = Modifier + .statusBarsPadding() + .displayCutoutPadding(), + topBar = { StandardAppBar(title = stringResource(R.string.nc_settings), menuItems = null) }, + snackbarHost = { SnackbarHost(snackbarHostState) } + ) { paddingValues -> + SettingsContent(state = state, callbacks = callbacks, paddingValues = paddingValues) + } + if (state.showPhoneNumberDialog) { + PhoneNumberDialog( + isError = state.phoneNumberError, + onPhoneNumberChange = callbacks.onPhoneNumberChange, + onSubmit = callbacks.onSubmitPhoneNumber, + onDismiss = callbacks.onDismissPhoneNumberDialog + ) + } +} + +@Composable +private fun SettingsContent(state: SettingsUiState, callbacks: SettingsScreenCallbacks, paddingValues: PaddingValues) { + val listState = rememberLazyListState() + var scrolledToNotifications by rememberSaveable { mutableStateOf(false) } + LaunchedEffect(Unit) { + if (state.highlightNotificationIssues && !scrolledToNotifications) { + listState.scrollToItem(SettingsSection.NOTIFICATIONS.ordinal) + scrolledToNotifications = true + } + } + LazyColumn( + state = listState, + contentPadding = PaddingValues(bottom = 48.dp), + modifier = Modifier + .fillMaxSize() + .background(colorResource(R.color.bg_default)) + .padding(paddingValues) + .consumeWindowInsets(paddingValues) + .imePadding() + ) { + items(SettingsSection.entries, key = { it }) { section -> + when (section) { + SettingsSection.ACCOUNT -> AccountSection(state, callbacks) + SettingsSection.APPEARANCE -> AppearanceSection(state.appearance, callbacks) + SettingsSection.NOTIFICATIONS -> NotificationsSection( + state = state.notifications, + baseUrl = state.account.baseUrl, + highlightIssues = state.highlightNotificationIssues, + callbacks = callbacks + ) + SettingsSection.PRIVACY -> PrivacySection(state.privacy, callbacks) + SettingsSection.DIAGNOSIS -> DiagnosisSection(state.loggingStatus, callbacks) + SettingsSection.ADVANCED -> AdvancedSection(state, callbacks) + SettingsSection.ABOUT -> AboutSection(state.isOnline, callbacks) + } + } + } +} + +internal fun previewSettingsState(): SettingsUiState = + SettingsUiState( + isOnline = true, + account = AccountUiState( + displayName = "Jane Doe", + baseUrl = "https://cloud.example.com", + avatarId = "jane", + serverAgeWarning = ServerAgeWarning.ALMOST_END_OF_LIFE + ), + notifications = NotificationsUiState( + unifiedPush = UnifiedPushUiState(enabled = true, distributor = "ntfy", canPickDistributor = true), + notificationPermissionGranted = false, + batteryOptimizationIgnored = false, + fullScreenIntentGranted = true, + callRingtone = RingtoneState.Default, + messageRingtone = RingtoneState.Disabled, + showNotificationWarningSetting = true, + showNotificationWarning = true + ), + privacy = PrivacyUiState( + screenLockAvailable = true, + screenLock = true, + screenLockTimeout = "300", + phoneBookIntegrationAvailable = true, + readStatusAvailable = true, + readStatusShared = true, + typingStatus = TypingStatusUiState.RequiresHighPerformanceBackend + ), + proxy = ProxyUiState(type = "HTTP", host = "proxy.example.com", port = "3128", useCredentials = true) + ) + +@Preview(name = "Light", heightDp = 2400) +@Preview(name = "Dark", heightDp = 2400, uiMode = Configuration.UI_MODE_NIGHT_YES) +@Preview(name = "RTL Arabic", heightDp = 2400, locale = "ar") +@Composable +private fun SettingsScreenPreview() { + MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) { + SettingsScreen(state = previewSettingsState(), callbacks = SettingsScreenCallbacks()) + } +} diff --git a/app/src/main/java/com/nextcloud/talk/ui/dialog/SetPhoneNumberDialogFragment.kt b/app/src/main/java/com/nextcloud/talk/ui/dialog/SetPhoneNumberDialogFragment.kt deleted file mode 100644 index 11d4f6e6e86..00000000000 --- a/app/src/main/java/com/nextcloud/talk/ui/dialog/SetPhoneNumberDialogFragment.kt +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Nextcloud Talk - Android Client - * - * SPDX-FileCopyrightText: 2024 Parneet Singh - * SPDX-FileCopyrightText: 2022 Andy Scherzinger - * SPDX-License-Identifier: GPL-3.0-or-later - */ -package com.nextcloud.talk.ui.dialog - -import android.app.Dialog -import android.content.Context -import android.content.DialogInterface -import android.content.res.ColorStateList -import android.os.Bundle -import android.text.Editable -import android.text.TextWatcher -import androidx.appcompat.app.AlertDialog -import androidx.fragment.app.DialogFragment -import autodagger.AutoInjector -import com.google.android.material.dialog.MaterialAlertDialogBuilder -import com.google.android.material.textfield.TextInputLayout -import com.nextcloud.talk.R -import com.nextcloud.talk.application.NextcloudTalkApplication -import com.nextcloud.talk.databinding.DialogSetPhoneNumberBinding -import com.nextcloud.talk.ui.theme.ViewThemeUtils -import com.nextcloud.talk.ui.theme.hostViewThemeUtils -import javax.inject.Inject - -@AutoInjector(NextcloudTalkApplication::class) -class SetPhoneNumberDialogFragment : DialogFragment() { - - @Inject - lateinit var viewThemeUtils: ViewThemeUtils - - private lateinit var clickListener: SetPhoneNumberDialogClickListener - - private lateinit var binding: DialogSetPhoneNumberBinding - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - NextcloudTalkApplication.sharedApplication?.componentApplication?.inject(this) - viewThemeUtils = hostViewThemeUtils(activity, viewThemeUtils) - } - - override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { - binding = DialogSetPhoneNumberBinding.inflate(requireActivity().layoutInflater) - - val dialogBuilder = - MaterialAlertDialogBuilder(requireActivity()) - .setTitle(R.string.nc_settings_phone_book_integration_phone_number_dialog_title) - .setView(binding.root) - .setMessage(R.string.nc_settings_phone_book_integration_phone_number_dialog_description) - .setPositiveButton(requireContext().resources.getString(R.string.nc_common_set)) { dialog, _ -> - clickListener - .onSubmitClick(binding.phoneInputLayout, dialog) - } - .setNegativeButton(requireContext().resources.getString(R.string.nc_common_skip), null) - - viewThemeUtils.dialog.colorMaterialAlertDialogBackground(requireActivity(), dialogBuilder) - - binding.phoneInputLayout.setHelperTextColor( - ColorStateList.valueOf(resources.getColor(R.color.nc_darkRed, null)) - ) - - binding.phoneEditTextField.addTextChangedListener(object : TextWatcher { - override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { - binding.phoneInputLayout.helperText = "" - } - - override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { - // unused atm - } - override fun afterTextChanged(s: Editable?) { - // unused atm - } - }) - - return dialogBuilder.create() - } - - override fun onStart() { - super.onStart() - val alertDialog = dialog as AlertDialog? - alertDialog?.let { - viewThemeUtils.platform.colorTextButtons(it.getButton(AlertDialog.BUTTON_POSITIVE)) - viewThemeUtils.platform.colorTextButtons(it.getButton(AlertDialog.BUTTON_NEGATIVE)) - } - } - - override fun onAttach(context: Context) { - super.onAttach(context) - clickListener = context as SetPhoneNumberDialogClickListener - } - - interface SetPhoneNumberDialogClickListener { - fun onSubmitClick(textInputLayout: TextInputLayout, dialog: DialogInterface) - } - - companion object { - val TAG: String = SetPhoneNumberDialogFragment::class.java.simpleName - - fun newInstance(): DialogFragment = SetPhoneNumberDialogFragment() - } -} diff --git a/app/src/main/java/com/nextcloud/talk/utils/DrawableUtils.kt b/app/src/main/java/com/nextcloud/talk/utils/DrawableUtils.kt index aa25954710d..37a5b562ce3 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/DrawableUtils.kt +++ b/app/src/main/java/com/nextcloud/talk/utils/DrawableUtils.kt @@ -6,23 +6,14 @@ */ package com.nextcloud.talk.utils -import android.graphics.drawable.Drawable -import android.graphics.drawable.RippleDrawable -import android.util.Log import com.nextcloud.talk.R import com.nextcloud.talk.utils.Mimetype.AUDIO_PREFIX import com.nextcloud.talk.utils.Mimetype.FOLDER import com.nextcloud.talk.utils.Mimetype.IMAGE_PREFIX import com.nextcloud.talk.utils.Mimetype.TEXT_PREFIX import com.nextcloud.talk.utils.Mimetype.VIDEO_PREFIX -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch object DrawableUtils { - private val TAG = DrawableUtils::class.java.simpleName - @Suppress("Detekt.LongMethod") fun getDrawableResourceIdForMimeType(mimetype: String?): Int { var localMimetype = mimetype @@ -162,23 +153,4 @@ object DrawableUtils { drawableMap["unknown"]!! } } - - @Suppress("MagicNumber", "TooGenericExceptionCaught") - fun blinkDrawable(rippleView: Drawable) { - try { - (rippleView as RippleDrawable).let { rippleDrawable -> - CoroutineScope(Dispatchers.Main).launch { - delay(1000L) // Wait 2 seconds before starting - repeat(3) { - rippleDrawable.state = intArrayOf(android.R.attr.state_pressed, android.R.attr.state_enabled) - delay(250L) // Ripple active duration - rippleDrawable.state = intArrayOf() // Reset state - delay(250L) // Time between blinks - } - } - } - } catch (e: Exception) { - Log.e(TAG, "Failed to blink Drawable", e) - } - } } diff --git a/app/src/main/java/com/nextcloud/talk/utils/preferences/AppPreferences.java b/app/src/main/java/com/nextcloud/talk/utils/preferences/AppPreferences.java index 262894b8527..391be08cc0e 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/preferences/AppPreferences.java +++ b/app/src/main/java/com/nextcloud/talk/utils/preferences/AppPreferences.java @@ -173,14 +173,6 @@ public interface AppPreferences { long getPhoneBookIntegrationLastRun(Long defaultValue); - void setReadPrivacy(boolean value); - - boolean getReadPrivacy(); - - void setTypingStatus(boolean value); - - boolean getTypingStatus(); - void setSorting(String value); String getSorting(); diff --git a/app/src/main/java/com/nextcloud/talk/utils/preferences/AppPreferencesImpl.kt b/app/src/main/java/com/nextcloud/talk/utils/preferences/AppPreferencesImpl.kt index 5383854e3b4..6ab33e25c14 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/preferences/AppPreferencesImpl.kt +++ b/app/src/main/java/com/nextcloud/talk/utils/preferences/AppPreferencesImpl.kt @@ -523,31 +523,6 @@ class AppPreferencesImpl(val context: Context) : AppPreferences { return result } - override fun setReadPrivacy(value: Boolean) = - runBlocking { - val key = context.resources.getString(R.string.nc_settings_read_privacy_key) - async { - writeBoolean(key, value) - } - } - - override fun getReadPrivacy(): Boolean { - val key = context.resources.getString(R.string.nc_settings_read_privacy_key) - return runBlocking { async { readBoolean(key).first() } }.getCompleted() - } - - override fun setTypingStatus(value: Boolean) = - runBlocking { - async { - writeBoolean(TYPING_STATUS, value) - } - } - - override fun getTypingStatus(): Boolean = - runBlocking { - async { readBoolean(TYPING_STATUS).first() } - }.getCompleted() - override fun setSorting(value: String?) = runBlocking { val key = context.resources.getString(R.string.nc_file_browser_sort_by_key) @@ -748,7 +723,6 @@ class AppPreferencesImpl(val context: Context) : AppPreferences { const val DB_CYPHER_V4_UPGRADE = "db_cypher_v4_upgrade" const val DB_ROOM_MIGRATED = "db_room_migrated" const val PHONE_BOOK_INTEGRATION_LAST_RUN = "phone_book_integration_last_run" - const val TYPING_STATUS = "typing_status" const val MESSAGE_QUEUE = "@message_queue" const val PLAY_BACK = "_playback" const val AUDIO_FILE_PLAY_BACK = "_audio_file_playback" diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml deleted file mode 100644 index 3fc0988719a..00000000000 --- a/app/src/main/res/layout/activity_settings.xml +++ /dev/null @@ -1,1127 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/layout/dialog_set_phone_number.xml b/app/src/main/res/layout/dialog_set_phone_number.xml deleted file mode 100644 index 95871075ed9..00000000000 --- a/app/src/main/res/layout/dialog_set_phone_number.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 194d80f8eb4..4f813d52f1a 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -168,7 +168,6 @@ How to translate with transifex: View-only Editable Close video playback - read_privacy Tap to unlock Locked Share my read-status and show the read-status of others @@ -214,7 +213,6 @@ How to translate with transifex: Diagnosis & Logs Open diagnosis screen to check settings Logs - View local log files Share diagnosis report Share the logs and diagnosis info @@ -996,7 +994,6 @@ How to translate with transifex: 3128 8080 1080 - This is a test message Lock recording for continuously recording of the voice message Remind me later Next week diff --git a/app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt b/app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt new file mode 100644 index 00000000000..b92232b75da --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt @@ -0,0 +1,359 @@ +/* + * 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 android.content.res.Resources +import androidx.lifecycle.ViewModelStore +import androidx.work.WorkInfo +import androidx.work.WorkManager +import com.nextcloud.talk.R +import com.nextcloud.talk.data.network.NetworkMonitor +import com.nextcloud.talk.data.user.model.User +import com.nextcloud.talk.logger.Level +import com.nextcloud.talk.logger.Logger +import com.nextcloud.talk.logger.LogsRepository +import com.nextcloud.talk.models.json.capabilities.CapabilitiesDto +import com.nextcloud.talk.models.json.capabilities.SpreedCapabilityDto +import com.nextcloud.talk.models.json.userprofile.UserProfileDataDto +import com.nextcloud.talk.settings.data.SettingsRepository +import com.nextcloud.talk.users.UserManager +import com.nextcloud.talk.utils.preferences.AppPreferences +import com.nextcloud.talk.utils.singletons.ApplicationWideMessageHolder +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.stub +import org.mockito.kotlin.timeout +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import java.io.IOException +import java.util.UUID + +@OptIn(ExperimentalCoroutinesApi::class) +@Suppress("TooManyFunctions") +class SettingsViewModelTest { + + private val dispatcher = UnconfinedTestDispatcher() + private val viewModelStore = ViewModelStore() + private val appScope = CoroutineScope(SupervisorJob()) + + private val user = User( + id = USER_ID, + userId = "jane", + username = "jane", + baseUrl = "https://cloud.example.com", + token = "token", + displayName = "Jane", + capabilities = capabilities(readStatusPrivate = false) + ) + private val userFlow = MutableStateFlow(user) + + private lateinit var appPreferences: AppPreferences + private lateinit var userManager: UserManager + private lateinit var workManager: WorkManager + private lateinit var context: Context + private val repository = FakeSettingsRepository() + + @Before + fun setUp() { + Dispatchers.setMain(dispatcher) + appPreferences = mock { + on { proxyType } doReturn NO_PROXY + on { theme } doReturn "night_yes" + on { screenLockTimeout } doReturn "60" + on { showRegularNotificationWarning } doReturn true + } + userManager = mock { + on { userFlow(USER_ID) } doReturn userFlow + } + userManager.stub { + onBlocking { scheduleUserForDeletionWithId(any()) } doReturn true + onBlocking { getUsers() } doReturn listOf(user) + } + workManager = mock() + val resources = mock { + on { getBoolean(R.bool.is_branded_client) } doReturn false + } + context = mock { + on { this.resources } doReturn resources + on { getString(R.string.nc_no_proxy) } doReturn NO_PROXY + on { getString(R.string.nc_settings_http_value) } doReturn "3128" + on { getString(R.string.nc_settings_socks_value) } doReturn "1080" + } + } + + @After + fun tearDown() { + viewModelStore.clear() + appScope.cancel() + Dispatchers.resetMain() + } + + private fun createViewModel(highlightNotificationIssues: Boolean = false): SettingsViewModel { + val networkMonitor = mock { on { isOnline } doReturn MutableStateFlow(true) } + val logsRepository = mock { on { minimumLevel } doReturn Level.INFO } + return SettingsViewModel( + appPreferences = appPreferences, + userManager = userManager, + settingsRepository = repository, + logsRepository = logsRepository, + deviceStateReader = mock { on { read() } doReturn DEVICE_STATE }, + workManager = workManager, + logger = mock(), + networkMonitor = networkMonitor, + appScope = appScope, + context = context, + initialUser = user, + highlightNotificationIssues = highlightNotificationIssues + ).also { + it.ioDispatcher = dispatcher + viewModelStore.put("settings", it) + } + } + + @Test + fun `initial state reflects the stored preferences and the account`() { + val state = createViewModel(highlightNotificationIssues = true).uiState.value + + assertEquals("night_yes", state.appearance.theme) + assertEquals("60", state.privacy.screenLockTimeout) + assertTrue(state.notifications.showNotificationWarning) + assertEquals("Jane", state.account.displayName) + assertTrue(state.privacy.readStatusAvailable) + assertTrue(state.privacy.readStatusShared) + assertTrue(state.highlightNotificationIssues) + assertEquals(ProxyUiState(type = NO_PROXY), state.proxy) + } + + @Test + fun `read status change is reverted when the server rejects it`() { + repository.failPrivacyRequests = true + val viewModel = createViewModel() + + viewModel.setReadStatusShared(false) + + assertTrue(viewModel.uiState.value.privacy.readStatusShared) + assertEquals(listOf(false), repository.readStatusRequests) + } + + @Test + fun `confirmed read status change survives an unrelated update of the account`() { + val viewModel = createViewModel() + + viewModel.setReadStatusShared(false) + userFlow.value = user.copy(displayName = "Jane Doe") + + assertFalse(viewModel.uiState.value.privacy.readStatusShared) + assertEquals("Jane Doe", viewModel.uiState.value.account.displayName) + } + + @Test + fun `read status follows a change on the server`() { + val viewModel = createViewModel() + + userFlow.value = user.copy(capabilities = capabilities(readStatusPrivate = true)) + + assertFalse(viewModel.uiState.value.privacy.readStatusShared) + } + + @Test + fun `selecting a proxy type sets its default port`() { + val viewModel = createViewModel() + + viewModel.setProxyType("HTTP") + + assertEquals(ProxyUiState(type = "HTTP", port = "3128"), viewModel.uiState.value.proxy) + verify(appPreferences, timeout(TIMEOUT_MS)).proxyPort = "3128" + } + + @Test + fun `turning the proxy off clears its settings`() { + val viewModel = createViewModel() + viewModel.setProxyType("SOCKS") + viewModel.setProxyHost("proxy.example.com") + viewModel.setProxyUseCredentials(true) + viewModel.setProxyUsername("user") + + viewModel.setProxyType(NO_PROXY) + + assertEquals(ProxyUiState(type = NO_PROXY), viewModel.uiState.value.proxy) + // also cleared once on creation, as the proxy was off + verify(appPreferences, timeout(TIMEOUT_MS).times(2)).removeProxyHost() + verify(appPreferences, timeout(TIMEOUT_MS).times(2)).removeProxyUsername() + } + + @Test + fun `turning proxy credentials off clears them`() { + val viewModel = createViewModel() + viewModel.setProxyType("HTTP") + viewModel.setProxyUseCredentials(true) + viewModel.setProxyUsername("user") + viewModel.setProxyPassword("secret") + + viewModel.setProxyUseCredentials(false) + + val proxy = viewModel.uiState.value.proxy + assertFalse(proxy.useCredentials) + assertEquals("", proxy.username) + assertEquals("", proxy.password) + } + + @Test + fun `phone number is asked for when the phone book integration is enabled without one`() { + repository.profile = UserProfileDataDto().apply { phone = "" } + val viewModel = createViewModel() + + viewModel.enablePhoneBookIntegration() + + assertTrue(viewModel.uiState.value.privacy.phoneBookIntegration) + assertTrue(viewModel.uiState.value.showPhoneNumberDialog) + } + + @Test + fun `rejected phone number keeps the dialog open with an error`() { + repository.acceptPhoneNumber = false + val viewModel = createViewModel() + + viewModel.submitPhoneNumber("123") + + assertTrue(viewModel.uiState.value.phoneNumberError) + } + + @Test + fun `accepted phone number closes the dialog and confirms it`() = + runTest(dispatcher) { + val viewModel = createViewModel() + repository.profile = UserProfileDataDto().apply { phone = "" } + viewModel.enablePhoneBookIntegration() + + viewModel.submitPhoneNumber("49123456") + + assertFalse(viewModel.uiState.value.showPhoneNumberDialog) + assertEquals( + SettingsEvent.ShowMessage(R.string.nc_settings_phone_book_integration_phone_number_dialog_success), + viewModel.events.first() + ) + } + + @Test + fun `denied contacts permission keeps the phone book integration off`() = + runTest(dispatcher) { + val viewModel = createViewModel() + + viewModel.onContactsPermissionDenied() + + assertFalse(viewModel.uiState.value.privacy.phoneBookIntegration) + assertEquals( + SettingsEvent.ShowMessage(R.string.no_phone_book_integration_due_to_permissions), + viewModel.events.first() + ) + } + + @Test + fun `removed account is reported once the removal finished`() = + runTest(dispatcher) { + val workInfo = WorkInfo(UUID.randomUUID(), WorkInfo.State.SUCCEEDED, emptySet()) + whenever(workManager.getWorkInfoByIdFlow(any())).thenReturn(flowOf(workInfo)) + val viewModel = createViewModel() + + viewModel.removeAccount() + userFlow.value = user.copy(scheduledForDeletion = true) + + assertEquals(SettingsEvent.AccountRemoved("Jane"), viewModel.events.first()) + } + + @Test + fun `screen is closed when its account disappears`() = + runTest(dispatcher) { + val viewModel = createViewModel() + + userFlow.value = null + + assertEquals(SettingsEvent.AccountUnavailable, viewModel.events.first()) + } + + @Test + fun `account message is shown until dismissed`() { + val viewModel = createViewModel() + ApplicationWideMessageHolder.getInstance().messageType = + ApplicationWideMessageHolder.MessageType.ACCOUNT_WAS_IMPORTED + viewModel.onResume() + + assertEquals(AccountMessage.ACCOUNT_IMPORTED, viewModel.uiState.value.accountMessage) + + viewModel.dismissAccountMessage() + + assertNull(viewModel.uiState.value.accountMessage) + } + + private fun capabilities(readStatusPrivate: Boolean) = + CapabilitiesDto().apply { + spreedCapability = SpreedCapabilityDto( + features = emptyList(), + config = hashMapOf("chat" to hashMapOf("read-privacy" to if (readStatusPrivate) 1 else 0)), + version = "" + ) + } + + private class FakeSettingsRepository : SettingsRepository { + var profile: UserProfileDataDto? = null + var acceptPhoneNumber = true + var failPrivacyRequests = false + val readStatusRequests = mutableListOf() + + override suspend fun getUserProfile(user: User): UserProfileDataDto? = profile + + override suspend fun setPhoneNumber(user: User, phoneNumber: String): Boolean = acceptPhoneNumber + + override suspend fun setReadStatusShared(user: User, shared: Boolean) { + readStatusRequests += shared + if (failPrivacyRequests) throw IOException("rejected") + } + + override suspend fun setTypingStatusShared(user: User, shared: Boolean) { + if (failPrivacyRequests) throw IOException("rejected") + } + } + + companion object { + private const val USER_ID = 1L + private const val NO_PROXY = "No proxy" + private const val TIMEOUT_MS = 1000L + private val DEVICE_STATE = DeviceState( + isGooglePlayServicesAvailable = true, + hasEmbeddedDistributor = false, + externalDistributorCount = 0, + acknowledgedDistributor = null, + notificationPermissionGranted = true, + batteryOptimizationIgnored = true, + fullScreenIntentGranted = null, + callRingtone = RingtoneState.Default, + messageRingtone = RingtoneState.Disabled, + isKeyguardSecure = true + ) + } +} From 4ea8baf5a8aa81f8df327b9017db1bba224b520a Mon Sep 17 00:00:00 2001 From: Marcel Hibbe Date: Mon, 16 Nov 2026 22:38:15 +0100 Subject: [PATCH 2/5] fix(settings): address review findings of the Compose migration - Remove accounts via AccountRemover in the application scope, so the app still restarts after the settings screen closes, and keep the screen open while its account is being removed - Ignore selecting the current proxy type, which reset a custom port - Send read and typing status changes one at a time and revert failed ones to the value the server confirmed last - Load the avatar with the Authorization header - Apply the incognito keyboard setting to Compose text fields via IncognitoKeyboard - Reset the screen lock timeout when the device lock is not secure - Keep the state update free of side effects - Store proxy fields when editing ends instead of on every keystroke - Compute whether the proxy is enabled once in the view model - Remove the unused NcApi.getUserData Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marcel Hibbe --- .../java/com/nextcloud/talk/api/NcApi.java | 3 - .../talk/components/IncognitoKeyboard.kt | 41 +++++ .../nextcloud/talk/settings/AccountRemover.kt | 63 +++++++ .../talk/settings/SettingsActivity.kt | 10 -- .../talk/settings/SettingsUiState.kt | 6 +- .../talk/settings/SettingsViewModel.kt | 167 ++++++++++++------ .../settings/ui/SettingsAccountSection.kt | 17 +- .../talk/settings/ui/SettingsProxySection.kt | 41 +++-- .../talk/settings/ui/SettingsScreen.kt | 43 +++-- .../talk/settings/SettingsViewModelTest.kt | 96 ++++++++-- 10 files changed, 369 insertions(+), 118 deletions(-) create mode 100644 app/src/main/java/com/nextcloud/talk/components/IncognitoKeyboard.kt create mode 100644 app/src/main/java/com/nextcloud/talk/settings/AccountRemover.kt diff --git a/app/src/main/java/com/nextcloud/talk/api/NcApi.java b/app/src/main/java/com/nextcloud/talk/api/NcApi.java index 152ce67a188..aba26db0cef 100644 --- a/app/src/main/java/com/nextcloud/talk/api/NcApi.java +++ b/app/src/main/java/com/nextcloud/talk/api/NcApi.java @@ -255,9 +255,6 @@ Observable pullSignalingMessages(@Nullable @Header("Authorizat Observable getUserProfile(@Header("Authorization") String authorization, @Url String url); - @GET - Observable getUserData(@Header("Authorization") String authorization, @Url String url); - @DELETE Observable revertStatus(@Header("Authentication") String authorization, @Url String url); diff --git a/app/src/main/java/com/nextcloud/talk/components/IncognitoKeyboard.kt b/app/src/main/java/com/nextcloud/talk/components/IncognitoKeyboard.kt new file mode 100644 index 00000000000..2b1b97e0c61 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/components/IncognitoKeyboard.kt @@ -0,0 +1,41 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.components + +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputConnection +import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.InterceptPlatformTextInput +import androidx.compose.ui.platform.PlatformTextInputMethodRequest + +/** + * Asks the keyboard not to learn from what is typed into the text fields of [content] while [enabled], like + * `BaseActivity` does for the text fields of views. + */ +@Composable +fun IncognitoKeyboard(enabled: Boolean, content: @Composable () -> Unit) { + InterceptPlatformTextInput( + interceptor = { request, nextHandler -> + // a changed flag passes a new interceptor, which restarts an active session with it + if (enabled) { + nextHandler.startInputMethod( + object : PlatformTextInputMethodRequest { + override fun createInputConnection(outAttributes: EditorInfo): InputConnection { + val inputConnection = request.createInputConnection(outAttributes) + outAttributes.imeOptions = + outAttributes.imeOptions or EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING + return inputConnection + } + } + ) + } else { + nextHandler.startInputMethod(request) + } + }, + content = content + ) +} diff --git a/app/src/main/java/com/nextcloud/talk/settings/AccountRemover.kt b/app/src/main/java/com/nextcloud/talk/settings/AccountRemover.kt new file mode 100644 index 00000000000..66a058166a2 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/AccountRemover.kt @@ -0,0 +1,63 @@ +/* + * 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 android.widget.Toast +import androidx.work.OneTimeWorkRequest +import androidx.work.WorkInfo +import androidx.work.WorkManager +import com.nextcloud.talk.R +import com.nextcloud.talk.dagger.modules.ApplicationScope +import com.nextcloud.talk.jobs.AccountRemovalWorker +import com.nextcloud.talk.logger.Logger +import com.nextcloud.talk.users.UserManager +import com.nextcloud.talk.utils.AppTasks +import com.nextcloud.talk.utils.setExpeditedIfSupported +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import javax.inject.Inject + +/** + * Removes an account and restarts the app afterwards. Runs in the application scope, as the screen that started it is + * closed as soon as the account is gone. + */ +class AccountRemover @Inject constructor( + private val context: Context, + private val userManager: UserManager, + private val workManager: WorkManager, + private val logger: Logger, + @ApplicationScope private val appScope: CoroutineScope +) { + fun remove(userId: Long, displayName: String) { + appScope.launch { + userManager.scheduleUserForDeletionWithId(userId) + val request = OneTimeWorkRequest.Builder(AccountRemovalWorker::class.java) + .setExpeditedIfSupported() + .build() + workManager.enqueue(request) + val result = workManager.getWorkInfoByIdFlow(request.id).first { it?.state?.isFinished == true } + val message = if (result?.state == WorkInfo.State.SUCCEEDED) { + context.getString(R.string.nc_deleted_user, displayName) + } else { + logger.e(TAG, "Failed to remove the account with id $userId") + context.getString(R.string.nc_common_error_sorry) + } + withContext(Dispatchers.Main) { + Toast.makeText(context, message, Toast.LENGTH_LONG).show() + context.startActivity(AppTasks.createRestartIntent(context)) + } + } + } + + companion object { + private val TAG = AccountRemover::class.java.simpleName + } +} 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 eff10417f24..88d2776641d 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt @@ -19,7 +19,6 @@ import android.provider.Settings import android.security.KeyChain import android.util.Log import android.view.WindowManager -import android.widget.Toast import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.material3.MaterialTheme @@ -48,7 +47,6 @@ 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.utils.AppTasks import com.nextcloud.talk.utils.LoggingUtils.sendMailWithAttachment import com.nextcloud.talk.utils.NotificationUtils import com.nextcloud.talk.utils.UnifiedPushUtils @@ -208,14 +206,6 @@ class SettingsActivity : BaseActivity() { private suspend fun handleEvent(event: SettingsEvent) { when (event) { is SettingsEvent.ShowMessage -> snackbarHostState.showSnackbar(getString(event.messageRes)) - is SettingsEvent.AccountRemoved -> { - Toast.makeText(this, getString(R.string.nc_deleted_user, event.displayName), Toast.LENGTH_LONG).show() - startActivity(AppTasks.createRestartIntent(this)) - } - SettingsEvent.AccountRemovalFailed -> { - Toast.makeText(this, R.string.nc_common_error_sorry, Toast.LENGTH_LONG).show() - startActivity(AppTasks.createRestartIntent(this)) - } SettingsEvent.AccountUnavailable -> finish() } } 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 2fa51a92316..7cfecb5e143 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt @@ -31,6 +31,8 @@ data class AccountUiState( val displayName: String = "", val baseUrl: String = "", val avatarId: String = "", + /** Authorization for loading the avatar. */ + val credentials: String = "", val serverAgeWarning: ServerAgeWarning = ServerAgeWarning.NONE ) @@ -128,6 +130,8 @@ enum class LoggingStatus { data class ProxyUiState( /** One of `R.array.proxy_type_descriptions`. */ val type: String = "", + /** Whether [type] is a proxy, not "No proxy". */ + val enabled: Boolean = false, val host: String = "", val port: String = "", val useCredentials: Boolean = false, @@ -138,8 +142,6 @@ data class ProxyUiState( /** One-off effects of the settings screen that the activity performs. */ sealed interface SettingsEvent { data class ShowMessage(val messageRes: Int) : SettingsEvent - data class AccountRemoved(val displayName: String) : SettingsEvent - data object AccountRemovalFailed : SettingsEvent /** The account of the screen doesn't exist anymore. */ data object AccountUnavailable : SettingsEvent 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 7ee773ed40d..cf74db39607 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt @@ -12,14 +12,12 @@ import androidx.annotation.VisibleForTesting import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.work.OneTimeWorkRequest -import androidx.work.WorkInfo import androidx.work.WorkManager import com.nextcloud.talk.R import com.nextcloud.talk.conversationlist.ConversationsListActivity.Companion.NOTIFICATION_WARNING_DATE_NOT_SET import com.nextcloud.talk.dagger.modules.ApplicationScope import com.nextcloud.talk.data.network.NetworkMonitor import com.nextcloud.talk.data.user.model.User -import com.nextcloud.talk.jobs.AccountRemovalWorker import com.nextcloud.talk.jobs.CapabilitiesSyncWorker import com.nextcloud.talk.jobs.ContactAddressBookWorker import com.nextcloud.talk.logger.Level @@ -27,6 +25,7 @@ import com.nextcloud.talk.logger.Logger import com.nextcloud.talk.logger.LogsRepository import com.nextcloud.talk.settings.data.SettingsRepository import com.nextcloud.talk.users.UserManager +import com.nextcloud.talk.utils.ApiUtils import com.nextcloud.talk.utils.CapabilitiesUtil import com.nextcloud.talk.utils.SecurityUtils import com.nextcloud.talk.utils.SpreedFeatures @@ -45,10 +44,11 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import retrofit2.HttpException import java.io.IOException @@ -60,6 +60,7 @@ class SettingsViewModel @AssistedInject constructor( private val settingsRepository: SettingsRepository, private val logsRepository: LogsRepository, private val deviceStateReader: DeviceStateReader, + private val accountRemover: AccountRemover, private val workManager: WorkManager, private val logger: Logger, networkMonitor: NetworkMonitor, @@ -82,8 +83,10 @@ class SettingsViewModel @AssistedInject constructor( // The last values in the stored account, which are only updated with the capabilities. A change is shown until // they change, so that an update of e.g. the display name doesn't revert it. - private var serverReadStatusShared: Boolean? = null - private var serverTypingStatusShared: Boolean? = null + private var storedReadStatusShared: Boolean? = null + private var storedTypingStatusShared: Boolean? = null + private val readStatusSetting = ServerSetting() + private val typingStatusSetting = ServerSetting() private var allAccountsSupportWebPush = false private var unifiedPushPreference = false @@ -103,16 +106,28 @@ class SettingsViewModel @AssistedInject constructor( clearDisabledProxySettings() viewModelScope.launch { userManager.userFlow(userId).collect { updatedUser -> - if (updatedUser == null || (updatedUser.scheduledForDeletion && !isRemovingAccount)) { - _events.send(SettingsEvent.AccountUnavailable) - } else { - user.value = updatedUser + when { + // the account disappears while it is removed, which restarts the app when done + isRemovingAccount -> Unit + updatedUser == null || updatedUser.scheduledForDeletion -> + _events.send(SettingsEvent.AccountUnavailable) + else -> user.value = updatedUser } } } viewModelScope.launch { combine(user, networkMonitor.isOnline, ::Pair).collect { (currentUser, isOnline) -> - _uiState.update { it.withUser(currentUser, isOnline) } + val readStatusChange = storedValueChange( + value = !CapabilitiesUtil.isReadStatusPrivate(currentUser), + previous = storedReadStatusShared, + setting = readStatusSetting + ).also { storedReadStatusShared = it ?: storedReadStatusShared } + val typingStatusChange = storedValueChange( + value = !CapabilitiesUtil.isTypingStatusPrivate(currentUser), + previous = storedTypingStatusShared, + setting = typingStatusSetting + ).also { storedTypingStatusShared = it ?: storedTypingStatusShared } + _uiState.update { it.withUser(currentUser, isOnline, readStatusChange, typingStatusChange) } } } } @@ -144,10 +159,15 @@ class SettingsViewModel @AssistedInject constructor( _uiState.update { it.copy( notifications = notificationsState(state), - privacy = it.privacy.copy( - screenLockAvailable = state.isKeyguardSecure, - screenLock = state.isKeyguardSecure && it.privacy.screenLock - ) + privacy = if (state.isKeyguardSecure) { + it.privacy.copy(screenLockAvailable = true) + } else { + it.privacy.copy( + screenLockAvailable = false, + screenLock = false, + screenLockTimeout = context.getString(R.string.nc_screen_lock_timeout_sixty) + ) + } ) } } @@ -284,14 +304,16 @@ class SettingsViewModel @AssistedInject constructor( fun setReadStatusShared(shared: Boolean) { updatePrivacySetting( + setting = readStatusSetting, apply = { state, value -> state.copy(readStatusShared = value) }, shared = shared, - request = { settingsRepository.setReadStatusShared(user.value, shared) } + request = { settingsRepository.setReadStatusShared(user.value, it) } ) } fun setTypingStatusShared(shared: Boolean) { updatePrivacySetting( + setting = typingStatusSetting, apply = { state, value -> if (state.typingStatus is TypingStatusUiState.Available) { state.copy(typingStatus = TypingStatusUiState.Available(value)) @@ -300,7 +322,7 @@ class SettingsViewModel @AssistedInject constructor( } }, shared = shared, - request = { settingsRepository.setTypingStatusShared(user.value, shared) } + request = { settingsRepository.setTypingStatusShared(user.value, it) } ) } @@ -318,6 +340,7 @@ class SettingsViewModel @AssistedInject constructor( } fun setProxyType(type: String) { + if (type == _uiState.value.proxy.type) return if (!isProxyEnabled(type)) { _uiState.update { it.copy(proxy = ProxyUiState(type = type)) } persist { prefs -> prefs.proxyType = type } @@ -325,19 +348,22 @@ class SettingsViewModel @AssistedInject constructor( return } val port = defaultProxyPort(type) ?: _uiState.value.proxy.port - _uiState.update { it.copy(proxy = it.proxy.copy(type = type, port = port)) } + _uiState.update { it.copy(proxy = it.proxy.copy(type = type, enabled = true, port = port)) } persist { prefs -> prefs.proxyType = type prefs.proxyPort = port } } + // the text fields commit when they leave the screen, also after the proxy or its credentials were turned off fun setProxyHost(host: String) { + if (!_uiState.value.proxy.enabled) return _uiState.update { it.copy(proxy = it.proxy.copy(host = host)) } persist { prefs -> prefs.proxyHost = host } } fun setProxyPort(port: String) { + if (!_uiState.value.proxy.enabled) return _uiState.update { it.copy(proxy = it.proxy.copy(port = port)) } persist { prefs -> prefs.proxyPort = port } } @@ -362,11 +388,13 @@ class SettingsViewModel @AssistedInject constructor( } fun setProxyUsername(username: String) { + if (!_uiState.value.proxy.useCredentials) return _uiState.update { it.copy(proxy = it.proxy.copy(username = username)) } persist { prefs -> prefs.proxyUsername = username } } fun setProxyPassword(password: String) { + if (!_uiState.value.proxy.useCredentials) return _uiState.update { it.copy(proxy = it.proxy.copy(password = password)) } persist { prefs -> prefs.proxyPassword = password } } @@ -374,21 +402,7 @@ class SettingsViewModel @AssistedInject constructor( fun removeAccount() { if (isRemovingAccount) return isRemovingAccount = true - val displayName = _uiState.value.account.displayName - viewModelScope.launch { - userManager.scheduleUserForDeletionWithId(userId) - val request = OneTimeWorkRequest.Builder(AccountRemovalWorker::class.java) - .setExpeditedIfSupported() - .build() - workManager.enqueue(request) - val result = workManager.getWorkInfoByIdFlow(request.id).first { it?.state?.isFinished == true } - if (result?.state == WorkInfo.State.SUCCEEDED) { - _events.send(SettingsEvent.AccountRemoved(displayName)) - } else { - logger.e(TAG, "Failed to remove the account with id $userId") - _events.send(SettingsEvent.AccountRemovalFailed) - } - } + accountRemover.remove(userId, _uiState.value.account.displayName) } private fun initialState(initialUser: User, highlightNotificationIssues: Boolean): SettingsUiState { @@ -417,6 +431,7 @@ class SettingsViewModel @AssistedInject constructor( proxy = if (isProxyEnabled(proxyType)) { ProxyUiState( type = proxyType, + enabled = true, host = appPreferences.proxyHost, port = appPreferences.proxyPort, useCredentials = useCredentials, @@ -430,21 +445,24 @@ class SettingsViewModel @AssistedInject constructor( ) } - private fun SettingsUiState.withUser(currentUser: User, isOnline: Boolean): SettingsUiState { - val readStatusShared = !CapabilitiesUtil.isReadStatusPrivate(currentUser) - val typingStatusShared = !CapabilitiesUtil.isTypingStatusPrivate(currentUser) - val readStatusChangedOnServer = readStatusShared != serverReadStatusShared - val typingStatusChangedOnServer = typingStatusShared != serverTypingStatusShared - serverReadStatusShared = readStatusShared - serverTypingStatusShared = typingStatusShared - + /** + * Applies [currentUser]. [readStatusChange] and [typingStatusChange] are the values of the stored account if they + * changed, else null to keep what the screen shows. + */ + private fun SettingsUiState.withUser( + currentUser: User, + isOnline: Boolean, + readStatusChange: Boolean?, + typingStatusChange: Boolean? + ): SettingsUiState { val spreedCapability = currentUser.capabilities?.spreedCapability val typingStatus = when { currentUser.externalSignalingServer?.externalSignalingServer.isNullOrEmpty() -> TypingStatusUiState.RequiresHighPerformanceBackend !isOnline || !CapabilitiesUtil.isTypingStatusAvailable(currentUser) -> TypingStatusUiState.Hidden - typingStatusChangedOnServer || privacy.typingStatus !is TypingStatusUiState.Available -> - TypingStatusUiState.Available(typingStatusShared) + typingStatusChange != null -> TypingStatusUiState.Available(typingStatusChange) + privacy.typingStatus !is TypingStatusUiState.Available -> + TypingStatusUiState.Available(typingStatusSetting.requested ?: false) else -> privacy.typingStatus } return copy( @@ -458,7 +476,7 @@ class SettingsViewModel @AssistedInject constructor( phoneBookIntegrationAvailable = isOnline && CapabilitiesUtil.hasSpreedFeatureCapability(spreedCapability, SpreedFeatures.PHONEBOOK_SEARCH), readStatusAvailable = isOnline && CapabilitiesUtil.isReadStatusAvailable(spreedCapability), - readStatusShared = if (readStatusChangedOnServer) readStatusShared else privacy.readStatusShared, + readStatusShared = readStatusChange ?: privacy.readStatusShared, typingStatus = typingStatus ) ) @@ -470,6 +488,7 @@ class SettingsViewModel @AssistedInject constructor( displayName = currentUser.displayName.orEmpty(), baseUrl = currentUser.baseUrl.orEmpty(), avatarId = currentUser.userId?.takeIf { it.isNotEmpty() } ?: currentUser.username.orEmpty(), + credentials = ApiUtils.getCredentials(currentUser.username, currentUser.token).orEmpty(), serverAgeWarning = when { CapabilitiesUtil.isServerEOL(serverVersion) -> ServerAgeWarning.END_OF_LIFE CapabilitiesUtil.isServerAlmostEOL(serverVersion) -> ServerAgeWarning.ALMOST_END_OF_LIFE @@ -511,25 +530,58 @@ class SettingsViewModel @AssistedInject constructor( ) } + /** + * Returns [value] if it differs from the [previous] value of the stored account, after taking it over as the + * confirmed value of [setting]. Returns null if it didn't change. + */ + private fun storedValueChange(value: Boolean, previous: Boolean?, setting: ServerSetting): Boolean? { + if (value == previous) return null + setting.confirmed = value + setting.requested = value + return value + } + + /** + * Shows [shared] right away and sends it to the server. Requests are sent one at a time, a change replaced by a + * newer one is skipped, and a failed change shows the value the server confirmed last. + */ private fun updatePrivacySetting( + setting: ServerSetting, apply: (PrivacyUiState, Boolean) -> PrivacyUiState, shared: Boolean, - request: suspend () -> Unit + request: suspend (Boolean) -> Unit ) { + setting.requested = shared _uiState.update { it.copy(privacy = apply(it.privacy, shared)) } viewModelScope.launch { - try { - request() - } catch (e: IOException) { - logger.e(TAG, "Failed to change a privacy setting", e) - _uiState.update { it.copy(privacy = apply(it.privacy, !shared)) } - } catch (e: HttpException) { - logger.e(TAG, "Failed to change a privacy setting", e) - _uiState.update { it.copy(privacy = apply(it.privacy, !shared)) } + setting.mutex.withLock { + if (setting.requested != shared || setting.confirmed == shared) return@withLock + try { + request(shared) + setting.confirmed = shared + } catch (e: IOException) { + logger.e(TAG, "Failed to change a privacy setting", e) + revertPrivacySetting(setting, apply, shared) + } catch (e: HttpException) { + logger.e(TAG, "Failed to change a privacy setting", e) + revertPrivacySetting(setting, apply, shared) + } } } } + private fun revertPrivacySetting( + setting: ServerSetting, + apply: (PrivacyUiState, Boolean) -> PrivacyUiState, + failed: Boolean + ) { + val confirmed = setting.confirmed ?: !failed + if (setting.requested == failed) { + setting.requested = confirmed + _uiState.update { it.copy(privacy = apply(it.privacy, confirmed)) } + } + } + private fun setPhoneBookIntegrationState(enabled: Boolean) { _uiState.update { it.copy(privacy = it.privacy.copy(phoneBookIntegration = enabled)) } } @@ -620,3 +672,14 @@ class SettingsViewModel @AssistedInject constructor( private const val PROXY_TYPE_SOCKS = "SOCKS" } } + +/** A setting stored on the server, which the screen changes one request at a time. */ +private class ServerSetting { + val mutex = Mutex() + + /** The value the server confirmed last, or the one of the stored account. */ + var confirmed: Boolean? = null + + /** The value chosen last on the screen. */ + var requested: Boolean? = null +} diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsAccountSection.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsAccountSection.kt index 57028f41a59..1ef436a2ad8 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsAccountSection.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsAccountSection.kt @@ -46,8 +46,9 @@ import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.core.net.toUri import coil.compose.AsyncImage +import coil.request.ImageRequest +import coil.transform.CircleCropTransformation import com.nextcloud.talk.R -import com.nextcloud.talk.contacts.loadImage import com.nextcloud.talk.settings.AccountMessage import com.nextcloud.talk.settings.AccountUiState import com.nextcloud.talk.settings.ServerAgeWarning @@ -162,12 +163,14 @@ private fun AccountAvatar(account: AccountUiState) { } val context = LocalContext.current val isDarkTheme = isSystemInDarkTheme() - val request = remember(account.baseUrl, account.avatarId, isDarkTheme) { - loadImage( - ApiUtils.getUrlForAvatar(account.baseUrl, account.avatarId, true, isDarkTheme), - context, - R.drawable.account_circle_96dp - ) + val request = remember(account.baseUrl, account.avatarId, account.credentials, isDarkTheme) { + ImageRequest.Builder(context) + .data(ApiUtils.getUrlForAvatar(account.baseUrl, account.avatarId, true, isDarkTheme)) + .addHeader("Authorization", account.credentials) + .transformations(CircleCropTransformation()) + .placeholder(R.drawable.account_circle_96dp) + .error(R.drawable.account_circle_96dp) + .build() } AsyncImage(model = request, contentDescription = stringResource(R.string.avatar), modifier = modifier) } diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsProxySection.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsProxySection.kt index 2efb2eff4da..e7f3e61d1ac 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsProxySection.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsProxySection.kt @@ -19,11 +19,14 @@ import androidx.compose.material3.Text 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.mutableStateOf +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.res.stringArrayResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction @@ -32,13 +35,14 @@ import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect import com.nextcloud.talk.R import com.nextcloud.talk.settings.ProxyUiState @Composable internal fun ProxySettings(state: ProxyUiState, callbacks: ProxyCallbacks) { val proxyTypes = stringArrayResource(R.array.proxy_type_descriptions) - val proxyEnabled = state.type.isNotEmpty() && state.type != proxyTypes.first() Column { SettingsDropdown( label = stringResource(R.string.nc_settings_proxy_type_title), @@ -46,12 +50,12 @@ internal fun ProxySettings(state: ProxyUiState, callbacks: ProxyCallbacks) { selectedValue = state.type, onValueSelected = callbacks.onTypeChange ) - if (proxyEnabled) { + if (state.enabled) { ProxyTextField( label = stringResource(R.string.nc_settings_proxy_host_title), initialValue = state.host, keyboardType = KeyboardType.Uri, - onValueChange = callbacks.onHostChange + onCommit = callbacks.onHostChange ) // the port is replaced by the default port of a newly selected type ProxyTextField( @@ -59,7 +63,7 @@ internal fun ProxySettings(state: ProxyUiState, callbacks: ProxyCallbacks) { initialValue = state.port, resetKey = state.type, keyboardType = KeyboardType.Number, - onValueChange = callbacks.onPortChange + onCommit = callbacks.onPortChange ) SettingsSwitchItem( title = stringResource(R.string.nc_settings_use_credentials_title), @@ -71,13 +75,13 @@ internal fun ProxySettings(state: ProxyUiState, callbacks: ProxyCallbacks) { label = stringResource(R.string.nc_settings_proxy_username_title), initialValue = state.username, keyboardType = KeyboardType.Text, - onValueChange = callbacks.onUsernameChange + onCommit = callbacks.onUsernameChange ) ProxyTextField( label = stringResource(R.string.nc_settings_proxy_password_title), initialValue = state.password, keyboardType = KeyboardType.Password, - onValueChange = callbacks.onPasswordChange + onCommit = callbacks.onPasswordChange ) } } @@ -85,24 +89,34 @@ internal fun ProxySettings(state: ProxyUiState, callbacks: ProxyCallbacks) { } /** - * A text field that keeps its text locally, so that typing isn't delayed by the round trip through the view model. The - * text is reset to [initialValue] when [resetKey] changes. + * A text field whose text is committed with [onCommit] once editing ends: when it loses the focus, leaves the screen or + * the app goes to the background. That avoids storing every intermediate value. The text is reset to [initialValue] + * when [resetKey] changes. */ @Composable private fun ProxyTextField( label: String, initialValue: String, keyboardType: KeyboardType, - onValueChange: (String) -> Unit, + onCommit: (String) -> Unit, resetKey: Any? = null ) { var text by rememberSaveable(resetKey) { mutableStateOf(initialValue) } + var committedText by rememberSaveable(resetKey) { mutableStateOf(initialValue) } + val currentOnCommit by rememberUpdatedState(onCommit) + val commit by rememberUpdatedState { + if (text != committedText) { + committedText = text + currentOnCommit(text) + } + } + LifecycleEventEffect(Lifecycle.Event.ON_STOP) { commit() } + DisposableEffect(Unit) { + onDispose { commit() } + } OutlinedTextField( value = text, - onValueChange = { - text = it - onValueChange(it) - }, + onValueChange = { text = it }, label = { Text(label) }, singleLine = true, visualTransformation = if (keyboardType == KeyboardType.Password) { @@ -118,6 +132,7 @@ private fun ProxyTextField( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 8.dp) + .onFocusChanged { if (!it.isFocused) commit() } ) } 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 b794cc23083..49472ffadc8 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 @@ -39,6 +39,7 @@ import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.nextcloud.talk.R 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.NotificationsUiState @@ -114,22 +115,24 @@ fun SettingsScreen( snackbarHostState: SnackbarHostState = remember { SnackbarHostState() } ) { ColoredStatusBar() - Scaffold( - modifier = Modifier - .statusBarsPadding() - .displayCutoutPadding(), - topBar = { StandardAppBar(title = stringResource(R.string.nc_settings), menuItems = null) }, - snackbarHost = { SnackbarHost(snackbarHostState) } - ) { paddingValues -> - SettingsContent(state = state, callbacks = callbacks, paddingValues = paddingValues) - } - if (state.showPhoneNumberDialog) { - PhoneNumberDialog( - isError = state.phoneNumberError, - onPhoneNumberChange = callbacks.onPhoneNumberChange, - onSubmit = callbacks.onSubmitPhoneNumber, - onDismiss = callbacks.onDismissPhoneNumberDialog - ) + IncognitoKeyboard(enabled = state.privacy.incognitoKeyboard) { + Scaffold( + modifier = Modifier + .statusBarsPadding() + .displayCutoutPadding(), + topBar = { StandardAppBar(title = stringResource(R.string.nc_settings), menuItems = null) }, + snackbarHost = { SnackbarHost(snackbarHostState) } + ) { paddingValues -> + SettingsContent(state = state, callbacks = callbacks, paddingValues = paddingValues) + } + if (state.showPhoneNumberDialog) { + PhoneNumberDialog( + isError = state.phoneNumberError, + onPhoneNumberChange = callbacks.onPhoneNumberChange, + onSubmit = callbacks.onSubmitPhoneNumber, + onDismiss = callbacks.onDismissPhoneNumberDialog + ) + } } } @@ -200,7 +203,13 @@ internal fun previewSettingsState(): SettingsUiState = readStatusShared = true, typingStatus = TypingStatusUiState.RequiresHighPerformanceBackend ), - proxy = ProxyUiState(type = "HTTP", host = "proxy.example.com", port = "3128", useCredentials = true) + proxy = ProxyUiState( + type = "HTTP", + enabled = true, + host = "proxy.example.com", + port = "3128", + useCredentials = true + ) ) @Preview(name = "Light", heightDp = 2400) 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 b92232b75da..f9f024eee89 100644 --- a/app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt +++ b/app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt @@ -9,7 +9,6 @@ package com.nextcloud.talk.settings import android.content.Context import android.content.res.Resources import androidx.lifecycle.ViewModelStore -import androidx.work.WorkInfo import androidx.work.WorkManager import com.nextcloud.talk.R import com.nextcloud.talk.data.network.NetworkMonitor @@ -24,6 +23,7 @@ import com.nextcloud.talk.settings.data.SettingsRepository import com.nextcloud.talk.users.UserManager import com.nextcloud.talk.utils.preferences.AppPreferences import com.nextcloud.talk.utils.singletons.ApplicationWideMessageHolder +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -31,11 +31,11 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeoutOrNull import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse @@ -43,15 +43,13 @@ import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test -import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.stub import org.mockito.kotlin.timeout import org.mockito.kotlin.verify -import org.mockito.kotlin.whenever import java.io.IOException -import java.util.UUID @OptIn(ExperimentalCoroutinesApi::class) @Suppress("TooManyFunctions") @@ -77,6 +75,8 @@ class SettingsViewModelTest { private lateinit var workManager: WorkManager private lateinit var context: Context private val repository = FakeSettingsRepository() + private val accountRemover = mock() + private var deviceState = DEVICE_STATE @Before fun setUp() { @@ -84,14 +84,13 @@ class SettingsViewModelTest { appPreferences = mock { on { proxyType } doReturn NO_PROXY on { theme } doReturn "night_yes" - on { screenLockTimeout } doReturn "60" + on { screenLockTimeout } doReturn "30" on { showRegularNotificationWarning } doReturn true } userManager = mock { on { userFlow(USER_ID) } doReturn userFlow } userManager.stub { - onBlocking { scheduleUserForDeletionWithId(any()) } doReturn true onBlocking { getUsers() } doReturn listOf(user) } workManager = mock() @@ -103,6 +102,7 @@ class SettingsViewModelTest { on { getString(R.string.nc_no_proxy) } doReturn NO_PROXY on { getString(R.string.nc_settings_http_value) } doReturn "3128" on { getString(R.string.nc_settings_socks_value) } doReturn "1080" + on { getString(R.string.nc_screen_lock_timeout_sixty) } doReturn "60" } } @@ -121,7 +121,8 @@ class SettingsViewModelTest { userManager = userManager, settingsRepository = repository, logsRepository = logsRepository, - deviceStateReader = mock { on { read() } doReturn DEVICE_STATE }, + deviceStateReader = mock { on { read() } doAnswer { deviceState } }, + accountRemover = accountRemover, workManager = workManager, logger = mock(), networkMonitor = networkMonitor, @@ -140,7 +141,7 @@ class SettingsViewModelTest { val state = createViewModel(highlightNotificationIssues = true).uiState.value assertEquals("night_yes", state.appearance.theme) - assertEquals("60", state.privacy.screenLockTimeout) + assertEquals("30", state.privacy.screenLockTimeout) assertTrue(state.notifications.showNotificationWarning) assertEquals("Jane", state.account.displayName) assertTrue(state.privacy.readStatusAvailable) @@ -186,7 +187,7 @@ class SettingsViewModelTest { viewModel.setProxyType("HTTP") - assertEquals(ProxyUiState(type = "HTTP", port = "3128"), viewModel.uiState.value.proxy) + assertEquals(ProxyUiState(type = "HTTP", enabled = true, port = "3128"), viewModel.uiState.value.proxy) verify(appPreferences, timeout(TIMEOUT_MS)).proxyPort = "3128" } @@ -274,16 +275,16 @@ class SettingsViewModelTest { } @Test - fun `removed account is reported once the removal finished`() = + fun `screen stays open while its account is removed`() = runTest(dispatcher) { - val workInfo = WorkInfo(UUID.randomUUID(), WorkInfo.State.SUCCEEDED, emptySet()) - whenever(workManager.getWorkInfoByIdFlow(any())).thenReturn(flowOf(workInfo)) val viewModel = createViewModel() viewModel.removeAccount() userFlow.value = user.copy(scheduledForDeletion = true) + userFlow.value = null - assertEquals(SettingsEvent.AccountRemoved("Jane"), viewModel.events.first()) + verify(accountRemover).remove(USER_ID, "Jane") + assertNull(withTimeoutOrNull(TIMEOUT_MS) { viewModel.events.first() }) } @Test @@ -310,6 +311,71 @@ class SettingsViewModelTest { assertNull(viewModel.uiState.value.accountMessage) } + @Test + fun `selecting the current proxy type again keeps a custom port`() { + val viewModel = createViewModel() + viewModel.setProxyType("HTTP") + viewModel.setProxyPort("8888") + + viewModel.setProxyType("HTTP") + + assertEquals("8888", viewModel.uiState.value.proxy.port) + } + + @Test + fun `proxy text committed after the proxy was turned off is ignored`() { + val viewModel = createViewModel() + viewModel.setProxyType("HTTP") + viewModel.setProxyType(NO_PROXY) + + viewModel.setProxyHost("proxy.example.com") + + assertEquals("", viewModel.uiState.value.proxy.host) + } + + @Test + fun `failed quick read status changes show the value the server confirmed`() { + val viewModel = createViewModel() + val gate = CompletableDeferred() + repository.gate = gate + repository.failPrivacyRequests = true + + viewModel.setReadStatusShared(false) + viewModel.setReadStatusShared(true) + viewModel.setReadStatusShared(false) + gate.complete(Unit) + + assertTrue(viewModel.uiState.value.privacy.readStatusShared) + assertEquals(listOf(false), repository.readStatusRequests) + } + + @Test + fun `quick read status changes reach the server in order`() { + val viewModel = createViewModel() + val gate = CompletableDeferred() + repository.gate = gate + + viewModel.setReadStatusShared(false) + viewModel.setReadStatusShared(true) + gate.complete(Unit) + + assertTrue(viewModel.uiState.value.privacy.readStatusShared) + assertEquals(listOf(false, true), repository.readStatusRequests) + } + + @Test + fun `screen lock timeout is reset when the device lock screen is not secure`() { + deviceState = DEVICE_STATE.copy(isKeyguardSecure = false) + val viewModel = createViewModel() + + viewModel.onResume() + + val privacy = viewModel.uiState.value.privacy + assertFalse(privacy.screenLockAvailable) + assertFalse(privacy.screenLock) + assertEquals("60", privacy.screenLockTimeout) + } + private fun capabilities(readStatusPrivate: Boolean) = CapabilitiesDto().apply { spreedCapability = SpreedCapabilityDto( @@ -323,6 +389,7 @@ class SettingsViewModelTest { var profile: UserProfileDataDto? = null var acceptPhoneNumber = true var failPrivacyRequests = false + var gate: CompletableDeferred? = null val readStatusRequests = mutableListOf() override suspend fun getUserProfile(user: User): UserProfileDataDto? = profile @@ -331,6 +398,7 @@ class SettingsViewModelTest { override suspend fun setReadStatusShared(user: User, shared: Boolean) { readStatusRequests += shared + gate?.await() if (failPrivacyRequests) throw IOException("rejected") } From 4bad642534d67ab330b72a9c5f92dfcca8d09d37 Mon Sep 17 00:00:00 2001 From: Marcel Hibbe Date: Mon, 16 Nov 2026 23:13:36 +0100 Subject: [PATCH 3/5] fix(settings): address second review of the Compose migration - Ignore a cancelled client certificate choice instead of erasing the stored certificate - Send read and typing status changes in the application scope, so closing the screen doesn't cancel them, and sync the capabilities after a successful change - Show the account message above the list, so it is shown and consumed also when the screen opens scrolled to the notification settings - Store "No proxy" as the literal RestModule expects and treat the translated label stored by older versions as no proxy - Show snackbars in their own coroutine, so later events don't wait - Consume the account message outside of the state update - Reuse User.getCredentials() - Inject the I/O dispatcher, so tests control preference writes Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marcel Hibbe --- .../talk/dagger/modules/IoDispatcher.kt | 14 ++++ .../talk/dagger/modules/UtilsModule.kt | 5 ++ .../talk/settings/SettingsActivity.kt | 7 +- .../talk/settings/SettingsUiState.kt | 17 +++- .../talk/settings/SettingsViewModel.kt | 57 +++++++------ .../settings/data/SettingsRepositoryImpl.kt | 10 +-- .../settings/ui/SettingsAccountSection.kt | 26 +++--- .../talk/settings/ui/SettingsProxySection.kt | 8 +- .../talk/settings/ui/SettingsScreen.kt | 53 ++++++++---- .../talk/settings/SettingsViewModelTest.kt | 80 ++++++++++++++++--- 10 files changed, 200 insertions(+), 77 deletions(-) create mode 100644 app/src/main/java/com/nextcloud/talk/dagger/modules/IoDispatcher.kt diff --git a/app/src/main/java/com/nextcloud/talk/dagger/modules/IoDispatcher.kt b/app/src/main/java/com/nextcloud/talk/dagger/modules/IoDispatcher.kt new file mode 100644 index 00000000000..681394cc25a --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/dagger/modules/IoDispatcher.kt @@ -0,0 +1,14 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.dagger.modules + +import javax.inject.Qualifier + +/** The dispatcher for blocking I/O, replaceable in tests. */ +@Qualifier +@Retention(AnnotationRetention.BINARY) +annotation class IoDispatcher diff --git a/app/src/main/java/com/nextcloud/talk/dagger/modules/UtilsModule.kt b/app/src/main/java/com/nextcloud/talk/dagger/modules/UtilsModule.kt index ee7a87c1326..b7df8894599 100644 --- a/app/src/main/java/com/nextcloud/talk/dagger/modules/UtilsModule.kt +++ b/app/src/main/java/com/nextcloud/talk/dagger/modules/UtilsModule.kt @@ -23,6 +23,7 @@ import dagger.Provides import dagger.Reusable import java.io.File import javax.inject.Singleton +import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob @@ -77,4 +78,8 @@ class UtilsModule { @Singleton @ApplicationScope fun provideApplicationScope(): CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + @Provides + @IoDispatcher + fun provideIoDispatcher(): CoroutineDispatcher = Dispatchers.IO } 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 88d2776641d..088e53e6eb7 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt @@ -203,9 +203,12 @@ class SettingsActivity : BaseActivity() { } } - private suspend fun handleEvent(event: SettingsEvent) { + private fun handleEvent(event: SettingsEvent) { when (event) { - is SettingsEvent.ShowMessage -> snackbarHostState.showSnackbar(getString(event.messageRes)) + // shown in its own coroutine, so that later events don't wait until the snackbar is gone + is SettingsEvent.ShowMessage -> lifecycleScope.launch { + snackbarHostState.showSnackbar(getString(event.messageRes)) + } SettingsEvent.AccountUnavailable -> finish() } } 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 7cfecb5e143..eb060b40398 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt @@ -128,8 +128,8 @@ enum class LoggingStatus { @Immutable data class ProxyUiState( - /** One of `R.array.proxy_type_descriptions`. */ - val type: String = "", + /** [NO_PROXY] or one of [PROXY_TYPES]. */ + val type: String = NO_PROXY, /** Whether [type] is a proxy, not "No proxy". */ val enabled: Boolean = false, val host: String = "", @@ -137,7 +137,18 @@ data class ProxyUiState( val useCredentials: Boolean = false, val username: String = "", val password: String = "" -) +) { + companion object { + /** The stored type without a proxy, as `RestModule` expects it. */ + const val NO_PROXY = "No proxy" + const val TYPE_HTTP = "HTTP" + const val TYPE_DIRECT = "DIRECT" + const val TYPE_SOCKS = "SOCKS" + + /** The names of the `java.net.Proxy.Type` values that can be chosen. */ + val PROXY_TYPES = listOf(TYPE_HTTP, TYPE_DIRECT, TYPE_SOCKS) + } +} /** One-off effects of the settings screen that the activity performs. */ sealed interface SettingsEvent { 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 cf74db39607..b276561cbf7 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt @@ -8,7 +8,6 @@ package com.nextcloud.talk.settings import android.annotation.SuppressLint import android.content.Context -import androidx.annotation.VisibleForTesting import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.work.OneTimeWorkRequest @@ -16,6 +15,7 @@ import androidx.work.WorkManager import com.nextcloud.talk.R import com.nextcloud.talk.conversationlist.ConversationsListActivity.Companion.NOTIFICATION_WARNING_DATE_NOT_SET import com.nextcloud.talk.dagger.modules.ApplicationScope +import com.nextcloud.talk.dagger.modules.IoDispatcher import com.nextcloud.talk.data.network.NetworkMonitor import com.nextcloud.talk.data.user.model.User import com.nextcloud.talk.jobs.CapabilitiesSyncWorker @@ -25,7 +25,6 @@ import com.nextcloud.talk.logger.Logger import com.nextcloud.talk.logger.LogsRepository import com.nextcloud.talk.settings.data.SettingsRepository import com.nextcloud.talk.users.UserManager -import com.nextcloud.talk.utils.ApiUtils import com.nextcloud.talk.utils.CapabilitiesUtil import com.nextcloud.talk.utils.SecurityUtils import com.nextcloud.talk.utils.SpreedFeatures @@ -65,21 +64,18 @@ class SettingsViewModel @AssistedInject constructor( private val logger: Logger, networkMonitor: NetworkMonitor, @ApplicationScope private val appScope: CoroutineScope, + @IoDispatcher private val ioDispatcher: CoroutineDispatcher, // Dagger provides the application context, which cannot leak an Activity @field:SuppressLint("StaticFieldLeak") private val context: Context, @Assisted initialUser: User, @Assisted highlightNotificationIssues: Boolean ) : ViewModel() { - @VisibleForTesting - internal var ioDispatcher: CoroutineDispatcher = Dispatchers.IO - // preferences are written in the order they were changed, and also after the screen was closed - private val preferenceWriter by lazy { ioDispatcher.limitedParallelism(1) } + private val preferenceWriter = ioDispatcher.limitedParallelism(1) private val userId = initialUser.id!! private val user = MutableStateFlow(initialUser) - private val noProxy = context.getString(R.string.nc_no_proxy) // The last values in the stored account, which are only updated with the capabilities. A change is shown until // they change, so that an update of e.g. the display name doesn't revert it. @@ -134,9 +130,18 @@ class SettingsViewModel @AssistedInject constructor( /** Refreshes everything that may have changed while the screen was in the background. */ fun onResume() { - _uiState.update { it.copy(loggingStatus = loggingStatus(), accountMessage = consumeAccountMessage()) } + val accountMessage = consumeAccountMessage() + val loggingStatus = loggingStatus() + _uiState.update { + it.copy(loggingStatus = loggingStatus, accountMessage = accountMessage ?: it.accountMessage) + } refreshDeviceState() refreshUserProfile() + syncCapabilities() + } + + /** Loads the capabilities of the account anew, which updates [user] through the stored account. */ + private fun syncCapabilities() { workManager.enqueue( OneTimeWorkRequest.Builder(CapabilitiesSyncWorker::class.java).setExpeditedIfSupported().build() ) @@ -331,19 +336,20 @@ class SettingsViewModel @AssistedInject constructor( persist { prefs -> prefs.setCompressUploadImages(reduced) } } - /** Stores the alias of the chosen client certificate, or removes it if [alias] is null. */ + /** Stores the alias of the chosen client certificate. A null [alias] means the choice was cancelled. */ fun onClientCertificateChosen(alias: String?) { - _uiState.update { it.copy(clientCertificateSet = alias != null) } + if (alias == null) return + _uiState.update { it.copy(clientCertificateSet = true) } viewModelScope.launch { - userManager.updateClientCertificate(userId, alias.orEmpty()) + userManager.updateClientCertificate(userId, alias) } } fun setProxyType(type: String) { if (type == _uiState.value.proxy.type) return if (!isProxyEnabled(type)) { - _uiState.update { it.copy(proxy = ProxyUiState(type = type)) } - persist { prefs -> prefs.proxyType = type } + _uiState.update { it.copy(proxy = ProxyUiState(type = ProxyUiState.NO_PROXY)) } + persist { prefs -> prefs.proxyType = ProxyUiState.NO_PROXY } clearProxySettings() return } @@ -406,7 +412,8 @@ class SettingsViewModel @AssistedInject constructor( } private fun initialState(initialUser: User, highlightNotificationIssues: Boolean): SettingsUiState { - val proxyType = appPreferences.proxyType.ifEmpty { noProxy } + // older versions stored the translated label of "No proxy" + val proxyType = appPreferences.proxyType.takeIf(::isProxyEnabled) ?: ProxyUiState.NO_PROXY val useCredentials = isProxyEnabled(proxyType) && appPreferences.proxyCredentials return SettingsUiState( account = accountState(initialUser), @@ -488,7 +495,7 @@ class SettingsViewModel @AssistedInject constructor( displayName = currentUser.displayName.orEmpty(), baseUrl = currentUser.baseUrl.orEmpty(), avatarId = currentUser.userId?.takeIf { it.isNotEmpty() } ?: currentUser.username.orEmpty(), - credentials = ApiUtils.getCredentials(currentUser.username, currentUser.token).orEmpty(), + credentials = currentUser.getCredentials(), serverAgeWarning = when { CapabilitiesUtil.isServerEOL(serverVersion) -> ServerAgeWarning.END_OF_LIFE CapabilitiesUtil.isServerAlmostEOL(serverVersion) -> ServerAgeWarning.ALMOST_END_OF_LIFE @@ -543,7 +550,9 @@ class SettingsViewModel @AssistedInject constructor( /** * Shows [shared] right away and sends it to the server. Requests are sent one at a time, a change replaced by a - * newer one is skipped, and a failed change shows the value the server confirmed last. + * newer one is skipped, and a failed change shows the value the server confirmed last. They run in the application + * scope, so that closing the screen doesn't cancel a change it already shows, and on the main thread, which + * [setting] is confined to. */ private fun updatePrivacySetting( setting: ServerSetting, @@ -553,12 +562,13 @@ class SettingsViewModel @AssistedInject constructor( ) { setting.requested = shared _uiState.update { it.copy(privacy = apply(it.privacy, shared)) } - viewModelScope.launch { + appScope.launch(Dispatchers.Main.immediate) { setting.mutex.withLock { if (setting.requested != shared || setting.confirmed == shared) return@withLock try { request(shared) setting.confirmed = shared + syncCapabilities() } catch (e: IOException) { logger.e(TAG, "Failed to change a privacy setting", e) revertPrivacySetting(setting, apply, shared) @@ -603,7 +613,7 @@ class SettingsViewModel @AssistedInject constructor( else -> null } holder.messageType = null - return message ?: _uiState.value.accountMessage + return message } private fun refreshUserProfile() { @@ -625,13 +635,13 @@ class SettingsViewModel @AssistedInject constructor( } } - private fun isProxyEnabled(type: String): Boolean = type.isNotEmpty() && type != noProxy + private fun isProxyEnabled(type: String): Boolean = type in ProxyUiState.PROXY_TYPES private fun defaultProxyPort(type: String): String? = when (type) { - PROXY_TYPE_HTTP -> context.getString(R.string.nc_settings_http_value) - PROXY_TYPE_DIRECT -> context.getString(R.string.nc_settings_direct_value) - PROXY_TYPE_SOCKS -> context.getString(R.string.nc_settings_socks_value) + ProxyUiState.TYPE_HTTP -> context.getString(R.string.nc_settings_http_value) + ProxyUiState.TYPE_DIRECT -> context.getString(R.string.nc_settings_direct_value) + ProxyUiState.TYPE_SOCKS -> context.getString(R.string.nc_settings_socks_value) else -> null } @@ -667,9 +677,6 @@ class SettingsViewModel @AssistedInject constructor( companion object { private val TAG = SettingsViewModel::class.java.simpleName - private const val PROXY_TYPE_HTTP = "HTTP" - private const val PROXY_TYPE_DIRECT = "DIRECT" - private const val PROXY_TYPE_SOCKS = "SOCKS" } } diff --git a/app/src/main/java/com/nextcloud/talk/settings/data/SettingsRepositoryImpl.kt b/app/src/main/java/com/nextcloud/talk/settings/data/SettingsRepositoryImpl.kt index 7b3e046b310..2980d9071c7 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/data/SettingsRepositoryImpl.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/data/SettingsRepositoryImpl.kt @@ -20,13 +20,13 @@ class SettingsRepositoryImpl @Inject constructor(private val ncApiCoroutines: Nc override suspend fun getUserProfile(user: User): UserProfileDataDto? = ncApiCoroutines.getUserProfile( - user.credentials(), + user.getCredentials(), ApiUtils.getUrlForUserProfile(user.baseUrl!!) ).ocs?.data override suspend fun setPhoneNumber(user: User, phoneNumber: String): Boolean { val response = ncApiCoroutines.setUserData( - user.credentials(), + user.getCredentials(), ApiUtils.getUrlForUserData(user.baseUrl!!, user.userId!!), KEY_PHONE, phoneNumber @@ -36,7 +36,7 @@ class SettingsRepositoryImpl @Inject constructor(private val ncApiCoroutines: Nc override suspend fun setReadStatusShared(user: User, shared: Boolean) { ncApiCoroutines.setReadStatusPrivacy( - user.credentials(), + user.getCredentials(), ApiUtils.getUrlForUserSettings(user.baseUrl!!), privacySettingBody(KEY_READ_STATUS_PRIVACY, shared) ) @@ -44,14 +44,12 @@ class SettingsRepositoryImpl @Inject constructor(private val ncApiCoroutines: Nc override suspend fun setTypingStatusShared(user: User, shared: Boolean) { ncApiCoroutines.setTypingStatusPrivacy( - user.credentials(), + user.getCredentials(), ApiUtils.getUrlForUserSettings(user.baseUrl!!), privacySettingBody(KEY_TYPING_PRIVACY, shared) ) } - private fun User.credentials(): String = ApiUtils.getCredentials(username, token).orEmpty() - /** The server expects 0 for public and 1 for private. */ private fun privacySettingBody(key: String, shared: Boolean): RequestBody = JSONObject() diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsAccountSection.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsAccountSection.kt index 1ef436a2ad8..a553e442fa9 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsAccountSection.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsAccountSection.kt @@ -10,6 +10,7 @@ import android.content.res.Configuration import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.tween import androidx.compose.animation.fadeOut +import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.clickable import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Column @@ -52,7 +53,6 @@ import com.nextcloud.talk.R import com.nextcloud.talk.settings.AccountMessage import com.nextcloud.talk.settings.AccountUiState import com.nextcloud.talk.settings.ServerAgeWarning -import com.nextcloud.talk.settings.SettingsUiState import com.nextcloud.talk.utils.ApiUtils import kotlinx.coroutines.delay @@ -60,13 +60,12 @@ private const val ACCOUNT_MESSAGE_DURATION_MS = 5000L private const val ACCOUNT_MESSAGE_FADE_OUT_MS = 2500 @Composable -internal fun AccountSection(state: SettingsUiState, callbacks: SettingsScreenCallbacks) { +internal fun AccountSection(account: AccountUiState, callbacks: SettingsScreenCallbacks) { var showRemoveAccountDialog by rememberSaveable { mutableStateOf(false) } Column { - AccountMessageBanner(message = state.accountMessage, onShown = callbacks.onAccountMessageShown) - AccountHeader(account = state.account, onClick = callbacks.onProfileClick) - if (state.account.serverAgeWarning != ServerAgeWarning.NONE) { - ServerAgeWarningCard(state.account.serverAgeWarning) + AccountHeader(account = account, onClick = callbacks.onProfileClick) + if (account.serverAgeWarning != ServerAgeWarning.NONE) { + ServerAgeWarningCard(account.serverAgeWarning) } Text( text = stringResource(R.string.nc_settings_remove_account), @@ -91,7 +90,7 @@ internal fun AccountSection(state: SettingsUiState, callbacks: SettingsScreenCal /** Shows [message] for a while and fades it out, then reports it as shown. */ @Composable -private fun AccountMessageBanner(message: AccountMessage?, onShown: () -> Unit) { +internal fun AccountMessageBanner(message: AccountMessage?, onShown: () -> Unit) { var visible by remember(message) { mutableStateOf(message != null) } LaunchedEffect(message) { if (message != null) { @@ -101,7 +100,10 @@ private fun AccountMessageBanner(message: AccountMessage?, onShown: () -> Unit) onShown() } } - AnimatedVisibility(visible = visible, exit = fadeOut(tween(ACCOUNT_MESSAGE_FADE_OUT_MS))) { + AnimatedVisibility( + visible = visible, + exit = fadeOut(tween(ACCOUNT_MESSAGE_FADE_OUT_MS)) + shrinkVertically(tween(ACCOUNT_MESSAGE_FADE_OUT_MS)) + ) { val (text, color) = when (message) { AccountMessage.ACCOUNT_UPDATED -> stringResource(R.string.nc_settings_account_updated) to MaterialTheme.colorScheme.primary @@ -208,10 +210,10 @@ private val avatarSize = 96.dp private fun AccountSectionPreview() { MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) { Surface { - AccountSection( - state = previewSettingsState().copy(accountMessage = AccountMessage.ACCOUNT_IMPORTED), - callbacks = SettingsScreenCallbacks() - ) + Column { + AccountMessageBanner(message = AccountMessage.ACCOUNT_IMPORTED, onShown = {}) + AccountSection(account = previewSettingsState().account, callbacks = SettingsScreenCallbacks()) + } } } } diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsProxySection.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsProxySection.kt index e7f3e61d1ac..3eb1bdf015d 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsProxySection.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsProxySection.kt @@ -22,6 +22,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue @@ -42,11 +43,14 @@ import com.nextcloud.talk.settings.ProxyUiState @Composable internal fun ProxySettings(state: ProxyUiState, callbacks: ProxyCallbacks) { - val proxyTypes = stringArrayResource(R.array.proxy_type_descriptions) + val proxyTypeLabels = stringArrayResource(R.array.proxy_type_descriptions) + val options = remember(proxyTypeLabels) { + (listOf(ProxyUiState.NO_PROXY) + ProxyUiState.PROXY_TYPES).zip(proxyTypeLabels) + } Column { SettingsDropdown( label = stringResource(R.string.nc_settings_proxy_type_title), - options = proxyTypes.map { it to it }, + options = options, selectedValue = state.type, onValueSelected = callbacks.onTypeChange ) 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 49472ffadc8..29401b7a955 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 @@ -9,10 +9,12 @@ package com.nextcloud.talk.settings.ui import android.content.res.Configuration import androidx.compose.foundation.background import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.displayCutoutPadding import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.statusBarsPadding @@ -146,9 +148,8 @@ private fun SettingsContent(state: SettingsUiState, callbacks: SettingsScreenCal scrolledToNotifications = true } } - LazyColumn( - state = listState, - contentPadding = PaddingValues(bottom = 48.dp), + // outside of the list, so that it is shown and consumed also when the list starts scrolled down + Column( modifier = Modifier .fillMaxSize() .background(colorResource(R.color.bg_default)) @@ -156,25 +157,43 @@ private fun SettingsContent(state: SettingsUiState, callbacks: SettingsScreenCal .consumeWindowInsets(paddingValues) .imePadding() ) { - items(SettingsSection.entries, key = { it }) { section -> - when (section) { - SettingsSection.ACCOUNT -> AccountSection(state, callbacks) - SettingsSection.APPEARANCE -> AppearanceSection(state.appearance, callbacks) - SettingsSection.NOTIFICATIONS -> NotificationsSection( - state = state.notifications, - baseUrl = state.account.baseUrl, - highlightIssues = state.highlightNotificationIssues, - callbacks = callbacks - ) - SettingsSection.PRIVACY -> PrivacySection(state.privacy, callbacks) - SettingsSection.DIAGNOSIS -> DiagnosisSection(state.loggingStatus, callbacks) - SettingsSection.ADVANCED -> AdvancedSection(state, callbacks) - SettingsSection.ABOUT -> AboutSection(state.isOnline, callbacks) + AccountMessageBanner(message = state.accountMessage, onShown = callbacks.onAccountMessageShown) + LazyColumn( + state = listState, + contentPadding = PaddingValues(bottom = 48.dp), + modifier = Modifier + .fillMaxWidth() + .weight(1f) + ) { + items(SettingsSection.entries, key = { it }) { section -> + SettingsSectionContent(section, state, callbacks) } } } } +@Composable +private fun SettingsSectionContent( + section: SettingsSection, + state: SettingsUiState, + callbacks: SettingsScreenCallbacks +) { + when (section) { + SettingsSection.ACCOUNT -> AccountSection(state.account, callbacks) + SettingsSection.APPEARANCE -> AppearanceSection(state.appearance, callbacks) + SettingsSection.NOTIFICATIONS -> NotificationsSection( + state = state.notifications, + baseUrl = state.account.baseUrl, + highlightIssues = state.highlightNotificationIssues, + callbacks = callbacks + ) + SettingsSection.PRIVACY -> PrivacySection(state.privacy, callbacks) + SettingsSection.DIAGNOSIS -> DiagnosisSection(state.loggingStatus, callbacks) + SettingsSection.ADVANCED -> AdvancedSection(state, callbacks) + SettingsSection.ABOUT -> AboutSection(state.isOnline, callbacks) + } +} + internal fun previewSettingsState(): SettingsUiState = SettingsUiState( isOnline = true, 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 f9f024eee89..de3f9ce826d 100644 --- a/app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt +++ b/app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt @@ -31,6 +31,7 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest @@ -43,11 +44,16 @@ import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.stub -import org.mockito.kotlin.timeout +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verifyBlocking +import org.mockito.kotlin.whenever import org.mockito.kotlin.verify import java.io.IOException @@ -56,6 +62,7 @@ import java.io.IOException class SettingsViewModelTest { private val dispatcher = UnconfinedTestDispatcher() + private val ioDispatcher = StandardTestDispatcher(dispatcher.scheduler) private val viewModelStore = ViewModelStore() private val appScope = CoroutineScope(SupervisorJob()) @@ -113,7 +120,10 @@ class SettingsViewModelTest { Dispatchers.resetMain() } - private fun createViewModel(highlightNotificationIssues: Boolean = false): SettingsViewModel { + private fun createViewModel( + initialUser: User = user, + highlightNotificationIssues: Boolean = false + ): SettingsViewModel { val networkMonitor = mock { on { isOnline } doReturn MutableStateFlow(true) } val logsRepository = mock { on { minimumLevel } doReturn Level.INFO } return SettingsViewModel( @@ -127,13 +137,11 @@ class SettingsViewModelTest { logger = mock(), networkMonitor = networkMonitor, appScope = appScope, + ioDispatcher = ioDispatcher, context = context, - initialUser = user, + initialUser = initialUser, highlightNotificationIssues = highlightNotificationIssues - ).also { - it.ioDispatcher = dispatcher - viewModelStore.put("settings", it) - } + ).also { viewModelStore.put("settings", it) } } @Test @@ -188,7 +196,8 @@ class SettingsViewModelTest { viewModel.setProxyType("HTTP") assertEquals(ProxyUiState(type = "HTTP", enabled = true, port = "3128"), viewModel.uiState.value.proxy) - verify(appPreferences, timeout(TIMEOUT_MS)).proxyPort = "3128" + dispatcher.scheduler.advanceUntilIdle() + verify(appPreferences).proxyPort = "3128" } @Test @@ -203,8 +212,9 @@ class SettingsViewModelTest { assertEquals(ProxyUiState(type = NO_PROXY), viewModel.uiState.value.proxy) // also cleared once on creation, as the proxy was off - verify(appPreferences, timeout(TIMEOUT_MS).times(2)).removeProxyHost() - verify(appPreferences, timeout(TIMEOUT_MS).times(2)).removeProxyUsername() + dispatcher.scheduler.advanceUntilIdle() + verify(appPreferences, times(2)).removeProxyHost() + verify(appPreferences, times(2)).removeProxyUsername() } @Test @@ -369,6 +379,7 @@ class SettingsViewModelTest { val viewModel = createViewModel() viewModel.onResume() + dispatcher.scheduler.advanceUntilIdle() val privacy = viewModel.uiState.value.privacy assertFalse(privacy.screenLockAvailable) @@ -376,6 +387,53 @@ class SettingsViewModelTest { assertEquals("60", privacy.screenLockTimeout) } + @Test + fun `cancelled certificate choice keeps the stored certificate`() { + val viewModel = createViewModel(user.copy(clientCertificate = "alias")) + + viewModel.onClientCertificateChosen(null) + + assertTrue(viewModel.uiState.value.clientCertificateSet) + verifyBlocking(userManager, never()) { updateClientCertificate(any(), anyOrNull()) } + } + + @Test + fun `read status change is still sent after the screen was closed`() { + val viewModel = createViewModel() + val gate = CompletableDeferred() + repository.gate = gate + + viewModel.setReadStatusShared(false) + viewModelStore.clear() + gate.complete(Unit) + + assertEquals(listOf(false), repository.completedReadStatusRequests) + } + + @Test + fun `translated label of no proxy stored by older versions means no proxy`() { + whenever(appPreferences.proxyType).thenReturn("Kein Proxy") + + val viewModel = createViewModel() + dispatcher.scheduler.advanceUntilIdle() + + assertEquals(ProxyUiState(), viewModel.uiState.value.proxy) + verify(appPreferences).removeProxyHost() + } + + @Test + fun `pending account message is kept when the screen is resumed again`() { + val viewModel = createViewModel() + ApplicationWideMessageHolder.getInstance().messageType = + ApplicationWideMessageHolder.MessageType.ACCOUNT_WAS_IMPORTED + + viewModel.onResume() + viewModel.onResume() + + assertEquals(AccountMessage.ACCOUNT_IMPORTED, viewModel.uiState.value.accountMessage) + assertNull(ApplicationWideMessageHolder.getInstance().messageType) + } + private fun capabilities(readStatusPrivate: Boolean) = CapabilitiesDto().apply { spreedCapability = SpreedCapabilityDto( @@ -391,6 +449,7 @@ class SettingsViewModelTest { var failPrivacyRequests = false var gate: CompletableDeferred? = null val readStatusRequests = mutableListOf() + val completedReadStatusRequests = mutableListOf() override suspend fun getUserProfile(user: User): UserProfileDataDto? = profile @@ -400,6 +459,7 @@ class SettingsViewModelTest { readStatusRequests += shared gate?.await() if (failPrivacyRequests) throw IOException("rejected") + completedReadStatusRequests += shared } override suspend fun setTypingStatusShared(user: User, shared: Boolean) { From 613aca429e24a6543029a9db208a1d6211dc16ff Mon Sep 17 00:00:00 2001 From: Marcel Hibbe Date: Mon, 16 Nov 2026 23:42:40 +0100 Subject: [PATCH 4/5] fix(settings): add a cancel button to the media quality dialog The dialog had no buttons, which left an empty button row at its bottom. Selecting an option still applies it right away. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marcel Hibbe --- .../java/com/nextcloud/talk/settings/ui/SettingsDialogs.kt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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 424c0dcaffd..19bf9f92dbe 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 @@ -126,7 +126,10 @@ internal fun MediaQualityDialog(reducedQuality: Boolean, onSelect: (Boolean) -> ) } }, - confirmButton = {} + // selecting an option applies it, so the only button cancels + confirmButton = { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.nc_cancel)) } + } ) } From 458cbfb6e7c673f83c2c4fc68af8d69685aa39f1 Mon Sep 17 00:00:00 2001 From: Marcel Hibbe Date: Tue, 17 Nov 2026 11:07:39 +0100 Subject: [PATCH 5/5] fix(conversation-list): apply a changed app switcher setting The setting was read once when the screen was composed, so turning the app switcher on or off in the settings only took effect after a restart of the app. It is now read again on resume and observed by the screen, like the notification warning. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marcel Hibbe --- .../talk/conversationlist/ConversationsListActivity.kt | 6 +++++- .../talk/conversationlist/ui/ConversationsListScreen.kt | 5 +++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/nextcloud/talk/conversationlist/ConversationsListActivity.kt b/app/src/main/java/com/nextcloud/talk/conversationlist/ConversationsListActivity.kt index da01d75f791..d5d62885bf6 100644 --- a/app/src/main/java/com/nextcloud/talk/conversationlist/ConversationsListActivity.kt +++ b/app/src/main/java/com/nextcloud/talk/conversationlist/ConversationsListActivity.kt @@ -216,6 +216,7 @@ class ConversationsListActivity : BaseActivity() { private val showUnreadBubbleState = MutableStateFlow(false) private val isFabVisibleState = MutableStateFlow(true) private val showNotificationWarningState = MutableStateFlow(false) + private val showEcosystemState = MutableStateFlow(false) private val isRefreshingState = MutableStateFlow(false) private val showAccountDialogState = MutableStateFlow(false) @@ -461,7 +462,7 @@ class ConversationsListActivity : BaseActivity() { credentials = credentials ?: "", showLogo = BrandingUtils.isOriginalNextcloudClient(applicationContext), viewThemeUtils = viewThemeUtils, - isShowEcosystem = appPreferences.isShowEcosystem && !resources.getBoolean(R.bool.is_branded_client), + showEcosystemFlow = showEcosystemState, snackbarHostState = snackbarHostState, isMaintenanceModeFlow = isMaintenanceModeState, isOnlineFlow = networkMonitor.isOnline, @@ -646,6 +647,9 @@ class ConversationsListActivity : BaseActivity() { } showNotificationWarningState.value = shouldShowNotificationWarning() + // may have been changed in the settings meanwhile + val isBrandedClient = resources.getBoolean(R.bool.is_branded_client) + showEcosystemState.value = appPreferences.isShowEcosystem && !isBrandedClient showShareToScreenState.value = isShare(intent) takeConversationOfShortcut() diff --git a/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationsListScreen.kt b/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationsListScreen.kt index 0a31f8b90e3..1338baf858a 100644 --- a/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationsListScreen.kt +++ b/app/src/main/java/com/nextcloud/talk/conversationlist/ui/ConversationsListScreen.kt @@ -80,7 +80,7 @@ data class ConversationsListScreenState( val credentials: String, val showLogo: Boolean, val viewThemeUtils: ViewThemeUtils, - val isShowEcosystem: Boolean, + val showEcosystemFlow: StateFlow, val snackbarHostState: SnackbarHostState, val isMaintenanceModeFlow: StateFlow, val isOnlineFlow: StateFlow, @@ -168,6 +168,7 @@ fun ConversationsListScreen( val isForward by state.forwardMessageFlow.collectAsStateWithLifecycle() val hasMultipleAccounts by state.hasMultipleAccountsFlow.collectAsStateWithLifecycle() val showAccountDialog by state.showAccountDialogFlow.collectAsStateWithLifecycle() + val showEcosystem by state.showEcosystemFlow.collectAsStateWithLifecycle() val selectedConversationForOps by state.selectedConversationForOpsFlow.collectAsStateWithLifecycle() val opsSheetState = rememberModalBottomSheetState() @@ -405,7 +406,7 @@ fun ConversationsListScreen( LaunchedEffect(shouldDismiss.value) { if (shouldDismiss.value) callbacks.onAccountDialogDismiss() } - dialog.GetChooseAccountDialog(shouldDismiss, activity, state.isShowEcosystem) + dialog.GetChooseAccountDialog(shouldDismiss, activity, showEcosystem) } // Conversation-operations bottom sheet