Big annoying commit: execute command ./gradlew ktlintFormat - Fix "chain-wrapping"

This commit is contained in:
Benoit Marty 2021-10-01 13:22:01 +02:00 committed by Benoit Marty
parent 2ca3c68611
commit a1caccbcc8
146 changed files with 593 additions and 600 deletions

View file

@ -67,9 +67,9 @@ class DeactivateAccountTest : InstrumentedTest {
val throwable = commonTestHelper.logAccountWithError(session.myUserId, TestConstants.PASSWORD)
// Test the error
assertTrue(throwable is Failure.ServerError
&& throwable.error.code == MatrixError.M_USER_DEACTIVATED
&& throwable.error.message == "This account has been deactivated")
assertTrue(throwable is Failure.ServerError &&
throwable.error.code == MatrixError.M_USER_DEACTIVATED &&
throwable.error.message == "This account has been deactivated")
// Try to create an account with the deactivate account user id, it will fail (M_USER_IN_USE)
val hs = commonTestHelper.createHomeServerConfig()
@ -95,8 +95,8 @@ class DeactivateAccountTest : InstrumentedTest {
// Test the error
accountCreationError.let {
assertTrue(it is Failure.ServerError
&& it.error.code == MatrixError.M_USER_IN_USE)
assertTrue(it is Failure.ServerError &&
it.error.code == MatrixError.M_USER_IN_USE)
}
// No need to close the session, it has been deactivated

View file

@ -50,8 +50,8 @@ class PreShareKeysTest : InstrumentedTest {
aliceSession.cryptoService().discardOutboundSession(e2eRoomID)
val preShareCount = bobSession.cryptoService().getGossipingEvents().count {
it.senderId == aliceSession.myUserId
&& it.getClearType() == EventType.ROOM_KEY
it.senderId == aliceSession.myUserId &&
it.getClearType() == EventType.ROOM_KEY
}
assertEquals("Bob should not have receive any key from alice at this point", 0, preShareCount)
@ -65,16 +65,16 @@ class PreShareKeysTest : InstrumentedTest {
mTestHelper.waitWithLatch { latch ->
mTestHelper.retryPeriodicallyWithLatch(latch) {
val newGossipCount = bobSession.cryptoService().getGossipingEvents().count {
it.senderId == aliceSession.myUserId
&& it.getClearType() == EventType.ROOM_KEY
it.senderId == aliceSession.myUserId &&
it.getClearType() == EventType.ROOM_KEY
}
newGossipCount > preShareCount
}
}
val latest = bobSession.cryptoService().getGossipingEvents().lastOrNull {
it.senderId == aliceSession.myUserId
&& it.getClearType() == EventType.ROOM_KEY
it.senderId == aliceSession.myUserId &&
it.getClearType() == EventType.ROOM_KEY
}
val content = latest?.getClearContent().toModel<RoomKeyContent>()

View file

@ -91,8 +91,8 @@ internal class StateObserver(private val keysBackup: KeysBackupService,
stateList.add(newState)
// Check that state transition is valid
if (stateList.size >= 2
&& !allowedStateTransitions.contains(stateList[stateList.size - 2] to newState)) {
if (stateList.size >= 2 &&
!allowedStateTransitions.contains(stateList[stateList.size - 2] to newState)) {
// Forbidden transition detected
lastTransitionError = "Forbidden transition detected from " + stateList[stateList.size - 2] + " to " + newState
}

View file

@ -111,8 +111,8 @@ class TimelineBackToPreviousLastForwardTest : InstrumentedTest {
}
// Ok, we have the 10 last messages from Alice.
snapshot.size == 10
&& snapshot.all { it.root.content.toModel<MessageContent>()?.body?.startsWith(messageRoot).orFalse() }
snapshot.size == 10 &&
snapshot.all { it.root.content.toModel<MessageContent>()?.body?.startsWith(messageRoot).orFalse() }
}
bobTimeline.addListener(eventsListener)
@ -160,10 +160,10 @@ class TimelineBackToPreviousLastForwardTest : InstrumentedTest {
}
// Bob can see the first event of the room (so Back pagination has worked)
snapshot.lastOrNull()?.root?.getClearType() == EventType.STATE_ROOM_CREATE
snapshot.lastOrNull()?.root?.getClearType() == EventType.STATE_ROOM_CREATE &&
// 8 for room creation item, and 30 for the forward pagination
&& snapshot.size == 38
&& snapshot.checkSendOrder(messageRoot, 30, 0)
snapshot.size == 38 &&
snapshot.checkSendOrder(messageRoot, 30, 0)
}
bobTimeline.addListener(eventsListener)

View file

@ -86,8 +86,8 @@ class TimelineForwardPaginationTest : InstrumentedTest {
}
// Ok, we have the 10 last messages of the initial sync
snapshot.size == 10
&& snapshot.all { it.root.content.toModel<MessageContent>()?.body?.startsWith(message).orFalse() }
snapshot.size == 10 &&
snapshot.all { it.root.content.toModel<MessageContent>()?.body?.startsWith(message).orFalse() }
}
// Open the timeline at last sent message
@ -110,8 +110,8 @@ class TimelineForwardPaginationTest : InstrumentedTest {
}
// The event is not in db, so it is fetch alone
snapshot.size == 1
&& snapshot.all { it.root.content.toModel<MessageContent>()?.body?.startsWith("Message from Alice").orFalse() }
snapshot.size == 1 &&
snapshot.all { it.root.content.toModel<MessageContent>()?.body?.startsWith("Message from Alice").orFalse() }
}
aliceTimeline.addListener(aliceEventsListener)
@ -137,9 +137,9 @@ class TimelineForwardPaginationTest : InstrumentedTest {
}
// Alice can see the first event of the room (so Back pagination has worked)
snapshot.lastOrNull()?.root?.getClearType() == EventType.STATE_ROOM_CREATE
snapshot.lastOrNull()?.root?.getClearType() == EventType.STATE_ROOM_CREATE &&
// 6 for room creation item (backward pagination), 1 for the context, and 50 for the forward pagination
&& snapshot.size == 57 // 6 + 1 + 50
snapshot.size == 57 // 6 + 1 + 50
}
aliceTimeline.addListener(aliceEventsListener)
@ -166,8 +166,8 @@ class TimelineForwardPaginationTest : InstrumentedTest {
Timber.w(" event ${it.root.content}")
}
// 6 for room creation item (backward pagination),and numberOfMessagesToSend (all the message of the room)
snapshot.size == 6 + numberOfMessagesToSend
&& snapshot.checkSendOrder(message, numberOfMessagesToSend, 0)
snapshot.size == 6 + numberOfMessagesToSend &&
snapshot.checkSendOrder(message, numberOfMessagesToSend, 0)
}
aliceTimeline.addListener(aliceEventsListener)

View file

@ -107,8 +107,8 @@ class TimelinePreviousLastForwardTest : InstrumentedTest {
}
// Ok, we have the 10 last messages from Alice. This will be our future previous lastForward chunk
snapshot.size == 10
&& snapshot.all { it.root.content.toModel<MessageContent>()?.body?.startsWith(firstMessage).orFalse() }
snapshot.size == 10 &&
snapshot.all { it.root.content.toModel<MessageContent>()?.body?.startsWith(firstMessage).orFalse() }
}
bobTimeline.addListener(eventsListener)
@ -141,8 +141,8 @@ class TimelinePreviousLastForwardTest : InstrumentedTest {
}
// Ok, we have the 10 last messages from Alice. This will be our future previous lastForward chunk
snapshot.size == 10
&& snapshot.all { it.root.content.toModel<MessageContent>()?.body?.startsWith(secondMessage).orFalse() }
snapshot.size == 10 &&
snapshot.all { it.root.content.toModel<MessageContent>()?.body?.startsWith(secondMessage).orFalse() }
}
bobTimeline.addListener(eventsListener)
@ -216,11 +216,11 @@ class TimelinePreviousLastForwardTest : InstrumentedTest {
}
// Bob can see the first event of the room (so Back pagination has worked)
snapshot.lastOrNull()?.root?.getClearType() == EventType.STATE_ROOM_CREATE
snapshot.lastOrNull()?.root?.getClearType() == EventType.STATE_ROOM_CREATE &&
// 8 for room creation item 60 message from Alice
&& snapshot.size == 68 // 8 + 60
&& snapshot.checkSendOrder(secondMessage, 30, 0)
&& snapshot.checkSendOrder(firstMessage, 30, 30)
snapshot.size == 68 && // 8 + 60
snapshot.checkSendOrder(secondMessage, 30, 0) &&
snapshot.checkSendOrder(firstMessage, 30, 30)
}
bobTimeline.addListener(eventsListener)

View file

@ -90,8 +90,8 @@ internal class CurlLoggingInterceptor @Inject constructor()
curlCmd += ((if (compressed) " --compressed " else " ") + "'" + request.url.toString()
// Replace localhost for emulator by localhost for shell
.replace("://10.0.2.2:8080/".toRegex(), "://127.0.0.1:8080/")
+ "'")
.replace("://10.0.2.2:8080/".toRegex(), "://127.0.0.1:8080/") +
"'")
// Add Json formatting
curlCmd += " | python -m json.tool"

View file

@ -128,10 +128,10 @@ object MatrixPatterns {
* @return true if the string is a valid event id.
*/
fun isEventId(str: String?): Boolean {
return str != null
&& (str matches PATTERN_CONTAIN_MATRIX_EVENT_IDENTIFIER
|| str matches PATTERN_CONTAIN_MATRIX_EVENT_IDENTIFIER_V3
|| str matches PATTERN_CONTAIN_MATRIX_EVENT_IDENTIFIER_V4)
return str != null &&
(str matches PATTERN_CONTAIN_MATRIX_EVENT_IDENTIFIER ||
str matches PATTERN_CONTAIN_MATRIX_EVENT_IDENTIFIER_V3 ||
str matches PATTERN_CONTAIN_MATRIX_EVENT_IDENTIFIER_V4)
}
/**

View file

@ -19,24 +19,23 @@ package org.matrix.android.sdk.api.failure
import org.matrix.android.sdk.api.auth.registration.RegistrationFlowResponse
import org.matrix.android.sdk.api.extensions.tryOrNull
import org.matrix.android.sdk.internal.di.MoshiProvider
import java.io.IOException
import javax.net.ssl.HttpsURLConnection
fun Throwable.is401() =
this is Failure.ServerError
&& httpCode == HttpsURLConnection.HTTP_UNAUTHORIZED /* 401 */
&& error.code == MatrixError.M_UNAUTHORIZED
this is Failure.ServerError &&
httpCode == HttpsURLConnection.HTTP_UNAUTHORIZED && /* 401 */
error.code == MatrixError.M_UNAUTHORIZED
fun Throwable.isTokenError() =
this is Failure.ServerError
&& (error.code == MatrixError.M_UNKNOWN_TOKEN
|| error.code == MatrixError.M_MISSING_TOKEN
|| error.code == MatrixError.ORG_MATRIX_EXPIRED_ACCOUNT)
this is Failure.ServerError &&
(error.code == MatrixError.M_UNKNOWN_TOKEN ||
error.code == MatrixError.M_MISSING_TOKEN ||
error.code == MatrixError.ORG_MATRIX_EXPIRED_ACCOUNT)
fun Throwable.shouldBeRetried(): Boolean {
return this is Failure.NetworkConnection
|| this is IOException
|| (this is Failure.ServerError && error.code == MatrixError.M_LIMIT_EXCEEDED)
return this is Failure.NetworkConnection ||
this is IOException ||
(this is Failure.ServerError && error.code == MatrixError.M_LIMIT_EXCEEDED)
}
/**
@ -52,31 +51,31 @@ fun Throwable.getRetryDelay(defaultValue: Long): Long {
}
fun Throwable.isInvalidPassword(): Boolean {
return this is Failure.ServerError
&& error.code == MatrixError.M_FORBIDDEN
&& error.message == "Invalid password"
return this is Failure.ServerError &&
error.code == MatrixError.M_FORBIDDEN &&
error.message == "Invalid password"
}
fun Throwable.isInvalidUIAAuth(): Boolean {
return this is Failure.ServerError
&& error.code == MatrixError.M_FORBIDDEN
&& error.flows != null
return this is Failure.ServerError &&
error.code == MatrixError.M_FORBIDDEN &&
error.flows != null
}
/**
* Try to convert to a RegistrationFlowResponse. Return null in the cases it's not possible
*/
fun Throwable.toRegistrationFlowResponse(): RegistrationFlowResponse? {
return if (this is Failure.OtherServerError
&& httpCode == HttpsURLConnection.HTTP_UNAUTHORIZED /* 401 */) {
return if (this is Failure.OtherServerError &&
httpCode == HttpsURLConnection.HTTP_UNAUTHORIZED /* 401 */) {
tryOrNull {
MoshiProvider.providesMoshi()
.adapter(RegistrationFlowResponse::class.java)
.fromJson(errorBody)
}
} else if (this is Failure.ServerError
&& httpCode == HttpsURLConnection.HTTP_UNAUTHORIZED /* 401 */
&& error.code == MatrixError.M_FORBIDDEN) {
} else if (this is Failure.ServerError &&
httpCode == HttpsURLConnection.HTTP_UNAUTHORIZED && /* 401 */
error.code == MatrixError.M_FORBIDDEN) {
// This happens when the submission for this stage was bad (like bad password)
if (error.session != null && error.flows != null) {
RegistrationFlowResponse(
@ -94,9 +93,9 @@ fun Throwable.toRegistrationFlowResponse(): RegistrationFlowResponse? {
}
fun Throwable.isRegistrationAvailabilityError(): Boolean {
return this is Failure.ServerError
&& httpCode == HttpsURLConnection.HTTP_BAD_REQUEST /* 400 */
&& (error.code == MatrixError.M_USER_IN_USE
|| error.code == MatrixError.M_INVALID_USERNAME
|| error.code == MatrixError.M_EXCLUSIVE)
return this is Failure.ServerError &&
httpCode == HttpsURLConnection.HTTP_BAD_REQUEST && /* 400 */
(error.code == MatrixError.M_USER_IN_USE ||
error.code == MatrixError.M_INVALID_USERNAME ||
error.code == MatrixError.M_EXCLUSIVE)
}

View file

@ -24,8 +24,8 @@ data class MXCrossSigningInfo(
val crossSigningKeys: List<CryptoCrossSigningKey>
) {
fun isTrusted(): Boolean = masterKey()?.trustLevel?.isVerified() == true
&& selfSigningKey()?.trustLevel?.isVerified() == true
fun isTrusted(): Boolean = masterKey()?.trustLevel?.isVerified() == true &&
selfSigningKey()?.trustLevel?.isVerified() == true
fun masterKey(): CryptoCrossSigningKey? = crossSigningKeys
.firstOrNull { it.usages?.contains(KeyUsage.MASTER.value) == true }

View file

@ -48,8 +48,8 @@ data class PendingVerificationRequest(
* SAS is supported if I support it and the other party support it
*/
fun isSasSupported(): Boolean {
return requestInfo?.methods?.contains(VERIFICATION_METHOD_SAS).orFalse()
&& readyInfo?.methods?.contains(VERIFICATION_METHOD_SAS).orFalse()
return requestInfo?.methods?.contains(VERIFICATION_METHOD_SAS).orFalse() &&
readyInfo?.methods?.contains(VERIFICATION_METHOD_SAS).orFalse()
}
/**
@ -57,11 +57,11 @@ data class PendingVerificationRequest(
*/
fun otherCanShowQrCode(): Boolean {
return if (isIncoming) {
requestInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SHOW).orFalse()
&& readyInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SCAN).orFalse()
requestInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SHOW).orFalse() &&
readyInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SCAN).orFalse()
} else {
requestInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SCAN).orFalse()
&& readyInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SHOW).orFalse()
requestInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SCAN).orFalse() &&
readyInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SHOW).orFalse()
}
}
@ -70,11 +70,11 @@ data class PendingVerificationRequest(
*/
fun otherCanScanQrCode(): Boolean {
return if (isIncoming) {
requestInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SCAN).orFalse()
&& readyInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SHOW).orFalse()
requestInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SCAN).orFalse() &&
readyInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SHOW).orFalse()
} else {
requestInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SHOW).orFalse()
&& readyInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SCAN).orFalse()
requestInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SHOW).orFalse() &&
readyInfo?.methods?.contains(VERIFICATION_METHOD_QR_CODE_SCAN).orFalse()
}
}
}

