diff --git a/.gitlab-ci-files/job-android.yml b/.gitlab-ci-files/job-android.yml index 3bb32bbf5..a66ce9e9f 100644 --- a/.gitlab-ci-files/job-android.yml +++ b/.gitlab-ci-files/job-android.yml @@ -2,15 +2,15 @@ job-android: stage: build tags: [ "docker-android" ] - image: gitlab.linphone.org:4567/bc/public/linphone-android/bc-dev-android:20220609_android_33 + image: gitlab.linphone.org:4567/bc/public/linphone-android/bc-dev-android:20230414_bullseye_jdk_17_cleaned before_script: - if ! [ -z ${SCP_PRIVATE_KEY+x} ]; then eval $(ssh-agent -s); fi - if ! [ -z ${SCP_PRIVATE_KEY+x} ]; then echo "$SCP_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null; fi - - echo "$ANDROID_SETTINGS_GRADLE" > settings.gradle + - if ! [ -z ${ANDROID_SETTINGS_GRADLE+x} ]; then echo "$ANDROID_SETTINGS_GRADLE" > settings.gradle; fi + - git config --global --add safe.directory /builds/BC/public/linphone-android script: - - sdkmanager - scp -oStrictHostKeyChecking=no $DEPLOY_SERVER:$ANDROID_KEYSTORE_PATH app/ - scp -oStrictHostKeyChecking=no $DEPLOY_SERVER:$ANDROID_GOOGLE_SERVICES_PATH app/ - echo storePassword=$ANDROID_KEYSTORE_PASSWORD > keystore.properties diff --git a/app/build.gradle b/app/build.gradle index 7f076c908..7ad1008fa 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -2,7 +2,7 @@ plugins { id 'com.android.application' id 'kotlin-android' id 'kotlin-kapt' - id 'org.jlleitschuh.gradle.ktlint' + id 'org.jlleitschuh.gradle.ktlint' version '11.3.1' id 'org.jetbrains.kotlin.android' } @@ -78,8 +78,12 @@ project.tasks['preBuild'].dependsOn 'getGitVersion' project.tasks['preBuild'].dependsOn 'linphoneSdkSource' android { + compileOptions { + sourceCompatibility = 17 + targetCompatibility = 17 + } + compileSdkVersion 33 - buildToolsVersion '33.0.0' defaultConfig { minSdkVersion 23 targetSdkVersion 33 @@ -228,7 +232,7 @@ dependencies { // https://github.com/Baseflow/PhotoView/blob/master/LICENSE Apache v2.0 implementation 'com.github.chrisbanes:PhotoView:2.3.0' - implementation platform('com.google.firebase:firebase-bom:31.2.3') + implementation platform('com.google.firebase:firebase-bom:31.5.0') if (crashlyticsAvailable) { debugImplementation 'com.google.firebase:firebase-crashlytics-ndk' releaseWithCrashlyticsImplementation 'com.google.firebase:firebase-crashlytics-ndk' diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index fab63497f..e70e74af6 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -22,3 +22,20 @@ -keep public class * extends androidx.fragment.app.Fragment { *; } -dontwarn com.google.errorprone.annotations.Immutable + +# To prevent following errors: +#ERROR: Missing classes detected while running R8. Please add the missing classes or apply additional keep rules that are generated in /builds/BC/public/linphone-android/app/build/outputs/mapping/release/missing_rules.txt. +#ERROR: R8: Missing class org.bouncycastle.jsse.BCSSLParameters (referenced from: void okhttp3.internal.platform.BouncyCastlePlatform.configureTlsExtensions(javax.net.ssl.SSLSocket, java.lang.String, java.util.List) and 1 other context) +#Missing class org.bouncycastle.jsse.BCSSLSocket (referenced from: void okhttp3.internal.platform.BouncyCastlePlatform.configureTlsExtensions(javax.net.ssl.SSLSocket, java.lang.String, java.util.List) and 5 other contexts) +#Missing class org.bouncycastle.jsse.provider.BouncyCastleJsseProvider (referenced from: void okhttp3.internal.platform.BouncyCastlePlatform.()) +#Missing class org.conscrypt.Conscrypt$Version (referenced from: boolean okhttp3.internal.platform.ConscryptPlatform$Companion.atLeastVersion(int, int, int)) +#Missing class org.conscrypt.Conscrypt (referenced from: boolean okhttp3.internal.platform.ConscryptPlatform$Companion.atLeastVersion(int, int, int) and 4 other contexts) +#Missing class org.conscrypt.ConscryptHostnameVerifier (referenced from: okhttp3.internal.platform.ConscryptPlatform$DisabledHostnameVerifier) +#Missing class org.openjsse.javax.net.ssl.SSLParameters (referenced from: void okhttp3.internal.platform.OpenJSSEPlatform.configureTlsExtensions(javax.net.ssl.SSLSocket, java.lang.String, java.util.List)) +#Missing class org.openjsse.javax.net.ssl.SSLSocket (referenced from: void okhttp3.internal.platform.OpenJSSEPlatform.configureTlsExtensions(javax.net.ssl.SSLSocket, java.lang.String, java.util.List) and 1 other context) +#Missing class org.openjsse.net.ssl.OpenJSSE (referenced from: void okhttp3.internal.platform.OpenJSSEPlatform.()) +#> Task :app:lintVitalAnalyzeRelease +#FAILURE: Build failed with an exception. +-dontwarn org.conscrypt.** +-dontwarn org.bouncycastle.** +-dontwarn org.openjsse.** \ No newline at end of file diff --git a/app/src/main/java/org/linphone/LinphoneApplication.kt b/app/src/main/java/org/linphone/LinphoneApplication.kt index 2d66cd129..87e435932 100644 --- a/app/src/main/java/org/linphone/LinphoneApplication.kt +++ b/app/src/main/java/org/linphone/LinphoneApplication.kt @@ -38,6 +38,7 @@ class LinphoneApplication : Application(), ImageLoaderFactory { companion object { @SuppressLint("StaticFieldLeak") lateinit var corePreferences: CorePreferences + @SuppressLint("StaticFieldLeak") lateinit var coreContext: CoreContext @@ -59,7 +60,10 @@ class LinphoneApplication : Application(), ImageLoaderFactory { CoreContext.activateVFS() } - val config = Factory.instance().createConfigWithFactory(corePreferences.configPath, corePreferences.factoryConfigPath) + val config = Factory.instance().createConfigWithFactory( + corePreferences.configPath, + corePreferences.factoryConfigPath + ) corePreferences.config = config val appName = context.getString(R.string.app_name) @@ -83,8 +87,15 @@ class LinphoneApplication : Application(), ImageLoaderFactory { return false } - Log.i("[Application] Core context is being created ${if (pushReceived) "from push" else ""}") - coreContext = CoreContext(context, corePreferences.config, service, useAutoStartDescription) + Log.i( + "[Application] Core context is being created ${if (pushReceived) "from push" else ""}" + ) + coreContext = CoreContext( + context, + corePreferences.config, + service, + useAutoStartDescription + ) coreContext.start() return true } diff --git a/app/src/main/java/org/linphone/activities/GenericFragment.kt b/app/src/main/java/org/linphone/activities/GenericFragment.kt index 5a2652a9c..0d1f89fc0 100644 --- a/app/src/main/java/org/linphone/activities/GenericFragment.kt +++ b/app/src/main/java/org/linphone/activities/GenericFragment.kt @@ -74,7 +74,9 @@ abstract class GenericFragment : Fragment() { if (!navController.popBackStack()) { Log.d("[Generic Fragment] ${getFragmentRealClassName()} couldn't pop") if (!navController.navigateUp()) { - Log.d("[Generic Fragment] ${getFragmentRealClassName()} couldn't navigate up") + Log.d( + "[Generic Fragment] ${getFragmentRealClassName()} couldn't navigate up" + ) // Disable this callback & start a new back press event isEnabled = false goBack() @@ -98,7 +100,9 @@ abstract class GenericFragment : Fragment() { } sharedViewModel.isSlidingPaneSlideable.observe(viewLifecycleOwner) { - Log.d("[Generic Fragment] ${getFragmentRealClassName()} shared main VM sliding pane has changed") + Log.d( + "[Generic Fragment] ${getFragmentRealClassName()} shared main VM sliding pane has changed" + ) onBackPressedCallback.isEnabled = backPressedCallBackEnabled() } @@ -151,7 +155,10 @@ abstract class GenericFragment : Fragment() { onBackPressedCallback.isEnabled = false } - requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, onBackPressedCallback) + requireActivity().onBackPressedDispatcher.addCallback( + viewLifecycleOwner, + onBackPressedCallback + ) } private fun backPressedCallBackEnabled(): Boolean { @@ -161,9 +168,13 @@ abstract class GenericFragment : Fragment() { if (findNavController().graph.id == R.id.main_nav_graph_xml) return false val isSlidingPaneFlat = sharedViewModel.isSlidingPaneSlideable.value == false - Log.d("[Generic Fragment] ${getFragmentRealClassName()} isSlidingPaneFlat ? $isSlidingPaneFlat") + Log.d( + "[Generic Fragment] ${getFragmentRealClassName()} isSlidingPaneFlat ? $isSlidingPaneFlat" + ) val isPreviousFragmentEmpty = findNavController().previousBackStackEntry?.destination?.id in emptyFragmentsIds - Log.d("[Generic Fragment] ${getFragmentRealClassName()} isPreviousFragmentEmpty ? $isPreviousFragmentEmpty") + Log.d( + "[Generic Fragment] ${getFragmentRealClassName()} isPreviousFragmentEmpty ? $isPreviousFragmentEmpty" + ) val popBackStack = isSlidingPaneFlat || !isPreviousFragmentEmpty Log.d("[Generic Fragment] ${getFragmentRealClassName()} popBackStack ? $popBackStack") return popBackStack diff --git a/app/src/main/java/org/linphone/activities/ProximitySensorActivity.kt b/app/src/main/java/org/linphone/activities/ProximitySensorActivity.kt index 10622685f..605af6df8 100644 --- a/app/src/main/java/org/linphone/activities/ProximitySensorActivity.kt +++ b/app/src/main/java/org/linphone/activities/ProximitySensorActivity.kt @@ -34,7 +34,9 @@ abstract class ProximitySensorActivity : GenericActivity() { val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager if (!powerManager.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) { - Log.w("[Proximity Sensor Activity] PROXIMITY_SCREEN_OFF_WAKE_LOCK isn't supported on this device!") + Log.w( + "[Proximity Sensor Activity] PROXIMITY_SCREEN_OFF_WAKE_LOCK isn't supported on this device!" + ) } proximityWakeLock = powerManager.newWakeLock( @@ -58,7 +60,9 @@ abstract class ProximitySensorActivity : GenericActivity() { protected fun enableProximitySensor(enable: Boolean) { if (enable) { if (!proximitySensorEnabled) { - Log.i("[Proximity Sensor Activity] Enabling proximity sensor (turning screen OFF when wake lock is acquired)") + Log.i( + "[Proximity Sensor Activity] Enabling proximity sensor (turning screen OFF when wake lock is acquired)" + ) if (!proximityWakeLock.isHeld) { Log.i("[Proximity Sensor Activity] Acquiring PROXIMITY_SCREEN_OFF_WAKE_LOCK") proximityWakeLock.acquire() @@ -67,9 +71,13 @@ abstract class ProximitySensorActivity : GenericActivity() { } } else { if (proximitySensorEnabled) { - Log.i("[Proximity Sensor Activity] Disabling proximity sensor (turning screen ON when wake lock is released)") + Log.i( + "[Proximity Sensor Activity] Disabling proximity sensor (turning screen ON when wake lock is released)" + ) if (proximityWakeLock.isHeld) { - Log.i("[Proximity Sensor Activity] Asking to release PROXIMITY_SCREEN_OFF_WAKE_LOCK next time sensor detects no proximity") + Log.i( + "[Proximity Sensor Activity] Asking to release PROXIMITY_SCREEN_OFF_WAKE_LOCK next time sensor detects no proximity" + ) proximityWakeLock.release(RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) } proximitySensorEnabled = false diff --git a/app/src/main/java/org/linphone/activities/assistant/adapters/CountryPickerAdapter.kt b/app/src/main/java/org/linphone/activities/assistant/adapters/CountryPickerAdapter.kt index 0b36c1637..47220e0a7 100644 --- a/app/src/main/java/org/linphone/activities/assistant/adapters/CountryPickerAdapter.kt +++ b/app/src/main/java/org/linphone/activities/assistant/adapters/CountryPickerAdapter.kt @@ -41,7 +41,11 @@ class CountryPickerAdapter : BaseAdapter(), Filterable { } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { - val view: View = convertView ?: LayoutInflater.from(parent.context).inflate(R.layout.assistant_country_picker_cell, parent, false) + val view: View = convertView ?: LayoutInflater.from(parent.context).inflate( + R.layout.assistant_country_picker_cell, + parent, + false + ) val dialPlan: DialPlan = countries[position] val name = view.findViewById(R.id.country_name) diff --git a/app/src/main/java/org/linphone/activities/assistant/fragments/AbstractPhoneFragment.kt b/app/src/main/java/org/linphone/activities/assistant/fragments/AbstractPhoneFragment.kt index 1693c0ce4..f355ef69c 100644 --- a/app/src/main/java/org/linphone/activities/assistant/fragments/AbstractPhoneFragment.kt +++ b/app/src/main/java/org/linphone/activities/assistant/fragments/AbstractPhoneFragment.kt @@ -58,7 +58,10 @@ abstract class AbstractPhoneFragment : GenericFragment() if (!resources.getBoolean(R.bool.isTablet)) { if (!PermissionHelper.get().hasReadPhoneStateOrPhoneNumbersPermission()) { Log.i("[Assistant] Asking for READ_PHONE_STATE/READ_PHONE_NUMBERS permission") - Compatibility.requestReadPhoneStateOrNumbersPermission(this, READ_PHONE_STATE_PERMISSION_REQUEST_CODE) + Compatibility.requestReadPhoneStateOrNumbersPermission( + this, + READ_PHONE_STATE_PERMISSION_REQUEST_CODE + ) } else { updateFromDeviceInfo() } diff --git a/app/src/main/java/org/linphone/activities/assistant/fragments/EchoCancellerCalibrationFragment.kt b/app/src/main/java/org/linphone/activities/assistant/fragments/EchoCancellerCalibrationFragment.kt index 1449eddcd..9c48cb0d0 100644 --- a/app/src/main/java/org/linphone/activities/assistant/fragments/EchoCancellerCalibrationFragment.kt +++ b/app/src/main/java/org/linphone/activities/assistant/fragments/EchoCancellerCalibrationFragment.kt @@ -57,7 +57,10 @@ class EchoCancellerCalibrationFragment : GenericFragment 0) { val clip = data.getItemAt(0).text.toString() if (clip.length == 4) { - Log.i("[Assistant] [Phone Account Validation] Found 4 digits as primary clip in clipboard, using it and clear it") + Log.i( + "[Assistant] [Phone Account Validation] Found 4 digits as primary clip in clipboard, using it and clear it" + ) viewModel.code.value = clip clipboard.clearPrimaryClip() } diff --git a/app/src/main/java/org/linphone/activities/assistant/fragments/QrCodeFragment.kt b/app/src/main/java/org/linphone/activities/assistant/fragments/QrCodeFragment.kt index 420669552..0fe20d93e 100644 --- a/app/src/main/java/org/linphone/activities/assistant/fragments/QrCodeFragment.kt +++ b/app/src/main/java/org/linphone/activities/assistant/fragments/QrCodeFragment.kt @@ -67,7 +67,10 @@ class QrCodeFragment : GenericFragment() { if (!PermissionHelper.required(requireContext()).hasCameraPermission()) { Log.i("[QR Code] Asking for CAMERA permission") - requestPermissions(arrayOf(android.Manifest.permission.CAMERA), CAMERA_PERMISSION_REQUEST_CODE) + requestPermissions( + arrayOf(android.Manifest.permission.CAMERA), + CAMERA_PERMISSION_REQUEST_CODE + ) } } diff --git a/app/src/main/java/org/linphone/activities/assistant/fragments/WelcomeFragment.kt b/app/src/main/java/org/linphone/activities/assistant/fragments/WelcomeFragment.kt index 07dd1a0ea..5ed4196a5 100644 --- a/app/src/main/java/org/linphone/activities/assistant/fragments/WelcomeFragment.kt +++ b/app/src/main/java/org/linphone/activities/assistant/fragments/WelcomeFragment.kt @@ -107,7 +107,12 @@ class WelcomeFragment : GenericFragment() { } } } - spannable.setSpan(clickableSpan, termsMatcher.start(0), termsMatcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) + spannable.setSpan( + clickableSpan, + termsMatcher.start(0), + termsMatcher.end(), + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE + ) } val policyMatcher = Pattern.compile(privacy).matcher(label) @@ -125,7 +130,12 @@ class WelcomeFragment : GenericFragment() { } } } - spannable.setSpan(clickableSpan, policyMatcher.start(0), policyMatcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) + spannable.setSpan( + clickableSpan, + policyMatcher.start(0), + policyMatcher.end(), + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE + ) } binding.termsAndPrivacy.text = spannable diff --git a/app/src/main/java/org/linphone/activities/assistant/viewmodels/AccountLoginViewModel.kt b/app/src/main/java/org/linphone/activities/assistant/viewmodels/AccountLoginViewModel.kt index 85145717d..d74b17fa0 100644 --- a/app/src/main/java/org/linphone/activities/assistant/viewmodels/AccountLoginViewModel.kt +++ b/app/src/main/java/org/linphone/activities/assistant/viewmodels/AccountLoginViewModel.kt @@ -159,7 +159,9 @@ class AccountLoginViewModel(accountCreator: AccountCreator) : AbstractPhoneViewM if (loginWithUsernamePassword.value == true) { val result = accountCreator.setUsername(username.value) if (result != AccountCreator.UsernameStatus.Ok) { - Log.e("[Assistant] [Account Login] Error [${result.name}] setting the username: ${username.value}") + Log.e( + "[Assistant] [Account Login] Error [${result.name}] setting the username: ${username.value}" + ) usernameError.value = result.name return } @@ -180,9 +182,13 @@ class AccountLoginViewModel(accountCreator: AccountCreator) : AbstractPhoneViewM onErrorEvent.value = Event("Error: Failed to create account object") } } else { - val result = AccountCreator.PhoneNumberStatus.fromInt(accountCreator.setPhoneNumber(phoneNumber.value, prefix.value)) + val result = AccountCreator.PhoneNumberStatus.fromInt( + accountCreator.setPhoneNumber(phoneNumber.value, prefix.value) + ) if (result != AccountCreator.PhoneNumberStatus.Ok) { - Log.e("[Assistant] [Account Login] Error [$result] setting the phone number: ${phoneNumber.value} with prefix: ${prefix.value}") + Log.e( + "[Assistant] [Account Login] Error [$result] setting the phone number: ${phoneNumber.value} with prefix: ${prefix.value}" + ) phoneNumberError.value = result.name return } @@ -190,7 +196,9 @@ class AccountLoginViewModel(accountCreator: AccountCreator) : AbstractPhoneViewM val result2 = accountCreator.setUsername(accountCreator.phoneNumber) if (result2 != AccountCreator.UsernameStatus.Ok) { - Log.e("[Assistant] [Account Login] Error [${result2.name}] setting the username: ${accountCreator.phoneNumber}") + Log.e( + "[Assistant] [Account Login] Error [${result2.name}] setting the username: ${accountCreator.phoneNumber}" + ) usernameError.value = result2.name return } @@ -229,7 +237,9 @@ class AccountLoginViewModel(accountCreator: AccountCreator) : AbstractPhoneViewM if (proxyConfig.dialPrefix.isNullOrEmpty()) { val dialPlan = PhoneNumberUtils.getDialPlanForCurrentCountry(coreContext.context) if (dialPlan != null) { - Log.i("[Assistant] [Account Login] Found dial plan country ${dialPlan.country} with international prefix ${dialPlan.countryCallingCode}") + Log.i( + "[Assistant] [Account Login] Found dial plan country ${dialPlan.country} with international prefix ${dialPlan.countryCallingCode}" + ) proxyConfig.edit() proxyConfig.dialPrefix = dialPlan.countryCallingCode proxyConfig.done() diff --git a/app/src/main/java/org/linphone/activities/assistant/viewmodels/EmailAccountCreationViewModel.kt b/app/src/main/java/org/linphone/activities/assistant/viewmodels/EmailAccountCreationViewModel.kt index 24f0a8e20..d3e1bde22 100644 --- a/app/src/main/java/org/linphone/activities/assistant/viewmodels/EmailAccountCreationViewModel.kt +++ b/app/src/main/java/org/linphone/activities/assistant/viewmodels/EmailAccountCreationViewModel.kt @@ -74,7 +74,9 @@ class EmailAccountCreationViewModel(val accountCreator: AccountCreator) : ViewMo when (status) { AccountCreator.Status.AccountExist, AccountCreator.Status.AccountExistWithAlias -> { waitForServerAnswer.value = false - usernameError.value = AppUtils.getString(R.string.assistant_error_username_already_exists) + usernameError.value = AppUtils.getString( + R.string.assistant_error_username_already_exists + ) } AccountCreator.Status.AccountNotExist -> { val createAccountStatus = creator.createAccount() diff --git a/app/src/main/java/org/linphone/activities/assistant/viewmodels/EmailAccountValidationViewModel.kt b/app/src/main/java/org/linphone/activities/assistant/viewmodels/EmailAccountValidationViewModel.kt index 1f67ba43d..856d11b10 100644 --- a/app/src/main/java/org/linphone/activities/assistant/viewmodels/EmailAccountValidationViewModel.kt +++ b/app/src/main/java/org/linphone/activities/assistant/viewmodels/EmailAccountValidationViewModel.kt @@ -109,9 +109,13 @@ class EmailAccountValidationViewModel(val accountCreator: AccountCreator) : View proxyConfig.isPushNotificationAllowed = true if (proxyConfig.dialPrefix.isNullOrEmpty()) { - val dialPlan = PhoneNumberUtils.getDialPlanForCurrentCountry(LinphoneApplication.coreContext.context) + val dialPlan = PhoneNumberUtils.getDialPlanForCurrentCountry( + LinphoneApplication.coreContext.context + ) if (dialPlan != null) { - Log.i("[Assistant] [Account Validation] Found dial plan country ${dialPlan.country} with international prefix ${dialPlan.countryCallingCode}") + Log.i( + "[Assistant] [Account Validation] Found dial plan country ${dialPlan.country} with international prefix ${dialPlan.countryCallingCode}" + ) proxyConfig.edit() proxyConfig.dialPrefix = dialPlan.countryCallingCode proxyConfig.done() diff --git a/app/src/main/java/org/linphone/activities/assistant/viewmodels/PhoneAccountCreationViewModel.kt b/app/src/main/java/org/linphone/activities/assistant/viewmodels/PhoneAccountCreationViewModel.kt index fa39df29e..46b249ff1 100644 --- a/app/src/main/java/org/linphone/activities/assistant/viewmodels/PhoneAccountCreationViewModel.kt +++ b/app/src/main/java/org/linphone/activities/assistant/viewmodels/PhoneAccountCreationViewModel.kt @@ -41,7 +41,9 @@ class PhoneAccountCreationViewModelFactory(private val accountCreator: AccountCr } } -class PhoneAccountCreationViewModel(accountCreator: AccountCreator) : AbstractPhoneViewModel(accountCreator) { +class PhoneAccountCreationViewModel(accountCreator: AccountCreator) : AbstractPhoneViewModel( + accountCreator +) { val username = MutableLiveData() val useUsername = MutableLiveData() val usernameError = MutableLiveData() @@ -71,9 +73,13 @@ class PhoneAccountCreationViewModel(accountCreator: AccountCreator) : AbstractPh AccountCreator.Status.AccountExist, AccountCreator.Status.AccountExistWithAlias -> { waitForServerAnswer.value = false if (useUsername.value == true) { - usernameError.value = AppUtils.getString(R.string.assistant_error_username_already_exists) + usernameError.value = AppUtils.getString( + R.string.assistant_error_username_already_exists + ) } else { - phoneNumberError.value = AppUtils.getString(R.string.assistant_error_phone_number_already_exists) + phoneNumberError.value = AppUtils.getString( + R.string.assistant_error_phone_number_already_exists + ) } } AccountCreator.Status.AccountNotExist -> { @@ -103,7 +109,9 @@ class PhoneAccountCreationViewModel(accountCreator: AccountCreator) : AbstractPh goToSmsValidationEvent.value = Event(true) } AccountCreator.Status.AccountExistWithAlias -> { - phoneNumberError.value = AppUtils.getString(R.string.assistant_error_phone_number_already_exists) + phoneNumberError.value = AppUtils.getString( + R.string.assistant_error_phone_number_already_exists + ) } else -> { onErrorEvent.value = Event("Error: ${status.name}") @@ -161,7 +169,11 @@ class PhoneAccountCreationViewModel(accountCreator: AccountCreator) : AbstractPh } private fun isCreateButtonEnabled(): Boolean { - val usernameRegexp = corePreferences.config.getString("assistant", "username_regex", "^[a-z0-9+_.\\-]*\$") + val usernameRegexp = corePreferences.config.getString( + "assistant", + "username_regex", + "^[a-z0-9+_.\\-]*\$" + ) return isPhoneNumberOk() && usernameRegexp != null && ( useUsername.value == false || diff --git a/app/src/main/java/org/linphone/activities/assistant/viewmodels/PhoneAccountLinkingViewModel.kt b/app/src/main/java/org/linphone/activities/assistant/viewmodels/PhoneAccountLinkingViewModel.kt index f30cba209..62c8bf9e5 100644 --- a/app/src/main/java/org/linphone/activities/assistant/viewmodels/PhoneAccountLinkingViewModel.kt +++ b/app/src/main/java/org/linphone/activities/assistant/viewmodels/PhoneAccountLinkingViewModel.kt @@ -35,7 +35,9 @@ class PhoneAccountLinkingViewModelFactory(private val accountCreator: AccountCre } } -class PhoneAccountLinkingViewModel(accountCreator: AccountCreator) : AbstractPhoneViewModel(accountCreator) { +class PhoneAccountLinkingViewModel(accountCreator: AccountCreator) : AbstractPhoneViewModel( + accountCreator +) { val username = MutableLiveData() val allowSkip = MutableLiveData() diff --git a/app/src/main/java/org/linphone/activities/assistant/viewmodels/PhoneAccountValidationViewModel.kt b/app/src/main/java/org/linphone/activities/assistant/viewmodels/PhoneAccountValidationViewModel.kt index 34b88a4ba..5b6592341 100644 --- a/app/src/main/java/org/linphone/activities/assistant/viewmodels/PhoneAccountValidationViewModel.kt +++ b/app/src/main/java/org/linphone/activities/assistant/viewmodels/PhoneAccountValidationViewModel.kt @@ -125,7 +125,9 @@ class PhoneAccountValidationViewModel(val accountCreator: AccountCreator) : View fun finish() { accountCreator.activationCode = code.value.orEmpty() - Log.i("[Assistant] [Phone Account Validation] Phone number is ${accountCreator.phoneNumber} and activation code is ${accountCreator.activationCode}") + Log.i( + "[Assistant] [Phone Account Validation] Phone number is ${accountCreator.phoneNumber} and activation code is ${accountCreator.activationCode}" + ) waitForServerAnswer.value = true val status = when { @@ -145,7 +147,9 @@ class PhoneAccountValidationViewModel(val accountCreator: AccountCreator) : View val proxyConfig: ProxyConfig? = accountCreator.createProxyConfig() if (proxyConfig == null) { - Log.e("[Assistant] [Phone Account Validation] Account creator couldn't create proxy config") + Log.e( + "[Assistant] [Phone Account Validation] Account creator couldn't create proxy config" + ) return false } diff --git a/app/src/main/java/org/linphone/activities/chat_bubble/ChatBubbleActivity.kt b/app/src/main/java/org/linphone/activities/chat_bubble/ChatBubbleActivity.kt index 29ea39d61..ddcdefa5b 100644 --- a/app/src/main/java/org/linphone/activities/chat_bubble/ChatBubbleActivity.kt +++ b/app/src/main/java/org/linphone/activities/chat_bubble/ChatBubbleActivity.kt @@ -77,11 +77,15 @@ class ChatBubbleActivity : GenericActivity() { var chatRoom: ChatRoom? = null if (localSipUri != null && remoteSipUri != null) { - Log.i("[Chat Bubble] Found local [$localSipUri] & remote [$remoteSipUri] addresses in arguments") + Log.i( + "[Chat Bubble] Found local [$localSipUri] & remote [$remoteSipUri] addresses in arguments" + ) val localAddress = Factory.instance().createAddress(localSipUri) val remoteSipAddress = Factory.instance().createAddress(remoteSipUri) chatRoom = coreContext.core.searchChatRoom( - null, localAddress, remoteSipAddress, + null, + localAddress, + remoteSipAddress, arrayOfNulls( 0 ) @@ -155,7 +159,10 @@ class ChatBubbleActivity : GenericActivity() { binding.setOpenAppClickListener { coreContext.notificationsManager.currentlyDisplayedChatRoomAddress = null - coreContext.notificationsManager.changeDismissNotificationUponReadForChatRoom(viewModel.chatRoom, false) + coreContext.notificationsManager.changeDismissNotificationUponReadForChatRoom( + viewModel.chatRoom, + false + ) val intent = Intent(this, MainActivity::class.java) intent.putExtra("RemoteSipUri", remoteSipUri) @@ -181,7 +188,10 @@ class ChatBubbleActivity : GenericActivity() { viewModel.chatRoom.addListener(listener) // Workaround for the removed notification when a chat room is marked as read - coreContext.notificationsManager.changeDismissNotificationUponReadForChatRoom(viewModel.chatRoom, true) + coreContext.notificationsManager.changeDismissNotificationUponReadForChatRoom( + viewModel.chatRoom, + true + ) viewModel.chatRoom.markAsRead() val peerAddress = viewModel.chatRoom.peerAddress.asStringUriOnly() @@ -199,7 +209,10 @@ class ChatBubbleActivity : GenericActivity() { viewModel.chatRoom.removeListener(listener) coreContext.notificationsManager.currentlyDisplayedChatRoomAddress = null - coreContext.notificationsManager.changeDismissNotificationUponReadForChatRoom(viewModel.chatRoom, false) + coreContext.notificationsManager.changeDismissNotificationUponReadForChatRoom( + viewModel.chatRoom, + false + ) super.onPause() } diff --git a/app/src/main/java/org/linphone/activities/main/MainActivity.kt b/app/src/main/java/org/linphone/activities/main/MainActivity.kt index 49c758bab..c776e1dc3 100644 --- a/app/src/main/java/org/linphone/activities/main/MainActivity.kt +++ b/app/src/main/java/org/linphone/activities/main/MainActivity.kt @@ -205,7 +205,9 @@ class MainActivity : GenericActivity(), SnackBarActivity, NavController.OnDestin binding.rootCoordinatorLayout.addKeyboardInsetListener { keyboardVisible -> val portraitOrientation = resources.configuration.orientation != Configuration.ORIENTATION_LANDSCAPE - Log.i("[Main Activity] Keyboard is ${if (keyboardVisible) "visible" else "invisible"}, orientation is ${if (portraitOrientation) "portrait" else "landscape"}") + Log.i( + "[Main Activity] Keyboard is ${if (keyboardVisible) "visible" else "invisible"}, orientation is ${if (portraitOrientation) "portrait" else "landscape"}" + ) shouldTabsBeVisibleDueToOrientationAndKeyboard = !portraitOrientation || !keyboardVisible updateTabsFragmentVisibility() } @@ -255,7 +257,9 @@ class MainActivity : GenericActivity(), SnackBarActivity, NavController.OnDestin } private fun handleIntentParams(intent: Intent) { - Log.i("[Main Activity] Handling intent with action [${intent.action}], type [${intent.type}] and data [${intent.data}]") + Log.i( + "[Main Activity] Handling intent with action [${intent.action}], type [${intent.type}] and data [${intent.data}]" + ) when (intent.action) { Intent.ACTION_MAIN -> handleMainIntent(intent) @@ -291,10 +295,14 @@ class MainActivity : GenericActivity(), SnackBarActivity, NavController.OnDestin if (stringUri.startsWith("linphone-config:")) { val remoteConfigUri = stringUri.substring("linphone-config:".length) if (corePreferences.autoRemoteProvisioningOnConfigUriHandler) { - Log.w("[Main Activity] Remote provisioning URL set to [$remoteConfigUri], restarting Core now") + Log.w( + "[Main Activity] Remote provisioning URL set to [$remoteConfigUri], restarting Core now" + ) applyRemoteProvisioning(remoteConfigUri) } else { - Log.i("[Main Activity] Remote provisioning URL found [$remoteConfigUri], asking for user validation") + Log.i( + "[Main Activity] Remote provisioning URL found [$remoteConfigUri], asking for user validation" + ) showAcceptRemoteConfigurationDialog(remoteConfigUri) } } else { @@ -339,7 +347,9 @@ class MainActivity : GenericActivity(), SnackBarActivity, NavController.OnDestin if (intent.hasExtra("RemoteSipUri") && intent.hasExtra("LocalSipUri")) { val peerAddress = intent.getStringExtra("RemoteSipUri") val localAddress = intent.getStringExtra("LocalSipUri") - Log.i("[Main Activity] Found chat room intent extra: local SIP URI=[$localAddress], peer SIP URI=[$peerAddress]") + Log.i( + "[Main Activity] Found chat room intent extra: local SIP URI=[$localAddress], peer SIP URI=[$peerAddress]" + ) navigateToChatRoom(localAddress, peerAddress) } else { Log.i("[Main Activity] Found chat intent extra, go to chat rooms list") @@ -362,9 +372,16 @@ class MainActivity : GenericActivity(), SnackBarActivity, NavController.OnDestin val core = coreContext.core val call = core.currentCall ?: core.calls.firstOrNull() if (call != null) { - Log.i("[Main Activity] Launcher clicked while there is at least one active call, go to CallActivity") - val callIntent = Intent(this, org.linphone.activities.voip.CallActivity::class.java) - callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) + Log.i( + "[Main Activity] Launcher clicked while there is at least one active call, go to CallActivity" + ) + val callIntent = Intent( + this, + org.linphone.activities.voip.CallActivity::class.java + ) + callIntent.addFlags( + Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT + ) startActivity(callIntent) } } @@ -391,7 +408,10 @@ class MainActivity : GenericActivity(), SnackBarActivity, NavController.OnDestin } } - val address = coreContext.core.interpretUrl(addressToCall, LinphoneUtils.applyInternationalPrefix()) + val address = coreContext.core.interpretUrl( + addressToCall, + LinphoneUtils.applyInternationalPrefix() + ) if (address != null) { addressToCall = address.asStringUriOnly() } @@ -490,8 +510,13 @@ class MainActivity : GenericActivity(), SnackBarActivity, NavController.OnDestin val localAddress = coreContext.core.defaultAccount?.params?.identityAddress?.asStringUriOnly() - val peerAddress = coreContext.core.interpretUrl(addressToIM, LinphoneUtils.applyInternationalPrefix())?.asStringUriOnly() - Log.i("[Main Activity] Navigating to chat room with local [$localAddress] and peer [$peerAddress] addresses") + val peerAddress = coreContext.core.interpretUrl( + addressToIM, + LinphoneUtils.applyInternationalPrefix() + )?.asStringUriOnly() + Log.i( + "[Main Activity] Navigating to chat room with local [$localAddress] and peer [$peerAddress] addresses" + ) navigateToChatRoom(localAddress, peerAddress) } else { val shortcutId = intent.getStringExtra("android.intent.extra.shortcut.ID") // Intent.EXTRA_SHORTCUT_ID @@ -510,10 +535,14 @@ class MainActivity : GenericActivity(), SnackBarActivity, NavController.OnDestin if (split.size == 2) { val localAddress = split[0] val peerAddress = split[1] - Log.i("[Main Activity] Navigating to chat room with local [$localAddress] and peer [$peerAddress] addresses, computed from shortcut/locus id") + Log.i( + "[Main Activity] Navigating to chat room with local [$localAddress] and peer [$peerAddress] addresses, computed from shortcut/locus id" + ) navigateToChatRoom(localAddress, peerAddress) } else { - Log.e("[Main Activity] Failed to parse shortcut/locus id: $id, going to chat rooms list") + Log.e( + "[Main Activity] Failed to parse shortcut/locus id: $id, going to chat rooms list" + ) navigateToChatRooms() } } @@ -562,7 +591,10 @@ class MainActivity : GenericActivity(), SnackBarActivity, NavController.OnDestin } private fun showAcceptRemoteConfigurationDialog(remoteConfigUri: String) { - val dialogViewModel = DialogViewModel(remoteConfigUri, getString(R.string.dialog_apply_remote_provisioning_title)) + val dialogViewModel = DialogViewModel( + remoteConfigUri, + getString(R.string.dialog_apply_remote_provisioning_title) + ) val dialog = DialogUtils.getDialog(this, dialogViewModel) dialogViewModel.showCancelButton { @@ -575,7 +607,9 @@ class MainActivity : GenericActivity(), SnackBarActivity, NavController.OnDestin ) dialogViewModel.showOkButton( { - Log.w("[Main Activity] Remote provisioning URL set to [$remoteConfigUri], restarting Core now") + Log.w( + "[Main Activity] Remote provisioning URL set to [$remoteConfigUri], restarting Core now" + ) applyRemoteProvisioning(remoteConfigUri) dialog.dismiss() }, diff --git a/app/src/main/java/org/linphone/activities/main/chat/ChatScrollListener.kt b/app/src/main/java/org/linphone/activities/main/chat/ChatScrollListener.kt index d2e2c7622..795be99ed 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/ChatScrollListener.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/ChatScrollListener.kt @@ -26,6 +26,7 @@ internal abstract class ChatScrollListener(private val mLayoutManager: LinearLay RecyclerView.OnScrollListener() { // The total number of items in the data set after the last load private var previousTotalItemCount = 0 + // True if we are still waiting for the last set of data to load. private var loading = true diff --git a/app/src/main/java/org/linphone/activities/main/chat/adapters/ChatMessagesListAdapter.kt b/app/src/main/java/org/linphone/activities/main/chat/adapters/ChatMessagesListAdapter.kt index 1161486ef..b4fd5a72a 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/adapters/ChatMessagesListAdapter.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/adapters/ChatMessagesListAdapter.kt @@ -55,7 +55,10 @@ import org.linphone.utils.HeaderAdapter class ChatMessagesListAdapter( selectionVM: ListTopBarViewModel, private val viewLifecycleOwner: LifecycleOwner -) : SelectionListAdapter(selectionVM, ChatMessageDiffCallback()), +) : SelectionListAdapter( + selectionVM, + ChatMessageDiffCallback() +), HeaderAdapter { companion object { const val MAX_TIME_TO_GROUP_MESSAGES = 60 // 1 minute @@ -116,7 +119,9 @@ class ChatMessagesListAdapter( override fun onWebUrlClicked(url: String) { if (popup?.isShowing == true) { - Log.w("[Chat Message Data] Long press that displayed context menu detected, aborting click on URL [$url]") + Log.w( + "[Chat Message Data] Long press that displayed context menu detected, aborting click on URL [$url]" + ) return } urlClickEvent.value = Event(url) @@ -124,7 +129,9 @@ class ChatMessagesListAdapter( override fun onSipAddressClicked(sipUri: String) { if (popup?.isShowing == true) { - Log.w("[Chat Message Data] Long press that displayed context menu detected, aborting click on SIP URI [$sipUri]") + Log.w( + "[Chat Message Data] Long press that displayed context menu detected, aborting click on SIP URI [$sipUri]" + ) return } sipUriClickedEvent.value = Event(sipUri) @@ -155,7 +162,9 @@ class ChatMessagesListAdapter( private fun createChatMessageViewHolder(parent: ViewGroup): ChatMessageViewHolder { val binding: ChatMessageListCellBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), - R.layout.chat_message_list_cell, parent, false + R.layout.chat_message_list_cell, + parent, + false ) return ChatMessageViewHolder(binding) } @@ -163,7 +172,9 @@ class ChatMessagesListAdapter( private fun createEventViewHolder(parent: ViewGroup): EventViewHolder { val binding: ChatEventListCellBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), - R.layout.chat_event_list_cell, parent, false + R.layout.chat_event_list_cell, + parent, + false ) return EventViewHolder(binding) } @@ -199,9 +210,14 @@ class ChatMessagesListAdapter( override fun getHeaderViewForPosition(context: Context, position: Int): View { val binding: ChatUnreadMessagesListHeaderBinding = DataBindingUtil.inflate( LayoutInflater.from(context), - R.layout.chat_unread_messages_list_header, null, false + R.layout.chat_unread_messages_list_header, + null, + false + ) + binding.title = AppUtils.getStringWithPlural( + R.plurals.chat_room_unread_messages_event, + unreadMessagesCount ) - binding.title = AppUtils.getStringWithPlural(R.plurals.chat_room_unread_messages_event, unreadMessagesCount) binding.executePendingBindings() return binding.root } @@ -281,7 +297,10 @@ class ChatMessagesListAdapter( val previousItem = getItem(bindingAdapterPosition - 1) if (previousItem.eventLog.type == EventLog.Type.ConferenceChatMessage) { val previousMessage = previousItem.eventLog.chatMessage - if (previousMessage != null && previousMessage.fromAddress.weakEqual(chatMessage.fromAddress)) { + if (previousMessage != null && previousMessage.fromAddress.weakEqual( + chatMessage.fromAddress + ) + ) { if (abs(chatMessage.time - previousMessage.time) < MAX_TIME_TO_GROUP_MESSAGES) { hasPrevious = true } @@ -293,7 +312,10 @@ class ChatMessagesListAdapter( val nextItem = getItem(bindingAdapterPosition + 1) if (nextItem.eventLog.type == EventLog.Type.ConferenceChatMessage) { val nextMessage = nextItem.eventLog.chatMessage - if (nextMessage != null && nextMessage.fromAddress.weakEqual(chatMessage.fromAddress)) { + if (nextMessage != null && nextMessage.fromAddress.weakEqual( + chatMessage.fromAddress + ) + ) { if (abs(nextMessage.time - chatMessage.time) < MAX_TIME_TO_GROUP_MESSAGES) { hasNext = true } @@ -308,12 +330,17 @@ class ChatMessagesListAdapter( setContextMenuClickListener { val popupView: ChatMessageLongPressMenuBindingImpl = DataBindingUtil.inflate( LayoutInflater.from(root.context), - R.layout.chat_message_long_press_menu, null, false + R.layout.chat_message_long_press_menu, + null, + false ) val itemSize = AppUtils.getDimension(R.dimen.chat_message_popup_item_height).toInt() var totalSize = itemSize * 7 - if (chatMessage.chatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { + if (chatMessage.chatRoom.hasCapability( + ChatRoomCapabilities.OneToOne.toInt() + ) + ) { // No message id popupView.imdnHidden = true totalSize -= itemSize @@ -497,7 +524,9 @@ private class ChatMessageDiffCallback : DiffUtil.ItemCallback() { oldData.time.value == newData.time.value && oldData.isOutgoing == newData.isOutgoing - } else oldItem.notifyId == newItem.notifyId + } else { + oldItem.notifyId == newItem.notifyId + } } override fun areContentsTheSame( diff --git a/app/src/main/java/org/linphone/activities/main/chat/adapters/ChatRoomsListAdapter.kt b/app/src/main/java/org/linphone/activities/main/chat/adapters/ChatRoomsListAdapter.kt index c16ecd479..12e6c7157 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/adapters/ChatRoomsListAdapter.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/adapters/ChatRoomsListAdapter.kt @@ -48,7 +48,9 @@ class ChatRoomsListAdapter( override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding: ChatRoomListCellBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), - R.layout.chat_room_list_cell, parent, false + R.layout.chat_room_list_cell, + parent, + false ) return ViewHolder(binding) } @@ -77,7 +79,9 @@ class ChatRoomsListAdapter( try { notifyItemChanged(bindingAdapterPosition) } catch (e: Exception) { - Log.e("[Chat Rooms Adapter] Can't notify item [$bindingAdapterPosition] has changed: $e") + Log.e( + "[Chat Rooms Adapter] Can't notify item [$bindingAdapterPosition] has changed: $e" + ) } } } diff --git a/app/src/main/java/org/linphone/activities/main/chat/adapters/GroupInfoParticipantsAdapter.kt b/app/src/main/java/org/linphone/activities/main/chat/adapters/GroupInfoParticipantsAdapter.kt index 36331690c..b9d13bc60 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/adapters/GroupInfoParticipantsAdapter.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/adapters/GroupInfoParticipantsAdapter.kt @@ -46,7 +46,9 @@ class GroupInfoParticipantsAdapter( override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding: ChatRoomGroupInfoParticipantCellBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), - R.layout.chat_room_group_info_participant_cell, parent, false + R.layout.chat_room_group_info_participant_cell, + parent, + false ) return ViewHolder(binding) } diff --git a/app/src/main/java/org/linphone/activities/main/chat/adapters/ImdnAdapter.kt b/app/src/main/java/org/linphone/activities/main/chat/adapters/ImdnAdapter.kt index f05a833ef..3226780ea 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/adapters/ImdnAdapter.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/adapters/ImdnAdapter.kt @@ -41,7 +41,9 @@ class ImdnAdapter( override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding: ChatRoomImdnParticipantCellBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), - R.layout.chat_room_imdn_participant_cell, parent, false + R.layout.chat_room_imdn_participant_cell, + parent, + false ) return ViewHolder(binding) } @@ -70,14 +72,18 @@ class ImdnAdapter( val previousPosition = position - 1 return if (previousPosition >= 0) { getItem(previousPosition).imdnState.state != participantImdnState.imdnState.state - } else true + } else { + true + } } override fun getHeaderViewForPosition(context: Context, position: Int): View { val participantImdnState = getItem(position).imdnState val binding: ImdnListHeaderBinding = DataBindingUtil.inflate( LayoutInflater.from(context), - R.layout.imdn_list_header, null, false + R.layout.imdn_list_header, + null, + false ) when (participantImdnState.state) { ChatMessage.State.Displayed -> { diff --git a/app/src/main/java/org/linphone/activities/main/chat/data/ChatMessageContentData.kt b/app/src/main/java/org/linphone/activities/main/chat/data/ChatMessageContentData.kt index f09c6b6b9..c734d69cd 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/data/ChatMessageContentData.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/data/ChatMessageContentData.kt @@ -48,7 +48,7 @@ import org.linphone.utils.TimestampUtils class ChatMessageContentData( private val chatMessage: ChatMessage, - private val contentIndex: Int, + private val contentIndex: Int ) { var listener: OnContentClickedListener? = null @@ -172,7 +172,9 @@ class ChatMessageContentData( fun download() { if (chatMessage.isFileTransferInProgress) { - Log.w("[Content] Another FileTransfer content for this message is currently being downloaded, can't start another one for now") + Log.w( + "[Content] Another FileTransfer content for this message is currently being downloaded, can't start another one for now" + ) listener?.onError(R.string.chat_message_download_already_in_progress) return } @@ -191,7 +193,9 @@ class ChatMessageContentData( return } } else { - Log.w("[Content] File path already set [$filePath] using it (auto download that failed probably)") + Log.w( + "[Content] File path already set [$filePath] using it (auto download that failed probably)" + ) } if (!chatMessage.downloadContent(content)) { @@ -221,7 +225,9 @@ class ChatMessageContentData( val content = getContent() isFileEncrypted = content.isFileEncrypted - Log.i("[Content] Is ${if (content.isFile) "file" else "file transfer"} content encrypted ? $isFileEncrypted") + Log.i( + "[Content] Is ${if (content.isFile) "file" else "file transfer"} content encrypted ? $isFileEncrypted" + ) filePath.value = "" fileName.value = if (content.name.isNullOrEmpty() && !content.filePath.isNullOrEmpty()) { @@ -232,7 +238,9 @@ class ChatMessageContentData( // Display download size and underline text val fileSize = AppUtils.bytesToDisplayableSize(content.fileSize.toLong()) - val spannable = SpannableString("${AppUtils.getString(R.string.chat_message_download_file)} ($fileSize)") + val spannable = SpannableString( + "${AppUtils.getString(R.string.chat_message_download_file)} ($fileSize)" + ) spannable.setSpan(UnderlineSpan(), 0, spannable.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) downloadLabel.value = spannable @@ -247,7 +255,9 @@ class ChatMessageContentData( if (content.isFile || (content.isFileTransfer && chatMessage.isOutgoing)) { val path = if (isFileEncrypted) { - Log.i("[Content] [VFS] Content is encrypted, requesting plain file path for file [${content.filePath}]") + Log.i( + "[Content] [VFS] Content is encrypted, requesting plain file path for file [${content.filePath}]" + ) content.exportPlainFile() } else { content.filePath ?: "" @@ -277,13 +287,19 @@ class ChatMessageContentData( isConferenceIcs -> "conference invitation" else -> "unknown" } - Log.i("[Content] Extension for file [$path] is [$extension], deduced type from MIME is [$type]") + Log.i( + "[Content] Extension for file [$path] is [$extension], deduced type from MIME is [$type]" + ) if (isVoiceRecord) { val duration = content.fileDuration // duration is in ms voiceRecordDuration.value = duration - formattedDuration.value = SimpleDateFormat("mm:ss", Locale.getDefault()).format(duration) - Log.i("[Content] Voice recording duration is ${voiceRecordDuration.value} ($duration)") + formattedDuration.value = SimpleDateFormat("mm:ss", Locale.getDefault()).format( + duration + ) + Log.i( + "[Content] Voice recording duration is ${voiceRecordDuration.value} ($duration)" + ) } else if (isConferenceIcs) { parseConferenceInvite(content) } @@ -291,7 +307,9 @@ class ChatMessageContentData( Log.i("[Content] Found content with icalendar file") parseConferenceInvite(content) } else { - Log.w("[Content] Found ${if (content.isFile) "file" else "file transfer"} content with empty path...") + Log.w( + "[Content] Found ${if (content.isFile) "file" else "file transfer"} content with empty path..." + ) isImage.value = false isVideo.value = false isAudio.value = false @@ -325,7 +343,9 @@ class ChatMessageContentData( val conferenceUri = conferenceInfo?.uri?.asStringUriOnly() if (conferenceInfo != null && conferenceUri != null) { conferenceAddress.value = conferenceUri!! - Log.i("[Content] Created conference info from ICS with address ${conferenceAddress.value}") + Log.i( + "[Content] Created conference info from ICS with address ${conferenceAddress.value}" + ) conferenceSubject.value = conferenceInfo.subject conferenceDescription.value = conferenceInfo.description @@ -355,7 +375,10 @@ class ChatMessageContentData( } } if (!organizerFound) participantsCount += 1 // +1 for organizer - conferenceParticipantCount.value = String.format(AppUtils.getString(R.string.conference_invite_participants_count), participantsCount) + conferenceParticipantCount.value = String.format( + AppUtils.getString(R.string.conference_invite_participants_count), + participantsCount + ) } else if (conferenceInfo == null) { if (content.filePath != null) { try { @@ -367,7 +390,9 @@ class ChatMessageContentData( textBuilder.append('\n') } br.close() - Log.e("[Content] Failed to create conference info from ICS file [${content.filePath}]: $textBuilder") + Log.e( + "[Content] Failed to create conference info from ICS file [${content.filePath}]: $textBuilder" + ) } catch (e: Exception) { Log.e("[Content] Failed to read content of ICS file [${content.filePath}]: $e") } @@ -375,7 +400,9 @@ class ChatMessageContentData( Log.e("[Content] Failed to create conference info from ICS: ${content.utf8Text}") } } else if (conferenceInfo.uri == null) { - Log.e("[Content] Failed to find the conference URI in conference info [$conferenceInfo]") + Log.e( + "[Content] Failed to find the conference URI in conference info [$conferenceInfo]" + ) } } @@ -398,7 +425,11 @@ class ChatMessageContentData( } if (AppUtils.isMediaVolumeLow(coreContext.context)) { - Toast.makeText(coreContext.context, R.string.chat_message_voice_recording_playback_low_volume, Toast.LENGTH_LONG).show() + Toast.makeText( + coreContext.context, + R.string.chat_message_voice_recording_playback_low_volume, + Toast.LENGTH_LONG + ).show() } if (voiceRecordAudioFocusRequest == null) { @@ -440,7 +471,9 @@ class ChatMessageContentData( private fun initVoiceRecordPlayer() { Log.i("[Voice Recording] Creating player for voice record") val playbackSoundCard = AudioRouteUtils.getAudioPlaybackDeviceIdForCallRecordingOrVoiceMessage() - Log.i("[Voice Recording] Using device $playbackSoundCard to make the voice message playback") + Log.i( + "[Voice Recording] Using device $playbackSoundCard to make the voice message playback" + ) val localPlayer = coreContext.core.createLocalPlayer(playbackSoundCard, null, null) if (localPlayer != null) { @@ -454,8 +487,12 @@ class ChatMessageContentData( val path = filePath.value voiceRecordingPlayer.open(path.orEmpty()) voiceRecordDuration.value = voiceRecordingPlayer.duration - formattedDuration.value = SimpleDateFormat("mm:ss", Locale.getDefault()).format(voiceRecordingPlayer.duration) // is already in milliseconds - Log.i("[Voice Recording] Duration is ${voiceRecordDuration.value} (${voiceRecordingPlayer.duration})") + formattedDuration.value = SimpleDateFormat("mm:ss", Locale.getDefault()).format( + voiceRecordingPlayer.duration + ) // is already in milliseconds + Log.i( + "[Voice Recording] Duration is ${voiceRecordDuration.value} (${voiceRecordingPlayer.duration})" + ) } private fun stopVoiceRecording() { diff --git a/app/src/main/java/org/linphone/activities/main/chat/data/ChatMessageData.kt b/app/src/main/java/org/linphone/activities/main/chat/data/ChatMessageData.kt index b0b7c6433..dc8f84a90 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/data/ChatMessageData.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/data/ChatMessageData.kt @@ -89,7 +89,9 @@ class ChatMessageData(val chatMessage: ChatMessage) : GenericContactData(chatMes if (chatMessage.isReply) { val reply = chatMessage.replyMessage if (reply != null) { - Log.i("[Chat Message Data] Message is a reply of message id [${chatMessage.replyMessageId}] sent by [${chatMessage.replyMessageSenderAddress?.asStringUriOnly()}]") + Log.i( + "[Chat Message Data] Message is a reply of message id [${chatMessage.replyMessageId}] sent by [${chatMessage.replyMessageSenderAddress?.asStringUriOnly()}]" + ) replyData.value = ChatMessageData(reply) } } @@ -194,7 +196,9 @@ class ChatMessageData(val chatMessage: ChatMessage) : GenericContactData(chatMes val spannable = Spannable.Factory.getInstance().newSpannable(textContent) text.value = PatternClickableSpan() .add( - Pattern.compile("(?:)?"), + Pattern.compile( + "(?:)?" + ), object : PatternClickableSpan.SpannableClickedListener { override fun onSpanClicked(text: String) { Log.i("[Chat Message Data] Clicked on SIP URI: $text") @@ -222,7 +226,9 @@ class ChatMessageData(val chatMessage: ChatMessage) : GenericContactData(chatMes ).build(spannable) isTextEmoji.value = AppUtils.isTextOnlyContainingEmoji(textContent) } else { - Log.e("[Chat Message Data] Unexpected content with type: ${content.type}/${content.subtype}") + Log.e( + "[Chat Message Data] Unexpected content with type: ${content.type}/${content.subtype}" + ) } } @@ -257,7 +263,12 @@ class ChatMessageData(val chatMessage: ChatMessage) : GenericContactData(chatMes val days = seconds / 86400 return when { days >= 1L -> AppUtils.getStringWithPlural(R.plurals.days, days.toInt()) - else -> String.format("%02d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, (seconds % 60)) + else -> String.format( + "%02d:%02d:%02d", + seconds / 3600, + (seconds % 3600) / 60, + (seconds % 60) + ) } } } diff --git a/app/src/main/java/org/linphone/activities/main/chat/data/ChatRoomData.kt b/app/src/main/java/org/linphone/activities/main/chat/data/ChatRoomData.kt index fb780d534..80cad7923 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/data/ChatRoomData.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/data/ChatRoomData.kt @@ -158,7 +158,9 @@ class ChatRoomData(val chatRoom: ChatRoom) : ContactDataInterface { if (participants.isNotEmpty()) { participants.first().address } else { - Log.e("[Chat Room] ${chatRoom.peerAddress} doesn't have any participant (state ${chatRoom.state})!") + Log.e( + "[Chat Room] ${chatRoom.peerAddress} doesn't have any participant (state ${chatRoom.state})!" + ) null } } @@ -213,7 +215,9 @@ class ChatRoomData(val chatRoom: ChatRoom) : ContactDataInterface { val sender: String = coreContext.contactsManager.findContactByAddress(msg.fromAddress)?.name ?: LinphoneUtils.getDisplayName(msg.fromAddress) - builder.append(coreContext.context.getString(R.string.chat_room_last_message_sender_format, sender)) + builder.append( + coreContext.context.getString(R.string.chat_room_last_message_sender_format, sender) + ) builder.append(" ") } @@ -221,12 +225,22 @@ class ChatRoomData(val chatRoom: ChatRoom) : ContactDataInterface { if (content.isIcalendar) { val body = AppUtils.getString(R.string.conference_invitation) builder.append(body) - builder.setSpan(StyleSpan(Typeface.ITALIC), builder.length - body.length, builder.length, 0) + builder.setSpan( + StyleSpan(Typeface.ITALIC), + builder.length - body.length, + builder.length, + 0 + ) break } else if (content.isVoiceRecording) { val body = AppUtils.getString(R.string.chat_message_voice_recording) builder.append(body) - builder.setSpan(StyleSpan(Typeface.ITALIC), builder.length - body.length, builder.length, 0) + builder.setSpan( + StyleSpan(Typeface.ITALIC), + builder.length - body.length, + builder.length, + 0 + ) break } else if (content.isFile || content.isFileTransfer) { builder.append(content.name + " ") diff --git a/app/src/main/java/org/linphone/activities/main/chat/data/DevicesListGroupData.kt b/app/src/main/java/org/linphone/activities/main/chat/data/DevicesListGroupData.kt index cd4957a16..e3febca66 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/data/DevicesListGroupData.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/data/DevicesListGroupData.kt @@ -27,7 +27,9 @@ import org.linphone.core.ChatRoomSecurityLevel import org.linphone.core.Participant import org.linphone.utils.LinphoneUtils -class DevicesListGroupData(private val participant: Participant) : GenericContactData(participant.address) { +class DevicesListGroupData(private val participant: Participant) : GenericContactData( + participant.address +) { val securityLevelIcon: Int by lazy { when (participant.securityLevel) { ChatRoomSecurityLevel.Safe -> R.drawable.security_2_indicator diff --git a/app/src/main/java/org/linphone/activities/main/chat/data/EventData.kt b/app/src/main/java/org/linphone/activities/main/chat/data/EventData.kt index 4a7a0d792..4c9f08ec8 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/data/EventData.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/data/EventData.kt @@ -65,28 +65,60 @@ class EventData(private val eventLog: EventLog) : GenericContactData( val context: Context = coreContext.context text.value = when (eventLog.type) { - EventLog.Type.ConferenceCreated -> context.getString(R.string.chat_event_conference_created) - EventLog.Type.ConferenceTerminated -> context.getString(R.string.chat_event_conference_destroyed) - EventLog.Type.ConferenceParticipantAdded -> context.getString(R.string.chat_event_participant_added).format(getName()) - EventLog.Type.ConferenceParticipantRemoved -> context.getString(R.string.chat_event_participant_removed).format(getName()) - EventLog.Type.ConferenceSubjectChanged -> context.getString(R.string.chat_event_subject_changed).format(eventLog.subject) - EventLog.Type.ConferenceParticipantSetAdmin -> context.getString(R.string.chat_event_admin_set).format(getName()) - EventLog.Type.ConferenceParticipantUnsetAdmin -> context.getString(R.string.chat_event_admin_unset).format(getName()) - EventLog.Type.ConferenceParticipantDeviceAdded -> context.getString(R.string.chat_event_device_added).format(getName()) - EventLog.Type.ConferenceParticipantDeviceRemoved -> context.getString(R.string.chat_event_device_removed).format(getName()) + EventLog.Type.ConferenceCreated -> context.getString( + R.string.chat_event_conference_created + ) + EventLog.Type.ConferenceTerminated -> context.getString( + R.string.chat_event_conference_destroyed + ) + EventLog.Type.ConferenceParticipantAdded -> context.getString( + R.string.chat_event_participant_added + ).format(getName()) + EventLog.Type.ConferenceParticipantRemoved -> context.getString( + R.string.chat_event_participant_removed + ).format(getName()) + EventLog.Type.ConferenceSubjectChanged -> context.getString( + R.string.chat_event_subject_changed + ).format(eventLog.subject) + EventLog.Type.ConferenceParticipantSetAdmin -> context.getString( + R.string.chat_event_admin_set + ).format(getName()) + EventLog.Type.ConferenceParticipantUnsetAdmin -> context.getString( + R.string.chat_event_admin_unset + ).format(getName()) + EventLog.Type.ConferenceParticipantDeviceAdded -> context.getString( + R.string.chat_event_device_added + ).format(getName()) + EventLog.Type.ConferenceParticipantDeviceRemoved -> context.getString( + R.string.chat_event_device_removed + ).format(getName()) EventLog.Type.ConferenceSecurityEvent -> { val name = getName() when (eventLog.securityEventType) { - EventLog.SecurityEventType.EncryptionIdentityKeyChanged -> context.getString(R.string.chat_security_event_lime_identity_key_changed).format(name) - EventLog.SecurityEventType.ManInTheMiddleDetected -> context.getString(R.string.chat_security_event_man_in_the_middle_detected).format(name) - EventLog.SecurityEventType.SecurityLevelDowngraded -> context.getString(R.string.chat_security_event_security_level_downgraded).format(name) - EventLog.SecurityEventType.ParticipantMaxDeviceCountExceeded -> context.getString(R.string.chat_security_event_participant_max_count_exceeded).format(name) + EventLog.SecurityEventType.EncryptionIdentityKeyChanged -> context.getString( + R.string.chat_security_event_lime_identity_key_changed + ).format(name) + EventLog.SecurityEventType.ManInTheMiddleDetected -> context.getString( + R.string.chat_security_event_man_in_the_middle_detected + ).format(name) + EventLog.SecurityEventType.SecurityLevelDowngraded -> context.getString( + R.string.chat_security_event_security_level_downgraded + ).format(name) + EventLog.SecurityEventType.ParticipantMaxDeviceCountExceeded -> context.getString( + R.string.chat_security_event_participant_max_count_exceeded + ).format(name) else -> "Unexpected security event for $name: ${eventLog.securityEventType}" } } - EventLog.Type.ConferenceEphemeralMessageDisabled -> context.getString(R.string.chat_event_ephemeral_disabled) - EventLog.Type.ConferenceEphemeralMessageEnabled -> context.getString(R.string.chat_event_ephemeral_enabled).format(formatEphemeralExpiration(context, eventLog.ephemeralMessageLifetime)) - EventLog.Type.ConferenceEphemeralMessageLifetimeChanged -> context.getString(R.string.chat_event_ephemeral_lifetime_changed).format(formatEphemeralExpiration(context, eventLog.ephemeralMessageLifetime)) + EventLog.Type.ConferenceEphemeralMessageDisabled -> context.getString( + R.string.chat_event_ephemeral_disabled + ) + EventLog.Type.ConferenceEphemeralMessageEnabled -> context.getString( + R.string.chat_event_ephemeral_enabled + ).format(formatEphemeralExpiration(context, eventLog.ephemeralMessageLifetime)) + EventLog.Type.ConferenceEphemeralMessageLifetimeChanged -> context.getString( + R.string.chat_event_ephemeral_lifetime_changed + ).format(formatEphemeralExpiration(context, eventLog.ephemeralMessageLifetime)) else -> "Unexpected event: ${eventLog.type}" } } diff --git a/app/src/main/java/org/linphone/activities/main/chat/data/GroupInfoParticipantData.kt b/app/src/main/java/org/linphone/activities/main/chat/data/GroupInfoParticipantData.kt index ffd9248a8..adfb37949 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/data/GroupInfoParticipantData.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/data/GroupInfoParticipantData.kt @@ -26,7 +26,9 @@ import org.linphone.contact.GenericContactData import org.linphone.core.ChatRoomSecurityLevel import org.linphone.utils.LinphoneUtils -class GroupInfoParticipantData(val participant: GroupChatRoomMember) : GenericContactData(participant.address) { +class GroupInfoParticipantData(val participant: GroupChatRoomMember) : GenericContactData( + participant.address +) { val sipUri: String get() = LinphoneUtils.getDisplayableAddress(participant.address) val isAdmin = MutableLiveData() diff --git a/app/src/main/java/org/linphone/activities/main/chat/data/ImdnParticipantData.kt b/app/src/main/java/org/linphone/activities/main/chat/data/ImdnParticipantData.kt index 5446b9243..4d93970c3 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/data/ImdnParticipantData.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/data/ImdnParticipantData.kt @@ -23,7 +23,9 @@ import org.linphone.contact.GenericContactData import org.linphone.core.ParticipantImdnState import org.linphone.utils.TimestampUtils -class ImdnParticipantData(val imdnState: ParticipantImdnState) : GenericContactData(imdnState.participant.address) { +class ImdnParticipantData(val imdnState: ParticipantImdnState) : GenericContactData( + imdnState.participant.address +) { val sipUri: String = imdnState.participant.address.asStringUriOnly() val time: String = TimestampUtils.toString(imdnState.stateChangeTime) diff --git a/app/src/main/java/org/linphone/activities/main/chat/fragments/ChatRoomCreationFragment.kt b/app/src/main/java/org/linphone/activities/main/chat/fragments/ChatRoomCreationFragment.kt index 2d086f796..52225b074 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/fragments/ChatRoomCreationFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/fragments/ChatRoomCreationFragment.kt @@ -70,7 +70,9 @@ class ChatRoomCreationFragment : SecureFragment binding.contactsList.layoutManager = layoutManager // Divider between items - binding.contactsList.addItemDecoration(AppUtils.getDividerDecoration(requireContext(), layoutManager)) + binding.contactsList.addItemDecoration( + AppUtils.getDividerDecoration(requireContext(), layoutManager) + ) binding.back.visibility = if (resources.getBoolean(R.bool.isTablet)) View.INVISIBLE else View.VISIBLE diff --git a/app/src/main/java/org/linphone/activities/main/chat/fragments/DetailChatRoomFragment.kt b/app/src/main/java/org/linphone/activities/main/chat/fragments/DetailChatRoomFragment.kt index f09d1f85b..ad07ce7e2 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/fragments/DetailChatRoomFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/fragments/DetailChatRoomFragment.kt @@ -85,7 +85,9 @@ class DetailChatRoomFragment : MasterFragment if (keyboardVisible && chatSendingViewModel.isEmojiPickerOpen.value == true) { - Log.d("[Chat Room] Emoji picker is opened, closing it because keyboard is now visible") + Log.d( + "[Chat Room] Emoji picker is opened, closing it because keyboard is now visible" + ) chatSendingViewModel.isEmojiPickerOpen.value = false } } @@ -275,12 +293,18 @@ class DetailChatRoomFragment : MasterFragment { if (content.isFileEncrypted) { - Log.w("[Chat Room] File is encrypted and can't be opened in one of our viewers...") + Log.w( + "[Chat Room] File is encrypted and can't be opened in one of our viewers..." + ) showDialogForUserConsentBeforeExportingFileInThirdPartyApp( content ) @@ -570,7 +604,9 @@ class DetailChatRoomFragment : MasterFragment if (eventLog.eventLog.type == EventLog.Type.ConferenceChatMessage) { (eventLog.data as ChatMessageData).chatMessage.messageId == chatMessage.messageId - } else false + } else { + false + } } index = events.indexOf(eventLog) if (index == -1) { @@ -632,7 +668,7 @@ class DetailChatRoomFragment : MasterFragment + _, _ -> val clipboard: ClipboardManager = coreContext.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText("Chat room info", message) @@ -662,17 +698,25 @@ class DetailChatRoomFragment : MasterFragment { - Log.i("[Chat Room] Start recording voice message as long as recording button is held") + Log.i( + "[Chat Room] Start recording voice message as long as recording button is held" + ) chatSendingViewModel.startVoiceRecording() } MotionEvent.ACTION_UP -> { val voiceRecordingDuration = chatSendingViewModel.voiceRecordingDuration.value ?: 0 if (voiceRecordingDuration < 1000) { - Log.w("[Chat Room] Voice recording button has been held for less than a second, considering miss click") + Log.w( + "[Chat Room] Voice recording button has been held for less than a second, considering miss click" + ) chatSendingViewModel.cancelVoiceRecording() - (activity as MainActivity).showSnackBar(R.string.chat_message_voice_recording_hold_to_record) + (activity as MainActivity).showSnackBar( + R.string.chat_message_voice_recording_hold_to_record + ) } else { - Log.i("[Chat Room] Voice recording button has been released, stop recording") + Log.i( + "[Chat Room] Voice recording button has been released, stop recording" + ) chatSendingViewModel.stopVoiceRecording() } view.performClick() @@ -712,7 +756,9 @@ class DetailChatRoomFragment : MasterFragment if (doNotAskAgain) corePreferences.limeSecurityPopupEnabled = false @@ -921,7 +973,9 @@ class DetailChatRoomFragment : MasterFragment() { binding.participants.layoutManager = layoutManager // Divider between items - binding.participants.addItemDecoration(AppUtils.getDividerDecoration(requireContext(), layoutManager)) + binding.participants.addItemDecoration( + AppUtils.getDividerDecoration(requireContext(), layoutManager) + ) viewModel.participants.observe( viewLifecycleOwner @@ -148,7 +150,9 @@ class GroupInfoFragment : SecureFragment() { } binding.setLeaveClickListener { - val dialogViewModel = DialogViewModel(getString(R.string.chat_room_group_info_leave_dialog_message)) + val dialogViewModel = DialogViewModel( + getString(R.string.chat_room_group_info_leave_dialog_message) + ) val dialog: Dialog = DialogUtils.getDialog(requireContext(), dialogViewModel) dialogViewModel.showDeleteButton( @@ -190,7 +194,11 @@ class GroupInfoFragment : SecureFragment() { } else { list.add( GroupInfoParticipantData( - GroupChatRoomMember(address, false, hasLimeX3DHCapability = viewModel.isEncrypted.value == true) + GroupChatRoomMember( + address, + false, + hasLimeX3DHCapability = viewModel.isEncrypted.value == true + ) ) ) } diff --git a/app/src/main/java/org/linphone/activities/main/chat/fragments/ImdnFragment.kt b/app/src/main/java/org/linphone/activities/main/chat/fragments/ImdnFragment.kt index 9f2e0b2aa..adadf75f5 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/fragments/ImdnFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/fragments/ImdnFragment.kt @@ -84,7 +84,9 @@ class ImdnFragment : SecureFragment() { binding.participantsList.layoutManager = layoutManager // Divider between items - binding.participantsList.addItemDecoration(AppUtils.getDividerDecoration(requireContext(), layoutManager)) + binding.participantsList.addItemDecoration( + AppUtils.getDividerDecoration(requireContext(), layoutManager) + ) // Displays state header val headerItemDecoration = RecyclerViewHeaderDecoration(requireContext(), adapter) diff --git a/app/src/main/java/org/linphone/activities/main/chat/fragments/MasterChatRoomsFragment.kt b/app/src/main/java/org/linphone/activities/main/chat/fragments/MasterChatRoomsFragment.kt index c215500e7..1e0b468bd 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/fragments/MasterChatRoomsFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/fragments/MasterChatRoomsFragment.kt @@ -133,7 +133,9 @@ class MasterChatRoomsFragment : MasterFragment= maxVoiceRecordDuration) { - Log.w("[Chat Message Sending] Max duration for voice recording exceeded (${maxVoiceRecordDuration}ms), stopping.") + Log.w( + "[Chat Message Sending] Max duration for voice recording exceeded (${maxVoiceRecordDuration}ms), stopping." + ) stopVoiceRecording() } } @@ -463,7 +474,11 @@ class ChatMessageSendingViewModel(private val chatRoom: ChatRoom) : ViewModel() } if (AppUtils.isMediaVolumeLow(coreContext.context)) { - Toast.makeText(coreContext.context, R.string.chat_message_voice_recording_playback_low_volume, Toast.LENGTH_LONG).show() + Toast.makeText( + coreContext.context, + R.string.chat_message_voice_recording_playback_low_volume, + Toast.LENGTH_LONG + ).show() } if (voiceRecordAudioFocusRequest == null) { @@ -508,7 +523,9 @@ class ChatMessageSendingViewModel(private val chatRoom: ChatRoom) : ViewModel() val recordingAudioDevice = AudioRouteUtils.getAudioRecordingDeviceForVoiceMessage() recorderParams.audioDevice = recordingAudioDevice - Log.i("[Chat Message Sending] Using device ${recorderParams.audioDevice?.id} to make the voice message recording") + Log.i( + "[Chat Message Sending] Using device ${recorderParams.audioDevice?.id} to make the voice message recording" + ) recorder = coreContext.core.createRecorder(recorderParams) } @@ -517,7 +534,9 @@ class ChatMessageSendingViewModel(private val chatRoom: ChatRoom) : ViewModel() Log.i("[Chat Message Sending] Creating player for voice record") val playbackSoundCard = AudioRouteUtils.getAudioPlaybackDeviceIdForCallRecordingOrVoiceMessage() - Log.i("[Chat Message Sending] Using device $playbackSoundCard to make the voice message playback") + Log.i( + "[Chat Message Sending] Using device $playbackSoundCard to make the voice message playback" + ) val localPlayer = coreContext.core.createLocalPlayer(playbackSoundCard, null, null) if (localPlayer != null) { @@ -559,6 +578,10 @@ class ChatMessageSendingViewModel(private val chatRoom: ChatRoom) : ViewModel() } private fun updateChatRoomReadOnlyState() { - isReadOnly.value = chatRoom.isReadOnly || (chatRoom.hasCapability(ChatRoomCapabilities.Conference.toInt()) && chatRoom.participants.isEmpty()) + isReadOnly.value = chatRoom.isReadOnly || ( + chatRoom.hasCapability( + ChatRoomCapabilities.Conference.toInt() + ) && chatRoom.participants.isEmpty() + ) } } diff --git a/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatMessagesListViewModel.kt b/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatMessagesListViewModel.kt index 2b842a069..976ba5880 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatMessagesListViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatMessagesListViewModel.kt @@ -107,7 +107,9 @@ class ChatMessagesListViewModel(private val chatRoom: ChatRoom) : ViewModel() { } override fun onEphemeralMessageDeleted(chatRoom: ChatRoom, eventLog: EventLog) { - Log.i("[Chat Messages] An ephemeral chat message has expired, removing it from event list") + Log.i( + "[Chat Messages] An ephemeral chat message has expired, removing it from event list" + ) deleteEvent(eventLog) } @@ -163,7 +165,10 @@ class ChatMessagesListViewModel(private val chatRoom: ChatRoom) : ViewModel() { upperBound = maxSize } - val history: Array = chatRoom.getHistoryRangeEvents(totalItemsCount, upperBound) + val history: Array = chatRoom.getHistoryRangeEvents( + totalItemsCount, + upperBound + ) val list = arrayListOf() for (eventLog in history) { list.add(EventLogData(eventLog)) @@ -187,7 +192,9 @@ class ChatMessagesListViewModel(private val chatRoom: ChatRoom) : ViewModel() { val list = arrayListOf() val unreadCount = chatRoom.unreadMessagesCount var loadCount = max(MESSAGES_PER_PAGE, unreadCount) - Log.i("[Chat Messages] $unreadCount unread messages in this chat room, loading $loadCount from history") + Log.i( + "[Chat Messages] $unreadCount unread messages in this chat room, loading $loadCount from history" + ) val history = chatRoom.getHistoryEvents(loadCount) var messageCount = 0 @@ -200,8 +207,13 @@ class ChatMessagesListViewModel(private val chatRoom: ChatRoom) : ViewModel() { // Load enough events to have at least all unread messages while (unreadCount > 0 && messageCount < unreadCount) { - Log.w("[Chat Messages] There is only $messageCount messages in the last $loadCount events, loading $MESSAGES_PER_PAGE more") - val moreHistory = chatRoom.getHistoryRangeEvents(loadCount, loadCount + MESSAGES_PER_PAGE) + Log.w( + "[Chat Messages] There is only $messageCount messages in the last $loadCount events, loading $MESSAGES_PER_PAGE more" + ) + val moreHistory = chatRoom.getHistoryRangeEvents( + loadCount, + loadCount + MESSAGES_PER_PAGE + ) loadCount += MESSAGES_PER_PAGE for (eventLog in moreHistory) { list.add(EventLogData(eventLog)) @@ -235,14 +247,18 @@ class ChatMessagesListViewModel(private val chatRoom: ChatRoom) : ViewModel() { data.eventLog.type == EventLog.Type.ConferenceChatMessage && data.eventLog.chatMessage?.messageId == chatMessage.messageId } if (existingEvent != null) { - Log.w("[Chat Messages] Found already present chat message, don't add it it's probably the result of an auto download or an aggregated message received before but notified after the conversation was displayed") + Log.w( + "[Chat Messages] Found already present chat message, don't add it it's probably the result of an auto download or an aggregated message received before but notified after the conversation was displayed" + ) return } if (!PermissionHelper.get().hasWriteExternalStoragePermission()) { for (content in chatMessage.contents) { if (content.isFileTransfer) { - Log.i("[Chat Messages] Android < 10 detected and WRITE_EXTERNAL_STORAGE permission isn't granted yet") + Log.i( + "[Chat Messages] Android < 10 detected and WRITE_EXTERNAL_STORAGE permission isn't granted yet" + ) requestWriteExternalStoragePermissionEvent.value = Event(true) } } diff --git a/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatRoomCreationViewModel.kt b/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatRoomCreationViewModel.kt index 579911067..d6ea68369 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatRoomCreationViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatRoomCreationViewModel.kt @@ -68,7 +68,9 @@ class ChatRoomCreationViewModel : ContactsSelectionViewModel() { fun updateEncryption(encrypted: Boolean) { if (!encrypted && secureChatMandatory) { - Log.w("[Chat Room Creation] Something tries to force plain text chat room even if secureChatMandatory is enabled!") + Log.w( + "[Chat Room Creation] Something tries to force plain text chat room even if secureChatMandatory is enabled!" + ) return } isEncrypted.value = encrypted @@ -79,7 +81,10 @@ class ChatRoomCreationViewModel : ContactsSelectionViewModel() { val defaultAccount = coreContext.core.defaultAccount var room: ChatRoom? - val address = searchResult.address ?: coreContext.core.interpretUrl(searchResult.phoneNumber ?: "", LinphoneUtils.applyInternationalPrefix()) + val address = searchResult.address ?: coreContext.core.interpretUrl( + searchResult.phoneNumber ?: "", + LinphoneUtils.applyInternationalPrefix() + ) if (address == null) { Log.e("[Chat Room Creation] Can't get a valid address from search result $searchResult") onMessageToNotifyEvent.value = Event(R.string.chat_room_creation_failed_snack) @@ -94,12 +99,15 @@ class ChatRoomCreationViewModel : ContactsSelectionViewModel() { if (encrypted) { params.isEncryptionEnabled = true params.backend = ChatRoomBackend.FlexisipChat - params.ephemeralMode = if (corePreferences.useEphemeralPerDeviceMode) + params.ephemeralMode = if (corePreferences.useEphemeralPerDeviceMode) { ChatRoomEphemeralMode.DeviceManaged - else + } else { ChatRoomEphemeralMode.AdminManaged + } params.ephemeralLifetime = 0 // Make sure ephemeral is disabled by default - Log.i("[Chat Room Creation] Ephemeral mode is ${params.ephemeralMode}, lifetime is ${params.ephemeralLifetime}") + Log.i( + "[Chat Room Creation] Ephemeral mode is ${params.ephemeralMode}, lifetime is ${params.ephemeralLifetime}" + ) params.subject = AppUtils.getString(R.string.chat_room_dummy_subject) } @@ -108,7 +116,9 @@ class ChatRoomCreationViewModel : ContactsSelectionViewModel() { room = coreContext.core.searchChatRoom(params, localAddress, null, participants) if (room == null) { - Log.w("[Chat Room Creation] Couldn't find existing 1-1 chat room with remote ${address.asStringUriOnly()}, encryption=$encrypted and local identity ${localAddress?.asStringUriOnly()}") + Log.w( + "[Chat Room Creation] Couldn't find existing 1-1 chat room with remote ${address.asStringUriOnly()}, encryption=$encrypted and local identity ${localAddress?.asStringUriOnly()}" + ) room = coreContext.core.createChatRoom(params, localAddress, participants) if (room != null) { @@ -119,7 +129,9 @@ class ChatRoomCreationViewModel : ContactsSelectionViewModel() { chatRoomCreatedEvent.value = Event(room) waitForChatRoomCreation.value = false } else { - Log.i("[Chat Room Creation] Chat room creation is pending [$state], waiting for Created state") + Log.i( + "[Chat Room Creation] Chat room creation is pending [$state], waiting for Created state" + ) room.addListener(listener) } } else { @@ -127,11 +139,15 @@ class ChatRoomCreationViewModel : ContactsSelectionViewModel() { waitForChatRoomCreation.value = false } } else { - Log.e("[Chat Room Creation] Couldn't create chat room with remote ${address.asStringUriOnly()} and local identity ${localAddress?.asStringUriOnly()}") + Log.e( + "[Chat Room Creation] Couldn't create chat room with remote ${address.asStringUriOnly()} and local identity ${localAddress?.asStringUriOnly()}" + ) waitForChatRoomCreation.value = false } } else { - Log.i("[Chat Room Creation] Found existing 1-1 chat room with remote ${address.asStringUriOnly()}, encryption=$encrypted and local identity ${localAddress?.asStringUriOnly()}") + Log.i( + "[Chat Room Creation] Found existing 1-1 chat room with remote ${address.asStringUriOnly()}, encryption=$encrypted and local identity ${localAddress?.asStringUriOnly()}" + ) chatRoomCreatedEvent.value = Event(room) waitForChatRoomCreation.value = false } diff --git a/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatRoomViewModel.kt b/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatRoomViewModel.kt index 0c5794f6f..e1f3c9ee6 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatRoomViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatRoomViewModel.kt @@ -111,7 +111,10 @@ class ChatRoomViewModel(val chatRoom: ChatRoom) : ViewModel(), ContactDataInterf private var addressToCall: Address? = null private val bounceAnimator: ValueAnimator by lazy { - ValueAnimator.ofFloat(AppUtils.getDimension(R.dimen.tabs_fragment_unread_count_bounce_offset), 0f).apply { + ValueAnimator.ofFloat( + AppUtils.getDimension(R.dimen.tabs_fragment_unread_count_bounce_offset), + 0f + ).apply { addUpdateListener { val value = it.animatedValue as Float chatUnreadCountTranslateY.value = value @@ -265,11 +268,11 @@ class ChatRoomViewModel(val chatRoom: ChatRoom) : ViewModel(), ContactDataInterf val localAddress = chatRoom.localAddress.clone() localAddress.clean() // Remove GRUU val addresses = Array(chatRoom.participants.size) { - index -> + index -> chatRoom.participants[index].address } val localAccount = coreContext.core.accountList.find { - account -> + account -> account.params.identityAddress?.weakEqual(localAddress) ?: false } @@ -298,7 +301,9 @@ class ChatRoomViewModel(val chatRoom: ChatRoom) : ViewModel(), ContactDataInterf if (chatRoom.participants.isNotEmpty()) { chatRoom.participants[0].address } else { - Log.e("[Chat Room] ${chatRoom.peerAddress} doesn't have any participant (state ${chatRoom.state})!") + Log.e( + "[Chat Room] ${chatRoom.peerAddress} doesn't have any participant (state ${chatRoom.state})!" + ) null } } @@ -338,11 +343,18 @@ class ChatRoomViewModel(val chatRoom: ChatRoom) : ViewModel(), ContactDataInterf } TimestampUtils.isYesterday(timestamp) -> { val time = TimestampUtils.timeToString(timestamp, timestampInSecs = true) - val text = AppUtils.getString(R.string.chat_room_presence_last_seen_online_yesterday) + val text = AppUtils.getString( + R.string.chat_room_presence_last_seen_online_yesterday + ) "$text $time" } else -> { - val date = TimestampUtils.toString(timestamp, onlyDate = true, shortDate = false, hideYear = true) + val date = TimestampUtils.toString( + timestamp, + onlyDate = true, + shortDate = false, + hideYear = true + ) val text = AppUtils.getString(R.string.chat_room_presence_last_seen_online) "$text $date" } @@ -390,7 +402,11 @@ class ChatRoomViewModel(val chatRoom: ChatRoom) : ViewModel(), ContactDataInterf composing += if (composing.isNotEmpty()) ", " else "" composing += contact?.name ?: LinphoneUtils.getDisplayName(address) } - composingList.value = AppUtils.getStringWithPlural(R.plurals.chat_room_remote_composing, chatRoom.composingAddresses.size, composing) + composingList.value = AppUtils.getStringWithPlural( + R.plurals.chat_room_remote_composing, + chatRoom.composingAddresses.size, + composing + ) } private fun updateParticipants() { @@ -400,10 +416,11 @@ class ChatRoomViewModel(val chatRoom: ChatRoom) : ViewModel(), ContactDataInterf chatRoom.me?.devices?.size == 1 && participants.firstOrNull()?.devices?.size == 1 - addressToCall = if (basicChatRoom) + addressToCall = if (basicChatRoom) { chatRoom.peerAddress - else + } else { participants.firstOrNull()?.address + } onlyParticipantOnlyDeviceAddress = participants.firstOrNull()?.devices?.firstOrNull()?.address } @@ -411,7 +428,8 @@ class ChatRoomViewModel(val chatRoom: ChatRoom) : ViewModel(), ContactDataInterf private fun updateUnreadMessageCount() { val count = chatRoom.unreadMessagesCount unreadMessagesCount.value = count - if (count > 0 && corePreferences.enableAnimations) bounceAnimator.start() - else if (count == 0 && bounceAnimator.isStarted) bounceAnimator.end() + if (count > 0 && corePreferences.enableAnimations) { + bounceAnimator.start() + } else if (count == 0 && bounceAnimator.isStarted) bounceAnimator.end() } } diff --git a/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatRoomsListViewModel.kt b/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatRoomsListViewModel.kt index 664e4e125..7f3915a7a 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatRoomsListViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ChatRoomsListViewModel.kt @@ -48,7 +48,9 @@ class ChatRoomsListViewModel : MessageNotifierViewModel() { private val chatRoomListener = object : ChatRoomListenerStub() { override fun onStateChanged(chatRoom: ChatRoom, newState: ChatRoom.State) { if (newState == ChatRoom.State.Deleted) { - Log.i("[Chat Rooms] Chat room [${LinphoneUtils.getChatRoomId(chatRoom)}] is in Deleted state, removing it from list") + Log.i( + "[Chat Rooms] Chat room [${LinphoneUtils.getChatRoomId(chatRoom)}] is in Deleted state, removing it from list" + ) val list = arrayListOf() val id = LinphoneUtils.getChatRoomId(chatRoom) for (data in chatRooms.value.orEmpty()) { @@ -64,14 +66,18 @@ class ChatRoomsListViewModel : MessageNotifierViewModel() { private val listener: CoreListenerStub = object : CoreListenerStub() { override fun onChatRoomStateChanged(core: Core, chatRoom: ChatRoom, state: ChatRoom.State) { if (state == ChatRoom.State.Created) { - Log.i("[Chat Rooms] Chat room [${LinphoneUtils.getChatRoomId(chatRoom)}] is in Created state, adding it to list") + Log.i( + "[Chat Rooms] Chat room [${LinphoneUtils.getChatRoomId(chatRoom)}] is in Created state, adding it to list" + ) val data = ChatRoomData(chatRoom) val list = arrayListOf() list.add(data) list.addAll(chatRooms.value.orEmpty()) chatRooms.value = list } else if (state == ChatRoom.State.TerminationFailed) { - Log.e("[Chat Rooms] Group chat room removal for address ${chatRoom.peerAddress.asStringUriOnly()} has failed !") + Log.e( + "[Chat Rooms] Group chat room removal for address ${chatRoom.peerAddress.asStringUriOnly()} has failed !" + ) onMessageToNotifyEvent.value = Event(R.string.chat_room_removal_failed_snack) } } @@ -155,8 +161,11 @@ class ChatRoomsListViewModel : MessageNotifierViewModel() { fun notifyChatRoomUpdate(chatRoom: ChatRoom) { val index = findChatRoomIndex(chatRoom) - if (index == -1) updateChatRooms() - else chatRoomIndexUpdatedEvent.value = Event(index) + if (index == -1) { + updateChatRooms() + } else { + chatRoomIndexUpdatedEvent.value = Event(index) + } } private fun reorderChatRooms() { diff --git a/app/src/main/java/org/linphone/activities/main/chat/viewmodels/EphemeralViewModel.kt b/app/src/main/java/org/linphone/activities/main/chat/viewmodels/EphemeralViewModel.kt index ce56f8034..22da304cf 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/viewmodels/EphemeralViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/viewmodels/EphemeralViewModel.kt @@ -50,7 +50,9 @@ class EphemeralViewModel(private val chatRoom: ChatRoom) : ViewModel() { } init { - Log.i("[Ephemeral Messages] Current lifetime is ${chatRoom.ephemeralLifetime}, ephemeral enabled? ${chatRoom.isEphemeralEnabled}") + Log.i( + "[Ephemeral Messages] Current lifetime is ${chatRoom.ephemeralLifetime}, ephemeral enabled? ${chatRoom.isEphemeralEnabled}" + ) currentSelectedDuration = if (chatRoom.isEphemeralEnabled) chatRoom.ephemeralLifetime else 0 computeEphemeralDurationValues() } @@ -59,10 +61,14 @@ class EphemeralViewModel(private val chatRoom: ChatRoom) : ViewModel() { Log.i("[Ephemeral Messages] Selected value is $currentSelectedDuration") if (currentSelectedDuration > 0) { if (chatRoom.ephemeralLifetime != currentSelectedDuration) { - Log.i("[Ephemeral Messages] Setting new lifetime for ephemeral messages to $currentSelectedDuration") + Log.i( + "[Ephemeral Messages] Setting new lifetime for ephemeral messages to $currentSelectedDuration" + ) chatRoom.ephemeralLifetime = currentSelectedDuration } else { - Log.i("[Ephemeral Messages] Configured lifetime for ephemeral messages was already $currentSelectedDuration") + Log.i( + "[Ephemeral Messages] Configured lifetime for ephemeral messages was already $currentSelectedDuration" + ) } if (!chatRoom.isEphemeralEnabled) { @@ -77,12 +83,54 @@ class EphemeralViewModel(private val chatRoom: ChatRoom) : ViewModel() { private fun computeEphemeralDurationValues() { val list = arrayListOf() - list.add(EphemeralDurationData(R.string.chat_room_ephemeral_message_disabled, currentSelectedDuration, 0, listener)) - list.add(EphemeralDurationData(R.string.chat_room_ephemeral_message_one_minute, currentSelectedDuration, 60, listener)) - list.add(EphemeralDurationData(R.string.chat_room_ephemeral_message_one_hour, currentSelectedDuration, 3600, listener)) - list.add(EphemeralDurationData(R.string.chat_room_ephemeral_message_one_day, currentSelectedDuration, 86400, listener)) - list.add(EphemeralDurationData(R.string.chat_room_ephemeral_message_three_days, currentSelectedDuration, 259200, listener)) - list.add(EphemeralDurationData(R.string.chat_room_ephemeral_message_one_week, currentSelectedDuration, 604800, listener)) + list.add( + EphemeralDurationData( + R.string.chat_room_ephemeral_message_disabled, + currentSelectedDuration, + 0, + listener + ) + ) + list.add( + EphemeralDurationData( + R.string.chat_room_ephemeral_message_one_minute, + currentSelectedDuration, + 60, + listener + ) + ) + list.add( + EphemeralDurationData( + R.string.chat_room_ephemeral_message_one_hour, + currentSelectedDuration, + 3600, + listener + ) + ) + list.add( + EphemeralDurationData( + R.string.chat_room_ephemeral_message_one_day, + currentSelectedDuration, + 86400, + listener + ) + ) + list.add( + EphemeralDurationData( + R.string.chat_room_ephemeral_message_three_days, + currentSelectedDuration, + 259200, + listener + ) + ) + list.add( + EphemeralDurationData( + R.string.chat_room_ephemeral_message_one_week, + currentSelectedDuration, + 604800, + listener + ) + ) durationsList.value = list } } diff --git a/app/src/main/java/org/linphone/activities/main/chat/viewmodels/GroupInfoViewModel.kt b/app/src/main/java/org/linphone/activities/main/chat/viewmodels/GroupInfoViewModel.kt index e308ec32e..9084e6899 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/viewmodels/GroupInfoViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/viewmodels/GroupInfoViewModel.kt @@ -99,7 +99,9 @@ class GroupInfoViewModel(val chatRoom: ChatRoom?) : MessageNotifierViewModel() { subject.value = chatRoom?.subject isMeAdmin.value = chatRoom == null || (chatRoom.me?.isAdmin == true && !chatRoom.isReadOnly) canLeaveGroup.value = chatRoom != null && !chatRoom.isReadOnly - isEncrypted.value = corePreferences.forceEndToEndEncryptedChat || chatRoom?.hasCapability(ChatRoomCapabilities.Encrypted.toInt()) == true + isEncrypted.value = corePreferences.forceEndToEndEncryptedChat || chatRoom?.hasCapability( + ChatRoomCapabilities.Encrypted.toInt() + ) == true if (chatRoom != null) updateParticipants() @@ -120,13 +122,16 @@ class GroupInfoViewModel(val chatRoom: ChatRoom?) : MessageNotifierViewModel() { params.isEncryptionEnabled = corePreferences.forceEndToEndEncryptedChat || isEncrypted.value == true params.isGroupEnabled = true if (params.isEncryptionEnabled) { - params.ephemeralMode = if (corePreferences.useEphemeralPerDeviceMode) + params.ephemeralMode = if (corePreferences.useEphemeralPerDeviceMode) { ChatRoomEphemeralMode.DeviceManaged - else + } else { ChatRoomEphemeralMode.AdminManaged + } } params.ephemeralLifetime = 0 // Make sure ephemeral is disabled by default - Log.i("[Chat Room Group Info] Ephemeral mode is ${params.ephemeralMode}, lifetime is ${params.ephemeralLifetime}") + Log.i( + "[Chat Room Group Info] Ephemeral mode is ${params.ephemeralMode}, lifetime is ${params.ephemeralLifetime}" + ) params.subject = subject.value val addresses = arrayOfNulls
(participants.value.orEmpty().size) @@ -137,7 +142,11 @@ class GroupInfoViewModel(val chatRoom: ChatRoom?) : MessageNotifierViewModel() { index += 1 } - val chatRoom: ChatRoom? = coreContext.core.createChatRoom(params, coreContext.core.defaultAccount?.params?.identityAddress, addresses) + val chatRoom: ChatRoom? = coreContext.core.createChatRoom( + params, + coreContext.core.defaultAccount?.params?.identityAddress, + addresses + ) chatRoom?.addListener(listener) if (chatRoom == null) { Log.e("[Chat Room Group Info] Couldn't create chat room!") @@ -162,7 +171,9 @@ class GroupInfoViewModel(val chatRoom: ChatRoom?) : MessageNotifierViewModel() { participant.address.weakEqual(member.participant.address) } if (member == null) { - Log.w("[Chat Room Group Info] Participant ${participant.address.asStringUriOnly()} will be removed from group") + Log.w( + "[Chat Room Group Info] Participant ${participant.address.asStringUriOnly()} will be removed from group" + ) participantsToRemove.add(participant) } } @@ -180,12 +191,19 @@ class GroupInfoViewModel(val chatRoom: ChatRoom?) : MessageNotifierViewModel() { // Participant found, check if admin status needs to be updated if (member.participant.isAdmin != participant.isAdmin) { if (chatRoom.me?.isAdmin == true) { - Log.i("[Chat Room Group Info] Participant ${member.sipUri} will be admin? ${member.isAdmin}") - chatRoom.setParticipantAdminStatus(participant, member.participant.isAdmin) + Log.i( + "[Chat Room Group Info] Participant ${member.sipUri} will be admin? ${member.isAdmin}" + ) + chatRoom.setParticipantAdminStatus( + participant, + member.participant.isAdmin + ) } } } else { - Log.i("[Chat Room Group Info] Participant ${member.sipUri} will be added to group") + Log.i( + "[Chat Room Group Info] Participant ${member.sipUri} will be added to group" + ) participantsToAdd.add(member.participant.address) } } @@ -223,7 +241,12 @@ class GroupInfoViewModel(val chatRoom: ChatRoom?) : MessageNotifierViewModel() { for (participant in chatRoom.participants) { list.add( GroupInfoParticipantData( - GroupChatRoomMember(participant.address, participant.isAdmin, participant.securityLevel, canBeSetAdmin = true) + GroupChatRoomMember( + participant.address, + participant.isAdmin, + participant.securityLevel, + canBeSetAdmin = true + ) ) ) } diff --git a/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ImdnViewModel.kt b/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ImdnViewModel.kt index d5595d240..2b9c72593 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ImdnViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/viewmodels/ImdnViewModel.kt @@ -68,7 +68,9 @@ class ImdnViewModel(private val chatMessage: ChatMessage) : ViewModel() { for (participant in chatMessage.getParticipantsByImdnState(ChatMessage.State.Displayed)) { list.add(ImdnParticipantData(participant)) } - for (participant in chatMessage.getParticipantsByImdnState(ChatMessage.State.DeliveredToUser)) { + for (participant in chatMessage.getParticipantsByImdnState( + ChatMessage.State.DeliveredToUser + )) { list.add(ImdnParticipantData(participant)) } for (participant in chatMessage.getParticipantsByImdnState(ChatMessage.State.Delivered)) { diff --git a/app/src/main/java/org/linphone/activities/main/chat/views/RichEditText.kt b/app/src/main/java/org/linphone/activities/main/chat/views/RichEditText.kt index aa44cfc5c..48662b95b 100644 --- a/app/src/main/java/org/linphone/activities/main/chat/views/RichEditText.kt +++ b/app/src/main/java/org/linphone/activities/main/chat/views/RichEditText.kt @@ -62,7 +62,8 @@ class RichEditText : AppCompatEditText { private fun initReceiveContentListener() { ViewCompat.setOnReceiveContentListener( - this, RichContentReceiver.MIME_TYPES, + this, + RichContentReceiver.MIME_TYPES, RichContentReceiver { uri -> Log.i("[Rich Edit Text] Received URI: $uri") val activity = context as Activity diff --git a/app/src/main/java/org/linphone/activities/main/conference/adapters/ScheduledConferencesAdapter.kt b/app/src/main/java/org/linphone/activities/main/conference/adapters/ScheduledConferencesAdapter.kt index 8784ff34a..2d02ed599 100644 --- a/app/src/main/java/org/linphone/activities/main/conference/adapters/ScheduledConferencesAdapter.kt +++ b/app/src/main/java/org/linphone/activities/main/conference/adapters/ScheduledConferencesAdapter.kt @@ -41,7 +41,10 @@ import org.linphone.utils.TimestampUtils class ScheduledConferencesAdapter( selectionVM: ListTopBarViewModel, private val viewLifecycleOwner: LifecycleOwner -) : SelectionListAdapter(selectionVM, ConferenceInfoDiffCallback()), +) : SelectionListAdapter( + selectionVM, + ConferenceInfoDiffCallback() +), HeaderAdapter { val copyAddressToClipboardEvent: MutableLiveData> by lazy { MutableLiveData>() @@ -62,7 +65,9 @@ class ScheduledConferencesAdapter( override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ScheduledConferencesAdapter.ViewHolder { val binding: ConferenceScheduleCellBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), - R.layout.conference_schedule_cell, parent, false + R.layout.conference_schedule_cell, + parent, + false ) return ViewHolder(binding) } @@ -77,15 +82,22 @@ class ScheduledConferencesAdapter( val previousPosition = position - 1 return if (previousPosition >= 0) { val previousItem = getItem(previousPosition) - !TimestampUtils.isSameDay(previousItem.conferenceInfo.dateTime, conferenceInfo.conferenceInfo.dateTime) - } else true + !TimestampUtils.isSameDay( + previousItem.conferenceInfo.dateTime, + conferenceInfo.conferenceInfo.dateTime + ) + } else { + true + } } override fun getHeaderViewForPosition(context: Context, position: Int): View { val data = getItem(position) val binding: ConferenceScheduleListHeaderBinding = DataBindingUtil.inflate( LayoutInflater.from(context), - R.layout.conference_schedule_list_header, null, false + R.layout.conference_schedule_list_header, + null, + false ) binding.title = formatDate(context, data.conferenceInfo.dateTime) binding.executePendingBindings() @@ -143,7 +155,9 @@ class ScheduledConferencesAdapter( setJoinConferenceClickListener { val address = conferenceData.conferenceInfo.uri if (address != null) { - joinConferenceEvent.value = Event(Pair(address.asStringUriOnly(), conferenceData.conferenceInfo.subject)) + joinConferenceEvent.value = Event( + Pair(address.asStringUriOnly(), conferenceData.conferenceInfo.subject) + ) } } diff --git a/app/src/main/java/org/linphone/activities/main/conference/data/ScheduledConferenceData.kt b/app/src/main/java/org/linphone/activities/main/conference/data/ScheduledConferenceData.kt index 0dd033278..04b3d1151 100644 --- a/app/src/main/java/org/linphone/activities/main/conference/data/ScheduledConferenceData.kt +++ b/app/src/main/java/org/linphone/activities/main/conference/data/ScheduledConferenceData.kt @@ -54,7 +54,12 @@ class ScheduledConferenceData(val conferenceInfo: ConferenceInfo, private val is description.value = conferenceInfo.description time.value = TimestampUtils.timeToString(conferenceInfo.dateTime) - date.value = TimestampUtils.toString(conferenceInfo.dateTime, onlyDate = true, shortDate = false, hideYear = false) + date.value = TimestampUtils.toString( + conferenceInfo.dateTime, + onlyDate = true, + shortDate = false, + hideYear = false + ) isConferenceCancelled.value = conferenceInfo.state == State.Cancelled val minutes = conferenceInfo.duration @@ -72,13 +77,16 @@ class ScheduledConferenceData(val conferenceInfo: ConferenceInfo, private val is canEdit.value = localAccount != null val contact = coreContext.contactsManager.findContactByAddress(organizerAddress) - organizer.value = if (contact != null) + organizer.value = if (contact != null) { contact.name - else + } else { LinphoneUtils.getDisplayName(conferenceInfo.organizer) + } } else { canEdit.value = false - Log.e("[Scheduled Conference] No organizer SIP URI found for: ${conferenceInfo.uri?.asStringUriOnly()}") + Log.e( + "[Scheduled Conference] No organizer SIP URI found for: ${conferenceInfo.uri?.asStringUriOnly()}" + ) } computeBackgroundResId() @@ -88,7 +96,9 @@ class ScheduledConferenceData(val conferenceInfo: ConferenceInfo, private val is fun destroy() {} fun delete() { - Log.w("[Scheduled Conference] Deleting conference info with URI: ${conferenceInfo.uri?.asStringUriOnly()}") + Log.w( + "[Scheduled Conference] Deleting conference info with URI: ${conferenceInfo.uri?.asStringUriOnly()}" + ) coreContext.core.deleteConferenceInformation(conferenceInfo) } @@ -134,7 +144,13 @@ class ScheduledConferenceData(val conferenceInfo: ConferenceInfo, private val is for (participant in conferenceInfo.participants) { val contact = coreContext.contactsManager.findContactByAddress(participant) - val name = if (contact != null) contact.name else LinphoneUtils.getDisplayName(participant) + val name = if (contact != null) { + contact.name + } else { + LinphoneUtils.getDisplayName( + participant + ) + } val address = participant.asStringUriOnly() participantsListShort += "$name, " participantsListExpanded += "$name ($address)\n" diff --git a/app/src/main/java/org/linphone/activities/main/conference/fragments/ConferenceSchedulingFragment.kt b/app/src/main/java/org/linphone/activities/main/conference/fragments/ConferenceSchedulingFragment.kt index 99b51e20f..c16a42c4f 100644 --- a/app/src/main/java/org/linphone/activities/main/conference/fragments/ConferenceSchedulingFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/conference/fragments/ConferenceSchedulingFragment.kt @@ -38,7 +38,9 @@ import org.linphone.core.tools.Log import org.linphone.databinding.ConferenceSchedulingFragmentBinding class ConferenceSchedulingFragment : GenericFragment() { - private val viewModel: ConferenceSchedulingViewModel by navGraphViewModels(R.id.conference_scheduling_nav_graph) + private val viewModel: ConferenceSchedulingViewModel by navGraphViewModels( + R.id.conference_scheduling_nav_graph + ) override fun getLayoutId(): Int = R.layout.conference_scheduling_fragment @@ -53,7 +55,9 @@ class ConferenceSchedulingFragment : GenericFragment - Log.i("[Conference Scheduling] Found participants (${participants.size}) to pre-populate for meeting schedule") + Log.i( + "[Conference Scheduling] Found participants (${participants.size}) to pre-populate for meeting schedule" + ) viewModel.prePopulateParticipantsList(participants, true) } } @@ -64,12 +68,18 @@ class ConferenceSchedulingFragment : GenericFragment val conferenceAddress = Factory.instance().createAddress(address) if (conferenceAddress != null) { - Log.i("[Conference Scheduling] Trying to edit conference info using address: $address") - val conferenceInfo = coreContext.core.findConferenceInformationFromUri(conferenceAddress) + Log.i( + "[Conference Scheduling] Trying to edit conference info using address: $address" + ) + val conferenceInfo = coreContext.core.findConferenceInformationFromUri( + conferenceAddress + ) if (conferenceInfo != null) { viewModel.populateFromConferenceInfo(conferenceInfo) } else { - Log.e("[Conference Scheduling] Failed to find ConferenceInfo matching address: $address") + Log.e( + "[Conference Scheduling] Failed to find ConferenceInfo matching address: $address" + ) } } else { Log.e("[Conference Scheduling] Failed to parse conference address: $address") diff --git a/app/src/main/java/org/linphone/activities/main/conference/fragments/ConferenceSchedulingParticipantsListFragment.kt b/app/src/main/java/org/linphone/activities/main/conference/fragments/ConferenceSchedulingParticipantsListFragment.kt index 362e8b9a0..b59247d44 100644 --- a/app/src/main/java/org/linphone/activities/main/conference/fragments/ConferenceSchedulingParticipantsListFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/conference/fragments/ConferenceSchedulingParticipantsListFragment.kt @@ -37,7 +37,9 @@ import org.linphone.utils.AppUtils import org.linphone.utils.PermissionHelper class ConferenceSchedulingParticipantsListFragment : GenericFragment() { - private val viewModel: ConferenceSchedulingViewModel by navGraphViewModels(R.id.conference_scheduling_nav_graph) + private val viewModel: ConferenceSchedulingViewModel by navGraphViewModels( + R.id.conference_scheduling_nav_graph + ) private lateinit var adapter: ContactsSelectionAdapter override fun getLayoutId(): Int = R.layout.conference_scheduling_participants_list_fragment @@ -57,7 +59,9 @@ class ConferenceSchedulingParticipantsListFragment : GenericFragment() { - private val viewModel: ConferenceSchedulingViewModel by navGraphViewModels(R.id.conference_scheduling_nav_graph) + private val viewModel: ConferenceSchedulingViewModel by navGraphViewModels( + R.id.conference_scheduling_nav_graph + ) override fun getLayoutId(): Int = R.layout.conference_scheduling_summary_fragment @@ -47,7 +49,9 @@ class ConferenceSchedulingSummaryFragment : GenericFragment if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { - Log.i("[Conference Waiting Room] BLUETOOTH_CONNECT permission has been granted") + Log.i( + "[Conference Waiting Room] BLUETOOTH_CONNECT permission has been granted" + ) } } } diff --git a/app/src/main/java/org/linphone/activities/main/conference/fragments/ScheduledConferencesFragment.kt b/app/src/main/java/org/linphone/activities/main/conference/fragments/ScheduledConferencesFragment.kt index b9f720e1d..a570af0c4 100644 --- a/app/src/main/java/org/linphone/activities/main/conference/fragments/ScheduledConferencesFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/conference/fragments/ScheduledConferencesFragment.kt @@ -82,7 +82,9 @@ class ScheduledConferencesFragment : MasterFragment= adapter.currentList.size) { - Log.e("[Scheduled Conferences] Index is out of bound, can't delete conference info") + Log.e( + "[Scheduled Conferences] Index is out of bound, can't delete conference info" + ) } else { val deletedConfInfo = adapter.currentList[index] showConfInfoDeleteConfirmationDialog(deletedConfInfo, index) @@ -111,7 +113,9 @@ class ScheduledConferencesFragment : MasterFragment { - Log.w("[Conference Waiting Room] Call has failed, leaving waiting room fragment") + Log.w( + "[Conference Waiting Room] Call has failed, leaving waiting room fragment" + ) leaveWaitingRoomEvent.value = Event(true) } else -> {} @@ -138,7 +140,9 @@ class ConferenceWaitingRoomViewModel : MessageNotifierViewModel() { state: Conference.State? ) { if (state == Conference.State.Created) { - Log.i("[Conference Waiting Room] Conference has been created, leaving waiting room fragment") + Log.i( + "[Conference Waiting Room] Conference has been created, leaving waiting room fragment" + ) leaveWaitingRoomEvent.value = Event(true) } } @@ -156,8 +160,12 @@ class ConferenceWaitingRoomViewModel : MessageNotifierViewModel() { val core = coreContext.core core.addListener(listener) - audioRoutesMenuTranslateY.value = AppUtils.getDimension(R.dimen.voip_audio_routes_menu_translate_y) - conferenceLayoutMenuTranslateY.value = AppUtils.getDimension(R.dimen.voip_audio_routes_menu_translate_y) + audioRoutesMenuTranslateY.value = AppUtils.getDimension( + R.dimen.voip_audio_routes_menu_translate_y + ) + conferenceLayoutMenuTranslateY.value = AppUtils.getDimension( + R.dimen.voip_audio_routes_menu_translate_y + ) val reachable = core.isNetworkReachable networkReachable.value = reachable @@ -166,7 +174,9 @@ class ConferenceWaitingRoomViewModel : MessageNotifierViewModel() { } callParams.isMicEnabled = PermissionHelper.get().hasRecordAudioPermission() && coreContext.core.isMicEnabled - Log.i("[Conference Waiting Room] Microphone will be ${if (callParams.isMicEnabled) "enabled" else "muted"}") + Log.i( + "[Conference Waiting Room] Microphone will be ${if (callParams.isMicEnabled) "enabled" else "muted"}" + ) updateMicState() callParams.isVideoEnabled = isVideoAvailableInCore() @@ -175,7 +185,9 @@ class ConferenceWaitingRoomViewModel : MessageNotifierViewModel() { isLowBandwidth.value = false if (LinphoneUtils.checkIfNetworkHasLowBandwidth(coreContext.context)) { - Log.w("[Conference Waiting Room] Enabling low bandwidth mode, forcing audio only layout!") + Log.w( + "[Conference Waiting Room] Enabling low bandwidth mode, forcing audio only layout!" + ) callParams.isLowBandwidthEnabled = true callParams.isVideoEnabled = false callParams.videoDirection = MediaDirection.Inactive @@ -224,7 +236,9 @@ class ConferenceWaitingRoomViewModel : MessageNotifierViewModel() { } callParams.isMicEnabled = !callParams.isMicEnabled - Log.i("[Conference Waiting Room] Microphone will be ${if (callParams.isMicEnabled) "enabled" else "muted"}") + Log.i( + "[Conference Waiting Room] Microphone will be ${if (callParams.isMicEnabled) "enabled" else "muted"}" + ) updateMicState() } @@ -254,10 +268,14 @@ class ConferenceWaitingRoomViewModel : MessageNotifierViewModel() { fun setBluetoothAudioRoute() { Log.i("[Conference Waiting Room] Set default output audio device to Bluetooth") callParams.outputAudioDevice = coreContext.core.audioDevices.find { - it.type == AudioDevice.Type.Bluetooth && it.hasCapability(AudioDevice.Capabilities.CapabilityPlay) + it.type == AudioDevice.Type.Bluetooth && it.hasCapability( + AudioDevice.Capabilities.CapabilityPlay + ) } callParams.inputAudioDevice = coreContext.core.audioDevices.find { - it.type == AudioDevice.Type.Bluetooth && it.hasCapability(AudioDevice.Capabilities.CapabilityRecord) + it.type == AudioDevice.Type.Bluetooth && it.hasCapability( + AudioDevice.Capabilities.CapabilityRecord + ) } updateAudioRouteState() @@ -270,10 +288,14 @@ class ConferenceWaitingRoomViewModel : MessageNotifierViewModel() { fun setSpeakerAudioRoute() { Log.i("[Conference Waiting Room] Set default output audio device to Speaker") callParams.outputAudioDevice = coreContext.core.audioDevices.find { - it.type == AudioDevice.Type.Speaker && it.hasCapability(AudioDevice.Capabilities.CapabilityPlay) + it.type == AudioDevice.Type.Speaker && it.hasCapability( + AudioDevice.Capabilities.CapabilityPlay + ) } callParams.inputAudioDevice = coreContext.core.audioDevices.find { - it.type == AudioDevice.Type.Microphone && it.hasCapability(AudioDevice.Capabilities.CapabilityRecord) + it.type == AudioDevice.Type.Microphone && it.hasCapability( + AudioDevice.Capabilities.CapabilityRecord + ) } updateAudioRouteState() @@ -286,10 +308,14 @@ class ConferenceWaitingRoomViewModel : MessageNotifierViewModel() { fun setEarpieceAudioRoute() { Log.i("[Conference Waiting Room] Set default output audio device to Earpiece") callParams.outputAudioDevice = coreContext.core.audioDevices.find { - it.type == AudioDevice.Type.Earpiece && it.hasCapability(AudioDevice.Capabilities.CapabilityPlay) + it.type == AudioDevice.Type.Earpiece && it.hasCapability( + AudioDevice.Capabilities.CapabilityPlay + ) } callParams.inputAudioDevice = coreContext.core.audioDevices.find { - it.type == AudioDevice.Type.Microphone && it.hasCapability(AudioDevice.Capabilities.CapabilityRecord) + it.type == AudioDevice.Type.Microphone && it.hasCapability( + AudioDevice.Capabilities.CapabilityRecord + ) } updateAudioRouteState() @@ -376,7 +402,9 @@ class ConferenceWaitingRoomViewModel : MessageNotifierViewModel() { if (!bluetoothDeviceAvailable) { audioRoutesSelected.value = false - Log.w("[Conference Waiting Room] Bluetooth device no longer available, switching back to default microphone & earpiece/speaker") + Log.w( + "[Conference Waiting Room] Bluetooth device no longer available, switching back to default microphone & earpiece/speaker" + ) if (isBluetoothHeadsetSelected.value == true) { for (audioDevice in coreContext.core.audioDevices) { if (isVideoEnabled.value == true) { @@ -418,7 +446,9 @@ class ConferenceWaitingRoomViewModel : MessageNotifierViewModel() { private fun updateVideoState() { isVideoAvailable.value = callParams.isVideoEnabled isVideoEnabled.value = callParams.isVideoEnabled && callParams.videoDirection == MediaDirection.SendRecv - Log.i("[Conference Waiting Room] Video will be ${if (callParams.isVideoEnabled) "enabled" else "disabled"} with direction ${callParams.videoDirection}") + Log.i( + "[Conference Waiting Room] Video will be ${if (callParams.isVideoEnabled) "enabled" else "disabled"} with direction ${callParams.videoDirection}" + ) isSwitchCameraAvailable.value = callParams.isVideoEnabled && coreContext.showSwitchCameraButton() coreContext.core.isVideoPreviewEnabled = isVideoEnabled.value == true diff --git a/app/src/main/java/org/linphone/activities/main/conference/viewmodels/ScheduledConferencesViewModel.kt b/app/src/main/java/org/linphone/activities/main/conference/viewmodels/ScheduledConferencesViewModel.kt index ada01326b..c8acab844 100644 --- a/app/src/main/java/org/linphone/activities/main/conference/viewmodels/ScheduledConferencesViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/conference/viewmodels/ScheduledConferencesViewModel.kt @@ -52,7 +52,9 @@ class ScheduledConferencesViewModel : ViewModel() { ) { Log.i("[Scheduled Conferences] Conference scheduler state is $state") if (state == ConferenceScheduler.State.Ready) { - Log.i("[Scheduled Conferences] Conference ${conferenceScheduler.info?.subject} cancelled") + Log.i( + "[Scheduled Conferences] Conference ${conferenceScheduler.info?.subject} cancelled" + ) val chatRoomParams = LinphoneUtils.getConferenceInvitationsChatRoomParams() conferenceScheduler.sendInvitations(chatRoomParams) // Send cancel ICS } @@ -64,10 +66,14 @@ class ScheduledConferencesViewModel : ViewModel() { ) { if (failedInvitations?.isNotEmpty() == true) { for (address in failedInvitations) { - Log.e("[Scheduled Conferences] Conference cancelled ICS wasn't sent to participant ${address.asStringUriOnly()}") + Log.e( + "[Scheduled Conferences] Conference cancelled ICS wasn't sent to participant ${address.asStringUriOnly()}" + ) } } else { - Log.i("[Scheduled Conferences] Conference cancelled ICS successfully sent to all participants") + Log.i( + "[Scheduled Conferences] Conference cancelled ICS successfully sent to all participants" + ) } } } @@ -139,7 +145,9 @@ class ScheduledConferencesViewModel : ViewModel() { } } else { val oneHourAgo = now - 7200 // Show all conferences from 2 hours ago and forward - for (conferenceInfo in coreContext.core.getConferenceInformationListAfterTime(oneHourAgo)) { + for (conferenceInfo in coreContext.core.getConferenceInformationListAfterTime( + oneHourAgo + )) { if (conferenceInfo.duration == 0) continue // This isn't a scheduled conference, don't display it val data = ScheduledConferenceData(conferenceInfo, false) conferencesList.add(data) diff --git a/app/src/main/java/org/linphone/activities/main/contact/adapters/ContactsListAdapter.kt b/app/src/main/java/org/linphone/activities/main/contact/adapters/ContactsListAdapter.kt index 83e3930d7..5d503f94f 100644 --- a/app/src/main/java/org/linphone/activities/main/contact/adapters/ContactsListAdapter.kt +++ b/app/src/main/java/org/linphone/activities/main/contact/adapters/ContactsListAdapter.kt @@ -42,7 +42,11 @@ import org.linphone.utils.HeaderAdapter class ContactsListAdapter( selectionVM: ListTopBarViewModel, private val viewLifecycleOwner: LifecycleOwner -) : SelectionListAdapter(selectionVM, ContactDiffCallback()), HeaderAdapter { +) : SelectionListAdapter( + selectionVM, + ContactDiffCallback() +), + HeaderAdapter { val selectedContactEvent: MutableLiveData> by lazy { MutableLiveData>() } @@ -50,7 +54,9 @@ class ContactsListAdapter( override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding: ContactListCellBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), - R.layout.contact_list_cell, parent, false + R.layout.contact_list_cell, + parent, + false ) return ViewHolder(binding) } @@ -108,7 +114,9 @@ class ContactsListAdapter( return if (previousPosition >= 0) { val previousItemFirstLetter = getItem(previousPosition).fullName.firstOrNull().toString() !firstLetter.equals(previousItemFirstLetter, ignoreCase = true) - } else true + } else { + true + } } override fun getHeaderViewForPosition(context: Context, position: Int): View { @@ -116,7 +124,9 @@ class ContactsListAdapter( val firstLetter = AppUtils.getInitials(contact.fullName, 1) val binding: GenericListHeaderBinding = DataBindingUtil.inflate( LayoutInflater.from(context), - R.layout.generic_list_header, null, false + R.layout.generic_list_header, + null, + false ) binding.title = firstLetter binding.executePendingBindings() diff --git a/app/src/main/java/org/linphone/activities/main/contact/adapters/SyncAccountAdapter.kt b/app/src/main/java/org/linphone/activities/main/contact/adapters/SyncAccountAdapter.kt index 45e201c49..f8303bcb7 100644 --- a/app/src/main/java/org/linphone/activities/main/contact/adapters/SyncAccountAdapter.kt +++ b/app/src/main/java/org/linphone/activities/main/contact/adapters/SyncAccountAdapter.kt @@ -19,7 +19,11 @@ class SyncAccountAdapter : BaseAdapter() { } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { - val view: View = convertView ?: LayoutInflater.from(parent.context).inflate(R.layout.contact_sync_account_picker_cell, parent, false) + val view: View = convertView ?: LayoutInflater.from(parent.context).inflate( + R.layout.contact_sync_account_picker_cell, + parent, + false + ) val account = getItem(position) val icon = view.findViewById(R.id.account_icon) diff --git a/app/src/main/java/org/linphone/activities/main/contact/data/ContactEditorData.kt b/app/src/main/java/org/linphone/activities/main/contact/data/ContactEditorData.kt index fdef62159..d1ef3ce6c 100644 --- a/app/src/main/java/org/linphone/activities/main/contact/data/ContactEditorData.kt +++ b/app/src/main/java/org/linphone/activities/main/contact/data/ContactEditorData.kt @@ -88,7 +88,9 @@ class ContactEditorData(val friend: Friend?) : ContactDataInterface { Log.w("[Contact Editor] vCard first & last name not filled-in yet, doing it now") fetchFirstAndLastNames(refKey) } else { - Log.e("[Contact Editor] vCard first & last name not available as contact doesn't have a native ID") + Log.e( + "[Contact Editor] vCard first & last name not available as contact doesn't have a native ID" + ) } } else { firstName.value = vCard?.givenName @@ -246,10 +248,16 @@ class ContactEditorData(val friend: Friend?) : ContactDataInterface { while (cursor != null && cursor.moveToNext()) { val linphoneMime = AppUtils.getString(R.string.linphone_address_mime_type) val mime: String? = - cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Data.MIMETYPE)) + cursor.getString( + cursor.getColumnIndexOrThrow(ContactsContract.Data.MIMETYPE) + ) if (mime == ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) { val data1: String? = - cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)) + cursor.getString( + cursor.getColumnIndexOrThrow( + ContactsContract.CommonDataKinds.Phone.NUMBER + ) + ) if (data1 != null) { phoneNumbers.add(NumberOrAddressEditorData(data1, false)) } @@ -258,7 +266,11 @@ class ContactEditorData(val friend: Friend?) : ContactDataInterface { mime == linphoneMime ) { val data1: String? = - cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS)) + cursor.getString( + cursor.getColumnIndexOrThrow( + ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS + ) + ) if (data1 != null) { sipAddresses.add(NumberOrAddressEditorData(data1, true)) } @@ -274,7 +286,9 @@ class ContactEditorData(val friend: Friend?) : ContactDataInterface { } if (!fetched) { - Log.w("[Contact Editor] Fall-backing to friend info (might be inaccurate and thus edition/removal might fail)") + Log.w( + "[Contact Editor] Fall-backing to friend info (might be inaccurate and thus edition/removal might fail)" + ) for (number in friend?.phoneNumbers.orEmpty()) { phoneNumbers.add(NumberOrAddressEditorData(number, false)) } @@ -310,17 +324,27 @@ class ContactEditorData(val friend: Friend?) : ContactDataInterface { ) while (cursor != null && cursor.moveToNext()) { - val mime: String? = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Data.MIMETYPE)) + val mime: String? = cursor.getString( + cursor.getColumnIndexOrThrow(ContactsContract.Data.MIMETYPE) + ) if (mime == ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) { val givenName: String? = - cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME)) + cursor.getString( + cursor.getColumnIndexOrThrow( + ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME + ) + ) if (!givenName.isNullOrEmpty()) { friend?.vcard?.givenName = givenName firstName.value = givenName!! } val familyName: String? = - cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME)) + cursor.getString( + cursor.getColumnIndexOrThrow( + ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME + ) + ) if (!familyName.isNullOrEmpty()) { friend?.vcard?.familyName = familyName lastName.value = familyName!! diff --git a/app/src/main/java/org/linphone/activities/main/contact/fragments/ContactEditorFragment.kt b/app/src/main/java/org/linphone/activities/main/contact/fragments/ContactEditorFragment.kt index 43766bcff..94b0d81f9 100644 --- a/app/src/main/java/org/linphone/activities/main/contact/fragments/ContactEditorFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/contact/fragments/ContactEditorFragment.kt @@ -116,7 +116,9 @@ class ContactEditorFragment : GenericFragment(), S Log.i("[Contact Editor] WRITE_CONTACTS permission granted") } else { Log.w("[Contact Editor] WRITE_CONTACTS permission denied") - (activity as MainActivity).showSnackBar(R.string.contact_editor_write_permission_denied) + (activity as MainActivity).showSnackBar( + R.string.contact_editor_write_permission_denied + ) goBack() } } @@ -126,7 +128,10 @@ class ContactEditorFragment : GenericFragment(), S override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) { if (resultCode == Activity.RESULT_OK) { lifecycleScope.launch { - val contactImageFilePath = FileUtils.getFilePathFromPickerIntent(intent, temporaryPicturePath) + val contactImageFilePath = FileUtils.getFilePathFromPickerIntent( + intent, + temporaryPicturePath + ) if (contactImageFilePath != null) { data.setPictureFromPath(contactImageFilePath) } @@ -171,7 +176,10 @@ class ContactEditorFragment : GenericFragment(), S val chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.chat_message_pick_file_dialog)) - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(arrayOf())) + chooserIntent.putExtra( + Intent.EXTRA_INITIAL_INTENTS, + cameraIntents.toArray(arrayOf()) + ) startActivityForResult(chooserIntent, 0) } diff --git a/app/src/main/java/org/linphone/activities/main/contact/fragments/DetailContactFragment.kt b/app/src/main/java/org/linphone/activities/main/contact/fragments/DetailContactFragment.kt index ed0445386..78cff1f94 100644 --- a/app/src/main/java/org/linphone/activities/main/contact/fragments/DetailContactFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/contact/fragments/DetailContactFragment.kt @@ -88,7 +88,9 @@ class DetailContactFragment : GenericFragment() { ) { it.consume { address -> if (coreContext.core.callsNb > 0) { - Log.i("[Contact] Starting dialer with pre-filled URI ${address.asStringUriOnly()}, is transfer? ${sharedViewModel.pendingCallTransfer}") + Log.i( + "[Contact] Starting dialer with pre-filled URI ${address.asStringUriOnly()}, is transfer? ${sharedViewModel.pendingCallTransfer}" + ) sharedViewModel.updateContactsAnimationsBasedOnDestination.value = Event(R.id.dialerFragment) sharedViewModel.updateDialerAnimationsBasedOnDestination.value = @@ -186,7 +188,9 @@ class DetailContactFragment : GenericFragment() { val smsIntent = Intent(Intent.ACTION_SENDTO) smsIntent.putExtra("address", number) smsIntent.data = Uri.parse("smsto:$number") - val text = getString(R.string.contact_send_sms_invite_text).format(getString(R.string.contact_send_sms_invite_download_link)) + val text = getString(R.string.contact_send_sms_invite_text).format( + getString(R.string.contact_send_sms_invite_download_link) + ) smsIntent.putExtra("sms_body", text) startActivity(smsIntent) } diff --git a/app/src/main/java/org/linphone/activities/main/contact/fragments/MasterContactsFragment.kt b/app/src/main/java/org/linphone/activities/main/contact/fragments/MasterContactsFragment.kt index 01a50b8d5..344d4f588 100644 --- a/app/src/main/java/org/linphone/activities/main/contact/fragments/MasterContactsFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/contact/fragments/MasterContactsFragment.kt @@ -115,7 +115,9 @@ class MasterContactsFragment : MasterFragment() { } binding.setNewContactClickListener { - sharedViewModel.updateDialerAnimationsBasedOnDestination.value = Event(R.id.masterContactsFragment) - sharedViewModel.updateContactsAnimationsBasedOnDestination.value = Event(R.id.dialerFragment) + sharedViewModel.updateDialerAnimationsBasedOnDestination.value = Event( + R.id.masterContactsFragment + ) + sharedViewModel.updateContactsAnimationsBasedOnDestination.value = Event( + R.id.dialerFragment + ) navigateToContacts(viewModel.enteredUri.value) } binding.setNewConferenceClickListener { - sharedViewModel.updateDialerAnimationsBasedOnDestination.value = Event(R.id.conferenceSchedulingFragment) + sharedViewModel.updateDialerAnimationsBasedOnDestination.value = Event( + R.id.conferenceSchedulingFragment + ) navigateToConferenceScheduling() } @@ -157,7 +163,9 @@ class DialerFragment : SecureFragment() { } if (corePreferences.firstStart) { - Log.w("[Dialer] First start detected, wait for assistant to be finished to check for update & request permissions") + Log.w( + "[Dialer] First start detected, wait for assistant to be finished to check for update & request permissions" + ) return } @@ -168,10 +176,14 @@ class DialerFragment : SecureFragment() { if (corePreferences.skipDialerForNewCallAndTransfer) { if (sharedViewModel.pendingCallTransfer) { - Log.i("[Dialer] We were asked to skip dialer so starting new call to [$address] now") + Log.i( + "[Dialer] We were asked to skip dialer so starting new call to [$address] now" + ) viewModel.transferCallTo(address) } else { - Log.i("[Dialer] We were asked to skip dialer so starting transfer to [$address] now") + Log.i( + "[Dialer] We were asked to skip dialer so starting transfer to [$address] now" + ) viewModel.directCall(address) } } else if (corePreferences.callRightAway && !skipAutoCall) { @@ -289,7 +301,9 @@ class DialerFragment : SecureFragment() { if (Compatibility.hasTelecomManagerFeature(requireContext())) { TelecomHelper.create(requireContext()) } else { - Log.e("[Dialer] Telecom Helper can't be created, device doesn't support connection service!") + Log.e( + "[Dialer] Telecom Helper can't be created, device doesn't support connection service!" + ) return } } else { diff --git a/app/src/main/java/org/linphone/activities/main/dialer/viewmodels/DialerViewModel.kt b/app/src/main/java/org/linphone/activities/main/dialer/viewmodels/DialerViewModel.kt index bcbf32f03..4f3997043 100644 --- a/app/src/main/java/org/linphone/activities/main/dialer/viewmodels/DialerViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/dialer/viewmodels/DialerViewModel.kt @@ -112,7 +112,9 @@ class DialerViewModel : LogsUploadViewModel() { if (reachable && address.isNotEmpty()) { val now = System.currentTimeMillis() if (now - timeAtWitchWeTriedToCall > 1000) { - Log.e("[Dialer] More than 1 second has passed waiting for network, abort auto call to $address") + Log.e( + "[Dialer] More than 1 second has passed waiting for network, abort auto call to $address" + ) enteredUri.value = address } else { Log.i("[Dialer] Network is available, continue auto call to $address") @@ -198,7 +200,9 @@ class DialerViewModel : LogsUploadViewModel() { if (coreContext.core.isNetworkReachable) { coreContext.startCall(to) } else { - Log.w("[Dialer] Network isnt't reachable at the time, wait for network to start call (happens mainly when app is cold started)") + Log.w( + "[Dialer] Network isnt't reachable at the time, wait for network to start call (happens mainly when app is cold started)" + ) timeAtWitchWeTriedToCall = System.currentTimeMillis() addressWaitingNetworkToBeCalled = to } diff --git a/app/src/main/java/org/linphone/activities/main/files/adapters/PdfPagesListAdapter.kt b/app/src/main/java/org/linphone/activities/main/files/adapters/PdfPagesListAdapter.kt index 895292a2a..cfb4b48a2 100644 --- a/app/src/main/java/org/linphone/activities/main/files/adapters/PdfPagesListAdapter.kt +++ b/app/src/main/java/org/linphone/activities/main/files/adapters/PdfPagesListAdapter.kt @@ -29,7 +29,9 @@ import org.linphone.activities.main.files.viewmodels.PdfFileViewModel class PdfPagesListAdapter(private val pdfViewModel: PdfFileViewModel) : RecyclerView.Adapter() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PdfPageViewHolder { val view = LayoutInflater.from(parent.context).inflate( - R.layout.file_pdf_viewer_cell, parent, false + R.layout.file_pdf_viewer_cell, + parent, + false ) return PdfPageViewHolder(view) } diff --git a/app/src/main/java/org/linphone/activities/main/files/fragments/TopBarFragment.kt b/app/src/main/java/org/linphone/activities/main/files/fragments/TopBarFragment.kt index 868f7b946..d636d194c 100644 --- a/app/src/main/java/org/linphone/activities/main/files/fragments/TopBarFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/files/fragments/TopBarFragment.kt @@ -98,10 +98,14 @@ class TopBarFragment : GenericFragment() { Compatibility.addImageToMediaStore(requireContext(), content) } if (export.await()) { - Log.i("[File Viewer] Successfully exported image [${content.name}] to Media Store: ${content.userData}") + Log.i( + "[File Viewer] Successfully exported image [${content.name}] to Media Store: ${content.userData}" + ) mediaStoreFilePath = content.userData.toString() } else { - Log.e("[File Viewer] Something went wrong while copying file to Media Store...") + Log.e( + "[File Viewer] Something went wrong while copying file to Media Store..." + ) } } FileUtils.isMimeVideo(mime) -> { @@ -109,10 +113,14 @@ class TopBarFragment : GenericFragment() { Compatibility.addVideoToMediaStore(requireContext(), content) } if (export.await()) { - Log.i("[File Viewer] Successfully exported video [${content.name}] to Media Store: ${content.userData}") + Log.i( + "[File Viewer] Successfully exported video [${content.name}] to Media Store: ${content.userData}" + ) mediaStoreFilePath = content.userData.toString() } else { - Log.e("[File Viewer] Something went wrong while copying file to Media Store...") + Log.e( + "[File Viewer] Something went wrong while copying file to Media Store..." + ) } } FileUtils.isMimeAudio(mime) -> { @@ -120,32 +128,46 @@ class TopBarFragment : GenericFragment() { Compatibility.addAudioToMediaStore(requireContext(), content) } if (export.await()) { - Log.i("[File Viewer] Successfully exported audio [${content.name}] to Media Store: ${content.userData}") + Log.i( + "[File Viewer] Successfully exported audio [${content.name}] to Media Store: ${content.userData}" + ) mediaStoreFilePath = content.userData.toString() } else { - Log.e("[File Viewer] Something went wrong while copying file to Media Store...") + Log.e( + "[File Viewer] Something went wrong while copying file to Media Store..." + ) } } else -> { - Log.w("[File Viewer] File [${content.name}] isn't either an image, an audio file or a video, can't add it to the Media Store") + Log.w( + "[File Viewer] File [${content.name}] isn't either an image, an audio file or a video, can't add it to the Media Store" + ) } } } else { - Log.w("[File Viewer] Can't export image through Media Store API (requires Android 10 or WRITE_EXTERNAL permission, using fallback method...") + Log.w( + "[File Viewer] Can't export image through Media Store API (requires Android 10 or WRITE_EXTERNAL permission, using fallback method..." + ) } withContext(Dispatchers.Main) { if (mediaStoreFilePath.isEmpty()) { - Log.w("[File Viewer] Media store file path is empty, media store export failed?") + Log.w( + "[File Viewer] Media store file path is empty, media store export failed?" + ) val filePath = content.exportPlainFile().orEmpty() plainFilePath = filePath.ifEmpty { content.filePath.orEmpty() } Log.i("[File Viewer] Plain file path is: $plainFilePath") if (plainFilePath.isNotEmpty()) { if (!FileUtils.openFileInThirdPartyApp(requireActivity(), plainFilePath)) { - (requireActivity() as SnackBarActivity).showSnackBar(R.string.chat_message_no_app_found_to_handle_file_mime_type) + (requireActivity() as SnackBarActivity).showSnackBar( + R.string.chat_message_no_app_found_to_handle_file_mime_type + ) if (plainFilePath != content.filePath.orEmpty()) { - Log.i("[File Viewer] No app to open plain file path [$plainFilePath], destroying it") + Log.i( + "[File Viewer] No app to open plain file path [$plainFilePath], destroying it" + ) FileUtils.deleteFile(plainFilePath) } plainFilePath = "" diff --git a/app/src/main/java/org/linphone/activities/main/files/viewmodels/AudioFileViewModel.kt b/app/src/main/java/org/linphone/activities/main/files/viewmodels/AudioFileViewModel.kt index e822cbe41..a196bd76e 100644 --- a/app/src/main/java/org/linphone/activities/main/files/viewmodels/AudioFileViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/files/viewmodels/AudioFileViewModel.kt @@ -41,7 +41,11 @@ class AudioFileViewModel(content: Content) : FileViewerViewModel(content), Media init { mediaPlayer.apply { - setAudioAttributes(AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).setUsage(AudioAttributes.USAGE_MEDIA).build()) + setAudioAttributes( + AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).setUsage( + AudioAttributes.USAGE_MEDIA + ).build() + ) setDataSource(filePath) prepare() start() diff --git a/app/src/main/java/org/linphone/activities/main/files/viewmodels/FileViewerViewModel.kt b/app/src/main/java/org/linphone/activities/main/files/viewmodels/FileViewerViewModel.kt index 693b951a9..d9f46d86c 100644 --- a/app/src/main/java/org/linphone/activities/main/files/viewmodels/FileViewerViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/files/viewmodels/FileViewerViewModel.kt @@ -33,7 +33,9 @@ open class FileViewerViewModel(val content: Content) : ViewModel() { init { filePath = if (deleteAfterUse) { - Log.i("[File Viewer] [VFS] Content is encrypted, requesting plain file path for file [${content.filePath}]") + Log.i( + "[File Viewer] [VFS] Content is encrypted, requesting plain file path for file [${content.filePath}]" + ) content.exportPlainFile() } else { content.filePath.orEmpty() diff --git a/app/src/main/java/org/linphone/activities/main/fragments/MasterFragment.kt b/app/src/main/java/org/linphone/activities/main/fragments/MasterFragment.kt index ae4ccbcf1..b38de9c08 100644 --- a/app/src/main/java/org/linphone/activities/main/fragments/MasterFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/fragments/MasterFragment.kt @@ -136,14 +136,15 @@ abstract class MasterFragment) class SlidingPaneBackPressedCallback(private val slidingPaneLayout: SlidingPaneLayout) : - OnBackPressedCallback - ( + OnBackPressedCallback( slidingPaneLayout.isSlideable && slidingPaneLayout.isOpen ), SlidingPaneLayout.PanelSlideListener { init { - Log.d("[Master Fragment] SlidingPane isSlideable = ${slidingPaneLayout.isSlideable}, isOpen = ${slidingPaneLayout.isOpen}") + Log.d( + "[Master Fragment] SlidingPane isSlideable = ${slidingPaneLayout.isSlideable}, isOpen = ${slidingPaneLayout.isOpen}" + ) slidingPaneLayout.addPanelSlideListener(this) } diff --git a/app/src/main/java/org/linphone/activities/main/fragments/SecureFragment.kt b/app/src/main/java/org/linphone/activities/main/fragments/SecureFragment.kt index 2741c437c..bb84d2359 100644 --- a/app/src/main/java/org/linphone/activities/main/fragments/SecureFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/fragments/SecureFragment.kt @@ -77,7 +77,9 @@ abstract class SecureFragment : GenericFragment() { if ((enable && flags and WindowManager.LayoutParams.FLAG_SECURE != 0) || (!enable && flags and WindowManager.LayoutParams.FLAG_SECURE == 0) ) { - Log.d("[Secure Fragment] Secure flag is already ${if (enable) "enabled" else "disabled"}, skipping...") + Log.d( + "[Secure Fragment] Secure flag is already ${if (enable) "enabled" else "disabled"}, skipping..." + ) return } diff --git a/app/src/main/java/org/linphone/activities/main/fragments/TabsFragment.kt b/app/src/main/java/org/linphone/activities/main/fragments/TabsFragment.kt index 94774681d..b62708eb3 100644 --- a/app/src/main/java/org/linphone/activities/main/fragments/TabsFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/fragments/TabsFragment.kt @@ -54,32 +54,48 @@ class TabsFragment : GenericFragment(), NavController.OnDes binding.setHistoryClickListener { when (findNavController().currentDestination?.id) { - R.id.masterContactsFragment -> sharedViewModel.updateContactsAnimationsBasedOnDestination.value = Event(R.id.masterCallLogsFragment) - R.id.dialerFragment -> sharedViewModel.updateDialerAnimationsBasedOnDestination.value = Event(R.id.masterCallLogsFragment) + R.id.masterContactsFragment -> sharedViewModel.updateContactsAnimationsBasedOnDestination.value = Event( + R.id.masterCallLogsFragment + ) + R.id.dialerFragment -> sharedViewModel.updateDialerAnimationsBasedOnDestination.value = Event( + R.id.masterCallLogsFragment + ) } navigateToCallHistory() } binding.setContactsClickListener { when (findNavController().currentDestination?.id) { - R.id.dialerFragment -> sharedViewModel.updateDialerAnimationsBasedOnDestination.value = Event(R.id.masterContactsFragment) + R.id.dialerFragment -> sharedViewModel.updateDialerAnimationsBasedOnDestination.value = Event( + R.id.masterContactsFragment + ) } - sharedViewModel.updateContactsAnimationsBasedOnDestination.value = Event(findNavController().currentDestination?.id ?: -1) + sharedViewModel.updateContactsAnimationsBasedOnDestination.value = Event( + findNavController().currentDestination?.id ?: -1 + ) navigateToContacts() } binding.setDialerClickListener { when (findNavController().currentDestination?.id) { - R.id.masterContactsFragment -> sharedViewModel.updateContactsAnimationsBasedOnDestination.value = Event(R.id.dialerFragment) + R.id.masterContactsFragment -> sharedViewModel.updateContactsAnimationsBasedOnDestination.value = Event( + R.id.dialerFragment + ) } - sharedViewModel.updateDialerAnimationsBasedOnDestination.value = Event(findNavController().currentDestination?.id ?: -1) + sharedViewModel.updateDialerAnimationsBasedOnDestination.value = Event( + findNavController().currentDestination?.id ?: -1 + ) navigateToDialer() } binding.setChatClickListener { when (findNavController().currentDestination?.id) { - R.id.masterContactsFragment -> sharedViewModel.updateContactsAnimationsBasedOnDestination.value = Event(R.id.masterChatRoomsFragment) - R.id.dialerFragment -> sharedViewModel.updateDialerAnimationsBasedOnDestination.value = Event(R.id.masterChatRoomsFragment) + R.id.masterContactsFragment -> sharedViewModel.updateContactsAnimationsBasedOnDestination.value = Event( + R.id.masterChatRoomsFragment + ) + R.id.dialerFragment -> sharedViewModel.updateDialerAnimationsBasedOnDestination.value = Event( + R.id.masterChatRoomsFragment + ) } navigateToChatRooms() } @@ -102,17 +118,30 @@ class TabsFragment : GenericFragment(), NavController.OnDes ) { if (corePreferences.enableAnimations) { when (destination.id) { - R.id.masterCallLogsFragment -> binding.motionLayout.transitionToState(R.id.call_history) + R.id.masterCallLogsFragment -> binding.motionLayout.transitionToState( + R.id.call_history + ) R.id.masterContactsFragment -> binding.motionLayout.transitionToState(R.id.contacts) R.id.dialerFragment -> binding.motionLayout.transitionToState(R.id.dialer) - R.id.masterChatRoomsFragment -> binding.motionLayout.transitionToState(R.id.chat_rooms) + R.id.masterChatRoomsFragment -> binding.motionLayout.transitionToState( + R.id.chat_rooms + ) } } else { when (destination.id) { - R.id.masterCallLogsFragment -> binding.motionLayout.setTransition(R.id.call_history, R.id.call_history) - R.id.masterContactsFragment -> binding.motionLayout.setTransition(R.id.contacts, R.id.contacts) + R.id.masterCallLogsFragment -> binding.motionLayout.setTransition( + R.id.call_history, + R.id.call_history + ) + R.id.masterContactsFragment -> binding.motionLayout.setTransition( + R.id.contacts, + R.id.contacts + ) R.id.dialerFragment -> binding.motionLayout.setTransition(R.id.dialer, R.id.dialer) - R.id.masterChatRoomsFragment -> binding.motionLayout.setTransition(R.id.chat_rooms, R.id.chat_rooms) + R.id.masterChatRoomsFragment -> binding.motionLayout.setTransition( + R.id.chat_rooms, + R.id.chat_rooms + ) } } } diff --git a/app/src/main/java/org/linphone/activities/main/history/adapters/CallLogsListAdapter.kt b/app/src/main/java/org/linphone/activities/main/history/adapters/CallLogsListAdapter.kt index 0e935aa77..4c20b767e 100644 --- a/app/src/main/java/org/linphone/activities/main/history/adapters/CallLogsListAdapter.kt +++ b/app/src/main/java/org/linphone/activities/main/history/adapters/CallLogsListAdapter.kt @@ -39,7 +39,11 @@ import org.linphone.utils.* class CallLogsListAdapter( selectionVM: ListTopBarViewModel, private val viewLifecycleOwner: LifecycleOwner -) : SelectionListAdapter(selectionVM, CallLogDiffCallback()), HeaderAdapter { +) : SelectionListAdapter( + selectionVM, + CallLogDiffCallback() +), + HeaderAdapter { val selectedCallLogEvent: MutableLiveData> by lazy { MutableLiveData>() } @@ -51,7 +55,9 @@ class CallLogsListAdapter( override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val binding: HistoryListCellBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), - R.layout.history_list_cell, parent, false + R.layout.history_list_cell, + parent, + false ) return ViewHolder(binding) } @@ -115,7 +121,9 @@ class CallLogsListAdapter( return if (previousPosition >= 0) { val previousItemDate = getItem(previousPosition).lastCallLogStartTimestamp !TimestampUtils.isSameDay(date, previousItemDate) - } else true + } else { + true + } } override fun getHeaderViewForPosition(context: Context, position: Int): View { @@ -123,7 +131,9 @@ class CallLogsListAdapter( val date = formatDate(context, callLog.lastCallLogStartTimestamp) val binding: GenericListHeaderBinding = DataBindingUtil.inflate( LayoutInflater.from(context), - R.layout.generic_list_header, null, false + R.layout.generic_list_header, + null, + false ) binding.title = date binding.executePendingBindings() diff --git a/app/src/main/java/org/linphone/activities/main/history/fragments/DetailCallLogFragment.kt b/app/src/main/java/org/linphone/activities/main/history/fragments/DetailCallLogFragment.kt index 0265d3d83..ee2e24d1b 100644 --- a/app/src/main/java/org/linphone/activities/main/history/fragments/DetailCallLogFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/history/fragments/DetailCallLogFragment.kt @@ -62,12 +62,16 @@ class DetailCallLogFragment : GenericFragment() { copy.clean() val address = copy.asStringUriOnly() Log.i("[History] Creating contact with SIP URI [$address]") - sharedViewModel.updateContactsAnimationsBasedOnDestination.value = Event(R.id.masterCallLogsFragment) + sharedViewModel.updateContactsAnimationsBasedOnDestination.value = Event( + R.id.masterCallLogsFragment + ) navigateToContacts(address) } binding.setContactClickListener { - sharedViewModel.updateContactsAnimationsBasedOnDestination.value = Event(R.id.masterCallLogsFragment) + sharedViewModel.updateContactsAnimationsBasedOnDestination.value = Event( + R.id.masterCallLogsFragment + ) val contactId = viewModel.contact.value?.refKey if (contactId != null) { Log.i("[History] Displaying native contact [$contactId]") @@ -90,7 +94,9 @@ class DetailCallLogFragment : GenericFragment() { address.clean() if (coreContext.core.callsNb > 0) { - Log.i("[History] Starting dialer with pre-filled URI [${address.asStringUriOnly()}], is transfer? ${sharedViewModel.pendingCallTransfer}") + Log.i( + "[History] Starting dialer with pre-filled URI [${address.asStringUriOnly()}], is transfer? ${sharedViewModel.pendingCallTransfer}" + ) sharedViewModel.updateDialerAnimationsBasedOnDestination.value = Event(R.id.masterCallLogsFragment) @@ -104,7 +110,9 @@ class DetailCallLogFragment : GenericFragment() { navigateToDialer(args) } else { val localAddress = callLog.localAddress - Log.i("[History] Starting call to ${address.asStringUriOnly()} with local address ${localAddress.asStringUriOnly()}") + Log.i( + "[History] Starting call to ${address.asStringUriOnly()} with local address ${localAddress.asStringUriOnly()}" + ) coreContext.startCall(address, localAddress = localAddress) } } diff --git a/app/src/main/java/org/linphone/activities/main/history/fragments/MasterCallLogsFragment.kt b/app/src/main/java/org/linphone/activities/main/history/fragments/MasterCallLogsFragment.kt index 0e4693589..c10985411 100644 --- a/app/src/main/java/org/linphone/activities/main/history/fragments/MasterCallLogsFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/history/fragments/MasterCallLogsFragment.kt @@ -105,7 +105,9 @@ class MasterCallLogsFragment : MasterFragment val callLog = callLogGroup.lastCallLog @@ -244,8 +250,12 @@ class MasterCallLogsFragment : MasterFragment 0 -> { val cleanAddress = LinphoneUtils.getCleanedAddress(callLog.remoteAddress) - Log.i("[History] Starting dialer with pre-filled URI ${cleanAddress.asStringUriOnly()}, is transfer? ${sharedViewModel.pendingCallTransfer}") - sharedViewModel.updateDialerAnimationsBasedOnDestination.value = Event(R.id.masterCallLogsFragment) + Log.i( + "[History] Starting dialer with pre-filled URI ${cleanAddress.asStringUriOnly()}, is transfer? ${sharedViewModel.pendingCallTransfer}" + ) + sharedViewModel.updateDialerAnimationsBasedOnDestination.value = Event( + R.id.masterCallLogsFragment + ) val args = Bundle() args.putString("URI", cleanAddress.asStringUriOnly()) args.putBoolean("Transfer", sharedViewModel.pendingCallTransfer) @@ -255,7 +265,9 @@ class MasterCallLogsFragment : MasterFragment { val cleanAddress = LinphoneUtils.getCleanedAddress(callLog.remoteAddress) val localAddress = callLogGroup.lastCallLog.localAddress - Log.i("[History] Starting call to ${cleanAddress.asStringUriOnly()} with local address ${localAddress.asStringUriOnly()}") + Log.i( + "[History] Starting call to ${cleanAddress.asStringUriOnly()} with local address ${localAddress.asStringUriOnly()}" + ) coreContext.startCall(cleanAddress, localAddress = localAddress) } } @@ -289,7 +301,9 @@ class MasterCallLogsFragment : MasterFragment= 3600) "HH:mm:ss" else "mm:ss", Locale.getDefault()) + val dateFormat = SimpleDateFormat( + if (callLog.duration >= 3600) "HH:mm:ss" else "mm:ss", + Locale.getDefault() + ) val cal = Calendar.getInstance() cal[0, 0, 0, 0, 0] = callLog.duration dateFormat.format(cal.time) @@ -101,14 +106,25 @@ class CallLogViewModel(val callLog: CallLog, private val isRelated: Boolean = fa val hidePlainChat = corePreferences.forceEndToEndEncryptedChat - val secureChatAllowed = LinphoneUtils.isEndToEndEncryptedChatAvailable() && (corePreferences.allowEndToEndEncryptedChatWithoutPresence || (contact.value?.getPresenceModelForUriOrTel(peerSipUri)?.hasCapability(FriendCapability.LimeX3Dh) ?: false)) + val secureChatAllowed = LinphoneUtils.isEndToEndEncryptedChatAvailable() && ( + corePreferences.allowEndToEndEncryptedChatWithoutPresence || ( + contact.value?.getPresenceModelForUriOrTel( + peerSipUri + )?.hasCapability(FriendCapability.LimeX3Dh) ?: false + ) + ) val relatedCallLogs = MutableLiveData>() private val listener = object : CoreListenerStub() { override fun onCallLogUpdated(core: Core, log: CallLog) { - if (callLog.remoteAddress.weakEqual(log.remoteAddress) && callLog.localAddress.weakEqual(log.localAddress)) { - Log.i("[History Detail] New call log for ${callLog.remoteAddress.asStringUriOnly()} with local address ${callLog.localAddress.asStringUriOnly()}") + if (callLog.remoteAddress.weakEqual(log.remoteAddress) && callLog.localAddress.weakEqual( + log.localAddress + ) + ) { + Log.i( + "[History Detail] New call log for ${callLog.remoteAddress.asStringUriOnly()} with local address ${callLog.localAddress.asStringUriOnly()}" + ) addRelatedCallLogs(arrayListOf(log)) } } @@ -161,11 +177,21 @@ class CallLogViewModel(val callLog: CallLog, private val isRelated: Boolean = fa val organizer = conferenceInfo.organizer if (organizer != null) { organizerParticipantData.value = - ConferenceSchedulingParticipantData(organizer, showLimeBadge = false, showDivider = false) + ConferenceSchedulingParticipantData( + organizer, + showLimeBadge = false, + showDivider = false + ) } val list = arrayListOf() for (participant in conferenceInfo.participants) { - list.add(ConferenceSchedulingParticipantData(participant, showLimeBadge = false, showDivider = true)) + list.add( + ConferenceSchedulingParticipantData( + participant, + showLimeBadge = false, + showDivider = true + ) + ) } conferenceParticipantsData.value = list } @@ -205,7 +231,9 @@ class CallLogViewModel(val callLog: CallLog, private val isRelated: Boolean = fa } } else { waitForChatRoomCreation.value = false - Log.e("[History Detail] Couldn't create chat room with address ${callLog.remoteAddress}") + Log.e( + "[History Detail] Couldn't create chat room with address ${callLog.remoteAddress}" + ) onMessageToNotifyEvent.value = Event(R.string.chat_room_creation_failed_snack) } } diff --git a/app/src/main/java/org/linphone/activities/main/history/viewmodels/CallLogsListViewModel.kt b/app/src/main/java/org/linphone/activities/main/history/viewmodels/CallLogsListViewModel.kt index 4ca463a92..cc41770cc 100644 --- a/app/src/main/java/org/linphone/activities/main/history/viewmodels/CallLogsListViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/history/viewmodels/CallLogsListViewModel.kt @@ -153,7 +153,11 @@ class CallLogsListViewModel : ViewModel() { callLogs.value = when (filter.value) { CallLogsFilter.MISSED -> computeCallLogs(allCallLogs, missed = true, conference = false) - CallLogsFilter.CONFERENCE -> computeCallLogs(allCallLogs, missed = false, conference = true) + CallLogsFilter.CONFERENCE -> computeCallLogs( + allCallLogs, + missed = false, + conference = true + ) else -> computeCallLogs(allCallLogs, missed = false, conference = false) } } diff --git a/app/src/main/java/org/linphone/activities/main/recordings/adapters/RecordingsListAdapter.kt b/app/src/main/java/org/linphone/activities/main/recordings/adapters/RecordingsListAdapter.kt index 839271c38..6151ba58a 100644 --- a/app/src/main/java/org/linphone/activities/main/recordings/adapters/RecordingsListAdapter.kt +++ b/app/src/main/java/org/linphone/activities/main/recordings/adapters/RecordingsListAdapter.kt @@ -39,7 +39,11 @@ import org.linphone.utils.* class RecordingsListAdapter( selectionVM: ListTopBarViewModel, private val viewLifecycleOwner: LifecycleOwner -) : SelectionListAdapter(selectionVM, RecordingDiffCallback()), HeaderAdapter { +) : SelectionListAdapter( + selectionVM, + RecordingDiffCallback() +), + HeaderAdapter { private lateinit var videoSurface: TextureView @@ -50,7 +54,9 @@ class RecordingsListAdapter( override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val binding: RecordingListCellBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), - R.layout.recording_list_cell, parent, false + R.layout.recording_list_cell, + parent, + false ) return ViewHolder(binding) } @@ -104,7 +110,9 @@ class RecordingsListAdapter( return if (previousPosition >= 0) { val previousItemDate = getItem(previousPosition).date !TimestampUtils.isSameDay(date, previousItemDate) - } else true + } else { + true + } } override fun getHeaderViewForPosition(context: Context, position: Int): View { @@ -112,7 +120,9 @@ class RecordingsListAdapter( val date = formatDate(context, recording.date.time) val binding: GenericListHeaderBinding = DataBindingUtil.inflate( LayoutInflater.from(context), - R.layout.generic_list_header, null, false + R.layout.generic_list_header, + null, + false ) binding.title = date binding.executePendingBindings() @@ -126,7 +136,13 @@ class RecordingsListAdapter( } else if (TimestampUtils.isYesterday(date, false)) { return context.getString(R.string.yesterday) } - return TimestampUtils.toString(date, onlyDate = true, timestampInSecs = false, shortDate = false, hideYear = false) + return TimestampUtils.toString( + date, + onlyDate = true, + timestampInSecs = false, + shortDate = false, + hideYear = false + ) } } diff --git a/app/src/main/java/org/linphone/activities/main/recordings/data/RecordingData.kt b/app/src/main/java/org/linphone/activities/main/recordings/data/RecordingData.kt index 6512c77dd..022ffd171 100644 --- a/app/src/main/java/org/linphone/activities/main/recordings/data/RecordingData.kt +++ b/app/src/main/java/org/linphone/activities/main/recordings/data/RecordingData.kt @@ -174,13 +174,18 @@ class RecordingData(val path: String, private val recordingListener: RecordingLi Log.i("[Recording] Using device $playbackSoundCard to make the call recording playback") val localPlayer = coreContext.core.createLocalPlayer(playbackSoundCard, null, null) - if (localPlayer != null) player = localPlayer - else Log.e("[Recording] Couldn't create local player!") + if (localPlayer != null) { + player = localPlayer + } else { + Log.e("[Recording] Couldn't create local player!") + } player.addListener(listener) player.open(path) duration.value = player.duration - formattedDuration.value = SimpleDateFormat("mm:ss", Locale.getDefault()).format(player.duration) // is already in milliseconds + formattedDuration.value = SimpleDateFormat("mm:ss", Locale.getDefault()).format( + player.duration + ) // is already in milliseconds formattedDate.value = DateFormat.getTimeInstance(DateFormat.SHORT).format(date) } diff --git a/app/src/main/java/org/linphone/activities/main/recordings/fragments/RecordingsFragment.kt b/app/src/main/java/org/linphone/activities/main/recordings/fragments/RecordingsFragment.kt index 0f1e40670..b8c48a8a0 100644 --- a/app/src/main/java/org/linphone/activities/main/recordings/fragments/RecordingsFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/recordings/fragments/RecordingsFragment.kt @@ -66,7 +66,9 @@ class RecordingsFragment : MasterFragment() for (payload in coreContext.core.audioPayloadTypes) { - val binding = DataBindingUtil.inflate(LayoutInflater.from(requireContext()), R.layout.settings_widget_switch, null, false) + val binding = DataBindingUtil.inflate( + LayoutInflater.from(requireContext()), + R.layout.settings_widget_switch, + null, + false + ) binding.setVariable(BR.title, payload.mimeType) binding.setVariable(BR.subtitle, "${payload.clockRate} Hz") binding.setVariable(BR.checked, payload.enabled()) diff --git a/app/src/main/java/org/linphone/activities/main/settings/fragments/CallSettingsFragment.kt b/app/src/main/java/org/linphone/activities/main/settings/fragments/CallSettingsFragment.kt index 30323ec19..735febf15 100644 --- a/app/src/main/java/org/linphone/activities/main/settings/fragments/CallSettingsFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/settings/fragments/CallSettingsFragment.kt @@ -99,7 +99,9 @@ class CallSettingsFragment : GenericSettingFragment updateTelecomManagerAccount() } } else { - Log.e("[Telecom Helper] Telecom Helper can't be created, device doesn't support connection service!") + Log.e( + "[Telecom Helper] Telecom Helper can't be created, device doesn't support connection service!" + ) } } } @@ -138,7 +140,9 @@ class CallSettingsFragment : GenericSettingFragment if (Compatibility.hasTelecomManagerFeature(requireContext())) { TelecomHelper.create(requireContext()) } else { - Log.e("[Telecom Helper] Telecom Helper can't be created, device doesn't support connection service") + Log.e( + "[Telecom Helper] Telecom Helper can't be created, device doesn't support connection service" + ) } } updateTelecomManagerAccount() @@ -168,7 +172,9 @@ class CallSettingsFragment : GenericSettingFragment for (index in grantResults.indices) { val result = grantResults[index] if (result != PackageManager.PERMISSION_GRANTED) { - Log.w("[Call Settings] ${permissions[index]} permission denied but required for telecom manager") + Log.w( + "[Call Settings] ${permissions[index]} permission denied but required for telecom manager" + ) viewModel.useTelecomManager.value = false corePreferences.useTelecomManager = false return @@ -179,7 +185,9 @@ class CallSettingsFragment : GenericSettingFragment TelecomHelper.create(requireContext()) updateTelecomManagerAccount() } else { - Log.e("[Telecom Helper] Telecom Helper can't be created, device doesn't support connection service") + Log.e( + "[Telecom Helper] Telecom Helper can't be created, device doesn't support connection service" + ) } } } diff --git a/app/src/main/java/org/linphone/activities/main/settings/fragments/ContactsSettingsFragment.kt b/app/src/main/java/org/linphone/activities/main/settings/fragments/ContactsSettingsFragment.kt index c27dda7b1..a00ba90a4 100644 --- a/app/src/main/java/org/linphone/activities/main/settings/fragments/ContactsSettingsFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/settings/fragments/ContactsSettingsFragment.kt @@ -67,7 +67,9 @@ class ContactsSettingsFragment : GenericSettingFragment() { val navHostFragment = childFragmentManager.findFragmentById(R.id.settings_nav_container) as NavHostFragment if (navHostFragment.navController.currentDestination?.id == R.id.emptySettingsFragment) { - Log.i("[Settings] Foldable device has been folded, closing side pane with empty fragment") + Log.i( + "[Settings] Foldable device has been folded, closing side pane with empty fragment" + ) binding.slidingPane.closePane() } } diff --git a/app/src/main/java/org/linphone/activities/main/settings/fragments/VideoSettingsFragment.kt b/app/src/main/java/org/linphone/activities/main/settings/fragments/VideoSettingsFragment.kt index 498bf8f76..6ad8561bd 100644 --- a/app/src/main/java/org/linphone/activities/main/settings/fragments/VideoSettingsFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/settings/fragments/VideoSettingsFragment.kt @@ -76,7 +76,12 @@ class VideoSettingsFragment : GenericSettingFragment() for (payload in coreContext.core.videoPayloadTypes) { - val binding = DataBindingUtil.inflate(LayoutInflater.from(requireContext()), R.layout.settings_widget_switch_and_text, null, false) + val binding = DataBindingUtil.inflate( + LayoutInflater.from(requireContext()), + R.layout.settings_widget_switch_and_text, + null, + false + ) binding.setVariable(BR.switch_title, payload.mimeType) binding.setVariable(BR.switch_subtitle, "") binding.setVariable(BR.text_title, "recv-fmtp") diff --git a/app/src/main/java/org/linphone/activities/main/settings/viewmodels/AccountSettingsViewModel.kt b/app/src/main/java/org/linphone/activities/main/settings/viewmodels/AccountSettingsViewModel.kt index 47a7ed980..55abd1ad3 100644 --- a/app/src/main/java/org/linphone/activities/main/settings/viewmodels/AccountSettingsViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/settings/viewmodels/AccountSettingsViewModel.kt @@ -89,7 +89,9 @@ class AccountSettingsViewModel(val account: Account) : GenericSettingsViewModel( message: String ) { if (state == RegistrationState.Cleared && account == accountToDelete) { - Log.i("[Account Settings] Account to remove ([${account.params.identityAddress?.asStringUriOnly()}]) registration is now cleared, removing it") + Log.i( + "[Account Settings] Account to remove ([${account.params.identityAddress?.asStringUriOnly()}]) registration is now cleared, removing it" + ) waitForUnregister.value = false deleteAccount(account) } else { @@ -121,7 +123,9 @@ class AccountSettingsViewModel(val account: Account) : GenericSettingsViewModel( params.identityAddress = newIdentityAddress account.params = params } else { - Log.e("[Account Settings] Failed to create identity address sip:$newValue@$domain") + Log.e( + "[Account Settings] Failed to create identity address sip:$newValue@$domain" + ) } } } @@ -157,10 +161,19 @@ class AccountSettingsViewModel(val account: Account) : GenericSettingsViewModel( val identity = params.identityAddress if (identity != null && identity.username != null) { val newAuthInfo = Factory.instance() - .createAuthInfo(identity.username!!, userId.value, newValue, null, null, identity.domain) + .createAuthInfo( + identity.username!!, + userId.value, + newValue, + null, + null, + identity.domain + ) core.addAuthInfo(newAuthInfo) } else { - Log.e("[Account Settings] Failed to find the user's identity, can't create a new auth info") + Log.e( + "[Account Settings] Failed to find the user's identity, can't create a new auth info" + ) } } } @@ -394,7 +407,9 @@ class AccountSettingsViewModel(val account: Account) : GenericSettingsViewModel( val conferenceFactoryUriListener = object : SettingListenerStub() { override fun onTextValueChanged(newValue: String) { val params = account.params.clone() - Log.i("[Account Settings] Forcing conference factory on proxy config ${params.identityAddress?.asString()} to value: $newValue") + Log.i( + "[Account Settings] Forcing conference factory on proxy config ${params.identityAddress?.asString()} to value: $newValue" + ) params.conferenceFactoryUri = newValue account.params = params } @@ -405,7 +420,9 @@ class AccountSettingsViewModel(val account: Account) : GenericSettingsViewModel( override fun onTextValueChanged(newValue: String) { val params = account.params.clone() val uri = coreContext.core.interpretUrl(newValue, false) - Log.i("[Account Settings] Forcing audio/video conference factory on proxy config ${params.identityAddress?.asString()} to value: $newValue") + Log.i( + "[Account Settings] Forcing audio/video conference factory on proxy config ${params.identityAddress?.asString()} to value: $newValue" + ) params.audioVideoConferenceFactoryAddress = uri account.params = params } @@ -510,7 +527,9 @@ class AccountSettingsViewModel(val account: Account) : GenericSettingsViewModel( } fun startDeleteAccount() { - Log.i("[Account Settings] Starting to delete account [${account.params.identityAddress?.asStringUriOnly()}]") + Log.i( + "[Account Settings] Starting to delete account [${account.params.identityAddress?.asStringUriOnly()}]" + ) accountToDelete = account val registered = account.state == RegistrationState.Ok @@ -521,7 +540,9 @@ class AccountSettingsViewModel(val account: Account) : GenericSettingsViewModel( for (accountIterator in core.accountList) { if (account != accountIterator) { core.defaultAccount = accountIterator - Log.i("[Account Settings] New default account is [${accountIterator.params.identityAddress?.asStringUriOnly()}]") + Log.i( + "[Account Settings] New default account is [${accountIterator.params.identityAddress?.asStringUriOnly()}]" + ) break } } @@ -532,10 +553,14 @@ class AccountSettingsViewModel(val account: Account) : GenericSettingsViewModel( account.params = params if (!registered) { - Log.w("[Account Settings] Account isn't registered, don't unregister before removing it") + Log.w( + "[Account Settings] Account isn't registered, don't unregister before removing it" + ) deleteAccount(account) } else { - Log.i("[Account Settings] Waiting for account registration to be cleared before removing it") + Log.i( + "[Account Settings] Waiting for account registration to be cleared before removing it" + ) } } } diff --git a/app/src/main/java/org/linphone/activities/main/settings/viewmodels/AudioSettingsViewModel.kt b/app/src/main/java/org/linphone/activities/main/settings/viewmodels/AudioSettingsViewModel.kt index fa733b711..192106b83 100644 --- a/app/src/main/java/org/linphone/activities/main/settings/viewmodels/AudioSettingsViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/settings/viewmodels/AudioSettingsViewModel.kt @@ -44,7 +44,9 @@ class AudioSettingsViewModel : GenericSettingsViewModel() { core.isEchoCancellationEnabled = newValue if (!newValue) { core.resetEchoCancellationCalibration() - softwareEchoCalibration.value = prefs.getString(R.string.audio_settings_echo_canceller_calibration_summary) + softwareEchoCalibration.value = prefs.getString( + R.string.audio_settings_echo_canceller_calibration_summary + ) } } } @@ -161,7 +163,9 @@ class AudioSettingsViewModel : GenericSettingsViewModel() { softwareEchoCanceller.value = core.isEchoCancellationEnabled adaptiveRateControl.value = core.isAdaptiveRateControlEnabled softwareEchoCalibration.value = if (core.echoCancellationCalibration > 0) { - prefs.getString(R.string.audio_settings_echo_cancellation_calibration_value).format(core.echoCancellationCalibration) + prefs.getString(R.string.audio_settings_echo_cancellation_calibration_value).format( + core.echoCancellationCalibration + ) } else { prefs.getString(R.string.audio_settings_echo_canceller_calibration_summary) } @@ -183,7 +187,9 @@ class AudioSettingsViewModel : GenericSettingsViewModel() { core.addListener(listener) core.startEchoCancellerCalibration() - softwareEchoCalibration.value = prefs.getString(R.string.audio_settings_echo_cancellation_calibration_started) + softwareEchoCalibration.value = prefs.getString( + R.string.audio_settings_echo_cancellation_calibration_started + ) } fun echoCancellerCalibrationFinished(status: EcCalibratorStatus, delay: Int) { @@ -191,31 +197,43 @@ class AudioSettingsViewModel : GenericSettingsViewModel() { when (status) { EcCalibratorStatus.DoneNoEcho -> { - softwareEchoCalibration.value = prefs.getString(R.string.audio_settings_echo_cancellation_calibration_no_echo) + softwareEchoCalibration.value = prefs.getString( + R.string.audio_settings_echo_cancellation_calibration_no_echo + ) softwareEchoCanceller.value = false } EcCalibratorStatus.Done -> { - softwareEchoCalibration.value = prefs.getString(R.string.audio_settings_echo_cancellation_calibration_value).format(delay) + softwareEchoCalibration.value = prefs.getString( + R.string.audio_settings_echo_cancellation_calibration_value + ).format(delay) softwareEchoCanceller.value = true } EcCalibratorStatus.Failed -> { - softwareEchoCalibration.value = prefs.getString(R.string.audio_settings_echo_cancellation_calibration_failed) + softwareEchoCalibration.value = prefs.getString( + R.string.audio_settings_echo_cancellation_calibration_failed + ) } EcCalibratorStatus.InProgress -> { // We should never get here but still - softwareEchoCalibration.value = prefs.getString(R.string.audio_settings_echo_cancellation_calibration_started) + softwareEchoCalibration.value = prefs.getString( + R.string.audio_settings_echo_cancellation_calibration_started + ) } } } fun startEchoTester() { echoTesterIsRunning = true - echoTesterStatus.value = prefs.getString(R.string.audio_settings_echo_tester_summary_is_running) + echoTesterStatus.value = prefs.getString( + R.string.audio_settings_echo_tester_summary_is_running + ) core.startEchoTester(0) } fun stopEchoTester() { echoTesterIsRunning = false - echoTesterStatus.value = prefs.getString(R.string.audio_settings_echo_tester_summary_is_stopped) + echoTesterStatus.value = prefs.getString( + R.string.audio_settings_echo_tester_summary_is_stopped + ) core.stopEchoTester() } diff --git a/app/src/main/java/org/linphone/activities/main/settings/viewmodels/CallSettingsViewModel.kt b/app/src/main/java/org/linphone/activities/main/settings/viewmodels/CallSettingsViewModel.kt index 6bc91ed3d..c0bf4583c 100644 --- a/app/src/main/java/org/linphone/activities/main/settings/viewmodels/CallSettingsViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/settings/viewmodels/CallSettingsViewModel.kt @@ -291,7 +291,9 @@ class CallSettingsViewModel : GenericSettingsViewModel() { } if (core.mediaEncryptionSupported(MediaEncryption.ZRTP)) { if (core.postQuantumAvailable) { - labels.add(prefs.getString(R.string.call_settings_media_encryption_zrtp_post_quantum)) + labels.add( + prefs.getString(R.string.call_settings_media_encryption_zrtp_post_quantum) + ) } else { labels.add(prefs.getString(R.string.call_settings_media_encryption_zrtp)) } diff --git a/app/src/main/java/org/linphone/activities/main/settings/viewmodels/LdapSettingsViewModel.kt b/app/src/main/java/org/linphone/activities/main/settings/viewmodels/LdapSettingsViewModel.kt index ab6abcf15..0abd83f0c 100644 --- a/app/src/main/java/org/linphone/activities/main/settings/viewmodels/LdapSettingsViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/settings/viewmodels/LdapSettingsViewModel.kt @@ -123,7 +123,9 @@ class LdapSettingsViewModel(private val ldap: Ldap, val index: String) : Generic val ldapCertCheckListener = object : SettingListenerStub() { override fun onListValueChanged(position: Int) { val params = ldap.params.clone() - params.serverCertificatesVerificationMode = LdapCertVerificationMode.fromInt(ldapCertCheckValues[position]) + params.serverCertificatesVerificationMode = LdapCertVerificationMode.fromInt( + ldapCertCheckValues[position] + ) ldap.params = params ldapCertCheckIndex.value = position } @@ -291,6 +293,8 @@ class LdapSettingsViewModel(private val ldap: Ldap, val index: String) : Generic ldapCertCheckValues.add(LdapCertVerificationMode.Enabled.toInt()) ldapCertCheckLabels.value = labels - ldapCertCheckIndex.value = ldapCertCheckValues.indexOf(ldap.params.serverCertificatesVerificationMode.toInt()) + ldapCertCheckIndex.value = ldapCertCheckValues.indexOf( + ldap.params.serverCertificatesVerificationMode.toInt() + ) } } diff --git a/app/src/main/java/org/linphone/activities/main/settings/viewmodels/VideoSettingsViewModel.kt b/app/src/main/java/org/linphone/activities/main/settings/viewmodels/VideoSettingsViewModel.kt index d871e341a..68278a2da 100644 --- a/app/src/main/java/org/linphone/activities/main/settings/viewmodels/VideoSettingsViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/settings/viewmodels/VideoSettingsViewModel.kt @@ -143,7 +143,9 @@ class VideoSettingsViewModel : GenericSettingsViewModel() { val index = labels.indexOf(core.videoDevice) if (index == -1) { val firstDevice = cameraDeviceLabels.value.orEmpty().firstOrNull() - Log.w("[Video Settings] Device not found in labels list: ${core.videoDevice}, replace it by $firstDevice") + Log.w( + "[Video Settings] Device not found in labels list: ${core.videoDevice}, replace it by $firstDevice" + ) if (firstDevice != null) { cameraDeviceIndex.value = 0 core.videoDevice = firstDevice diff --git a/app/src/main/java/org/linphone/activities/main/sidemenu/fragments/SideMenuFragment.kt b/app/src/main/java/org/linphone/activities/main/sidemenu/fragments/SideMenuFragment.kt index 34182931e..a994a7ac6 100644 --- a/app/src/main/java/org/linphone/activities/main/sidemenu/fragments/SideMenuFragment.kt +++ b/app/src/main/java/org/linphone/activities/main/sidemenu/fragments/SideMenuFragment.kt @@ -142,7 +142,10 @@ class SideMenuFragment : GenericFragment() { override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode == Activity.RESULT_OK) { lifecycleScope.launch { - val contactImageFilePath = FileUtils.getFilePathFromPickerIntent(data, temporaryPicturePath) + val contactImageFilePath = FileUtils.getFilePathFromPickerIntent( + data, + temporaryPicturePath + ) if (contactImageFilePath != null) { viewModel.setPictureFromPath(contactImageFilePath) } @@ -176,7 +179,10 @@ class SideMenuFragment : GenericFragment() { val chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.chat_message_pick_file_dialog)) - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(arrayOf())) + chooserIntent.putExtra( + Intent.EXTRA_INITIAL_INTENTS, + cameraIntents.toArray(arrayOf()) + ) startActivityForResult(chooserIntent, 0) } @@ -186,11 +192,15 @@ class SideMenuFragment : GenericFragment() { goToAccountSettings: Boolean = false, accountIdentity: String = "" ) { - val dialogViewModel = DialogViewModel(getString(R.string.settings_password_protection_dialog_title)) + val dialogViewModel = DialogViewModel( + getString(R.string.settings_password_protection_dialog_title) + ) dialogViewModel.showIcon = true dialogViewModel.iconResource = R.drawable.security_toggle_icon_green dialogViewModel.showPassword = true - dialogViewModel.passwordTitle = getString(R.string.settings_password_protection_dialog_input_hint) + dialogViewModel.passwordTitle = getString( + R.string.settings_password_protection_dialog_input_hint + ) val dialog = DialogUtils.getDialog(requireContext(), dialogViewModel) dialogViewModel.showCancelButton { @@ -206,13 +216,19 @@ class SideMenuFragment : GenericFragment() { } else { val authInfo = defaultAccount.findAuthInfo() if (authInfo == null) { - Log.e("[Side Menu] No auth info found for account [${defaultAccount.params.identityAddress?.asString()}], can't check password input!") + Log.e( + "[Side Menu] No auth info found for account [${defaultAccount.params.identityAddress?.asString()}], can't check password input!" + ) (requireActivity() as MainActivity).showSnackBar(R.string.error_unexpected) } else { val expectedHash = authInfo.ha1 if (expectedHash == null) { - Log.e("[Side Menu] No ha1 found in auth info, can't check password input!") - (requireActivity() as MainActivity).showSnackBar(R.string.error_unexpected) + Log.e( + "[Side Menu] No ha1 found in auth info, can't check password input!" + ) + (requireActivity() as MainActivity).showSnackBar( + R.string.error_unexpected + ) } else { val hashAlgorithm = authInfo.algorithm ?: "MD5" val userId = (authInfo.userid ?: authInfo.username).orEmpty() @@ -225,8 +241,12 @@ class SideMenuFragment : GenericFragment() { hashAlgorithm ) if (computedHash != expectedHash) { - Log.e("[Side Menu] Computed hash [$computedHash] using userId [$userId], realm [$realm] and algorithm [$hashAlgorithm] doesn't match expected hash!") - (requireActivity() as MainActivity).showSnackBar(R.string.settings_password_protection_dialog_invalid_input) + Log.e( + "[Side Menu] Computed hash [$computedHash] using userId [$userId], realm [$realm] and algorithm [$hashAlgorithm] doesn't match expected hash!" + ) + (requireActivity() as MainActivity).showSnackBar( + R.string.settings_password_protection_dialog_invalid_input + ) } else { if (goToSettings) { navigateToSettings() diff --git a/app/src/main/java/org/linphone/activities/main/viewmodels/TabsViewModel.kt b/app/src/main/java/org/linphone/activities/main/viewmodels/TabsViewModel.kt index b55e0252c..f637c71a3 100644 --- a/app/src/main/java/org/linphone/activities/main/viewmodels/TabsViewModel.kt +++ b/app/src/main/java/org/linphone/activities/main/viewmodels/TabsViewModel.kt @@ -41,7 +41,10 @@ class TabsViewModel : ViewModel() { val chatUnreadCountTranslateY = MutableLiveData() private val bounceAnimator: ValueAnimator by lazy { - ValueAnimator.ofFloat(AppUtils.getDimension(R.dimen.tabs_fragment_unread_count_bounce_offset), 0f).apply { + ValueAnimator.ofFloat( + AppUtils.getDimension(R.dimen.tabs_fragment_unread_count_bounce_offset), + 0f + ).apply { addUpdateListener { val value = it.animatedValue as Float historyMissedCountTranslateY.value = -value diff --git a/app/src/main/java/org/linphone/activities/voip/CallActivity.kt b/app/src/main/java/org/linphone/activities/voip/CallActivity.kt index c97afbb44..a0dca5daa 100644 --- a/app/src/main/java/org/linphone/activities/voip/CallActivity.kt +++ b/app/src/main/java/org/linphone/activities/voip/CallActivity.kt @@ -104,14 +104,20 @@ class CallActivity : ProximitySensorActivity() { controlsViewModel.proximitySensorEnabled.observe( this ) { enabled -> - Log.i("[Call Activity] ${if (enabled) "Enabling" else "Disabling"} proximity sensor (if possible)") + Log.i( + "[Call Activity] ${if (enabled) "Enabling" else "Disabling"} proximity sensor (if possible)" + ) enableProximitySensor(enabled) } controlsViewModel.isVideoEnabled.observe( this ) { enabled -> - Compatibility.enableAutoEnterPiP(this, enabled, conferenceViewModel.conferenceExists.value == true) + Compatibility.enableAutoEnterPiP( + this, + enabled, + conferenceViewModel.conferenceExists.value == true + ) } controlsViewModel.callStatsVisible.observe( @@ -136,10 +142,14 @@ class CallActivity : ProximitySensorActivity() { ) { callData -> val call = callData.call if (call.conference == null) { - Log.i("[Call Activity] Current call isn't linked to a conference, switching to SingleCall fragment") + Log.i( + "[Call Activity] Current call isn't linked to a conference, switching to SingleCall fragment" + ) navigateToActiveCall() } else { - Log.i("[Call Activity] Current call is linked to a conference, switching to ConferenceCall fragment") + Log.i( + "[Call Activity] Current call is linked to a conference, switching to ConferenceCall fragment" + ) navigateToConferenceCall() } } @@ -157,10 +167,14 @@ class CallActivity : ProximitySensorActivity() { this ) { exists -> if (exists) { - Log.i("[Call Activity] Found active conference, changing switching to ConferenceCall fragment") + Log.i( + "[Call Activity] Found active conference, changing switching to ConferenceCall fragment" + ) navigateToConferenceCall() } else if (coreContext.core.callsNb > 0) { - Log.i("[Call Activity] Conference no longer exists, switching to SingleCall fragment") + Log.i( + "[Call Activity] Conference no longer exists, switching to SingleCall fragment" + ) navigateToActiveCall() } } @@ -193,7 +207,9 @@ class CallActivity : ProximitySensorActivity() { ) { super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig) - Log.i("[Call Activity] onPictureInPictureModeChanged: is in PiP mode? $isInPictureInPictureMode") + Log.i( + "[Call Activity] onPictureInPictureModeChanged: is in PiP mode? $isInPictureInPictureMode" + ) if (::controlsViewModel.isInitialized) { // To hide UI except for TextureViews controlsViewModel.pipMode.value = isInPictureInPictureMode @@ -299,7 +315,9 @@ class CallActivity : ProximitySensorActivity() { Log.i("[Call Activity] BLUETOOTH_CONNECT permission has been granted") } Manifest.permission.WRITE_EXTERNAL_STORAGE -> if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { - Log.i("[Call Activity] WRITE_EXTERNAL_STORAGE permission has been granted, taking snapshot") + Log.i( + "[Call Activity] WRITE_EXTERNAL_STORAGE permission has been granted, taking snapshot" + ) controlsViewModel.takeSnapshot() } } @@ -310,7 +328,9 @@ class CallActivity : ProximitySensorActivity() { override fun onLayoutChanges(foldingFeature: FoldingFeature?) { foldingFeature ?: return - Log.i("[Call Activity] Folding feature state changed: ${foldingFeature.state}, orientation is ${foldingFeature.orientation}") + Log.i( + "[Call Activity] Folding feature state changed: ${foldingFeature.state}, orientation is ${foldingFeature.orientation}" + ) controlsViewModel.foldingState.value = foldingFeature } diff --git a/app/src/main/java/org/linphone/activities/voip/data/CallData.kt b/app/src/main/java/org/linphone/activities/voip/data/CallData.kt index 25050638e..857d86c86 100644 --- a/app/src/main/java/org/linphone/activities/voip/data/CallData.kt +++ b/app/src/main/java/org/linphone/activities/voip/data/CallData.kt @@ -101,7 +101,10 @@ open class CallData(val call: Call) : GenericContactData(call.remoteAddress) { scope.launch { if (Compatibility.addImageToMediaStore(coreContext.context, content)) { Log.i("[Call] Added snapshot ${content.name} to Media Store") - val message = String.format(AppUtils.getString(R.string.call_screenshot_taken), content.name) + val message = String.format( + AppUtils.getString(R.string.call_screenshot_taken), + content.name + ) Toast.makeText(coreContext.context, message, Toast.LENGTH_SHORT).show() } else { Log.e("[Call] Something went wrong while copying file to Media Store...") @@ -188,7 +191,9 @@ open class CallData(val call: Call) : GenericContactData(call.remoteAddress) { Call.State.PausedByRemote -> { val conference = call.conference if (conference != null && conference.me.isFocus) { - Log.w("[Call] State is paused by remote but we are the focus of the conference, so considering call as active") + Log.w( + "[Call] State is paused by remote but we are the focus of the conference, so considering call as active" + ) false } else { true @@ -237,7 +242,9 @@ open class CallData(val call: Call) : GenericContactData(call.remoteAddress) { if (conference != null) { Log.d("[Call] Found conference attached to call") remoteConferenceSubject.value = LinphoneUtils.getConferenceSubject(conference) - Log.d("[Call] Found conference related to this call with subject [${remoteConferenceSubject.value}]") + Log.d( + "[Call] Found conference related to this call with subject [${remoteConferenceSubject.value}]" + ) val participantsList = arrayListOf() for (participant in conference.participantList) { @@ -246,12 +253,23 @@ open class CallData(val call: Call) : GenericContactData(call.remoteAddress) { } conferenceParticipants.value = participantsList - conferenceParticipantsCountLabel.value = coreContext.context.getString(R.string.conference_participants_title, participantsList.size) + conferenceParticipantsCountLabel.value = coreContext.context.getString( + R.string.conference_participants_title, + participantsList.size + ) } else { val conferenceAddress = LinphoneUtils.getConferenceAddress(call) - val conferenceInfo = if (conferenceAddress != null) coreContext.core.findConferenceInformationFromUri(conferenceAddress) else null + val conferenceInfo = if (conferenceAddress != null) { + coreContext.core.findConferenceInformationFromUri( + conferenceAddress + ) + } else { + null + } if (conferenceInfo != null) { - Log.d("[Call] Found matching conference info with subject: ${conferenceInfo.subject}") + Log.d( + "[Call] Found matching conference info with subject: ${conferenceInfo.subject}" + ) remoteConferenceSubject.value = conferenceInfo.subject val participantsList = arrayListOf() @@ -271,7 +289,10 @@ open class CallData(val call: Call) : GenericContactData(call.remoteAddress) { } conferenceParticipants.value = participantsList - conferenceParticipantsCountLabel.value = coreContext.context.getString(R.string.conference_participants_title, participantsList.size) + conferenceParticipantsCountLabel.value = coreContext.context.getString( + R.string.conference_participants_title, + participantsList.size + ) } } } diff --git a/app/src/main/java/org/linphone/activities/voip/data/ConferenceParticipantData.kt b/app/src/main/java/org/linphone/activities/voip/data/ConferenceParticipantData.kt index ae05689b2..43d54d4a5 100644 --- a/app/src/main/java/org/linphone/activities/voip/data/ConferenceParticipantData.kt +++ b/app/src/main/java/org/linphone/activities/voip/data/ConferenceParticipantData.kt @@ -38,33 +38,47 @@ class ConferenceParticipantData( init { isAdmin.value = participant.isAdmin isMeAdmin.value = conference.me.isAdmin - Log.i("[Conference Participant] Participant ${participant.address.asStringUriOnly()} is ${if (participant.isAdmin) "admin" else "not admin"}") + Log.i( + "[Conference Participant] Participant ${participant.address.asStringUriOnly()} is ${if (participant.isAdmin) "admin" else "not admin"}" + ) } fun setAdmin() { if (conference.me.isAdmin) { - Log.i("[Conference Participant] Participant ${participant.address.asStringUriOnly()} will be set as admin") + Log.i( + "[Conference Participant] Participant ${participant.address.asStringUriOnly()} will be set as admin" + ) conference.setParticipantAdminStatus(participant, true) } else { - Log.e("[Conference Participant] You aren't admin, you can't change participants admin rights") + Log.e( + "[Conference Participant] You aren't admin, you can't change participants admin rights" + ) } } fun unsetAdmin() { if (conference.me.isAdmin) { - Log.i("[Conference Participant] Participant ${participant.address.asStringUriOnly()} will be unset as admin") + Log.i( + "[Conference Participant] Participant ${participant.address.asStringUriOnly()} will be unset as admin" + ) conference.setParticipantAdminStatus(participant, false) } else { - Log.e("[Conference Participant] You aren't admin, you can't change participants admin rights") + Log.e( + "[Conference Participant] You aren't admin, you can't change participants admin rights" + ) } } fun removeParticipantFromConference() { if (conference.me.isAdmin) { - Log.i("[Conference Participant] Removing participant ${participant.address.asStringUriOnly()} from conference") + Log.i( + "[Conference Participant] Removing participant ${participant.address.asStringUriOnly()} from conference" + ) conference.removeParticipant(participant) } else { - Log.e("[Conference Participant] Can't remove participant ${participant.address.asStringUriOnly()} from conference, you aren't admin") + Log.e( + "[Conference Participant] Can't remove participant ${participant.address.asStringUriOnly()} from conference, you aren't admin" + ) } } } diff --git a/app/src/main/java/org/linphone/activities/voip/data/ConferenceParticipantDeviceData.kt b/app/src/main/java/org/linphone/activities/voip/data/ConferenceParticipantDeviceData.kt index 4091c4f8e..887a9b832 100644 --- a/app/src/main/java/org/linphone/activities/voip/data/ConferenceParticipantDeviceData.kt +++ b/app/src/main/java/org/linphone/activities/voip/data/ConferenceParticipantDeviceData.kt @@ -55,12 +55,16 @@ class ConferenceParticipantDeviceData( participantDevice: ParticipantDevice, isSpeaking: Boolean ) { - Log.i("[Conference Participant Device] Participant [${participantDevice.address.asStringUriOnly()}] is ${if (isSpeaking) "speaking" else "not speaking"}") + Log.i( + "[Conference Participant Device] Participant [${participantDevice.address.asStringUriOnly()}] is ${if (isSpeaking) "speaking" else "not speaking"}" + ) this@ConferenceParticipantDeviceData.isSpeaking.value = isSpeaking } override fun onIsMuted(participantDevice: ParticipantDevice, isMuted: Boolean) { - Log.i("[Conference Participant Device] Participant [${participantDevice.address.asStringUriOnly()}] is ${if (isMuted) "muted" else "not muted"}") + Log.i( + "[Conference Participant Device] Participant [${participantDevice.address.asStringUriOnly()}] is ${if (isMuted) "muted" else "not muted"}" + ) this@ConferenceParticipantDeviceData.isMuted.value = isMuted } @@ -68,7 +72,9 @@ class ConferenceParticipantDeviceData( participantDevice: ParticipantDevice, state: ParticipantDeviceState ) { - Log.i("[Conference Participant Device] Participant [${participantDevice.address.asStringUriOnly()}] state has changed: $state") + Log.i( + "[Conference Participant Device] Participant [${participantDevice.address.asStringUriOnly()}] state has changed: $state" + ) when (state) { ParticipantDeviceState.Joining, ParticipantDeviceState.Alerting -> isJoining.value = true ParticipantDeviceState.OnHold -> { @@ -89,7 +95,9 @@ class ConferenceParticipantDeviceData( streamType: StreamType ) { if (streamType == StreamType.Video) { - Log.i("[Conference Participant Device] Participant [${participantDevice.address.asStringUriOnly()}] video capability changed to $direction") + Log.i( + "[Conference Participant Device] Participant [${participantDevice.address.asStringUriOnly()}] video capability changed to $direction" + ) isSendingVideo.value = direction == MediaDirection.SendRecv || direction == MediaDirection.SendOnly } } @@ -100,7 +108,9 @@ class ConferenceParticipantDeviceData( streamType: StreamType ) { if (streamType == StreamType.Video) { - Log.i("[Conference Participant Device] Participant [${participantDevice.address.asStringUriOnly()}] video availability changed to ${if (available) "available" else "unavailable"}") + Log.i( + "[Conference Participant Device] Participant [${participantDevice.address.asStringUriOnly()}] video availability changed to ${if (available) "available" else "unavailable"}" + ) videoAvailable.value = available if (available) { updateWindowId(textureView) @@ -110,7 +120,9 @@ class ConferenceParticipantDeviceData( } init { - Log.i("[Conference Participant Device] Created device width Address [${participantDevice.address.asStringUriOnly()}], is it myself? $isMe") + Log.i( + "[Conference Participant Device] Created device width Address [${participantDevice.address.asStringUriOnly()}], is it myself? $isMe" + ) participantDevice.addListener(listener) isSpeaking.value = false @@ -124,7 +136,9 @@ class ConferenceParticipantDeviceData( val state = participantDevice.state isJoining.value = state == ParticipantDeviceState.Joining || state == ParticipantDeviceState.Alerting - Log.i("[Conference Participant Device] State for participant [${participantDevice.address.asStringUriOnly()}] is $state") + Log.i( + "[Conference Participant Device] State for participant [${participantDevice.address.asStringUriOnly()}] is $state" + ) videoEnabled.value = isVideoAvailableAndSendReceive() videoEnabled.addSource(videoAvailable) { @@ -134,7 +148,9 @@ class ConferenceParticipantDeviceData( videoEnabled.value = isVideoAvailableAndSendReceive() } - Log.i("[Conference Participant Device] Participant [${participantDevice.address.asStringUriOnly()}], is in conf? ${isInConference.value}, is video available? ${videoAvailable.value} ($videoCapability), is mic muted? ${isMuted.value}") + Log.i( + "[Conference Participant Device] Participant [${participantDevice.address.asStringUriOnly()}], is in conf? ${isInConference.value}, is video available? ${videoAvailable.value} ($videoCapability), is mic muted? ${isMuted.value}" + ) } override fun destroy() { @@ -154,7 +170,9 @@ class ConferenceParticipantDeviceData( fun setTextureView(tv: TextureView) { textureView = tv - Log.i("[Conference Participant Device] Setting textureView [$textureView] for participant [${participantDevice.address.asStringUriOnly()}]") + Log.i( + "[Conference Participant Device] Setting textureView [$textureView] for participant [${participantDevice.address.asStringUriOnly()}]" + ) updateWindowId(textureView) } diff --git a/app/src/main/java/org/linphone/activities/voip/data/StatItemData.kt b/app/src/main/java/org/linphone/activities/voip/data/StatItemData.kt index 5057aefe0..26374ee94 100644 --- a/app/src/main/java/org/linphone/activities/voip/data/StatItemData.kt +++ b/app/src/main/java/org/linphone/activities/voip/data/StatItemData.kt @@ -65,8 +65,20 @@ class StatItemData(val type: StatType) { val payloadType = if (stats.type == StreamType.Audio) call.currentParams.usedAudioPayloadType else call.currentParams.usedVideoPayloadType payloadType ?: return value.value = when (type) { - StatType.CAPTURE -> if (stats.type == StreamType.Audio) audioDeviceToString(call.inputAudioDevice) else call.core.videoDevice - StatType.PLAYBACK -> if (stats.type == StreamType.Audio) audioDeviceToString(call.outputAudioDevice) else call.core.videoDisplayFilter + StatType.CAPTURE -> if (stats.type == StreamType.Audio) { + audioDeviceToString( + call.inputAudioDevice + ) + } else { + call.core.videoDevice + } + StatType.PLAYBACK -> if (stats.type == StreamType.Audio) { + audioDeviceToString( + call.outputAudioDevice + ) + } else { + call.core.videoDisplayFilter + } StatType.PAYLOAD -> "${payloadType.mimeType}/${payloadType.clockRate / 1000} kHz" StatType.ENCODER -> call.core.mediastreamerFactory.getDecoderText(payloadType.mimeType) StatType.DECODER -> call.core.mediastreamerFactory.getEncoderText(payloadType.mimeType) @@ -86,14 +98,22 @@ class StatItemData(val type: StatType) { when (call.currentParams.mediaEncryption) { MediaEncryption.ZRTP -> { if (stats.isZrtpKeyAgreementAlgoPostQuantum) { - AppUtils.getString(R.string.call_settings_media_encryption_zrtp_post_quantum) + AppUtils.getString( + R.string.call_settings_media_encryption_zrtp_post_quantum + ) } else { AppUtils.getString(R.string.call_settings_media_encryption_zrtp) } } - MediaEncryption.DTLS -> AppUtils.getString(R.string.call_settings_media_encryption_dtls) - MediaEncryption.SRTP -> AppUtils.getString(R.string.call_settings_media_encryption_srtp) - MediaEncryption.None -> AppUtils.getString(R.string.call_settings_media_encryption_none) + MediaEncryption.DTLS -> AppUtils.getString( + R.string.call_settings_media_encryption_dtls + ) + MediaEncryption.SRTP -> AppUtils.getString( + R.string.call_settings_media_encryption_srtp + ) + MediaEncryption.None -> AppUtils.getString( + R.string.call_settings_media_encryption_none + ) else -> "Unexpected!" } } diff --git a/app/src/main/java/org/linphone/activities/voip/fragments/CallsListFragment.kt b/app/src/main/java/org/linphone/activities/voip/fragments/CallsListFragment.kt index 39a8b0e03..2cd8ba9a3 100644 --- a/app/src/main/java/org/linphone/activities/voip/fragments/CallsListFragment.kt +++ b/app/src/main/java/org/linphone/activities/voip/fragments/CallsListFragment.kt @@ -99,7 +99,9 @@ class CallsListFragment : GenericVideoPreviewFragment() { val remoteSipUri = arguments?.getString("RemoteSipUri") var chatRoom: ChatRoom? = null if (localSipUri != null && remoteSipUri != null) { - Log.i("[Chat] Found local [$localSipUri] & remote [$remoteSipUri] addresses in arguments") + Log.i( + "[Chat] Found local [$localSipUri] & remote [$remoteSipUri] addresses in arguments" + ) val localAddress = Factory.instance().createAddress(localSipUri) val remoteSipAddress = Factory.instance().createAddress(remoteSipUri) - chatRoom = coreContext.core.searchChatRoom(null, localAddress, remoteSipAddress, arrayOfNulls(0)) + chatRoom = coreContext.core.searchChatRoom( + null, + localAddress, + remoteSipAddress, + arrayOfNulls(0) + ) } chatRoom ?: return @@ -184,10 +191,10 @@ class ChatFragment : GenericFragment() { if (resultCode == Activity.RESULT_OK) { lifecycleScope.launch { for ( - fileToUploadPath in FileUtils.getFilesPathFromPickerIntent( - data, - chatSendingViewModel.temporaryFileUploadPath - ) + fileToUploadPath in FileUtils.getFilesPathFromPickerIntent( + data, + chatSendingViewModel.temporaryFileUploadPath + ) ) { chatSendingViewModel.addAttachment(fileToUploadPath) } diff --git a/app/src/main/java/org/linphone/activities/voip/fragments/ConferenceAddParticipantsFragment.kt b/app/src/main/java/org/linphone/activities/voip/fragments/ConferenceAddParticipantsFragment.kt index 29d832b6d..4b588a2eb 100644 --- a/app/src/main/java/org/linphone/activities/voip/fragments/ConferenceAddParticipantsFragment.kt +++ b/app/src/main/java/org/linphone/activities/voip/fragments/ConferenceAddParticipantsFragment.kt @@ -68,7 +68,9 @@ class ConferenceAddParticipantsFragment : GenericFragment(R.id.conference_active_speaker_remote_video) + Log.i( + "[Conference Call] Local participant is in conference and current layout is active speaker, updating Core's native window id" + ) + val window = binding.root.findViewById( + R.id.conference_active_speaker_remote_video + ) coreContext.core.nativeVideoWindowId = window - val preview = binding.root.findViewById(R.id.local_preview_video_surface) + val preview = binding.root.findViewById( + R.id.local_preview_video_surface + ) if (preview != null) { conferenceViewModel.meParticipant.value?.setTextureView(preview) } } else { - Log.i("[Conference Call] Either not in conference or current layout isn't active speaker, updating Core's native window id") + Log.i( + "[Conference Call] Either not in conference or current layout isn't active speaker, updating Core's native window id" + ) coreContext.core.nativeVideoWindowId = null } } @@ -129,11 +139,17 @@ class ConferenceCallFragment : GenericFragment conferenceViewModel.maxParticipantsForMosaicLayout ) { - Log.w("[Conference Call] More than ${conferenceViewModel.maxParticipantsForMosaicLayout} participants (${it.size}), forcing active speaker layout") + Log.w( + "[Conference Call] More than ${conferenceViewModel.maxParticipantsForMosaicLayout} participants (${it.size}), forcing active speaker layout" + ) conferenceViewModel.changeLayout(ConferenceDisplayMode.ACTIVE_SPEAKER, false) refreshConferenceFragment() // Can't use SnackBar whilst changing fragment - Toast.makeText(requireContext(), R.string.conference_too_many_participants_for_mosaic_layout, Toast.LENGTH_LONG).show() + Toast.makeText( + requireContext(), + R.string.conference_too_many_participants_for_mosaic_layout, + Toast.LENGTH_LONG + ).show() } } @@ -173,7 +189,11 @@ class ConferenceCallFragment : GenericFragment val conference = call.conference if (conference != null && conferenceViewModel.conference.value == null) { - Log.i("[Conference Call] Found conference attached to call and no conference in dedicated view model, init & configure it") + Log.i( + "[Conference Call] Found conference attached to call and no conference in dedicated view model, init & configure it" + ) conferenceViewModel.initConference(conference) conferenceViewModel.configureConference(conference) } @@ -271,7 +293,9 @@ class ConferenceCallFragment : GenericFragment { - Log.i("[Conference Call] Conference has video enabled but our device hasn't joined yet") + Log.i( + "[Conference Call] Conference has video enabled but our device hasn't joined yet" + ) } - conference.me.devices.find { it.isInConference && it.getStreamAvailability(StreamType.Video) } != null -> { - Log.i("[Conference Call] Conference has video enabled & our device has video enabled, enabling full screen mode") + conference.me.devices.find { + it.isInConference && it.getStreamAvailability( + StreamType.Video + ) + } != null -> { + Log.i( + "[Conference Call] Conference has video enabled & our device has video enabled, enabling full screen mode" + ) controlsViewModel.fullScreenMode.value = true } else -> { - Log.i("[Conference Call] Conference has video enabled but our device video is disabled") + Log.i( + "[Conference Call] Conference has video enabled but our device video is disabled" + ) } } } @@ -323,7 +357,9 @@ class ConferenceCallFragment : GenericFragment(R.id.conference_constraint_layout) + val constraintLayout = binding.root.findViewById( + R.id.conference_constraint_layout + ) ?: return val set = ConstraintSet() set.clone(constraintLayout) @@ -358,14 +394,18 @@ class ConferenceCallFragment : GenericFragment switchToActiveSpeakerLayoutWhenAlone() 2 -> switchToActiveSpeakerLayoutForTwoParticipants() else -> switchToActiveSpeakerLayoutForMoreThanTwoParticipants() } } else { - Log.w("[Conference] Active speaker layout not adjusted, conference state is: ${conferenceViewModel.conference.value?.state}") + Log.w( + "[Conference] Active speaker layout not adjusted, conference state is: ${conferenceViewModel.conference.value?.state}" + ) } } @@ -443,7 +483,9 @@ class ConferenceCallFragment : GenericFragment(R.id.too_many_participants_dialog) + val dialog = binding.root.findViewById( + R.id.too_many_participants_dialog + ) dialog?.visibility = View.GONE } } diff --git a/app/src/main/java/org/linphone/activities/voip/fragments/SingleCallFragment.kt b/app/src/main/java/org/linphone/activities/voip/fragments/SingleCallFragment.kt index b20888c83..49411a72f 100644 --- a/app/src/main/java/org/linphone/activities/voip/fragments/SingleCallFragment.kt +++ b/app/src/main/java/org/linphone/activities/voip/fragments/SingleCallFragment.kt @@ -84,15 +84,21 @@ class SingleCallFragment : GenericVideoPreviewFragment { - Log.i("[Single Call] New current call is in [$callState] state, switching to IncomingCall fragment") + Log.i( + "[Single Call] New current call is in [$callState] state, switching to IncomingCall fragment" + ) navigateToIncomingCall() } Call.State.OutgoingInit, Call.State.OutgoingProgress, Call.State.OutgoingRinging, Call.State.OutgoingEarlyMedia -> { - Log.i("[Single Call] New current call is in [$callState] state, switching to OutgoingCall fragment") + Log.i( + "[Single Call] New current call is in [$callState] state, switching to OutgoingCall fragment" + ) navigateToOutgoingCall() } else -> { - Log.i("[Single Call] New current call is in [$callState] state, updating call UI") + Log.i( + "[Single Call] New current call is in [$callState] state, updating call UI" + ) val timer = binding.root.findViewById(R.id.active_call_timer) timer.base = SystemClock.elapsedRealtime() - (1000 * call.duration) // Linphone timestamps are in seconds @@ -100,7 +106,9 @@ class SingleCallFragment : GenericVideoPreviewFragment() { } } - val viewModel = DialogViewModel(getString(R.string.zrtp_dialog_explanation), getString(R.string.zrtp_dialog_title)) + val viewModel = DialogViewModel( + getString(R.string.zrtp_dialog_explanation), + getString(R.string.zrtp_dialog_title) + ) viewModel.showZrtp = true viewModel.zrtpReadSas = toRead.uppercase(Locale.getDefault()) viewModel.zrtpListenSas = toListen.uppercase(Locale.getDefault()) diff --git a/app/src/main/java/org/linphone/activities/voip/viewmodels/CallsViewModel.kt b/app/src/main/java/org/linphone/activities/voip/viewmodels/CallsViewModel.kt index ab9dceb53..20439c445 100644 --- a/app/src/main/java/org/linphone/activities/voip/viewmodels/CallsViewModel.kt +++ b/app/src/main/java/org/linphone/activities/voip/viewmodels/CallsViewModel.kt @@ -108,7 +108,9 @@ class CallsViewModel : ViewModel() { if (state == Call.State.End || state == Call.State.Released || state == Call.State.Error) { removeCallFromList(call) if (core.callsNb > 0) { - Log.i("[Calls] Call has ended but there are still at least one other existing call") + Log.i( + "[Calls] Call has ended but there are still at least one other existing call" + ) callEndedEvent.value = Event(call) } } else if (call.state == Call.State.UpdatedByRemote) { @@ -140,7 +142,9 @@ class CallsViewModel : ViewModel() { val currentCall = coreContext.core.currentCall ?: coreContext.core.calls.firstOrNull() if (currentCall != null) { - Log.i("[Calls] Initializing ViewModel using call [${currentCall.remoteAddress.asStringUriOnly()}] as current") + Log.i( + "[Calls] Initializing ViewModel using call [${currentCall.remoteAddress.asStringUriOnly()}] as current" + ) currentCallData.value?.destroy() val viewModel = CallData(currentCall) @@ -242,7 +246,9 @@ class CallsViewModel : ViewModel() { // Make sure the current call data is matching the only call val firstData = callsData.value?.firstOrNull() if (firstData != null && currentCallData.value != firstData) { - Log.i("[Calls] Only one call in Core and the current call data doesn't match it, updating it") + Log.i( + "[Calls] Only one call in Core and the current call data doesn't match it, updating it" + ) currentCallData.value = firstData!! } return @@ -252,7 +258,9 @@ class CallsViewModel : ViewModel() { call.state != Call.State.Error && call.state != Call.State.End && call.state != Call.State.Released } if (firstCall != null && currentCallData.value?.call != firstCall) { - Log.i("[Calls] Using [${firstCall.remoteAddress.asStringUriOnly()}] call as \"current\" call") + Log.i( + "[Calls] Using [${firstCall.remoteAddress.asStringUriOnly()}] call as \"current\" call" + ) callToUse = firstCall } } @@ -265,14 +273,18 @@ class CallsViewModel : ViewModel() { var found = false for (callData in callsData.value.orEmpty()) { if (callData.call == callToUse) { - Log.i("[Calls] Updating current call to: ${callData.call.remoteAddress.asStringUriOnly()}") + Log.i( + "[Calls] Updating current call to: ${callData.call.remoteAddress.asStringUriOnly()}" + ) currentCallData.value = callData found = true break } } if (!found) { - Log.w("[Calls] Call with ID [${callToUse.callLog.callId}] not found in calls data list, shouldn't happen!") + Log.w( + "[Calls] Call with ID [${callToUse.callLog.callId}] not found in calls data list, shouldn't happen!" + ) val viewModel = CallData(callToUse) currentCallData.value = viewModel } diff --git a/app/src/main/java/org/linphone/activities/voip/viewmodels/ConferenceParticipantsViewModel.kt b/app/src/main/java/org/linphone/activities/voip/viewmodels/ConferenceParticipantsViewModel.kt index 69f178007..a3dc7aa9c 100644 --- a/app/src/main/java/org/linphone/activities/voip/viewmodels/ConferenceParticipantsViewModel.kt +++ b/app/src/main/java/org/linphone/activities/voip/viewmodels/ConferenceParticipantsViewModel.kt @@ -48,7 +48,9 @@ class ConferenceParticipantsViewModel(val conference: Conference) : ContactsSele participant.address.weakEqual(address) } if (participant == null) { - Log.i("[Conference Participants] Participant ${address.asStringUriOnly()} will be added to group") + Log.i( + "[Conference Participants] Participant ${address.asStringUriOnly()} will be added to group" + ) conference.addParticipant(address) } } @@ -59,7 +61,9 @@ class ConferenceParticipantsViewModel(val conference: Conference) : ContactsSele participant.address.weakEqual(address) } if (member == null) { - Log.w("[Conference Participants] Participant ${participant.address.asStringUriOnly()} will be removed from conference") + Log.w( + "[Conference Participants] Participant ${participant.address.asStringUriOnly()} will be removed from conference" + ) conference.removeParticipant(participant) } } diff --git a/app/src/main/java/org/linphone/activities/voip/viewmodels/ConferenceViewModel.kt b/app/src/main/java/org/linphone/activities/voip/viewmodels/ConferenceViewModel.kt index 09a75dc0a..515d1f2a9 100644 --- a/app/src/main/java/org/linphone/activities/voip/viewmodels/ConferenceViewModel.kt +++ b/app/src/main/java/org/linphone/activities/voip/viewmodels/ConferenceViewModel.kt @@ -100,7 +100,9 @@ class ConferenceViewModel : ViewModel() { conference: Conference, participantDevice: ParticipantDevice ) { - Log.i("[Conference] Participant device added: ${participantDevice.address.asStringUriOnly()}") + Log.i( + "[Conference] Participant device added: ${participantDevice.address.asStringUriOnly()}" + ) addParticipantDevice(participantDevice) if (conferenceParticipantDevices.value.orEmpty().size == 2) { @@ -114,7 +116,9 @@ class ConferenceViewModel : ViewModel() { conference: Conference, participantDevice: ParticipantDevice ) { - Log.i("[Conference] Participant device removed: ${participantDevice.address.asStringUriOnly()}") + Log.i( + "[Conference] Participant device removed: ${participantDevice.address.asStringUriOnly()}" + ) removeParticipantDevice(participantDevice) when (conferenceParticipantDevices.value.orEmpty().size) { @@ -133,22 +137,32 @@ class ConferenceViewModel : ViewModel() { conference: Conference, participant: Participant ) { - Log.i("[Conference] Participant admin status changed [${participant.address.asStringUriOnly()}] is ${if (participant.isAdmin) "now admin" else "no longer admin"}") + Log.i( + "[Conference] Participant admin status changed [${participant.address.asStringUriOnly()}] is ${if (participant.isAdmin) "now admin" else "no longer admin"}" + ) isMeAdmin.value = conference.me.isAdmin updateParticipantsList(conference) if (conference.me.address.weakEqual(participant.address)) { - Log.i("[Conference] Found me participant [${participant.address.asStringUriOnly()}]") + Log.i( + "[Conference] Found me participant [${participant.address.asStringUriOnly()}]" + ) val participantData = ConferenceParticipantData(conference, participant) participantAdminStatusChangedEvent.value = Event(participantData) return } - val participantData = conferenceParticipants.value.orEmpty().find { data -> data.participant.address.weakEqual(participant.address) } + val participantData = conferenceParticipants.value.orEmpty().find { data -> + data.participant.address.weakEqual( + participant.address + ) + } if (participantData != null) { participantAdminStatusChangedEvent.value = Event(participantData) } else { - Log.w("[Conference] Failed to find participant [${participant.address.asStringUriOnly()}] in conferenceParticipants list") + Log.w( + "[Conference] Failed to find participant [${participant.address.asStringUriOnly()}] in conferenceParticipants list" + ) } } @@ -181,7 +195,9 @@ class ConferenceViewModel : ViewModel() { conference: Conference, participantDevice: ParticipantDevice ) { - Log.i("[Conference] Participant [${participantDevice.address.asStringUriOnly()}] is currently being displayed as active speaker") + Log.i( + "[Conference] Participant [${participantDevice.address.asStringUriOnly()}] is currently being displayed as active speaker" + ) val device = conferenceParticipantDevices.value.orEmpty().find { it.participantDevice.address.weakEqual(participantDevice.address) } @@ -192,7 +208,9 @@ class ConferenceViewModel : ViewModel() { device.isActiveSpeaker.value = true speakingParticipant.value = device!! } else if (device == null) { - Log.w("[Conference] Participant device [${participantDevice.address.asStringUriOnly()}] is the active speaker but couldn't find it in devices list") + Log.w( + "[Conference] Participant device [${participantDevice.address.asStringUriOnly()}] is the active speaker but couldn't find it in devices list" + ) } } @@ -249,7 +267,9 @@ class ConferenceViewModel : ViewModel() { conferenceParticipants.value = arrayListOf() conferenceParticipantDevices.value = arrayListOf() activeSpeakerConferenceParticipantDevices.addSource(conferenceParticipantDevices) { - activeSpeakerConferenceParticipantDevices.value = conferenceParticipantDevices.value.orEmpty().drop(1) + activeSpeakerConferenceParticipantDevices.value = conferenceParticipantDevices.value.orEmpty().drop( + 1 + ) } subject.value = AppUtils.getString(R.string.conference_default_title) @@ -285,8 +305,12 @@ class ConferenceViewModel : ViewModel() { conference.value?.removeListener(conferenceListener) conferenceParticipants.value.orEmpty().forEach(ConferenceParticipantData::destroy) - conferenceParticipantDevices.value.orEmpty().forEach(ConferenceParticipantDeviceData::destroy) - activeSpeakerConferenceParticipantDevices.value.orEmpty().forEach(ConferenceParticipantDeviceData::destroy) + conferenceParticipantDevices.value.orEmpty().forEach( + ConferenceParticipantDeviceData::destroy + ) + activeSpeakerConferenceParticipantDevices.value.orEmpty().forEach( + ConferenceParticipantDeviceData::destroy + ) super.onCleared() } @@ -306,7 +330,9 @@ class ConferenceViewModel : ViewModel() { Log.i("[Conference] Stopping conference recording") conference.value?.stopRecording() } else { - val path = LinphoneUtils.getRecordingFilePathForConference(conference.value?.currentParams?.subject) + val path = LinphoneUtils.getRecordingFilePathForConference( + conference.value?.currentParams?.subject + ) Log.i("[Conference] Starting recording in file $path") conference.value?.startRecording(path) } @@ -365,11 +391,15 @@ class ConferenceViewModel : ViewModel() { fun switchLayoutFromAudioOnlyToActiveSpeaker() { if (conferenceDisplayMode.value == ConferenceDisplayMode.AUDIO_ONLY) { - Log.i("[Conference] Trying to switch from AUDIO_ONLY to ACTIVE_SPEAKER and toggle video ON") + Log.i( + "[Conference] Trying to switch from AUDIO_ONLY to ACTIVE_SPEAKER and toggle video ON" + ) changeLayout(ConferenceDisplayMode.ACTIVE_SPEAKER, true) waitForNextStreamsRunningToUpdateLayout = true } else { - Log.w("[Conference] Can't switch from AUDIO_ONLY to ACTIVE_SPEAKER as current display mode isn't AUDIO_ONLY but ${conferenceDisplayMode.value}") + Log.w( + "[Conference] Can't switch from AUDIO_ONLY to ACTIVE_SPEAKER as current display mode isn't AUDIO_ONLY but ${conferenceDisplayMode.value}" + ) } } @@ -434,7 +464,9 @@ class ConferenceViewModel : ViewModel() { val list = sortDevicesDataList(conferenceParticipantDevices.value.orEmpty()) conferenceParticipantDevices.value = list - Log.i("[Conference] Current layout is [${conferenceDisplayMode.value}], video direction is [${params.videoDirection}]") + Log.i( + "[Conference] Current layout is [${conferenceDisplayMode.value}], video direction is [${params.videoDirection}]" + ) } private fun terminateConference(conference: Conference) { @@ -444,8 +476,12 @@ class ConferenceViewModel : ViewModel() { conference.removeListener(conferenceListener) conferenceParticipants.value.orEmpty().forEach(ConferenceParticipantData::destroy) - conferenceParticipantDevices.value.orEmpty().forEach(ConferenceParticipantDeviceData::destroy) - activeSpeakerConferenceParticipantDevices.value.orEmpty().forEach(ConferenceParticipantDeviceData::destroy) + conferenceParticipantDevices.value.orEmpty().forEach( + ConferenceParticipantDeviceData::destroy + ) + activeSpeakerConferenceParticipantDevices.value.orEmpty().forEach( + ConferenceParticipantDeviceData::destroy + ) conferenceParticipants.value = arrayListOf() conferenceParticipantDevices.value = arrayListOf() @@ -459,7 +495,9 @@ class ConferenceViewModel : ViewModel() { Log.i("[Conference] Conference has ${participantsList.size} participants") for (participant in participantsList) { val participantDevices = participant.devices - Log.i("[Conference] Participant found: ${participant.address.asStringUriOnly()} with ${participantDevices.size} device(s)") + Log.i( + "[Conference] Participant found: ${participant.address.asStringUriOnly()} with ${participantDevices.size} device(s)" + ) val participantData = ConferenceParticipantData(conference, participant) participants.add(participantData) @@ -469,8 +507,12 @@ class ConferenceViewModel : ViewModel() { } private fun updateParticipantsDevicesList(conference: Conference) { - conferenceParticipantDevices.value.orEmpty().forEach(ConferenceParticipantDeviceData::destroy) - activeSpeakerConferenceParticipantDevices.value.orEmpty().forEach(ConferenceParticipantDeviceData::destroy) + conferenceParticipantDevices.value.orEmpty().forEach( + ConferenceParticipantDeviceData::destroy + ) + activeSpeakerConferenceParticipantDevices.value.orEmpty().forEach( + ConferenceParticipantDeviceData::destroy + ) val devices = arrayListOf() val participantsList = conference.participantList @@ -481,15 +523,21 @@ class ConferenceViewModel : ViewModel() { for (participant in participantsList) { val participantDevices = participant.devices - Log.i("[Conference] Participant found: ${participant.address.asStringUriOnly()} with ${participantDevices.size} device(s)") + Log.i( + "[Conference] Participant found: ${participant.address.asStringUriOnly()} with ${participantDevices.size} device(s)" + ) for (device in participantDevices) { - Log.i("[Conference] Participant device found: ${device.name} (${device.address.asStringUriOnly()})") + Log.i( + "[Conference] Participant device found: ${device.name} (${device.address.asStringUriOnly()})" + ) val deviceData = ConferenceParticipantDeviceData(device, false) devices.add(deviceData) if (activelySpeakingParticipantDevice == device) { - Log.i("[Conference] Actively speaking participant device found: ${device.name} (${device.address.asStringUriOnly()})") + Log.i( + "[Conference] Actively speaking participant device found: ${device.name} (${device.address.asStringUriOnly()})" + ) speakingParticipant.value = deviceData deviceData.isActiveSpeaker.value = true foundActivelySpeakingParticipantDevice = true @@ -498,14 +546,18 @@ class ConferenceViewModel : ViewModel() { } if (!foundActivelySpeakingParticipantDevice && devices.isNotEmpty()) { - Log.w("[Conference] Actively speaking participant device not found, using first participant device available") + Log.w( + "[Conference] Actively speaking participant device not found, using first participant device available" + ) val deviceData = devices.first() speakingParticipant.value = deviceData deviceData.isActiveSpeaker.value = true } for (device in conference.me.devices) { - Log.i("[Conference] Participant device for myself found: ${device.name} (${device.address.asStringUriOnly()})") + Log.i( + "[Conference] Participant device for myself found: ${device.name} (${device.address.asStringUriOnly()})" + ) val deviceData = ConferenceParticipantDeviceData(device, true) devices.add(deviceData) meParticipant.value = deviceData @@ -524,11 +576,15 @@ class ConferenceViewModel : ViewModel() { it.participantDevice.address.weakEqual(device.address) } if (existingDevice != null) { - Log.e("[Conference] Participant is already in devices list: ${device.name} (${device.address.asStringUriOnly()})") + Log.e( + "[Conference] Participant is already in devices list: ${device.name} (${device.address.asStringUriOnly()})" + ) return } - Log.i("[Conference] New participant device found: ${device.name} (${device.address.asStringUriOnly()})") + Log.i( + "[Conference] New participant device found: ${device.name} (${device.address.asStringUriOnly()})" + ) val deviceData = ConferenceParticipantDeviceData(device, false) devices.add(deviceData) @@ -553,7 +609,9 @@ class ConferenceViewModel : ViewModel() { devices.add(participantDevice) } else { if (speakingParticipant.value == participantDevice) { - Log.w("[Conference] Removed participant device was the actively speaking participant device") + Log.w( + "[Conference] Removed participant device was the actively speaking participant device" + ) removedDeviceWasActiveSpeaker = true } participantDevice.destroy() @@ -562,11 +620,15 @@ class ConferenceViewModel : ViewModel() { val devicesCount = devices.size if (devicesCount == conferenceParticipantDevices.value.orEmpty().size) { - Log.e("[Conference] Failed to remove participant device: ${device.name} (${device.address.asStringUriOnly()})") + Log.e( + "[Conference] Failed to remove participant device: ${device.name} (${device.address.asStringUriOnly()})" + ) } if (removedDeviceWasActiveSpeaker && devicesCount > 1) { - Log.w("[Conference] Updating actively speaking participant device using first one available") + Log.w( + "[Conference] Updating actively speaking participant device using first one available" + ) // Using second device as first is ourselves val deviceData = devices[1] speakingParticipant.value = deviceData @@ -593,7 +655,9 @@ class ConferenceViewModel : ViewModel() { sortedList.size - 1 } if (index != expectedIndex) { - Log.i("[Conference] Me device data is at index $index, moving it to index $expectedIndex") + Log.i( + "[Conference] Me device data is at index $index, moving it to index $expectedIndex" + ) sortedList.removeAt(index) sortedList.add(expectedIndex, meDeviceData) } diff --git a/app/src/main/java/org/linphone/activities/voip/viewmodels/ControlsViewModel.kt b/app/src/main/java/org/linphone/activities/voip/viewmodels/ControlsViewModel.kt index e91135669..13b0f999c 100644 --- a/app/src/main/java/org/linphone/activities/voip/viewmodels/ControlsViewModel.kt +++ b/app/src/main/java/org/linphone/activities/voip/viewmodels/ControlsViewModel.kt @@ -165,7 +165,10 @@ class ControlsViewModel : ViewModel() { val extraButtonsMenuTranslateY = MutableLiveData() private val extraButtonsMenuAnimator: ValueAnimator by lazy { - ValueAnimator.ofFloat(AppUtils.getDimension(R.dimen.voip_call_extra_buttons_translate_y), 0f).apply { + ValueAnimator.ofFloat( + AppUtils.getDimension(R.dimen.voip_call_extra_buttons_translate_y), + 0f + ).apply { addUpdateListener { val value = it.animatedValue as Float extraButtonsMenuTranslateY.value = value @@ -204,8 +207,12 @@ class ControlsViewModel : ViewModel() { coreContext.core.addListener(listener) fullScreenMode.value = false - extraButtonsMenuTranslateY.value = AppUtils.getDimension(R.dimen.voip_call_extra_buttons_translate_y) - audioRoutesMenuTranslateY.value = AppUtils.getDimension(R.dimen.voip_audio_routes_menu_translate_y) + extraButtonsMenuTranslateY.value = AppUtils.getDimension( + R.dimen.voip_call_extra_buttons_translate_y + ) + audioRoutesMenuTranslateY.value = AppUtils.getDimension( + R.dimen.voip_audio_routes_menu_translate_y + ) audioRoutesSelected.value = false forceDisableProximitySensor.value = false @@ -249,7 +256,7 @@ class ControlsViewModel : ViewModel() { fun answer() { val currentCall = coreContext.core.currentCall ?: coreContext.core.calls.find { - call -> + call -> call.state == Call.State.IncomingReceived || call.state == Call.State.IncomingEarlyMedia } if (currentCall != null) { @@ -301,7 +308,9 @@ class ControlsViewModel : ViewModel() { fun toggleVideo() { if (!PermissionHelper.get().hasCameraPermission()) { - Log.w("[Call Controls] Camera permission isn't granted, asking it before toggling video") + Log.w( + "[Call Controls] Camera permission isn't granted, asking it before toggling video" + ) askPermissionEvent.value = Event(Manifest.permission.CAMERA) return } @@ -330,7 +339,9 @@ class ControlsViewModel : ViewModel() { } } else { params?.isVideoEnabled = params?.isVideoEnabled == false - Log.i("[Call Controls] Updating call with video enabled set to ${params?.isVideoEnabled}") + Log.i( + "[Call Controls] Updating call with video enabled set to ${params?.isVideoEnabled}" + ) } currentCall.update(params) } else { @@ -366,7 +377,9 @@ class ControlsViewModel : ViewModel() { fun hideExtraButtons(skipAnimation: Boolean) { // Animation must be skipped when called from Fragment's onPause() ! if (skipAnimation) { - extraButtonsMenuTranslateY.value = AppUtils.getDimension(R.dimen.voip_call_extra_buttons_translate_y) + extraButtonsMenuTranslateY.value = AppUtils.getDimension( + R.dimen.voip_call_extra_buttons_translate_y + ) } else { extraButtonsMenuAnimator.reverse() } @@ -446,11 +459,15 @@ class ControlsViewModel : ViewModel() { it.state == Call.State.Paused } if (callToTransferTo == null) { - Log.e("[Call Controls] Couldn't find a call in Paused state to transfer current call to") + Log.e( + "[Call Controls] Couldn't find a call in Paused state to transfer current call to" + ) return } - Log.i("[Call Controls] Doing an attended transfer between active call [${currentCall.remoteAddress.asStringUriOnly()}] and paused call [${callToTransferTo.remoteAddress.asStringUriOnly()}]") + Log.i( + "[Call Controls] Doing an attended transfer between active call [${currentCall.remoteAddress.asStringUriOnly()}] and paused call [${callToTransferTo.remoteAddress.asStringUriOnly()}]" + ) val result = callToTransferTo.transferToAnother(currentCall) if (result != 0) { Log.e("[Call Controls] Attended transfer failed!") @@ -509,7 +526,9 @@ class ControlsViewModel : ViewModel() { if (!AudioRouteUtils.isHeadsetAudioRouteAvailable() && !AudioRouteUtils.isBluetoothAudioRouteCurrentlyUsed() ) { - Log.i("[Call Controls] Video enabled and no wired headset not bluetooth in use, routing audio to speaker") + Log.i( + "[Call Controls] Video enabled and no wired headset not bluetooth in use, routing audio to speaker" + ) AudioRouteUtils.routeAudioToSpeaker() } } @@ -529,11 +548,17 @@ class ControlsViewModel : ViewModel() { private fun shouldProximitySensorBeEnabled(): Boolean { if (forceDisableProximitySensor.value == true) { - Log.i("[Call Controls] Forcing proximity sensor to be disabled (usually in incoming/outgoing call fragments)") + Log.i( + "[Call Controls] Forcing proximity sensor to be disabled (usually in incoming/outgoing call fragments)" + ) } else if (isVideoEnabled.value == true) { - Log.i("[Call Controls] Active call current params says video is enabled, proximity sensor will be disabled") + Log.i( + "[Call Controls] Active call current params says video is enabled, proximity sensor will be disabled" + ) } else if (nonEarpieceOutputAudioDevice.value == true) { - Log.i("[Call Controls] Current audio route is not earpiece, proximity sensor will be disabled") + Log.i( + "[Call Controls] Current audio route is not earpiece, proximity sensor will be disabled" + ) } return forceDisableProximitySensor.value == false && diff --git a/app/src/main/java/org/linphone/activities/voip/views/GridBoxLayout.kt b/app/src/main/java/org/linphone/activities/voip/views/GridBoxLayout.kt index 69cf9d6cc..37a57c1dc 100644 --- a/app/src/main/java/org/linphone/activities/voip/views/GridBoxLayout.kt +++ b/app/src/main/java/org/linphone/activities/voip/views/GridBoxLayout.kt @@ -30,9 +30,12 @@ import org.linphone.core.tools.Log class GridBoxLayout : GridLayout { companion object { private val placementMatrix = arrayOf( - intArrayOf(1, 2, 3, 4, 5, 6), intArrayOf(1, 1, 2, 2, 3, 3), - intArrayOf(1, 1, 1, 2, 2, 2), intArrayOf(1, 1, 1, 1, 2, 2), - intArrayOf(1, 1, 1, 1, 1, 2), intArrayOf(1, 1, 1, 1, 1, 1) + intArrayOf(1, 2, 3, 4, 5, 6), + intArrayOf(1, 1, 2, 2, 3, 3), + intArrayOf(1, 1, 1, 2, 2, 2), + intArrayOf(1, 1, 1, 1, 2, 2), + intArrayOf(1, 1, 1, 1, 1, 2), + intArrayOf(1, 1, 1, 1, 1, 1) ) } @@ -72,7 +75,9 @@ class GridBoxLayout : GridLayout { val maxChild = placementMatrix[0].size if (childCount > maxChild) { val maxMosaicParticipants = corePreferences.maxConferenceParticipantsForMosaicLayout - Log.e("[GridBoxLayout] $childCount children but placementMatrix only knows how to display $maxChild (max allowed participants for grid layout in settings is $maxMosaicParticipants)") + Log.e( + "[GridBoxLayout] $childCount children but placementMatrix only knows how to display $maxChild (max allowed participants for grid layout in settings is $maxMosaicParticipants)" + ) return } @@ -102,8 +107,15 @@ class GridBoxLayout : GridLayout { } if (centerContent) { - setPadding((availableSize.first - (columnCount * cellSize)) / 2, (availableSize.second - (rowCount * cellSize)) / 2, (availableSize.first - (columnCount * cellSize)) / 2, (availableSize.second - (rowCount * cellSize)) / 2) + setPadding( + (availableSize.first - (columnCount * cellSize)) / 2, + (availableSize.second - (rowCount * cellSize)) / 2, + (availableSize.first - (columnCount * cellSize)) / 2, + (availableSize.second - (rowCount * cellSize)) / 2 + ) } - Log.d("[GridBoxLayout] cellsize=$cellSize columns=$columnCount rows=$rowCount availablesize=$availableSize") + Log.d( + "[GridBoxLayout] cellsize=$cellSize columns=$columnCount rows=$rowCount availablesize=$availableSize" + ) } } diff --git a/app/src/main/java/org/linphone/activities/voip/views/RoundCornersTextureView.kt b/app/src/main/java/org/linphone/activities/voip/views/RoundCornersTextureView.kt index 55c3f4143..80a4279a6 100644 --- a/app/src/main/java/org/linphone/activities/voip/views/RoundCornersTextureView.kt +++ b/app/src/main/java/org/linphone/activities/voip/views/RoundCornersTextureView.kt @@ -60,13 +60,19 @@ class RoundCornersTextureView : CaptureTextureView { ).apply { try { mAlignTopRight = getBoolean(R.styleable.RoundCornersTextureView_alignTopRight, true) - val mode = getInteger(R.styleable.RoundCornersTextureView_displayMode, DisplayMode.BLACK_BARS.ordinal) + val mode = getInteger( + R.styleable.RoundCornersTextureView_displayMode, + DisplayMode.BLACK_BARS.ordinal + ) mDisplayMode = when (mode) { 1 -> DisplayMode.OCCUPY_ALL_SPACE 2 -> DisplayMode.HYBRID else -> DisplayMode.BLACK_BARS } - mRadius = getFloat(R.styleable.RoundCornersTextureView_radius, context.resources.getDimension(R.dimen.voip_round_corners_texture_view_radius)) + mRadius = getFloat( + R.styleable.RoundCornersTextureView_radius, + context.resources.getDimension(R.dimen.voip_round_corners_texture_view_radius) + ) } finally { recycle() } diff --git a/app/src/main/java/org/linphone/activities/voip/views/ScrollDotsView.kt b/app/src/main/java/org/linphone/activities/voip/views/ScrollDotsView.kt index 3ab2f61f3..e0498b948 100644 --- a/app/src/main/java/org/linphone/activities/voip/views/ScrollDotsView.kt +++ b/app/src/main/java/org/linphone/activities/voip/views/ScrollDotsView.kt @@ -114,16 +114,23 @@ class ScrollDotsView : View { context.theme.obtainStyledAttributes( attrs, R.styleable.ScrollDot, - defStyleAttr, 0 + defStyleAttr, + 0 ).apply { try { radius = getDimension(R.styleable.ScrollDot_dotRadius, 5f) count = getInt(R.styleable.ScrollDot_dotCount, 1) - val color = getColor(R.styleable.ScrollDot_dotColor, context.resources.getColor(R.color.voip_gray_dots)) + val color = getColor( + R.styleable.ScrollDot_dotColor, + context.resources.getColor(R.color.voip_gray_dots) + ) dotPaint.color = color - val selectedColor = getColor(R.styleable.ScrollDot_selectedDotColor, context.resources.getColor(R.color.voip_dark_gray)) + val selectedColor = getColor( + R.styleable.ScrollDot_selectedDotColor, + context.resources.getColor(R.color.voip_dark_gray) + ) selectedDotPaint.color = selectedColor selected = getInt(R.styleable.ScrollDot_selectedDot, 1) @@ -153,11 +160,15 @@ class ScrollDotsView : View { screenWidth = screenRect.width().toFloat() screenHeight = screenRect.height().toFloat() - val marginBetweenItems = context.resources.getDimension(R.dimen.voip_active_speaker_miniature_margin) + val marginBetweenItems = context.resources.getDimension( + R.dimen.voip_active_speaker_miniature_margin + ) itemWidth = context.resources.getDimension(R.dimen.voip_active_speaker_miniature_size) + marginBetweenItems itemHeight = context.resources.getDimension(R.dimen.voip_active_speaker_miniature_size) + marginBetweenItems - Log.d("[Scroll Dots] Screen size is $screenWidth/$screenHeight and item size is $itemWidth/$itemHeight") + Log.d( + "[Scroll Dots] Screen size is $screenWidth/$screenHeight and item size is $itemWidth/$itemHeight" + ) } override fun onDraw(canvas: Canvas) { @@ -229,12 +240,16 @@ class ScrollDotsView : View { if (isHorizontal) { val itemsPerScreen = (screenWidth / itemWidth) val dots = ceil(items.toDouble() / itemsPerScreen).toInt() - Log.d("[Scroll Dots] Calculated $count for $items items ($itemsPerScreen items fit in screen width), given that screen width is $screenWidth and item width is $itemWidth") + Log.d( + "[Scroll Dots] Calculated $count for $items items ($itemsPerScreen items fit in screen width), given that screen width is $screenWidth and item width is $itemWidth" + ) setDotCount(dots) } else { val itemsPerScreen = (screenHeight / itemHeight) val dots = ceil(items.toDouble() / itemsPerScreen).toInt() - Log.d("[Scroll Dots] Calculated $count for $items items ($itemsPerScreen items fit in screen height), given that screen height is $screenHeight and item height is $itemHeight") + Log.d( + "[Scroll Dots] Calculated $count for $items items ($itemsPerScreen items fit in screen height), given that screen height is $screenHeight and item height is $itemHeight" + ) setDotCount(dots) } } diff --git a/app/src/main/java/org/linphone/compatibility/Api23Compatibility.kt b/app/src/main/java/org/linphone/compatibility/Api23Compatibility.kt index ea529b1a7..25e399413 100644 --- a/app/src/main/java/org/linphone/compatibility/Api23Compatibility.kt +++ b/app/src/main/java/org/linphone/compatibility/Api23Compatibility.kt @@ -168,9 +168,13 @@ class Api23Compatibility { val isContentEncrypted = content.isFileEncrypted val filePath = if (content.isFileEncrypted) { val plainFilePath = content.exportPlainFile().orEmpty() - Log.i("[Media Store] [VFS] Content is encrypted, plain file path is: $plainFilePath") + Log.i( + "[Media Store] [VFS] Content is encrypted, plain file path is: $plainFilePath" + ) plainFilePath - } else content.filePath + } else { + content.filePath + } if (filePath.isNullOrEmpty()) { Log.e("[Media Store] Content doesn't have a file path!") @@ -193,7 +197,9 @@ class Api23Compatibility { isAudio -> "audio" else -> "unexpected" } - Log.i("[Media Store] Adding $type [$filePath] to Media Store with name [$fileName] and MIME [$mime], asking to be stored in: $relativePath") + Log.i( + "[Media Store] Adding $type [$filePath] to Media Store with name [$fileName] and MIME [$mime], asking to be stored in: $relativePath" + ) val mediaStoreFilePath = when { isImage -> { diff --git a/app/src/main/java/org/linphone/compatibility/Api25Compatibility.kt b/app/src/main/java/org/linphone/compatibility/Api25Compatibility.kt index 48b947b90..39111541f 100644 --- a/app/src/main/java/org/linphone/compatibility/Api25Compatibility.kt +++ b/app/src/main/java/org/linphone/compatibility/Api25Compatibility.kt @@ -33,7 +33,8 @@ class Api25Compatibility { @SuppressLint("MissingPermission") fun getDeviceName(context: Context): String { var name = Settings.Global.getString( - context.contentResolver, Settings.Global.DEVICE_NAME + context.contentResolver, + Settings.Global.DEVICE_NAME ) if (name == null) { val adapter = BluetoothAdapter.getDefaultAdapter() diff --git a/app/src/main/java/org/linphone/compatibility/Api26Compatibility.kt b/app/src/main/java/org/linphone/compatibility/Api26Compatibility.kt index 8953f9006..95dcb07af 100644 --- a/app/src/main/java/org/linphone/compatibility/Api26Compatibility.kt +++ b/app/src/main/java/org/linphone/compatibility/Api26Compatibility.kt @@ -70,7 +70,9 @@ class Api26Compatibility { if (!activity.enterPictureInPictureMode(params)) { Log.e("[Call] Failed to enter PiP mode") } else { - Log.i("[Call] Entering PiP mode with ${if (conference) "portrait" else "landscape"} aspect ratio") + Log.i( + "[Call] Entering PiP mode with ${if (conference) "portrait" else "landscape"} aspect ratio" + ) } } catch (e: Exception) { Log.e("[Call] Can't build PiP params: $e") @@ -167,10 +169,25 @@ class Api26Compatibility { val info: String val remoteContact = call.remoteContact - val conferenceAddress = if (remoteContact != null) coreContext.core.interpretUrl(remoteContact, false) else null - val conferenceInfo = if (conferenceAddress != null) coreContext.core.findConferenceInformationFromUri(conferenceAddress) else null + val conferenceAddress = if (remoteContact != null) { + coreContext.core.interpretUrl( + remoteContact, + false + ) + } else { + null + } + val conferenceInfo = if (conferenceAddress != null) { + coreContext.core.findConferenceInformationFromUri( + conferenceAddress + ) + } else { + null + } if (conferenceInfo == null) { - Log.i("[Notifications Manager] No conference info found for remote contact address $remoteContact") + Log.i( + "[Notifications Manager] No conference info found for remote contact address $remoteContact" + ) contact = coreContext.contactsManager.findContactByAddress(call.remoteAddress) roundPicture = ImageUtils.getRoundBitmapFromUri(context, contact?.getThumbnailUri()) @@ -183,10 +200,15 @@ class Api26Compatibility { address = LinphoneUtils.getDisplayableAddress(conferenceInfo.organizer) roundPicture = coreContext.contactsManager.groupBitmap info = context.getString(R.string.incoming_group_call_notification_title) - Log.i("[Notifications Manager] Displaying incoming group call notification with subject $displayName for remote contact address $remoteContact") + Log.i( + "[Notifications Manager] Displaying incoming group call notification with subject $displayName for remote contact address $remoteContact" + ) } - val notificationLayoutHeadsUp = RemoteViews(context.packageName, R.layout.call_incoming_notification_heads_up) + val notificationLayoutHeadsUp = RemoteViews( + context.packageName, + R.layout.call_incoming_notification_heads_up + ) notificationLayoutHeadsUp.setTextViewText(R.id.caller, displayName) notificationLayoutHeadsUp.setTextViewText(R.id.sip_uri, address) notificationLayoutHeadsUp.setTextViewText(R.id.incoming_call_info, info) @@ -195,7 +217,10 @@ class Api26Compatibility { notificationLayoutHeadsUp.setImageViewBitmap(R.id.caller_picture, roundPicture) } - val builder = NotificationCompat.Builder(context, context.getString(R.string.notification_channel_incoming_call_id)) + val builder = NotificationCompat.Builder( + context, + context.getString(R.string.notification_channel_incoming_call_id) + ) .setStyle(NotificationCompat.DecoratedCustomViewStyle()) .addPerson(notificationsManager.getPerson(contact, displayName, roundPicture)) .setSmallIcon(R.drawable.topbar_call_notification) @@ -236,11 +261,21 @@ class Api26Compatibility { val person: Person val conferenceAddress = LinphoneUtils.getConferenceAddress(call) - val conferenceInfo = if (conferenceAddress != null) coreContext.core.findConferenceInformationFromUri(conferenceAddress) else null - if (conferenceInfo != null) { - Log.i("[Notifications Manager] Displaying group call notification with subject ${conferenceInfo.subject}") + val conferenceInfo = if (conferenceAddress != null) { + coreContext.core.findConferenceInformationFromUri( + conferenceAddress + ) } else { - Log.i("[Notifications Manager] No conference info found for remote contact address ${call.remoteAddress} (${call.remoteContact})") + null + } + if (conferenceInfo != null) { + Log.i( + "[Notifications Manager] Displaying group call notification with subject ${conferenceInfo.subject}" + ) + } else { + Log.i( + "[Notifications Manager] No conference info found for remote contact address ${call.remoteAddress} (${call.remoteContact})" + ) } if (conferenceInfo == null) { @@ -283,7 +318,8 @@ class Api26Compatibility { } val builder = NotificationCompat.Builder( - context, channel + context, + channel ) .setContentTitle(title) .setContentText(context.getString(stringResourceId)) @@ -309,7 +345,11 @@ class Api26Compatibility { @SuppressLint("MissingPermission") fun eventVibration(vibrator: Vibrator) { - val effect = VibrationEffect.createWaveform(longArrayOf(0L, 100L, 100L), intArrayOf(0, VibrationEffect.DEFAULT_AMPLITUDE, 0), -1) + val effect = VibrationEffect.createWaveform( + longArrayOf(0L, 100L, 100L), + intArrayOf(0, VibrationEffect.DEFAULT_AMPLITUDE, 0), + -1 + ) val audioAttrs = AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT) .build() @@ -317,7 +357,9 @@ class Api26Compatibility { } fun changeAudioRouteForTelecomManager(connection: NativeCallWrapper, route: Int): Boolean { - Log.i("[Telecom Helper] Changing audio route [${routeToString(route)}] on connection [${connection.callId}] with state [${connection.stateAsString()}]") + Log.i( + "[Telecom Helper] Changing audio route [${routeToString(route)}] on connection [${connection.callId}] with state [${connection.stateAsString()}]" + ) val audioState = connection.callAudioState if (audioState != null) { @@ -354,7 +396,9 @@ class Api26Compatibility { } fun hasTelecomManagerFeature(context: Context): Boolean { - return context.packageManager.hasSystemFeature(PackageManager.FEATURE_CONNECTION_SERVICE) + return context.packageManager.hasSystemFeature( + PackageManager.FEATURE_CONNECTION_SERVICE + ) } private fun routeToString(route: Int): String { diff --git a/app/src/main/java/org/linphone/compatibility/Api29Compatibility.kt b/app/src/main/java/org/linphone/compatibility/Api29Compatibility.kt index c8b64ede9..ee6ad686c 100644 --- a/app/src/main/java/org/linphone/compatibility/Api29Compatibility.kt +++ b/app/src/main/java/org/linphone/compatibility/Api29Compatibility.kt @@ -95,12 +95,16 @@ class Api29Compatibility { val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val bubblesAllowed = notificationManager.areBubblesAllowed() - Log.i("[Notifications Manager] Bubbles notifications are ${if (bubblesAllowed) "allowed" else "forbidden"}") + Log.i( + "[Notifications Manager] Bubbles notifications are ${if (bubblesAllowed) "allowed" else "forbidden"}" + ) return bubblesAllowed } fun getBitmapFromUri(context: Context, uri: Uri): Bitmap { - return ImageDecoder.decodeBitmap(ImageDecoder.createSource(context.contentResolver, uri)) + return ImageDecoder.decodeBitmap( + ImageDecoder.createSource(context.contentResolver, uri) + ) } suspend fun addImageToMediaStore(context: Context, content: Content): Boolean { @@ -125,9 +129,13 @@ class Api29Compatibility { val isContentEncrypted = content.isFileEncrypted val filePath = if (content.isFileEncrypted) { val plainFilePath = content.exportPlainFile().orEmpty() - Log.i("[Media Store] [VFS] Content is encrypted, plain file path is: $plainFilePath") + Log.i( + "[Media Store] [VFS] Content is encrypted, plain file path is: $plainFilePath" + ) plainFilePath - } else content.filePath + } else { + content.filePath + } if (filePath.isNullOrEmpty()) { Log.e("[Media Store] Content doesn't have a file path!") @@ -150,7 +158,9 @@ class Api29Compatibility { isAudio -> "audio" else -> "unexpected" } - Log.i("[Media Store] Adding $type [$filePath] to Media Store with name [$fileName] and MIME [$mime], asking to be stored in: $relativePath") + Log.i( + "[Media Store] Adding $type [$filePath] to Media Store with name [$fileName] and MIME [$mime], asking to be stored in: $relativePath" + ) val mediaStoreFilePath = when { isImage -> { @@ -160,8 +170,16 @@ class Api29Compatibility { put(MediaStore.Images.Media.RELATIVE_PATH, relativePath) put(MediaStore.Images.Media.IS_PENDING, 1) } - val collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) - addContentValuesToCollection(context, filePath, collection, values, MediaStore.Images.Media.IS_PENDING) + val collection = MediaStore.Images.Media.getContentUri( + MediaStore.VOLUME_EXTERNAL_PRIMARY + ) + addContentValuesToCollection( + context, + filePath, + collection, + values, + MediaStore.Images.Media.IS_PENDING + ) } isVideo -> { val values = ContentValues().apply { @@ -171,8 +189,16 @@ class Api29Compatibility { put(MediaStore.Video.Media.RELATIVE_PATH, relativePath) put(MediaStore.Video.Media.IS_PENDING, 1) } - val collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) - addContentValuesToCollection(context, filePath, collection, values, MediaStore.Video.Media.IS_PENDING) + val collection = MediaStore.Video.Media.getContentUri( + MediaStore.VOLUME_EXTERNAL_PRIMARY + ) + addContentValuesToCollection( + context, + filePath, + collection, + values, + MediaStore.Video.Media.IS_PENDING + ) } isAudio -> { val values = ContentValues().apply { @@ -182,8 +208,16 @@ class Api29Compatibility { put(MediaStore.Audio.Media.RELATIVE_PATH, relativePath) put(MediaStore.Audio.Media.IS_PENDING, 1) } - val collection = MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) - addContentValuesToCollection(context, filePath, collection, values, MediaStore.Audio.Media.IS_PENDING) + val collection = MediaStore.Audio.Media.getContentUri( + MediaStore.VOLUME_EXTERNAL_PRIMARY + ) + addContentValuesToCollection( + context, + filePath, + collection, + values, + MediaStore.Audio.Media.IS_PENDING + ) } else -> "" } diff --git a/app/src/main/java/org/linphone/compatibility/Api30Compatibility.kt b/app/src/main/java/org/linphone/compatibility/Api30Compatibility.kt index 67dae9d11..7d41cb093 100644 --- a/app/src/main/java/org/linphone/compatibility/Api30Compatibility.kt +++ b/app/src/main/java/org/linphone/compatibility/Api30Compatibility.kt @@ -37,7 +37,10 @@ import org.linphone.utils.LinphoneUtils class Api30Compatibility { companion object { fun hasReadPhoneNumbersPermission(context: Context): Boolean { - val granted = Compatibility.hasPermission(context, Manifest.permission.READ_PHONE_NUMBERS) + val granted = Compatibility.hasPermission( + context, + Manifest.permission.READ_PHONE_NUMBERS + ) if (granted) { Log.d("[Permission Helper] Permission READ_PHONE_NUMBERS is granted") } else { diff --git a/app/src/main/java/org/linphone/compatibility/Api31Compatibility.kt b/app/src/main/java/org/linphone/compatibility/Api31Compatibility.kt index ca4923f4d..f225df602 100644 --- a/app/src/main/java/org/linphone/compatibility/Api31Compatibility.kt +++ b/app/src/main/java/org/linphone/compatibility/Api31Compatibility.kt @@ -52,12 +52,29 @@ class Api31Compatibility { notificationsManager: NotificationsManager ): Notification { val remoteContact = call.remoteContact - val conferenceAddress = if (remoteContact != null) coreContext.core.interpretUrl(remoteContact, false) else null - val conferenceInfo = if (conferenceAddress != null) coreContext.core.findConferenceInformationFromUri(conferenceAddress) else null - if (conferenceInfo != null) { - Log.i("[Notifications Manager] Displaying incoming group call notification with subject ${conferenceInfo.subject} and remote contact address $remoteContact") + val conferenceAddress = if (remoteContact != null) { + coreContext.core.interpretUrl( + remoteContact, + false + ) } else { - Log.i("[Notifications Manager] No conference info found for remote contact address $remoteContact") + null + } + val conferenceInfo = if (conferenceAddress != null) { + coreContext.core.findConferenceInformationFromUri( + conferenceAddress + ) + } else { + null + } + if (conferenceInfo != null) { + Log.i( + "[Notifications Manager] Displaying incoming group call notification with subject ${conferenceInfo.subject} and remote contact address $remoteContact" + ) + } else { + Log.i( + "[Notifications Manager] No conference info found for remote contact address $remoteContact" + ) } val caller = if (conferenceInfo == null) { @@ -77,7 +94,15 @@ class Api31Compatibility { .build() } else { Person.Builder() - .setName(if (conferenceInfo.subject.isNullOrEmpty()) context.getString(R.string.conference_incoming_title) else conferenceInfo.subject) + .setName( + if (conferenceInfo.subject.isNullOrEmpty()) { + context.getString( + R.string.conference_incoming_title + ) + } else { + conferenceInfo.subject + } + ) .setIcon(coreContext.contactsManager.groupAvatar.toIcon(context)) .setImportant(false) .build() @@ -90,7 +115,10 @@ class Api31Compatibility { val isVideoAutomaticallyAccepted = call.core.videoActivationPolicy.automaticallyAccept val isVideo = isVideoEnabledInRemoteParams && isVideoAutomaticallyAccepted - val builder = Notification.Builder(context, context.getString(R.string.notification_channel_incoming_call_id)).apply { + val builder = Notification.Builder( + context, + context.getString(R.string.notification_channel_incoming_call_id) + ).apply { try { style = Notification.CallStyle.forIncomingCall( caller, @@ -98,8 +126,16 @@ class Api31Compatibility { answerIntent ).setIsVideo(isVideo) } catch (iae: IllegalArgumentException) { - Log.e("[Api31 Compatibility] Can't use notification call style: $iae, using API 26 notification instead") - return Api26Compatibility.createIncomingCallNotification(context, call, notifiable, pendingIntent, notificationsManager) + Log.e( + "[Api31 Compatibility] Can't use notification call style: $iae, using API 26 notification instead" + ) + return Api26Compatibility.createIncomingCallNotification( + context, + call, + notifiable, + pendingIntent, + notificationsManager + ) } setSmallIcon(R.drawable.topbar_call_notification) setCategory(Notification.CATEGORY_CALL) @@ -128,11 +164,21 @@ class Api31Compatibility { notificationsManager: NotificationsManager ): Notification { val conferenceAddress = LinphoneUtils.getConferenceAddress(call) - val conferenceInfo = if (conferenceAddress != null) coreContext.core.findConferenceInformationFromUri(conferenceAddress) else null - if (conferenceInfo != null) { - Log.i("[Notifications Manager] Displaying group call notification with subject ${conferenceInfo.subject}") + val conferenceInfo = if (conferenceAddress != null) { + coreContext.core.findConferenceInformationFromUri( + conferenceAddress + ) } else { - Log.i("[Notifications Manager] No conference info found for remote contact address ${call.remoteAddress} (${call.remoteContact})") + null + } + if (conferenceInfo != null) { + Log.i( + "[Notifications Manager] Displaying group call notification with subject ${conferenceInfo.subject}" + ) + } else { + Log.i( + "[Notifications Manager] No conference info found for remote contact address ${call.remoteAddress} (${call.remoteContact})" + ) } val caller = if (conferenceInfo == null) { @@ -173,14 +219,24 @@ class Api31Compatibility { val declineIntent = notificationsManager.getCallDeclinePendingIntent(notifiable) val builder = Notification.Builder( - context, channel + context, + channel ).apply { try { style = Notification.CallStyle.forOngoingCall(caller, declineIntent) .setIsVideo(isVideo) } catch (iae: IllegalArgumentException) { - Log.e("[Api31 Compatibility] Can't use notification call style: $iae, using API 26 notification instead") - return Api26Compatibility.createCallNotification(context, call, notifiable, pendingIntent, channel, notificationsManager) + Log.e( + "[Api31 Compatibility] Can't use notification call style: $iae, using API 26 notification instead" + ) + return Api26Compatibility.createCallNotification( + context, + call, + notifiable, + pendingIntent, + channel, + notificationsManager + ) } setSmallIcon(iconResourceId) setAutoCancel(false) @@ -230,7 +286,9 @@ class Api31Compatibility { .build() try { activity.setPictureInPictureParams(params) - Log.i("[Call] PiP auto enter enabled params set to $enable with ${if (conference) "portrait" else "landscape"} aspect ratio") + Log.i( + "[Call] PiP auto enter enabled params set to $enable with ${if (conference) "portrait" else "landscape"} aspect ratio" + ) } catch (e: Exception) { Log.e("[Call] Can't build PiP params: $e") } diff --git a/app/src/main/java/org/linphone/compatibility/Compatibility.kt b/app/src/main/java/org/linphone/compatibility/Compatibility.kt index f7e429c97..846f0af4a 100644 --- a/app/src/main/java/org/linphone/compatibility/Compatibility.kt +++ b/app/src/main/java/org/linphone/compatibility/Compatibility.kt @@ -108,7 +108,9 @@ class Compatibility { fun hasPostNotificationsPermission(context: Context): Boolean { return if (Version.sdkAboveOrEqual(Version.API33_ANDROID_13_TIRAMISU)) { Api33Compatibility.hasPostNotificationsPermission(context) - } else true + } else { + true + } } fun requestReadExternalStorageAndCameraPermissions(fragment: Fragment, code: Int) { @@ -222,11 +224,29 @@ class Compatibility { // Samsung One UI 4.0 (API 31) doesn't (currently) display CallStyle notifications well // Tested on Samsung S10 and Z Fold 2 if (Version.sdkAboveOrEqual(Version.API31_ANDROID_12) && manufacturer != "samsung") { - return Api31Compatibility.createIncomingCallNotification(context, call, notifiable, pendingIntent, notificationsManager) + return Api31Compatibility.createIncomingCallNotification( + context, + call, + notifiable, + pendingIntent, + notificationsManager + ) } else if (manufacturer == "xiaomi") { // Xiaomi devices don't handle CustomHeadsUpContentView correctly - return XiaomiCompatibility.createIncomingCallNotification(context, call, notifiable, pendingIntent, notificationsManager) + return XiaomiCompatibility.createIncomingCallNotification( + context, + call, + notifiable, + pendingIntent, + notificationsManager + ) } - return Api26Compatibility.createIncomingCallNotification(context, call, notifiable, pendingIntent, notificationsManager) + return Api26Compatibility.createIncomingCallNotification( + context, + call, + notifiable, + pendingIntent, + notificationsManager + ) } fun createCallNotification( @@ -241,9 +261,23 @@ class Compatibility { // Samsung One UI 4.0 (API 31) doesn't (currently) display CallStyle notifications well // Tested on Samsung S10 and Z Fold 2 if (Version.sdkAboveOrEqual(Version.API31_ANDROID_12) && manufacturer != "samsung") { - return Api31Compatibility.createCallNotification(context, call, notifiable, pendingIntent, channel, notificationsManager) + return Api31Compatibility.createCallNotification( + context, + call, + notifiable, + pendingIntent, + channel, + notificationsManager + ) } - return Api26Compatibility.createCallNotification(context, call, notifiable, pendingIntent, channel, notificationsManager) + return Api26Compatibility.createCallNotification( + context, + call, + notifiable, + pendingIntent, + channel, + notificationsManager + ) } fun startForegroundService(context: Context, intent: Intent) { @@ -278,7 +312,10 @@ class Compatibility { } fun enterPipMode(activity: Activity, conference: Boolean) { - if (Version.sdkStrictlyBelow(Version.API31_ANDROID_12) && Version.sdkAboveOrEqual(Version.API26_O_80)) { + if (Version.sdkStrictlyBelow(Version.API31_ANDROID_12) && Version.sdkAboveOrEqual( + Version.API26_O_80 + ) + ) { Api26Compatibility.enterPipMode(activity, conference) } } diff --git a/app/src/main/java/org/linphone/compatibility/XiaomiCompatibility.kt b/app/src/main/java/org/linphone/compatibility/XiaomiCompatibility.kt index 2a37701ec..a914c537d 100644 --- a/app/src/main/java/org/linphone/compatibility/XiaomiCompatibility.kt +++ b/app/src/main/java/org/linphone/compatibility/XiaomiCompatibility.kt @@ -55,10 +55,25 @@ class XiaomiCompatibility { val info: String val remoteContact = call.remoteContact - val conferenceAddress = if (remoteContact != null) coreContext.core.interpretUrl(remoteContact, false) else null - val conferenceInfo = if (conferenceAddress != null) coreContext.core.findConferenceInformationFromUri(conferenceAddress) else null + val conferenceAddress = if (remoteContact != null) { + coreContext.core.interpretUrl( + remoteContact, + false + ) + } else { + null + } + val conferenceInfo = if (conferenceAddress != null) { + coreContext.core.findConferenceInformationFromUri( + conferenceAddress + ) + } else { + null + } if (conferenceInfo == null) { - Log.i("[Notifications Manager] No conference info found for remote contact address $remoteContact") + Log.i( + "[Notifications Manager] No conference info found for remote contact address $remoteContact" + ) contact = coreContext.contactsManager.findContactByAddress(call.remoteAddress) roundPicture = ImageUtils.getRoundBitmapFromUri(context, contact?.getThumbnailUri()) @@ -71,13 +86,23 @@ class XiaomiCompatibility { address = LinphoneUtils.getDisplayableAddress(conferenceInfo.organizer) roundPicture = coreContext.contactsManager.groupBitmap info = context.getString(R.string.incoming_group_call_notification_title) - Log.i("[Notifications Manager] Displaying incoming group call notification with subject $displayName and remote contact address $remoteContact") + Log.i( + "[Notifications Manager] Displaying incoming group call notification with subject $displayName and remote contact address $remoteContact" + ) } - val builder = NotificationCompat.Builder(context, context.getString(R.string.notification_channel_incoming_call_id)) + val builder = NotificationCompat.Builder( + context, + context.getString(R.string.notification_channel_incoming_call_id) + ) .addPerson(notificationsManager.getPerson(contact, displayName, roundPicture)) .setSmallIcon(R.drawable.topbar_call_notification) - .setLargeIcon(roundPicture ?: BitmapFactory.decodeResource(context.resources, R.drawable.voip_single_contact_avatar_alt)) + .setLargeIcon( + roundPicture ?: BitmapFactory.decodeResource( + context.resources, + R.drawable.voip_single_contact_avatar_alt + ) + ) .setContentTitle(displayName) .setContentText(address) .setSubText(info) diff --git a/app/src/main/java/org/linphone/contact/ContactLoader.kt b/app/src/main/java/org/linphone/contact/ContactLoader.kt index 6b8b662a6..9888c64ae 100644 --- a/app/src/main/java/org/linphone/contact/ContactLoader.kt +++ b/app/src/main/java/org/linphone/contact/ContactLoader.kt @@ -60,7 +60,9 @@ class ContactLoader : LoaderManager.LoaderCallbacks { override fun onCreateLoader(id: Int, args: Bundle?): Loader { val lastFetch = coreContext.contactsManager.latestContactFetch - Log.i("[Contacts Loader] Loader created, ${if (lastFetch.isEmpty()) "first fetch" else "last fetch happened at [$lastFetch]"}") + Log.i( + "[Contacts Loader] Loader created, ${if (lastFetch.isEmpty()) "first fetch" else "last fetch happened at [$lastFetch]"}" + ) coreContext.contactsManager.fetchInProgress.value = true val mimeType = ContactsContract.Data.MIMETYPE @@ -118,9 +120,13 @@ class ContactLoader : LoaderManager.LoaderCallbacks { while (cursor != null && !cursor.isClosed && cursor.moveToNext()) { try { val id: String = - cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Data.CONTACT_ID)) + cursor.getString( + cursor.getColumnIndexOrThrow(ContactsContract.Data.CONTACT_ID) + ) val mime: String? = - cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Data.MIMETYPE)) + cursor.getString( + cursor.getColumnIndexOrThrow(ContactsContract.Data.MIMETYPE) + ) if (previousId.isEmpty() || previousId != id) { friendsPhoneNumbers.clear() @@ -132,7 +138,11 @@ class ContactLoader : LoaderManager.LoaderCallbacks { friend.refKey = id if (friend.name.isNullOrEmpty()) { val displayName: String? = - cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Data.DISPLAY_NAME_PRIMARY)) + cursor.getString( + cursor.getColumnIndexOrThrow( + ContactsContract.Data.DISPLAY_NAME_PRIMARY + ) + ) friend.name = displayName friend.photo = Uri.withAppendedPath( @@ -144,10 +154,18 @@ class ContactLoader : LoaderManager.LoaderCallbacks { ).toString() val starred = - cursor.getInt(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.STARRED)) == 1 + cursor.getInt( + cursor.getColumnIndexOrThrow( + ContactsContract.Contacts.STARRED + ) + ) == 1 friend.starred = starred val lookupKey = - cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.LOOKUP_KEY)) + cursor.getString( + cursor.getColumnIndexOrThrow( + ContactsContract.Contacts.LOOKUP_KEY + ) + ) friend.nativeUri = "${ContactsContract.Contacts.CONTENT_LOOKUP_URI}/$lookupKey" @@ -159,13 +177,29 @@ class ContactLoader : LoaderManager.LoaderCallbacks { when (mime) { ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE -> { val data1: String? = - cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)) + cursor.getString( + cursor.getColumnIndexOrThrow( + ContactsContract.CommonDataKinds.Phone.NUMBER + ) + ) val data2: String? = - cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.TYPE)) + cursor.getString( + cursor.getColumnIndexOrThrow( + ContactsContract.CommonDataKinds.Phone.TYPE + ) + ) val data3: String? = - cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.LABEL)) + cursor.getString( + cursor.getColumnIndexOrThrow( + ContactsContract.CommonDataKinds.Phone.LABEL + ) + ) val data4: String? = - cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER)) + cursor.getString( + cursor.getColumnIndexOrThrow( + ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER + ) + ) val label = PhoneNumberUtils.addressBookLabelTypeToVcardParamString( @@ -202,7 +236,11 @@ class ContactLoader : LoaderManager.LoaderCallbacks { } linphoneMime, ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE -> { val sipAddress: String? = - cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS)) + cursor.getString( + cursor.getColumnIndexOrThrow( + ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS + ) + ) if (sipAddress != null) { val address = core.interpretUrl(sipAddress, true) if (address != null && @@ -217,7 +255,11 @@ class ContactLoader : LoaderManager.LoaderCallbacks { } ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE -> { val organization: String? = - cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Organization.COMPANY)) + cursor.getString( + cursor.getColumnIndexOrThrow( + ContactsContract.CommonDataKinds.Organization.COMPANY + ) + ) if (organization != null) { friend.organization = organization } @@ -241,15 +283,21 @@ class ContactLoader : LoaderManager.LoaderCallbacks { withContext(Dispatchers.Main) { if (core.globalState == GlobalState.Shutdown || core.globalState == GlobalState.Off) { - Log.w("[Contacts Loader] Core is being stopped or already destroyed, abort") + Log.w( + "[Contacts Loader] Core is being stopped or already destroyed, abort" + ) } else { Log.i("[Contacts Loader] ${friends.size} friends created") val contactId = coreContext.contactsManager.contactIdToWatchFor if (contactId.isNotEmpty()) { val friend = friends[contactId] - Log.i("[Contacts Loader] Manager was asked to monitor contact id $contactId") + Log.i( + "[Contacts Loader] Manager was asked to monitor contact id $contactId" + ) if (friend != null) { - Log.i("[Contacts Loader] Found new contact matching id $contactId, notifying listeners") + Log.i( + "[Contacts Loader] Found new contact matching id $contactId, notifying listeners" + ) coreContext.contactsManager.notifyListeners(friend) } } diff --git a/app/src/main/java/org/linphone/contact/ContactSelectionData.kt b/app/src/main/java/org/linphone/contact/ContactSelectionData.kt index 61e78a7ac..ccd0b072d 100644 --- a/app/src/main/java/org/linphone/contact/ContactSelectionData.kt +++ b/app/src/main/java/org/linphone/contact/ContactSelectionData.kt @@ -41,7 +41,9 @@ class ContactSelectionData(private val searchResult: SearchResult) : ContactData } val isLinphoneUser: Boolean by lazy { - searchResult.friend?.getPresenceModelForUriOrTel(searchResult.phoneNumber ?: searchResult.address?.asStringUriOnly() ?: "")?.basicStatus == PresenceBasicStatus.Open + searchResult.friend?.getPresenceModelForUriOrTel( + searchResult.phoneNumber ?: searchResult.address?.asStringUriOnly() ?: "" + )?.basicStatus == PresenceBasicStatus.Open } val sipUri: String by lazy { @@ -84,7 +86,9 @@ class ContactSelectionData(private val searchResult: SearchResult) : ContactData } displayName.value = LinphoneUtils.getDisplayName(address) } else if (searchResult.phoneNumber != null) { - val found = coreContext.contactsManager.findContactByPhoneNumber(searchResult.phoneNumber.orEmpty()) + val found = coreContext.contactsManager.findContactByPhoneNumber( + searchResult.phoneNumber.orEmpty() + ) if (found != null) { contact.value = found!! presenceStatus.value = found.consolidatedPresence diff --git a/app/src/main/java/org/linphone/contact/ContactsManager.kt b/app/src/main/java/org/linphone/contact/ContactsManager.kt index 723ddc93c..401f2c560 100644 --- a/app/src/main/java/org/linphone/contact/ContactsManager.kt +++ b/app/src/main/java/org/linphone/contact/ContactsManager.kt @@ -95,9 +95,18 @@ class ContactsManager(private val context: Context) { init { initSyncAccount() - contactAvatar = IconCompat.createWithResource(context, R.drawable.voip_single_contact_avatar_alt) - groupAvatar = IconCompat.createWithResource(context, R.drawable.voip_multiple_contacts_avatar_alt) - groupBitmap = BitmapFactory.decodeResource(context.resources, R.drawable.voip_multiple_contacts_avatar_alt) + contactAvatar = IconCompat.createWithResource( + context, + R.drawable.voip_single_contact_avatar_alt + ) + groupAvatar = IconCompat.createWithResource( + context, + R.drawable.voip_multiple_contacts_avatar_alt + ) + groupBitmap = BitmapFactory.decodeResource( + context.resources, + R.drawable.voip_multiple_contacts_avatar_alt + ) val core = coreContext.core for (list in core.friendsLists) { @@ -137,7 +146,9 @@ class ContactsManager(private val context: Context) { friend.photo = parsedUri } - Log.i("[Contacts Manager] Local contact created for account [${address.asString()}] and picture [${friend.photo}]") + Log.i( + "[Contacts Manager] Local contact created for account [${address.asString()}] and picture [${friend.photo}]" + ) localFriends.add(friend) } } @@ -229,7 +240,9 @@ class ContactsManager(private val context: Context) { private fun initSyncAccount() { val accountManager = context.getSystemService(Context.ACCOUNT_SERVICE) as AccountManager - val accounts = accountManager.getAccountsByType(context.getString(R.string.sync_account_type)) + val accounts = accountManager.getAccountsByType( + context.getString(R.string.sync_account_type) + ) if (accounts.isEmpty()) { val newAccount = Account( context.getString(R.string.sync_account_name), @@ -245,7 +258,9 @@ class ContactsManager(private val context: Context) { } } else { for (account in accounts) { - Log.i("[Contacts Manager] Found account with name [${account.name}] and type [${account.type}]") + Log.i( + "[Contacts Manager] Found account with name [${account.name}] and type [${account.type}]" + ) } } } @@ -259,14 +274,25 @@ class ContactsManager(private val context: Context) { for (syncAdapter in syncAdapters) { if (syncAdapter.authority == "com.android.contacts" && syncAdapter.isUserVisible) { - if (syncAdapter.supportsUploading() || syncAdapter.accountType == context.getString(R.string.sync_account_type)) { - Log.i("[Contacts Manager] Found sync adapter for com.android.contacts authority: ${syncAdapter.accountType}") + if (syncAdapter.supportsUploading() || syncAdapter.accountType == context.getString( + R.string.sync_account_type + ) + ) { + Log.i( + "[Contacts Manager] Found sync adapter for com.android.contacts authority: ${syncAdapter.accountType}" + ) val accounts = accountManager.getAccountsByType(syncAdapter.accountType) for (account in accounts) { - Log.i("[Contacts Manager] Found account for account type ${syncAdapter.accountType}: ${account.name}") + Log.i( + "[Contacts Manager] Found account for account type ${syncAdapter.accountType}: ${account.name}" + ) for (authenticator in authenticators) { if (authenticator.type == account.type) { - val drawable = packageManager.getDrawable(authenticator.packageName, authenticator.smallIconId, null) + val drawable = packageManager.getDrawable( + authenticator.packageName, + authenticator.smallIconId, + null + ) val triple = Triple(account.name, account.type, drawable) available.add(triple) } @@ -281,7 +307,9 @@ class ContactsManager(private val context: Context) { @Synchronized private fun refreshContactOnPresenceReceived(friend: Friend) { - Log.d("[Contacts Manager] Received presence information for contact [${friend.name}]: [${friend.consolidatedPresence}]") + Log.d( + "[Contacts Manager] Received presence information for contact [${friend.name}]: [${friend.consolidatedPresence}]" + ) if (corePreferences.storePresenceInNativeContact && PermissionHelper.get().hasWriteContactsPermission()) { if (friend.refKey != null) { Log.i("[Contacts Manager] Storing presence in native contact ${friend.refKey}") @@ -296,7 +324,9 @@ class ContactsManager(private val context: Context) { for (phoneNumber in friend.phoneNumbers) { val sipAddress = friend.getContactForPhoneNumberOrAddress(phoneNumber) if (sipAddress != null) { - Log.d("[Contacts Manager] Found presence information to store in native contact $friend under Linphone sync account") + Log.d( + "[Contacts Manager] Found presence information to store in native contact $friend under Linphone sync account" + ) contactEditor.setPresenceInformation( phoneNumber, sipAddress @@ -400,7 +430,9 @@ fun Friend.getPerson(): Person { personBuilder.setIcon( if (bm == null) { coreContext.contactsManager.contactAvatar - } else IconCompat.createWithAdaptiveBitmap(bm) + } else { + IconCompat.createWithAdaptiveBitmap(bm) + } ) personBuilder.setKey(refKey) diff --git a/app/src/main/java/org/linphone/contact/ContactsSelectionAdapter.kt b/app/src/main/java/org/linphone/contact/ContactsSelectionAdapter.kt index b21b8026c..988adf296 100644 --- a/app/src/main/java/org/linphone/contact/ContactsSelectionAdapter.kt +++ b/app/src/main/java/org/linphone/contact/ContactsSelectionAdapter.kt @@ -65,7 +65,9 @@ class ContactsSelectionAdapter( override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val binding: ContactSelectionCellBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), - R.layout.contact_selection_cell, parent, false + R.layout.contact_selection_cell, + parent, + false ) return ViewHolder(binding) } @@ -114,9 +116,19 @@ class ContactsSelectionAdapter( val securityEnabled = requireLimeCapability.value ?: false val groupCapabilityRequired = requireGroupChatCapability.value ?: false val searchAddress = searchResult.address - val isMyself = securityEnabled && searchAddress != null && coreContext.core.defaultAccount?.params?.identityAddress?.weakEqual(searchAddress) ?: false - val limeCheck = !securityEnabled || (securityEnabled && searchResult.hasCapability(FriendCapability.LimeX3Dh)) - val groupCheck = !groupCapabilityRequired || (groupCapabilityRequired && searchResult.hasCapability(FriendCapability.GroupChat)) + val isMyself = securityEnabled && searchAddress != null && coreContext.core.defaultAccount?.params?.identityAddress?.weakEqual( + searchAddress + ) ?: false + val limeCheck = !securityEnabled || ( + securityEnabled && searchResult.hasCapability( + FriendCapability.LimeX3Dh + ) + ) + val groupCheck = !groupCapabilityRequired || ( + groupCapabilityRequired && searchResult.hasCapability( + FriendCapability.GroupChat + ) + ) val disabled = if (searchResult.friend != null) !limeCheck || !groupCheck || isMyself else false // Generated entry from search filter viewModel.isDisabled.value = disabled diff --git a/app/src/main/java/org/linphone/contact/ContactsSelectionViewModel.kt b/app/src/main/java/org/linphone/contact/ContactsSelectionViewModel.kt index 933aec855..5e754ed19 100644 --- a/app/src/main/java/org/linphone/contact/ContactsSelectionViewModel.kt +++ b/app/src/main/java/org/linphone/contact/ContactsSelectionViewModel.kt @@ -97,7 +97,12 @@ open class ContactsSelectionViewModel : MessageNotifierViewModel() { val domain = if (sipContactsSelected.value == true) coreContext.core.defaultAccount?.params?.domain ?: "" else "" searchResultsPending = true fastFetchJob?.cancel() - coreContext.contactsManager.magicSearch.getContactsListAsync(filterValue, domain, MagicSearchSource.All.toInt(), MagicSearchAggregation.None) + coreContext.contactsManager.magicSearch.getContactsListAsync( + filterValue, + domain, + MagicSearchSource.All.toInt(), + MagicSearchAggregation.None + ) val spinnerDelay = corePreferences.delayBeforeShowingContactsSearchSpinner.toLong() fastFetchJob = viewModelScope.launch { diff --git a/app/src/main/java/org/linphone/contact/DummySyncService.kt b/app/src/main/java/org/linphone/contact/DummySyncService.kt index 60cec9642..3aca7e36a 100644 --- a/app/src/main/java/org/linphone/contact/DummySyncService.kt +++ b/app/src/main/java/org/linphone/contact/DummySyncService.kt @@ -26,7 +26,10 @@ import android.os.Bundle import android.os.IBinder // Below classes are required to be able to use our own contact MIME type entry... -class DummySyncAdapter(context: Context, autoInit: Boolean) : AbstractThreadedSyncAdapter(context, autoInit) { +class DummySyncAdapter(context: Context, autoInit: Boolean) : AbstractThreadedSyncAdapter( + context, + autoInit +) { override fun onPerformSync( account: Account?, extras: Bundle?, diff --git a/app/src/main/java/org/linphone/contact/NativeContactEditor.kt b/app/src/main/java/org/linphone/contact/NativeContactEditor.kt index 29accf52a..1e96818fb 100644 --- a/app/src/main/java/org/linphone/contact/NativeContactEditor.kt +++ b/app/src/main/java/org/linphone/contact/NativeContactEditor.kt @@ -103,7 +103,9 @@ class NativeContactEditor(val friend: Friend) { if (rawId == null) { try { rawId = cursor.getString(cursor.getColumnIndexOrThrow(RawContacts._ID)) - Log.d("[Native Contact Editor] Found raw id $rawId for native contact with id ${friend.refKey}") + Log.d( + "[Native Contact Editor] Found raw id $rawId for native contact with id ${friend.refKey}" + ) } catch (iae: IllegalArgumentException) { Log.e("[Native Contact Editor] Exception: $iae") } @@ -136,10 +138,12 @@ class NativeContactEditor(val friend: Friend) { CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE ) .withValue( - CommonDataKinds.StructuredName.GIVEN_NAME, firstName + CommonDataKinds.StructuredName.GIVEN_NAME, + firstName ) .withValue( - CommonDataKinds.StructuredName.FAMILY_NAME, lastName + CommonDataKinds.StructuredName.FAMILY_NAME, + lastName ) addChanges(builder.build()) return this @@ -172,7 +176,8 @@ class NativeContactEditor(val friend: Friend) { CommonDataKinds.Organization.CONTENT_ITEM_TYPE ) .withValue( - CommonDataKinds.Organization.COMPANY, value + CommonDataKinds.Organization.COMPANY, + value ) addChanges(builder.build()) @@ -210,7 +215,9 @@ class NativeContactEditor(val friend: Friend) { } } - Log.i("[Native Contact Editor] $addCount numbers added, $removeCount numbers removed and $editCount numbers updated") + Log.i( + "[Native Contact Editor] $addCount numbers added, $removeCount numbers removed and $editCount numbers updated" + ) return this } @@ -245,7 +252,9 @@ class NativeContactEditor(val friend: Friend) { } } - Log.i("[Native Contact Editor] $addCount addresses added, $removeCount addresses removed and $editCount addresses updated") + Log.i( + "[Native Contact Editor] $addCount addresses added, $removeCount addresses removed and $editCount addresses updated" + ) return this } @@ -273,7 +282,9 @@ class NativeContactEditor(val friend: Friend) { if (accountType == AppUtils.getString(R.string.sync_account_type) && syncAccountRawId == null) { syncAccountRawId = cursor.getString(cursor.getColumnIndexOrThrow(RawContacts._ID)) - Log.d("[Native Contact Editor] Found linphone raw id $syncAccountRawId for native contact with id ${friend.refKey}") + Log.d( + "[Native Contact Editor] Found linphone raw id $syncAccountRawId for native contact with id ${friend.refKey}" + ) } } catch (iae: IllegalArgumentException) { Log.e("[Native Contact Editor] Exception: $iae") @@ -292,7 +303,9 @@ class NativeContactEditor(val friend: Friend) { .build() addChanges(insert) val update = - ContentProviderOperation.newUpdate(ContactsContract.AggregationExceptions.CONTENT_URI) + ContentProviderOperation.newUpdate( + ContactsContract.AggregationExceptions.CONTENT_URI + ) .withValue( ContactsContract.AggregationExceptions.TYPE, ContactsContract.AggregationExceptions.TYPE_KEEP_TOGETHER @@ -308,7 +321,9 @@ class NativeContactEditor(val friend: Friend) { } if (syncAccountRawId == null) { - Log.e("[Native Contact Editor] Can't add presence to contact in Linphone sync account, no raw id") + Log.e( + "[Native Contact Editor] Can't add presence to contact in Linphone sync account, no raw id" + ) return this } @@ -328,7 +343,9 @@ class NativeContactEditor(val friend: Friend) { Log.i("[Native Contact Editor] Result is $uri") if (uri != null && updateSyncAccountRawId && syncAccountRawId == null) { syncAccountRawId = ContentUris.parseId(uri).toString() - Log.i("[Native Contact Editor] Sync account raw id is $syncAccountRawId") + Log.i( + "[Native Contact Editor] Sync account raw id is $syncAccountRawId" + ) } } } @@ -480,22 +497,34 @@ class NativeContactEditor(val friend: Friend) { } catch (iae: IllegalArgumentException) { Log.e("[Native Contact Editor] Exception: $iae") } - } else null - } else null + } else { + null + } + } else { + null + } cursor?.close() val address = if (sipAddress.endsWith(";user=phone")) { sipAddress.substring(0, sipAddress.length - ";user=phone".length) - } else sipAddress + } else { + sipAddress + } if (count == 0) { - Log.i("[Native Contact Editor] No existing presence information found for this phone number ($phoneNumber) & SIP address ($address), let's add it") + Log.i( + "[Native Contact Editor] No existing presence information found for this phone number ($phoneNumber) & SIP address ($address), let's add it" + ) addPresenceLinphoneSipAddressForPhoneNumber(address, phoneNumber) } else { if (data1 != null && data1 == address) { - Log.d("[Native Contact Editor] There is already an entry for this phone number and SIP address, skipping") + Log.d( + "[Native Contact Editor] There is already an entry for this phone number and SIP address, skipping" + ) } else { - Log.w("[Native Contact Editor] There is already an entry for this phone number ($phoneNumber) but not for the same SIP address ($data1 != $address)") + Log.w( + "[Native Contact Editor] There is already an entry for this phone number ($phoneNumber) but not for the same SIP address ($data1 != $address)" + ) updatePresenceLinphoneSipAddressForPhoneNumber(address, phoneNumber) } } diff --git a/app/src/main/java/org/linphone/core/CoreContext.kt b/app/src/main/java/org/linphone/core/CoreContext.kt index 4d18621b5..d9eaab658 100644 --- a/app/src/main/java/org/linphone/core/CoreContext.kt +++ b/app/src/main/java/org/linphone/core/CoreContext.kt @@ -135,7 +135,9 @@ class CoreContext( if (state == GlobalState.On) { if (corePreferences.disableVideo) { // if video has been disabled, don't forget to tell the Core to disable it as well - Log.w("[Context] Video has been disabled in app, disabling it as well in the Core") + Log.w( + "[Context] Video has been disabled in app, disabling it as well in the Core" + ) core.isVideoCaptureEnabled = false core.isVideoDisplayEnabled = false @@ -155,7 +157,9 @@ class CoreContext( state: RegistrationState?, message: String ) { - Log.i("[Context] Account [${account.params.identityAddress?.asStringUriOnly()}] registration state changed [$state]") + Log.i( + "[Context] Account [${account.params.identityAddress?.asStringUriOnly()}] registration state changed [$state]" + ) if (state == RegistrationState.Ok && account == core.defaultAccount) { notificationsManager.stopForegroundNotificationIfPossible() } @@ -189,7 +193,9 @@ class CoreContext( Log.w("[Context] Auto answering call immediately") answerCall(call) } else { - Log.i("[Context] Scheduling auto answering in $autoAnswerDelay milliseconds") + Log.i( + "[Context] Scheduling auto answering in $autoAnswerDelay milliseconds" + ) handler.postDelayed( { Log.w("[Context] Auto answering call") @@ -216,7 +222,9 @@ class CoreContext( // Do not automatically route audio to bluetooth after first call if (core.callsNb == 1) { // Only try to route bluetooth / headphone / headset when the call is in StreamsRunning for the first time - Log.i("[Context] First call going into StreamsRunning state for the first time, trying to route audio to headset or bluetooth if available") + Log.i( + "[Context] First call going into StreamsRunning state for the first time, trying to route audio to headset or bluetooth if available" + ) if (AudioRouteUtils.isHeadsetAudioRouteAvailable()) { AudioRouteUtils.routeAudioToHeadset(call) } else if (corePreferences.routeAudioToBluetoothIfAvailable && AudioRouteUtils.isBluetoothAudioRouteAvailable()) { @@ -227,22 +235,34 @@ class CoreContext( // Only start call recording when the call is in StreamsRunning for the first time if (corePreferences.automaticallyStartCallRecording && !call.params.isRecording) { if (call.conference == null) { // TODO: FIXME: We disabled conference recording for now - Log.i("[Context] We were asked to start the call recording automatically") + Log.i( + "[Context] We were asked to start the call recording automatically" + ) call.startRecording() } } } } else if (state == Call.State.End || state == Call.State.Error || state == Call.State.Released) { if (state == Call.State.Error) { - Log.w("[Context] Call error reason is ${call.errorInfo.protocolCode} / ${call.errorInfo.reason} / ${call.errorInfo.phrase}") + Log.w( + "[Context] Call error reason is ${call.errorInfo.protocolCode} / ${call.errorInfo.reason} / ${call.errorInfo.phrase}" + ) val toastMessage = when (call.errorInfo.reason) { Reason.Busy -> context.getString(R.string.call_error_user_busy) Reason.IOError -> context.getString(R.string.call_error_io_error) - Reason.NotAcceptable -> context.getString(R.string.call_error_incompatible_media_params) + Reason.NotAcceptable -> context.getString( + R.string.call_error_incompatible_media_params + ) Reason.NotFound -> context.getString(R.string.call_error_user_not_found) - Reason.ServerTimeout -> context.getString(R.string.call_error_server_timeout) - Reason.TemporarilyUnavailable -> context.getString(R.string.call_error_temporarily_unavailable) - else -> context.getString(R.string.call_error_generic).format("${call.errorInfo.protocolCode} / ${call.errorInfo.phrase}") + Reason.ServerTimeout -> context.getString( + R.string.call_error_server_timeout + ) + Reason.TemporarilyUnavailable -> context.getString( + R.string.call_error_temporarily_unavailable + ) + else -> context.getString(R.string.call_error_generic).format( + "${call.errorInfo.protocolCode} / ${call.errorInfo.phrase}" + ) } callErrorMessageResourceId.value = Event(toastMessage) } else if (state == Call.State.End && @@ -336,10 +356,14 @@ class CoreContext( // CoreContext listener must be added first! if (Version.sdkAboveOrEqual(Version.API26_O_80) && corePreferences.useTelecomManager) { if (Compatibility.hasTelecomManagerPermissions(context)) { - Log.i("[Context] Creating Telecom Helper, disabling audio focus requests in AudioHelper") + Log.i( + "[Context] Creating Telecom Helper, disabling audio focus requests in AudioHelper" + ) core.config.setBool("audio", "android_disable_audio_focus_requests", true) val telecomHelper = TelecomHelper.required(context) - Log.i("[Context] Telecom Helper created, account is ${if (telecomHelper.isAccountEnabled()) "enabled" else "disabled"}") + Log.i( + "[Context] Telecom Helper created, account is ${if (telecomHelper.isAccountEnabled()) "enabled" else "disabled"}" + ) } else { Log.w("[Context] Can't create Telecom Helper, permissions have been revoked") corePreferences.useTelecomManager = false @@ -360,7 +384,9 @@ class CoreContext( if (corePreferences.vfsEnabled) { val notClearedCount = FileUtils.countFilesInDirectory(corePreferences.vfsCachePath) if (notClearedCount > 0) { - Log.w("[Context] [VFS] There are [$notClearedCount] plain files not cleared from previous app lifetime, removing them now") + Log.w( + "[Context] [VFS] There are [$notClearedCount] plain files not cleared from previous app lifetime, removing them now" + ) } FileUtils.clearExistingPlainFiles() } @@ -439,7 +465,9 @@ class CoreContext( // Disable Telecom Manager on Android < 10 to prevent crash due to OS bug in Android 9 if (Version.sdkStrictlyBelow(Version.API29_ANDROID_10)) { if (corePreferences.useTelecomManager) { - Log.w("[Context] Android < 10 detected, disabling telecom manager to prevent crash due to OS bug") + Log.w( + "[Context] Android < 10 detected, disabling telecom manager to prevent crash due to OS bug" + ) } corePreferences.useTelecomManager = false corePreferences.manuallyDisabledTelecomManager = true @@ -451,7 +479,11 @@ class CoreContext( val fiveOneMigrationRequired = core.config.getBool("app", "migration_5.1_required", true) if (fiveOneMigrationRequired) { - core.config.setBool("sip", "update_presence_model_timestamp_before_publish_expires_refresh", true) + core.config.setBool( + "sip", + "update_presence_model_timestamp_before_publish_expires_refresh", + true + ) } for (account in core.accountList) { @@ -462,14 +494,18 @@ class CoreContext( if (fiveOneMigrationRequired) { val newExpire = 2629800 // 1 month if (account.params.expires != newExpire) { - Log.i("[Context] Updating expire on proxy config ${params.identityAddress?.asString()} from ${account.params.expires} to newExpire") + Log.i( + "[Context] Updating expire on proxy config ${params.identityAddress?.asString()} from ${account.params.expires} to newExpire" + ) params.expires = newExpire paramsChanged = true } // Enable presence publish/subscribe for new feature if (!account.params.isPublishEnabled) { - Log.i("[Context] Enabling presence publish on proxy config ${params.identityAddress?.asString()}") + Log.i( + "[Context] Enabling presence publish on proxy config ${params.identityAddress?.asString()}" + ) params.isPublishEnabled = true params.publishExpires = 120 paramsChanged = true @@ -479,7 +515,9 @@ class CoreContext( // Ensure conference factory URI is set on sip.linphone.org proxy configs if (account.params.conferenceFactoryUri == null) { val uri = corePreferences.conferenceServerUri - Log.i("[Context] Setting conference factory on proxy config ${params.identityAddress?.asString()} to default value: $uri") + Log.i( + "[Context] Setting conference factory on proxy config ${params.identityAddress?.asString()} to default value: $uri" + ) params.conferenceFactoryUri = uri paramsChanged = true } @@ -489,7 +527,9 @@ class CoreContext( val uri = corePreferences.audioVideoConferenceServerUri val address = core.interpretUrl(uri, false) if (address != null) { - Log.i("[Context] Setting audio/video conference factory on proxy config ${params.identityAddress?.asString()} to default value: $uri") + Log.i( + "[Context] Setting audio/video conference factory on proxy config ${params.identityAddress?.asString()} to default value: $uri" + ) params.audioVideoConferenceFactoryAddress = address paramsChanged = true } else { @@ -499,7 +539,9 @@ class CoreContext( // Enable Bundle mode by default if (!account.params.isRtpBundleEnabled) { - Log.i("[Context] Enabling RTP bundle mode on proxy config ${params.identityAddress?.asString()}") + Log.i( + "[Context] Enabling RTP bundle mode on proxy config ${params.identityAddress?.asString()}" + ) params.isRtpBundleEnabled = true paramsChanged = true } @@ -508,18 +550,24 @@ class CoreContext( if (!account.params.isCpimInBasicChatRoomEnabled) { params.isCpimInBasicChatRoomEnabled = true paramsChanged = true - Log.i("[Context] CPIM allowed in basic chat rooms for account ${params.identityAddress?.asString()}") + Log.i( + "[Context] CPIM allowed in basic chat rooms for account ${params.identityAddress?.asString()}" + ) } if (account.params.limeServerUrl.isNullOrEmpty()) { if (limeServerUrl.isNotEmpty()) { params.limeServerUrl = limeServerUrl paramsChanged = true - Log.i("[Context] Moving Core's LIME X3DH server URL [$limeServerUrl] on account ${params.identityAddress?.asString()}") + Log.i( + "[Context] Moving Core's LIME X3DH server URL [$limeServerUrl] on account ${params.identityAddress?.asString()}" + ) } else { params.limeServerUrl = corePreferences.limeServerUrl paramsChanged = true - Log.w("[Context] Linphone account [${params.identityAddress?.asString()}] didn't have a LIME X3DH server URL, setting one: ${corePreferences.limeServerUrl}") + Log.w( + "[Context] Linphone account [${params.identityAddress?.asString()}] didn't have a LIME X3DH server URL, setting one: ${corePreferences.limeServerUrl}" + ) } } @@ -567,7 +615,9 @@ class CoreContext( } fun newAccountConfigured(isLinphoneAccount: Boolean) { - Log.i("[Context] A new ${if (isLinphoneAccount) AppUtils.getString(R.string.app_name) else "third-party"} account has been configured") + Log.i( + "[Context] A new ${if (isLinphoneAccount) AppUtils.getString(R.string.app_name) else "third-party"} account has been configured" + ) if (isLinphoneAccount) { core.config.setString("sip", "rls_uri", corePreferences.defaultRlsUri) @@ -596,14 +646,20 @@ class CoreContext( if (PermissionHelper.required(context).hasReadPhoneStatePermission()) { try { phoneStateListener = - Compatibility.createPhoneListener(context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager) + Compatibility.createPhoneListener( + context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager + ) } catch (exception: SecurityException) { val hasReadPhoneStatePermission = PermissionHelper.get().hasReadPhoneStateOrPhoneNumbersPermission() - Log.e("[Context] Failed to create phone state listener: $exception, READ_PHONE_STATE permission status is $hasReadPhoneStatePermission") + Log.e( + "[Context] Failed to create phone state listener: $exception, READ_PHONE_STATE permission status is $hasReadPhoneStatePermission" + ) } } else { - Log.w("[Context] Can't create phone state listener, READ_PHONE_STATE permission isn't granted") + Log.w( + "[Context] Can't create phone state listener, READ_PHONE_STATE permission isn't granted" + ) } } @@ -623,7 +679,9 @@ class CoreContext( if (!TelecomHelper.get().isIncomingCallPermitted() || TelecomHelper.get().isInManagedCall() ) { - Log.w("[Context] Refusing the call with reason busy because Telecom Manager will reject the call") + Log.w( + "[Context] Refusing the call with reason busy because Telecom Manager will reject the call" + ) return true } } else { @@ -675,7 +733,9 @@ class CoreContext( // Do the same as the conference waiting room params.isVideoEnabled = true params.videoDirection = if (core.videoActivationPolicy.automaticallyInitiate) MediaDirection.SendRecv else MediaDirection.RecvOnly - Log.i("[Context] Enabling video on call params to prevent audio-only layout when answering") + Log.i( + "[Context] Enabling video on call params to prevent audio-only layout when answering" + ) } call.acceptWithParams(params) @@ -726,10 +786,15 @@ class CoreContext( } } - val address: Address? = core.interpretUrl(stringAddress, LinphoneUtils.applyInternationalPrefix()) + val address: Address? = core.interpretUrl( + stringAddress, + LinphoneUtils.applyInternationalPrefix() + ) if (address == null) { Log.e("[Context] Failed to parse $stringAddress, abort outgoing call") - callErrorMessageResourceId.value = Event(context.getString(R.string.call_error_network_unreachable)) + callErrorMessageResourceId.value = Event( + context.getString(R.string.call_error_network_unreachable) + ) return } @@ -744,7 +809,9 @@ class CoreContext( ) { if (!core.isNetworkReachable) { Log.e("[Context] Network unreachable, abort outgoing call") - callErrorMessageResourceId.value = Event(context.getString(R.string.call_error_network_unreachable)) + callErrorMessageResourceId.value = Event( + context.getString(R.string.call_error_network_unreachable) + ) return } @@ -770,9 +837,13 @@ class CoreContext( } if (account != null) { params.account = account - Log.i("[Context] Using account matching address ${localAddress.asStringUriOnly()} as From") + Log.i( + "[Context] Using account matching address ${localAddress.asStringUriOnly()} as From" + ) } else { - Log.e("[Context] Failed to find account matching address ${localAddress.asStringUriOnly()}") + Log.e( + "[Context] Failed to find account matching address ${localAddress.asStringUriOnly()}" + ) } } @@ -934,7 +1005,9 @@ class CoreContext( } } } else { - Log.e("[Context] Can't make file public, app doesn't have WRITE_EXTERNAL_STORAGE permission") + Log.e( + "[Context] Can't make file public, app doesn't have WRITE_EXTERNAL_STORAGE permission" + ) } } @@ -958,27 +1031,41 @@ class CoreContext( when { FileUtils.isMimeImage(mime) -> { if (Compatibility.addImageToMediaStore(context, content)) { - Log.i("[Context] Successfully exported image [${content.name}] to Media Store") + Log.i( + "[Context] Successfully exported image [${content.name}] to Media Store" + ) } else { - Log.e("[Context] Something went wrong while copying file to Media Store...") + Log.e( + "[Context] Something went wrong while copying file to Media Store..." + ) } } FileUtils.isMimeVideo(mime) -> { if (Compatibility.addVideoToMediaStore(context, content)) { - Log.i("[Context] Successfully exported video [${content.name}] to Media Store") + Log.i( + "[Context] Successfully exported video [${content.name}] to Media Store" + ) } else { - Log.e("[Context] Something went wrong while copying file to Media Store...") + Log.e( + "[Context] Something went wrong while copying file to Media Store..." + ) } } FileUtils.isMimeAudio(mime) -> { if (Compatibility.addAudioToMediaStore(context, content)) { - Log.i("[Context] Successfully exported audio [${content.name}] to Media Store") + Log.i( + "[Context] Successfully exported audio [${content.name}] to Media Store" + ) } else { - Log.e("[Context] Something went wrong while copying file to Media Store...") + Log.e( + "[Context] Something went wrong while copying file to Media Store..." + ) } } else -> { - Log.w("[Context] File [$filePath] isn't either an image, an audio file or a video [${content.type}/${content.subtype}], can't add it to the Media Store") + Log.w( + "[Context] File [$filePath] isn't either an image, an audio file or a video [${content.type}/${content.subtype}], can't add it to the Media Store" + ) } } } @@ -991,7 +1078,9 @@ class CoreContext( delay(delayInMs) withContext(Dispatchers.Main) { if (core.defaultAccount != null && core.defaultAccount?.state == RegistrationState.Ok) { - Log.i("[Context] Default account is registered, cancel foreground service notification if possible") + Log.i( + "[Context] Default account is registered, cancel foreground service notification if possible" + ) notificationsManager.stopForegroundNotificationIfPossible() } } diff --git a/app/src/main/java/org/linphone/core/CorePreferences.kt b/app/src/main/java/org/linphone/core/CorePreferences.kt index e12bd8540..9d88e0a32 100644 --- a/app/src/main/java/org/linphone/core/CorePreferences.kt +++ b/app/src/main/java/org/linphone/core/CorePreferences.kt @@ -55,7 +55,9 @@ class CorePreferences constructor(private val context: Context) { ).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build() try { EncryptedSharedPreferences.create( - context, encryptedSharedPreferencesFile, masterKey, + context, + encryptedSharedPreferencesFile, + masterKey, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) @@ -89,12 +91,18 @@ class CorePreferences constructor(private val context: Context) { } fun chatRoomMuted(id: String): Boolean { - val sharedPreferences: SharedPreferences = coreContext.context.getSharedPreferences("notifications", Context.MODE_PRIVATE) + val sharedPreferences: SharedPreferences = coreContext.context.getSharedPreferences( + "notifications", + Context.MODE_PRIVATE + ) return sharedPreferences.getBoolean(id, false) } fun muteChatRoom(id: String, mute: Boolean) { - val sharedPreferences: SharedPreferences = coreContext.context.getSharedPreferences("notifications", Context.MODE_PRIVATE) + val sharedPreferences: SharedPreferences = coreContext.context.getSharedPreferences( + "notifications", + Context.MODE_PRIVATE + ) val editor = sharedPreferences.edit() editor.putBoolean(id, mute) editor.apply() @@ -595,7 +603,11 @@ class CorePreferences constructor(private val context: Context) { get() = config.getBool("app", "side_menu_recordings", true) val showScheduledConferencesInSideMenu: Boolean - get() = config.getBool("app", "side_menu_conferences", LinphoneUtils.isRemoteConferencingAvailable()) + get() = config.getBool( + "app", + "side_menu_conferences", + LinphoneUtils.isRemoteConferencingAvailable() + ) val showAboutInSideMenu: Boolean get() = config.getBool("app", "side_menu_about", true) @@ -636,7 +648,11 @@ class CorePreferences constructor(private val context: Context) { get() = config.getBool("app", "settings_advanced", true) val showConferencesSettings: Boolean - get() = config.getBool("app", "settings_conferences", LinphoneUtils.isRemoteConferencingAvailable()) + get() = config.getBool( + "app", + "settings_conferences", + LinphoneUtils.isRemoteConferencingAvailable() + ) /* Assets stuff */ @@ -673,8 +689,14 @@ class CorePreferences constructor(private val context: Context) { copy("assistant_linphone_default_values", linphoneDefaultValuesPath, true) copy("assistant_default_values", defaultValuesPath, true) - move(context.filesDir.absolutePath + "/linphone-log-history.db", context.filesDir.absolutePath + "/call-history.db") - move(context.filesDir.absolutePath + "/zrtp_secrets", context.filesDir.absolutePath + "/zrtp-secrets.db") + move( + context.filesDir.absolutePath + "/linphone-log-history.db", + context.filesDir.absolutePath + "/call-history.db" + ) + move( + context.filesDir.absolutePath + "/zrtp_secrets", + context.filesDir.absolutePath + "/zrtp-secrets.db" + ) } fun getString(resource: Int): String { @@ -685,11 +707,17 @@ class CorePreferences constructor(private val context: Context) { val outFile = File(to) if (outFile.exists()) { if (!overrideIfExists) { - android.util.Log.i(context.getString(org.linphone.R.string.app_name), "[Preferences] File $to already exists") + android.util.Log.i( + context.getString(org.linphone.R.string.app_name), + "[Preferences] File $to already exists" + ) return } } - android.util.Log.i(context.getString(org.linphone.R.string.app_name), "[Preferences] Overriding $to by $from asset") + android.util.Log.i( + context.getString(org.linphone.R.string.app_name), + "[Preferences] Overriding $to by $from asset" + ) val outStream = FileOutputStream(outFile) val inFile = context.assets.open(from) @@ -711,7 +739,10 @@ class CorePreferences constructor(private val context: Context) { val outFile = File(to) if (inFile.exists()) { if (outFile.exists() && !overrideIfExists) { - android.util.Log.w(context.getString(org.linphone.R.string.app_name), "[Preferences] Can't move [$from] to [$to], destination file already exists") + android.util.Log.w( + context.getString(org.linphone.R.string.app_name), + "[Preferences] Can't move [$from] to [$to], destination file already exists" + ) } else { val inStream = FileInputStream(inFile) val outStream = FileOutputStream(outFile) @@ -727,10 +758,16 @@ class CorePreferences constructor(private val context: Context) { outStream.close() inFile.delete() - android.util.Log.i(context.getString(org.linphone.R.string.app_name), "[Preferences] Successfully moved [$from] to [$to]") + android.util.Log.i( + context.getString(org.linphone.R.string.app_name), + "[Preferences] Successfully moved [$from] to [$to]" + ) } } else { - android.util.Log.w(context.getString(org.linphone.R.string.app_name), "[Preferences] Can't move [$from] to [$to], source file doesn't exists") + android.util.Log.w( + context.getString(org.linphone.R.string.app_name), + "[Preferences] Can't move [$from] to [$to], source file doesn't exists" + ) } } } diff --git a/app/src/main/java/org/linphone/core/CoreService.kt b/app/src/main/java/org/linphone/core/CoreService.kt index c3b35cf11..a8bfead64 100644 --- a/app/src/main/java/org/linphone/core/CoreService.kt +++ b/app/src/main/java/org/linphone/core/CoreService.kt @@ -37,17 +37,34 @@ class CoreService : CoreService() { Log.i("[Service] Ensuring Core exists") if (corePreferences.keepServiceAlive) { Log.i("[Service] Starting as foreground to keep app alive in background") - if (!ensureCoreExists(applicationContext, pushReceived = false, service = this, useAutoStartDescription = false)) { + if (!ensureCoreExists( + applicationContext, + pushReceived = false, + service = this, + useAutoStartDescription = false + ) + ) { coreContext.notificationsManager.startForeground(this, false) } } else if (intent?.extras?.get("StartForeground") == true) { Log.i("[Service] Starting as foreground due to device boot or app update") - if (!ensureCoreExists(applicationContext, pushReceived = false, service = this, useAutoStartDescription = true)) { + if (!ensureCoreExists( + applicationContext, + pushReceived = false, + service = this, + useAutoStartDescription = true + ) + ) { coreContext.notificationsManager.startForeground(this, true) } coreContext.checkIfForegroundServiceNotificationCanBeRemovedAfterDelay(5000) } else { - ensureCoreExists(applicationContext, pushReceived = false, service = this, useAutoStartDescription = false) + ensureCoreExists( + applicationContext, + pushReceived = false, + service = this, + useAutoStartDescription = false + ) } coreContext.notificationsManager.serviceCreated(this) @@ -72,7 +89,9 @@ class CoreService : CoreService() { override fun onTaskRemoved(rootIntent: Intent?) { if (LinphoneApplication.contextExists()) { if (coreContext.core.callsNb > 0) { - Log.w("[Service] Task removed but there is at least one active call, do not stop the Core!") + Log.w( + "[Service] Task removed but there is at least one active call, do not stop the Core!" + ) } else if (!corePreferences.keepServiceAlive) { if (coreContext.core.isInBackground) { Log.i("[Service] Task removed, stopping Core") @@ -81,7 +100,9 @@ class CoreService : CoreService() { Log.w("[Service] Task removed but Core is not in background, skipping") } } else { - Log.i("[Service] Task removed but we were asked to keep the service alive, so doing nothing") + Log.i( + "[Service] Task removed but we were asked to keep the service alive, so doing nothing" + ) } } diff --git a/app/src/main/java/org/linphone/notifications/NotificationBroadcastReceiver.kt b/app/src/main/java/org/linphone/notifications/NotificationBroadcastReceiver.kt index ebfc134cd..6665f3f1c 100644 --- a/app/src/main/java/org/linphone/notifications/NotificationBroadcastReceiver.kt +++ b/app/src/main/java/org/linphone/notifications/NotificationBroadcastReceiver.kt @@ -36,7 +36,9 @@ class NotificationBroadcastReceiver : BroadcastReceiver() { ensureCoreExists(context.applicationContext, false) val notificationId = intent.getIntExtra(NotificationsManager.INTENT_NOTIF_ID, 0) - Log.i("[Notification Broadcast Receiver] Got notification broadcast for ID [$notificationId]") + Log.i( + "[Notification Broadcast Receiver] Got notification broadcast for ID [$notificationId]" + ) if (intent.action == NotificationsManager.INTENT_REPLY_NOTIF_ACTION || intent.action == NotificationsManager.INTENT_MARK_AS_READ_ACTION) { handleChatIntent(context, intent, notificationId) @@ -48,31 +50,41 @@ class NotificationBroadcastReceiver : BroadcastReceiver() { private fun handleChatIntent(context: Context, intent: Intent, notificationId: Int) { val remoteSipAddress = intent.getStringExtra(NotificationsManager.INTENT_REMOTE_ADDRESS) if (remoteSipAddress == null) { - Log.e("[Notification Broadcast Receiver] Remote SIP address is null for notification id $notificationId") + Log.e( + "[Notification Broadcast Receiver] Remote SIP address is null for notification id $notificationId" + ) return } val core: Core = coreContext.core val remoteAddress = core.interpretUrl(remoteSipAddress, false) if (remoteAddress == null) { - Log.e("[Notification Broadcast Receiver] Couldn't interpret remote address $remoteSipAddress") + Log.e( + "[Notification Broadcast Receiver] Couldn't interpret remote address $remoteSipAddress" + ) return } val localIdentity = intent.getStringExtra(NotificationsManager.INTENT_LOCAL_IDENTITY) if (localIdentity == null) { - Log.e("[Notification Broadcast Receiver] Local identity is null for notification id $notificationId") + Log.e( + "[Notification Broadcast Receiver] Local identity is null for notification id $notificationId" + ) return } val localAddress = core.interpretUrl(localIdentity, false) if (localAddress == null) { - Log.e("[Notification Broadcast Receiver] Couldn't interpret local address $localIdentity") + Log.e( + "[Notification Broadcast Receiver] Couldn't interpret local address $localIdentity" + ) return } val room = core.searchChatRoom(null, localAddress, remoteAddress, arrayOfNulls(0)) if (room == null) { - Log.e("[Notification Broadcast Receiver] Couldn't find chat room for remote address $remoteSipAddress and local address $localIdentity") + Log.e( + "[Notification Broadcast Receiver] Couldn't find chat room for remote address $remoteSipAddress and local address $localIdentity" + ) return } @@ -91,7 +103,9 @@ class NotificationBroadcastReceiver : BroadcastReceiver() { } else { room.markAsRead() if (!coreContext.notificationsManager.dismissChatNotification(room)) { - Log.w("[Notification Broadcast Receiver] Notifications Manager failed to cancel notification") + Log.w( + "[Notification Broadcast Receiver] Notifications Manager failed to cancel notification" + ) val notificationManager = context.getSystemService(NotificationManager::class.java) notificationManager.cancel(NotificationsManager.CHAT_TAG, notificationId) } @@ -110,7 +124,9 @@ class NotificationBroadcastReceiver : BroadcastReceiver() { val remoteAddress = core.interpretUrl(remoteSipAddress, false) val call = if (remoteAddress != null) core.getCallByRemoteAddress2(remoteAddress) else null if (call == null) { - Log.e("[Notification Broadcast Receiver] Couldn't find call from remote address $remoteSipAddress") + Log.e( + "[Notification Broadcast Receiver] Couldn't find call from remote address $remoteSipAddress" + ) return } diff --git a/app/src/main/java/org/linphone/notifications/NotificationsManager.kt b/app/src/main/java/org/linphone/notifications/NotificationsManager.kt index 606b672d3..df4a30389 100644 --- a/app/src/main/java/org/linphone/notifications/NotificationsManager.kt +++ b/app/src/main/java/org/linphone/notifications/NotificationsManager.kt @@ -122,7 +122,9 @@ class NotificationsManager(private val context: Context) { when (call.state) { Call.State.IncomingEarlyMedia, Call.State.IncomingReceived -> { if (service != null) { - Log.i("[Notifications Manager] Service isn't null, show incoming call notification") + Log.i( + "[Notifications Manager] Service isn't null, show incoming call notification" + ) displayIncomingCallNotification(call, false) } else { Log.w("[Notifications Manager] No service found, waiting for it to start") @@ -152,7 +154,9 @@ class NotificationsManager(private val context: Context) { } if (currentlyDisplayedChatRoomAddress == room.peerAddress.asStringUriOnly()) { - Log.i("[Notifications Manager] Chat room is currently displayed, do not notify received message") + Log.i( + "[Notifications Manager] Chat room is currently displayed, do not notify received message" + ) // Mark as read is now done in the DetailChatRoomFragment return } @@ -168,7 +172,9 @@ class NotificationsManager(private val context: Context) { if (ShortcutsHelper.isShortcutToChatRoomAlreadyCreated(context, room)) { Log.i("[Notifications Manager] Chat room shortcut already exists") } else { - Log.i("[Notifications Manager] Ensure chat room shortcut exists for bubble notification") + Log.i( + "[Notifications Manager] Ensure chat room shortcut exists for bubble notification" + ) ShortcutsHelper.createShortcutsToChatRooms(context) } } @@ -177,7 +183,9 @@ class NotificationsManager(private val context: Context) { if (notifiable.messages.isNotEmpty()) { displayChatNotifiable(room, notifiable) } else { - Log.w("[Notifications Manager] No message to display in received aggregated messages") + Log.w( + "[Notifications Manager] No message to display in received aggregated messages" + ) } } @@ -186,24 +194,34 @@ class NotificationsManager(private val context: Context) { val notifiable = chatNotificationsMap[address] if (notifiable != null) { if (chatBubbleNotifications.contains(notifiable.notificationId)) { - Log.i("[Notifications Manager] Chat room [$chatRoom] has been marked as read, not removing notification because of a chat bubble") + Log.i( + "[Notifications Manager] Chat room [$chatRoom] has been marked as read, not removing notification because of a chat bubble" + ) } else { - Log.i("[Notifications Manager] Chat room [$chatRoom] has been marked as read, removing notification if any") + Log.i( + "[Notifications Manager] Chat room [$chatRoom] has been marked as read, removing notification if any" + ) dismissChatNotification(chatRoom) } } else { val notificationId = getNotificationIdForChat(chatRoom) if (chatBubbleNotifications.contains(notificationId)) { - Log.i("[Notifications Manager] Chat room [$chatRoom] has been marked as read but no notifiable found, not removing notification because of a chat bubble") + Log.i( + "[Notifications Manager] Chat room [$chatRoom] has been marked as read but no notifiable found, not removing notification because of a chat bubble" + ) } else { - Log.i("[Notifications Manager] Chat room [$chatRoom] has been marked as read but no notifiable found, removing notification if any") + Log.i( + "[Notifications Manager] Chat room [$chatRoom] has been marked as read but no notifiable found, removing notification if any" + ) dismissChatNotification(chatRoom) } } } override fun onLastCallEnded(core: Core) { - Log.i("[Notifications Manager] Last call ended, make sure foreground service is stopped and notification removed") + Log.i( + "[Notifications Manager] Last call ended, make sure foreground service is stopped and notification removed" + ) stopCallForeground() } } @@ -224,11 +242,15 @@ class NotificationsManager(private val context: Context) { val notifiable = chatNotificationsMap[address] if (notifiable != null) { if (notifiable.notificationId != id) { - Log.w("[Notifications Manager] ID doesn't match: ${notifiable.notificationId} != $id") + Log.w( + "[Notifications Manager] ID doesn't match: ${notifiable.notificationId} != $id" + ) } displayReplyMessageNotification(message, notifiable) } else { - Log.e("[Notifications Manager] Couldn't find notification for chat room $address") + Log.e( + "[Notifications Manager] Couldn't find notification for chat room $address" + ) cancel(id, CHAT_TAG) } } else if (state == ChatMessage.State.NotDelivered) { @@ -244,10 +266,14 @@ class NotificationsManager(private val context: Context) { val manager = context.getSystemService(NotificationManager::class.java) as NotificationManager for (notification in manager.activeNotifications) { if (notification.tag.isNullOrEmpty()) { // We use null tag for call notifications otherwise it will create duplicates when used with Service.startForeground()... - Log.w("[Notifications Manager] Found existing call? notification [${notification.id}], cancelling it") + Log.w( + "[Notifications Manager] Found existing call? notification [${notification.id}], cancelling it" + ) manager.cancel(notification.tag, notification.id) } else if (notification.tag == CHAT_TAG) { - Log.i("[Notifications Manager] Found existing chat notification [${notification.id}]") + Log.i( + "[Notifications Manager] Found existing chat notification [${notification.id}]" + ) previousChatNotifications.add(notification.id) } } @@ -262,7 +288,9 @@ class NotificationsManager(private val context: Context) { // When a message is received by a push, it will create a CoreService // but it might be getting killed quite quickly after that // causing the notification to be missed by the user... - Log.i("[Notifications Manager] Getting destroyed, clearing foreground Service & call notifications") + Log.i( + "[Notifications Manager] Getting destroyed, clearing foreground Service & call notifications" + ) if (currentForegroundServiceNotificationId > 0 && !corePreferences.keepServiceAlive) { Log.i("[Notifications Manager] Clearing foreground Service") @@ -282,7 +310,9 @@ class NotificationsManager(private val context: Context) { @SuppressLint("MissingPermission") private fun notify(id: Int, notification: Notification, tag: String? = null) { if (!PermissionHelper.get().hasPostNotificationsPermission()) { - Log.w("[Notifications Manager] Can't notify [$id] with tag [$tag], POST_NOTIFICATIONS permission isn't granted!") + Log.w( + "[Notifications Manager] Can't notify [$id] with tag [$tag], POST_NOTIFICATIONS permission isn't granted!" + ) return } @@ -313,7 +343,9 @@ class NotificationsManager(private val context: Context) { if (coreService != null) { startForeground(coreService, useAutoStartDescription = false) } else { - Log.w("[Notifications Manager] Can't start service as foreground without a service, starting it now") + Log.w( + "[Notifications Manager] Can't start service as foreground without a service, starting it now" + ) val intent = Intent() intent.setClass(coreContext.context, CoreService::class.java) try { @@ -331,9 +363,13 @@ class NotificationsManager(private val context: Context) { when { currentForegroundServiceNotificationId != 0 -> { if (currentForegroundServiceNotificationId != SERVICE_NOTIF_ID) { - Log.e("[Notifications Manager] There is already a foreground service notification [$currentForegroundServiceNotificationId]") + Log.e( + "[Notifications Manager] There is already a foreground service notification [$currentForegroundServiceNotificationId]" + ) } else { - Log.i("[Notifications Manager] There is already a foreground service notification, no need to use the call notification to keep Service alive") + Log.i( + "[Notifications Manager] There is already a foreground service notification, no need to use the call notification to keep Service alive" + ) } } coreContext.core.callsNb > 0 -> { @@ -341,11 +377,15 @@ class NotificationsManager(private val context: Context) { val call = coreContext.core.currentCall ?: coreContext.core.calls[0] when (call.state) { Call.State.IncomingReceived, Call.State.IncomingEarlyMedia -> { - Log.i("[Notifications Manager] Creating incoming call notification to be used as foreground service") + Log.i( + "[Notifications Manager] Creating incoming call notification to be used as foreground service" + ) displayIncomingCallNotification(call, true) } else -> { - Log.i("[Notifications Manager] Creating call notification to be used as foreground service") + Log.i( + "[Notifications Manager] Creating call notification to be used as foreground service" + ) displayCallNotification(call, true) } } @@ -359,19 +399,29 @@ class NotificationsManager(private val context: Context) { if (serviceNotification == null) { createServiceNotification(useAutoStartDescription) if (serviceNotification == null) { - Log.e("[Notifications Manager] Failed to create service notification, aborting foreground service!") + Log.e( + "[Notifications Manager] Failed to create service notification, aborting foreground service!" + ) return } } currentForegroundServiceNotificationId = SERVICE_NOTIF_ID - Log.i("[Notifications Manager] Starting service as foreground [$currentForegroundServiceNotificationId]") - Compatibility.startForegroundService(coreService, currentForegroundServiceNotificationId, serviceNotification) + Log.i( + "[Notifications Manager] Starting service as foreground [$currentForegroundServiceNotificationId]" + ) + Compatibility.startForegroundService( + coreService, + currentForegroundServiceNotificationId, + serviceNotification + ) } private fun startForeground(notificationId: Int, callNotification: Notification) { if (currentForegroundServiceNotificationId == 0 && service != null) { - Log.i("[Notifications Manager] Starting service as foreground using call notification [$notificationId]") + Log.i( + "[Notifications Manager] Starting service as foreground using call notification [$notificationId]" + ) try { currentForegroundServiceNotificationId = notificationId @@ -391,14 +441,18 @@ class NotificationsManager(private val context: Context) { currentForegroundServiceNotificationId = 0 } } else { - Log.w("[Notifications Manager] Can't start foreground service using notification id [$notificationId] (current foreground service notification id is [$currentForegroundServiceNotificationId]) and service [$service]") + Log.w( + "[Notifications Manager] Can't start foreground service using notification id [$notificationId] (current foreground service notification id is [$currentForegroundServiceNotificationId]) and service [$service]" + ) } } fun stopForegroundNotification() { if (service != null) { if (currentForegroundServiceNotificationId != 0) { - Log.i("[Notifications Manager] Stopping service as foreground [$currentForegroundServiceNotificationId]") + Log.i( + "[Notifications Manager] Stopping service as foreground [$currentForegroundServiceNotificationId]" + ) currentForegroundServiceNotificationId = 0 } service?.stopForeground(true) @@ -407,14 +461,18 @@ class NotificationsManager(private val context: Context) { fun stopForegroundNotificationIfPossible() { if (service != null && currentForegroundServiceNotificationId == SERVICE_NOTIF_ID && !corePreferences.keepServiceAlive) { - Log.i("[Notifications Manager] Stopping auto-started service notification [$currentForegroundServiceNotificationId]") + Log.i( + "[Notifications Manager] Stopping auto-started service notification [$currentForegroundServiceNotificationId]" + ) stopForegroundNotification() } } fun stopCallForeground() { if (service != null && currentForegroundServiceNotificationId != SERVICE_NOTIF_ID) { - Log.i("[Notifications Manager] Stopping call notification [$currentForegroundServiceNotificationId] used as foreground service") + Log.i( + "[Notifications Manager] Stopping call notification [$currentForegroundServiceNotificationId] used as foreground service" + ) stopForegroundNotification() } } @@ -445,7 +503,15 @@ class NotificationsManager(private val context: Context) { val builder = NotificationCompat.Builder(context, serviceChannel) .setContentTitle(context.getString(R.string.service_name)) - .setContentText(if (useAutoStartDescription) context.getString(R.string.service_auto_start_description) else context.getString(R.string.service_description)) + .setContentText( + if (useAutoStartDescription) { + context.getString( + R.string.service_auto_start_description + ) + } else { + context.getString(R.string.service_description) + } + ) .setSmallIcon(R.drawable.topbar_service_notification) .setCategory(NotificationCompat.CATEGORY_SERVICE) .setVisibility(NotificationCompat.VISIBILITY_SECRET) @@ -496,13 +562,17 @@ class NotificationsManager(private val context: Context) { fun displayIncomingCallNotification(call: Call, useAsForeground: Boolean) { if (coreContext.declineCallDueToGsmActiveCall()) { - Log.w("[Notifications Manager] Call will be declined, do not show incoming call notification") + Log.w( + "[Notifications Manager] Call will be declined, do not show incoming call notification" + ) return } val notifiable = getNotifiableForCall(call) if (notifiable.notificationId == currentForegroundServiceNotificationId) { - Log.i("[Notifications Manager] There is already a Service foreground notification for this incoming call, skipping") + Log.i( + "[Notifications Manager] There is already a Service foreground notification for this incoming call, skipping" + ) return } @@ -512,13 +582,19 @@ class NotificationsManager(private val context: Context) { "lock_screen_show_notifications", 0 ) - Log.i("[Notifications Manager] Are notifications allowed on lock screen? ${showLockScreenNotification != 0} ($showLockScreenNotification)") + Log.i( + "[Notifications Manager] Are notifications allowed on lock screen? ${showLockScreenNotification != 0} ($showLockScreenNotification)" + ) } catch (e: Exception) { - Log.e("[Notifications Manager] Failed to get android.provider.Settings.Secure.getInt(lock_screen_show_notifications): $e") + Log.e( + "[Notifications Manager] Failed to get android.provider.Settings.Secure.getInt(lock_screen_show_notifications): $e" + ) } val incomingCallNotificationIntent = Intent(context, CallActivity::class.java) - incomingCallNotificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_USER_ACTION or Intent.FLAG_FROM_BACKGROUND) + incomingCallNotificationIntent.addFlags( + Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_USER_ACTION or Intent.FLAG_FROM_BACKGROUND + ) val pendingIntent = PendingIntent.getActivity( context, 0, @@ -526,12 +602,22 @@ class NotificationsManager(private val context: Context) { PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE ) - val notification = Compatibility.createIncomingCallNotification(context, call, notifiable, pendingIntent, this) - Log.i("[Notifications Manager] Notifying incoming call notification [${notifiable.notificationId}]") + val notification = Compatibility.createIncomingCallNotification( + context, + call, + notifiable, + pendingIntent, + this + ) + Log.i( + "[Notifications Manager] Notifying incoming call notification [${notifiable.notificationId}]" + ) notify(notifiable.notificationId, notification) if (useAsForeground) { - Log.i("[Notifications Manager] Notifying incoming call notification for foreground service [${notifiable.notificationId}]") + Log.i( + "[Notifications Manager] Notifying incoming call notification for foreground service [${notifiable.notificationId}]" + ) startForeground(notifiable.notificationId, notification) } } @@ -542,7 +628,9 @@ class NotificationsManager(private val context: Context) { if (missedCallCount > 1) { body = context.getString(R.string.missed_calls_notification_body) .format(missedCallCount) - Log.i("[Notifications Manager] Updating missed calls notification count to $missedCallCount") + Log.i( + "[Notifications Manager] Updating missed calls notification count to $missedCallCount" + ) } else { val friend: Friend? = coreContext.contactsManager.findContactByAddress(remoteAddress) body = context.getString(R.string.missed_call_notification_body) @@ -557,7 +645,8 @@ class NotificationsManager(private val context: Context) { .createPendingIntent() val builder = NotificationCompat.Builder( - context, context.getString(R.string.notification_channel_missed_call_id) + context, + context.getString(R.string.notification_channel_missed_call_id) ) .setContentTitle(context.getString(R.string.missed_call_notification_title)) .setContentText(body) @@ -586,9 +675,16 @@ class NotificationsManager(private val context: Context) { val notifiable = getNotifiableForCall(call) val serviceChannel = context.getString(R.string.notification_channel_service_id) - val channelToUse = when (val serviceChannelImportance = Compatibility.getChannelImportance(notificationManager, serviceChannel)) { + val channelToUse = when ( + val serviceChannelImportance = Compatibility.getChannelImportance( + notificationManager, + serviceChannel + ) + ) { NotificationManagerCompat.IMPORTANCE_NONE -> { - Log.w("[Notifications Manager] Service channel is disabled, using incoming call channel instead!") + Log.w( + "[Notifications Manager] Service channel is disabled, using incoming call channel instead!" + ) context.getString(R.string.notification_channel_incoming_call_id) } NotificationManagerCompat.IMPORTANCE_LOW -> { @@ -597,7 +693,9 @@ class NotificationsManager(private val context: Context) { } else -> { // If user disables & enabled back service notifications channel, importance won't be low anymore but default! - Log.w("[Notifications Manager] Service channel importance is $serviceChannelImportance and not LOW (${NotificationManagerCompat.IMPORTANCE_LOW}) as expected!") + Log.w( + "[Notifications Manager] Service channel importance is $serviceChannelImportance and not LOW (${NotificationManagerCompat.IMPORTANCE_LOW}) as expected!" + ) serviceChannel } } @@ -611,12 +709,21 @@ class NotificationsManager(private val context: Context) { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) - val notification = Compatibility.createCallNotification(context, call, notifiable, pendingIntent, channelToUse, this) + val notification = Compatibility.createCallNotification( + context, + call, + notifiable, + pendingIntent, + channelToUse, + this + ) Log.i("[Notifications Manager] Notifying call notification [${notifiable.notificationId}]") notify(notifiable.notificationId, notification) if (useAsForeground || (service != null && currentForegroundServiceNotificationId == 0)) { - Log.i("[Notifications Manager] Notifying call notification for foreground service [${notifiable.notificationId}]") + Log.i( + "[Notifications Manager] Notifying call notification for foreground service [${notifiable.notificationId}]" + ) startForeground(notifiable.notificationId, notification) } } @@ -665,7 +772,13 @@ class NotificationsManager(private val context: Context) { val id = LinphoneUtils.getChatRoomId(room.localAddress, room.peerAddress) val me = coreContext.contactsManager.getMePerson(room.localAddress) - val notification = createMessageNotification(notifiable, pendingIntent, bubbleIntent, id, me) + val notification = createMessageNotification( + notifiable, + pendingIntent, + bubbleIntent, + id, + me + ) notify(notifiable.notificationId, notification, CHAT_TAG) } @@ -747,9 +860,13 @@ class NotificationsManager(private val context: Context) { MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) notifiableMessage.filePath = contentUri notifiableMessage.fileMime = mime - Log.i("[Notifications Manager] Added file $contentUri with MIME $mime to notification") + Log.i( + "[Notifications Manager] Added file $contentUri with MIME $mime to notification" + ) } else { - Log.e("[Notifications Manager] Couldn't find extension for incoming message with file $path") + Log.e( + "[Notifications Manager] Couldn't find extension for incoming message with file $path" + ) } } } @@ -759,7 +876,9 @@ class NotificationsManager(private val context: Context) { } private fun displayReplyMessageNotification(message: ChatMessage, notifiable: Notifiable) { - Log.i("[Notifications Manager] Updating message notification with reply for notification ${notifiable.notificationId}") + Log.i( + "[Notifications Manager] Updating message notification with reply for notification ${notifiable.notificationId}" + ) val text = message.contents.find { content -> content.isText }?.utf8Text ?: "" val senderAddress = message.fromAddress @@ -779,17 +898,27 @@ class NotificationsManager(private val context: Context) { val address = room.peerAddress.asStringUriOnly() val notifiable: Notifiable? = chatNotificationsMap[address] if (notifiable != null) { - Log.i("[Notifications Manager] Dismissing notification for chat room $room with id ${notifiable.notificationId}") + Log.i( + "[Notifications Manager] Dismissing notification for chat room $room with id ${notifiable.notificationId}" + ) notifiable.messages.clear() cancel(notifiable.notificationId, CHAT_TAG) return true } else { - val previousNotificationId = previousChatNotifications.find { id -> id == getNotificationIdForChat(room) } + val previousNotificationId = previousChatNotifications.find { id -> + id == getNotificationIdForChat( + room + ) + } if (previousNotificationId != null) { if (chatBubbleNotifications.contains(previousNotificationId)) { - Log.i("[Notifications Manager] Found previous notification with same ID [$previousNotificationId] but not cancelling it as it's ID is in chat bubbles list") + Log.i( + "[Notifications Manager] Found previous notification with same ID [$previousNotificationId] but not cancelling it as it's ID is in chat bubbles list" + ) } else { - Log.i("[Notifications Manager] Found previous notification with same ID [$previousNotificationId], canceling it") + Log.i( + "[Notifications Manager] Found previous notification with same ID [$previousNotificationId], canceling it" + ) cancel(previousNotificationId, CHAT_TAG) } return true @@ -801,10 +930,14 @@ class NotificationsManager(private val context: Context) { fun changeDismissNotificationUponReadForChatRoom(chatRoom: ChatRoom, dismiss: Boolean) { val notificationId = getNotificationIdForChat(chatRoom) if (dismiss) { - Log.i("[Notifications Manager] Allow notification with id [$notificationId] to be dismissed when chat room will be marked as read, used for chat bubble") + Log.i( + "[Notifications Manager] Allow notification with id [$notificationId] to be dismissed when chat room will be marked as read, used for chat bubble" + ) chatBubbleNotifications.add(notificationId) } else { - Log.i("[Notifications Manager] Prevent notification with id [$notificationId] from being dismissed when chat room will be marked as read, used for chat bubble") + Log.i( + "[Notifications Manager] Prevent notification with id [$notificationId] from being dismissed when chat room will be marked as read, used for chat bubble" + ) chatBubbleNotifications.remove(notificationId) } } @@ -839,9 +972,17 @@ class NotificationsManager(private val context: Context) { val senderPerson = if (message.isOutgoing) null else person // Use null for ourselves val msg = if (corePreferences.hideChatMessageContentInNotification) { - NotificationCompat.MessagingStyle.Message(AppUtils.getString(R.string.chat_message_notification_hidden_content), message.time, senderPerson) + NotificationCompat.MessagingStyle.Message( + AppUtils.getString(R.string.chat_message_notification_hidden_content), + message.time, + senderPerson + ) } else { - val tmp = NotificationCompat.MessagingStyle.Message(message.message, message.time, senderPerson) + val tmp = NotificationCompat.MessagingStyle.Message( + message.message, + message.time, + senderPerson + ) if (message.filePath != null) tmp.setData(message.fileMime, message.filePath) tmp } @@ -861,7 +1002,10 @@ class NotificationsManager(private val context: Context) { .build() val largeIcon = if (notifiable.isGroup) coreContext.contactsManager.groupBitmap else lastPersonAvatar - val notificationBuilder = NotificationCompat.Builder(context, context.getString(R.string.notification_channel_chat_id)) + val notificationBuilder = NotificationCompat.Builder( + context, + context.getString(R.string.notification_channel_chat_id) + ) .setSmallIcon(R.drawable.topbar_chat_notification) .setAutoCancel(true) .setLargeIcon(largeIcon) @@ -887,7 +1031,9 @@ class NotificationsManager(private val context: Context) { } if (corePreferences.markAsReadUponChatMessageNotificationDismissal) { - Log.i("[Notifications Manager] Chat room will be marked as read when notification will be dismissed") + Log.i( + "[Notifications Manager] Chat room will be marked as read when notification will be dismissed" + ) notificationBuilder .setDeleteIntent(getMarkMessageAsReadPendingIntent(notifiable)) } diff --git a/app/src/main/java/org/linphone/telecom/NativeCallWrapper.kt b/app/src/main/java/org/linphone/telecom/NativeCallWrapper.kt index c2de142a1..76382bb3a 100644 --- a/app/src/main/java/org/linphone/telecom/NativeCallWrapper.kt +++ b/app/src/main/java/org/linphone/telecom/NativeCallWrapper.kt @@ -50,7 +50,9 @@ class NativeCallWrapper(var callId: String) : Connection() { } override fun onStateChanged(state: Int) { - Log.i("[Connection] Telecom state changed [${intStateToString(state)}] for call with id: $callId") + Log.i( + "[Connection] Telecom state changed [${intStateToString(state)}] for call with id: $callId" + ) super.onStateChanged(state) } @@ -77,12 +79,16 @@ class NativeCallWrapper(var callId: String) : Connection() { val call = getCall() if (call != null) { if (getState() != STATE_ACTIVE && getState() != STATE_DIALING) { - Log.w("[Connection] Call state isn't STATE_ACTIVE or STATE_DIALING, ignoring mute mic & audio route directive from TelecomManager") + Log.w( + "[Connection] Call state isn't STATE_ACTIVE or STATE_DIALING, ignoring mute mic & audio route directive from TelecomManager" + ) return } if (state.isMuted != call.microphoneMuted) { - Log.w("[Connection] Connection audio state asks for changing in mute: ${state.isMuted}, currently is ${call.microphoneMuted}") + Log.w( + "[Connection] Connection audio state asks for changing in mute: ${state.isMuted}, currently is ${call.microphoneMuted}" + ) if (state.isMuted) { Log.w("[Connection] Muting microphone") call.microphoneMuted = true @@ -93,7 +99,10 @@ class NativeCallWrapper(var callId: String) : Connection() { CallAudioState.ROUTE_EARPIECE -> AudioRouteUtils.routeAudioToEarpiece(call, true) CallAudioState.ROUTE_SPEAKER -> AudioRouteUtils.routeAudioToSpeaker(call, true) CallAudioState.ROUTE_BLUETOOTH -> AudioRouteUtils.routeAudioToBluetooth(call, true) - CallAudioState.ROUTE_WIRED_HEADSET -> AudioRouteUtils.routeAudioToHeadset(call, true) + CallAudioState.ROUTE_WIRED_HEADSET -> AudioRouteUtils.routeAudioToHeadset( + call, + true + ) } } else { selfDestroy() diff --git a/app/src/main/java/org/linphone/telecom/TelecomConnectionService.kt b/app/src/main/java/org/linphone/telecom/TelecomConnectionService.kt index 9e779ddbb..fddfc8bb6 100644 --- a/app/src/main/java/org/linphone/telecom/TelecomConnectionService.kt +++ b/app/src/main/java/org/linphone/telecom/TelecomConnectionService.kt @@ -41,19 +41,25 @@ class TelecomConnectionService : ConnectionService() { state: Call.State?, message: String ) { - Log.i("[Telecom Connection Service] call [${call.callLog.callId}] state changed: $state") + Log.i( + "[Telecom Connection Service] call [${call.callLog.callId}] state changed: $state" + ) when (call.state) { Call.State.OutgoingProgress -> { for (connection in TelecomHelper.get().connections) { if (connection.callId.isEmpty()) { - Log.i("[Telecom Connection Service] Updating connection with call ID: ${call.callLog.callId}") + Log.i( + "[Telecom Connection Service] Updating connection with call ID: ${call.callLog.callId}" + ) connection.callId = core.currentCall?.callLog?.callId ?: "" } } } Call.State.Error -> onCallError(call) Call.State.End, Call.State.Released -> onCallEnded(call) - Call.State.Paused, Call.State.Pausing, Call.State.PausedByRemote -> onCallPaused(call) + Call.State.Paused, Call.State.Pausing, Call.State.PausedByRemote -> onCallPaused( + call + ) Call.State.Connected, Call.State.StreamsRunning -> onCallConnected(call) else -> {} } @@ -62,9 +68,13 @@ class TelecomConnectionService : ConnectionService() { override fun onLastCallEnded(core: Core) { val connectionsCount = TelecomHelper.get().connections.size if (connectionsCount > 0) { - Log.w("[Telecom Connection Service] Last call ended, there is $connectionsCount connections still alive") + Log.w( + "[Telecom Connection Service] Last call ended, there is $connectionsCount connections still alive" + ) for (connection in TelecomHelper.get().connections) { - Log.w("[Telecom Connection Service] Destroying zombie connection ${connection.callId}") + Log.w( + "[Telecom Connection Service] Destroying zombie connection ${connection.callId}" + ) connection.setDisconnected(DisconnectCause(DisconnectCause.OTHER)) connection.destroy() } @@ -109,11 +119,15 @@ class TelecomConnectionService : ConnectionService() { if (callId == null) { callId = coreContext.core.currentCall?.callLog?.callId ?: "" } - Log.i("[Telecom Connection Service] Outgoing connection is for call [$callId] with display name [$displayName]") + Log.i( + "[Telecom Connection Service] Outgoing connection is for call [$callId] with display name [$displayName]" + ) // Prevents user dialing back from native dialer app history if (callId.isEmpty() && displayName.isNullOrEmpty()) { - Log.e("[Telecom Connection Service] Looks like a call was made from native dialer history, aborting") + Log.e( + "[Telecom Connection Service] Looks like a call was made from native dialer history, aborting" + ) return Connection.createFailedConnection(DisconnectCause(DisconnectCause.OTHER)) } @@ -121,15 +135,21 @@ class TelecomConnectionService : ConnectionService() { val call = coreContext.core.calls.find { it.callLog.callId == callId } if (call != null) { val callState = call.state - Log.i("[Telecom Connection Service] Found outgoing call from ID [$callId] with state [$callState]") + Log.i( + "[Telecom Connection Service] Found outgoing call from ID [$callId] with state [$callState]" + ) when (callState) { Call.State.OutgoingEarlyMedia, Call.State.OutgoingInit, Call.State.OutgoingProgress, Call.State.OutgoingRinging -> connection.setDialing() Call.State.Paused, Call.State.PausedByRemote, Call.State.Pausing -> connection.setOnHold() - Call.State.End, Call.State.Error, Call.State.Released -> connection.setDisconnected(DisconnectCause(DisconnectCause.ERROR)) + Call.State.End, Call.State.Error, Call.State.Released -> connection.setDisconnected( + DisconnectCause(DisconnectCause.ERROR) + ) else -> connection.setActive() } } else { - Log.w("[Telecom Connection Service] Outgoing call not found for cal ID [$callId], assuming it's state is dialing") + Log.w( + "[Telecom Connection Service] Outgoing call not found for cal ID [$callId], assuming it's state is dialing" + ) connection.setDialing() } @@ -172,21 +192,29 @@ class TelecomConnectionService : ConnectionService() { if (callId == null) { callId = coreContext.core.currentCall?.callLog?.callId ?: "" } - Log.i("[Telecom Connection Service] Incoming connection is for call [$callId] with display name [$displayName]") + Log.i( + "[Telecom Connection Service] Incoming connection is for call [$callId] with display name [$displayName]" + ) val connection = NativeCallWrapper(callId) val call = coreContext.core.calls.find { it.callLog.callId == callId } if (call != null) { val callState = call.state - Log.i("[Telecom Connection Service] Found incoming call from ID [$callId] with state [$callState]") + Log.i( + "[Telecom Connection Service] Found incoming call from ID [$callId] with state [$callState]" + ) when (callState) { Call.State.IncomingEarlyMedia, Call.State.IncomingReceived -> connection.setRinging() Call.State.Paused, Call.State.PausedByRemote, Call.State.Pausing -> connection.setOnHold() - Call.State.End, Call.State.Error, Call.State.Released -> connection.setDisconnected(DisconnectCause(DisconnectCause.ERROR)) + Call.State.End, Call.State.Error, Call.State.Released -> connection.setDisconnected( + DisconnectCause(DisconnectCause.ERROR) + ) else -> connection.setActive() } } else { - Log.w("[Telecom Connection Service] Incoming call not found for cal ID [$callId], assuming it's state is ringing") + Log.w( + "[Telecom Connection Service] Incoming call not found for cal ID [$callId], assuming it's state is ringing" + ) connection.setRinging() } @@ -218,7 +246,9 @@ class TelecomConnectionService : ConnectionService() { } TelecomHelper.get().connections.remove(connection) - Log.i("[Telecom Connection Service] Call [$callId] is in error, destroying connection currently in ${connection.stateAsString()}") + Log.i( + "[Telecom Connection Service] Call [$callId] is in error, destroying connection currently in ${connection.stateAsString()}" + ) connection.setDisconnected(DisconnectCause(DisconnectCause.ERROR)) connection.destroy() } @@ -233,7 +263,9 @@ class TelecomConnectionService : ConnectionService() { TelecomHelper.get().connections.remove(connection) val reason = call.reason - Log.i("[Telecom Connection Service] Call [$callId] ended with reason: $reason, destroying connection currently in ${connection.stateAsString()}") + Log.i( + "[Telecom Connection Service] Call [$callId] ended with reason: $reason, destroying connection currently in ${connection.stateAsString()}" + ) connection.setDisconnected(DisconnectCause(DisconnectCause.LOCAL)) connection.destroy() } @@ -245,7 +277,9 @@ class TelecomConnectionService : ConnectionService() { Log.e("[Telecom Connection Service] Failed to find connection for call id: $callId") return } - Log.i("[Telecom Connection Service] Setting connection as on hold, currently in ${connection.stateAsString()}") + Log.i( + "[Telecom Connection Service] Setting connection as on hold, currently in ${connection.stateAsString()}" + ) connection.setOnHold() } @@ -257,7 +291,9 @@ class TelecomConnectionService : ConnectionService() { return } - Log.i("[Telecom Connection Service] Setting connection as active, currently in ${connection.stateAsString()}") + Log.i( + "[Telecom Connection Service] Setting connection as active, currently in ${connection.stateAsString()}" + ) connection.setActive() } } diff --git a/app/src/main/java/org/linphone/telecom/TelecomHelper.kt b/app/src/main/java/org/linphone/telecom/TelecomHelper.kt index c02a6e8ce..3f55f3a89 100644 --- a/app/src/main/java/org/linphone/telecom/TelecomHelper.kt +++ b/app/src/main/java/org/linphone/telecom/TelecomHelper.kt @@ -197,7 +197,9 @@ class TelecomHelper private constructor(context: Context) { } private fun onIncomingCall(call: Call) { - Log.i("[Telecom Helper] Incoming call received from ${call.remoteAddress.asStringUriOnly()}, using account handle ${account.accountHandle}") + Log.i( + "[Telecom Helper] Incoming call received from ${call.remoteAddress.asStringUriOnly()}, using account handle ${account.accountHandle}" + ) val extras = prepareBundle(call) telecomManager.addNewIncomingCall( @@ -211,7 +213,9 @@ class TelecomHelper private constructor(context: Context) { @SuppressLint("MissingPermission") private fun onOutgoingCall(call: Call) { - Log.i("[Telecom Helper] Outgoing call started to ${call.remoteAddress.asStringUriOnly()}, using account handle ${account.accountHandle}") + Log.i( + "[Telecom Helper] Outgoing call started to ${call.remoteAddress.asStringUriOnly()}, using account handle ${account.accountHandle}" + ) val extras = prepareBundle(call) telecomManager.placeCall( diff --git a/app/src/main/java/org/linphone/utils/AppUtils.kt b/app/src/main/java/org/linphone/utils/AppUtils.kt index 1faec9ebe..aeb738b20 100644 --- a/app/src/main/java/org/linphone/utils/AppUtils.kt +++ b/app/src/main/java/org/linphone/utils/AppUtils.kt @@ -52,7 +52,9 @@ class AppUtils { return try { EmojiCompat.get() } catch (ise: IllegalStateException) { - Log.w("[App Utils] EmojiCompat.get() triggered IllegalStateException [$ise], trying manual init") + Log.w( + "[App Utils] EmojiCompat.get() triggered IllegalStateException [$ise], trying manual init" + ) EmojiCompat.init(coreContext.context) } } @@ -84,7 +86,10 @@ class AppUtils { for (i in split.indices) { if (split[i].isNotEmpty()) { try { - if (emoji?.loadState == EmojiCompat.LOAD_STATE_SUCCEEDED && emoji.hasEmojiGlyph(split[i])) { + if (emoji?.loadState == EmojiCompat.LOAD_STATE_SUCCEEDED && emoji.hasEmojiGlyph( + split[i] + ) + ) { val glyph = emoji.process(split[i]) if (characters > 0) { // Limit initial to 1 emoji only Log.d("[App Utils] We limit initials to one emoji only") @@ -112,7 +117,9 @@ class AppUtils { emoji ?: return false if (emoji.loadState != EmojiCompat.LOAD_STATE_SUCCEEDED) { - Log.w("[App Utils] Can't check emoji presence in text due to EmojiCompat library not loaded yet [${emoji.loadState}]") + Log.w( + "[App Utils] Can't check emoji presence in text due to EmojiCompat library not loaded yet [${emoji.loadState}]" + ) return false } @@ -127,7 +134,9 @@ class AppUtils { } } } catch (npe: NullPointerException) { - Log.e("[App Utils] Can't check emoji presence in text due to NPE in EmojiCompat library, assuming there is none") + Log.e( + "[App Utils] Can't check emoji presence in text due to NPE in EmojiCompat library, assuming there is none" + ) // This can happen in EmojiCompat library, mProcessor can be null (https://issuetracker.google.com/issues/277182750) return false } @@ -164,7 +173,12 @@ class AppUtils { intent.type = "text/plain" try { - activity.startActivity(Intent.createChooser(intent, activity.getString(R.string.share_uploaded_logs_link))) + activity.startActivity( + Intent.createChooser( + intent, + activity.getString(R.string.share_uploaded_logs_link) + ) + ) } catch (ex: ActivityNotFoundException) { Log.e(ex) } @@ -205,7 +219,9 @@ class AppUtils { .build() val request = - AudioFocusRequestCompat.Builder(AudioManagerCompat.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE) + AudioFocusRequestCompat.Builder( + AudioManagerCompat.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE + ) .setAudioAttributes(audioAttrs) .setOnAudioFocusChangeListener { } .build() diff --git a/app/src/main/java/org/linphone/utils/AudioRouteUtils.kt b/app/src/main/java/org/linphone/utils/AudioRouteUtils.kt index 42b367659..537e7c8f3 100644 --- a/app/src/main/java/org/linphone/utils/AudioRouteUtils.kt +++ b/app/src/main/java/org/linphone/utils/AudioRouteUtils.kt @@ -41,10 +41,11 @@ class AudioRouteUtils { null } val conference = coreContext.core.conference - val capability = if (output) + val capability = if (output) { AudioDevice.Capabilities.CapabilityPlay - else + } else { AudioDevice.Capabilities.CapabilityRecord + } val preferredDriver = if (output) { coreContext.core.defaultOutputAudioDevice?.driverName } else { @@ -52,12 +53,18 @@ class AudioRouteUtils { } val extendedAudioDevices = coreContext.core.extendedAudioDevices - Log.i("[Audio Route Helper] Looking for an ${if (output) "output" else "input"} audio device with capability [$capability], driver name [$preferredDriver] and type [$types] in extended audio devices list (size ${extendedAudioDevices.size})") + Log.i( + "[Audio Route Helper] Looking for an ${if (output) "output" else "input"} audio device with capability [$capability], driver name [$preferredDriver] and type [$types] in extended audio devices list (size ${extendedAudioDevices.size})" + ) val foundAudioDevice = extendedAudioDevices.find { - it.driverName == preferredDriver && types.contains(it.type) && it.hasCapability(capability) + it.driverName == preferredDriver && types.contains(it.type) && it.hasCapability( + capability + ) } val audioDevice = if (foundAudioDevice == null) { - Log.w("[Audio Route Helper] Failed to find an audio device with capability [$capability], driver name [$preferredDriver] and type [$types]") + Log.w( + "[Audio Route Helper] Failed to find an audio device with capability [$capability], driver name [$preferredDriver] and type [$types]" + ) extendedAudioDevices.find { types.contains(it.type) && it.hasCapability(capability) } @@ -66,25 +73,44 @@ class AudioRouteUtils { } if (audioDevice == null) { - Log.e("[Audio Route Helper] Couldn't find audio device with capability [$capability] and type [$types]") + Log.e( + "[Audio Route Helper] Couldn't find audio device with capability [$capability] and type [$types]" + ) for (device in extendedAudioDevices) { // TODO: switch to debug? - Log.i("[Audio Route Helper] Extended audio device: [${device.deviceName} (${device.driverName}) ${device.type} / ${device.capabilities}]") + Log.i( + "[Audio Route Helper] Extended audio device: [${device.deviceName} (${device.driverName}) ${device.type} / ${device.capabilities}]" + ) } return } if (conference != null && conference.isIn) { - Log.i("[Audio Route Helper] Found [${audioDevice.type}] ${if (output) "playback" else "recorder"} audio device [${audioDevice.deviceName} (${audioDevice.driverName})], routing conference audio to it") - if (output) conference.outputAudioDevice = audioDevice - else conference.inputAudioDevice = audioDevice + Log.i( + "[Audio Route Helper] Found [${audioDevice.type}] ${if (output) "playback" else "recorder"} audio device [${audioDevice.deviceName} (${audioDevice.driverName})], routing conference audio to it" + ) + if (output) { + conference.outputAudioDevice = audioDevice + } else { + conference.inputAudioDevice = audioDevice + } } else if (currentCall != null) { - Log.i("[Audio Route Helper] Found [${audioDevice.type}] ${if (output) "playback" else "recorder"} audio device [${audioDevice.deviceName} (${audioDevice.driverName})], routing call audio to it") - if (output) currentCall.outputAudioDevice = audioDevice - else currentCall.inputAudioDevice = audioDevice + Log.i( + "[Audio Route Helper] Found [${audioDevice.type}] ${if (output) "playback" else "recorder"} audio device [${audioDevice.deviceName} (${audioDevice.driverName})], routing call audio to it" + ) + if (output) { + currentCall.outputAudioDevice = audioDevice + } else { + currentCall.inputAudioDevice = audioDevice + } } else { - Log.i("[Audio Route Helper] Found [${audioDevice.type}] ${if (output) "playback" else "recorder"} audio device [${audioDevice.deviceName} (${audioDevice.driverName})], changing core default audio device") - if (output) coreContext.core.outputAudioDevice = audioDevice - else coreContext.core.inputAudioDevice = audioDevice + Log.i( + "[Audio Route Helper] Found [${audioDevice.type}] ${if (output) "playback" else "recorder"} audio device [${audioDevice.deviceName} (${audioDevice.driverName})], changing core default audio device" + ) + if (output) { + coreContext.core.outputAudioDevice = audioDevice + } else { + coreContext.core.inputAudioDevice = audioDevice + } } } @@ -92,18 +118,28 @@ class AudioRouteUtils { when (types.first()) { AudioDevice.Type.Bluetooth -> { if (isBluetoothAudioRecorderAvailable()) { - Log.i("[Audio Route Helper] Bluetooth device is able to record audio, also change input audio device") + Log.i( + "[Audio Route Helper] Bluetooth device is able to record audio, also change input audio device" + ) applyAudioRouteChange(call, arrayListOf(AudioDevice.Type.Bluetooth), false) } } AudioDevice.Type.Headset, AudioDevice.Type.Headphones -> { if (isHeadsetAudioRecorderAvailable()) { - Log.i("[Audio Route Helper] Headphones/Headset device is able to record audio, also change input audio device") - applyAudioRouteChange(call, (arrayListOf(AudioDevice.Type.Headphones, AudioDevice.Type.Headset)), false) + Log.i( + "[Audio Route Helper] Headphones/Headset device is able to record audio, also change input audio device" + ) + applyAudioRouteChange( + call, + (arrayListOf(AudioDevice.Type.Headphones, AudioDevice.Type.Headset)), + false + ) } } AudioDevice.Type.Earpiece, AudioDevice.Type.Speaker -> { - Log.i("[Audio Route Helper] Audio route requested to Earpiece or Speaker, setting input to Microphone") + Log.i( + "[Audio Route Helper] Audio route requested to Earpiece or Speaker, setting input to Microphone" + ) applyAudioRouteChange(call, (arrayListOf(AudioDevice.Type.Microphone)), false) } else -> { @@ -119,8 +155,12 @@ class AudioRouteUtils { ) { val currentCall = call ?: coreContext.core.currentCall ?: coreContext.core.calls.firstOrNull() if (currentCall != null && !skipTelecom && TelecomHelper.exists()) { - Log.i("[Audio Route Helper] Call provided & Telecom Helper exists, trying to dispatch audio route change through Telecom API") - val connection = TelecomHelper.get().findConnectionForCallId(currentCall.callLog.callId.orEmpty()) + Log.i( + "[Audio Route Helper] Call provided & Telecom Helper exists, trying to dispatch audio route change through Telecom API" + ) + val connection = TelecomHelper.get().findConnectionForCallId( + currentCall.callLog.callId.orEmpty() + ) if (connection != null) { val route = when (types.first()) { AudioDevice.Type.Earpiece -> CallAudioState.ROUTE_EARPIECE @@ -129,11 +169,15 @@ class AudioRouteUtils { AudioDevice.Type.Bluetooth, AudioDevice.Type.BluetoothA2DP -> CallAudioState.ROUTE_BLUETOOTH else -> CallAudioState.ROUTE_WIRED_OR_EARPIECE } - Log.i("[Audio Route Helper] Telecom Helper & matching connection found, dispatching audio route change through it") + Log.i( + "[Audio Route Helper] Telecom Helper & matching connection found, dispatching audio route change through it" + ) // We will be called here again by NativeCallWrapper.onCallAudioStateChanged() // but this time with skipTelecom = true if (!Compatibility.changeAudioRouteForTelecomManager(connection, route)) { - Log.w("[Audio Route Helper] Connection is already using this route internally, make the change!") + Log.w( + "[Audio Route Helper] Connection is already using this route internally, make the change!" + ) applyAudioRouteChange(currentCall, types) changeCaptureDeviceToMatchAudioRoute(currentCall, types) } @@ -161,7 +205,11 @@ class AudioRouteUtils { } fun routeAudioToHeadset(call: Call? = null, skipTelecom: Boolean = false) { - routeAudioTo(call, arrayListOf(AudioDevice.Type.Headphones, AudioDevice.Type.Headset), skipTelecom) + routeAudioTo( + call, + arrayListOf(AudioDevice.Type.Headphones, AudioDevice.Type.Headset), + skipTelecom + ) } fun isSpeakerAudioRouteCurrentlyUsed(call: Call? = null): Boolean { @@ -173,15 +221,18 @@ class AudioRouteUtils { } val conference = coreContext.core.conference - val audioDevice = if (conference != null && conference.isIn) + val audioDevice = if (conference != null && conference.isIn) { conference.outputAudioDevice - else if (currentCall != null) + } else if (currentCall != null) { currentCall.outputAudioDevice - else + } else { coreContext.core.outputAudioDevice + } if (audioDevice == null) return false - Log.i("[Audio Route Helper] Playback audio device currently in use is [${audioDevice.deviceName} (${audioDevice.driverName}) ${audioDevice.type}]") + Log.i( + "[Audio Route Helper] Playback audio device currently in use is [${audioDevice.deviceName} (${audioDevice.driverName}) ${audioDevice.type}]" + ) return audioDevice.type == AudioDevice.Type.Speaker } @@ -193,13 +244,16 @@ class AudioRouteUtils { val currentCall = call ?: coreContext.core.currentCall ?: coreContext.core.calls[0] val conference = coreContext.core.conference - val audioDevice = if (conference != null && conference.isIn) + val audioDevice = if (conference != null && conference.isIn) { conference.outputAudioDevice - else + } else { currentCall.outputAudioDevice + } if (audioDevice == null) return false - Log.i("[Audio Route Helper] Playback audio device currently in use is [${audioDevice.deviceName} (${audioDevice.driverName}) ${audioDevice.type}]") + Log.i( + "[Audio Route Helper] Playback audio device currently in use is [${audioDevice.deviceName} (${audioDevice.driverName}) ${audioDevice.type}]" + ) return audioDevice.type == AudioDevice.Type.Bluetooth } @@ -208,7 +262,9 @@ class AudioRouteUtils { if (audioDevice.type == AudioDevice.Type.Bluetooth && audioDevice.hasCapability(AudioDevice.Capabilities.CapabilityPlay) ) { - Log.i("[Audio Route Helper] Found bluetooth audio device [${audioDevice.deviceName} (${audioDevice.driverName})]") + Log.i( + "[Audio Route Helper] Found bluetooth audio device [${audioDevice.deviceName} (${audioDevice.driverName})]" + ) return true } } @@ -220,7 +276,9 @@ class AudioRouteUtils { if (audioDevice.type == AudioDevice.Type.Bluetooth && audioDevice.hasCapability(AudioDevice.Capabilities.CapabilityRecord) ) { - Log.i("[Audio Route Helper] Found bluetooth audio recorder [${audioDevice.deviceName} (${audioDevice.driverName})]") + Log.i( + "[Audio Route Helper] Found bluetooth audio recorder [${audioDevice.deviceName} (${audioDevice.driverName})]" + ) return true } } @@ -232,7 +290,9 @@ class AudioRouteUtils { if ((audioDevice.type == AudioDevice.Type.Headset || audioDevice.type == AudioDevice.Type.Headphones) && audioDevice.hasCapability(AudioDevice.Capabilities.CapabilityPlay) ) { - Log.i("[Audio Route Helper] Found headset/headphones audio device [${audioDevice.deviceName} (${audioDevice.driverName})]") + Log.i( + "[Audio Route Helper] Found headset/headphones audio device [${audioDevice.deviceName} (${audioDevice.driverName})]" + ) return true } } @@ -244,7 +304,9 @@ class AudioRouteUtils { if ((audioDevice.type == AudioDevice.Type.Headset || audioDevice.type == AudioDevice.Type.Headphones) && audioDevice.hasCapability(AudioDevice.Capabilities.CapabilityRecord) ) { - Log.i("[Audio Route Helper] Found headset/headphones audio recorder [${audioDevice.deviceName} (${audioDevice.driverName})]") + Log.i( + "[Audio Route Helper] Found headset/headphones audio recorder [${audioDevice.deviceName} (${audioDevice.driverName})]" + ) return true } } @@ -277,7 +339,9 @@ class AudioRouteUtils { } } } - Log.i("[Audio Route Helper] Found headset/headphones/hearingAid sound card [$headphonesCard], bluetooth sound card [$bluetoothCard], speaker sound card [$speakerCard] and earpiece sound card [$earpieceCard]") + Log.i( + "[Audio Route Helper] Found headset/headphones/hearingAid sound card [$headphonesCard], bluetooth sound card [$bluetoothCard], speaker sound card [$speakerCard] and earpiece sound card [$earpieceCard]" + ) return headphonesCard ?: bluetoothCard ?: speakerCard ?: earpieceCard } @@ -303,7 +367,9 @@ class AudioRouteUtils { } } } - Log.i("[Audio Route Helper] Found headset/headphones/hearingAid [${headsetAudioDevice?.id}], bluetooth [${bluetoothAudioDevice?.id}] and builtin microphone [${builtinMicrophone?.id}]") + Log.i( + "[Audio Route Helper] Found headset/headphones/hearingAid [${headsetAudioDevice?.id}], bluetooth [${bluetoothAudioDevice?.id}] and builtin microphone [${builtinMicrophone?.id}]" + ) return headsetAudioDevice ?: bluetoothAudioDevice ?: builtinMicrophone } } diff --git a/app/src/main/java/org/linphone/utils/DataBindingUtils.kt b/app/src/main/java/org/linphone/utils/DataBindingUtils.kt index 5d943e499..7fffb7b22 100644 --- a/app/src/main/java/org/linphone/utils/DataBindingUtils.kt +++ b/app/src/main/java/org/linphone/utils/DataBindingUtils.kt @@ -75,7 +75,9 @@ fun View.hideKeyboard() { fun View.addKeyboardInsetListener(lambda: (visible: Boolean) -> Unit) { doOnLayout { - var isKeyboardVisible = ViewCompat.getRootWindowInsets(this)?.isVisible(WindowInsetsCompat.Type.ime()) == true + var isKeyboardVisible = ViewCompat.getRootWindowInsets(this)?.isVisible( + WindowInsetsCompat.Type.ime() + ) == true lambda(isKeyboardVisible) @@ -354,7 +356,9 @@ fun loadImageWithCoil(imageView: ImageView, path: String?) { diskCachePolicy(CachePolicy.DISABLED) listener( onError = { _, result -> - Log.e("[Data Binding] [VFS] [Coil] Error loading [$path]: ${result.throwable}") + Log.e( + "[Data Binding] [VFS] [Coil] Error loading [$path]: ${result.throwable}" + ) } ) } @@ -394,7 +398,9 @@ private suspend fun loadContactPictureWithCoil( imageView.load(R.drawable.icon_single_contact_avatar) } } else if (contact.showGroupChatAvatar) { - imageView.load(AppCompatResources.getDrawable(context, R.drawable.icon_multiple_contacts_avatar)) + imageView.load( + AppCompatResources.getDrawable(context, R.drawable.icon_multiple_contacts_avatar) + ) } else { val displayName = contact.contact.value?.name ?: contact.displayName.value.orEmpty() val source = contact.contact.value?.getPictureUri(useThumbnail) @@ -402,7 +408,9 @@ private suspend fun loadContactPictureWithCoil( val base64 = if (ImageUtils.isBase64(sourceStr)) { Log.d("[Coil] Picture URI is base64 encoded") ImageUtils.getBase64ImageFromString(sourceStr) - } else null + } else { + null + } imageView.load(base64 ?: source) { transformations(CircleCropTransformation()) @@ -451,8 +459,11 @@ fun loadBigContactPictureWithCoil(imageView: ImageView, contact: ContactDataInte coroutineScope.launch { withContext(Dispatchers.Main) { loadContactPictureWithCoil( - imageView, contact, false, - R.dimen.contact_avatar_big_size, R.dimen.contact_avatar_text_big_size + imageView, + contact, + false, + R.dimen.contact_avatar_big_size, + R.dimen.contact_avatar_text_big_size ) } } @@ -464,9 +475,13 @@ fun loadVoipContactPictureWithCoilAlt(imageView: ImageView, contact: ContactData coroutineScope.launch { withContext(Dispatchers.Main) { loadContactPictureWithCoil( - imageView, contact, false, - R.dimen.voip_contact_avatar_max_size, R.dimen.voip_contact_avatar_text_size, - R.attr.voipParticipantBackgroundColor, R.color.white_color + imageView, + contact, + false, + R.dimen.voip_contact_avatar_max_size, + R.dimen.voip_contact_avatar_text_size, + R.attr.voipParticipantBackgroundColor, + R.color.white_color ) } } @@ -478,9 +493,13 @@ fun loadVoipContactPictureWithCoil(imageView: ImageView, contact: ContactDataInt coroutineScope.launch { withContext(Dispatchers.Main) { loadContactPictureWithCoil( - imageView, contact, false, - R.dimen.voip_contact_avatar_max_size, R.dimen.voip_contact_avatar_text_size, - R.attr.voipBackgroundColor, R.color.white_color + imageView, + contact, + false, + R.dimen.voip_contact_avatar_max_size, + R.dimen.voip_contact_avatar_text_size, + R.attr.voipBackgroundColor, + R.color.white_color ) } } @@ -492,9 +511,13 @@ fun loadSelfAvatarWithCoil(imageView: ImageView, contact: ContactDataInterface?) coroutineScope.launch { withContext(Dispatchers.Main) { loadContactPictureWithCoil( - imageView, contact, false, - R.dimen.voip_contact_avatar_max_size, R.dimen.voip_contact_avatar_text_size, - R.attr.voipBackgroundColor, R.color.white_color, + imageView, + contact, + false, + R.dimen.voip_contact_avatar_max_size, + R.dimen.voip_contact_avatar_text_size, + R.attr.voipBackgroundColor, + R.color.white_color, corePreferences.defaultAccountAvatarPath ) } @@ -539,7 +562,9 @@ fun addPhoneNumberEditTextValidation(editText: EditText, enabled: Boolean) { when { s?.matches(Regex("\\d+")) == false -> editText.error = - editText.context.getString(R.string.assistant_error_phone_number_invalid_characters) + editText.context.getString( + R.string.assistant_error_phone_number_invalid_characters + ) } } @@ -580,7 +605,9 @@ fun addUsernameEditTextValidation(editText: EditText, enabled: Boolean) { when { s?.matches(Regex(usernameRegexp)) == false -> editText.error = - editText.context.getString(R.string.assistant_error_username_invalid_characters) + editText.context.getString( + R.string.assistant_error_username_invalid_characters + ) (s?.length ?: 0) > usernameMaxLength -> { editText.error = editText.context.getString(R.string.assistant_error_username_too_long) @@ -638,7 +665,9 @@ fun addPasswordConfirmationEditTextValidation(password: EditText, passwordConfir override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { if (passwordConfirmation.text == null || s == null || passwordConfirmation.text.toString() != s.toString()) { passwordConfirmation.error = - passwordConfirmation.context.getString(R.string.assistant_error_passwords_dont_match) + passwordConfirmation.context.getString( + R.string.assistant_error_passwords_dont_match + ) } else { passwordConfirmation.error = null // To clear other edit text field error } @@ -653,7 +682,9 @@ fun addPasswordConfirmationEditTextValidation(password: EditText, passwordConfir override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { if (password.text == null || s == null || password.text.toString() != s.toString()) { passwordConfirmation.error = - passwordConfirmation.context.getString(R.string.assistant_error_passwords_dont_match) + passwordConfirmation.context.getString( + R.string.assistant_error_passwords_dont_match + ) } } }) @@ -811,8 +842,12 @@ fun ImageView.setPresenceIcon(presence: ConsolidatedPresence) { setImageResource(icon) val contentDescription = when (presence) { - ConsolidatedPresence.Online -> AppUtils.getString(R.string.content_description_presence_online) - ConsolidatedPresence.DoNotDisturb -> AppUtils.getString(R.string.content_description_presence_do_not_disturb) + ConsolidatedPresence.Online -> AppUtils.getString( + R.string.content_description_presence_online + ) + ConsolidatedPresence.DoNotDisturb -> AppUtils.getString( + R.string.content_description_presence_do_not_disturb + ) else -> AppUtils.getString(R.string.content_description_presence_offline) } setContentDescription(contentDescription) diff --git a/app/src/main/java/org/linphone/utils/DialogUtils.kt b/app/src/main/java/org/linphone/utils/DialogUtils.kt index 8c7fe46cf..f88a958c1 100644 --- a/app/src/main/java/org/linphone/utils/DialogUtils.kt +++ b/app/src/main/java/org/linphone/utils/DialogUtils.kt @@ -39,11 +39,18 @@ class DialogUtils { val dialog = Dialog(context) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - val binding: DialogBinding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.dialog, null, false) + val binding: DialogBinding = DataBindingUtil.inflate( + LayoutInflater.from(context), + R.layout.dialog, + null, + false + ) binding.viewModel = viewModel dialog.setContentView(binding.root) - val d: Drawable = ColorDrawable(ContextCompat.getColor(dialog.context, R.color.dark_grey_color)) + val d: Drawable = ColorDrawable( + ContextCompat.getColor(dialog.context, R.color.dark_grey_color) + ) d.alpha = 200 dialog.window ?.setLayout( @@ -58,11 +65,18 @@ class DialogUtils { val dialog = Dialog(context, R.style.AppTheme) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) - val binding: VoipDialogBinding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.voip_dialog, null, false) + val binding: VoipDialogBinding = DataBindingUtil.inflate( + LayoutInflater.from(context), + R.layout.voip_dialog, + null, + false + ) binding.viewModel = viewModel dialog.setContentView(binding.root) - val d: Drawable = ColorDrawable(ContextCompat.getColor(dialog.context, R.color.voip_dark_gray)) + val d: Drawable = ColorDrawable( + ContextCompat.getColor(dialog.context, R.color.voip_dark_gray) + ) d.alpha = 166 dialog.window ?.setLayout( diff --git a/app/src/main/java/org/linphone/utils/FileUtils.kt b/app/src/main/java/org/linphone/utils/FileUtils.kt index 1b7a93444..f15260a19 100644 --- a/app/src/main/java/org/linphone/utils/FileUtils.kt +++ b/app/src/main/java/org/linphone/utils/FileUtils.kt @@ -100,7 +100,9 @@ class FileUtils { val dir = File(corePreferences.vfsCachePath) if (dir.exists()) { for (file in dir.listFiles().orEmpty()) { - Log.w("[File Utils] [VFS] Found forgotten plain file [${file.path}], deleting it") + Log.w( + "[File Utils] [VFS] Found forgotten plain file [${file.path}], deleting it" + ) deleteFile(file.path) } } @@ -119,7 +121,11 @@ class FileUtils { } val returnPath: File = path ?: coreContext.context.filesDir - if (path == null) Log.w("[File Utils] Couldn't get external storage path, using internal") + if (path == null) { + Log.w( + "[File Utils] Couldn't get external storage path, using internal" + ) + } return returnPath } @@ -230,7 +236,9 @@ class FileUtils { filePath.startsWith("file://") ) { val result = getFilePath(coreContext.context, uriToParse) - Log.i("[File Utils] Path was using a content or file scheme, real path is: $result") + Log.i( + "[File Utils] Path was using a content or file scheme, real path is: $result" + ) if (result == null) { Log.e("[File Utils] Failed to get access to file $uriToParse") } @@ -304,10 +312,14 @@ class FileUtils { if (displayName != null) { name = displayName } else { - Log.e("[File Utils] Failed to get the display name for URI $uri, returned value is null") + Log.e( + "[File Utils] Failed to get the display name for URI $uri, returned value is null" + ) } } catch (e: CursorIndexOutOfBoundsException) { - Log.e("[File Utils] Failed to get the display name for URI $uri, exception is $e") + Log.e( + "[File Utils] Failed to get the display name for URI $uri, exception is $e" + ) } } else { Log.e("[File Utils] Couldn't get DISPLAY_NAME column index for URI: $uri") @@ -463,7 +475,9 @@ class FileUtils { } else { "file/$extension" } - Log.w("[File Viewer] Can't get MIME type from extension: $extension, will use $type") + Log.w( + "[File Viewer] Can't get MIME type from extension: $extension, will use $type" + ) } intent.setDataAndType(contentUri, type) diff --git a/app/src/main/java/org/linphone/utils/ImageUtils.kt b/app/src/main/java/org/linphone/utils/ImageUtils.kt index 3e2a8a432..44f0c650b 100644 --- a/app/src/main/java/org/linphone/utils/ImageUtils.kt +++ b/app/src/main/java/org/linphone/utils/ImageUtils.kt @@ -48,7 +48,10 @@ class ImageUtils { if (fromPictureUri != null) { bm = try { // We make a copy to ensure Bitmap will be Software and not Hardware, required for shortcuts - Compatibility.getBitmapFromUri(context, fromPictureUri).copy(Bitmap.Config.ARGB_8888, true) + Compatibility.getBitmapFromUri(context, fromPictureUri).copy( + Bitmap.Config.ARGB_8888, + true + ) } catch (fnfe: FileNotFoundException) { return null } catch (e: Exception) { @@ -70,7 +73,13 @@ class ImageUtils { val matrix = Matrix() matrix.postRotate(angle) val rotatedBitmap = Bitmap.createBitmap( - source, 0, 0, source.width, source.height, matrix, true + source, + 0, + 0, + source.width, + source.height, + matrix, + true ) source.recycle() return rotatedBitmap diff --git a/app/src/main/java/org/linphone/utils/LinphoneUtils.kt b/app/src/main/java/org/linphone/utils/LinphoneUtils.kt index 6c86477a0..e386dc3c0 100644 --- a/app/src/main/java/org/linphone/utils/LinphoneUtils.kt +++ b/app/src/main/java/org/linphone/utils/LinphoneUtils.kt @@ -80,10 +80,11 @@ class LinphoneUtils { fun getConferenceAddress(call: Call): Address? { val remoteContact = call.remoteContact val conferenceAddress = if (call.dir == Call.Dir.Incoming) { - if (remoteContact != null) + if (remoteContact != null) { coreContext.core.interpretUrl(remoteContact, false) - else + } else { null + } } else { call.remoteAddress } @@ -92,7 +93,9 @@ class LinphoneUtils { fun getConferenceSubject(conference: Conference): String? { return if (conference.subject.isNullOrEmpty()) { - val conferenceInfo = coreContext.core.findConferenceInformationFromUri(conference.conferenceAddress) + val conferenceInfo = coreContext.core.findConferenceInformationFromUri( + conference.conferenceAddress + ) if (conferenceInfo != null) { conferenceInfo.subject } else { @@ -139,8 +142,17 @@ class LinphoneUtils { val participants = arrayOf(participant) - return core.searchChatRoom(params, defaultAccount?.params?.identityAddress, null, participants) - ?: core.createChatRoom(params, defaultAccount?.params?.identityAddress, participants) + return core.searchChatRoom( + params, + defaultAccount?.params?.identityAddress, + null, + participants + ) + ?: core.createChatRoom( + params, + defaultAccount?.params?.identityAddress, + participants + ) } fun getConferenceInvitationsChatRoomParams(): ChatRoomParams { @@ -189,10 +201,11 @@ class LinphoneUtils { RECORDING_DATE_PATTERN, Locale.getDefault() ) - val fileName = if (subject.isNullOrEmpty()) + val fileName = if (subject.isNullOrEmpty()) { "conference_${dateFormat.format(Date())}.mkv" - else + } else { "${subject}_${dateFormat.format(Date())}.mkv" + } return FileUtils.getFileStoragePath(fileName).absolutePath } diff --git a/app/src/main/java/org/linphone/utils/PowerManagerUtils.kt b/app/src/main/java/org/linphone/utils/PowerManagerUtils.kt index cf3f03610..f54c7d44a 100644 --- a/app/src/main/java/org/linphone/utils/PowerManagerUtils.kt +++ b/app/src/main/java/org/linphone/utils/PowerManagerUtils.kt @@ -117,7 +117,8 @@ class PowerManagerUtils { Intent() .setComponent( ComponentName( - "com.asus.mobilemanager", "com.asus.mobilemanager.MainActivity" + "com.asus.mobilemanager", + "com.asus.mobilemanager.MainActivity" ) ), Intent() diff --git a/app/src/main/java/org/linphone/utils/RecyclerViewHeaderDecoration.kt b/app/src/main/java/org/linphone/utils/RecyclerViewHeaderDecoration.kt index 031dead06..4b598a4e7 100644 --- a/app/src/main/java/org/linphone/utils/RecyclerViewHeaderDecoration.kt +++ b/app/src/main/java/org/linphone/utils/RecyclerViewHeaderDecoration.kt @@ -50,13 +50,24 @@ class RecyclerViewHeaderDecoration(private val context: Context, private val ada private fun measureHeaderView(view: View, parent: ViewGroup) { if (view.layoutParams == null) { - view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) + view.layoutParams = ViewGroup.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT + ) } val widthSpec = View.MeasureSpec.makeMeasureSpec(parent.width, View.MeasureSpec.EXACTLY) val heightSpec = View.MeasureSpec.makeMeasureSpec(parent.height, View.MeasureSpec.EXACTLY) - val childWidth = ViewGroup.getChildMeasureSpec(widthSpec, parent.paddingLeft + parent.paddingRight, view.layoutParams.width) - val childHeight = ViewGroup.getChildMeasureSpec(heightSpec, parent.paddingTop + parent.paddingBottom, view.layoutParams.height) + val childWidth = ViewGroup.getChildMeasureSpec( + widthSpec, + parent.paddingLeft + parent.paddingRight, + view.layoutParams.width + ) + val childHeight = ViewGroup.getChildMeasureSpec( + heightSpec, + parent.paddingTop + parent.paddingBottom, + view.layoutParams.height + ) view.measure(childWidth, childHeight) view.layout(0, 0, view.measuredWidth, view.measuredHeight) @@ -68,7 +79,10 @@ class RecyclerViewHeaderDecoration(private val context: Context, private val ada val position = parent.getChildAdapterPosition(child) if (position != RecyclerView.NO_POSITION && adapter.displayHeaderForPosition(position)) { canvas.save() - val headerView: View = headers.get(position) ?: adapter.getHeaderViewForPosition(context, position) + val headerView: View = headers.get(position) ?: adapter.getHeaderViewForPosition( + context, + position + ) canvas.translate(0f, child.y - headerView.height) headerView.draw(canvas) canvas.restore() diff --git a/app/src/main/java/org/linphone/utils/RecyclerViewSwipeUtils.kt b/app/src/main/java/org/linphone/utils/RecyclerViewSwipeUtils.kt index 52808677a..764e7dbc0 100644 --- a/app/src/main/java/org/linphone/utils/RecyclerViewSwipeUtils.kt +++ b/app/src/main/java/org/linphone/utils/RecyclerViewSwipeUtils.kt @@ -53,6 +53,7 @@ class RecyclerViewSwipeConfiguration { val iconMargin = 16f val actionTextSizeUnit = TypedValue.COMPLEX_UNIT_SP + // At least CROSSCALL Action-X3 device doesn't have SANS_SERIF typeface... val actionTextFont: Typeface? = Typeface.SANS_SERIF val actionTextSize = 14f @@ -120,10 +121,12 @@ private class RecyclerViewSwipeUtilsCallback( ) @Suppress("DEPRECATION") - if (configuration.leftToRightAction.iconTint != 0) icon.setColorFilter( - configuration.leftToRightAction.iconTint, - PorterDuff.Mode.SRC_IN - ) + if (configuration.leftToRightAction.iconTint != 0) { + icon.setColorFilter( + configuration.leftToRightAction.iconTint, + PorterDuff.Mode.SRC_IN + ) + } icon.draw(canvas) } } @@ -208,10 +211,12 @@ private class RecyclerViewSwipeUtilsCallback( ) @Suppress("DEPRECATION") - if (configuration.rightToLeftAction.iconTint != 0) icon.setColorFilter( - configuration.rightToLeftAction.iconTint, - PorterDuff.Mode.SRC_IN - ) + if (configuration.rightToLeftAction.iconTint != 0) { + icon.setColorFilter( + configuration.rightToLeftAction.iconTint, + PorterDuff.Mode.SRC_IN + ) + } icon.draw(canvas) } } diff --git a/app/src/main/java/org/linphone/utils/ShortcutsHelper.kt b/app/src/main/java/org/linphone/utils/ShortcutsHelper.kt index 28e0e73c0..2926c78d8 100644 --- a/app/src/main/java/org/linphone/utils/ShortcutsHelper.kt +++ b/app/src/main/java/org/linphone/utils/ShortcutsHelper.kt @@ -81,9 +81,14 @@ class ShortcutsHelper(val context: Context) { coreContext.contactsManager.findContactByAddress(address) if (contact != null && contact.refKey != null) { - val shortcut: ShortcutInfoCompat? = createContactShortcut(context, contact) + val shortcut: ShortcutInfoCompat? = createContactShortcut( + context, + contact + ) if (shortcut != null) { - Log.i("[Shortcut Helper] Creating launcher shortcut for ${shortcut.shortLabel}") + Log.i( + "[Shortcut Helper] Creating launcher shortcut for ${shortcut.shortLabel}" + ) shortcuts.add(shortcut) count += 1 } @@ -117,7 +122,9 @@ class ShortcutsHelper(val context: Context) { .setIntent(intent) .build() } catch (e: Exception) { - Log.e("[Shortcuts Helper] createContactShortcut for contact [${contact.name}] exception: $e") + Log.e( + "[Shortcuts Helper] createContactShortcut for contact [${contact.name}] exception: $e" + ) } return null diff --git a/app/src/main/java/org/linphone/utils/TimestampUtils.kt b/app/src/main/java/org/linphone/utils/TimestampUtils.kt index 384c805fd..baf0e7262 100644 --- a/app/src/main/java/org/linphone/utils/TimestampUtils.kt +++ b/app/src/main/java/org/linphone/utils/TimestampUtils.kt @@ -72,7 +72,9 @@ class TimestampUtils { } fun timeToString(hour: Int, minutes: Int): String { - val use24hFormat = android.text.format.DateFormat.is24HourFormat(LinphoneApplication.coreContext.context) + val use24hFormat = android.text.format.DateFormat.is24HourFormat( + LinphoneApplication.coreContext.context + ) val calendar = Calendar.getInstance() calendar.set(Calendar.HOUR_OF_DAY, hour) calendar.set(Calendar.MINUTE, minutes) @@ -85,7 +87,9 @@ class TimestampUtils { } fun timeToString(time: Long, timestampInSecs: Boolean = true): String { - val use24hFormat = android.text.format.DateFormat.is24HourFormat(LinphoneApplication.coreContext.context) + val use24hFormat = android.text.format.DateFormat.is24HourFormat( + LinphoneApplication.coreContext.context + ) val calendar = Calendar.getInstance() calendar.timeInMillis = if (timestampInSecs) time * 1000 else time @@ -129,14 +133,20 @@ class TimestampUtils { if (onlyDate) { DateFormat.getDateInstance(if (shortDate) DateFormat.SHORT else DateFormat.FULL) } else { - DateFormat.getDateTimeInstance(if (shortDate) DateFormat.SHORT else DateFormat.MEDIUM, DateFormat.SHORT) + DateFormat.getDateTimeInstance( + if (shortDate) DateFormat.SHORT else DateFormat.MEDIUM, + DateFormat.SHORT + ) } } as SimpleDateFormat if (hideYear || isSameYear(timestamp, timestampInSecs)) { // Remove the year part of the format dateFormat.applyPattern( - dateFormat.toPattern().replace("/?y+/?|,?\\s?y+\\s?".toRegex(), if (shortDate) "" else " ") + dateFormat.toPattern().replace( + "/?y+/?|,?\\s?y+\\s?".toRegex(), + if (shortDate) "" else " " + ) ) } diff --git a/app/src/main/java/org/linphone/views/VoiceRecordProgressBar.kt b/app/src/main/java/org/linphone/views/VoiceRecordProgressBar.kt index 900e45e8f..619717f28 100644 --- a/app/src/main/java/org/linphone/views/VoiceRecordProgressBar.kt +++ b/app/src/main/java/org/linphone/views/VoiceRecordProgressBar.kt @@ -51,7 +51,11 @@ class VoiceRecordProgressBar : View { constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) - constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) { + constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super( + context, + attrs, + defStyle + ) { max = 100 progress = 0 secondaryProgress = 0 @@ -63,7 +67,8 @@ class VoiceRecordProgressBar : View { context.theme.obtainStyledAttributes( attrs, R.styleable.VoiceRecordProgressBar, - 0, 0 + 0, + 0 ).apply { try { @@ -71,8 +76,12 @@ class VoiceRecordProgressBar : View { if (drawable != null) { setProgressDrawable(drawable) } - setPrimaryLeftMargin(getDimension(R.styleable.VoiceRecordProgressBar_primaryLeftMargin, 0f)) - setPrimaryRightMargin(getDimension(R.styleable.VoiceRecordProgressBar_primaryRightMargin, 0f)) + setPrimaryLeftMargin( + getDimension(R.styleable.VoiceRecordProgressBar_primaryLeftMargin, 0f) + ) + setPrimaryRightMargin( + getDimension(R.styleable.VoiceRecordProgressBar_primaryRightMargin, 0f) + ) setMax(getInteger(R.styleable.VoiceRecordProgressBar_max, 100)) } finally { recycle() @@ -111,8 +120,10 @@ class VoiceRecordProgressBar : View { val scrollX: Int = scrollX + paddingLeft val scrollY: Int = scrollY + paddingTop invalidate( - dirty.left + scrollX, dirty.top + scrollY, - dirty.right + scrollX, dirty.bottom + scrollY + dirty.left + scrollX, + dirty.top + scrollY, + dirty.right + scrollX, + dirty.bottom + scrollY ) } else { super.invalidateDrawable(drawable) @@ -209,7 +220,9 @@ class VoiceRecordProgressBar : View { val drawable = progressDrawable if (drawable != null) { if (drawable is LayerDrawable) { - val secondaryProgressDrawable = drawable.findDrawableByLayerId(android.R.id.secondaryProgress) + val secondaryProgressDrawable = drawable.findDrawableByLayerId( + android.R.id.secondaryProgress + ) secondaryProgressDrawable?.setTint(color) } } @@ -307,7 +320,12 @@ class VoiceRecordProgressBar : View { if (i != 1) { canvas.translate(primaryLeftMargin, 0f) drawableLayer.draw(canvas) - drawableLayer.setBounds(0, 0, width - primaryRightMargin.toInt() - primaryLeftMargin.toInt(), height) + drawableLayer.setBounds( + 0, + 0, + width - primaryRightMargin.toInt() - primaryLeftMargin.toInt(), + height + ) canvas.translate(-primaryLeftMargin, 0f) } else { drawableLayer.draw(canvas) diff --git a/build.gradle b/build.gradle index 309d5ec91..6363a223b 100644 --- a/build.gradle +++ b/build.gradle @@ -11,11 +11,10 @@ buildscript { } // for com.github.chrisbanes:PhotoView } dependencies { - classpath 'com.android.tools.build:gradle:7.4.2' + classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.10' - classpath "org.jlleitschuh.gradle:ktlint-gradle:10.1.0" - classpath 'com.google.firebase:firebase-crashlytics-gradle:2.9.4' + classpath 'com.google.firebase:firebase-crashlytics-gradle:2.9.5' } } diff --git a/docker-files/bc-dev-android-33 b/docker-files/bc-dev-android-33 index 2a15406b3..6ea291fc4 100644 --- a/docker-files/bc-dev-android-33 +++ b/docker-files/bc-dev-android-33 @@ -1,4 +1,4 @@ -FROM debian:stretch +FROM debian:bullseye MAINTAINER Sylvain BERFINI @@ -13,43 +13,36 @@ ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' LC_ALL='en_US.UTF-8' ENV SHELL=/bin/bash # Define environment -ENV ANDROID_SDK 25.2.5 ENV ANDROID_HOME /opt/android-sdk-linux -ENV ANDROID_NDK_HOME /opt/android-sdk-linux/ndk - -# Backports required for JDK 11 -RUN echo "deb http://deb.debian.org/debian stretch-backports main" > /etc/apt/sources.list.d/backports.list # Install common general tools RUN apt-get update && \ - apt-get install -y curl nano sudo unzip vim wget rsync ssh git openjdk-8-jdk-headless && \ - apt-get -t stretch-backports install -y openjdk-11-jdk-headless && \ + apt-get install -y curl nano sudo unzip vim wget rsync ssh git openjdk-17-jdk-headless && \ apt-get clean -# Get the Android tools -RUN wget https://dl.google.com/android/repository/tools_r$ANDROID_SDK-linux.zip && \ - unzip tools_r$ANDROID_SDK-linux.zip -d $ANDROID_HOME && \ - rm -f tools_r$ANDROID_SDK-linux.zip - -# Get latest Android command line tools, otherwise won't work with JDK 11 +# Get latest Android command line tools, otherwise won't work with JDK 17 RUN mkdir -p $ANDROID_HOME/cmdline-tools/latest -RUN wget https://dl.google.com/android/repository/commandlinetools-linux-7583922_latest.zip && \ - unzip commandlinetools-linux-7583922_latest.zip && \ +RUN wget https://dl.google.com/android/repository/commandlinetools-linux-9477386_latest.zip && \ + unzip commandlinetools-linux-9477386_latest.zip && \ cp -R ./cmdline-tools/* $ANDROID_HOME/cmdline-tools/latest/ && \ rm -rf ./cmdline-tools && \ - rm -rf commandlinetools-linux-7583922_latest.zip + rm -rf commandlinetools-linux-9477386_latest.zip # Update path to include all Android SDK tools -ENV PATH $ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin:$ANDROID_HOME/platform-tools:ANDROID_NDK_HOME:$PATH - -# Test -RUN $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager --list --verbose --sdk_root=$ANDROID_HOME +ENV PATH $ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin:$ANDROID_HOME/platform-tools:$PATH # Get the Android SDK -RUN echo "y" | $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager "platforms;android-33" "build-tools;33.0.0" "extras;android;m2repository" "extras;google;m2repository" "platform-tools" "tools" "ndk;21.3.6528147" --sdk_root=$ANDROID_HOME +RUN echo "y" | $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager "platform-tools" "tools" "platforms;android-33" # Accept Android SDK licenses -RUN yes | $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager --licenses --sdk_root=$ANDROID_HOME +RUN yes | $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager --licenses + +# Give write rights +RUN chmod -R ugo+rwx $ANDROID_HOME + +# Consider all git repositories as safe +RUN git --version +RUN git config --global --add safe.directory '*' # Configure user bc RUN useradd -ms /bin/bash bc && \ diff --git a/gradle.properties b/gradle.properties index b9dfb6efa..1b8b6e1e6 100644 --- a/gradle.properties +++ b/gradle.properties @@ -18,3 +18,6 @@ android.useAndroidX=true # Kotlin code style for this project: "official" or "obsolete": kotlin.code.style=official LinphoneSdkBuildDir= +android.defaults.buildfeatures.buildconfig=true +android.nonTransitiveRClass=false +android.nonFinalResIds=false diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 91932d9ac..9b985ba37 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ #Thu Feb 03 11:43:32 CET 2022 distributionBase=GRADLE_USER_HOME -distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip distributionPath=wrapper/dists zipStorePath=wrapper/dists zipStoreBase=GRADLE_USER_HOME diff --git a/settings.gradle b/settings.gradle index 44f60d740..c60bbf4f7 100644 --- a/settings.gradle +++ b/settings.gradle @@ -20,6 +20,8 @@ dependencyResolutionManagement { includeGroup "org.linphone" } } + + // For "org.jlleitschuh.gradle:ktlint-gradle" mavenCentral() } }