View file

@ -238,8 +238,8 @@ data class Event(
}
fun Event.isTextMessage(): Boolean {
return getClearType() == EventType.MESSAGE
&& when (getClearContent()?.get(MessageContent.MSG_TYPE_JSON_KEY)) {
return getClearType() == EventType.MESSAGE &&
when (getClearContent()?.get(MessageContent.MSG_TYPE_JSON_KEY)) {
MessageType.MSGTYPE_TEXT,
MessageType.MSGTYPE_EMOTE,
MessageType.MSGTYPE_NOTICE -> true
@ -248,40 +248,40 @@ fun Event.isTextMessage(): Boolean {
}
fun Event.isImageMessage(): Boolean {
return getClearType() == EventType.MESSAGE
&& when (getClearContent()?.get(MessageContent.MSG_TYPE_JSON_KEY)) {
return getClearType() == EventType.MESSAGE &&
when (getClearContent()?.get(MessageContent.MSG_TYPE_JSON_KEY)) {
MessageType.MSGTYPE_IMAGE -> true
else -> false
}
}
fun Event.isVideoMessage(): Boolean {
return getClearType() == EventType.MESSAGE
&& when (getClearContent()?.get(MessageContent.MSG_TYPE_JSON_KEY)) {
return getClearType() == EventType.MESSAGE &&
when (getClearContent()?.get(MessageContent.MSG_TYPE_JSON_KEY)) {
MessageType.MSGTYPE_VIDEO -> true
else -> false
}
}
fun Event.isAudioMessage(): Boolean {
return getClearType() == EventType.MESSAGE
&& when (getClearContent()?.get(MessageContent.MSG_TYPE_JSON_KEY)) {
return getClearType() == EventType.MESSAGE &&
when (getClearContent()?.get(MessageContent.MSG_TYPE_JSON_KEY)) {
MessageType.MSGTYPE_AUDIO -> true
else -> false
}
}
fun Event.isFileMessage(): Boolean {
return getClearType() == EventType.MESSAGE
&& when (getClearContent()?.get(MessageContent.MSG_TYPE_JSON_KEY)) {
return getClearType() == EventType.MESSAGE &&
when (getClearContent()?.get(MessageContent.MSG_TYPE_JSON_KEY)) {
MessageType.MSGTYPE_FILE -> true
else -> false
}
}
fun Event.isAttachmentMessage(): Boolean {
return getClearType() == EventType.MESSAGE
&& when (getClearContent()?.get(MessageContent.MSG_TYPE_JSON_KEY)) {
return getClearType() == EventType.MESSAGE &&
when (getClearContent()?.get(MessageContent.MSG_TYPE_JSON_KEY)) {
MessageType.MSGTYPE_IMAGE,
MessageType.MSGTYPE_AUDIO,
MessageType.MSGTYPE_VIDEO,

View file

@ -106,13 +106,13 @@ object EventType {
internal const val DUMMY = "m.dummy"
fun isCallEvent(type: String): Boolean {
return type == CALL_INVITE
|| type == CALL_CANDIDATES
|| type == CALL_ANSWER
|| type == CALL_HANGUP
|| type == CALL_SELECT_ANSWER
|| type == CALL_NEGOTIATE
|| type == CALL_REJECT
|| type == CALL_REPLACES
return type == CALL_INVITE ||
type == CALL_CANDIDATES ||
type == CALL_ANSWER ||
type == CALL_HANGUP ||
type == CALL_SELECT_ANSWER ||
type == CALL_NEGOTIATE ||
type == CALL_REJECT ||
type == CALL_REPLACES
}
}

View file

@ -50,11 +50,11 @@ object MatrixLinkify {
if (startPos == 0 || text[startPos - 1] != '/') {
val endPos = match.range.last + 1
var url = text.substring(match.range)
if (MatrixPatterns.isUserId(url)
|| MatrixPatterns.isRoomAlias(url)
|| MatrixPatterns.isRoomId(url)
|| MatrixPatterns.isGroupId(url)
|| MatrixPatterns.isEventId(url)) {
if (MatrixPatterns.isUserId(url) ||
MatrixPatterns.isRoomAlias(url) ||
MatrixPatterns.isRoomId(url) ||
MatrixPatterns.isGroupId(url) ||
MatrixPatterns.isEventId(url)) {
url = PermalinkService.MATRIX_TO_URL_BASE + url
}
val span = MatrixPermalinkSpan(url, callback)

View file

@ -172,8 +172,8 @@ internal class DefaultAuthenticationService @Inject constructor(
return try {
getWellknownLoginFlowInternal(homeServerConnectionConfig)
} catch (failure: Throwable) {
if (failure is Failure.OtherServerError
&& failure.httpCode == HttpsURLConnection.HTTP_NOT_FOUND /* 404 */) {
if (failure is Failure.OtherServerError &&
failure.httpCode == HttpsURLConnection.HTTP_NOT_FOUND /* 404 */) {
// 404, no well-known data, try direct access to the API
// First check the homeserver version
return runCatching {
@ -190,8 +190,8 @@ internal class DefaultAuthenticationService @Inject constructor(
it
},
{
if (it is Failure.OtherServerError
&& it.httpCode == HttpsURLConnection.HTTP_NOT_FOUND /* 404 */) {
if (it is Failure.OtherServerError &&
it.httpCode == HttpsURLConnection.HTTP_NOT_FOUND /* 404 */) {
// It's maybe a Web client url?
getWebClientDomainLoginFlowInternal(homeServerConnectionConfig)
} else {
@ -225,8 +225,8 @@ internal class DefaultAuthenticationService @Inject constructor(
it
},
{
if (it is Failure.OtherServerError
&& it.httpCode == HttpsURLConnection.HTTP_NOT_FOUND /* 404 */) {
if (it is Failure.OtherServerError &&
it.httpCode == HttpsURLConnection.HTTP_NOT_FOUND /* 404 */) {
// Try with config.json
getWebClientLoginFlowInternal(homeServerConnectionConfig)
} else {

View file

@ -54,8 +54,8 @@ internal class DefaultIsValidClientServerApiTask @Inject constructor(
// We get a response, so the API is valid
true
} catch (failure: Throwable) {
if (failure is Failure.OtherServerError
&& failure.httpCode == HttpsURLConnection.HTTP_NOT_FOUND /* 404 */) {
if (failure is Failure.OtherServerError &&
failure.httpCode == HttpsURLConnection.HTTP_NOT_FOUND /* 404 */) {
// Probably not valid
false
} else {

View file

@ -63,9 +63,9 @@ internal fun Versions.isSupportedBySdk(): Boolean {
* Return true if the SDK supports this homeserver version for login and registration
*/
internal fun Versions.isLoginAndRegistrationSupportedBySdk(): Boolean {
return !doesServerRequireIdentityServerParam()
&& doesServerAcceptIdentityAccessToken()
&& doesServerSeparatesAddAndBind()
return !doesServerRequireIdentityServerParam() &&
doesServerAcceptIdentityAccessToken() &&
doesServerSeparatesAddAndBind()
}
/**
@ -74,8 +74,8 @@ internal fun Versions.isLoginAndRegistrationSupportedBySdk(): Boolean {
* @return true if the server support the lazy loading of room members
*/
private fun Versions.supportLazyLoadMembers(): Boolean {
return getMaxVersion() >= HomeServerVersion.r0_5_0
|| unstableFeatures?.get(FEATURE_LAZY_LOAD_MEMBERS) == true
return getMaxVersion() >= HomeServerVersion.r0_5_0 ||
unstableFeatures?.get(FEATURE_LAZY_LOAD_MEMBERS) == true
}
/**
@ -92,13 +92,13 @@ private fun Versions.doesServerRequireIdentityServerParam(): Boolean {
* Some homeservers may trigger errors if they are not prepared for the new parameter.
*/
private fun Versions.doesServerAcceptIdentityAccessToken(): Boolean {
return getMaxVersion() >= HomeServerVersion.r0_6_0
|| unstableFeatures?.get(FEATURE_ID_ACCESS_TOKEN) ?: false
return getMaxVersion() >= HomeServerVersion.r0_6_0 ||
unstableFeatures?.get(FEATURE_ID_ACCESS_TOKEN) ?: false
}
private fun Versions.doesServerSeparatesAddAndBind(): Boolean {
return getMaxVersion() >= HomeServerVersion.r0_6_0
|| unstableFeatures?.get(FEATURE_SEPARATE_ADD_AND_BIND) ?: false
return getMaxVersion() >= HomeServerVersion.r0_6_0 ||
unstableFeatures?.get(FEATURE_SEPARATE_ADD_AND_BIND) ?: false
}
private fun Versions.getMaxVersion(): HomeServerVersion {

View file

@ -868,8 +868,8 @@ internal class DefaultCryptoService @Inject constructor(
}
private fun getRoomUserIds(roomId: String): List<String> {
val encryptForInvitedMembers = isEncryptionEnabledForInvitedUser()
&& shouldEncryptForInvitedMembers(roomId)
val encryptForInvitedMembers = isEncryptionEnabledForInvitedUser() &&
shouldEncryptForInvitedMembers(roomId)
return cryptoSessionInfoProvider.getRoomUserIds(roomId, encryptForInvitedMembers)
}
@ -887,9 +887,9 @@ internal class DefaultCryptoService @Inject constructor(
if (membership == Membership.JOIN) {
// make sure we are tracking the deviceList for this user.
deviceListManager.startTrackingDeviceList(listOf(userId))
} else if (membership == Membership.INVITE
&& shouldEncryptForInvitedMembers(roomId)
&& isEncryptionEnabledForInvitedUser()) {
} else if (membership == Membership.INVITE &&
shouldEncryptForInvitedMembers(roomId) &&
isEncryptionEnabledForInvitedUser()) {
// track the deviceList for this invited user.
// Caution: there's a big edge case here in that federated servers do not
// know what other servers are in the room at the time they've been invited.

View file

@ -475,8 +475,8 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM
}
if (!isVerified) {
Timber.e("## CRYPTO | validateDeviceKeys() : Unable to verify signature on device " + userId + ":"
+ deviceKeys.deviceId + " with error " + errorMessage)
Timber.e("## CRYPTO | validateDeviceKeys() : Unable to verify signature on device " + userId + ":" +
deviceKeys.deviceId + " with error " + errorMessage)
return false
}
@ -486,9 +486,9 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM
// best off sticking with the original keys.
//
// Should we warn the user about it somehow?
Timber.e("## CRYPTO | validateDeviceKeys() : WARNING:Ed25519 key for device " + userId + ":"
+ deviceKeys.deviceId + " has changed : "
+ previouslyStoredDeviceKeys.fingerprint() + " -> " + signKey)
Timber.e("## CRYPTO | validateDeviceKeys() : WARNING:Ed25519 key for device " + userId + ":" +
deviceKeys.deviceId + " has changed : " +
previouslyStoredDeviceKeys.fingerprint() + " -> " + signKey)
Timber.e("## CRYPTO | validateDeviceKeys() : $previouslyStoredDeviceKeys -> $deviceKeys")
Timber.e("## CRYPTO | validateDeviceKeys() : ${previouslyStoredDeviceKeys.keys} -> ${deviceKeys.keys}")

View file

@ -107,8 +107,8 @@ internal class EventDecryptor @Inject constructor(
} catch (mxCryptoError: MXCryptoError) {
Timber.v("## CRYPTO | internalDecryptEvent : Failed to decrypt ${event.eventId} reason: $mxCryptoError")
if (algorithm == MXCRYPTO_ALGORITHM_OLM) {
if (mxCryptoError is MXCryptoError.Base
&& mxCryptoError.errorType == MXCryptoError.ErrorType.BAD_ENCRYPTED_MESSAGE) {
if (mxCryptoError is MXCryptoError.Base &&
mxCryptoError.errorType == MXCryptoError.ErrorType.BAD_ENCRYPTED_MESSAGE) {
// need to find sending device
cryptoCoroutineScope.launch(coroutineDispatchers.crypto) {
val olmContent = event.content.toModel<OlmEventContent>()

View file

@ -112,9 +112,8 @@ internal class OutgoingGossipingRequestManager @Inject constructor(
* @param andResend true to resend the key request
*/
private fun cancelRoomKeyRequest(requestBody: RoomKeyRequestBody, andResend: Boolean) {
val req = cryptoStore.getOutgoingRoomKeyRequest(requestBody)
?: // no request was made for this key
return Unit.also {
val req = cryptoStore.getOutgoingRoomKeyRequest(requestBody) // no request was made for this key
?: return Unit.also {
Timber.v("## CRYPTO - GOSSIP cancelRoomKeyRequest() Unknown request $requestBody")
}

View file

@ -90,8 +90,8 @@ internal class EnsureOlmSessionsForDevicesAction @Inject constructor(
oneTimeKey = key
}
if (oneTimeKey == null) {
Timber.w("## CRYPTO | ensureOlmSessionsForDevices() : No one-time keys " + oneTimeKeyAlgorithm
+ " for device " + userId + " : " + deviceId)
Timber.w("## CRYPTO | ensureOlmSessionsForDevices() : No one-time keys " + oneTimeKeyAlgorithm +
" for device " + userId + " : " + deviceId)
continue
}
// Update the result for this device in results
@ -126,15 +126,15 @@ internal class EnsureOlmSessionsForDevicesAction @Inject constructor(
sessionId = olmDevice.createOutboundSession(deviceInfo.identityKey()!!, oneTimeKey.value)
if (!sessionId.isNullOrEmpty()) {
Timber.v("## CRYPTO | verifyKeyAndStartSession() : Started new sessionid " + sessionId
+ " for device " + deviceInfo + "(theirOneTimeKey: " + oneTimeKey.value + ")")
Timber.v("## CRYPTO | verifyKeyAndStartSession() : Started new sessionid " + sessionId +
" for device " + deviceInfo + "(theirOneTimeKey: " + oneTimeKey.value + ")")
} else {
// Possibly a bad key
Timber.e("## CRYPTO | verifyKeyAndStartSession() : Error starting session with device $userId:$deviceId")
}
} else {
Timber.e("## CRYPTO | verifyKeyAndStartSession() : Unable to verify signature on one-time key for device " + userId
+ ":" + deviceId + " Error " + errorMessage)
Timber.e("## CRYPTO | verifyKeyAndStartSession() : Unable to verify signature on one-time key for device " + userId +
":" + deviceId + " Error " + errorMessage)
}
}

View file

@ -38,9 +38,9 @@ internal class EnsureOlmSessionsForUsersAction @Inject constructor(private val o
devices.filter {
// Don't bother setting up session to ourself
it.identityKey() != olmDevice.deviceCurve25519Key
it.identityKey() != olmDevice.deviceCurve25519Key &&
// Don't bother setting up sessions with blocked users
&& !(it.trustLevel?.isVerified() ?: false)
!(it.trustLevel?.isVerified() ?: false)
}
}
return ensureOlmSessionsForDevicesAction.handle(devicesByUser)

View file

@ -82,9 +82,9 @@ internal class MXMegolmDecryption(private val userId: String,
val encryptedEventContent = event.content.toModel<EncryptedEventContent>()
?: throw MXCryptoError.Base(MXCryptoError.ErrorType.MISSING_FIELDS, MXCryptoError.MISSING_FIELDS_REASON)
if (encryptedEventContent.senderKey.isNullOrBlank()
|| encryptedEventContent.sessionId.isNullOrBlank()
|| encryptedEventContent.ciphertext.isNullOrBlank()) {
if (encryptedEventContent.senderKey.isNullOrBlank() ||
encryptedEventContent.sessionId.isNullOrBlank() ||
encryptedEventContent.ciphertext.isNullOrBlank()) {
throw MXCryptoError.Base(MXCryptoError.ErrorType.MISSING_FIELDS, MXCryptoError.MISSING_FIELDS_REASON)
}

View file

@ -155,11 +155,11 @@ internal class MXMegolmEncryption(
private suspend fun ensureOutboundSession(devicesInRoom: MXUsersDevicesMap<CryptoDeviceInfo>): MXOutboundSessionInfo {
Timber.v("## CRYPTO | ensureOutboundSession start")
var session = outboundSession
if (session == null
if (session == null ||
// Need to make a brand new session?
|| session.needsRotation(sessionRotationPeriodMsgs, sessionRotationPeriodMs)
session.needsRotation(sessionRotationPeriodMsgs, sessionRotationPeriodMs) ||
// Determine if we have shared with anyone we shouldn't have
|| session.sharedWithTooManyDevices(devicesInRoom)) {
session.sharedWithTooManyDevices(devicesInRoom)) {
session = prepareNewSessionInRoom()
outboundSession = session
}
@ -380,8 +380,8 @@ internal class MXMegolmEncryption(
// with them, which means that they will have announced any new devices via
// an m.new_device.
val keys = deviceListManager.downloadKeys(userIds, false)
val encryptToVerifiedDevicesOnly = cryptoStore.getGlobalBlacklistUnverifiedDevices()
|| cryptoStore.getRoomsListBlacklistUnverifiedDevices().contains(roomId)
val encryptToVerifiedDevicesOnly = cryptoStore.getGlobalBlacklistUnverifiedDevices() ||
cryptoStore.getRoomsListBlacklistUnverifiedDevices().contains(roomId)
val devicesInRoom = DeviceInRoomInfo()
val unknownDevices = MXUsersDevicesMap<CryptoDeviceInfo>()
@ -446,10 +446,9 @@ internal class MXMegolmEncryption(
val devicesByUser = mapOf(userId to listOf(deviceInfo))
val usersDeviceMap = ensureOlmSessionsForDevicesAction.handle(devicesByUser)
val olmSessionResult = usersDeviceMap.getObject(userId, deviceId)
olmSessionResult?.sessionId
?: // no session with this device, probably because there were no one-time keys.
olmSessionResult?.sessionId // no session with this device, probably because there were no one-time keys.
// ensureOlmSessionsForDevicesAction has already done the logging, so just skip it.
return false.also {
?: return false.also {
Timber.w("## Crypto reshareKey: no session with this device, probably because there were no one-time keys")
}

View file

@ -529,13 +529,13 @@ internal class DefaultCrossSigningService @Inject constructor(
}
override fun canCrossSign(): Boolean {
return checkSelfTrust().isVerified() && cryptoStore.getCrossSigningPrivateKeys()?.selfSigned != null
&& cryptoStore.getCrossSigningPrivateKeys()?.user != null
return checkSelfTrust().isVerified() && cryptoStore.getCrossSigningPrivateKeys()?.selfSigned != null &&
cryptoStore.getCrossSigningPrivateKeys()?.user != null
}
override fun allPrivateKeysKnown(): Boolean {
return checkSelfTrust().isVerified()
&& cryptoStore.getCrossSigningPrivateKeys()?.allKnown().orFalse()
return checkSelfTrust().isVerified() &&
cryptoStore.getCrossSigningPrivateKeys()?.allKnown().orFalse()
}
override fun trustUser(otherUserId: String, callback: MatrixCallback<Unit>) {

View file

@ -860,8 +860,8 @@ internal class DefaultKeysBackupService @Inject constructor(
}
override fun onFailure(failure: Throwable) {
if (failure is Failure.ServerError
&& failure.error.code == MatrixError.M_NOT_FOUND) {
if (failure is Failure.ServerError &&
failure.error.code == MatrixError.M_NOT_FOUND) {
// Workaround because the homeserver currently returns M_NOT_FOUND when there is no key backup
callback.onSuccess(null)
} else {
@ -883,8 +883,8 @@ internal class DefaultKeysBackupService @Inject constructor(
}
override fun onFailure(failure: Throwable) {
if (failure is Failure.ServerError
&& failure.error.code == MatrixError.M_NOT_FOUND) {
if (failure is Failure.ServerError &&
failure.error.code == MatrixError.M_NOT_FOUND) {
// Workaround because the homeserver currently returns M_NOT_FOUND when there is no key backup
callback.onSuccess(null)
} else {
@ -1042,8 +1042,8 @@ internal class DefaultKeysBackupService @Inject constructor(
return null
}
if (authData.privateKeySalt.isNullOrBlank()
|| authData.privateKeyIterations == null) {
if (authData.privateKeySalt.isNullOrBlank() ||
authData.privateKeyIterations == null) {
Timber.w("recoveryKeyFromPassword: Salt and/or iterations not found in key backup auth data")
return null

View file

@ -44,16 +44,16 @@ internal class KeysBackupStateManager(private val uiHandler: Handler) {
}
val isEnabled: Boolean
get() = state == KeysBackupState.ReadyToBackUp
|| state == KeysBackupState.WillBackUp
|| state == KeysBackupState.BackingUp
get() = state == KeysBackupState.ReadyToBackUp ||
state == KeysBackupState.WillBackUp ||
state == KeysBackupState.BackingUp
// True if unknown or bad state
val isStucked: Boolean
get() = state == KeysBackupState.Unknown
|| state == KeysBackupState.Disabled
|| state == KeysBackupState.WrongBackUpVersion
|| state == KeysBackupState.NotTrusted
get() = state == KeysBackupState.Unknown ||
state == KeysBackupState.Disabled ||
state == KeysBackupState.WrongBackUpVersion ||
state == KeysBackupState.NotTrusted
fun addListener(listener: KeysBackupStateListener) {
synchronized(listeners) {

View file

@ -359,8 +359,8 @@ internal class DefaultSharedSecretStorageService @Inject constructor(
val keyInfo = (keyInfoResult as? KeyInfoResult.Success)?.keyInfo
?: return IntegrityResult.Error(SharedSecretStorageError.UnknownKey(keyId ?: ""))
if (keyInfo.content.algorithm != SSSS_ALGORITHM_AES_HMAC_SHA2
&& keyInfo.content.algorithm != SSSS_ALGORITHM_CURVE25519_AES_SHA2) {
if (keyInfo.content.algorithm != SSSS_ALGORITHM_AES_HMAC_SHA2 &&
keyInfo.content.algorithm != SSSS_ALGORITHM_CURVE25519_AES_SHA2) {
// Unsupported algorithm
return IntegrityResult.Error(
SharedSecretStorageError.UnsupportedAlgorithm(keyInfo.content.algorithm ?: "")

View file

@ -152,8 +152,8 @@ internal class RealmCryptoStore @Inject constructor(
// Check credentials
// The device id may not have been provided in credentials.
// Check it only if provided, else trust the stored one.
if (currentMetadata.userId != userId
|| (deviceId != null && deviceId != currentMetadata.deviceId)) {
if (currentMetadata.userId != userId ||
(deviceId != null && deviceId != currentMetadata.deviceId)) {
Timber.w("## open() : Credentials do not match, close this store and delete data")
deleteAll = true
currentMetadata = null
@ -178,9 +178,9 @@ internal class RealmCryptoStore @Inject constructor(
override fun hasData(): Boolean {
return doWithRealm(realmConfiguration) {
!it.isEmpty
!it.isEmpty &&
// Check if there is a MetaData object
&& it.where<CryptoMetadataEntity>().count() > 0
it.where<CryptoMetadataEntity>().count() > 0
}
}
@ -1025,10 +1025,10 @@ internal class RealmCryptoStore @Inject constructor(
}.mapNotNull {
it.toOutgoingGossipingRequest() as? OutgoingRoomKeyRequest
}.firstOrNull {
it.requestBody?.algorithm == requestBody.algorithm
&& it.requestBody?.roomId == requestBody.roomId
&& it.requestBody?.senderKey == requestBody.senderKey
&& it.requestBody?.sessionId == requestBody.sessionId
it.requestBody?.algorithm == requestBody.algorithm &&
it.requestBody?.roomId == requestBody.roomId &&
it.requestBody?.senderKey == requestBody.senderKey &&
it.requestBody?.sessionId == requestBody.sessionId
}
}
@ -1113,10 +1113,10 @@ internal class RealmCryptoStore @Inject constructor(
.mapNotNull {
it.toOutgoingGossipingRequest() as? OutgoingRoomKeyRequest
}.firstOrNull {
it.requestBody?.algorithm == requestBody.algorithm
&& it.requestBody?.sessionId == requestBody.sessionId
&& it.requestBody?.senderKey == requestBody.senderKey
&& it.requestBody?.roomId == requestBody.roomId
it.requestBody?.algorithm == requestBody.algorithm &&
it.requestBody?.sessionId == requestBody.sessionId &&
it.requestBody?.senderKey == requestBody.senderKey &&
it.requestBody?.roomId == requestBody.roomId
}
if (existing == null) {

View file

@ -46,8 +46,8 @@ internal class DefaultDeleteDeviceTask @Inject constructor(
cryptoApi.deleteDevice(params.deviceId, DeleteDeviceParams(params.userAuthParam?.asMap()))
}
} catch (throwable: Throwable) {
if (params.userInteractiveAuthInterceptor == null
|| !handleUIA(
if (params.userInteractiveAuthInterceptor == null ||
!handleUIA(
failure = throwable,
interceptor = params.userInteractiveAuthInterceptor,
retryBlock = { authUpdate ->

View file

@ -125,8 +125,8 @@ internal class DefaultInitializeCrossSigningTask @Inject constructor(
try {
uploadSigningKeysTask.execute(uploadSigningKeysParams)
} catch (failure: Throwable) {
if (params.interactiveAuthInterceptor == null
|| !handleUIA(
if (params.interactiveAuthInterceptor == null ||
!handleUIA(
failure = failure,
interceptor = params.interactiveAuthInterceptor,
retryBlock = { authUpdate ->

View file

@ -114,8 +114,8 @@ internal class DefaultIncomingSASDefaultVerificationTransaction(
// No common key sharing/hashing/hmac/SAS methods.
// If a device is unable to complete the verification because the devices are unable to find a common key sharing,
// hashing, hmac, or SAS method, then it should send a m.key.verification.cancel message
if (listOf(agreedProtocol, agreedHash, agreedMac).any { it.isNullOrBlank() }
|| agreedShortCode.isNullOrEmpty()) {
if (listOf(agreedProtocol, agreedHash, agreedMac).any { it.isNullOrBlank() } ||
agreedShortCode.isNullOrEmpty()) {
// Failed to find agreement
Timber.e("## SAS Failed to find agreement ")
cancel(CancelCode.UnknownMethod)
@ -241,12 +241,12 @@ internal class DefaultIncomingSASDefaultVerificationTransaction(
override fun onKeyVerificationMac(vMac: ValidVerificationInfoMac) {
Timber.v("## SAS I: received mac for request id:$transactionId")
// Check for state?
if (state != VerificationTxState.SendingKey
&& state != VerificationTxState.KeySent
&& state != VerificationTxState.ShortCodeReady
&& state != VerificationTxState.ShortCodeAccepted
&& state != VerificationTxState.SendingMac
&& state != VerificationTxState.MacSent) {
if (state != VerificationTxState.SendingKey &&
state != VerificationTxState.KeySent &&
state != VerificationTxState.ShortCodeReady &&
state != VerificationTxState.ShortCodeAccepted &&
state != VerificationTxState.SendingMac &&
state != VerificationTxState.MacSent) {
Timber.e("## SAS I: received key from invalid state $state")
cancel(CancelCode.UnexpectedMessage)
return

View file

@ -144,10 +144,10 @@ internal class DefaultOutgoingSASDefaultVerificationTransaction(
return
}
// Check that the agreement is correct
if (!KNOWN_AGREEMENT_PROTOCOLS.contains(accept.keyAgreementProtocol)
|| !KNOWN_HASHES.contains(accept.hash)
|| !KNOWN_MACS.contains(accept.messageAuthenticationCode)
|| accept.shortAuthenticationStrings.intersect(KNOWN_SHORT_CODES).isEmpty()) {
if (!KNOWN_AGREEMENT_PROTOCOLS.contains(accept.keyAgreementProtocol) ||
!KNOWN_HASHES.contains(accept.hash) ||
!KNOWN_MACS.contains(accept.messageAuthenticationCode) ||
accept.shortAuthenticationStrings.intersect(KNOWN_SHORT_CODES).isEmpty()) {
Timber.e("## SAS O: received invalid accept")
cancel(CancelCode.UnknownMethod)
return
@ -233,12 +233,12 @@ internal class DefaultOutgoingSASDefaultVerificationTransaction(
override fun onKeyVerificationMac(vMac: ValidVerificationInfoMac) {
Timber.v("## SAS O: onKeyVerificationMac id:$transactionId")
// There is starting to be a huge amount of state / race here :/
if (state != VerificationTxState.OnKeyReceived
&& state != VerificationTxState.ShortCodeReady
&& state != VerificationTxState.ShortCodeAccepted
&& state != VerificationTxState.KeySent
&& state != VerificationTxState.SendingMac
&& state != VerificationTxState.MacSent) {
if (state != VerificationTxState.OnKeyReceived &&
state != VerificationTxState.ShortCodeReady &&
state != VerificationTxState.ShortCodeAccepted &&
state != VerificationTxState.KeySent &&
state != VerificationTxState.SendingMac &&
state != VerificationTxState.MacSent) {
Timber.e("## SAS O: received mac from invalid state $state")
cancel(CancelCode.UnexpectedMessage)
return

View file

@ -537,8 +537,8 @@ internal class DefaultVerificationService @Inject constructor(
// as we are the one requesting in first place (or we accepted the request)
// I need to check if the pending request was related to this device also
val autoAccept = getExistingVerificationRequests(otherUserId).any {
it.transactionId == startReq.transactionId
&& (it.requestInfo?.fromDevice == this.deviceId || it.readyInfo?.fromDevice == this.deviceId)
it.transactionId == startReq.transactionId &&
(it.requestInfo?.fromDevice == this.deviceId || it.readyInfo?.fromDevice == this.deviceId)
}
val tx = DefaultIncomingSASDefaultVerificationTransaction(
// this,
@ -1278,8 +1278,8 @@ internal class DefaultVerificationService @Inject constructor(
private fun updatePendingRequest(updated: PendingVerificationRequest) {
val requestsForUser = pendingRequests.getOrPut(updated.otherUserId) { mutableListOf() }
val index = requestsForUser.indexOfFirst {
it.transactionId == updated.transactionId
|| it.transactionId == null && it.localId == updated.localId
it.transactionId == updated.transactionId ||
it.transactionId == null && it.localId == updated.localId
}
if (index != -1) {
requestsForUser.removeAt(index)

View file

@ -73,8 +73,8 @@ internal interface VerificationInfoStart : VerificationInfo<ValidVerificationInf
val validHashes = hashes?.takeIf { it.contains("sha256") } ?: return null
val validMessageAuthenticationCodes = messageAuthenticationCodes
?.takeIf {
it.contains(SASDefaultVerificationTransaction.SAS_MAC_SHA256)
|| it.contains(SASDefaultVerificationTransaction.SAS_MAC_SHA256_LONGKDF)
it.contains(SASDefaultVerificationTransaction.SAS_MAC_SHA256) ||
it.contains(SASDefaultVerificationTransaction.SAS_MAC_SHA256_LONGKDF)
}
?: return null
val validShortAuthenticationStrings = shortAuthenticationStrings?.takeIf { it.contains(SasMode.DECIMAL) } ?: return null

View file

@ -29,8 +29,8 @@ internal object IsUselessResolver {
return when (event.type) {
EventType.STATE_ROOM_MEMBER -> {
// Call toContent(), to filter out null value
event.content != null
&& event.content.toContent() == event.resolvedPrevContent()?.toContent()
event.content != null &&
event.content.toContent() == event.resolvedPrevContent()?.toContent()
}
else -> false
}

View file

@ -75,9 +75,9 @@ class WellKnown {
(config as? Map<*, *>)?.let { map ->
val apiUrl = map["api_url"] as? String
val uiUrl = map["ui_url"] as? String ?: apiUrl
if (apiUrl != null
&& apiUrl.startsWith("https://")
&& uiUrl!!.startsWith("https://")) {
if (apiUrl != null &&
apiUrl.startsWith("https://") &&
uiUrl!!.startsWith("https://")) {
managers.add(WellKnownManagerConfig(
apiUrl = apiUrl,
uiUrl = uiUrl

View file

@ -74,10 +74,10 @@ internal suspend inline fun <DATA> executeRequest(globalErrorReceiver: GlobalErr
currentRetryCount++
if (exception is Failure.ServerError
&& exception.httpCode == 429
&& exception.error.code == MatrixError.M_LIMIT_EXCEEDED
&& currentRetryCount < maxRetriesCount) {
if (exception is Failure.ServerError &&
exception.httpCode == 429 &&
exception.error.code == MatrixError.M_LIMIT_EXCEEDED &&
currentRetryCount < maxRetriesCount) {
// 429, we can retry
delay(exception.getRetryDelay(1_000))
} else if (canRetry && currentRetryCount < maxRetriesCount && exception.shouldBeRetried()) {

View file

@ -73,8 +73,8 @@ internal class UserAgentHolder @Inject constructor(private val context: Context,
// if there is no user agent or cannot parse it
if (null == systemUserAgent || systemUserAgent.lastIndexOf(")") == -1 || !systemUserAgent.contains("(")) {
userAgent = (appName + "/" + appVersion + " ( Flavour " + flavorDescription
+ "; MatrixAndroidSdk2 " + BuildConfig.SDK_VERSION + ")")
userAgent = (appName + "/" + appVersion + " ( Flavour " + flavorDescription +
"; MatrixAndroidSdk2 " + BuildConfig.SDK_VERSION + ")")
} else {
// update
userAgent = appName + "/" + appVersion + " " +

View file

@ -45,9 +45,9 @@ internal class DefaultChangePasswordTask @Inject constructor(
} catch (throwable: Throwable) {
val registrationFlowResponse = throwable.toRegistrationFlowResponse()
if (registrationFlowResponse != null
if (registrationFlowResponse != null &&
/* Avoid infinite loop */
&& changePasswordParams.auth?.session == null) {
changePasswordParams.auth?.session == null) {
// Retry with authentication
executeRequest(globalErrorReceiver) {
accountAPI.changePassword(

View file

@ -67,8 +67,8 @@ internal class FileUploader @Inject constructor(
// Check size limit
val maxUploadFileSize = homeServerCapabilitiesService.getHomeServerCapabilities().maxUploadFileSize
if (maxUploadFileSize != HomeServerCapabilities.MAX_UPLOAD_FILE_SIZE_UNKNOWN
&& file.length() > maxUploadFileSize) {
if (maxUploadFileSize != HomeServerCapabilities.MAX_UPLOAD_FILE_SIZE_UNKNOWN &&
file.length() > maxUploadFileSize) {
// Known limitation and file too big for the server, save the pain to upload it
throw Failure.ServerError(
error = MatrixError(

View file

@ -157,10 +157,10 @@ internal class UploadContentWorker(val context: Context, params: WorkerParameter
params.attachment.size
)
if (attachment.type == ContentAttachmentData.Type.IMAGE
if (attachment.type == ContentAttachmentData.Type.IMAGE &&
// Do not compress gif
&& attachment.mimeType != MimeTypes.Gif
&& params.compressBeforeSending) {
attachment.mimeType != MimeTypes.Gif &&
params.compressBeforeSending) {
notifyTracker(params) { contentUploadStateTracker.setCompressingImage(it) }
fileToUpload = imageCompressor.compress(workingFile, MAX_IMAGE_SIZE, MAX_IMAGE_SIZE)
@ -177,10 +177,10 @@ internal class UploadContentWorker(val context: Context, params: WorkerParameter
}
}
.also { filesToDelete.add(it) }
} else if (attachment.type == ContentAttachmentData.Type.VIDEO
} else if (attachment.type == ContentAttachmentData.Type.VIDEO &&
// Do not compress gif
&& attachment.mimeType != MimeTypes.Gif
&& params.compressBeforeSending) {
attachment.mimeType != MimeTypes.Gif &&
params.compressBeforeSending) {
fileToUpload = videoCompressor.compress(workingFile, object : ProgressListener {
override fun onProgress(progress: Int, total: Int) {
notifyTracker(params) { contentUploadStateTracker.setCompressingVideo(it, progress.toFloat()) }

View file

@ -33,9 +33,9 @@ internal class DefaultFilterRepository @Inject constructor(@SessionDatabase priv
return Realm.getInstance(monarchy.realmConfiguration).use { realm ->
val filterEntity = FilterEntity.get(realm)
// Filter has changed, or no filter Id yet
filterEntity == null
|| filterEntity.filterBodyJson != filter.toJSONString()
|| filterEntity.filterId.isBlank()
filterEntity == null ||
filterEntity.filterBodyJson != filter.toJSONString() ||
filterEntity.filterId.isBlank()
}.also { hasChanged ->
if (hasChanged) {
// Filter is new or has changed, store it and reset the filter Id.

View file

@ -50,10 +50,10 @@ data class EventFilter(
@Json(name = "not_types") val notTypes: List<String>? = null
) {
fun hasData(): Boolean {
return limit != null
|| senders != null
|| notSenders != null
|| types != null
|| notTypes != null
return limit != null ||
senders != null ||
notSenders != null ||
types != null ||
notTypes != null
}
}

View file

@ -73,14 +73,14 @@ data class RoomEventFilter(
}
fun hasData(): Boolean {
return (limit != null
|| notSenders != null
|| notTypes != null
|| senders != null
|| types != null
|| rooms != null
|| notRooms != null
|| containsUrl != null
|| lazyLoadMembers != null)
return (limit != null ||
notSenders != null ||
notTypes != null ||
senders != null ||
types != null ||
rooms != null ||
notRooms != null ||
containsUrl != null ||
lazyLoadMembers != null)
}
}

View file

@ -59,12 +59,12 @@ data class RoomFilter(
) {
fun hasData(): Boolean {
return (notRooms != null
|| rooms != null
|| ephemeral != null
|| includeLeave != null
|| state != null
|| timeline != null
|| accountData != null)
return (notRooms != null ||
rooms != null ||
ephemeral != null ||
includeLeave != null ||
state != null ||
timeline != null ||
accountData != null)
}
}

View file

@ -320,12 +320,12 @@ internal class DefaultIdentityService @Inject constructor(
}
private fun Throwable.isInvalidToken(): Boolean {
return this is Failure.ServerError
&& httpCode == HttpsURLConnection.HTTP_UNAUTHORIZED /* 401 */
return this is Failure.ServerError &&
httpCode == HttpsURLConnection.HTTP_UNAUTHORIZED /* 401 */
}
private fun Throwable.isTermsNotSigned(): Boolean {
return this is Failure.ServerError
&& httpCode == HttpsURLConnection.HTTP_FORBIDDEN /* 403 */
&& error.code == MatrixError.M_TERMS_NOT_SIGNED
return this is Failure.ServerError &&
httpCode == HttpsURLConnection.HTTP_FORBIDDEN && /* 403 */
error.code == MatrixError.M_TERMS_NOT_SIGNED
}

View file

@ -117,8 +117,8 @@ internal class DefaultIdentityBulkLookupTask @Inject constructor(
return withOlmUtility { olmUtility ->
threePids.map { threePid ->
base64ToBase64Url(
olmUtility.sha256(threePid.value.lowercase(Locale.ROOT)
+ " " + threePid.toMedium() + " " + pepper)
olmUtility.sha256(threePid.value.lowercase(Locale.ROOT) +
" " + threePid.toMedium() + " " + pepper)
)
}
}

View file

@ -29,9 +29,9 @@ internal class IntegrationManagerConfigExtractor @Inject constructor() {
(config as? Map<*, *>)?.let { map ->
val apiUrl = map["api_url"] as? String
val uiUrl = map["ui_url"] as? String ?: apiUrl
if (apiUrl != null
&& apiUrl.startsWith("https://")
&& uiUrl!!.startsWith("https://")) {
if (apiUrl != null &&
apiUrl.startsWith("https://") &&
uiUrl!!.startsWith("https://")) {
return WellknownIntegrationManagerConfigEntity(
apiUrl = apiUrl,
uiUrl = uiUrl

View file

@ -33,9 +33,9 @@ internal class UrlsExtractor @Inject constructor() {
return event.takeIf { it.root.getClearType() == EventType.MESSAGE }
?.getLastMessageContent()
?.takeIf {
it.msgType == MessageType.MSGTYPE_TEXT
|| it.msgType == MessageType.MSGTYPE_NOTICE
|| it.msgType == MessageType.MSGTYPE_EMOTE
it.msgType == MessageType.MSGTYPE_TEXT ||
it.msgType == MessageType.MSGTYPE_NOTICE ||
it.msgType == MessageType.MSGTYPE_EMOTE
}
?.let { messageContent ->
if (event.isReply()) {

View file

@ -71,8 +71,8 @@ internal class DefaultFinalizeAddingThreePidTask @Inject constructor(
}
true
} catch (throwable: Throwable) {
if (params.userInteractiveAuthInterceptor == null
|| !handleUIA(
if (params.userInteractiveAuthInterceptor == null ||
!handleUIA(
failure = throwable,
interceptor = params.userInteractiveAuthInterceptor,
retryBlock = { authUpdate ->

View file

@ -131,8 +131,8 @@ internal class EventRelationsAggregationProcessor @Inject constructor(
EventType.ENCRYPTED -> {
// Relation type is in clear
val encryptedEventContent = event.content.toModel<EncryptedEventContent>()
if (encryptedEventContent?.relatesTo?.type == RelationType.REPLACE
|| encryptedEventContent?.relatesTo?.type == RelationType.RESPONSE
if (encryptedEventContent?.relatesTo?.type == RelationType.REPLACE ||
encryptedEventContent?.relatesTo?.type == RelationType.RESPONSE
) {
event.getClearContent().toModel<MessageContent>()?.let {
if (encryptedEventContent.relatesTo.type == RelationType.REPLACE) {

View file

@ -77,9 +77,9 @@ internal class CreateRoomBodyBuilder @Inject constructor(
buildHistoryVisibilityEvent(params),
buildAvatarEvent(params),
buildGuestAccess(params)
)
+ params.featurePreset?.setupInitialStates().orEmpty()
+ buildCustomInitialStates(params)
) +
params.featurePreset?.setupInitialStates().orEmpty() +
buildCustomInitialStates(params)
)
.takeIf { it.isNotEmpty() }
@ -154,8 +154,8 @@ internal class CreateRoomBodyBuilder @Inject constructor(
* Add the crypto algorithm to the room creation parameters.
*/
private suspend fun buildEncryptionWithAlgorithmEvent(params: CreateRoomParams): Event? {
if (params.algorithm == null
&& canEnableEncryption(params)) {
if (params.algorithm == null &&
canEnableEncryption(params)) {
// Enable the encryption
params.enableEncryption()
}
@ -173,13 +173,13 @@ internal class CreateRoomBodyBuilder @Inject constructor(
}
private suspend fun canEnableEncryption(params: CreateRoomParams): Boolean {
return params.enableEncryptionIfInvitedUsersSupportIt
return params.enableEncryptionIfInvitedUsersSupportIt &&
// Parity with web, enable if users have encryption ready devices
// for now remove checks on cross signing and 3pid invites
// && crossSigningService.isCrossSigningVerified()
&& params.invite3pids.isEmpty()
&& params.invitedUserIds.isNotEmpty()
&& params.invitedUserIds.let { userIds ->
params.invite3pids.isEmpty() &&
params.invitedUserIds.isNotEmpty() &&
params.invitedUserIds.let { userIds ->
val keys = deviceListManager.downloadKeys(userIds, forceDownload = false)
userIds.all { userId ->

View file

@ -81,13 +81,13 @@ internal class DefaultCreateRoomTask @Inject constructor(
}
} catch (throwable: Throwable) {
if (throwable is Failure.ServerError) {
if (throwable.httpCode == 403
&& throwable.error.code == MatrixError.M_FORBIDDEN
&& throwable.error.message.startsWith("Federation denied with")) {
if (throwable.httpCode == 403 &&
throwable.error.code == MatrixError.M_FORBIDDEN &&
throwable.error.message.startsWith("Federation denied with")) {
throw CreateRoomFailure.CreatedWithFederationFailure(throwable.error)
} else if (throwable.httpCode == 400
&& throwable.error.code == MatrixError.M_UNKNOWN
&& throwable.error.message == "Invalid characters in room alias") {
} else if (throwable.httpCode == 400 &&
throwable.error.code == MatrixError.M_UNKNOWN &&
throwable.error.message == "Invalid characters in room alias") {
throw CreateRoomFailure.AliasError(RoomAliasError.AliasInvalid)
}
}
@ -138,8 +138,8 @@ internal class DefaultCreateRoomTask @Inject constructor(
* @return true if it is a direct chat
*/
private fun CreateRoomParams.isDirect(): Boolean {
return preset == CreateRoomPreset.PRESET_TRUSTED_PRIVATE_CHAT
&& isDirect == true
return preset == CreateRoomPreset.PRESET_TRUSTED_PRIVATE_CHAT &&
isDirect == true
}
/**

View file

@ -82,8 +82,8 @@ internal class DefaultSetReadMarkersTask @Inject constructor(
markers[READ_MARKER] = fullyReadEventId
}
}
if (readReceiptEventId != null
&& !isEventRead(monarchy.realmConfiguration, userId, params.roomId, readReceiptEventId)) {
if (readReceiptEventId != null &&
!isEventRead(monarchy.realmConfiguration, userId, params.roomId, readReceiptEventId)) {
if (LocalEcho.isLocalEchoId(readReceiptEventId)) {
Timber.w("Can't set read receipt for local event $readReceiptEventId")
} else {

View file

@ -105,8 +105,8 @@ internal class RoomSummaryUpdater @Inject constructor(
}
// Hard to filter from the app now we use PagedList...
roomSummaryEntity.isHiddenFromUser = roomSummaryEntity.versioningState == VersioningState.UPGRADED_ROOM_JOINED
|| roomAccountDataDataSource.getAccountDataEvent(roomId, RoomAccountDataTypes.EVENT_TYPE_VIRTUAL_ROOM) != null
roomSummaryEntity.isHiddenFromUser = roomSummaryEntity.versioningState == VersioningState.UPGRADED_ROOM_JOINED ||
roomAccountDataDataSource.getAccountDataEvent(roomId, RoomAccountDataTypes.EVENT_TYPE_VIRTUAL_ROOM) != null
val lastNameEvent = CurrentStateEventEntity.getOrNull(realm, roomId, type = EventType.STATE_ROOM_NAME, stateKey = "")?.root
val lastTopicEvent = CurrentStateEventEntity.getOrNull(realm, roomId, type = EventType.STATE_ROOM_TOPIC, stateKey = "")?.root
@ -132,9 +132,9 @@ internal class RoomSummaryUpdater @Inject constructor(
roomSummaryEntity.lastActivityTime = lastActivityFromEvent
}
roomSummaryEntity.hasUnreadMessages = roomSummaryEntity.notificationCount > 0
roomSummaryEntity.hasUnreadMessages = roomSummaryEntity.notificationCount > 0 ||
// avoid this call if we are sure there are unread events
|| !isEventRead(realm.configuration, userId, roomId, latestPreviewableEvent?.eventId)
!isEventRead(realm.configuration, userId, roomId, latestPreviewableEvent?.eventId)
roomSummaryEntity.displayName = roomDisplayNameResolver.resolve(realm, roomId)
roomSummaryEntity.avatarUrl = roomAvatarResolver.resolve(realm, roomId)

View file

@ -475,8 +475,8 @@ internal class DefaultTimeline(
val currentChunk = getLiveChunk()
val token = if (direction == Timeline.Direction.BACKWARDS) currentChunk?.prevToken else currentChunk?.nextToken
if (token == null) {
if (direction == Timeline.Direction.BACKWARDS
|| (direction == Timeline.Direction.FORWARDS && currentChunk?.hasBeenALastForwardChunk().orFalse())) {
if (direction == Timeline.Direction.BACKWARDS ||
(direction == Timeline.Direction.FORWARDS && currentChunk?.hasBeenALastForwardChunk().orFalse())) {
// We are in the case where event exists, but we do not know the token.
// Fetch (again) the last event to get a token
val lastKnownEventId = if (direction == Timeline.Direction.FORWARDS) {
@ -583,8 +583,8 @@ internal class DefaultTimeline(
val transactionId = timelineEvent.root.unsignedData?.transactionId
uiEchoManager.onSyncedEvent(transactionId)
if (timelineEvent.isEncrypted()
&& timelineEvent.root.mxDecryptionResult == null) {
if (timelineEvent.isEncrypted() &&
timelineEvent.root.mxDecryptionResult == null) {
timelineEvent.root.eventId?.also { eventDecryptor.requestDecryption(TimelineEventDecryptor.DecryptionRequest(timelineEvent.root, timelineID)) }
}

View file

@ -238,8 +238,8 @@ internal class TokenChunkEventPersistor @Inject constructor(@SessionDatabase pri
it.deleteOnCascade(deleteStateEvents = false, canDeleteRoot = false)
}
val roomSummaryEntity = RoomSummaryEntity.getOrCreate(realm, roomId)
val shouldUpdateSummary = roomSummaryEntity.latestPreviewableEvent == null
|| (chunksToDelete.isNotEmpty() && currentChunk.isLastForward && direction == PaginationDirection.FORWARDS)
val shouldUpdateSummary = roomSummaryEntity.latestPreviewableEvent == null ||
(chunksToDelete.isNotEmpty() && currentChunk.isLastForward && direction == PaginationDirection.FORWARDS)
if (shouldUpdateSummary) {
roomSummaryEntity.latestPreviewableEvent = RoomSummaryEventsHelper.getLatestPreviewableEvent(realm, roomId)
}

View file

@ -50,9 +50,9 @@ internal class DefaultSignOutTask @Inject constructor(
}
} catch (throwable: Throwable) {
// Maybe due to https://github.com/matrix-org/synapse/issues/5756
if (throwable is Failure.ServerError
&& throwable.httpCode == HttpURLConnection.HTTP_UNAUTHORIZED /* 401 */
&& throwable.error.code == MatrixError.M_UNKNOWN_TOKEN) {
if (throwable is Failure.ServerError &&
throwable.httpCode == HttpURLConnection.HTTP_UNAUTHORIZED && /* 401 */
throwable.error.code == MatrixError.M_UNKNOWN_TOKEN) {
// Also throwable.error.isSoftLogout should be true
// Ignore
Timber.w("Ignore error due to https://github.com/matrix-org/synapse/issues/5755")

View file

@ -76,9 +76,9 @@ internal class DefaultPeekSpaceTask @Inject constructor(
if (depth >= maxDepth) return emptyList()
val childRoomsIds = stateEvents
.filter {
it.type == EventType.STATE_SPACE_CHILD && !it.stateKey.isNullOrEmpty()
it.type == EventType.STATE_SPACE_CHILD && !it.stateKey.isNullOrEmpty() &&
// Children where via is not present are ignored.
&& it.content?.toModel<SpaceChildContent>()?.via != null
it.content?.toModel<SpaceChildContent>()?.via != null
}
.map { it.stateKey to it.content?.toModel<SpaceChildContent>() }

View file

@ -42,8 +42,8 @@ internal class CryptoSyncHandler @Inject constructor(private val cryptoService:
// Decrypt event if necessary
Timber.i("## CRYPTO | To device event from ${event.senderId} of type:${event.type}")
decryptToDeviceEvent(event, null)
if (event.getClearType() == EventType.MESSAGE
&& event.getClearContent()?.toModel<MessageContent>()?.msgType == "m.bad.encrypted") {
if (event.getClearType() == EventType.MESSAGE &&
event.getClearContent()?.toModel<MessageContent>()?.msgType == "m.bad.encrypted") {
Timber.e("## CRYPTO | handleToDeviceEvent() : Warning: Unable to decrypt to-device event : ${event.content}")
} else {
verificationService.onToDeviceEvent(event)

View file

@ -63,8 +63,8 @@ internal class FileInitialSyncStatusRepository(directory: File) : InitialSyncSta
override fun getStep(): Int {
ensureCache()
val state = cache?.step ?: InitialSyncStatus.STEP_INIT
return if (state >= InitialSyncStatus.STEP_DOWNLOADED
&& System.currentTimeMillis() > (cache?.downloadedDate ?: 0) + INIT_SYNC_FILE_LIFETIME) {
return if (state >= InitialSyncStatus.STEP_DOWNLOADED &&
System.currentTimeMillis() > (cache?.downloadedDate ?: 0) + INIT_SYNC_FILE_LIFETIME) {
Timber.d("INIT_SYNC downloaded file is outdated, download it again")
// The downloaded file is outdated
setStep(InitialSyncStatus.STEP_INIT)

View file

@ -155,8 +155,8 @@ internal class WidgetManager @Inject constructor(private val integrationManager:
return extractWidgetSequence(widgetFactory)
.filter {
val widgetType = it.widgetContent.type ?: return@filter false
(widgetTypes == null || widgetTypes.contains(widgetType))
&& (excludedTypes == null || !excludedTypes.contains(widgetType))
(widgetTypes == null || widgetTypes.contains(widgetType)) &&
(excludedTypes == null || !excludedTypes.contains(widgetType))
}
.toList()
}

View file

@ -235,8 +235,8 @@ class DebugMenuActivity : VectorBaseActivity<ActivityDebugMenuBinding>() {
private val qrStartForActivityResult = registerStartForActivityResult { activityResult ->
if (activityResult.resultCode == Activity.RESULT_OK) {
toast("QrCode: " + QrCodeScannerActivity.getResultText(activityResult.data)
+ " is QRCode: " + QrCodeScannerActivity.getResultIsQrCode(activityResult.data))
toast("QrCode: " + QrCodeScannerActivity.getResultText(activityResult.data) +
" is QRCode: " + QrCodeScannerActivity.getResultIsQrCode(activityResult.data))
// Also update the current QR Code (reverse operation)
// renderQrCode(QrCodeScannerActivity.getResultText(data) ?: "")

View file

@ -76,8 +76,8 @@ class AppStateHandler @Inject constructor(
fun setCurrentSpace(spaceId: String?, session: Session? = null) {
val uSession = session ?: activeSessionHolder.getSafeActiveSession() ?: return
if (selectedSpaceDataSource.currentValue?.orNull() is RoomGroupingMethod.BySpace
&& spaceId == selectedSpaceDataSource.currentValue?.orNull()?.space()?.roomId) return
if (selectedSpaceDataSource.currentValue?.orNull() is RoomGroupingMethod.BySpace &&
spaceId == selectedSpaceDataSource.currentValue?.orNull()?.space()?.roomId) return
val spaceSum = spaceId?.let { uSession.getRoomSummary(spaceId) }
selectedSpaceDataSource.post(Option.just(RoomGroupingMethod.BySpace(spaceSum)))
if (spaceId != null) {
@ -91,8 +91,8 @@ class AppStateHandler @Inject constructor(
fun setCurrentGroup(groupId: String?, session: Session? = null) {
val uSession = session ?: activeSessionHolder.getSafeActiveSession() ?: return
if (selectedSpaceDataSource.currentValue?.orNull() is RoomGroupingMethod.ByLegacyGroup
&& groupId == selectedSpaceDataSource.currentValue?.orNull()?.group()?.groupId) return
if (selectedSpaceDataSource.currentValue?.orNull() is RoomGroupingMethod.ByLegacyGroup &&
groupId == selectedSpaceDataSource.currentValue?.orNull()?.group()?.groupId) return
val activeGroup = groupId?.let { uSession.getGroupSummary(groupId) }
selectedSpaceDataSource.post(Option.just(RoomGroupingMethod.ByLegacyGroup(activeGroup)))
if (groupId != null) {

View file

@ -105,8 +105,8 @@ class VectorApplication :
private val powerKeyReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent) {
if (intent.action == Intent.ACTION_SCREEN_OFF
&& vectorPreferences.useFlagPinCode()) {
if (intent.action == Intent.ACTION_SCREEN_OFF &&
vectorPreferences.useFlagPinCode()) {
pinLocker.screenIsOff()
}
}

View file

@ -62,15 +62,15 @@ fun Session.startSyncing(context: Context) {
* Tell is the session has unsaved e2e keys in the backup
*/
fun Session.hasUnsavedKeys(): Boolean {
return cryptoService().inboundGroupSessionsCount(false) > 0
&& cryptoService().keysBackupService().state != KeysBackupState.ReadyToBackUp
return cryptoService().inboundGroupSessionsCount(false) > 0 &&
cryptoService().keysBackupService().state != KeysBackupState.ReadyToBackUp
}
fun Session.cannotLogoutSafely(): Boolean {
// has some encrypted chat
return hasUnsavedKeys()
return hasUnsavedKeys() ||
// has local cross signing keys
|| (cryptoService().crossSigningService().allPrivateKeysKnown()
(cryptoService().crossSigningService().allPrivateKeysKnown() &&
// That are not backed up
&& !sharedSecretStorageService.isRecoverySetup())
!sharedSecretStorageService.isRecoverySetup())
}

View file

@ -40,8 +40,8 @@ import im.vector.app.features.themes.ThemeUtils
* Set a text in the TextView, or set visibility to GONE if the text is null
*/
fun TextView.setTextOrHide(newText: CharSequence?, hideWhenBlank: Boolean = true, vararg relatedViews: View = emptyArray()) {
if (newText == null
|| (newText.isBlank() && hideWhenBlank)) {
if (newText == null ||
(newText.isBlank() && hideWhenBlank)) {
isVisible = false
relatedViews.forEach { it.isVisible = false }
} else {

View file

@ -22,7 +22,7 @@ import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent
fun TimelineEvent.canReact(): Boolean {
// Only event of type EventType.MESSAGE or EventType.STICKER are supported for the moment
return root.getClearType() in listOf(EventType.MESSAGE, EventType.STICKER)
&& root.sendState == SendState.SYNCED
&& !root.isRedacted()
return root.getClearType() in listOf(EventType.MESSAGE, EventType.STICKER) &&
root.sendState == SendState.SYNCED &&
!root.isRedacted()
}

View file

@ -136,8 +136,8 @@ class KeysBackupBanner @JvmOverloads constructor(
}
private fun renderSetup(nbOfKeys: Int) {
if (nbOfKeys == 0
|| DefaultSharedPreferences.getInstance(context).getBoolean(BANNER_SETUP_DO_NOT_SHOW_AGAIN, false)) {
if (nbOfKeys == 0 ||
DefaultSharedPreferences.getInstance(context).getBoolean(BANNER_SETUP_DO_NOT_SHOW_AGAIN, false)) {
// Do not display the setup banner if there is no keys to backup, or if the user has already closed it
isVisible = false
} else {

View file

@ -59,8 +59,8 @@ class SnapOnScrollListener(
}
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
if (behavior == Behavior.NOTIFY_ON_SCROLL_STATE_IDLE
&& newState == RecyclerView.SCROLL_STATE_IDLE) {
if (behavior == Behavior.NOTIFY_ON_SCROLL_STATE_IDLE &&
newState == RecyclerView.SCROLL_STATE_IDLE) {
maybeNotifySnapPositionChange(recyclerView)
}
}

View file

@ -48,8 +48,8 @@ import im.vector.app.features.notifications.NotificationUtils
*/
fun isIgnoringBatteryOptimizations(context: Context): Boolean {
// no issue before Android M, battery optimisations did not exist
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M
|| context.getSystemService<PowerManager>()?.isIgnoringBatteryOptimizations(context.packageName) == true
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
context.getSystemService<PowerManager>()?.isIgnoringBatteryOptimizations(context.packageName) == true
}
fun isAirplaneModeOn(context: Context): Boolean {

View file

@ -220,8 +220,8 @@ class MainActivity : VectorBaseActivity<ActivityMainBinding>(), UnlockedActivity
private fun startNextActivityAndFinish(ignoreClearCredentials: Boolean = false) {
val intent = when {
args.clearCredentials
&& !ignoreClearCredentials
args.clearCredentials &&
!ignoreClearCredentials
&& (!args.isUserLoggedOut || args.isAccountDeactivated) -> {
// User has explicitly asked to log out or deactivated his account
navigator.openLogin(this, null)

View file

@ -27,9 +27,9 @@ private val listOfPreviewableMimeTypes = listOf(
fun ContentAttachmentData.isPreviewable(): Boolean {
// Preview supports image and video
return (type == ContentAttachmentData.Type.IMAGE
&& listOfPreviewableMimeTypes.contains(getSafeMimeType() ?: ""))
|| type == ContentAttachmentData.Type.VIDEO
return (type == ContentAttachmentData.Type.IMAGE &&
listOfPreviewableMimeTypes.contains(getSafeMimeType() ?: "")) ||
type == ContentAttachmentData.Type.VIDEO
}
data class GroupedContentAttachmentData(

View file

@ -24,7 +24,7 @@ import org.matrix.android.sdk.api.util.MimeTypes.isMimeTypeImage
* All images are editable, expect Gif
*/
fun ContentAttachmentData.isEditable(): Boolean {
return type == ContentAttachmentData.Type.IMAGE
&& getSafeMimeType()?.isMimeTypeImage() == true
&& getSafeMimeType() != MimeTypes.Gif
return type == ContentAttachmentData.Type.IMAGE &&
getSafeMimeType()?.isMimeTypeImage() == true &&
getSafeMimeType() != MimeTypes.Gif
}

View file

@ -37,8 +37,8 @@ class CommandAutocompletePolicy @Inject constructor() : AutocompletePolicy {
// Only if text which starts with '/' and without space
override fun shouldShowPopup(text: Spannable?, cursorPos: Int): Boolean {
return enabled && text?.startsWith("/") == true
&& !text.contains(" ")
return enabled && text?.startsWith("/") == true &&
!text.contains(" ")
}
override fun shouldDismissPopup(text: Spannable?, cursorPos: Int): Boolean {

View file

@ -104,8 +104,8 @@ class JitsiCallViewModel @AssistedInject constructor(
private fun handleSwitchTo(action: JitsiCallViewActions.SwitchTo) = withState { state ->
// Check if it is the same conf
if (action.args.roomId != state.roomId
|| action.args.widgetId != state.widgetId) {
if (action.args.roomId != state.roomId ||
action.args.widgetId != state.widgetId) {
if (action.withConfirmation) {
// Ask confirmation to switch, but wait a bit for the Activity to quit the PiP mode
viewModelScope.launch {

View file

@ -87,10 +87,10 @@ import org.matrix.android.sdk.api.session.room.model.Membership
fun render(roomDetailViewState: RoomDetailViewState) {
val summary = roomDetailViewState.asyncRoomSummary()
val newState = if (summary?.membership != Membership.JOIN
|| roomDetailViewState.isWebRTCCallOptionAvailable()
|| !roomDetailViewState.isAllowedToManageWidgets
|| roomDetailViewState.jitsiState.widgetId == null) {
val newState = if (summary?.membership != Membership.JOIN ||
roomDetailViewState.isWebRTCCallOptionAvailable() ||
!roomDetailViewState.isAllowedToManageWidgets ||
roomDetailViewState.jitsiState.widgetId == null) {
State.Unmount
} else if (roomDetailViewState.jitsiState.deleteWidgetInProgress) {
State.Progress

View file

@ -636,8 +636,8 @@ class WebRtcCall(
// We consider a call to be on hold only if *all* the tracks are on hold
// (is this the right thing to do?)
for (transceiver in peerConnection?.transceivers ?: emptyList()) {
val trackOnHold = transceiver.currentDirection == RtpTransceiver.RtpTransceiverDirection.INACTIVE
|| transceiver.currentDirection == RtpTransceiver.RtpTransceiverDirection.RECV_ONLY
val trackOnHold = transceiver.currentDirection == RtpTransceiver.RtpTransceiverDirection.INACTIVE ||
transceiver.currentDirection == RtpTransceiver.RtpTransceiverDirection.RECV_ONLY
if (!trackOnHold) callOnHold = false
}
return callOnHold
@ -891,8 +891,8 @@ class WebRtcCall(
val polite = !mxCall.isOutgoing
// Here we follow the perfect negotiation logic from
// https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Perfect_negotiation
val offerCollision = description.type == SdpType.OFFER
&& (makingOffer || peerConnection.signalingState() != PeerConnection.SignalingState.STABLE)
val offerCollision = description.type == SdpType.OFFER &&
(makingOffer || peerConnection.signalingState() != PeerConnection.SignalingState.STABLE)
ignoreOffer = !polite && offerCollision
if (ignoreOffer) {

View file

@ -104,8 +104,8 @@ class VectorConfiguration @Inject constructor(private val context: Context) {
* @return the local status value
*/
fun getHash(): String {
return (VectorLocale.applicationLocale.toString()
+ "_" + FontScale.getFontScaleValue(context).preferenceValue
+ "_" + ThemeUtils.getApplicationTheme(context))
return (VectorLocale.applicationLocale.toString() +
"_" + FontScale.getFontScaleValue(context).preferenceValue +
"_" + ThemeUtils.getApplicationTheme(context))
}
}

View file

@ -156,8 +156,8 @@ class ContactsBookViewModel @AssistedInject constructor(@Assisted
val filteredMappedContacts = mappedContacts
.filter { it.displayName.contains(state.searchTerm, true) }
.filter { contactModel ->
!state.onlyBoundContacts
|| contactModel.emails.any { it.matrixId != null } || contactModel.msisdns.any { it.matrixId != null }
!state.onlyBoundContacts ||
contactModel.emails.any { it.matrixId != null } || contactModel.msisdns.any { it.matrixId != null }
}
setState {

View file

@ -88,26 +88,26 @@ class KeysBackupRestoreSharedViewModel @Inject constructor(
override fun onStepProgress(step: StepProgressListener.Step) {
when (step) {
is StepProgressListener.Step.ComputingKey -> {
loadingEvent.postValue(WaitingViewData(stringProvider.getString(R.string.keys_backup_restoring_waiting_message)
+ "\n" + stringProvider.getString(R.string.keys_backup_restoring_computing_key_waiting_message),
loadingEvent.postValue(WaitingViewData(stringProvider.getString(R.string.keys_backup_restoring_waiting_message) +
"\n" + stringProvider.getString(R.string.keys_backup_restoring_computing_key_waiting_message),
step.progress,
step.total))
}
is StepProgressListener.Step.DownloadingKey -> {
loadingEvent.postValue(WaitingViewData(stringProvider.getString(R.string.keys_backup_restoring_waiting_message)
+ "\n" + stringProvider.getString(R.string.keys_backup_restoring_downloading_backup_waiting_message),
loadingEvent.postValue(WaitingViewData(stringProvider.getString(R.string.keys_backup_restoring_waiting_message) +
"\n" + stringProvider.getString(R.string.keys_backup_restoring_downloading_backup_waiting_message),
isIndeterminate = true))
}
is StepProgressListener.Step.ImportingKey -> {
Timber.d("backupKeys.ImportingKey.progress: ${step.progress}")
// Progress 0 can take a while, display an indeterminate progress in this case
if (step.progress == 0) {
loadingEvent.postValue(WaitingViewData(stringProvider.getString(R.string.keys_backup_restoring_waiting_message)
+ "\n" + stringProvider.getString(R.string.keys_backup_restoring_importing_keys_waiting_message),
loadingEvent.postValue(WaitingViewData(stringProvider.getString(R.string.keys_backup_restoring_waiting_message) +
"\n" + stringProvider.getString(R.string.keys_backup_restoring_importing_keys_waiting_message),
isIndeterminate = true))
} else {
loadingEvent.postValue(WaitingViewData(stringProvider.getString(R.string.keys_backup_restoring_waiting_message)
+ "\n" + stringProvider.getString(R.string.keys_backup_restoring_importing_keys_waiting_message),
loadingEvent.postValue(WaitingViewData(stringProvider.getString(R.string.keys_backup_restoring_waiting_message) +
"\n" + stringProvider.getString(R.string.keys_backup_restoring_importing_keys_waiting_message),
step.progress,
step.total))
}

View file

@ -163,7 +163,7 @@ class KeysBackupSettingsViewModel @AssistedInject constructor(@Assisted initialS
fun canExit(): Boolean {
val currentBackupState = keysBackupService.state
return currentBackupState == KeysBackupState.Unknown
|| currentBackupState == KeysBackupState.CheckingBackUpOnHomeserver
return currentBackupState == KeysBackupState.Unknown ||
currentBackupState == KeysBackupState.CheckingBackUpOnHomeserver
}
}

View file

@ -226,9 +226,9 @@ class KeyRequestHandler @Inject constructor(
val alertMgrUniqueKey = alertManagerId(userId, deviceId)
alertsToRequests[alertMgrUniqueKey]?.removeAll {
it.deviceId == request.deviceId
&& it.userId == request.userId
&& it.requestId == request.requestId
it.deviceId == request.deviceId &&
it.userId == request.userId &&
it.requestId == request.requestId
}
if (alertsToRequests[alertMgrUniqueKey]?.isEmpty() == true) {
popupAlertManager.cancelAlert(alertMgrUniqueKey)

View file

@ -81,9 +81,9 @@ class BootstrapCrossSigningTask @Inject constructor(
Timber.d("## BootstrapCrossSigningTask: mode:${params.setupMode} Starting...")
// Ensure cross-signing is initialized. Due to migration it is maybe not always correctly initialized
val shouldSetCrossSigning = !crossSigningService.isCrossSigningInitialized()
|| (params.setupMode == SetupMode.PASSPHRASE_AND_NEEDED_SECRETS_RESET && !crossSigningService.allPrivateKeysKnown())
|| (params.setupMode == SetupMode.HARD_RESET)
val shouldSetCrossSigning = !crossSigningService.isCrossSigningInitialized() ||
(params.setupMode == SetupMode.PASSPHRASE_AND_NEEDED_SECRETS_RESET && !crossSigningService.allPrivateKeysKnown()) ||
(params.setupMode == SetupMode.HARD_RESET)
if (shouldSetCrossSigning) {
Timber.d("## BootstrapCrossSigningTask: Cross signing not enabled, so initialize")
params.progressListener?.onProgress(
@ -227,9 +227,9 @@ class BootstrapCrossSigningTask @Inject constructor(
val knownMegolmSecret = session.cryptoService().keysBackupService().getKeyBackupRecoveryKeyInfo()
val isMegolmBackupSecretKnown = knownMegolmSecret != null && knownMegolmSecret.version == serverVersion?.version
val shouldCreateKeyBackup = serverVersion == null
|| (params.setupMode == SetupMode.PASSPHRASE_AND_NEEDED_SECRETS_RESET && !isMegolmBackupSecretKnown)
|| (params.setupMode == SetupMode.HARD_RESET)
val shouldCreateKeyBackup = serverVersion == null ||
(params.setupMode == SetupMode.PASSPHRASE_AND_NEEDED_SECRETS_RESET && !isMegolmBackupSecretKnown) ||
(params.setupMode == SetupMode.HARD_RESET)
if (shouldCreateKeyBackup) {
// clear all existing backups
while (serverVersion != null) {

View file

@ -437,9 +437,9 @@ class BootstrapSharedViewModel @AssistedInject constructor(
}
}
is BootstrapResult.Failure -> {
if (bootstrapResult is BootstrapResult.GenericError
&& bootstrapResult.failure is Failure.OtherServerError
&& bootstrapResult.failure.httpCode == 401) {
if (bootstrapResult is BootstrapResult.GenericError &&
bootstrapResult.failure is Failure.OtherServerError &&
bootstrapResult.failure.httpCode == 401) {
// Ignore this error
} else {
_viewEvents.post(BootstrapViewEvents.ModalError(bootstrapResult.error ?: stringProvider.getString(R.string.matrix_error)))

View file

@ -159,9 +159,9 @@ class VerificationBottomSheet : VectorBaseBottomSheetDialogFragment<BottomSheetV
state.otherUserMxItem?.let { matrixItem ->
if (state.isMe) {
avatarRenderer.render(matrixItem, views.otherUserAvatarImageView)
if (state.sasTransactionState == VerificationTxState.Verified
|| state.qrTransactionState == VerificationTxState.Verified
|| state.verifiedFromPrivateKeys) {
if (state.sasTransactionState == VerificationTxState.Verified ||
state.qrTransactionState == VerificationTxState.Verified ||
state.verifiedFromPrivateKeys) {
views.otherUserShield.render(RoomEncryptionTrustLevel.Trusted)
} else {
views.otherUserShield.render(RoomEncryptionTrustLevel.Warning)

View file

@ -172,9 +172,9 @@ class VerificationBottomSheetViewModel @AssistedInject constructor(
}
} else {
// if the verification is already done you can't cancel anymore
if (state.pendingRequest.invoke()?.cancelConclusion != null
|| state.sasTransactionState is VerificationTxState.TerminalTxState
|| state.verifyingFrom4S) {
if (state.pendingRequest.invoke()?.cancelConclusion != null ||
state.sasTransactionState is VerificationTxState.TerminalTxState ||
state.verifyingFrom4S) {
// you cannot cancel anymore
} else {
setState {
@ -537,9 +537,9 @@ class VerificationBottomSheetViewModel @AssistedInject constructor(
}
}
if (pr.localId == state.pendingLocalId
|| pr.localId == state.pendingRequest.invoke()?.localId
|| state.pendingRequest.invoke()?.transactionId == pr.transactionId) {
if (pr.localId == state.pendingLocalId ||
pr.localId == state.pendingRequest.invoke()?.localId ||
state.pendingRequest.invoke()?.transactionId == pr.transactionId) {
setState {
copy(
transactionId = args.verificationId ?: pr.transactionId,

View file

@ -194,8 +194,8 @@ class RoomDevToolActivity : SimpleFragmentActivity(), RoomDevToolViewModel.Facto
state.displayMode is RoomDevToolViewState.Mode.StateEventDetail
}
R.id.menuItemSend -> {
state.displayMode is RoomDevToolViewState.Mode.EditEventContent
|| state.displayMode is RoomDevToolViewState.Mode.SendEventForm
state.displayMode is RoomDevToolViewState.Mode.EditEventContent ||
state.displayMode is RoomDevToolViewState.Mode.SendEventForm
}
else -> true
}

View file

@ -282,8 +282,8 @@ class DiscoverySettingsController @Inject constructor(
val error = pidInfo.finalRequest.error
// Deal with error 500
// Ref: https://github.com/matrix-org/sydent/issues/292
if (error is Failure.ServerError
&& error.httpCode == HttpsURLConnection.HTTP_INTERNAL_ERROR /* 500 */) {
if (error is Failure.ServerError &&
error.httpCode == HttpsURLConnection.HTTP_INTERNAL_ERROR /* 500 */) {
stringProvider.getString(R.string.settings_text_message_sent_wrong_code)
} else {
errorFormatter.toHumanReadable(error)

View file

@ -254,8 +254,8 @@ class HomeActivity :
if (!vectorPreferences.didPromoteNewRestrictedFeature()) {
promoteRestrictedViewModel.subscribe(this) {
if (it.activeSpaceSummary != null && !it.activeSpaceSummary.isPublic
&& it.activeSpaceSummary.otherMemberIds.isNotEmpty()) {
if (it.activeSpaceSummary != null && !it.activeSpaceSummary.isPublic &&
it.activeSpaceSummary.otherMemberIds.isNotEmpty()) {
// It's a private space with some members show this once
if (it.canUserManageSpace && !popupAlertManager.hasAlertsToShow()) {
if (!vectorPreferences.didPromoteNewRestrictedFeature()) {
@ -298,8 +298,8 @@ class HomeActivity :
.observeOn(AndroidSchedulers.mainThread())
.subscribe { isHandled ->
if (!isHandled) {
val isMatrixToLink = deepLink.startsWith(PermalinkService.MATRIX_TO_URL_BASE)
|| deepLink.startsWith(MATRIX_TO_CUSTOM_SCHEME_URL_BASE)
val isMatrixToLink = deepLink.startsWith(PermalinkService.MATRIX_TO_URL_BASE) ||
deepLink.startsWith(MATRIX_TO_CUSTOM_SCHEME_URL_BASE)
MaterialAlertDialogBuilder(this)
.setTitle(R.string.dialog_title_error)
.setMessage(if (isMatrixToLink) R.string.permalink_malformed else R.string.universal_link_malformed)

View file

@ -218,9 +218,9 @@ class HomeActivityViewModel @AssistedInject constructor(
object : UserInteractiveAuthInterceptor {
override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation<UIABaseAuth>) {
// We missed server grace period or it's not setup, see if we remember locally password
if (flowResponse.nextUncompletedStage() == LoginFlowTypes.PASSWORD
&& errCode == null
&& reAuthHelper.data != null) {
if (flowResponse.nextUncompletedStage() == LoginFlowTypes.PASSWORD &&
errCode == null &&
reAuthHelper.data != null) {
promise.resume(
UserPasswordAuth(
session = flowResponse.session,

View file

@ -177,12 +177,12 @@ class UnreadMessagesSharedViewModel @AssistedInject constructor(@Assisted initia
CountInfo(
homeCount = counts,
otherCount = RoomAggregateNotificationCount(
notificationCount = rootCounts.fold(0, { acc, rs -> acc + rs.notificationCount })
+ (counts.notificationCount.takeIf { selectedSpace != null } ?: 0)
+ spaceInviteCount,
highlightCount = rootCounts.fold(0, { acc, rs -> acc + rs.highlightCount })
+ (counts.highlightCount.takeIf { selectedSpace != null } ?: 0)
+ spaceInviteCount
notificationCount = rootCounts.fold(0, { acc, rs -> acc + rs.notificationCount }) +
(counts.notificationCount.takeIf { selectedSpace != null } ?: 0) +
spaceInviteCount,
highlightCount = rootCounts.fold(0, { acc, rs -> acc + rs.highlightCount }) +
(counts.highlightCount.takeIf { selectedSpace != null } ?: 0) +
spaceInviteCount
)
)
}

View file

@ -105,8 +105,8 @@ class ChatEffectManager @Inject constructor() {
}
private fun hasAlreadyPlayed(event: TimelineEvent): Boolean {
return alreadyPlayed.contains(event.eventId)
|| (event.root.unsignedData?.transactionId?.let { alreadyPlayed.contains(it) } ?: false)
return alreadyPlayed.contains(event.eventId) ||
(event.root.unsignedData?.transactionId?.let { alreadyPlayed.contains(it) } ?: false)
}
private fun findEffect(content: MessageContent, event: TimelineEvent): ChatEffect? {

View file

@ -1279,10 +1279,10 @@ class RoomDetailFragment @Inject constructor(
true
}
// Add external keyboard functionality (to send messages)
else if (null != keyEvent
&& !keyEvent.isShiftPressed
&& keyEvent.keyCode == KeyEvent.KEYCODE_ENTER
&& resources.configuration.keyboard != Configuration.KEYBOARD_NOKEYS) {
else if (null != keyEvent &&
!keyEvent.isShiftPressed &&
keyEvent.keyCode == KeyEvent.KEYCODE_ENTER &&
resources.configuration.keyboard != Configuration.KEYBOARD_NOKEYS) {
sendTextMessage(v.text)
true
} else false
@ -1865,8 +1865,8 @@ class RoomDetailFragment @Inject constructor(
}
private fun onSaveActionClicked(action: EventSharedAction.Save) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
&& !checkPermissions(PERMISSIONS_FOR_WRITING_FILES, requireActivity(), saveActionActivityResultLauncher)) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q &&
!checkPermissions(PERMISSIONS_FOR_WRITING_FILES, requireActivity(), saveActionActivityResultLauncher)) {
sharedActionViewModel.pendingAction = action
return
}
@ -2018,8 +2018,8 @@ class RoomDetailFragment @Inject constructor(
private fun insertUserDisplayNameInTextEditor(userId: String) {
val startToCompose = views.composerLayout.text.isNullOrBlank()
if (startToCompose
&& userId == session.myUserId) {
if (startToCompose &&
userId == session.myUserId) {
// Empty composer, current user: start an emote
views.composerLayout.views.composerEditText.setText(Command.EMOTE.command + " ")
views.composerLayout.views.composerEditText.setSelection(Command.EMOTE.length)

View file

@ -550,8 +550,8 @@ class RoomDetailViewModel @AssistedInject constructor(
val widget = action.widget
val domain = action.widget.widgetContent.data["domain"] as? String ?: ""
val isAllowed = action.userJustAccepted || if (widget.type == WidgetType.Jitsi) {
widget.senderInfo?.userId == session.myUserId
|| session.integrationManagerService().isNativeWidgetDomainAllowed(
widget.senderInfo?.userId == session.myUserId ||
session.integrationManagerService().isNativeWidgetDomainAllowed(
action.widget.type.preferred,
domain
)
@ -1270,8 +1270,8 @@ class RoomDetailViewModel @AssistedInject constructor(
private fun handleOpenOrDownloadFile(action: RoomDetailAction.DownloadOrOpen) {
val mxcUrl = action.messageFileContent.getFileUrl() ?: return
val isLocalSendingFile = action.senderId == session.myUserId
&& mxcUrl.startsWith("content://")
val isLocalSendingFile = action.senderId == session.myUserId &&
mxcUrl.startsWith("content://")
if (isLocalSendingFile) {
tryOrNull { Uri.parse(mxcUrl) }?.let {
_viewEvents.post(RoomDetailViewEvents.OpenFile(

View file

@ -260,8 +260,8 @@ class VoiceMessageRecorderView: ConstraintLayout, VoiceMessagePlaybackTracker.Li
val previousRecordingState = recordingState
if (recordingState == RecordingState.STARTED) {
// Determine if cancelling or locking for the first move action.
if (((currentX < firstX && rtlXMultiplier == 1) || (currentX > firstX && rtlXMultiplier == -1))
&& distanceX > distanceY && distanceX > lastDistanceX) {
if (((currentX < firstX && rtlXMultiplier == 1) || (currentX > firstX && rtlXMultiplier == -1)) &&
distanceX > distanceY && distanceX > lastDistanceX) {
recordingState = RecordingState.CANCELLING
} else if (currentY < firstY && distanceY > distanceX && distanceY > lastDistanceY) {
recordingState = RecordingState.LOCKING

View file

@ -249,8 +249,8 @@ class TimelineEventController @Inject constructor(private val dateFormatter: Vec
if (partialState.highlightedEventId != newPartialState.highlightedEventId) {
// Clear cache to force a refresh
for (i in 0 until modelCache.size) {
if (modelCache[i]?.eventId == viewState.highlightedEventId
|| modelCache[i]?.eventId == partialState.highlightedEventId) {
if (modelCache[i]?.eventId == viewState.highlightedEventId ||
modelCache[i]?.eventId == partialState.highlightedEventId) {
modelCache[i] = null
}
}
@ -498,8 +498,8 @@ class TimelineEventController @Inject constructor(private val dateFormatter: Vec
if (vectorPreferences.labShowCompleteHistoryInEncryptedRoom()) {
return
}
if (event.root.type == EventType.STATE_ROOM_MEMBER
&& event.root.stateKey == session.myUserId) {
if (event.root.type == EventType.STATE_ROOM_MEMBER &&
event.root.stateKey == session.myUserId) {
val content = event.root.content.toModel<RoomMemberContent>()
if (content?.membership == Membership.INVITE) {
hasReachedInvite = true

View file

@ -365,14 +365,14 @@ class MessageActionsViewModel @AssistedInject constructor(@Assisted
if (vectorPreferences.developerMode()) {
if (timelineEvent.isEncrypted() && timelineEvent.root.mCryptoError != null) {
val keysBackupService = session.cryptoService().keysBackupService()
if (keysBackupService.state == KeysBackupState.NotTrusted
|| (keysBackupService.state == KeysBackupState.ReadyToBackUp
&& keysBackupService.canRestoreKeys())
if (keysBackupService.state == KeysBackupState.NotTrusted ||
(keysBackupService.state == KeysBackupState.ReadyToBackUp &&
keysBackupService.canRestoreKeys())
) {
add(EventSharedAction.UseKeyBackup)
}
if (session.cryptoService().getCryptoDeviceInfo(session.myUserId).size > 1
|| timelineEvent.senderInfo.userId != session.myUserId) {
if (session.cryptoService().getCryptoDeviceInfo(session.myUserId).size > 1 ||
timelineEvent.senderInfo.userId != session.myUserId) {
add(EventSharedAction.ReRequestKey(timelineEvent.eventId))
}
}
@ -435,9 +435,9 @@ class MessageActionsViewModel @AssistedInject constructor(@Assisted
}
private fun canRetry(event: TimelineEvent, actionPermissions: ActionPermissions): Boolean {
return event.root.sendState.hasFailed()
&& actionPermissions.canSendMessage
&& (event.root.isAttachmentMessage() || event.root.isTextMessage())
return event.root.sendState.hasFailed() &&
actionPermissions.canSendMessage &&
(event.root.isAttachmentMessage() || event.root.isTextMessage())
}
private fun canViewReactions(event: TimelineEvent): Boolean {
@ -453,8 +453,8 @@ class MessageActionsViewModel @AssistedInject constructor(@Assisted
// TODO if user is admin or moderator
val messageContent = event.root.getClearContent().toModel<MessageContent>()
return event.root.senderId == myUserId && (
messageContent?.msgType == MessageType.MSGTYPE_TEXT
|| messageContent?.msgType == MessageType.MSGTYPE_EMOTE
messageContent?.msgType == MessageType.MSGTYPE_TEXT ||
messageContent?.msgType == MessageType.MSGTYPE_EMOTE
)
}

Some files were not shown because too many files have changed in this diff Show more