From 31ec8d39d800bea50e8d7c08e9dcb18c89a6fbf6 Mon Sep 17 00:00:00 2001 From: yostyle Date: Thu, 28 Oct 2021 17:36:27 +0200 Subject: [PATCH 001/291] Open url on external browser task --- .../java/im/vector/app/core/utils/ExternalApplicationsUtil.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/vector/src/main/java/im/vector/app/core/utils/ExternalApplicationsUtil.kt b/vector/src/main/java/im/vector/app/core/utils/ExternalApplicationsUtil.kt index bdaf520ba1..17e9e117a7 100644 --- a/vector/src/main/java/im/vector/app/core/utils/ExternalApplicationsUtil.kt +++ b/vector/src/main/java/im/vector/app/core/utils/ExternalApplicationsUtil.kt @@ -76,6 +76,8 @@ fun openUrlInExternalBrowser(context: Context, url: String?) { fun openUrlInExternalBrowser(context: Context, uri: Uri?) { uri?.let { val browserIntent = Intent(Intent.ACTION_VIEW, it).apply { + // Open activity on browser task and not on element task + flags = Intent.FLAG_ACTIVITY_NEW_TASK putExtra(Browser.EXTRA_APPLICATION_ID, context.packageName) putExtra(Browser.EXTRA_CREATE_NEW_TAB, true) } From dab866d1708dea533e815b3178abf02c72218337 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Wed, 2 Mar 2022 12:30:28 +0100 Subject: [PATCH 002/291] Forces soft logout to be true for testing --- vector/src/main/java/im/vector/app/features/MainActivity.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vector/src/main/java/im/vector/app/features/MainActivity.kt b/vector/src/main/java/im/vector/app/features/MainActivity.kt index 33b735551c..b7bbc4de8d 100644 --- a/vector/src/main/java/im/vector/app/features/MainActivity.kt +++ b/vector/src/main/java/im/vector/app/features/MainActivity.kt @@ -60,7 +60,7 @@ data class MainActivityArgs( val clearCredentials: Boolean = false, val isUserLoggedOut: Boolean = false, val isAccountDeactivated: Boolean = false, - val isSoftLogout: Boolean = false + val isSoftLogout: Boolean = true ) : Parcelable /** @@ -135,7 +135,7 @@ class MainActivity : VectorBaseActivity(), UnlockedActivity clearCredentials = argsFromIntent?.clearCredentials ?: false, isUserLoggedOut = argsFromIntent?.isUserLoggedOut ?: false, isAccountDeactivated = argsFromIntent?.isAccountDeactivated ?: false, - isSoftLogout = argsFromIntent?.isSoftLogout ?: false + isSoftLogout = argsFromIntent?.isSoftLogout ?: true ) } From 448e8e001fd4cb125efce69b1469926a6ce9d203 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Wed, 2 Mar 2022 14:51:22 +0100 Subject: [PATCH 003/291] Reimplements soft logout simulation --- .../org/matrix/android/sdk/internal/session/sync/SyncTask.kt | 2 ++ vector/src/main/java/im/vector/app/features/MainActivity.kt | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncTask.kt index b4da1a02cd..a110f73ad2 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncTask.kt @@ -18,6 +18,7 @@ package org.matrix.android.sdk.internal.session.sync import android.os.SystemClock import okhttp3.ResponseBody +import org.matrix.android.sdk.api.failure.GlobalError import org.matrix.android.sdk.api.logger.LoggerTag import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.initsync.InitSyncStep @@ -151,6 +152,7 @@ internal class DefaultSyncTask @Inject constructor( defaultSyncStatusService.setStatus(SyncStatusService.Status.IncrementalSyncIdle) val syncResponse = try { executeRequest(globalErrorReceiver) { + globalErrorReceiver.handleGlobalError(GlobalError.InvalidToken(softLogout = true)) syncAPI.sync( params = requestParams, readTimeOut = readTimeOut diff --git a/vector/src/main/java/im/vector/app/features/MainActivity.kt b/vector/src/main/java/im/vector/app/features/MainActivity.kt index b7bbc4de8d..33b735551c 100644 --- a/vector/src/main/java/im/vector/app/features/MainActivity.kt +++ b/vector/src/main/java/im/vector/app/features/MainActivity.kt @@ -60,7 +60,7 @@ data class MainActivityArgs( val clearCredentials: Boolean = false, val isUserLoggedOut: Boolean = false, val isAccountDeactivated: Boolean = false, - val isSoftLogout: Boolean = true + val isSoftLogout: Boolean = false ) : Parcelable /** @@ -135,7 +135,7 @@ class MainActivity : VectorBaseActivity(), UnlockedActivity clearCredentials = argsFromIntent?.clearCredentials ?: false, isUserLoggedOut = argsFromIntent?.isUserLoggedOut ?: false, isAccountDeactivated = argsFromIntent?.isAccountDeactivated ?: false, - isSoftLogout = argsFromIntent?.isSoftLogout ?: true + isSoftLogout = argsFromIntent?.isSoftLogout ?: false ) } From 12dc8a81126a1fab4492d3bfbb96d1b91f662d5e Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Wed, 2 Mar 2022 15:23:39 +0100 Subject: [PATCH 004/291] Tests sso login mode --- .../app/features/signout/soft/SoftLogoutController.kt | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt index 0cd9cde547..25011ebc8a 100644 --- a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt +++ b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt @@ -34,6 +34,7 @@ import im.vector.app.features.signout.soft.epoxy.loginRedButtonItem import im.vector.app.features.signout.soft.epoxy.loginTextItem import im.vector.app.features.signout.soft.epoxy.loginTitleItem import im.vector.app.features.signout.soft.epoxy.loginTitleSmallItem +import timber.log.Timber import javax.inject.Inject class SoftLogoutController @Inject constructor( @@ -102,6 +103,8 @@ class SoftLogoutController @Inject constructor( } } is Success -> { + val loginMode = state.asyncHomeServerLoginFlowRequest.invoke() + Timber.i("Login Mode: $loginMode") when (state.asyncHomeServerLoginFlowRequest.invoke()) { LoginMode.Password -> { loginPasswordFormItem { @@ -123,6 +126,11 @@ class SoftLogoutController @Inject constructor( } } is LoginMode.SsoAndPassword -> { + loginCenterButtonItem { + id("sso") + text(host.stringProvider.getString(R.string.login_signin_sso)) + listener { host.listener?.signinFallbackSubmit() } + } } LoginMode.Unsupported -> { loginCenterButtonItem { From 209a442d5baf1fd8190ecbd932f444f733fc55a1 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Thu, 3 Mar 2022 10:55:51 +0100 Subject: [PATCH 005/291] Adds LoginType to SessionParams and its entity --- .../sdk/api/auth/data/SessionParams.kt | 9 +++++- .../internal/auth/db/SessionParamsEntity.kt | 3 +- .../internal/auth/db/SessionParamsMapper.kt | 7 ++-- .../sdk/internal/auth/login/LoginType.kt | 32 +++++++++++++++++++ 4 files changed, 47 insertions(+), 4 deletions(-) create mode 100644 matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt index b490ac877e..5d70bccb08 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt @@ -16,6 +16,8 @@ package org.matrix.android.sdk.api.auth.data +import org.matrix.android.sdk.internal.auth.login.LoginType + /** * This data class holds necessary data to open a session. * You don't have to manually instantiate it. @@ -34,7 +36,12 @@ data class SessionParams( /** * Set to false if the current token is not valid anymore. Application should not have to use this info. */ - val isTokenValid: Boolean + val isTokenValid: Boolean, + + /** + * Which authentication method was used to create the session + */ + val loginType: LoginType, ) { /* * Shortcuts. Usually the application should only need to use these shortcuts diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsEntity.kt index ba1ab8147b..46d54a3873 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsEntity.kt @@ -26,5 +26,6 @@ internal open class SessionParamsEntity( var homeServerConnectionConfigJson: String = "", // Set to false when the token is invalid and the user has been soft logged out // In case of hard logout, this object is deleted from DB - var isTokenValid: Boolean = true + var isTokenValid: Boolean = true, + var loginType: String, ) : RealmObject() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapper.kt index 147c0e8be0..e359577ff3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapper.kt @@ -21,6 +21,7 @@ import org.matrix.android.sdk.api.auth.data.Credentials import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.api.auth.data.SessionParams import org.matrix.android.sdk.api.auth.data.sessionId +import org.matrix.android.sdk.internal.auth.login.LoginType import javax.inject.Inject internal class SessionParamsMapper @Inject constructor(moshi: Moshi) { @@ -37,7 +38,7 @@ internal class SessionParamsMapper @Inject constructor(moshi: Moshi) { if (credentials == null || homeServerConnectionConfig == null) { return null } - return SessionParams(credentials, homeServerConnectionConfig, entity.isTokenValid) + return SessionParams(credentials, homeServerConnectionConfig, entity.isTokenValid, LoginType.fromValue(entity.loginType)) } fun map(sessionParams: SessionParams?): SessionParamsEntity? { @@ -54,6 +55,8 @@ internal class SessionParamsMapper @Inject constructor(moshi: Moshi) { sessionParams.userId, credentialsJson, homeServerConnectionConfigJson, - sessionParams.isTokenValid) + sessionParams.isTokenValid, + sessionParams.loginType.value, + ) } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt new file mode 100644 index 0000000000..a5f6ebd2f8 --- /dev/null +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.internal.auth.login + +enum class LoginType(val value: String) { + PASSWORD("password"), + SSO("sso"), + UNKNOWN("unknown"); + + companion object { + + fun fromValue(value: String) = when (value) { + PASSWORD.value -> PASSWORD + SSO.value -> SSO + else -> UNKNOWN + } + } +} From 25e73e5bd083cd7c621740c4592fa1906bddada9 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Thu, 3 Mar 2022 10:56:07 +0100 Subject: [PATCH 006/291] Adds SessionParamsMapper tests --- .../auth/db/SessionParamsMapperTest.kt | 146 ++++++++++++++++++ .../sdk/test/fixtures/CredentialsFixture.kt | 38 +++++ .../fixtures/SessionParamsEntityFixture.kt | 37 +++++ .../sdk/test/fixtures/SessionParamsFixture.kt | 37 +++++ 4 files changed, 258 insertions(+) create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/CredentialsFixture.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsEntityFixture.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt new file mode 100644 index 0000000000..ac01441588 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.internal.auth.db + +import com.squareup.moshi.JsonAdapter +import com.squareup.moshi.Moshi +import io.mockk.every +import io.mockk.mockk +import org.amshove.kluent.shouldBeEqualTo +import org.amshove.kluent.shouldBeNull +import org.junit.Before +import org.junit.Test +import org.matrix.android.sdk.api.auth.data.Credentials +import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig +import org.matrix.android.sdk.api.auth.data.SessionParams +import org.matrix.android.sdk.api.auth.data.sessionId +import org.matrix.android.sdk.internal.auth.login.LoginType +import org.matrix.android.sdk.test.fixtures.SessionParamsEntityFixture.aSessionParamsEntity +import org.matrix.android.sdk.test.fixtures.SessionParamsFixture.aSessionParams + +class SessionParamsMapperTest { + + private val moshi: Moshi = mockk() + private lateinit var sessionParamsMapper: SessionParamsMapper + + private val credentialsAdapter: JsonAdapter = mockk() + private val homeServerConnectionAdapter: JsonAdapter = mockk() + + @Before + fun setup() { + every { moshi.adapter(Credentials::class.java) } returns mockk() + every { moshi.adapter(HomeServerConnectionConfig::class.java) } returns mockk() + sessionParamsMapper = SessionParamsMapper(moshi) + + every { credentialsAdapter.fromJson(sessionParamsEntity.credentialsJson) } returns credentials + every { homeServerConnectionAdapter.fromJson(sessionParamsEntity.homeServerConnectionConfigJson) } returns homeServerConnectionConfig + every { credentialsAdapter.toJson(sessionParams.credentials) } returns CREDENTIALS_JSON + every { homeServerConnectionAdapter.toJson(sessionParams.homeServerConnectionConfig) } returns HOME_SERVER_CONNECTION_CONFIG_JSON + } + + @Test + fun `when mapping entity, then map as SessionParams`() { + + val output = sessionParamsMapper.map(sessionParamsEntity)!! + + output shouldBeEqualTo SessionParams( + credentials, + homeServerConnectionConfig, + sessionParamsEntity.isTokenValid, + LoginType.fromValue(sessionParamsEntity.loginType) + ) + } + + @Test + fun `given null input, when mapping entity, then return null`() { + val nullEntity: SessionParamsEntity? = null + + val output = sessionParamsMapper.map(nullEntity) + + output.shouldBeNull() + } + + @Test + fun `given null credentials, when mapping entity, then return null`() { + every { credentialsAdapter.fromJson(sessionParamsEntity.credentialsJson) } returns null + + val output = sessionParamsMapper.map(sessionParamsEntity) + + output.shouldBeNull() + } + + @Test + fun `given null homeServerConnectionConfig, when mapping entity, then return null`() { + every { homeServerConnectionAdapter.fromJson(sessionParamsEntity.homeServerConnectionConfigJson) } returns null + + val output = sessionParamsMapper.map(sessionParamsEntity) + + output.shouldBeNull() + } + + @Test + fun `when mapping sessionParams, then map as SessionParamsEntity`() { + + val output = sessionParamsMapper.map(sessionParams) + + output shouldBeEqualTo SessionParamsEntity( + sessionParams.credentials.sessionId(), + sessionParams.userId, + CREDENTIALS_JSON, + HOME_SERVER_CONNECTION_CONFIG_JSON, + sessionParams.isTokenValid, + sessionParams.loginType.value, + ) + } + + @Test + fun `given null input, when mapping sessionParams, then return null`() { + val nullSessionParams: SessionParams? = null + + val output = sessionParamsMapper.map(nullSessionParams) + + output.shouldBeNull() + } + + @Test + fun `given null credentials json, when mapping sessionParams, then return null`() { + every { credentialsAdapter.toJson(credentials) } returns null + + val output = sessionParamsMapper.map(sessionParams) + + output.shouldBeNull() + } + + @Test + fun `given null homeServerConnectionConfig json, when mapping sessionParams, then return null`() { + every { homeServerConnectionAdapter.toJson(homeServerConnectionConfig) } returns null + + val output = sessionParamsMapper.map(sessionParams) + + output.shouldBeNull() + } + + companion object { + private val sessionParamsEntity = aSessionParamsEntity() + private val sessionParams = aSessionParams() + + private val credentials: Credentials = mockk() + private val homeServerConnectionConfig: HomeServerConnectionConfig = mockk() + private const val CREDENTIALS_JSON = "credentials_json" + private const val HOME_SERVER_CONNECTION_CONFIG_JSON = "home_server_connection_config_json" + } +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/CredentialsFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/CredentialsFixture.kt new file mode 100644 index 0000000000..5002fe9153 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/CredentialsFixture.kt @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fixtures + +import org.matrix.android.sdk.api.auth.data.Credentials +import org.matrix.android.sdk.api.auth.data.DiscoveryInformation + +object CredentialsFixture { + fun aCredentials( + userId: String = "", + accessToken: String = "", + refreshToken: String? = null, + homeServer: String? = null, + deviceId: String? = null, + discoveryInformation: DiscoveryInformation? = null, + ) = Credentials( + userId, + accessToken, + refreshToken, + homeServer, + deviceId, + discoveryInformation, + ) +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsEntityFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsEntityFixture.kt new file mode 100644 index 0000000000..29b5b1a7c9 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsEntityFixture.kt @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fixtures + +import org.matrix.android.sdk.internal.auth.db.SessionParamsEntity + +internal object SessionParamsEntityFixture { + fun aSessionParamsEntity( + sessionId: String = "", + userId: String = "", + credentialsJson: String = "", + homeServerConnectionConfigJson: String = "", + isTokenValid: Boolean = true, + loginType: String = "", + ) = SessionParamsEntity( + sessionId, + userId, + credentialsJson, + homeServerConnectionConfigJson, + isTokenValid, + loginType, + ) +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt new file mode 100644 index 0000000000..387727e8f0 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fixtures + +import org.matrix.android.sdk.api.auth.data.Credentials +import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig +import org.matrix.android.sdk.api.auth.data.SessionParams +import org.matrix.android.sdk.internal.auth.login.LoginType +import org.matrix.android.sdk.test.fixtures.CredentialsFixture.aCredentials + +object SessionParamsFixture { + fun aSessionParams( + credentials: Credentials = aCredentials(), + homeServerConnectionConfig: HomeServerConnectionConfig = HomeServerConnectionConfig.Builder().build(), + isTokenValid: Boolean = false, + loginType: LoginType = LoginType.UNKNOWN, + ) = SessionParams( + credentials, + homeServerConnectionConfig, + isTokenValid, + loginType, + ) +} From 187502c358ba1358ee7950321338bf59197de8e5 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Thu, 3 Mar 2022 11:32:23 +0100 Subject: [PATCH 007/291] Refactors SessionParamsMapperTest by adding fake moshi --- .../auth/db/SessionParamsMapperTest.kt | 88 ++++---------- .../fakes/FakeSessionParamsMapperMoshi.kt | 112 ++++++++++++++++++ 2 files changed, 133 insertions(+), 67 deletions(-) create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/FakeSessionParamsMapperMoshi.kt diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt index ac01441588..26154e7d1a 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt @@ -16,80 +16,52 @@ package org.matrix.android.sdk.internal.auth.db -import com.squareup.moshi.JsonAdapter -import com.squareup.moshi.Moshi import io.mockk.every -import io.mockk.mockk -import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeNull -import org.junit.Before import org.junit.Test -import org.matrix.android.sdk.api.auth.data.Credentials -import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig -import org.matrix.android.sdk.api.auth.data.SessionParams -import org.matrix.android.sdk.api.auth.data.sessionId -import org.matrix.android.sdk.internal.auth.login.LoginType -import org.matrix.android.sdk.test.fixtures.SessionParamsEntityFixture.aSessionParamsEntity -import org.matrix.android.sdk.test.fixtures.SessionParamsFixture.aSessionParams +import org.matrix.android.sdk.test.fakes.FakeSessionParamsMapperMoshi +import org.matrix.android.sdk.test.fakes.FakeSessionParamsMapperMoshi.Companion.nullSessionParams +import org.matrix.android.sdk.test.fakes.FakeSessionParamsMapperMoshi.Companion.nullSessionParamsEntity +import org.matrix.android.sdk.test.fakes.FakeSessionParamsMapperMoshi.Companion.sessionParams +import org.matrix.android.sdk.test.fakes.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity class SessionParamsMapperTest { - private val moshi: Moshi = mockk() - private lateinit var sessionParamsMapper: SessionParamsMapper - - private val credentialsAdapter: JsonAdapter = mockk() - private val homeServerConnectionAdapter: JsonAdapter = mockk() - - @Before - fun setup() { - every { moshi.adapter(Credentials::class.java) } returns mockk() - every { moshi.adapter(HomeServerConnectionConfig::class.java) } returns mockk() - sessionParamsMapper = SessionParamsMapper(moshi) - - every { credentialsAdapter.fromJson(sessionParamsEntity.credentialsJson) } returns credentials - every { homeServerConnectionAdapter.fromJson(sessionParamsEntity.homeServerConnectionConfigJson) } returns homeServerConnectionConfig - every { credentialsAdapter.toJson(sessionParams.credentials) } returns CREDENTIALS_JSON - every { homeServerConnectionAdapter.toJson(sessionParams.homeServerConnectionConfig) } returns HOME_SERVER_CONNECTION_CONFIG_JSON - } + private val fakeMoshi = FakeSessionParamsMapperMoshi() + private val sessionParamsMapper = SessionParamsMapper(fakeMoshi.instance) @Test fun `when mapping entity, then map as SessionParams`() { - val output = sessionParamsMapper.map(sessionParamsEntity)!! + val output = sessionParamsMapper.map(sessionParamsEntity) - output shouldBeEqualTo SessionParams( - credentials, - homeServerConnectionConfig, - sessionParamsEntity.isTokenValid, - LoginType.fromValue(sessionParamsEntity.loginType) - ) + fakeMoshi.assertSessionParamsWasMappedSuccessfully(output) } @Test fun `given null input, when mapping entity, then return null`() { - val nullEntity: SessionParamsEntity? = null - val output = sessionParamsMapper.map(nullEntity) + val output = sessionParamsMapper.map(nullSessionParamsEntity) - output.shouldBeNull() + fakeMoshi.assertSessionParamsIsNull(output) } @Test fun `given null credentials, when mapping entity, then return null`() { - every { credentialsAdapter.fromJson(sessionParamsEntity.credentialsJson) } returns null + fakeMoshi.givenCredentialsFromJsonIsNull() val output = sessionParamsMapper.map(sessionParamsEntity) - output.shouldBeNull() + fakeMoshi.assertSessionParamsIsNull(output) } @Test fun `given null homeServerConnectionConfig, when mapping entity, then return null`() { - every { homeServerConnectionAdapter.fromJson(sessionParamsEntity.homeServerConnectionConfigJson) } returns null + fakeMoshi.givenHomeServerConnectionConfigFromJsonIsNull() val output = sessionParamsMapper.map(sessionParamsEntity) - output.shouldBeNull() + fakeMoshi.assertSessionParamsIsNull(output) } @Test @@ -97,50 +69,32 @@ class SessionParamsMapperTest { val output = sessionParamsMapper.map(sessionParams) - output shouldBeEqualTo SessionParamsEntity( - sessionParams.credentials.sessionId(), - sessionParams.userId, - CREDENTIALS_JSON, - HOME_SERVER_CONNECTION_CONFIG_JSON, - sessionParams.isTokenValid, - sessionParams.loginType.value, - ) + fakeMoshi.assertSessionParamsEntityWasMappedSuccessfully(output) } @Test fun `given null input, when mapping sessionParams, then return null`() { - val nullSessionParams: SessionParams? = null val output = sessionParamsMapper.map(nullSessionParams) - output.shouldBeNull() + fakeMoshi.assertSessionParamsEntityWasMappedSuccessfully(output) } @Test fun `given null credentials json, when mapping sessionParams, then return null`() { - every { credentialsAdapter.toJson(credentials) } returns null + fakeMoshi.givenCredentialsToJsonIsNull() val output = sessionParamsMapper.map(sessionParams) - output.shouldBeNull() + fakeMoshi.assertSessionParamsEntityIsNull(output) } @Test fun `given null homeServerConnectionConfig json, when mapping sessionParams, then return null`() { - every { homeServerConnectionAdapter.toJson(homeServerConnectionConfig) } returns null + fakeMoshi.givenHomeServerConnectionConfigToJsonIsNull() val output = sessionParamsMapper.map(sessionParams) - output.shouldBeNull() - } - - companion object { - private val sessionParamsEntity = aSessionParamsEntity() - private val sessionParams = aSessionParams() - - private val credentials: Credentials = mockk() - private val homeServerConnectionConfig: HomeServerConnectionConfig = mockk() - private const val CREDENTIALS_JSON = "credentials_json" - private const val HOME_SERVER_CONNECTION_CONFIG_JSON = "home_server_connection_config_json" + fakeMoshi.assertSessionParamsEntityIsNull(output) } } diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/FakeSessionParamsMapperMoshi.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/FakeSessionParamsMapperMoshi.kt new file mode 100644 index 0000000000..2d5dc8222b --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/FakeSessionParamsMapperMoshi.kt @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fakes + +import com.squareup.moshi.JsonAdapter +import com.squareup.moshi.Moshi +import io.mockk.every +import io.mockk.mockk +import org.amshove.kluent.shouldBeEqualTo +import org.amshove.kluent.shouldBeNull +import org.matrix.android.sdk.api.auth.data.Credentials +import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig +import org.matrix.android.sdk.api.auth.data.SessionParams +import org.matrix.android.sdk.api.auth.data.sessionId +import org.matrix.android.sdk.internal.auth.db.SessionParamsEntity +import org.matrix.android.sdk.internal.auth.login.LoginType +import org.matrix.android.sdk.test.fixtures.SessionParamsEntityFixture.aSessionParamsEntity +import org.matrix.android.sdk.test.fixtures.SessionParamsFixture.aSessionParams + +internal class FakeSessionParamsMapperMoshi { + + val instance: Moshi = mockk() + private val credentialsAdapter: JsonAdapter = mockk() + private val homeServerConnectionConfigAdapter: JsonAdapter = mockk() + + init { + stubAdapters() + stubJsonConversions() + } + + private fun stubAdapters() { + every { instance.adapter(Credentials::class.java) } returns credentialsAdapter + every { instance.adapter(HomeServerConnectionConfig::class.java) } returns homeServerConnectionConfigAdapter + } + + private fun stubJsonConversions() { + every { credentialsAdapter.fromJson(sessionParamsEntity.credentialsJson) } returns credentials + every { homeServerConnectionConfigAdapter.fromJson(sessionParamsEntity.homeServerConnectionConfigJson) } returns homeServerConnectionConfig + every { credentialsAdapter.toJson(sessionParams.credentials) } returns CREDENTIALS_JSON + every { homeServerConnectionConfigAdapter.toJson(sessionParams.homeServerConnectionConfig) } returns HOME_SERVER_CONNECTION_CONFIG_JSON + } + + fun givenCredentialsFromJsonIsNull() { + every { credentialsAdapter.fromJson(sessionParamsEntity.credentialsJson) } returns null + } + + fun givenHomeServerConnectionConfigFromJsonIsNull() { + every { homeServerConnectionConfigAdapter.fromJson(sessionParamsEntity.homeServerConnectionConfigJson) } returns null + } + + fun givenCredentialsToJsonIsNull() { + every { credentialsAdapter.toJson(credentials) } returns null + } + + fun givenHomeServerConnectionConfigToJsonIsNull() { + every { homeServerConnectionConfigAdapter.toJson(homeServerConnectionConfig) } returns null + } + + fun assertSessionParamsWasMappedSuccessfully(sessionParams: SessionParams?) { + sessionParams shouldBeEqualTo SessionParams( + credentials, + homeServerConnectionConfig, + sessionParamsEntity.isTokenValid, + LoginType.fromValue(sessionParamsEntity.loginType) + ) + } + + fun assertSessionParamsIsNull(sessionParams: SessionParams?) { + sessionParams.shouldBeNull() + } + + fun assertSessionParamsEntityWasMappedSuccessfully(sessionParamsEntity: SessionParamsEntity?) { + sessionParamsEntity shouldBeEqualTo SessionParamsEntity( + sessionParams.credentials.sessionId(), + sessionParams.userId, + CREDENTIALS_JSON, + HOME_SERVER_CONNECTION_CONFIG_JSON, + sessionParams.isTokenValid, + sessionParams.loginType.value, + ) + } + + fun assertSessionParamsEntityIsNull(sessionParamsEntity: SessionParamsEntity?) { + sessionParamsEntity.shouldBeNull() + } + + companion object { + val sessionParams = aSessionParams() + val sessionParamsEntity = aSessionParamsEntity() + val nullSessionParams: SessionParams? = null + val nullSessionParamsEntity: SessionParamsEntity? = null + + private val credentials: Credentials = mockk() + private val homeServerConnectionConfig: HomeServerConnectionConfig = mockk() + private const val CREDENTIALS_JSON = "credentials_json" + private const val HOME_SERVER_CONNECTION_CONFIG_JSON = "home_server_connection_config_json" + } +} From d33081c349df58642db4cca4ade932b130de210b Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Thu, 3 Mar 2022 11:47:31 +0100 Subject: [PATCH 008/291] Refactors SessionParamsMapperTest by adding fake json adapters --- .../auth/db/SessionParamsMapperTest.kt | 28 +++++------ .../FakeCredentialsJsonAdapter.kt | 45 +++++++++++++++++ ...keHomeServerConnectionConfigJsonAdapter.kt | 47 ++++++++++++++++++ .../FakeSessionParamsMapperMoshi.kt | 48 ++++--------------- 4 files changed, 114 insertions(+), 54 deletions(-) create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeCredentialsJsonAdapter.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt rename matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/{ => sessionparams}/FakeSessionParamsMapperMoshi.kt (59%) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt index 26154e7d1a..e496201d08 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt @@ -16,14 +16,12 @@ package org.matrix.android.sdk.internal.auth.db -import io.mockk.every -import org.amshove.kluent.shouldBeNull import org.junit.Test -import org.matrix.android.sdk.test.fakes.FakeSessionParamsMapperMoshi -import org.matrix.android.sdk.test.fakes.FakeSessionParamsMapperMoshi.Companion.nullSessionParams -import org.matrix.android.sdk.test.fakes.FakeSessionParamsMapperMoshi.Companion.nullSessionParamsEntity -import org.matrix.android.sdk.test.fakes.FakeSessionParamsMapperMoshi.Companion.sessionParams -import org.matrix.android.sdk.test.fakes.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity +import org.matrix.android.sdk.test.fakes.sessionparams.FakeSessionParamsMapperMoshi +import org.matrix.android.sdk.test.fakes.sessionparams.FakeSessionParamsMapperMoshi.Companion.nullSessionParams +import org.matrix.android.sdk.test.fakes.sessionparams.FakeSessionParamsMapperMoshi.Companion.nullSessionParamsEntity +import org.matrix.android.sdk.test.fakes.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams +import org.matrix.android.sdk.test.fakes.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity class SessionParamsMapperTest { @@ -47,8 +45,8 @@ class SessionParamsMapperTest { } @Test - fun `given null credentials, when mapping entity, then return null`() { - fakeMoshi.givenCredentialsFromJsonIsNull() + fun `given null credentials json deserialization, when mapping entity, then return null`() { + fakeMoshi.credentialsJsonAdapter.givenNullDeserialization() val output = sessionParamsMapper.map(sessionParamsEntity) @@ -56,8 +54,8 @@ class SessionParamsMapperTest { } @Test - fun `given null homeServerConnectionConfig, when mapping entity, then return null`() { - fakeMoshi.givenHomeServerConnectionConfigFromJsonIsNull() + fun `given null homeServerConnectionConfig json deserialization, when mapping entity, then return null`() { + fakeMoshi.homeServerConnectionConfigAdapter.givenNullDeserialization() val output = sessionParamsMapper.map(sessionParamsEntity) @@ -81,8 +79,8 @@ class SessionParamsMapperTest { } @Test - fun `given null credentials json, when mapping sessionParams, then return null`() { - fakeMoshi.givenCredentialsToJsonIsNull() + fun `given null credentials json serialization, when mapping sessionParams, then return null`() { + fakeMoshi.credentialsJsonAdapter.givenNullSerialization() val output = sessionParamsMapper.map(sessionParams) @@ -90,8 +88,8 @@ class SessionParamsMapperTest { } @Test - fun `given null homeServerConnectionConfig json, when mapping sessionParams, then return null`() { - fakeMoshi.givenHomeServerConnectionConfigToJsonIsNull() + fun `given null homeServerConnectionConfig json serialization, when mapping sessionParams, then return null`() { + fakeMoshi.homeServerConnectionConfigAdapter.givenNullSerialization() val output = sessionParamsMapper.map(sessionParams) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeCredentialsJsonAdapter.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeCredentialsJsonAdapter.kt new file mode 100644 index 0000000000..a7c5281687 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeCredentialsJsonAdapter.kt @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fakes.sessionparams + +import com.squareup.moshi.JsonAdapter +import io.mockk.every +import io.mockk.mockk +import org.matrix.android.sdk.api.auth.data.Credentials + +internal class FakeCredentialsJsonAdapter { + + val instance: JsonAdapter = mockk() + + init { + every { instance.fromJson(FakeSessionParamsMapperMoshi.sessionParamsEntity.credentialsJson) } returns credentials + every { instance.toJson(FakeSessionParamsMapperMoshi.sessionParams.credentials) } returns CREDENTIALS_JSON + } + + fun givenNullDeserialization() { + every { instance.fromJson(FakeSessionParamsMapperMoshi.sessionParamsEntity.credentialsJson) } returns null + } + + fun givenNullSerialization() { + every { instance.toJson(credentials) } returns null + } + + companion object { + val credentials: Credentials = mockk() + const val CREDENTIALS_JSON = "credentials_json" + } +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt new file mode 100644 index 0000000000..50af9bd9ea --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fakes.sessionparams + +import com.squareup.moshi.JsonAdapter +import io.mockk.every +import io.mockk.mockk +import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig +import org.matrix.android.sdk.test.fakes.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams +import org.matrix.android.sdk.test.fakes.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity + +internal class FakeHomeServerConnectionConfigJsonAdapter { + + val instance: JsonAdapter = mockk() + + init { + every { instance.fromJson(sessionParamsEntity.homeServerConnectionConfigJson) } returns homeServerConnectionConfig + every { instance.toJson(sessionParams.homeServerConnectionConfig) } returns HOME_SERVER_CONNECTION_CONFIG_JSON + } + + fun givenNullDeserialization() { + every { instance.fromJson(sessionParamsEntity.credentialsJson) } returns null + } + + fun givenNullSerialization() { + every { instance.toJson(homeServerConnectionConfig) } returns null + } + + companion object { + val homeServerConnectionConfig: HomeServerConnectionConfig = mockk() + const val HOME_SERVER_CONNECTION_CONFIG_JSON = "home_server_connection_config_json" + } +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/FakeSessionParamsMapperMoshi.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeSessionParamsMapperMoshi.kt similarity index 59% rename from matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/FakeSessionParamsMapperMoshi.kt rename to matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeSessionParamsMapperMoshi.kt index 2d5dc8222b..7dc0df94b6 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/FakeSessionParamsMapperMoshi.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeSessionParamsMapperMoshi.kt @@ -14,9 +14,8 @@ * limitations under the License. */ -package org.matrix.android.sdk.test.fakes +package org.matrix.android.sdk.test.fakes.sessionparams -import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import io.mockk.every import io.mockk.mockk @@ -28,46 +27,22 @@ import org.matrix.android.sdk.api.auth.data.SessionParams import org.matrix.android.sdk.api.auth.data.sessionId import org.matrix.android.sdk.internal.auth.db.SessionParamsEntity import org.matrix.android.sdk.internal.auth.login.LoginType +import org.matrix.android.sdk.test.fakes.sessionparams.FakeCredentialsJsonAdapter.Companion.CREDENTIALS_JSON +import org.matrix.android.sdk.test.fakes.sessionparams.FakeCredentialsJsonAdapter.Companion.credentials +import org.matrix.android.sdk.test.fakes.sessionparams.FakeHomeServerConnectionConfigJsonAdapter.Companion.HOME_SERVER_CONNECTION_CONFIG_JSON +import org.matrix.android.sdk.test.fakes.sessionparams.FakeHomeServerConnectionConfigJsonAdapter.Companion.homeServerConnectionConfig import org.matrix.android.sdk.test.fixtures.SessionParamsEntityFixture.aSessionParamsEntity import org.matrix.android.sdk.test.fixtures.SessionParamsFixture.aSessionParams internal class FakeSessionParamsMapperMoshi { val instance: Moshi = mockk() - private val credentialsAdapter: JsonAdapter = mockk() - private val homeServerConnectionConfigAdapter: JsonAdapter = mockk() + val credentialsJsonAdapter = FakeCredentialsJsonAdapter() + val homeServerConnectionConfigAdapter = FakeHomeServerConnectionConfigJsonAdapter() init { - stubAdapters() - stubJsonConversions() - } - - private fun stubAdapters() { - every { instance.adapter(Credentials::class.java) } returns credentialsAdapter - every { instance.adapter(HomeServerConnectionConfig::class.java) } returns homeServerConnectionConfigAdapter - } - - private fun stubJsonConversions() { - every { credentialsAdapter.fromJson(sessionParamsEntity.credentialsJson) } returns credentials - every { homeServerConnectionConfigAdapter.fromJson(sessionParamsEntity.homeServerConnectionConfigJson) } returns homeServerConnectionConfig - every { credentialsAdapter.toJson(sessionParams.credentials) } returns CREDENTIALS_JSON - every { homeServerConnectionConfigAdapter.toJson(sessionParams.homeServerConnectionConfig) } returns HOME_SERVER_CONNECTION_CONFIG_JSON - } - - fun givenCredentialsFromJsonIsNull() { - every { credentialsAdapter.fromJson(sessionParamsEntity.credentialsJson) } returns null - } - - fun givenHomeServerConnectionConfigFromJsonIsNull() { - every { homeServerConnectionConfigAdapter.fromJson(sessionParamsEntity.homeServerConnectionConfigJson) } returns null - } - - fun givenCredentialsToJsonIsNull() { - every { credentialsAdapter.toJson(credentials) } returns null - } - - fun givenHomeServerConnectionConfigToJsonIsNull() { - every { homeServerConnectionConfigAdapter.toJson(homeServerConnectionConfig) } returns null + every { instance.adapter(Credentials::class.java) } returns credentialsJsonAdapter.instance + every { instance.adapter(HomeServerConnectionConfig::class.java) } returns homeServerConnectionConfigAdapter.instance } fun assertSessionParamsWasMappedSuccessfully(sessionParams: SessionParams?) { @@ -103,10 +78,5 @@ internal class FakeSessionParamsMapperMoshi { val sessionParamsEntity = aSessionParamsEntity() val nullSessionParams: SessionParams? = null val nullSessionParamsEntity: SessionParamsEntity? = null - - private val credentials: Credentials = mockk() - private val homeServerConnectionConfig: HomeServerConnectionConfig = mockk() - private const val CREDENTIALS_JSON = "credentials_json" - private const val HOME_SERVER_CONNECTION_CONFIG_JSON = "home_server_connection_config_json" } } From dffd568e14562bd6f2aef8920437953bfe1c4843 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Thu, 3 Mar 2022 13:14:49 +0100 Subject: [PATCH 009/291] Adds AuthTo005 realm migration --- .../internal/auth/db/AuthRealmMigration.kt | 4 +- .../internal/auth/db/SessionParamsEntity.kt | 2 +- .../auth/db/migration/MigrateAuthTo005.kt | 34 ++++++++++ .../auth/db/migration/MigrateAuthTo005Test.kt | 34 ++++++++++ .../sdk/test/fakes/Fake005MigrationRealm.kt | 68 +++++++++++++++++++ 5 files changed, 140 insertions(+), 2 deletions(-) create mode 100644 matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/Fake005MigrationRealm.kt diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/AuthRealmMigration.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/AuthRealmMigration.kt index 59b6471a05..486dcb918a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/AuthRealmMigration.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/AuthRealmMigration.kt @@ -22,6 +22,7 @@ import org.matrix.android.sdk.internal.auth.db.migration.MigrateAuthTo001 import org.matrix.android.sdk.internal.auth.db.migration.MigrateAuthTo002 import org.matrix.android.sdk.internal.auth.db.migration.MigrateAuthTo003 import org.matrix.android.sdk.internal.auth.db.migration.MigrateAuthTo004 +import org.matrix.android.sdk.internal.auth.db.migration.MigrateAuthTo005 import timber.log.Timber import javax.inject.Inject @@ -33,7 +34,7 @@ internal class AuthRealmMigration @Inject constructor() : RealmMigration { override fun equals(other: Any?) = other is AuthRealmMigration override fun hashCode() = 4000 - val schemaVersion = 4L + val schemaVersion = 5L override fun migrate(realm: DynamicRealm, oldVersion: Long, newVersion: Long) { Timber.d("Migrating Auth Realm from $oldVersion to $newVersion") @@ -42,5 +43,6 @@ internal class AuthRealmMigration @Inject constructor() : RealmMigration { if (oldVersion < 2) MigrateAuthTo002(realm).perform() if (oldVersion < 3) MigrateAuthTo003(realm).perform() if (oldVersion < 4) MigrateAuthTo004(realm).perform() + if (oldVersion < 5) MigrateAuthTo005(realm).perform() } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsEntity.kt index 46d54a3873..f6c883cac0 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsEntity.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsEntity.kt @@ -27,5 +27,5 @@ internal open class SessionParamsEntity( // Set to false when the token is invalid and the user has been soft logged out // In case of hard logout, this object is deleted from DB var isTokenValid: Boolean = true, - var loginType: String, + var loginType: String = "", ) : RealmObject() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt new file mode 100644 index 0000000000..ca3cffeaae --- /dev/null +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.internal.auth.db.migration + +import io.realm.DynamicRealm +import org.matrix.android.sdk.internal.auth.db.SessionParamsEntityFields +import org.matrix.android.sdk.internal.auth.login.LoginType +import org.matrix.android.sdk.internal.util.database.RealmMigrator +import timber.log.Timber + +class MigrateAuthTo005(realm: DynamicRealm) : RealmMigrator(realm, 5) { + + override fun doMigrate(realm: DynamicRealm) { + Timber.d("Update SessionParamsEntity to add LoginType") + + realm.schema.get("SessionParamsEntity") + ?.addField(SessionParamsEntityFields.LOGIN_TYPE, String::class.java) + ?.transform { it.set(SessionParamsEntityFields.LOGIN_TYPE, LoginType.UNKNOWN.value) } + } +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt new file mode 100644 index 0000000000..da58863e3b --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.internal.auth.db.migration + +import org.junit.Test +import org.matrix.android.sdk.test.fakes.Fake005MigrationRealm + +class MigrateAuthTo005Test { + + private val fakeRealm = Fake005MigrationRealm() + private val migrator = MigrateAuthTo005(fakeRealm.instance) + + @Test + fun `when doMigrate, then LoginType field added`() { + + migrator.doMigrate(fakeRealm.instance) + + fakeRealm.verifyLoginTypeAdded() + } +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/Fake005MigrationRealm.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/Fake005MigrationRealm.kt new file mode 100644 index 0000000000..6ccbec03e0 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/Fake005MigrationRealm.kt @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fakes + +import io.mockk.every +import io.mockk.mockk +import io.mockk.slot +import io.mockk.verify +import io.mockk.verifyOrder +import io.realm.DynamicRealm +import io.realm.DynamicRealmObject +import io.realm.RealmObjectSchema +import io.realm.RealmSchema +import org.matrix.android.sdk.internal.auth.db.SessionParamsEntityFields +import org.matrix.android.sdk.internal.auth.login.LoginType + +class Fake005MigrationRealm { + + val instance: DynamicRealm = mockk() + + private val schema: RealmSchema = mockk() + private val objectSchema: RealmObjectSchema = mockk() + + init { + every { instance.schema } returns schema + every { schema.get("SessionParamsEntity") } returns objectSchema + every { objectSchema.addField(any(), any()) } returns objectSchema + every { objectSchema.transform(any()) } returns objectSchema + } + + fun verifyLoginTypeAdded() { + transformFunctionSlot.clear() + verifyLoginTypeFieldAddedAndTransformed() + verifyTransformationSetsUnknownLoginType() + } + + private fun verifyLoginTypeFieldAddedAndTransformed() { + verifyOrder { + objectSchema["SessionParamsEntity"] + objectSchema.addField(SessionParamsEntityFields.LOGIN_TYPE, String::class.java) + objectSchema.transform(capture(transformFunctionSlot)) + } + } + + private fun verifyTransformationSetsUnknownLoginType() { + val dynamicRealmObject: DynamicRealmObject = mockk() + transformFunctionSlot.captured.invoke(dynamicRealmObject) + verify { dynamicRealmObject.set(SessionParamsEntityFields.LOGIN_TYPE, LoginType.UNKNOWN.value) } + } + + companion object { + private val transformFunctionSlot = slot<(DynamicRealmObject) -> Unit>() + } +} From b82efe95bddcc815d6cc30ed7badfa62bf47ce04 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Thu, 3 Mar 2022 13:18:02 +0100 Subject: [PATCH 010/291] Moves test packages --- .../sdk/internal/auth/db/SessionParamsMapperTest.kt | 10 +++++----- .../internal/auth/db/migration/MigrateAuthTo005Test.kt | 2 +- .../{ => auth/db/migration}/Fake005MigrationRealm.kt | 2 +- .../db}/sessionparams/FakeCredentialsJsonAdapter.kt | 2 +- .../FakeHomeServerConnectionConfigJsonAdapter.kt | 6 +++--- .../db}/sessionparams/FakeSessionParamsMapperMoshi.kt | 10 +++++----- 6 files changed, 16 insertions(+), 16 deletions(-) rename matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/{ => auth/db/migration}/Fake005MigrationRealm.kt (97%) rename matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/{ => auth/db}/sessionparams/FakeCredentialsJsonAdapter.kt (95%) rename matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/{ => auth/db}/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt (84%) rename matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/{ => auth/db}/sessionparams/FakeSessionParamsMapperMoshi.kt (83%) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt index e496201d08..ffacb4b4a5 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt @@ -17,11 +17,11 @@ package org.matrix.android.sdk.internal.auth.db import org.junit.Test -import org.matrix.android.sdk.test.fakes.sessionparams.FakeSessionParamsMapperMoshi -import org.matrix.android.sdk.test.fakes.sessionparams.FakeSessionParamsMapperMoshi.Companion.nullSessionParams -import org.matrix.android.sdk.test.fakes.sessionparams.FakeSessionParamsMapperMoshi.Companion.nullSessionParamsEntity -import org.matrix.android.sdk.test.fakes.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams -import org.matrix.android.sdk.test.fakes.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity +import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi +import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.nullSessionParams +import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.nullSessionParamsEntity +import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams +import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity class SessionParamsMapperTest { diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt index da58863e3b..efb7bce378 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt @@ -17,7 +17,7 @@ package org.matrix.android.sdk.internal.auth.db.migration import org.junit.Test -import org.matrix.android.sdk.test.fakes.Fake005MigrationRealm +import org.matrix.android.sdk.test.fakes.auth.db.migration.Fake005MigrationRealm class MigrateAuthTo005Test { diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/Fake005MigrationRealm.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/migration/Fake005MigrationRealm.kt similarity index 97% rename from matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/Fake005MigrationRealm.kt rename to matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/migration/Fake005MigrationRealm.kt index 6ccbec03e0..3f317fadf0 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/Fake005MigrationRealm.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/migration/Fake005MigrationRealm.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.matrix.android.sdk.test.fakes +package org.matrix.android.sdk.test.fakes.auth.db.migration import io.mockk.every import io.mockk.mockk diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeCredentialsJsonAdapter.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt similarity index 95% rename from matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeCredentialsJsonAdapter.kt rename to matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt index a7c5281687..bcec6d7efe 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeCredentialsJsonAdapter.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.matrix.android.sdk.test.fakes.sessionparams +package org.matrix.android.sdk.test.fakes.auth.db.sessionparams import com.squareup.moshi.JsonAdapter import io.mockk.every diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt similarity index 84% rename from matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt rename to matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt index 50af9bd9ea..4d0e6615c4 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt @@ -14,14 +14,14 @@ * limitations under the License. */ -package org.matrix.android.sdk.test.fakes.sessionparams +package org.matrix.android.sdk.test.fakes.auth.db.sessionparams import com.squareup.moshi.JsonAdapter import io.mockk.every import io.mockk.mockk import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig -import org.matrix.android.sdk.test.fakes.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams -import org.matrix.android.sdk.test.fakes.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity +import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams +import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity internal class FakeHomeServerConnectionConfigJsonAdapter { diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeSessionParamsMapperMoshi.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt similarity index 83% rename from matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeSessionParamsMapperMoshi.kt rename to matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt index 7dc0df94b6..6327c90565 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/sessionparams/FakeSessionParamsMapperMoshi.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.matrix.android.sdk.test.fakes.sessionparams +package org.matrix.android.sdk.test.fakes.auth.db.sessionparams import com.squareup.moshi.Moshi import io.mockk.every @@ -27,10 +27,10 @@ import org.matrix.android.sdk.api.auth.data.SessionParams import org.matrix.android.sdk.api.auth.data.sessionId import org.matrix.android.sdk.internal.auth.db.SessionParamsEntity import org.matrix.android.sdk.internal.auth.login.LoginType -import org.matrix.android.sdk.test.fakes.sessionparams.FakeCredentialsJsonAdapter.Companion.CREDENTIALS_JSON -import org.matrix.android.sdk.test.fakes.sessionparams.FakeCredentialsJsonAdapter.Companion.credentials -import org.matrix.android.sdk.test.fakes.sessionparams.FakeHomeServerConnectionConfigJsonAdapter.Companion.HOME_SERVER_CONNECTION_CONFIG_JSON -import org.matrix.android.sdk.test.fakes.sessionparams.FakeHomeServerConnectionConfigJsonAdapter.Companion.homeServerConnectionConfig +import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeCredentialsJsonAdapter.Companion.CREDENTIALS_JSON +import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeCredentialsJsonAdapter.Companion.credentials +import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeHomeServerConnectionConfigJsonAdapter.Companion.HOME_SERVER_CONNECTION_CONFIG_JSON +import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeHomeServerConnectionConfigJsonAdapter.Companion.homeServerConnectionConfig import org.matrix.android.sdk.test.fixtures.SessionParamsEntityFixture.aSessionParamsEntity import org.matrix.android.sdk.test.fixtures.SessionParamsFixture.aSessionParams From d3d99dd3bad9e5a7b07dabe320f1d2855f732540 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Thu, 3 Mar 2022 13:21:04 +0100 Subject: [PATCH 011/291] Replaces mocks with fixtures in fake json adapters --- .../db/sessionparams/FakeCredentialsJsonAdapter.kt | 11 +++++++---- .../FakeHomeServerConnectionConfigJsonAdapter.kt | 2 +- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt index bcec6d7efe..7c0d78f96d 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt @@ -20,18 +20,21 @@ import com.squareup.moshi.JsonAdapter import io.mockk.every import io.mockk.mockk import org.matrix.android.sdk.api.auth.data.Credentials +import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams +import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity +import org.matrix.android.sdk.test.fixtures.CredentialsFixture.aCredentials internal class FakeCredentialsJsonAdapter { val instance: JsonAdapter = mockk() init { - every { instance.fromJson(FakeSessionParamsMapperMoshi.sessionParamsEntity.credentialsJson) } returns credentials - every { instance.toJson(FakeSessionParamsMapperMoshi.sessionParams.credentials) } returns CREDENTIALS_JSON + every { instance.fromJson(sessionParamsEntity.credentialsJson) } returns credentials + every { instance.toJson(sessionParams.credentials) } returns CREDENTIALS_JSON } fun givenNullDeserialization() { - every { instance.fromJson(FakeSessionParamsMapperMoshi.sessionParamsEntity.credentialsJson) } returns null + every { instance.fromJson(sessionParamsEntity.credentialsJson) } returns null } fun givenNullSerialization() { @@ -39,7 +42,7 @@ internal class FakeCredentialsJsonAdapter { } companion object { - val credentials: Credentials = mockk() + val credentials = aCredentials() const val CREDENTIALS_JSON = "credentials_json" } } diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt index 4d0e6615c4..6a9285e650 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt @@ -41,7 +41,7 @@ internal class FakeHomeServerConnectionConfigJsonAdapter { } companion object { - val homeServerConnectionConfig: HomeServerConnectionConfig = mockk() + val homeServerConnectionConfig = HomeServerConnectionConfig.Builder().build() const val HOME_SERVER_CONNECTION_CONFIG_JSON = "home_server_connection_config_json" } } From 47d5d09af2071fd331ffb589ae3a859376c903ef Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Thu, 3 Mar 2022 14:46:11 +0100 Subject: [PATCH 012/291] Fixes lint errors --- .../sdk/internal/auth/db/SessionParamsMapperTest.kt | 8 ++------ .../internal/auth/db/migration/MigrateAuthTo005Test.kt | 1 - 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt index ffacb4b4a5..72b8305b8b 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt @@ -30,15 +30,13 @@ class SessionParamsMapperTest { @Test fun `when mapping entity, then map as SessionParams`() { - val output = sessionParamsMapper.map(sessionParamsEntity) fakeMoshi.assertSessionParamsWasMappedSuccessfully(output) } @Test - fun `given null input, when mapping entity, then return null`() { - + fun `when mapping null entity, then return null`() { val output = sessionParamsMapper.map(nullSessionParamsEntity) fakeMoshi.assertSessionParamsIsNull(output) @@ -64,15 +62,13 @@ class SessionParamsMapperTest { @Test fun `when mapping sessionParams, then map as SessionParamsEntity`() { - val output = sessionParamsMapper.map(sessionParams) fakeMoshi.assertSessionParamsEntityWasMappedSuccessfully(output) } @Test - fun `given null input, when mapping sessionParams, then return null`() { - + fun `when mapping null sessionParams, then return null`() { val output = sessionParamsMapper.map(nullSessionParams) fakeMoshi.assertSessionParamsEntityWasMappedSuccessfully(output) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt index efb7bce378..ab5b1f4c7a 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt @@ -26,7 +26,6 @@ class MigrateAuthTo005Test { @Test fun `when doMigrate, then LoginType field added`() { - migrator.doMigrate(fakeRealm.instance) fakeRealm.verifyLoginTypeAdded() From 40dee006dd2ca130496f3a13470c02d5a47facf3 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Thu, 3 Mar 2022 17:51:50 +0100 Subject: [PATCH 013/291] Refactors SessionCreator with added tests --- matrix-sdk-android/build.gradle | 2 +- .../android/sdk/internal/auth/AuthModule.kt | 3 + .../sdk/internal/auth/SessionCreator.kt | 56 ++++--------- .../sdk/internal/auth/SessionParamsCreator.kt | 83 +++++++++++++++++++ .../auth/DefaultSessionCreatorTest.kt | 61 ++++++++++++++ .../auth/DefaultSessionParamsCreatorTest.kt | 62 ++++++++++++++ .../DefaultSessionParamsCreatorTestBase.kt | 72 ++++++++++++++++ .../auth/db/SessionParamsMapperTest.kt | 10 +-- .../auth/db/migration/MigrateAuthTo005Test.kt | 2 +- .../android/sdk/test/fakes/api/FakeSession.kt | 25 ++++++ .../test/fakes/internal/FakeSessionManager.kt | 45 ++++++++++ .../auth/FakeIsValidClientServerApiTask.kt | 41 +++++++++ .../internal/auth/FakePendingSessionStore.kt | 35 ++++++++ .../internal/auth/FakeSessionParamsCreator.kt | 47 +++++++++++ .../internal/auth/FakeSessionParamsStore.kt | 36 ++++++++ .../db/migration/Fake005MigrationRealm.kt | 2 +- .../FakeCredentialsJsonAdapter.kt | 6 +- ...keHomeServerConnectionConfigJsonAdapter.kt | 6 +- .../FakeSessionParamsMapperMoshi.kt | 10 +-- .../fixtures/DiscoveryInformationFixture.kt | 30 +++++++ .../fixtures/WellKnownBaseConfigFixture.kt | 27 ++++++ 21 files changed, 600 insertions(+), 61 deletions(-) create mode 100644 matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionParamsCreator.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/api/FakeSession.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/FakeSessionManager.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeIsValidClientServerApiTask.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakePendingSessionStore.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsStore.kt rename matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/{ => internal}/auth/db/migration/Fake005MigrationRealm.kt (97%) rename matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/{ => internal}/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt (81%) rename matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/{ => internal}/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt (82%) rename matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/{ => internal}/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt (82%) create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/DiscoveryInformationFixture.kt create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/WellKnownBaseConfigFixture.kt diff --git a/matrix-sdk-android/build.gradle b/matrix-sdk-android/build.gradle index 3e301eebb9..32a8b23f30 100644 --- a/matrix-sdk-android/build.gradle +++ b/matrix-sdk-android/build.gradle @@ -175,7 +175,7 @@ dependencies { // Note: version sticks to 1.9.2 due to https://github.com/mockk/mockk/issues/281 testImplementation libs.mockk.mockk testImplementation libs.tests.kluent - implementation libs.jetbrains.coroutinesAndroid + testImplementation libs.jetbrains.coroutinesTest // Plant Timber tree for test testImplementation 'net.lachlanmckee:timber-junit-rule:1.0.1' // Transitively required for mocking realm as monarchy doesn't expose Rx diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthModule.kt index 298e116199..b5c072370e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthModule.kt @@ -81,6 +81,9 @@ internal abstract class AuthModule { @Binds abstract fun bindSessionCreator(creator: DefaultSessionCreator): SessionCreator + @Binds + abstract fun bindSessionParamsCreator(creator: DefaultSessionParamsCreator): SessionParamsCreator + @Binds abstract fun bindDirectLoginTask(task: DefaultDirectLoginTask): DirectLoginTask diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionCreator.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionCreator.kt index cc00c963ea..5e6d19d21a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionCreator.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionCreator.kt @@ -16,69 +16,41 @@ package org.matrix.android.sdk.internal.auth -import android.net.Uri import org.matrix.android.sdk.api.auth.data.Credentials import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig -import org.matrix.android.sdk.api.auth.data.SessionParams -import org.matrix.android.sdk.api.extensions.tryOrNull import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.internal.SessionManager -import timber.log.Timber +import org.matrix.android.sdk.internal.auth.login.LoginType import javax.inject.Inject internal interface SessionCreator { - suspend fun createSession(credentials: Credentials, homeServerConnectionConfig: HomeServerConnectionConfig): Session + + suspend fun createSession( + credentials: Credentials, + homeServerConnectionConfig: HomeServerConnectionConfig, + loginType: LoginType, + ): Session } internal class DefaultSessionCreator @Inject constructor( private val sessionParamsStore: SessionParamsStore, private val sessionManager: SessionManager, private val pendingSessionStore: PendingSessionStore, - private val isValidClientServerApiTask: IsValidClientServerApiTask + private val sessionParamsCreator: SessionParamsCreator, ) : SessionCreator { /** * Credentials can affect the homeServerConnectionConfig, override homeserver url and/or * identity server url if provided in the credentials */ - override suspend fun createSession(credentials: Credentials, homeServerConnectionConfig: HomeServerConnectionConfig): Session { + override suspend fun createSession( + credentials: Credentials, + homeServerConnectionConfig: HomeServerConnectionConfig, + loginType: LoginType, + ): Session { // We can cleanup the pending session params pendingSessionStore.delete() - - val overriddenUrl = credentials.discoveryInformation?.homeServer?.baseURL - // remove trailing "/" - ?.trim { it == '/' } - ?.takeIf { it.isNotBlank() } - // It can be the same value, so in this case, do not check again the validity - ?.takeIf { it != homeServerConnectionConfig.homeServerUriBase.toString() } - ?.also { Timber.d("Overriding homeserver url to $it (will check if valid)") } - ?.let { Uri.parse(it) } - ?.takeIf { - // Validate the URL, if the configuration is wrong server side, do not override - tryOrNull { - isValidClientServerApiTask.execute( - IsValidClientServerApiTask.Params( - homeServerConnectionConfig.copy(homeServerUriBase = it) - ) - ) - .also { Timber.d("Overriding homeserver url: $it") } - } ?: true // In case of other error (no network, etc.), consider it is valid... - } - - val sessionParams = SessionParams( - credentials = credentials, - homeServerConnectionConfig = homeServerConnectionConfig.copy( - homeServerUriBase = overriddenUrl ?: homeServerConnectionConfig.homeServerUriBase, - identityServerUri = credentials.discoveryInformation?.identityServer?.baseURL - // remove trailing "/" - ?.trim { it == '/' } - ?.takeIf { it.isNotBlank() } - ?.also { Timber.d("Overriding identity server url to $it") } - ?.let { Uri.parse(it) } - ?: homeServerConnectionConfig.identityServerUri - ), - isTokenValid = true) - + val sessionParams = sessionParamsCreator.create(credentials, homeServerConnectionConfig, loginType) sessionParamsStore.save(sessionParams) return sessionManager.getOrCreateSession(sessionParams) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionParamsCreator.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionParamsCreator.kt new file mode 100644 index 0000000000..318389486e --- /dev/null +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionParamsCreator.kt @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.internal.auth + +import android.net.Uri +import org.matrix.android.sdk.api.auth.data.Credentials +import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig +import org.matrix.android.sdk.api.auth.data.SessionParams +import org.matrix.android.sdk.api.extensions.tryOrNull +import org.matrix.android.sdk.internal.auth.login.LoginType +import timber.log.Timber +import javax.inject.Inject + +internal interface SessionParamsCreator { + + suspend fun create( + credentials: Credentials, + homeServerConnectionConfig: HomeServerConnectionConfig, + loginType: LoginType, + ): SessionParams +} + +internal class DefaultSessionParamsCreator @Inject constructor( + private val isValidClientServerApiTask: IsValidClientServerApiTask +) : SessionParamsCreator { + + override suspend fun create( + credentials: Credentials, + homeServerConnectionConfig: HomeServerConnectionConfig, + loginType: LoginType, + ) = SessionParams( + credentials = credentials, + homeServerConnectionConfig = homeServerConnectionConfig.overrideWithCredentials(credentials), + isTokenValid = true, + loginType = loginType, + ) + + private suspend fun HomeServerConnectionConfig.overrideWithCredentials(credentials: Credentials) = copy( + homeServerUriBase = credentials.getHomeServerUri(this) ?: homeServerUriBase, + identityServerUri = credentials.getIdentityServerUri() ?: identityServerUri + ) + + private suspend fun Credentials.getHomeServerUri(homeServerConnectionConfig: HomeServerConnectionConfig) = + discoveryInformation?.homeServer?.baseURL + ?.trim { it == '/' } + ?.takeIf { it.isNotBlank() } + // It can be the same value, so in this case, do not check again the validity + ?.takeIf { it != homeServerConnectionConfig.homeServerUriBase.toString() } + ?.also { Timber.d("Overriding homeserver url to $it (will check if valid)") } + ?.let { Uri.parse(it) } + ?.takeIf { validateUri(it, homeServerConnectionConfig) } + + private suspend fun validateUri(uri: Uri, homeServerConnectionConfig: HomeServerConnectionConfig) = + // Validate the URL, if the configuration is wrong server side, do not override + tryOrNull { + performClientServerApiValidation(uri, homeServerConnectionConfig) + } ?: true // In case of other error (no network, etc.), consider it is valid... + + private suspend fun performClientServerApiValidation(uri: Uri, homeServerConnectionConfig: HomeServerConnectionConfig) = + isValidClientServerApiTask.execute( + IsValidClientServerApiTask.Params(homeServerConnectionConfig.copy(homeServerUriBase = uri)) + ).also { Timber.d("Overriding homeserver url: $it") } + + private fun Credentials.getIdentityServerUri() = discoveryInformation?.identityServer?.baseURL + ?.trim { it == '/' } + ?.takeIf { it.isNotBlank() } + ?.also { Timber.d("Overriding identity server url to $it") } + ?.let { Uri.parse(it) } +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt new file mode 100644 index 0000000000..c9eb2bc2e0 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.internal.auth + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runBlockingTest +import org.junit.Test +import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig +import org.matrix.android.sdk.internal.auth.login.LoginType +import org.matrix.android.sdk.test.fakes.internal.FakeSessionManager +import org.matrix.android.sdk.test.fakes.internal.auth.FakePendingSessionStore +import org.matrix.android.sdk.test.fakes.internal.auth.FakeSessionParamsCreator +import org.matrix.android.sdk.test.fakes.internal.auth.FakeSessionParamsStore +import org.matrix.android.sdk.test.fixtures.CredentialsFixture.aCredentials +import org.matrix.android.sdk.test.fixtures.SessionParamsFixture.aSessionParams + +@ExperimentalCoroutinesApi +class DefaultSessionCreatorTest { + + private val fakeSessionParamsStore = FakeSessionParamsStore() + private val fakeSessionManager = FakeSessionManager() + private val fakePendingSessionStore = FakePendingSessionStore() + private val fakeSessionParamsCreator = FakeSessionParamsCreator() + + private val sessionCreator = DefaultSessionCreator( + fakeSessionParamsStore.instance, + fakeSessionManager.instance, + fakePendingSessionStore.instance, + fakeSessionParamsCreator.instance, + ) + + @Test + fun `when createSession, then session created`() = runBlockingTest { + val output = sessionCreator.createSession(credentials, homeServerConnectionConfig, LoginType.UNKNOWN) + + fakePendingSessionStore.verifyPendingSessionDataCleared() + fakeSessionParamsCreator.verifyCreatedWithParameters(credentials, homeServerConnectionConfig, LoginType.UNKNOWN) + fakeSessionParamsStore.verifyParamsSaved(sessionParams) + fakeSessionManager.assertSessionCreatedWithParams(output, sessionParams) + } + + companion object { + private val sessionParams = aSessionParams() + private val credentials = aCredentials() + private val homeServerConnectionConfig = HomeServerConnectionConfig.Builder().build() + } +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt new file mode 100644 index 0000000000..85723d6e08 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.internal.auth + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runBlockingTest +import org.junit.Test +import org.matrix.android.sdk.internal.auth.login.LoginType +import org.matrix.android.sdk.test.fakes.internal.auth.FakeIsValidClientServerApiTask + +@ExperimentalCoroutinesApi +class DefaultSessionParamsCreatorTest : DefaultSessionParamsCreatorTestBase() { + + private val fakeIsValidClientServerApiTask = FakeIsValidClientServerApiTask() + + private val sessionParamsCreator = DefaultSessionParamsCreator(fakeIsValidClientServerApiTask.instance) + + @Test + fun `when create, then SessionParams created`() = runBlockingTest { + val output = sessionParamsCreator.create(credentials, homeServerConnectionConfig, LoginType.UNKNOWN) + + assertExpectedSessionParams(output) + } + + @Test + fun `given credentials contains homeServerUri, when create, then SessionParams created with validated credentials uri`() = runBlockingTest { + val output = sessionParamsCreator.create(credentialsWithHomeServer, homeServerConnectionConfig, LoginType.UNKNOWN) + + fakeIsValidClientServerApiTask.verifyExecutionWithConfig(homeServerConnectionConfig.copy(homeServerUriBase = discoveryWithHomeServer.getHomeServerUri())) + assertExpectedSessionParamsWithHomeServer(output) + } + + @Test + fun `given credentials homeServerUri is equal to homeServerConnectionConfig, when create, then do not validate`() = runBlockingTest { + val homeServerConnectionConfigWithCredentialsUri = homeServerConnectionConfig.copy(homeServerUriBase = discoveryWithHomeServer.getHomeServerUri()) + val output = sessionParamsCreator.create(credentialsWithHomeServer, homeServerConnectionConfigWithCredentialsUri , LoginType.UNKNOWN) + + fakeIsValidClientServerApiTask.verifyNoExecution() + assertExpectedSessionParamsWithHomeServer(output) + } + + @Test + fun `given credentials contains identityServerUri, when create, then SessionParams created with credentials uri`() = runBlockingTest { + val output = sessionParamsCreator.create(credentialsWithIdentityServer, homeServerConnectionConfig, LoginType.UNKNOWN) + + assertExpectedSessionParamsWithIdentityServer(output) + } +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt new file mode 100644 index 0000000000..8265c1cc27 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.internal.auth + +import android.net.Uri +import org.amshove.kluent.shouldBeEqualTo +import org.matrix.android.sdk.api.auth.data.DiscoveryInformation +import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig +import org.matrix.android.sdk.api.auth.data.SessionParams +import org.matrix.android.sdk.internal.auth.login.LoginType +import org.matrix.android.sdk.test.fixtures.CredentialsFixture +import org.matrix.android.sdk.test.fixtures.DiscoveryInformationFixture +import org.matrix.android.sdk.test.fixtures.WellKnownBaseConfigFixture + +abstract class DefaultSessionParamsCreatorTestBase { + + protected val discoveryWithHomeServer = DiscoveryInformationFixture.aDiscoveryInformation(homeServer = WellKnownBaseConfigFixture.aWellKnownBaseConfig("http://homeserver_url/")) + private val discoveryWithIdentityServer = DiscoveryInformationFixture.aDiscoveryInformation(identityServer = WellKnownBaseConfigFixture.aWellKnownBaseConfig("http://identity_server_url/")) + protected val credentials = CredentialsFixture.aCredentials() + protected val credentialsWithHomeServer = CredentialsFixture.aCredentials(discoveryInformation = discoveryWithHomeServer) + protected val credentialsWithIdentityServer = CredentialsFixture.aCredentials(discoveryInformation = discoveryWithIdentityServer) + protected val homeServerConnectionConfig = HomeServerConnectionConfig.Builder().build() + + protected fun assertExpectedSessionParams(sessionParams: SessionParams) { + sessionParams shouldBeEqualTo SessionParams( + credentials = credentials, + homeServerConnectionConfig = homeServerConnectionConfig, + isTokenValid = true, + loginType = LoginType.UNKNOWN, + ) + } + + protected fun assertExpectedSessionParamsWithHomeServer(sessionParams: SessionParams) { + sessionParams shouldBeEqualTo SessionParams( + credentials = credentialsWithHomeServer, + homeServerConnectionConfig = homeServerConnectionConfig.copy(homeServerUriBase = discoveryWithHomeServer.getHomeServerUri()), + isTokenValid = true, + loginType = LoginType.UNKNOWN, + ) + } + + protected fun assertExpectedSessionParamsWithIdentityServer(sessionParams: SessionParams) { + sessionParams shouldBeEqualTo SessionParams( + credentials = credentialsWithHomeServer, + homeServerConnectionConfig = homeServerConnectionConfig.copy(identityServerUri = discoveryWithIdentityServer.getIdentityServerUri()), + isTokenValid = true, + loginType = LoginType.UNKNOWN, + ) + } + + private fun DiscoveryInformation.getIdentityServerUri() = identityServer?.baseURL?.convertToUri()!! + + protected fun DiscoveryInformation.getHomeServerUri() = homeServer?.baseURL?.convertToUri()!! + + private fun String.convertToUri() = trim { it == '/' } + .takeIf { it.isNotBlank() } + .let { Uri.parse(it) } +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt index 72b8305b8b..1ba3724d63 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt @@ -17,11 +17,11 @@ package org.matrix.android.sdk.internal.auth.db import org.junit.Test -import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi -import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.nullSessionParams -import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.nullSessionParamsEntity -import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams -import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity +import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi +import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.nullSessionParams +import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.nullSessionParamsEntity +import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams +import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity class SessionParamsMapperTest { diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt index ab5b1f4c7a..6b2432b5f6 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt @@ -17,7 +17,7 @@ package org.matrix.android.sdk.internal.auth.db.migration import org.junit.Test -import org.matrix.android.sdk.test.fakes.auth.db.migration.Fake005MigrationRealm +import org.matrix.android.sdk.test.fakes.internal.auth.db.migration.Fake005MigrationRealm class MigrateAuthTo005Test { diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/api/FakeSession.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/api/FakeSession.kt new file mode 100644 index 0000000000..5aac29c328 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/api/FakeSession.kt @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fakes.api + +import io.mockk.mockk +import org.matrix.android.sdk.api.session.Session + +class FakeSession { + + val instance: Session = mockk() +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/FakeSessionManager.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/FakeSessionManager.kt new file mode 100644 index 0000000000..b251349249 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/FakeSessionManager.kt @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fakes.internal + +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import org.amshove.kluent.shouldBeEqualTo +import org.matrix.android.sdk.api.auth.data.SessionParams +import org.matrix.android.sdk.api.session.Session +import org.matrix.android.sdk.internal.SessionManager +import org.matrix.android.sdk.test.fakes.api.FakeSession + +internal class FakeSessionManager { + + val instance: SessionManager = mockk() + + init { + every { instance.getOrCreateSession(any()) } returns fakeSession.instance + } + + fun assertSessionCreatedWithParams(session: Session, sessionParams: SessionParams) { + verify { instance.getOrCreateSession(sessionParams) } + + session shouldBeEqualTo fakeSession.instance + } + + companion object { + private val fakeSession = FakeSession() + } +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeIsValidClientServerApiTask.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeIsValidClientServerApiTask.kt new file mode 100644 index 0000000000..3eeda6db65 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeIsValidClientServerApiTask.kt @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fakes.internal.auth + +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.mockk +import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig +import org.matrix.android.sdk.internal.auth.IsValidClientServerApiTask +import org.matrix.android.sdk.internal.auth.IsValidClientServerApiTask.Params + +internal class FakeIsValidClientServerApiTask { + + init { + coEvery { instance.execute(any()) } returns true + } + + val instance: IsValidClientServerApiTask = mockk() + + fun verifyExecutionWithConfig(config: HomeServerConnectionConfig) { + coVerify { instance.execute(Params(config)) } + } + + fun verifyNoExecution() { + coVerify(inverse = true) { instance.execute(any()) } + } +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakePendingSessionStore.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakePendingSessionStore.kt new file mode 100644 index 0000000000..be91daf910 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakePendingSessionStore.kt @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fakes.internal.auth + +import io.mockk.coJustRun +import io.mockk.coVerify +import io.mockk.mockk +import org.matrix.android.sdk.internal.auth.PendingSessionStore + +internal class FakePendingSessionStore { + + val instance: PendingSessionStore = mockk() + + init { + coJustRun { instance.delete() } + } + + fun verifyPendingSessionDataCleared() { + coVerify { instance.delete() } + } +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt new file mode 100644 index 0000000000..b0757d5bd5 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fakes.internal.auth + +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.mockk +import org.matrix.android.sdk.api.auth.data.Credentials +import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig +import org.matrix.android.sdk.internal.auth.SessionParamsCreator +import org.matrix.android.sdk.internal.auth.login.LoginType +import org.matrix.android.sdk.test.fixtures.SessionParamsFixture.aSessionParams + +internal class FakeSessionParamsCreator { + + val instance: SessionParamsCreator = mockk() + + init { + coEvery { instance.create(any(), any(), any()) } returns sessionParams + } + + fun verifyCreatedWithParameters( + credentials: Credentials, + homeServerConnectionConfig: HomeServerConnectionConfig, + loginType: LoginType, + ) { + coVerify { instance.create(credentials, homeServerConnectionConfig, loginType) } + } + + companion object { + val sessionParams = aSessionParams() + } +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsStore.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsStore.kt new file mode 100644 index 0000000000..4336f6ba7c --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsStore.kt @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fakes.internal.auth + +import io.mockk.coJustRun +import io.mockk.coVerify +import io.mockk.mockk +import org.matrix.android.sdk.api.auth.data.SessionParams +import org.matrix.android.sdk.internal.auth.SessionParamsStore + +internal class FakeSessionParamsStore { + + val instance: SessionParamsStore = mockk() + + init { + coJustRun { instance.save(any()) } + } + + fun verifyParamsSaved(sessionParams: SessionParams) { + coVerify { instance.save(sessionParams) } + } +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/migration/Fake005MigrationRealm.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/migration/Fake005MigrationRealm.kt similarity index 97% rename from matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/migration/Fake005MigrationRealm.kt rename to matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/migration/Fake005MigrationRealm.kt index 3f317fadf0..e5e2b6682f 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/migration/Fake005MigrationRealm.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/migration/Fake005MigrationRealm.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.matrix.android.sdk.test.fakes.auth.db.migration +package org.matrix.android.sdk.test.fakes.internal.auth.db.migration import io.mockk.every import io.mockk.mockk diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt similarity index 81% rename from matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt rename to matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt index 7c0d78f96d..eea3e4fab1 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt @@ -14,14 +14,14 @@ * limitations under the License. */ -package org.matrix.android.sdk.test.fakes.auth.db.sessionparams +package org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams import com.squareup.moshi.JsonAdapter import io.mockk.every import io.mockk.mockk import org.matrix.android.sdk.api.auth.data.Credentials -import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams -import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity +import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams +import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity import org.matrix.android.sdk.test.fixtures.CredentialsFixture.aCredentials internal class FakeCredentialsJsonAdapter { diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt similarity index 82% rename from matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt rename to matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt index 6a9285e650..d066907cdf 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt @@ -14,14 +14,14 @@ * limitations under the License. */ -package org.matrix.android.sdk.test.fakes.auth.db.sessionparams +package org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams import com.squareup.moshi.JsonAdapter import io.mockk.every import io.mockk.mockk import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig -import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams -import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity +import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams +import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity internal class FakeHomeServerConnectionConfigJsonAdapter { diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt similarity index 82% rename from matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt rename to matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt index 6327c90565..546f8dcee9 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.matrix.android.sdk.test.fakes.auth.db.sessionparams +package org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams import com.squareup.moshi.Moshi import io.mockk.every @@ -27,10 +27,10 @@ import org.matrix.android.sdk.api.auth.data.SessionParams import org.matrix.android.sdk.api.auth.data.sessionId import org.matrix.android.sdk.internal.auth.db.SessionParamsEntity import org.matrix.android.sdk.internal.auth.login.LoginType -import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeCredentialsJsonAdapter.Companion.CREDENTIALS_JSON -import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeCredentialsJsonAdapter.Companion.credentials -import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeHomeServerConnectionConfigJsonAdapter.Companion.HOME_SERVER_CONNECTION_CONFIG_JSON -import org.matrix.android.sdk.test.fakes.auth.db.sessionparams.FakeHomeServerConnectionConfigJsonAdapter.Companion.homeServerConnectionConfig +import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeCredentialsJsonAdapter.Companion.CREDENTIALS_JSON +import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeCredentialsJsonAdapter.Companion.credentials +import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeHomeServerConnectionConfigJsonAdapter.Companion.HOME_SERVER_CONNECTION_CONFIG_JSON +import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeHomeServerConnectionConfigJsonAdapter.Companion.homeServerConnectionConfig import org.matrix.android.sdk.test.fixtures.SessionParamsEntityFixture.aSessionParamsEntity import org.matrix.android.sdk.test.fixtures.SessionParamsFixture.aSessionParams diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/DiscoveryInformationFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/DiscoveryInformationFixture.kt new file mode 100644 index 0000000000..4a15fd383a --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/DiscoveryInformationFixture.kt @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fixtures + +import org.matrix.android.sdk.api.auth.data.DiscoveryInformation +import org.matrix.android.sdk.api.auth.data.WellKnownBaseConfig + +object DiscoveryInformationFixture { + fun aDiscoveryInformation( + homeServer: WellKnownBaseConfig? = null, + identityServer: WellKnownBaseConfig? = null, + ) = DiscoveryInformation( + homeServer, + identityServer + ) +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/WellKnownBaseConfigFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/WellKnownBaseConfigFixture.kt new file mode 100644 index 0000000000..96a146587c --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/WellKnownBaseConfigFixture.kt @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fixtures + +import org.matrix.android.sdk.api.auth.data.WellKnownBaseConfig + +object WellKnownBaseConfigFixture { + fun aWellKnownBaseConfig( + baseUrl: String? = null, + ) = WellKnownBaseConfig( + baseUrl, + ) +} From ea5346210755dba8877fbcf505d9f6c840383e64 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Thu, 3 Mar 2022 17:54:45 +0100 Subject: [PATCH 014/291] Adds loginType to DefaultLegacySessionImporter --- .../sdk/internal/legacy/DefaultLegacySessionImporter.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/DefaultLegacySessionImporter.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/DefaultLegacySessionImporter.kt index 22085e30fc..e7acee2f13 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/DefaultLegacySessionImporter.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/DefaultLegacySessionImporter.kt @@ -27,6 +27,7 @@ import org.matrix.android.sdk.api.auth.data.SessionParams import org.matrix.android.sdk.api.auth.data.WellKnownBaseConfig import org.matrix.android.sdk.api.legacy.LegacySessionImporter import org.matrix.android.sdk.internal.auth.SessionParamsStore +import org.matrix.android.sdk.internal.auth.login.LoginType import org.matrix.android.sdk.internal.crypto.store.db.RealmCryptoStoreMigration import org.matrix.android.sdk.internal.crypto.store.db.RealmCryptoStoreModule import org.matrix.android.sdk.internal.database.RealmKeysUtils @@ -145,7 +146,8 @@ internal class DefaultLegacySessionImporter @Inject constructor( forceUsageTlsVersions = legacyConfig.forceUsageOfTlsVersions() ), // If token is not valid, this boolean will be updated later - isTokenValid = true + isTokenValid = true, + loginType = LoginType.UNKNOWN, ) Timber.d("Migration: save session") From 32bde5a344f31f15a3d0927e8a63b467999b038f Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Fri, 4 Mar 2022 14:24:47 +0100 Subject: [PATCH 015/291] Adds loginType UNSUPPORTED --- .../sdk/internal/auth/login/LoginType.kt | 2 + .../sdk/internal/auth/login/LoginTypeTest.kt | 42 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt index a5f6ebd2f8..635ecc7658 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt @@ -19,6 +19,7 @@ package org.matrix.android.sdk.internal.auth.login enum class LoginType(val value: String) { PASSWORD("password"), SSO("sso"), + UNSUPPORTED("unsupported"), UNKNOWN("unknown"); companion object { @@ -26,6 +27,7 @@ enum class LoginType(val value: String) { fun fromValue(value: String) = when (value) { PASSWORD.value -> PASSWORD SSO.value -> SSO + UNSUPPORTED.value -> UNSUPPORTED else -> UNKNOWN } } diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt new file mode 100644 index 0000000000..c52dd4fe67 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.internal.auth.login + +import org.amshove.kluent.shouldBeEqualTo +import org.amshove.kluent.shouldNotBeEqualTo +import org.junit.Test + +class LoginTypeTest { + + @Test + fun `when getting type fromValue, then map correctly`() { + LoginType.fromValue(LoginType.PASSWORD.value) shouldBeEqualTo LoginType.PASSWORD + LoginType.fromValue(LoginType.SSO.value) shouldBeEqualTo LoginType.SSO + LoginType.fromValue(LoginType.UNSUPPORTED.value) shouldBeEqualTo LoginType.UNSUPPORTED + LoginType.fromValue(LoginType.UNKNOWN.value) shouldBeEqualTo LoginType.UNKNOWN + } + + @Test // This test failing means an existing type has not been correctly added to fromValue + fun `given non-unknown type value, when getting type fromValue, then type is not UNKNOWN`() { + val types = LoginType.values() + + types.forEach { type -> + if (type != LoginType.UNKNOWN) + LoginType.fromValue(type.value) shouldNotBeEqualTo LoginType.UNKNOWN + } + } +} From 2fda593c3c65917347bdeb255ca42c32f0d14850 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Fri, 4 Mar 2022 14:29:42 +0100 Subject: [PATCH 016/291] Adds login types to auth flows --- .../auth/DefaultAuthenticationService.kt | 3 ++- .../internal/auth/login/DefaultLoginWizard.kt | 6 ++--- .../internal/auth/login/DirectLoginTask.kt | 2 +- .../registration/DefaultRegistrationWizard.kt | 26 +++++++++++-------- 4 files changed, 21 insertions(+), 16 deletions(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt index 8784d85c10..25575dfa4c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt @@ -38,6 +38,7 @@ import org.matrix.android.sdk.internal.auth.data.WebClientConfig import org.matrix.android.sdk.internal.auth.db.PendingSessionData import org.matrix.android.sdk.internal.auth.login.DefaultLoginWizard import org.matrix.android.sdk.internal.auth.login.DirectLoginTask +import org.matrix.android.sdk.internal.auth.login.LoginType import org.matrix.android.sdk.internal.auth.registration.DefaultRegistrationWizard import org.matrix.android.sdk.internal.auth.version.Versions import org.matrix.android.sdk.internal.auth.version.isLoginAndRegistrationSupportedBySdk @@ -370,7 +371,7 @@ internal class DefaultAuthenticationService @Inject constructor( override suspend fun createSessionFromSso(homeServerConnectionConfig: HomeServerConnectionConfig, credentials: Credentials): Session { - return sessionCreator.createSession(credentials, homeServerConnectionConfig) + return sessionCreator.createSession(credentials, homeServerConnectionConfig, LoginType.SSO) } override suspend fun getWellKnownData(matrixId: String, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt index 0583951138..6e9a188631 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt @@ -76,7 +76,7 @@ internal class DefaultLoginWizard( authAPI.login(loginParams) } - return sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig) + return sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig, LoginType.PASSWORD) } /** @@ -90,7 +90,7 @@ internal class DefaultLoginWizard( authAPI.login(loginParams) } - return sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig) + return sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig, LoginType.UNSUPPORTED) } override suspend fun loginCustom(data: JsonDict): Session { @@ -98,7 +98,7 @@ internal class DefaultLoginWizard( authAPI.login(data) } - return sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig) + return sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig, LoginType.UNSUPPORTED) } override suspend fun resetPassword(email: String, newPassword: String) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt index 28706c7e80..16f6a13977 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt @@ -77,7 +77,7 @@ internal class DefaultDirectLoginTask @Inject constructor( } } - return sessionCreator.createSession(credentials, params.homeServerConnectionConfig) + return sessionCreator.createSession(credentials, params.homeServerConnectionConfig, LoginType.UNSUPPORTED) } private fun buildClient(homeServerConnectionConfig: HomeServerConnectionConfig): OkHttpClient { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt index 4a156e74cd..6d4a748a72 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt @@ -29,6 +29,7 @@ import org.matrix.android.sdk.internal.auth.AuthAPI import org.matrix.android.sdk.internal.auth.PendingSessionStore import org.matrix.android.sdk.internal.auth.SessionCreator import org.matrix.android.sdk.internal.auth.db.PendingSessionData +import org.matrix.android.sdk.internal.auth.login.LoginType /** * This class execute the registration request and is responsible to keep the session of interactive authentication @@ -63,7 +64,7 @@ internal class DefaultRegistrationWizard( override suspend fun getRegistrationFlow(): RegistrationResult { val params = RegistrationParams() - return performRegistrationRequest(params) + return performRegistrationRequest(params, LoginType.UNSUPPORTED) } override suspend fun createAccount(userName: String?, @@ -74,7 +75,7 @@ internal class DefaultRegistrationWizard( password = password, initialDeviceDisplayName = initialDeviceDisplayName ) - return performRegistrationRequest(params) + return performRegistrationRequest(params, LoginType.PASSWORD) .also { pendingSessionData = pendingSessionData.copy(isRegistrationStarted = true) .also { pendingSessionStore.savePendingSessionData(it) } @@ -86,7 +87,7 @@ internal class DefaultRegistrationWizard( ?: throw IllegalStateException("developer error, call createAccount() method first") val params = RegistrationParams(auth = AuthParams.createForCaptcha(safeSession, response)) - return performRegistrationRequest(params) + return performRegistrationRequest(params, LoginType.UNSUPPORTED) } override suspend fun acceptTerms(): RegistrationResult { @@ -94,7 +95,7 @@ internal class DefaultRegistrationWizard( ?: throw IllegalStateException("developer error, call createAccount() method first") val params = RegistrationParams(auth = AuthParams(type = LoginFlowTypes.TERMS, session = safeSession)) - return performRegistrationRequest(params) + return performRegistrationRequest(params, LoginType.UNSUPPORTED) } override suspend fun addThreePid(threePid: RegisterThreePid): RegistrationResult { @@ -144,14 +145,14 @@ internal class DefaultRegistrationWizard( .also { pendingSessionStore.savePendingSessionData(it) } // and send the sid a first time - return performRegistrationRequest(params) + return performRegistrationRequest(params, LoginType.UNSUPPORTED) } override suspend fun checkIfEmailHasBeenValidated(delayMillis: Long): RegistrationResult { val safeParam = pendingSessionData.currentThreePidData?.registrationParams ?: throw IllegalStateException("developer error, no pending three pid") - return performRegistrationRequest(safeParam, delayMillis) + return performRegistrationRequest(safeParam, LoginType.UNSUPPORTED, delayMillis) } override suspend fun handleValidateThreePid(code: String): RegistrationResult { @@ -172,7 +173,7 @@ internal class DefaultRegistrationWizard( if (validationResponse.isSuccess()) { // The entered code is correct // Same than validate email - return performRegistrationRequest(registrationParams, 3_000) + return performRegistrationRequest(registrationParams, LoginType.UNSUPPORTED, 3_000) } else { // The code is not correct throw Failure.SuccessError @@ -184,11 +185,14 @@ internal class DefaultRegistrationWizard( ?: throw IllegalStateException("developer error, call createAccount() method first") val params = RegistrationParams(auth = AuthParams(type = LoginFlowTypes.DUMMY, session = safeSession)) - return performRegistrationRequest(params) + return performRegistrationRequest(params, LoginType.UNSUPPORTED) } - private suspend fun performRegistrationRequest(registrationParams: RegistrationParams, - delayMillis: Long = 0): RegistrationResult { + private suspend fun performRegistrationRequest( + registrationParams: RegistrationParams, + loginType: LoginType, + delayMillis: Long = 0, + ): RegistrationResult { delay(delayMillis) val credentials = try { registerTask.execute(RegisterTask.Params(registrationParams)) @@ -202,7 +206,7 @@ internal class DefaultRegistrationWizard( } } - val session = sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig) + val session = sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig, loginType) return RegistrationResult.Success(session) } From 92f87a3a5a0f0ebee75878aec0036e53ed8f8a12 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Fri, 4 Mar 2022 14:51:39 +0100 Subject: [PATCH 017/291] Adds login type handling to SoftLogoutController --- .../signout/soft/SoftLogoutController.kt | 125 ++++++++++-------- .../signout/soft/SoftLogoutViewModel.kt | 7 +- .../signout/soft/SoftLogoutViewState.kt | 4 +- 3 files changed, 78 insertions(+), 58 deletions(-) diff --git a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt index 25011ebc8a..6742894fde 100644 --- a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt +++ b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt @@ -19,7 +19,9 @@ package im.vector.app.features.signout.soft import com.airbnb.epoxy.EpoxyController import com.airbnb.mvrx.Fail import com.airbnb.mvrx.Incomplete +import com.airbnb.mvrx.Loading import com.airbnb.mvrx.Success +import com.airbnb.mvrx.Uninitialized import im.vector.app.R import im.vector.app.core.epoxy.loadingItem import im.vector.app.core.error.ErrorFormatter @@ -34,7 +36,7 @@ import im.vector.app.features.signout.soft.epoxy.loginRedButtonItem import im.vector.app.features.signout.soft.epoxy.loginTextItem import im.vector.app.features.signout.soft.epoxy.loginTitleItem import im.vector.app.features.signout.soft.epoxy.loginTitleSmallItem -import timber.log.Timber +import org.matrix.android.sdk.internal.auth.login.LoginType import javax.inject.Inject class SoftLogoutController @Inject constructor( @@ -87,61 +89,74 @@ class SoftLogoutController @Inject constructor( } } - private fun buildForm(state: SoftLogoutViewState) { + private fun buildForm(state: SoftLogoutViewState) = when (state.asyncHomeServerLoginFlowRequest) { + is Incomplete -> buildLoadingItem() + is Fail -> buildLoginErrorWithRetryItem(state.asyncHomeServerLoginFlowRequest.error) + is Success -> buildLoginSuccessItem(state) + is Loading, Uninitialized -> Unit + } + + private fun buildLoadingItem() { + loadingItem { + id("loading") + } + } + + private fun buildLoginErrorWithRetryItem(error: Throwable) { val host = this - when (state.asyncHomeServerLoginFlowRequest) { - is Incomplete -> { - loadingItem { - id("loading") - } - } - is Fail -> { - loginErrorWithRetryItem { - id("errorRetry") - text(host.errorFormatter.toHumanReadable(state.asyncHomeServerLoginFlowRequest.error)) - listener { host.listener?.retry() } - } - } - is Success -> { - val loginMode = state.asyncHomeServerLoginFlowRequest.invoke() - Timber.i("Login Mode: $loginMode") - when (state.asyncHomeServerLoginFlowRequest.invoke()) { - LoginMode.Password -> { - loginPasswordFormItem { - id("passwordForm") - stringProvider(host.stringProvider) - passwordValue(state.enteredPassword) - submitEnabled(state.enteredPassword.isNotEmpty()) - onPasswordEdited { host.listener?.passwordEdited(it) } - errorText((state.asyncLoginAction as? Fail)?.error?.let { host.errorFormatter.toHumanReadable(it) }) - forgetPasswordClickListener { host.listener?.forgetPasswordClicked() } - submitClickListener { host.listener?.submit() } - } - } - is LoginMode.Sso -> { - loginCenterButtonItem { - id("sso") - text(host.stringProvider.getString(R.string.login_signin_sso)) - listener { host.listener?.signinFallbackSubmit() } - } - } - is LoginMode.SsoAndPassword -> { - loginCenterButtonItem { - id("sso") - text(host.stringProvider.getString(R.string.login_signin_sso)) - listener { host.listener?.signinFallbackSubmit() } - } - } - LoginMode.Unsupported -> { - loginCenterButtonItem { - id("fallback") - text(host.stringProvider.getString(R.string.login_signin)) - listener { host.listener?.signinFallbackSubmit() } - } - } - LoginMode.Unknown -> Unit // Should not happen - } - } + loginErrorWithRetryItem { + id("errorRetry") + text(host.errorFormatter.toHumanReadable(error)) + listener { host.listener?.retry() } + } + } + + private fun buildLoginSuccessItem(state: SoftLogoutViewState) = when (state.asyncHomeServerLoginFlowRequest.invoke()) { + LoginMode.Password -> buildLoginPasswordForm(state) + is LoginMode.Sso -> buildLoginSSOForm() + is LoginMode.SsoAndPassword -> disambiguateLoginSSOAndPasswordForm(state) + LoginMode.Unsupported -> buildLoginUnsupportedForm() + LoginMode.Unknown, null -> Unit // Should not happen + } + + private fun buildLoginPasswordForm(state: SoftLogoutViewState) { + val host = this + loginPasswordFormItem { + id("passwordForm") + stringProvider(host.stringProvider) + passwordValue(state.enteredPassword) + submitEnabled(state.enteredPassword.isNotEmpty()) + onPasswordEdited { host.listener?.passwordEdited(it) } + errorText((state.asyncLoginAction as? Fail)?.error?.let { host.errorFormatter.toHumanReadable(it) }) + forgetPasswordClickListener { host.listener?.forgetPasswordClicked() } + submitClickListener { host.listener?.submit() } + } + } + + private fun buildLoginSSOForm() { + val host = this + loginCenterButtonItem { + id("sso") + text(host.stringProvider.getString(R.string.login_signin_sso)) + listener { host.listener?.signinFallbackSubmit() } + } + } + + private fun disambiguateLoginSSOAndPasswordForm(state: SoftLogoutViewState) { + when (state.loginType) { + LoginType.PASSWORD -> buildLoginPasswordForm(state) + LoginType.SSO -> buildLoginSSOForm() + LoginType.UNSUPPORTED -> buildLoginUnsupportedForm() + LoginType.UNKNOWN -> Unit + } + } + + private fun buildLoginUnsupportedForm() { + val host = this + loginCenterButtonItem { + id("fallback") + text(host.stringProvider.getString(R.string.login_signin)) + listener { host.listener?.signinFallbackSubmit() } } } diff --git a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewModel.kt b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewModel.kt index 00422d8872..dcc18ea088 100644 --- a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewModel.kt @@ -37,6 +37,7 @@ import kotlinx.coroutines.launch import org.matrix.android.sdk.api.auth.AuthenticationService import org.matrix.android.sdk.api.auth.data.LoginFlowTypes import org.matrix.android.sdk.api.session.Session +import org.matrix.android.sdk.internal.auth.login.LoginType import timber.log.Timber /** @@ -69,7 +70,8 @@ class SoftLogoutViewModel @AssistedInject constructor( userId = userId, deviceId = session.sessionParams.deviceId.orEmpty(), userDisplayName = session.getUser(userId)?.displayName ?: userId, - hasUnsavedKeys = session.hasUnsavedKeys() + hasUnsavedKeys = session.hasUnsavedKeys(), + loginType = session.sessionParams.loginType, ) } else { SoftLogoutViewState( @@ -77,7 +79,8 @@ class SoftLogoutViewModel @AssistedInject constructor( userId = "", deviceId = "", userDisplayName = "", - hasUnsavedKeys = false + hasUnsavedKeys = false, + loginType = LoginType.UNKNOWN, ) } } diff --git a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewState.kt b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewState.kt index 511711ab2f..f13b089ac5 100644 --- a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewState.kt +++ b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewState.kt @@ -22,6 +22,7 @@ import com.airbnb.mvrx.MavericksState import com.airbnb.mvrx.Success import com.airbnb.mvrx.Uninitialized import im.vector.app.features.login.LoginMode +import org.matrix.android.sdk.internal.auth.login.LoginType data class SoftLogoutViewState( val asyncHomeServerLoginFlowRequest: Async = Uninitialized, @@ -31,7 +32,8 @@ data class SoftLogoutViewState( val deviceId: String, val userDisplayName: String, val hasUnsavedKeys: Boolean, - val enteredPassword: String = "" + val loginType: LoginType, + val enteredPassword: String = "", ) : MavericksState { fun isLoading(): Boolean { From 275505b3e60e029af96bc88e0cdcb6a4157017bc Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Fri, 4 Mar 2022 14:53:16 +0100 Subject: [PATCH 018/291] Fixes lint errors --- .../sdk/internal/auth/DefaultSessionParamsCreatorTest.kt | 2 +- .../matrix/android/sdk/internal/auth/login/LoginTypeTest.kt | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt index 85723d6e08..35693748ef 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt @@ -47,7 +47,7 @@ class DefaultSessionParamsCreatorTest : DefaultSessionParamsCreatorTestBase() { @Test fun `given credentials homeServerUri is equal to homeServerConnectionConfig, when create, then do not validate`() = runBlockingTest { val homeServerConnectionConfigWithCredentialsUri = homeServerConnectionConfig.copy(homeServerUriBase = discoveryWithHomeServer.getHomeServerUri()) - val output = sessionParamsCreator.create(credentialsWithHomeServer, homeServerConnectionConfigWithCredentialsUri , LoginType.UNKNOWN) + val output = sessionParamsCreator.create(credentialsWithHomeServer, homeServerConnectionConfigWithCredentialsUri, LoginType.UNKNOWN) fakeIsValidClientServerApiTask.verifyNoExecution() assertExpectedSessionParamsWithHomeServer(output) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt index c52dd4fe67..419dd50991 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt @@ -35,8 +35,9 @@ class LoginTypeTest { val types = LoginType.values() types.forEach { type -> - if (type != LoginType.UNKNOWN) + if (type != LoginType.UNKNOWN) { LoginType.fromValue(type.value) shouldNotBeEqualTo LoginType.UNKNOWN + } } } } From bb2369dad2f04489dc974ffa6237b637f7ab95a9 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Fri, 4 Mar 2022 15:02:03 +0100 Subject: [PATCH 019/291] Fixes broken tests due to uninitialised HomeServerConnectionConfig homeServerUri --- .../auth/DefaultSessionCreatorTest.kt | 4 +- .../DefaultSessionParamsCreatorTestBase.kt | 4 +- ...keHomeServerConnectionConfigJsonAdapter.kt | 3 +- .../HomeServerConnectionConfigFixture.kt | 51 +++++++++++++++++++ .../sdk/test/fixtures/SessionParamsFixture.kt | 3 +- 5 files changed, 59 insertions(+), 6 deletions(-) create mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/HomeServerConnectionConfigFixture.kt diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt index c9eb2bc2e0..35558fda2f 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt @@ -19,13 +19,13 @@ package org.matrix.android.sdk.internal.auth import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runBlockingTest import org.junit.Test -import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.internal.auth.login.LoginType import org.matrix.android.sdk.test.fakes.internal.FakeSessionManager import org.matrix.android.sdk.test.fakes.internal.auth.FakePendingSessionStore import org.matrix.android.sdk.test.fakes.internal.auth.FakeSessionParamsCreator import org.matrix.android.sdk.test.fakes.internal.auth.FakeSessionParamsStore import org.matrix.android.sdk.test.fixtures.CredentialsFixture.aCredentials +import org.matrix.android.sdk.test.fixtures.HomeServerConnectionConfigFixture.aHomeServerConnectionConfig import org.matrix.android.sdk.test.fixtures.SessionParamsFixture.aSessionParams @ExperimentalCoroutinesApi @@ -56,6 +56,6 @@ class DefaultSessionCreatorTest { companion object { private val sessionParams = aSessionParams() private val credentials = aCredentials() - private val homeServerConnectionConfig = HomeServerConnectionConfig.Builder().build() + private val homeServerConnectionConfig = aHomeServerConnectionConfig() } } diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt index 8265c1cc27..385b03b061 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt @@ -19,11 +19,11 @@ package org.matrix.android.sdk.internal.auth import android.net.Uri import org.amshove.kluent.shouldBeEqualTo import org.matrix.android.sdk.api.auth.data.DiscoveryInformation -import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.api.auth.data.SessionParams import org.matrix.android.sdk.internal.auth.login.LoginType import org.matrix.android.sdk.test.fixtures.CredentialsFixture import org.matrix.android.sdk.test.fixtures.DiscoveryInformationFixture +import org.matrix.android.sdk.test.fixtures.HomeServerConnectionConfigFixture.aHomeServerConnectionConfig import org.matrix.android.sdk.test.fixtures.WellKnownBaseConfigFixture abstract class DefaultSessionParamsCreatorTestBase { @@ -33,7 +33,7 @@ abstract class DefaultSessionParamsCreatorTestBase { protected val credentials = CredentialsFixture.aCredentials() protected val credentialsWithHomeServer = CredentialsFixture.aCredentials(discoveryInformation = discoveryWithHomeServer) protected val credentialsWithIdentityServer = CredentialsFixture.aCredentials(discoveryInformation = discoveryWithIdentityServer) - protected val homeServerConnectionConfig = HomeServerConnectionConfig.Builder().build() + protected val homeServerConnectionConfig = aHomeServerConnectionConfig() protected fun assertExpectedSessionParams(sessionParams: SessionParams) { sessionParams shouldBeEqualTo SessionParams( diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt index d066907cdf..0351849d33 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt @@ -22,6 +22,7 @@ import io.mockk.mockk import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity +import org.matrix.android.sdk.test.fixtures.HomeServerConnectionConfigFixture.aHomeServerConnectionConfig internal class FakeHomeServerConnectionConfigJsonAdapter { @@ -41,7 +42,7 @@ internal class FakeHomeServerConnectionConfigJsonAdapter { } companion object { - val homeServerConnectionConfig = HomeServerConnectionConfig.Builder().build() + val homeServerConnectionConfig = aHomeServerConnectionConfig() const val HOME_SERVER_CONNECTION_CONFIG_JSON = "home_server_connection_config_json" } } diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/HomeServerConnectionConfigFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/HomeServerConnectionConfigFixture.kt new file mode 100644 index 0000000000..ceffb506d6 --- /dev/null +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/HomeServerConnectionConfigFixture.kt @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.test.fixtures + +import android.net.Uri +import okhttp3.CipherSuite +import okhttp3.TlsVersion +import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig +import org.matrix.android.sdk.internal.network.ssl.Fingerprint + +object HomeServerConnectionConfigFixture { + fun aHomeServerConnectionConfig( + homeServerUri: Uri = Uri.EMPTY, + homeServerUriBase: Uri = Uri.EMPTY, + identityServerUri: Uri? = null, + antiVirusServerUri: Uri? = null, + allowedFingerprints: List = emptyList(), + shouldPin: Boolean = false, + tlsVersions: List? = null, + tlsCipherSuites: List? = null, + shouldAcceptTlsExtensions: Boolean = true, + allowHttpExtension: Boolean = false, + forceUsageTlsVersions: Boolean = false + ) = HomeServerConnectionConfig( + homeServerUri, + homeServerUriBase, + identityServerUri, + antiVirusServerUri, + allowedFingerprints, + shouldPin, + tlsVersions, + tlsCipherSuites, + shouldAcceptTlsExtensions, + allowHttpExtension, + forceUsageTlsVersions, + ) +} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt index 387727e8f0..37f18d1221 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt @@ -21,11 +21,12 @@ import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.api.auth.data.SessionParams import org.matrix.android.sdk.internal.auth.login.LoginType import org.matrix.android.sdk.test.fixtures.CredentialsFixture.aCredentials +import org.matrix.android.sdk.test.fixtures.HomeServerConnectionConfigFixture.aHomeServerConnectionConfig object SessionParamsFixture { fun aSessionParams( credentials: Credentials = aCredentials(), - homeServerConnectionConfig: HomeServerConnectionConfig = HomeServerConnectionConfig.Builder().build(), + homeServerConnectionConfig: HomeServerConnectionConfig = aHomeServerConnectionConfig(), isTokenValid: Boolean = false, loginType: LoginType = LoginType.UNKNOWN, ) = SessionParams( From bcd802d3355338403bd9bc96e08a234c021bdd2c Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Fri, 4 Mar 2022 20:58:30 +0100 Subject: [PATCH 020/291] Changes login types in wizards --- .../sdk/internal/auth/login/DefaultLoginWizard.kt | 2 +- .../auth/registration/DefaultRegistrationWizard.kt | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt index 6e9a188631..b4b81c7d35 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt @@ -90,7 +90,7 @@ internal class DefaultLoginWizard( authAPI.login(loginParams) } - return sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig, LoginType.UNSUPPORTED) + return sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig, LoginType.SSO) } override suspend fun loginCustom(data: JsonDict): Session { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt index 6d4a748a72..c76d24b3d0 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt @@ -64,7 +64,7 @@ internal class DefaultRegistrationWizard( override suspend fun getRegistrationFlow(): RegistrationResult { val params = RegistrationParams() - return performRegistrationRequest(params, LoginType.UNSUPPORTED) + return performRegistrationRequest(params, LoginType.PASSWORD) } override suspend fun createAccount(userName: String?, @@ -87,7 +87,7 @@ internal class DefaultRegistrationWizard( ?: throw IllegalStateException("developer error, call createAccount() method first") val params = RegistrationParams(auth = AuthParams.createForCaptcha(safeSession, response)) - return performRegistrationRequest(params, LoginType.UNSUPPORTED) + return performRegistrationRequest(params, LoginType.PASSWORD) } override suspend fun acceptTerms(): RegistrationResult { @@ -95,7 +95,7 @@ internal class DefaultRegistrationWizard( ?: throw IllegalStateException("developer error, call createAccount() method first") val params = RegistrationParams(auth = AuthParams(type = LoginFlowTypes.TERMS, session = safeSession)) - return performRegistrationRequest(params, LoginType.UNSUPPORTED) + return performRegistrationRequest(params, LoginType.PASSWORD) } override suspend fun addThreePid(threePid: RegisterThreePid): RegistrationResult { @@ -145,14 +145,14 @@ internal class DefaultRegistrationWizard( .also { pendingSessionStore.savePendingSessionData(it) } // and send the sid a first time - return performRegistrationRequest(params, LoginType.UNSUPPORTED) + return performRegistrationRequest(params, LoginType.PASSWORD) } override suspend fun checkIfEmailHasBeenValidated(delayMillis: Long): RegistrationResult { val safeParam = pendingSessionData.currentThreePidData?.registrationParams ?: throw IllegalStateException("developer error, no pending three pid") - return performRegistrationRequest(safeParam, LoginType.UNSUPPORTED, delayMillis) + return performRegistrationRequest(safeParam, LoginType.PASSWORD, delayMillis) } override suspend fun handleValidateThreePid(code: String): RegistrationResult { @@ -173,7 +173,7 @@ internal class DefaultRegistrationWizard( if (validationResponse.isSuccess()) { // The entered code is correct // Same than validate email - return performRegistrationRequest(registrationParams, LoginType.UNSUPPORTED, 3_000) + return performRegistrationRequest(registrationParams, LoginType.PASSWORD, 3_000) } else { // The code is not correct throw Failure.SuccessError @@ -185,7 +185,7 @@ internal class DefaultRegistrationWizard( ?: throw IllegalStateException("developer error, call createAccount() method first") val params = RegistrationParams(auth = AuthParams(type = LoginFlowTypes.DUMMY, session = safeSession)) - return performRegistrationRequest(params, LoginType.UNSUPPORTED) + return performRegistrationRequest(params, LoginType.PASSWORD) } private suspend fun performRegistrationRequest( From 489670cf6b04f4532c36032bbf7ba21b56e43f7a Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Fri, 4 Mar 2022 21:07:12 +0100 Subject: [PATCH 021/291] Adds validation failed test for SessionParamsCreator --- .../auth/DefaultSessionParamsCreatorTest.kt | 11 +++++++++++ .../auth/DefaultSessionParamsCreatorTestBase.kt | 16 ++++++++-------- .../auth/FakeIsValidClientServerApiTask.kt | 4 ++++ 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt index 35693748ef..b303df4d9b 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt @@ -47,6 +47,7 @@ class DefaultSessionParamsCreatorTest : DefaultSessionParamsCreatorTestBase() { @Test fun `given credentials homeServerUri is equal to homeServerConnectionConfig, when create, then do not validate`() = runBlockingTest { val homeServerConnectionConfigWithCredentialsUri = homeServerConnectionConfig.copy(homeServerUriBase = discoveryWithHomeServer.getHomeServerUri()) + val output = sessionParamsCreator.create(credentialsWithHomeServer, homeServerConnectionConfigWithCredentialsUri, LoginType.UNKNOWN) fakeIsValidClientServerApiTask.verifyNoExecution() @@ -59,4 +60,14 @@ class DefaultSessionParamsCreatorTest : DefaultSessionParamsCreatorTestBase() { assertExpectedSessionParamsWithIdentityServer(output) } + + @Test + fun `given home server validation fails, when create, then do not use home server uri from credentials`() = runBlockingTest { + fakeIsValidClientServerApiTask.givenValidationFails() + + val output = sessionParamsCreator.create(credentialsWithHomeServer, homeServerConnectionConfig, LoginType.UNKNOWN) + + fakeIsValidClientServerApiTask.verifyExecutionWithConfig(homeServerConnectionConfig) + assertExpectedSessionParams(output) + } } diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt index 385b03b061..61b808dd1a 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt @@ -21,18 +21,18 @@ import org.amshove.kluent.shouldBeEqualTo import org.matrix.android.sdk.api.auth.data.DiscoveryInformation import org.matrix.android.sdk.api.auth.data.SessionParams import org.matrix.android.sdk.internal.auth.login.LoginType -import org.matrix.android.sdk.test.fixtures.CredentialsFixture -import org.matrix.android.sdk.test.fixtures.DiscoveryInformationFixture +import org.matrix.android.sdk.test.fixtures.CredentialsFixture.aCredentials +import org.matrix.android.sdk.test.fixtures.DiscoveryInformationFixture.aDiscoveryInformation import org.matrix.android.sdk.test.fixtures.HomeServerConnectionConfigFixture.aHomeServerConnectionConfig -import org.matrix.android.sdk.test.fixtures.WellKnownBaseConfigFixture +import org.matrix.android.sdk.test.fixtures.WellKnownBaseConfigFixture.aWellKnownBaseConfig abstract class DefaultSessionParamsCreatorTestBase { - protected val discoveryWithHomeServer = DiscoveryInformationFixture.aDiscoveryInformation(homeServer = WellKnownBaseConfigFixture.aWellKnownBaseConfig("http://homeserver_url/")) - private val discoveryWithIdentityServer = DiscoveryInformationFixture.aDiscoveryInformation(identityServer = WellKnownBaseConfigFixture.aWellKnownBaseConfig("http://identity_server_url/")) - protected val credentials = CredentialsFixture.aCredentials() - protected val credentialsWithHomeServer = CredentialsFixture.aCredentials(discoveryInformation = discoveryWithHomeServer) - protected val credentialsWithIdentityServer = CredentialsFixture.aCredentials(discoveryInformation = discoveryWithIdentityServer) + protected val discoveryWithHomeServer = aDiscoveryInformation(homeServer = aWellKnownBaseConfig("http://homeserver_url/")) + private val discoveryWithIdentityServer = aDiscoveryInformation(identityServer = aWellKnownBaseConfig("http://identity_server_url/")) + protected val credentials = aCredentials() + protected val credentialsWithHomeServer = aCredentials(discoveryInformation = discoveryWithHomeServer) + protected val credentialsWithIdentityServer = aCredentials(discoveryInformation = discoveryWithIdentityServer) protected val homeServerConnectionConfig = aHomeServerConnectionConfig() protected fun assertExpectedSessionParams(sessionParams: SessionParams) { diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeIsValidClientServerApiTask.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeIsValidClientServerApiTask.kt index 3eeda6db65..f8018e7b7e 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeIsValidClientServerApiTask.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeIsValidClientServerApiTask.kt @@ -31,6 +31,10 @@ internal class FakeIsValidClientServerApiTask { val instance: IsValidClientServerApiTask = mockk() + fun givenValidationFails() { + coEvery { instance.execute(any()) } returns false + } + fun verifyExecutionWithConfig(config: HomeServerConnectionConfig) { coVerify { instance.execute(Params(config)) } } From c996f876a25ceaa9f70425cec839a88a7613779e Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Fri, 4 Mar 2022 21:10:52 +0100 Subject: [PATCH 022/291] Fixes Uri EMPTY must not be null --- .../sdk/test/fixtures/HomeServerConnectionConfigFixture.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/HomeServerConnectionConfigFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/HomeServerConnectionConfigFixture.kt index ceffb506d6..2b3d8cc4fa 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/HomeServerConnectionConfigFixture.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/HomeServerConnectionConfigFixture.kt @@ -24,8 +24,8 @@ import org.matrix.android.sdk.internal.network.ssl.Fingerprint object HomeServerConnectionConfigFixture { fun aHomeServerConnectionConfig( - homeServerUri: Uri = Uri.EMPTY, - homeServerUriBase: Uri = Uri.EMPTY, + homeServerUri: Uri = Uri.parse("aUri"), + homeServerUriBase: Uri = homeServerUri, identityServerUri: Uri? = null, antiVirusServerUri: Uri? = null, allowedFingerprints: List = emptyList(), From 2d07b80acee29bfd4cdfd9eb12192181f5badf3a Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Fri, 4 Mar 2022 21:14:27 +0100 Subject: [PATCH 023/291] Fixes broken migration test --- .../auth/db/migration/Fake005MigrationRealm.kt | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/migration/Fake005MigrationRealm.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/migration/Fake005MigrationRealm.kt index e5e2b6682f..434b937ad8 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/migration/Fake005MigrationRealm.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/migration/Fake005MigrationRealm.kt @@ -18,15 +18,11 @@ package org.matrix.android.sdk.test.fakes.internal.auth.db.migration import io.mockk.every import io.mockk.mockk -import io.mockk.slot -import io.mockk.verify import io.mockk.verifyOrder import io.realm.DynamicRealm -import io.realm.DynamicRealmObject import io.realm.RealmObjectSchema import io.realm.RealmSchema import org.matrix.android.sdk.internal.auth.db.SessionParamsEntityFields -import org.matrix.android.sdk.internal.auth.login.LoginType class Fake005MigrationRealm { @@ -43,26 +39,14 @@ class Fake005MigrationRealm { } fun verifyLoginTypeAdded() { - transformFunctionSlot.clear() verifyLoginTypeFieldAddedAndTransformed() - verifyTransformationSetsUnknownLoginType() } private fun verifyLoginTypeFieldAddedAndTransformed() { verifyOrder { objectSchema["SessionParamsEntity"] objectSchema.addField(SessionParamsEntityFields.LOGIN_TYPE, String::class.java) - objectSchema.transform(capture(transformFunctionSlot)) + objectSchema.transform(any()) } } - - private fun verifyTransformationSetsUnknownLoginType() { - val dynamicRealmObject: DynamicRealmObject = mockk() - transformFunctionSlot.captured.invoke(dynamicRealmObject) - verify { dynamicRealmObject.set(SessionParamsEntityFields.LOGIN_TYPE, LoginType.UNKNOWN.value) } - } - - companion object { - private val transformFunctionSlot = slot<(DynamicRealmObject) -> Unit>() - } } From 7896bf9023047231579ffcc5b8c88c47f8db00df Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Fri, 4 Mar 2022 21:36:10 +0100 Subject: [PATCH 024/291] Removes HomeServerConnectionConfigFixture --- .../auth/DefaultSessionCreatorTest.kt | 4 +- .../DefaultSessionParamsCreatorTestBase.kt | 4 +- .../HomeServerConnectionConfigFixture.kt | 51 ------------------- .../sdk/test/fixtures/SessionParamsFixture.kt | 3 +- 4 files changed, 5 insertions(+), 57 deletions(-) delete mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/HomeServerConnectionConfigFixture.kt diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt index 35558fda2f..b389dc5feb 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt @@ -19,13 +19,13 @@ package org.matrix.android.sdk.internal.auth import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runBlockingTest import org.junit.Test +import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.internal.auth.login.LoginType import org.matrix.android.sdk.test.fakes.internal.FakeSessionManager import org.matrix.android.sdk.test.fakes.internal.auth.FakePendingSessionStore import org.matrix.android.sdk.test.fakes.internal.auth.FakeSessionParamsCreator import org.matrix.android.sdk.test.fakes.internal.auth.FakeSessionParamsStore import org.matrix.android.sdk.test.fixtures.CredentialsFixture.aCredentials -import org.matrix.android.sdk.test.fixtures.HomeServerConnectionConfigFixture.aHomeServerConnectionConfig import org.matrix.android.sdk.test.fixtures.SessionParamsFixture.aSessionParams @ExperimentalCoroutinesApi @@ -56,6 +56,6 @@ class DefaultSessionCreatorTest { companion object { private val sessionParams = aSessionParams() private val credentials = aCredentials() - private val homeServerConnectionConfig = aHomeServerConnectionConfig() + private val homeServerConnectionConfig = HomeServerConnectionConfig.Builder().withHomeServerUri("homeserver").build() } } diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt index 61b808dd1a..9c810ff0dc 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt @@ -19,11 +19,11 @@ package org.matrix.android.sdk.internal.auth import android.net.Uri import org.amshove.kluent.shouldBeEqualTo import org.matrix.android.sdk.api.auth.data.DiscoveryInformation +import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.api.auth.data.SessionParams import org.matrix.android.sdk.internal.auth.login.LoginType import org.matrix.android.sdk.test.fixtures.CredentialsFixture.aCredentials import org.matrix.android.sdk.test.fixtures.DiscoveryInformationFixture.aDiscoveryInformation -import org.matrix.android.sdk.test.fixtures.HomeServerConnectionConfigFixture.aHomeServerConnectionConfig import org.matrix.android.sdk.test.fixtures.WellKnownBaseConfigFixture.aWellKnownBaseConfig abstract class DefaultSessionParamsCreatorTestBase { @@ -33,7 +33,7 @@ abstract class DefaultSessionParamsCreatorTestBase { protected val credentials = aCredentials() protected val credentialsWithHomeServer = aCredentials(discoveryInformation = discoveryWithHomeServer) protected val credentialsWithIdentityServer = aCredentials(discoveryInformation = discoveryWithIdentityServer) - protected val homeServerConnectionConfig = aHomeServerConnectionConfig() + protected val homeServerConnectionConfig = HomeServerConnectionConfig.Builder().withHomeServerUri("homeserver").build() protected fun assertExpectedSessionParams(sessionParams: SessionParams) { sessionParams shouldBeEqualTo SessionParams( diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/HomeServerConnectionConfigFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/HomeServerConnectionConfigFixture.kt deleted file mode 100644 index 2b3d8cc4fa..0000000000 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/HomeServerConnectionConfigFixture.kt +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2022 New Vector Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.android.sdk.test.fixtures - -import android.net.Uri -import okhttp3.CipherSuite -import okhttp3.TlsVersion -import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig -import org.matrix.android.sdk.internal.network.ssl.Fingerprint - -object HomeServerConnectionConfigFixture { - fun aHomeServerConnectionConfig( - homeServerUri: Uri = Uri.parse("aUri"), - homeServerUriBase: Uri = homeServerUri, - identityServerUri: Uri? = null, - antiVirusServerUri: Uri? = null, - allowedFingerprints: List = emptyList(), - shouldPin: Boolean = false, - tlsVersions: List? = null, - tlsCipherSuites: List? = null, - shouldAcceptTlsExtensions: Boolean = true, - allowHttpExtension: Boolean = false, - forceUsageTlsVersions: Boolean = false - ) = HomeServerConnectionConfig( - homeServerUri, - homeServerUriBase, - identityServerUri, - antiVirusServerUri, - allowedFingerprints, - shouldPin, - tlsVersions, - tlsCipherSuites, - shouldAcceptTlsExtensions, - allowHttpExtension, - forceUsageTlsVersions, - ) -} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt index 37f18d1221..079b42b9e7 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt @@ -21,12 +21,11 @@ import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.api.auth.data.SessionParams import org.matrix.android.sdk.internal.auth.login.LoginType import org.matrix.android.sdk.test.fixtures.CredentialsFixture.aCredentials -import org.matrix.android.sdk.test.fixtures.HomeServerConnectionConfigFixture.aHomeServerConnectionConfig object SessionParamsFixture { fun aSessionParams( credentials: Credentials = aCredentials(), - homeServerConnectionConfig: HomeServerConnectionConfig = aHomeServerConnectionConfig(), + homeServerConnectionConfig: HomeServerConnectionConfig = HomeServerConnectionConfig.Builder().withHomeServerUri("homeserver").build(), isTokenValid: Boolean = false, loginType: LoginType = LoginType.UNKNOWN, ) = SessionParams( From 9bd3254e41a48645b12d137b41c8ca9c1e1388d1 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Fri, 4 Mar 2022 23:27:21 +0100 Subject: [PATCH 025/291] Removes HomeServerConnectionConfigFixture in fake adapter --- .../sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt index 0351849d33..f0c5f10ebc 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt @@ -22,7 +22,6 @@ import io.mockk.mockk import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity -import org.matrix.android.sdk.test.fixtures.HomeServerConnectionConfigFixture.aHomeServerConnectionConfig internal class FakeHomeServerConnectionConfigJsonAdapter { @@ -42,7 +41,7 @@ internal class FakeHomeServerConnectionConfigJsonAdapter { } companion object { - val homeServerConnectionConfig = aHomeServerConnectionConfig() + val homeServerConnectionConfig = HomeServerConnectionConfig.Builder().withHomeServerUri("homeserver").build() const val HOME_SERVER_CONNECTION_CONFIG_JSON = "home_server_connection_config_json" } } From 858923846da93fab370853c28bf205112bc7a789 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Mon, 7 Mar 2022 09:56:44 +0100 Subject: [PATCH 026/291] Adds Uri static mocking --- .../sdk/internal/auth/DefaultSessionCreatorTest.kt | 11 +++++++++++ .../fakes/internal/auth/FakeSessionParamsCreator.kt | 5 +++++ .../db/sessionparams/FakeSessionParamsMapperMoshi.kt | 4 ++++ 3 files changed, 20 insertions(+) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt index b389dc5feb..ba88690587 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt @@ -16,8 +16,13 @@ package org.matrix.android.sdk.internal.auth +import android.net.Uri +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkStatic import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runBlockingTest +import org.junit.Before import org.junit.Test import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.internal.auth.login.LoginType @@ -43,6 +48,12 @@ class DefaultSessionCreatorTest { fakeSessionParamsCreator.instance, ) + @Before + fun setup() { + mockkStatic(Uri::class) + every { Uri.parse(any()) } returns mockk() + } + @Test fun `when createSession, then session created`() = runBlockingTest { val output = sessionCreator.createSession(credentials, homeServerConnectionConfig, LoginType.UNKNOWN) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt index b0757d5bd5..63cb02973c 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt @@ -16,9 +16,12 @@ package org.matrix.android.sdk.test.fakes.internal.auth +import android.net.Uri import io.mockk.coEvery import io.mockk.coVerify +import io.mockk.every import io.mockk.mockk +import io.mockk.mockkStatic import org.matrix.android.sdk.api.auth.data.Credentials import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.internal.auth.SessionParamsCreator @@ -30,6 +33,8 @@ internal class FakeSessionParamsCreator { val instance: SessionParamsCreator = mockk() init { + mockkStatic(Uri::class) + every { Uri.parse(any()) } returns mockk() coEvery { instance.create(any(), any(), any()) } returns sessionParams } diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt index 546f8dcee9..10c3664511 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt @@ -16,9 +16,11 @@ package org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams +import android.net.Uri import com.squareup.moshi.Moshi import io.mockk.every import io.mockk.mockk +import io.mockk.mockkStatic import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeNull import org.matrix.android.sdk.api.auth.data.Credentials @@ -41,6 +43,8 @@ internal class FakeSessionParamsMapperMoshi { val homeServerConnectionConfigAdapter = FakeHomeServerConnectionConfigJsonAdapter() init { + mockkStatic(Uri::class) + every { Uri.parse(any()) } returns mockk() every { instance.adapter(Credentials::class.java) } returns credentialsJsonAdapter.instance every { instance.adapter(HomeServerConnectionConfig::class.java) } returns homeServerConnectionConfigAdapter.instance } From 63389418853c1db018cc5e868c2c64113361ecc4 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Mon, 7 Mar 2022 10:28:48 +0100 Subject: [PATCH 027/291] Temporarily removes unit tests --- .../auth/DefaultSessionCreatorTest.kt | 72 -------------- .../auth/DefaultSessionParamsCreatorTest.kt | 73 -------------- .../DefaultSessionParamsCreatorTestBase.kt | 72 -------------- .../auth/db/SessionParamsMapperTest.kt | 94 ------------------- 4 files changed, 311 deletions(-) delete mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt delete mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt delete mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt delete mode 100644 matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt deleted file mode 100644 index ba88690587..0000000000 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionCreatorTest.kt +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2022 New Vector Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.android.sdk.internal.auth - -import android.net.Uri -import io.mockk.every -import io.mockk.mockk -import io.mockk.mockkStatic -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.test.runBlockingTest -import org.junit.Before -import org.junit.Test -import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig -import org.matrix.android.sdk.internal.auth.login.LoginType -import org.matrix.android.sdk.test.fakes.internal.FakeSessionManager -import org.matrix.android.sdk.test.fakes.internal.auth.FakePendingSessionStore -import org.matrix.android.sdk.test.fakes.internal.auth.FakeSessionParamsCreator -import org.matrix.android.sdk.test.fakes.internal.auth.FakeSessionParamsStore -import org.matrix.android.sdk.test.fixtures.CredentialsFixture.aCredentials -import org.matrix.android.sdk.test.fixtures.SessionParamsFixture.aSessionParams - -@ExperimentalCoroutinesApi -class DefaultSessionCreatorTest { - - private val fakeSessionParamsStore = FakeSessionParamsStore() - private val fakeSessionManager = FakeSessionManager() - private val fakePendingSessionStore = FakePendingSessionStore() - private val fakeSessionParamsCreator = FakeSessionParamsCreator() - - private val sessionCreator = DefaultSessionCreator( - fakeSessionParamsStore.instance, - fakeSessionManager.instance, - fakePendingSessionStore.instance, - fakeSessionParamsCreator.instance, - ) - - @Before - fun setup() { - mockkStatic(Uri::class) - every { Uri.parse(any()) } returns mockk() - } - - @Test - fun `when createSession, then session created`() = runBlockingTest { - val output = sessionCreator.createSession(credentials, homeServerConnectionConfig, LoginType.UNKNOWN) - - fakePendingSessionStore.verifyPendingSessionDataCleared() - fakeSessionParamsCreator.verifyCreatedWithParameters(credentials, homeServerConnectionConfig, LoginType.UNKNOWN) - fakeSessionParamsStore.verifyParamsSaved(sessionParams) - fakeSessionManager.assertSessionCreatedWithParams(output, sessionParams) - } - - companion object { - private val sessionParams = aSessionParams() - private val credentials = aCredentials() - private val homeServerConnectionConfig = HomeServerConnectionConfig.Builder().withHomeServerUri("homeserver").build() - } -} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt deleted file mode 100644 index b303df4d9b..0000000000 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTest.kt +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2022 New Vector Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.android.sdk.internal.auth - -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.test.runBlockingTest -import org.junit.Test -import org.matrix.android.sdk.internal.auth.login.LoginType -import org.matrix.android.sdk.test.fakes.internal.auth.FakeIsValidClientServerApiTask - -@ExperimentalCoroutinesApi -class DefaultSessionParamsCreatorTest : DefaultSessionParamsCreatorTestBase() { - - private val fakeIsValidClientServerApiTask = FakeIsValidClientServerApiTask() - - private val sessionParamsCreator = DefaultSessionParamsCreator(fakeIsValidClientServerApiTask.instance) - - @Test - fun `when create, then SessionParams created`() = runBlockingTest { - val output = sessionParamsCreator.create(credentials, homeServerConnectionConfig, LoginType.UNKNOWN) - - assertExpectedSessionParams(output) - } - - @Test - fun `given credentials contains homeServerUri, when create, then SessionParams created with validated credentials uri`() = runBlockingTest { - val output = sessionParamsCreator.create(credentialsWithHomeServer, homeServerConnectionConfig, LoginType.UNKNOWN) - - fakeIsValidClientServerApiTask.verifyExecutionWithConfig(homeServerConnectionConfig.copy(homeServerUriBase = discoveryWithHomeServer.getHomeServerUri())) - assertExpectedSessionParamsWithHomeServer(output) - } - - @Test - fun `given credentials homeServerUri is equal to homeServerConnectionConfig, when create, then do not validate`() = runBlockingTest { - val homeServerConnectionConfigWithCredentialsUri = homeServerConnectionConfig.copy(homeServerUriBase = discoveryWithHomeServer.getHomeServerUri()) - - val output = sessionParamsCreator.create(credentialsWithHomeServer, homeServerConnectionConfigWithCredentialsUri, LoginType.UNKNOWN) - - fakeIsValidClientServerApiTask.verifyNoExecution() - assertExpectedSessionParamsWithHomeServer(output) - } - - @Test - fun `given credentials contains identityServerUri, when create, then SessionParams created with credentials uri`() = runBlockingTest { - val output = sessionParamsCreator.create(credentialsWithIdentityServer, homeServerConnectionConfig, LoginType.UNKNOWN) - - assertExpectedSessionParamsWithIdentityServer(output) - } - - @Test - fun `given home server validation fails, when create, then do not use home server uri from credentials`() = runBlockingTest { - fakeIsValidClientServerApiTask.givenValidationFails() - - val output = sessionParamsCreator.create(credentialsWithHomeServer, homeServerConnectionConfig, LoginType.UNKNOWN) - - fakeIsValidClientServerApiTask.verifyExecutionWithConfig(homeServerConnectionConfig) - assertExpectedSessionParams(output) - } -} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt deleted file mode 100644 index 9c810ff0dc..0000000000 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/DefaultSessionParamsCreatorTestBase.kt +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2022 New Vector Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.android.sdk.internal.auth - -import android.net.Uri -import org.amshove.kluent.shouldBeEqualTo -import org.matrix.android.sdk.api.auth.data.DiscoveryInformation -import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig -import org.matrix.android.sdk.api.auth.data.SessionParams -import org.matrix.android.sdk.internal.auth.login.LoginType -import org.matrix.android.sdk.test.fixtures.CredentialsFixture.aCredentials -import org.matrix.android.sdk.test.fixtures.DiscoveryInformationFixture.aDiscoveryInformation -import org.matrix.android.sdk.test.fixtures.WellKnownBaseConfigFixture.aWellKnownBaseConfig - -abstract class DefaultSessionParamsCreatorTestBase { - - protected val discoveryWithHomeServer = aDiscoveryInformation(homeServer = aWellKnownBaseConfig("http://homeserver_url/")) - private val discoveryWithIdentityServer = aDiscoveryInformation(identityServer = aWellKnownBaseConfig("http://identity_server_url/")) - protected val credentials = aCredentials() - protected val credentialsWithHomeServer = aCredentials(discoveryInformation = discoveryWithHomeServer) - protected val credentialsWithIdentityServer = aCredentials(discoveryInformation = discoveryWithIdentityServer) - protected val homeServerConnectionConfig = HomeServerConnectionConfig.Builder().withHomeServerUri("homeserver").build() - - protected fun assertExpectedSessionParams(sessionParams: SessionParams) { - sessionParams shouldBeEqualTo SessionParams( - credentials = credentials, - homeServerConnectionConfig = homeServerConnectionConfig, - isTokenValid = true, - loginType = LoginType.UNKNOWN, - ) - } - - protected fun assertExpectedSessionParamsWithHomeServer(sessionParams: SessionParams) { - sessionParams shouldBeEqualTo SessionParams( - credentials = credentialsWithHomeServer, - homeServerConnectionConfig = homeServerConnectionConfig.copy(homeServerUriBase = discoveryWithHomeServer.getHomeServerUri()), - isTokenValid = true, - loginType = LoginType.UNKNOWN, - ) - } - - protected fun assertExpectedSessionParamsWithIdentityServer(sessionParams: SessionParams) { - sessionParams shouldBeEqualTo SessionParams( - credentials = credentialsWithHomeServer, - homeServerConnectionConfig = homeServerConnectionConfig.copy(identityServerUri = discoveryWithIdentityServer.getIdentityServerUri()), - isTokenValid = true, - loginType = LoginType.UNKNOWN, - ) - } - - private fun DiscoveryInformation.getIdentityServerUri() = identityServer?.baseURL?.convertToUri()!! - - protected fun DiscoveryInformation.getHomeServerUri() = homeServer?.baseURL?.convertToUri()!! - - private fun String.convertToUri() = trim { it == '/' } - .takeIf { it.isNotBlank() } - .let { Uri.parse(it) } -} diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt deleted file mode 100644 index 1ba3724d63..0000000000 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapperTest.kt +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2022 New Vector Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.android.sdk.internal.auth.db - -import org.junit.Test -import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi -import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.nullSessionParams -import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.nullSessionParamsEntity -import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParams -import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeSessionParamsMapperMoshi.Companion.sessionParamsEntity - -class SessionParamsMapperTest { - - private val fakeMoshi = FakeSessionParamsMapperMoshi() - private val sessionParamsMapper = SessionParamsMapper(fakeMoshi.instance) - - @Test - fun `when mapping entity, then map as SessionParams`() { - val output = sessionParamsMapper.map(sessionParamsEntity) - - fakeMoshi.assertSessionParamsWasMappedSuccessfully(output) - } - - @Test - fun `when mapping null entity, then return null`() { - val output = sessionParamsMapper.map(nullSessionParamsEntity) - - fakeMoshi.assertSessionParamsIsNull(output) - } - - @Test - fun `given null credentials json deserialization, when mapping entity, then return null`() { - fakeMoshi.credentialsJsonAdapter.givenNullDeserialization() - - val output = sessionParamsMapper.map(sessionParamsEntity) - - fakeMoshi.assertSessionParamsIsNull(output) - } - - @Test - fun `given null homeServerConnectionConfig json deserialization, when mapping entity, then return null`() { - fakeMoshi.homeServerConnectionConfigAdapter.givenNullDeserialization() - - val output = sessionParamsMapper.map(sessionParamsEntity) - - fakeMoshi.assertSessionParamsIsNull(output) - } - - @Test - fun `when mapping sessionParams, then map as SessionParamsEntity`() { - val output = sessionParamsMapper.map(sessionParams) - - fakeMoshi.assertSessionParamsEntityWasMappedSuccessfully(output) - } - - @Test - fun `when mapping null sessionParams, then return null`() { - val output = sessionParamsMapper.map(nullSessionParams) - - fakeMoshi.assertSessionParamsEntityWasMappedSuccessfully(output) - } - - @Test - fun `given null credentials json serialization, when mapping sessionParams, then return null`() { - fakeMoshi.credentialsJsonAdapter.givenNullSerialization() - - val output = sessionParamsMapper.map(sessionParams) - - fakeMoshi.assertSessionParamsEntityIsNull(output) - } - - @Test - fun `given null homeServerConnectionConfig json serialization, when mapping sessionParams, then return null`() { - fakeMoshi.homeServerConnectionConfigAdapter.givenNullSerialization() - - val output = sessionParamsMapper.map(sessionParams) - - fakeMoshi.assertSessionParamsEntityIsNull(output) - } -} From 22b21b8c7f0b161c408752bb6724742659ba5d5b Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Mon, 7 Mar 2022 10:53:43 +0100 Subject: [PATCH 028/291] Adds changelog file --- changelog.d/5398.bugfix | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/5398.bugfix diff --git a/changelog.d/5398.bugfix b/changelog.d/5398.bugfix new file mode 100644 index 0000000000..24da1952b3 --- /dev/null +++ b/changelog.d/5398.bugfix @@ -0,0 +1 @@ +Adds LoginType to SessionParams to fix soft logout form not showing for SSO and Password type From e8432f31408ed7b707f9bb6e05d85f1823947f12 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Mon, 7 Mar 2022 12:07:41 +0100 Subject: [PATCH 029/291] Adds setRequired to migration --- .../android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt index ca3cffeaae..868f62b8cd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt @@ -29,6 +29,7 @@ class MigrateAuthTo005(realm: DynamicRealm) : RealmMigrator(realm, 5) { realm.schema.get("SessionParamsEntity") ?.addField(SessionParamsEntityFields.LOGIN_TYPE, String::class.java) + ?.setRequired(SessionParamsEntityFields.LOGIN_TYPE, true) ?.transform { it.set(SessionParamsEntityFields.LOGIN_TYPE, LoginType.UNKNOWN.value) } } } From 085dd943ff560c817660dfbefc541433320c9ea8 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Mon, 7 Mar 2022 12:13:33 +0100 Subject: [PATCH 030/291] Fixes wrong legal comment on LoginType --- .../org/matrix/android/sdk/internal/auth/login/LoginType.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt index 635ecc7658..d14ef12bb6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. From 0d75273121647a0ed4cfae9e65e814ad8ad06b66 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Mon, 7 Mar 2022 12:22:25 +0100 Subject: [PATCH 031/291] Adds stubbing and verification for migration setRequired --- .../fakes/internal/auth/db/migration/Fake005MigrationRealm.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/migration/Fake005MigrationRealm.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/migration/Fake005MigrationRealm.kt index 434b937ad8..147f8df969 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/migration/Fake005MigrationRealm.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/migration/Fake005MigrationRealm.kt @@ -35,6 +35,7 @@ class Fake005MigrationRealm { every { instance.schema } returns schema every { schema.get("SessionParamsEntity") } returns objectSchema every { objectSchema.addField(any(), any()) } returns objectSchema + every { objectSchema.setRequired(any(), any()) } returns objectSchema every { objectSchema.transform(any()) } returns objectSchema } @@ -46,6 +47,7 @@ class Fake005MigrationRealm { verifyOrder { objectSchema["SessionParamsEntity"] objectSchema.addField(SessionParamsEntityFields.LOGIN_TYPE, String::class.java) + objectSchema.setRequired(SessionParamsEntityFields.LOGIN_TYPE, true) objectSchema.transform(any()) } } From e1f227a54545c4628bf749ef5ac5d0fec0e49b8b Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Mon, 7 Mar 2022 13:14:10 +0100 Subject: [PATCH 032/291] Fixes legal comments in matrix sdk files added --- .../matrix/android/sdk/internal/auth/SessionParamsCreator.kt | 2 +- .../sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt | 2 +- .../matrix/android/sdk/internal/auth/login/LoginTypeTest.kt | 2 +- .../android/sdk/test/fakes/internal/FakeSessionManager.kt | 2 +- .../test/fakes/internal/auth/FakeIsValidClientServerApiTask.kt | 2 +- .../sdk/test/fakes/internal/auth/FakePendingSessionStore.kt | 2 +- .../sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt | 3 +-- .../sdk/test/fakes/internal/auth/FakeSessionParamsStore.kt | 2 +- .../fakes/internal/auth/db/migration/Fake005MigrationRealm.kt | 2 +- .../auth/db/sessionparams/FakeCredentialsJsonAdapter.kt | 2 +- .../sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt | 2 +- .../auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt | 2 +- .../org/matrix/android/sdk/test/fixtures/CredentialsFixture.kt | 2 +- .../android/sdk/test/fixtures/DiscoveryInformationFixture.kt | 2 +- .../android/sdk/test/fixtures/SessionParamsEntityFixture.kt | 2 +- .../matrix/android/sdk/test/fixtures/SessionParamsFixture.kt | 2 +- .../android/sdk/test/fixtures/WellKnownBaseConfigFixture.kt | 2 +- vector/src/test/java/im/vector/app/test/fakes/FakeSession.kt | 2 +- 18 files changed, 18 insertions(+), 19 deletions(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionParamsCreator.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionParamsCreator.kt index 318389486e..607cab3c70 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionParamsCreator.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionParamsCreator.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt index 6b2432b5f6..95b226411b 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005Test.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt index 419dd50991..26741eba4b 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/FakeSessionManager.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/FakeSessionManager.kt index b251349249..2232ad9b4f 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/FakeSessionManager.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/FakeSessionManager.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeIsValidClientServerApiTask.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeIsValidClientServerApiTask.kt index f8018e7b7e..40681748c1 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeIsValidClientServerApiTask.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeIsValidClientServerApiTask.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakePendingSessionStore.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakePendingSessionStore.kt index be91daf910..8a18b75ca2 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakePendingSessionStore.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakePendingSessionStore.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt index 63cb02973c..79a3053f70 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.matrix.android.sdk.test.fakes.internal.auth import android.net.Uri diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsStore.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsStore.kt index 4336f6ba7c..22e8a32a32 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsStore.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsStore.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/migration/Fake005MigrationRealm.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/migration/Fake005MigrationRealm.kt index 147f8df969..13fd4a972c 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/migration/Fake005MigrationRealm.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/migration/Fake005MigrationRealm.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt index eea3e4fab1..f1cb4071fd 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeCredentialsJsonAdapter.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt index f0c5f10ebc..f85d6e2778 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeHomeServerConnectionConfigJsonAdapter.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt index 10c3664511..62b7f9fc20 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/CredentialsFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/CredentialsFixture.kt index 5002fe9153..2e7b36ff63 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/CredentialsFixture.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/CredentialsFixture.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/DiscoveryInformationFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/DiscoveryInformationFixture.kt index 4a15fd383a..c929a27d23 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/DiscoveryInformationFixture.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/DiscoveryInformationFixture.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsEntityFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsEntityFixture.kt index 29b5b1a7c9..bbea232a22 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsEntityFixture.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsEntityFixture.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt index 079b42b9e7..dad4b84fd0 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/WellKnownBaseConfigFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/WellKnownBaseConfigFixture.kt index 96a146587c..a33308dbd6 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/WellKnownBaseConfigFixture.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/WellKnownBaseConfigFixture.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/vector/src/test/java/im/vector/app/test/fakes/FakeSession.kt b/vector/src/test/java/im/vector/app/test/fakes/FakeSession.kt index a23c43b986..efb84f4892 100644 --- a/vector/src/test/java/im/vector/app/test/fakes/FakeSession.kt +++ b/vector/src/test/java/im/vector/app/test/fakes/FakeSession.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. From 04af8b23605e46bfb4785dd232747e24994c2708 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Mon, 7 Mar 2022 13:38:30 +0100 Subject: [PATCH 033/291] Changes LoginActivity onSignModeSelected SSO case --- .../src/main/java/im/vector/app/features/login/LoginActivity.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt b/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt index bf596fc6aa..499548ce78 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt @@ -252,7 +252,7 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA // It depends on the LoginMode when (state.loginMode) { LoginMode.Unknown, - is LoginMode.Sso -> error("Developer error") + is LoginMode.Sso, is LoginMode.SsoAndPassword, LoginMode.Password -> addFragmentToBackstack(views.loginFragmentContainer, LoginFragment::class.java, From 6836a125577da5218d12f169e4b7f3981446a35c Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Mon, 7 Mar 2022 13:49:23 +0100 Subject: [PATCH 034/291] Fixes legal comments --- .../java/org/matrix/android/sdk/test/fakes/api/FakeSession.kt | 2 +- vector/src/test/java/im/vector/app/test/fakes/FakeSession.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/api/FakeSession.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/api/FakeSession.kt index 5aac29c328..df22455fb1 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/api/FakeSession.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/api/FakeSession.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/vector/src/test/java/im/vector/app/test/fakes/FakeSession.kt b/vector/src/test/java/im/vector/app/test/fakes/FakeSession.kt index efb84f4892..18ed0e9957 100644 --- a/vector/src/test/java/im/vector/app/test/fakes/FakeSession.kt +++ b/vector/src/test/java/im/vector/app/test/fakes/FakeSession.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 The Matrix.org Foundation C.I.C. + * Copyright (c) 2022 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. From ec57ff1b030d690da47f7c0217ffcd701ac81bda Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Wed, 9 Mar 2022 11:07:39 +0100 Subject: [PATCH 035/291] Adds attempt at SSO session restore --- .../im/vector/app/features/login/LoginActivity.kt | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt b/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt index 499548ce78..f143929978 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt @@ -37,6 +37,7 @@ import im.vector.app.core.extensions.addFragment import im.vector.app.core.extensions.addFragmentToBackstack import im.vector.app.core.extensions.exhaustive import im.vector.app.core.platform.VectorBaseActivity +import im.vector.app.core.utils.openUrlInChromeCustomTab import im.vector.app.databinding.ActivityLoginBinding import im.vector.app.features.analytics.plan.MobileScreen import im.vector.app.features.home.HomeActivity @@ -252,7 +253,7 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA // It depends on the LoginMode when (state.loginMode) { LoginMode.Unknown, - is LoginMode.Sso, + is LoginMode.Sso -> launchSsoFlow() is LoginMode.SsoAndPassword, LoginMode.Password -> addFragmentToBackstack(views.loginFragmentContainer, LoginFragment::class.java, @@ -268,6 +269,16 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA }.exhaustive } + private fun launchSsoFlow() = withState(loginViewModel) { state -> + loginViewModel.getSsoUrl( + redirectUrl = SSORedirectRouterActivity.VECTOR_REDIRECT_URL, + deviceId = state.deviceId, + providerId = null, + )?.let { ssoUrl -> + openUrlInChromeCustomTab(this, null, ssoUrl) + } + } + /** * Handle the SSO redirection here */ From 70b5b9855a9dc558d8490e49d613913a53bb60e2 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Wed, 9 Mar 2022 12:26:52 +0100 Subject: [PATCH 036/291] Removes debug global error --- .../org/matrix/android/sdk/internal/session/sync/SyncTask.kt | 2 -- .../org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncTask.kt index a110f73ad2..b4da1a02cd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncTask.kt @@ -18,7 +18,6 @@ package org.matrix.android.sdk.internal.session.sync import android.os.SystemClock import okhttp3.ResponseBody -import org.matrix.android.sdk.api.failure.GlobalError import org.matrix.android.sdk.api.logger.LoggerTag import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.initsync.InitSyncStep @@ -152,7 +151,6 @@ internal class DefaultSyncTask @Inject constructor( defaultSyncStatusService.setStatus(SyncStatusService.Status.IncrementalSyncIdle) val syncResponse = try { executeRequest(globalErrorReceiver) { - globalErrorReceiver.handleGlobalError(GlobalError.InvalidToken(softLogout = true)) syncAPI.sync( params = requestParams, readTimeOut = readTimeOut diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt index 26741eba4b..95d143af3b 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt @@ -30,7 +30,7 @@ class LoginTypeTest { LoginType.fromValue(LoginType.UNKNOWN.value) shouldBeEqualTo LoginType.UNKNOWN } - @Test // This test failing means an existing type has not been correctly added to fromValue + @Test // The failure of this test means that an existing type has not been correctly added to fromValue fun `given non-unknown type value, when getting type fromValue, then type is not UNKNOWN`() { val types = LoginType.values() From ae540297b179162033ba0834ab178c81dbd34ec5 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Tue, 15 Mar 2022 14:53:59 +0100 Subject: [PATCH 037/291] Adds custom and direct login types --- .../android/sdk/internal/auth/login/DefaultLoginWizard.kt | 2 +- .../matrix/android/sdk/internal/auth/login/DirectLoginTask.kt | 2 +- .../org/matrix/android/sdk/internal/auth/login/LoginType.kt | 4 ++++ .../matrix/android/sdk/internal/auth/login/LoginTypeTest.kt | 2 ++ 4 files changed, 8 insertions(+), 2 deletions(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt index b4b81c7d35..489751c1e3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt @@ -98,7 +98,7 @@ internal class DefaultLoginWizard( authAPI.login(data) } - return sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig, LoginType.UNSUPPORTED) + return sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig, LoginType.CUSTOM) } override suspend fun resetPassword(email: String, newPassword: String) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt index 16f6a13977..787ea45eeb 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt @@ -77,7 +77,7 @@ internal class DefaultDirectLoginTask @Inject constructor( } } - return sessionCreator.createSession(credentials, params.homeServerConnectionConfig, LoginType.UNSUPPORTED) + return sessionCreator.createSession(credentials, params.homeServerConnectionConfig, LoginType.DIRECT) } private fun buildClient(homeServerConnectionConfig: HomeServerConnectionConfig): OkHttpClient { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt index d14ef12bb6..31d8b01d38 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt @@ -20,6 +20,8 @@ enum class LoginType(val value: String) { PASSWORD("password"), SSO("sso"), UNSUPPORTED("unsupported"), + CUSTOM("custom"), + DIRECT("direct"), UNKNOWN("unknown"); companion object { @@ -28,6 +30,8 @@ enum class LoginType(val value: String) { PASSWORD.value -> PASSWORD SSO.value -> SSO UNSUPPORTED.value -> UNSUPPORTED + CUSTOM.value -> CUSTOM + DIRECT.value -> DIRECT else -> UNKNOWN } } diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt index 95d143af3b..1650c863de 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt @@ -27,6 +27,8 @@ class LoginTypeTest { LoginType.fromValue(LoginType.PASSWORD.value) shouldBeEqualTo LoginType.PASSWORD LoginType.fromValue(LoginType.SSO.value) shouldBeEqualTo LoginType.SSO LoginType.fromValue(LoginType.UNSUPPORTED.value) shouldBeEqualTo LoginType.UNSUPPORTED + LoginType.fromValue(LoginType.CUSTOM.value) shouldBeEqualTo LoginType.CUSTOM + LoginType.fromValue(LoginType.DIRECT.value) shouldBeEqualTo LoginType.DIRECT LoginType.fromValue(LoginType.UNKNOWN.value) shouldBeEqualTo LoginType.UNKNOWN } From a173accfa5c2b5b9a0741723b3eee15269893336 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Tue, 15 Mar 2022 14:59:09 +0100 Subject: [PATCH 038/291] Replaces use of LoginType.value with name --- .../internal/auth/db/SessionParamsMapper.kt | 4 +-- .../sdk/internal/auth/login/LoginType.kt | 26 +++++++++---------- .../sdk/internal/auth/login/LoginTypeTest.kt | 18 ++++++------- .../FakeSessionParamsMapperMoshi.kt | 4 +-- 4 files changed, 26 insertions(+), 26 deletions(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapper.kt index e359577ff3..20de72dc8f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapper.kt @@ -38,7 +38,7 @@ internal class SessionParamsMapper @Inject constructor(moshi: Moshi) { if (credentials == null || homeServerConnectionConfig == null) { return null } - return SessionParams(credentials, homeServerConnectionConfig, entity.isTokenValid, LoginType.fromValue(entity.loginType)) + return SessionParams(credentials, homeServerConnectionConfig, entity.isTokenValid, LoginType.fromName(entity.loginType)) } fun map(sessionParams: SessionParams?): SessionParamsEntity? { @@ -56,7 +56,7 @@ internal class SessionParamsMapper @Inject constructor(moshi: Moshi) { credentialsJson, homeServerConnectionConfigJson, sessionParams.isTokenValid, - sessionParams.loginType.value, + sessionParams.loginType.name, ) } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt index 31d8b01d38..5bc38d81fc 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt @@ -16,22 +16,22 @@ package org.matrix.android.sdk.internal.auth.login -enum class LoginType(val value: String) { - PASSWORD("password"), - SSO("sso"), - UNSUPPORTED("unsupported"), - CUSTOM("custom"), - DIRECT("direct"), - UNKNOWN("unknown"); +enum class LoginType { + PASSWORD, + SSO, + UNSUPPORTED, + CUSTOM, + DIRECT, + UNKNOWN; companion object { - fun fromValue(value: String) = when (value) { - PASSWORD.value -> PASSWORD - SSO.value -> SSO - UNSUPPORTED.value -> UNSUPPORTED - CUSTOM.value -> CUSTOM - DIRECT.value -> DIRECT + fun fromName(name: String) = when (name) { + PASSWORD.name -> PASSWORD + SSO.name -> SSO + UNSUPPORTED.name -> UNSUPPORTED + CUSTOM.name -> CUSTOM + DIRECT.name -> DIRECT else -> UNKNOWN } } diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt index 1650c863de..341d09765c 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt @@ -23,22 +23,22 @@ import org.junit.Test class LoginTypeTest { @Test - fun `when getting type fromValue, then map correctly`() { - LoginType.fromValue(LoginType.PASSWORD.value) shouldBeEqualTo LoginType.PASSWORD - LoginType.fromValue(LoginType.SSO.value) shouldBeEqualTo LoginType.SSO - LoginType.fromValue(LoginType.UNSUPPORTED.value) shouldBeEqualTo LoginType.UNSUPPORTED - LoginType.fromValue(LoginType.CUSTOM.value) shouldBeEqualTo LoginType.CUSTOM - LoginType.fromValue(LoginType.DIRECT.value) shouldBeEqualTo LoginType.DIRECT - LoginType.fromValue(LoginType.UNKNOWN.value) shouldBeEqualTo LoginType.UNKNOWN + fun `when getting type fromName, then map correctly`() { + LoginType.fromName(LoginType.PASSWORD.name) shouldBeEqualTo LoginType.PASSWORD + LoginType.fromName(LoginType.SSO.name) shouldBeEqualTo LoginType.SSO + LoginType.fromName(LoginType.UNSUPPORTED.name) shouldBeEqualTo LoginType.UNSUPPORTED + LoginType.fromName(LoginType.CUSTOM.name) shouldBeEqualTo LoginType.CUSTOM + LoginType.fromName(LoginType.DIRECT.name) shouldBeEqualTo LoginType.DIRECT + LoginType.fromName(LoginType.UNKNOWN.name) shouldBeEqualTo LoginType.UNKNOWN } @Test // The failure of this test means that an existing type has not been correctly added to fromValue - fun `given non-unknown type value, when getting type fromValue, then type is not UNKNOWN`() { + fun `given non-unknown type name, when getting type fromName, then type is not UNKNOWN`() { val types = LoginType.values() types.forEach { type -> if (type != LoginType.UNKNOWN) { - LoginType.fromValue(type.value) shouldNotBeEqualTo LoginType.UNKNOWN + LoginType.fromName(type.name) shouldNotBeEqualTo LoginType.UNKNOWN } } } diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt index 62b7f9fc20..bc5a2fa7ca 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt @@ -54,7 +54,7 @@ internal class FakeSessionParamsMapperMoshi { credentials, homeServerConnectionConfig, sessionParamsEntity.isTokenValid, - LoginType.fromValue(sessionParamsEntity.loginType) + LoginType.fromName(sessionParamsEntity.loginType) ) } @@ -69,7 +69,7 @@ internal class FakeSessionParamsMapperMoshi { CREDENTIALS_JSON, HOME_SERVER_CONNECTION_CONFIG_JSON, sessionParams.isTokenValid, - sessionParams.loginType.value, + sessionParams.loginType.name, ) } From ef59faf160107fc7c0bc0e740439c6a0818b6f74 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Tue, 15 Mar 2022 15:05:33 +0100 Subject: [PATCH 039/291] Adds error throw for LoginActivity LoginMode Unknown --- .../registration/DefaultRegistrationWizard.kt | 98 ++++---- .../app/features/login/LoginActivity.kt | 230 +++++++++--------- 2 files changed, 165 insertions(+), 163 deletions(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt index c76d24b3d0..9e715be193 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt @@ -35,9 +35,9 @@ import org.matrix.android.sdk.internal.auth.login.LoginType * This class execute the registration request and is responsible to keep the session of interactive authentication */ internal class DefaultRegistrationWizard( - authAPI: AuthAPI, - private val sessionCreator: SessionCreator, - private val pendingSessionStore: PendingSessionStore + authAPI: AuthAPI, + private val sessionCreator: SessionCreator, + private val pendingSessionStore: PendingSessionStore ) : RegistrationWizard { private var pendingSessionData: PendingSessionData = pendingSessionStore.getPendingSessionData() ?: error("Pending session data should exist here") @@ -50,12 +50,12 @@ internal class DefaultRegistrationWizard( override val currentThreePid: String? get() { return when (val threePid = pendingSessionData.currentThreePidData?.threePid) { - is RegisterThreePid.Email -> threePid.email + is RegisterThreePid.Email -> threePid.email is RegisterThreePid.Msisdn -> { // Take formatted msisdn if provided by the server pendingSessionData.currentThreePidData?.addThreePidRegistrationResponse?.formattedMsisdn?.takeIf { it.isNotBlank() } ?: threePid.msisdn } - null -> null + null -> null } } @@ -67,24 +67,26 @@ internal class DefaultRegistrationWizard( return performRegistrationRequest(params, LoginType.PASSWORD) } - override suspend fun createAccount(userName: String?, - password: String?, - initialDeviceDisplayName: String?): RegistrationResult { + override suspend fun createAccount( + userName: String?, + password: String?, + initialDeviceDisplayName: String? + ): RegistrationResult { val params = RegistrationParams( - username = userName, - password = password, - initialDeviceDisplayName = initialDeviceDisplayName + username = userName, + password = password, + initialDeviceDisplayName = initialDeviceDisplayName ) return performRegistrationRequest(params, LoginType.PASSWORD) - .also { - pendingSessionData = pendingSessionData.copy(isRegistrationStarted = true) - .also { pendingSessionStore.savePendingSessionData(it) } - } + .also { + pendingSessionData = pendingSessionData.copy(isRegistrationStarted = true) + .also { pendingSessionStore.savePendingSessionData(it) } + } } override suspend fun performReCaptcha(response: String): RegistrationResult { val safeSession = pendingSessionData.currentSession - ?: throw IllegalStateException("developer error, call createAccount() method first") + ?: throw IllegalStateException("developer error, call createAccount() method first") val params = RegistrationParams(auth = AuthParams.createForCaptcha(safeSession, response)) return performRegistrationRequest(params, LoginType.PASSWORD) @@ -92,7 +94,7 @@ internal class DefaultRegistrationWizard( override suspend fun acceptTerms(): RegistrationResult { val safeSession = pendingSessionData.currentSession - ?: throw IllegalStateException("developer error, call createAccount() method first") + ?: throw IllegalStateException("developer error, call createAccount() method first") val params = RegistrationParams(auth = AuthParams(type = LoginFlowTypes.TERMS, session = safeSession)) return performRegistrationRequest(params, LoginType.PASSWORD) @@ -100,14 +102,14 @@ internal class DefaultRegistrationWizard( override suspend fun addThreePid(threePid: RegisterThreePid): RegistrationResult { pendingSessionData = pendingSessionData.copy(currentThreePidData = null) - .also { pendingSessionStore.savePendingSessionData(it) } + .also { pendingSessionStore.savePendingSessionData(it) } return sendThreePid(threePid) } override suspend fun sendAgainThreePid(): RegistrationResult { val safeCurrentThreePid = pendingSessionData.currentThreePidData?.threePid - ?: throw IllegalStateException("developer error, call createAccount() method first") + ?: throw IllegalStateException("developer error, call createAccount() method first") return sendThreePid(safeCurrentThreePid) } @@ -115,34 +117,34 @@ internal class DefaultRegistrationWizard( private suspend fun sendThreePid(threePid: RegisterThreePid): RegistrationResult { val safeSession = pendingSessionData.currentSession ?: throw IllegalStateException("developer error, call createAccount() method first") val response = registerAddThreePidTask.execute( - RegisterAddThreePidTask.Params( - threePid, - pendingSessionData.clientSecret, - pendingSessionData.sendAttempt)) + RegisterAddThreePidTask.Params( + threePid, + pendingSessionData.clientSecret, + pendingSessionData.sendAttempt)) pendingSessionData = pendingSessionData.copy(sendAttempt = pendingSessionData.sendAttempt + 1) - .also { pendingSessionStore.savePendingSessionData(it) } + .also { pendingSessionStore.savePendingSessionData(it) } val params = RegistrationParams( - auth = if (threePid is RegisterThreePid.Email) { - AuthParams.createForEmailIdentity(safeSession, - ThreePidCredentials( - clientSecret = pendingSessionData.clientSecret, - sid = response.sid - ) + auth = if (threePid is RegisterThreePid.Email) { + AuthParams.createForEmailIdentity(safeSession, + ThreePidCredentials( + clientSecret = pendingSessionData.clientSecret, + sid = response.sid ) - } else { - AuthParams.createForMsisdnIdentity(safeSession, - ThreePidCredentials( - clientSecret = pendingSessionData.clientSecret, - sid = response.sid - ) + ) + } else { + AuthParams.createForMsisdnIdentity(safeSession, + ThreePidCredentials( + clientSecret = pendingSessionData.clientSecret, + sid = response.sid ) - } + ) + } ) // Store data pendingSessionData = pendingSessionData.copy(currentThreePidData = ThreePidData.from(threePid, response, params)) - .also { pendingSessionStore.savePendingSessionData(it) } + .also { pendingSessionStore.savePendingSessionData(it) } // and send the sid a first time return performRegistrationRequest(params, LoginType.PASSWORD) @@ -150,7 +152,7 @@ internal class DefaultRegistrationWizard( override suspend fun checkIfEmailHasBeenValidated(delayMillis: Long): RegistrationResult { val safeParam = pendingSessionData.currentThreePidData?.registrationParams - ?: throw IllegalStateException("developer error, no pending three pid") + ?: throw IllegalStateException("developer error, no pending three pid") return performRegistrationRequest(safeParam, LoginType.PASSWORD, delayMillis) } @@ -161,13 +163,13 @@ internal class DefaultRegistrationWizard( private suspend fun validateThreePid(code: String): RegistrationResult { val registrationParams = pendingSessionData.currentThreePidData?.registrationParams - ?: throw IllegalStateException("developer error, no pending three pid") + ?: throw IllegalStateException("developer error, no pending three pid") val safeCurrentData = pendingSessionData.currentThreePidData ?: throw IllegalStateException("developer error, call createAccount() method first") val url = safeCurrentData.addThreePidRegistrationResponse.submitUrl ?: throw IllegalStateException("Missing url to send the code") val validationBody = ValidationCodeBody( - clientSecret = pendingSessionData.clientSecret, - sid = safeCurrentData.addThreePidRegistrationResponse.sid, - code = code + clientSecret = pendingSessionData.clientSecret, + sid = safeCurrentData.addThreePidRegistrationResponse.sid, + code = code ) val validationResponse = validateCodeTask.execute(ValidateCodeTask.Params(url, validationBody)) if (validationResponse.isSuccess()) { @@ -182,16 +184,16 @@ internal class DefaultRegistrationWizard( override suspend fun dummy(): RegistrationResult { val safeSession = pendingSessionData.currentSession - ?: throw IllegalStateException("developer error, call createAccount() method first") + ?: throw IllegalStateException("developer error, call createAccount() method first") val params = RegistrationParams(auth = AuthParams(type = LoginFlowTypes.DUMMY, session = safeSession)) return performRegistrationRequest(params, LoginType.PASSWORD) } private suspend fun performRegistrationRequest( - registrationParams: RegistrationParams, - loginType: LoginType, - delayMillis: Long = 0, + registrationParams: RegistrationParams, + loginType: LoginType, + delayMillis: Long = 0, ): RegistrationResult { delay(delayMillis) val credentials = try { @@ -199,7 +201,7 @@ internal class DefaultRegistrationWizard( } catch (exception: Throwable) { if (exception is RegistrationFlowError) { pendingSessionData = pendingSessionData.copy(currentSession = exception.registrationFlowResponse.session) - .also { pendingSessionStore.savePendingSessionData(it) } + .also { pendingSessionStore.savePendingSessionData(it) } return RegistrationResult.FlowResponse(exception.registrationFlowResponse.toFlowResult()) } else { throw exception diff --git a/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt b/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt index f143929978..b2be245c0e 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt @@ -69,11 +69,11 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA private val commonOption: (FragmentTransaction) -> Unit = { ft -> // Find the loginLogo on the current Fragment, this should not return null (topFragment?.view as? ViewGroup) - // Find findViewById does not work, I do not know why - // findViewById(R.id.loginLogo) - ?.children - ?.firstOrNull { it.id == R.id.loginLogo } - ?.let { ft.addSharedElement(it, ViewCompat.getTransitionName(it) ?: "") } + // Find findViewById does not work, I do not know why + // findViewById(R.id.loginLogo) + ?.children + ?.firstOrNull { it.id == R.id.loginLogo } + ?.let { ft.addSharedElement(it, ViewCompat.getTransitionName(it) ?: "") } ft.setCustomAnimations(enterAnim, exitAnim, popEnterAnim, popExitAnim) } @@ -107,7 +107,7 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA private fun handleLoginViewEvents(loginViewEvents: LoginViewEvents) { when (loginViewEvents) { - is LoginViewEvents.RegistrationFlowResult -> { + is LoginViewEvents.RegistrationFlowResult -> { // Check that all flows are supported by the application if (loginViewEvents.flowResult.missingStages.any { !it.isSupported() }) { // Display a popup to propose use web fallback @@ -121,80 +121,80 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA // I add a tag to indicate that this fragment is a registration stage. // This way it will be automatically popped in when starting the next registration stage addFragmentToBackstack(views.loginFragmentContainer, - LoginFragment::class.java, - tag = FRAGMENT_REGISTRATION_STAGE_TAG, - option = commonOption + LoginFragment::class.java, + tag = FRAGMENT_REGISTRATION_STAGE_TAG, + option = commonOption ) } } } - is LoginViewEvents.OutdatedHomeserver -> { + is LoginViewEvents.OutdatedHomeserver -> { MaterialAlertDialogBuilder(this) - .setTitle(R.string.login_error_outdated_homeserver_title) - .setMessage(R.string.login_error_outdated_homeserver_warning_content) - .setPositiveButton(R.string.ok, null) - .show() + .setTitle(R.string.login_error_outdated_homeserver_title) + .setMessage(R.string.login_error_outdated_homeserver_warning_content) + .setPositiveButton(R.string.ok, null) + .show() Unit } - is LoginViewEvents.OpenServerSelection -> + is LoginViewEvents.OpenServerSelection -> addFragmentToBackstack(views.loginFragmentContainer, - LoginServerSelectionFragment::class.java, - option = { ft -> - findViewById(R.id.loginSplashLogo)?.let { ft.addSharedElement(it, ViewCompat.getTransitionName(it) ?: "") } - // Disable transition of text - // findViewById(R.id.loginSplashTitle)?.let { ft.addSharedElement(it, ViewCompat.getTransitionName(it) ?: "") } - // No transition here now actually - // findViewById(R.id.loginSplashSubmit)?.let { ft.addSharedElement(it, ViewCompat.getTransitionName(it) ?: "") } - // TODO Disabled because it provokes a flickering - // ft.setCustomAnimations(enterAnim, exitAnim, popEnterAnim, popExitAnim) - }) - is LoginViewEvents.OnServerSelectionDone -> onServerSelectionDone(loginViewEvents) - is LoginViewEvents.OnSignModeSelected -> onSignModeSelected(loginViewEvents) - is LoginViewEvents.OnLoginFlowRetrieved -> + LoginServerSelectionFragment::class.java, + option = { ft -> + findViewById(R.id.loginSplashLogo)?.let { ft.addSharedElement(it, ViewCompat.getTransitionName(it) ?: "") } + // Disable transition of text + // findViewById(R.id.loginSplashTitle)?.let { ft.addSharedElement(it, ViewCompat.getTransitionName(it) ?: "") } + // No transition here now actually + // findViewById(R.id.loginSplashSubmit)?.let { ft.addSharedElement(it, ViewCompat.getTransitionName(it) ?: "") } + // TODO Disabled because it provokes a flickering + // ft.setCustomAnimations(enterAnim, exitAnim, popEnterAnim, popExitAnim) + }) + is LoginViewEvents.OnServerSelectionDone -> onServerSelectionDone(loginViewEvents) + is LoginViewEvents.OnSignModeSelected -> onSignModeSelected(loginViewEvents) + is LoginViewEvents.OnLoginFlowRetrieved -> addFragmentToBackstack(views.loginFragmentContainer, - LoginSignUpSignInSelectionFragment::class.java, - option = commonOption) - is LoginViewEvents.OnWebLoginError -> onWebLoginError(loginViewEvents) - is LoginViewEvents.OnForgetPasswordClicked -> + LoginSignUpSignInSelectionFragment::class.java, + option = commonOption) + is LoginViewEvents.OnWebLoginError -> onWebLoginError(loginViewEvents) + is LoginViewEvents.OnForgetPasswordClicked -> addFragmentToBackstack(views.loginFragmentContainer, - LoginResetPasswordFragment::class.java, - option = commonOption) - is LoginViewEvents.OnResetPasswordSendThreePidDone -> { + LoginResetPasswordFragment::class.java, + option = commonOption) + is LoginViewEvents.OnResetPasswordSendThreePidDone -> { supportFragmentManager.popBackStack(FRAGMENT_LOGIN_TAG, POP_BACK_STACK_EXCLUSIVE) addFragmentToBackstack(views.loginFragmentContainer, - LoginResetPasswordMailConfirmationFragment::class.java, - option = commonOption) + LoginResetPasswordMailConfirmationFragment::class.java, + option = commonOption) } - is LoginViewEvents.OnResetPasswordMailConfirmationSuccess -> { + is LoginViewEvents.OnResetPasswordMailConfirmationSuccess -> { supportFragmentManager.popBackStack(FRAGMENT_LOGIN_TAG, POP_BACK_STACK_EXCLUSIVE) addFragmentToBackstack(views.loginFragmentContainer, - LoginResetPasswordSuccessFragment::class.java, - option = commonOption) + LoginResetPasswordSuccessFragment::class.java, + option = commonOption) } is LoginViewEvents.OnResetPasswordMailConfirmationSuccessDone -> { // Go back to the login fragment supportFragmentManager.popBackStack(FRAGMENT_LOGIN_TAG, POP_BACK_STACK_EXCLUSIVE) } - is LoginViewEvents.OnSendEmailSuccess -> { + is LoginViewEvents.OnSendEmailSuccess -> { // Pop the enter email Fragment supportFragmentManager.popBackStack(FRAGMENT_REGISTRATION_STAGE_TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE) addFragmentToBackstack(views.loginFragmentContainer, - LoginWaitForEmailFragment::class.java, - LoginWaitForEmailFragmentArgument(loginViewEvents.email), - tag = FRAGMENT_REGISTRATION_STAGE_TAG, - option = commonOption) + LoginWaitForEmailFragment::class.java, + LoginWaitForEmailFragmentArgument(loginViewEvents.email), + tag = FRAGMENT_REGISTRATION_STAGE_TAG, + option = commonOption) } - is LoginViewEvents.OnSendMsisdnSuccess -> { + is LoginViewEvents.OnSendMsisdnSuccess -> { // Pop the enter Msisdn Fragment supportFragmentManager.popBackStack(FRAGMENT_REGISTRATION_STAGE_TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE) addFragmentToBackstack(views.loginFragmentContainer, - LoginGenericTextInputFormFragment::class.java, - LoginGenericTextInputFormFragmentArgument(TextInputFormFragmentMode.ConfirmMsisdn, true, loginViewEvents.msisdn), - tag = FRAGMENT_REGISTRATION_STAGE_TAG, - option = commonOption) + LoginGenericTextInputFormFragment::class.java, + LoginGenericTextInputFormFragmentArgument(TextInputFormFragmentMode.ConfirmMsisdn, true, loginViewEvents.msisdn), + tag = FRAGMENT_REGISTRATION_STAGE_TAG, + option = commonOption) } is LoginViewEvents.Failure, - is LoginViewEvents.Loading -> + is LoginViewEvents.Loading -> // This is handled by the Fragments Unit }.exhaustive @@ -207,8 +207,8 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA analyticsScreenName = MobileScreen.ScreenName.Register } val intent = HomeActivity.newIntent( - this, - accountCreation = loginViewState.signMode == SignMode.SignUp + this, + accountCreation = loginViewState.signMode == SignMode.SignUp ) startActivity(intent) finish() @@ -225,55 +225,55 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA // And inform the user MaterialAlertDialogBuilder(this) - .setTitle(R.string.dialog_title_error) - .setMessage(getString(R.string.login_sso_error_message, onWebLoginError.description, onWebLoginError.errorCode)) - .setPositiveButton(R.string.ok, null) - .show() + .setTitle(R.string.dialog_title_error) + .setMessage(getString(R.string.login_sso_error_message, onWebLoginError.description, onWebLoginError.errorCode)) + .setPositiveButton(R.string.ok, null) + .show() } private fun onServerSelectionDone(loginViewEvents: LoginViewEvents.OnServerSelectionDone) { when (loginViewEvents.serverType) { ServerType.MatrixOrg -> Unit // In this case, we wait for the login flow ServerType.EMS, - ServerType.Other -> addFragmentToBackstack(views.loginFragmentContainer, - LoginServerUrlFormFragment::class.java, - option = commonOption) - ServerType.Unknown -> Unit /* Should not happen */ + ServerType.Other -> addFragmentToBackstack(views.loginFragmentContainer, + LoginServerUrlFormFragment::class.java, + option = commonOption) + ServerType.Unknown -> Unit /* Should not happen */ } } private fun onSignModeSelected(loginViewEvents: LoginViewEvents.OnSignModeSelected) = withState(loginViewModel) { state -> // state.signMode could not be ready yet. So use value from the ViewEvent when (loginViewEvents.signMode) { - SignMode.Unknown -> error("Sign mode has to be set before calling this method") - SignMode.SignUp -> { + SignMode.Unknown -> error("Sign mode has to be set before calling this method") + SignMode.SignUp -> { // This is managed by the LoginViewEvents } - SignMode.SignIn -> { + SignMode.SignIn -> { // It depends on the LoginMode when (state.loginMode) { - LoginMode.Unknown, + LoginMode.Unknown -> error("Developer error") is LoginMode.Sso -> launchSsoFlow() is LoginMode.SsoAndPassword, - LoginMode.Password -> addFragmentToBackstack(views.loginFragmentContainer, - LoginFragment::class.java, - tag = FRAGMENT_LOGIN_TAG, - option = commonOption) + LoginMode.Password -> addFragmentToBackstack(views.loginFragmentContainer, + LoginFragment::class.java, + tag = FRAGMENT_LOGIN_TAG, + option = commonOption) LoginMode.Unsupported -> onLoginModeNotSupported(state.loginModeSupportedTypes) }.exhaustive } SignMode.SignInWithMatrixId -> addFragmentToBackstack(views.loginFragmentContainer, - LoginFragment::class.java, - tag = FRAGMENT_LOGIN_TAG, - option = commonOption) + LoginFragment::class.java, + tag = FRAGMENT_LOGIN_TAG, + option = commonOption) }.exhaustive } private fun launchSsoFlow() = withState(loginViewModel) { state -> loginViewModel.getSsoUrl( - redirectUrl = SSORedirectRouterActivity.VECTOR_REDIRECT_URL, - deviceId = state.deviceId, - providerId = null, + redirectUrl = SSORedirectRouterActivity.VECTOR_REDIRECT_URL, + deviceId = state.deviceId, + providerId = null, )?.let { ssoUrl -> openUrlInChromeCustomTab(this, null, ssoUrl) } @@ -286,34 +286,34 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA super.onNewIntent(intent) intent?.data - ?.let { tryOrNull { it.getQueryParameter("loginToken") } } - ?.let { loginViewModel.handle(LoginAction.LoginWithToken(it)) } + ?.let { tryOrNull { it.getQueryParameter("loginToken") } } + ?.let { loginViewModel.handle(LoginAction.LoginWithToken(it)) } } private fun onRegistrationStageNotSupported() { MaterialAlertDialogBuilder(this) - .setTitle(R.string.app_name) - .setMessage(getString(R.string.login_registration_not_supported)) - .setPositiveButton(R.string.yes) { _, _ -> - addFragmentToBackstack(views.loginFragmentContainer, - LoginWebFragment::class.java, - option = commonOption) - } - .setNegativeButton(R.string.no, null) - .show() + .setTitle(R.string.app_name) + .setMessage(getString(R.string.login_registration_not_supported)) + .setPositiveButton(R.string.yes) { _, _ -> + addFragmentToBackstack(views.loginFragmentContainer, + LoginWebFragment::class.java, + option = commonOption) + } + .setNegativeButton(R.string.no, null) + .show() } private fun onLoginModeNotSupported(supportedTypes: List) { MaterialAlertDialogBuilder(this) - .setTitle(R.string.app_name) - .setMessage(getString(R.string.login_mode_not_supported, supportedTypes.joinToString { "'$it'" })) - .setPositiveButton(R.string.yes) { _, _ -> - addFragmentToBackstack(views.loginFragmentContainer, - LoginWebFragment::class.java, - option = commonOption) - } - .setNegativeButton(R.string.no, null) - .show() + .setTitle(R.string.app_name) + .setMessage(getString(R.string.login_mode_not_supported, supportedTypes.joinToString { "'$it'" })) + .setPositiveButton(R.string.yes) { _, _ -> + addFragmentToBackstack(views.loginFragmentContainer, + LoginWebFragment::class.java, + option = commonOption) + } + .setNegativeButton(R.string.no, null) + .show() } private fun handleRegistrationNavigation(flowResult: FlowResult) { @@ -339,26 +339,26 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA when (stage) { is Stage.ReCaptcha -> addFragmentToBackstack(views.loginFragmentContainer, - LoginCaptchaFragment::class.java, - LoginCaptchaFragmentArgument(stage.publicKey), - tag = FRAGMENT_REGISTRATION_STAGE_TAG, - option = commonOption) - is Stage.Email -> addFragmentToBackstack(views.loginFragmentContainer, - LoginGenericTextInputFormFragment::class.java, - LoginGenericTextInputFormFragmentArgument(TextInputFormFragmentMode.SetEmail, stage.mandatory), - tag = FRAGMENT_REGISTRATION_STAGE_TAG, - option = commonOption) - is Stage.Msisdn -> addFragmentToBackstack(views.loginFragmentContainer, - LoginGenericTextInputFormFragment::class.java, - LoginGenericTextInputFormFragmentArgument(TextInputFormFragmentMode.SetMsisdn, stage.mandatory), - tag = FRAGMENT_REGISTRATION_STAGE_TAG, - option = commonOption) - is Stage.Terms -> addFragmentToBackstack(views.loginFragmentContainer, - LoginTermsFragment::class.java, - LoginTermsFragmentArgument(stage.policies.toLocalizedLoginTerms(getString(R.string.resources_language))), - tag = FRAGMENT_REGISTRATION_STAGE_TAG, - option = commonOption) - else -> Unit // Should not happen + LoginCaptchaFragment::class.java, + LoginCaptchaFragmentArgument(stage.publicKey), + tag = FRAGMENT_REGISTRATION_STAGE_TAG, + option = commonOption) + is Stage.Email -> addFragmentToBackstack(views.loginFragmentContainer, + LoginGenericTextInputFormFragment::class.java, + LoginGenericTextInputFormFragmentArgument(TextInputFormFragmentMode.SetEmail, stage.mandatory), + tag = FRAGMENT_REGISTRATION_STAGE_TAG, + option = commonOption) + is Stage.Msisdn -> addFragmentToBackstack(views.loginFragmentContainer, + LoginGenericTextInputFormFragment::class.java, + LoginGenericTextInputFormFragmentArgument(TextInputFormFragmentMode.SetMsisdn, stage.mandatory), + tag = FRAGMENT_REGISTRATION_STAGE_TAG, + option = commonOption) + is Stage.Terms -> addFragmentToBackstack(views.loginFragmentContainer, + LoginTermsFragment::class.java, + LoginTermsFragmentArgument(stage.policies.toLocalizedLoginTerms(getString(R.string.resources_language))), + tag = FRAGMENT_REGISTRATION_STAGE_TAG, + option = commonOption) + else -> Unit // Should not happen } } From 21459db63408cfe4d83ef5ebfbd4ef636874b10a Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Tue, 15 Mar 2022 15:23:03 +0100 Subject: [PATCH 040/291] Replaces login type unknown value with name in migration --- .../android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt index 868f62b8cd..9c5095e478 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt @@ -30,6 +30,6 @@ class MigrateAuthTo005(realm: DynamicRealm) : RealmMigrator(realm, 5) { realm.schema.get("SessionParamsEntity") ?.addField(SessionParamsEntityFields.LOGIN_TYPE, String::class.java) ?.setRequired(SessionParamsEntityFields.LOGIN_TYPE, true) - ?.transform { it.set(SessionParamsEntityFields.LOGIN_TYPE, LoginType.UNKNOWN.value) } + ?.transform { it.set(SessionParamsEntityFields.LOGIN_TYPE, LoginType.UNKNOWN.name) } } } From 5fcae7f4e6c87190240a811fd3fbd516d9afbcb9 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Tue, 15 Mar 2022 18:03:54 +0100 Subject: [PATCH 041/291] Adds direct and custom types to soft logout disambiguation --- .../signout/soft/SoftLogoutController.kt | 32 ++++++++++--------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt index 6742894fde..439f9ecdb5 100644 --- a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt +++ b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt @@ -40,8 +40,8 @@ import org.matrix.android.sdk.internal.auth.login.LoginType import javax.inject.Inject class SoftLogoutController @Inject constructor( - private val stringProvider: StringProvider, - private val errorFormatter: ErrorFormatter + private val stringProvider: StringProvider, + private val errorFormatter: ErrorFormatter ) : EpoxyController() { var listener: Listener? = null @@ -77,9 +77,9 @@ class SoftLogoutController @Inject constructor( loginTextItem { id("signText1") text(host.stringProvider.getString(R.string.soft_logout_signin_notice, - state.homeServerUrl.toReducedUrl(), - state.userDisplayName, - state.userId)) + state.homeServerUrl.toReducedUrl(), + state.userDisplayName, + state.userId)) } if (state.hasUnsavedKeys) { loginTextItem { @@ -90,9 +90,9 @@ class SoftLogoutController @Inject constructor( } private fun buildForm(state: SoftLogoutViewState) = when (state.asyncHomeServerLoginFlowRequest) { - is Incomplete -> buildLoadingItem() - is Fail -> buildLoginErrorWithRetryItem(state.asyncHomeServerLoginFlowRequest.error) - is Success -> buildLoginSuccessItem(state) + is Incomplete -> buildLoadingItem() + is Fail -> buildLoginErrorWithRetryItem(state.asyncHomeServerLoginFlowRequest.error) + is Success -> buildLoginSuccessItem(state) is Loading, Uninitialized -> Unit } @@ -112,11 +112,11 @@ class SoftLogoutController @Inject constructor( } private fun buildLoginSuccessItem(state: SoftLogoutViewState) = when (state.asyncHomeServerLoginFlowRequest.invoke()) { - LoginMode.Password -> buildLoginPasswordForm(state) - is LoginMode.Sso -> buildLoginSSOForm() + LoginMode.Password -> buildLoginPasswordForm(state) + is LoginMode.Sso -> buildLoginSSOForm() is LoginMode.SsoAndPassword -> disambiguateLoginSSOAndPasswordForm(state) - LoginMode.Unsupported -> buildLoginUnsupportedForm() - LoginMode.Unknown, null -> Unit // Should not happen + LoginMode.Unsupported -> buildLoginUnsupportedForm() + LoginMode.Unknown, null -> Unit // Should not happen } private fun buildLoginPasswordForm(state: SoftLogoutViewState) { @@ -144,10 +144,12 @@ class SoftLogoutController @Inject constructor( private fun disambiguateLoginSSOAndPasswordForm(state: SoftLogoutViewState) { when (state.loginType) { - LoginType.PASSWORD -> buildLoginPasswordForm(state) - LoginType.SSO -> buildLoginSSOForm() + LoginType.PASSWORD -> buildLoginPasswordForm(state) + LoginType.SSO -> buildLoginSSOForm() + LoginType.DIRECT, + LoginType.CUSTOM, LoginType.UNSUPPORTED -> buildLoginUnsupportedForm() - LoginType.UNKNOWN -> Unit + LoginType.UNKNOWN -> Unit } } From 92d177a68e9e8fe5846040de642eb4d02bb8681a Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Wed, 20 Apr 2022 20:05:54 +0200 Subject: [PATCH 042/291] Makes MigrateAuthTo005 class internal --- .../android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt index 9c5095e478..82996928de 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt @@ -22,7 +22,7 @@ import org.matrix.android.sdk.internal.auth.login.LoginType import org.matrix.android.sdk.internal.util.database.RealmMigrator import timber.log.Timber -class MigrateAuthTo005(realm: DynamicRealm) : RealmMigrator(realm, 5) { +internal class MigrateAuthTo005(realm: DynamicRealm) : RealmMigrator(realm, 5) { override fun doMigrate(realm: DynamicRealm) { Timber.d("Update SessionParamsEntity to add LoginType") From 6a3044cb2ec21c5bdcb423a27f0d27778d8d3fc1 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Tue, 17 May 2022 14:46:02 +0200 Subject: [PATCH 043/291] Fixes post merge errors --- .../registration/DefaultRegistrationWizard.kt | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt index 765d4ec20d..ff7bcb0303 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt @@ -207,7 +207,7 @@ internal class DefaultRegistrationWizard( mutableParams["session"] = safeSession val params = RegistrationCustomParams(auth = mutableParams) - return performRegistrationOtherRequest(params) + return performRegistrationOtherRequest(LoginType.CUSTOM, params) } private suspend fun performRegistrationRequest( @@ -216,17 +216,19 @@ internal class DefaultRegistrationWizard( delayMillis: Long = 0 ): RegistrationResult { delay(delayMillis) - return register { registerTask.execute(RegisterTask.Params(registrationParams)) } + return register(loginType) { registerTask.execute(RegisterTask.Params(registrationParams)) } } private suspend fun performRegistrationOtherRequest( - registrationCustomParams: RegistrationCustomParams + loginType: LoginType, + registrationCustomParams: RegistrationCustomParams, ): RegistrationResult { - return register { registerCustomTask.execute(RegisterCustomTask.Params(registrationCustomParams)) } + return register(loginType) { registerCustomTask.execute(RegisterCustomTask.Params(registrationCustomParams)) } } private suspend fun register( - execute: suspend () -> Credentials + loginType: LoginType, + execute: suspend () -> Credentials, ): RegistrationResult { val credentials = try { execute.invoke() @@ -241,8 +243,7 @@ internal class DefaultRegistrationWizard( } } - val session = - sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig, loginType) + val session = sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig, loginType) return RegistrationResult.Success(session) } From 61b8053b9b2d368b56cfc49d9c1d35d1f17d9647 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Wed, 18 May 2022 11:23:34 +0200 Subject: [PATCH 044/291] Moves LoginType to sdk api package --- .../auth/login => api/auth}/LoginType.kt | 2 +- .../sdk/api/auth/data/SessionParams.kt | 2 +- .../auth/DefaultAuthenticationService.kt | 2 +- .../sdk/internal/auth/SessionCreator.kt | 2 +- .../sdk/internal/auth/SessionParamsCreator.kt | 2 +- .../internal/auth/db/SessionParamsMapper.kt | 2 +- .../auth/db/migration/MigrateAuthTo005.kt | 2 +- .../internal/auth/login/DefaultLoginWizard.kt | 1 + .../internal/auth/login/DirectLoginTask.kt | 1 + .../registration/DefaultRegistrationWizard.kt | 2 +- .../legacy/DefaultLegacySessionImporter.kt | 2 +- .../sdk/internal/auth/login/LoginTypeTest.kt | 1 + .../internal/auth/FakeSessionParamsCreator.kt | 2 +- .../FakeSessionParamsMapperMoshi.kt | 6 ++--- .../sdk/test/fixtures/SessionParamsFixture.kt | 2 +- .../signout/soft/SoftLogoutController.kt | 26 +++++++++---------- .../signout/soft/SoftLogoutViewModel.kt | 6 ++--- .../signout/soft/SoftLogoutViewState.kt | 2 +- 18 files changed, 33 insertions(+), 32 deletions(-) rename matrix-sdk-android/src/main/java/org/matrix/android/sdk/{internal/auth/login => api/auth}/LoginType.kt (95%) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/LoginType.kt similarity index 95% rename from matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt rename to matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/LoginType.kt index 5bc38d81fc..627a825679 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/LoginType.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/LoginType.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.matrix.android.sdk.internal.auth.login +package org.matrix.android.sdk.api.auth enum class LoginType { PASSWORD, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt index 60cd792f7e..860c982eab 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt @@ -16,7 +16,7 @@ package org.matrix.android.sdk.api.auth.data -import org.matrix.android.sdk.internal.auth.login.LoginType +import org.matrix.android.sdk.api.auth.LoginType /** * This data class holds necessary data to open a session. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt index aa05ffb49b..33f30ae587 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt @@ -22,6 +22,7 @@ import okhttp3.OkHttpClient import org.matrix.android.sdk.api.MatrixPatterns import org.matrix.android.sdk.api.MatrixPatterns.getDomain import org.matrix.android.sdk.api.auth.AuthenticationService +import org.matrix.android.sdk.api.auth.LoginType import org.matrix.android.sdk.api.auth.data.Credentials import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.api.auth.data.LoginFlowResult @@ -38,7 +39,6 @@ import org.matrix.android.sdk.internal.auth.data.WebClientConfig import org.matrix.android.sdk.internal.auth.db.PendingSessionData import org.matrix.android.sdk.internal.auth.login.DefaultLoginWizard import org.matrix.android.sdk.internal.auth.login.DirectLoginTask -import org.matrix.android.sdk.internal.auth.login.LoginType import org.matrix.android.sdk.internal.auth.registration.DefaultRegistrationWizard import org.matrix.android.sdk.internal.auth.version.Versions import org.matrix.android.sdk.internal.auth.version.isLoginAndRegistrationSupportedBySdk diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionCreator.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionCreator.kt index f75b119f18..7dbb11c7fd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionCreator.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionCreator.kt @@ -16,11 +16,11 @@ package org.matrix.android.sdk.internal.auth +import org.matrix.android.sdk.api.auth.LoginType import org.matrix.android.sdk.api.auth.data.Credentials import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.internal.SessionManager -import org.matrix.android.sdk.internal.auth.login.LoginType import javax.inject.Inject internal interface SessionCreator { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionParamsCreator.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionParamsCreator.kt index 607cab3c70..31ed9a1e85 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionParamsCreator.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionParamsCreator.kt @@ -17,11 +17,11 @@ package org.matrix.android.sdk.internal.auth import android.net.Uri +import org.matrix.android.sdk.api.auth.LoginType import org.matrix.android.sdk.api.auth.data.Credentials import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.api.auth.data.SessionParams import org.matrix.android.sdk.api.extensions.tryOrNull -import org.matrix.android.sdk.internal.auth.login.LoginType import timber.log.Timber import javax.inject.Inject diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapper.kt index 20de72dc8f..23923bf267 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/SessionParamsMapper.kt @@ -17,11 +17,11 @@ package org.matrix.android.sdk.internal.auth.db import com.squareup.moshi.Moshi +import org.matrix.android.sdk.api.auth.LoginType import org.matrix.android.sdk.api.auth.data.Credentials import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.api.auth.data.SessionParams import org.matrix.android.sdk.api.auth.data.sessionId -import org.matrix.android.sdk.internal.auth.login.LoginType import javax.inject.Inject internal class SessionParamsMapper @Inject constructor(moshi: Moshi) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt index 82996928de..2cf1b62a4c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/migration/MigrateAuthTo005.kt @@ -17,8 +17,8 @@ package org.matrix.android.sdk.internal.auth.db.migration import io.realm.DynamicRealm +import org.matrix.android.sdk.api.auth.LoginType import org.matrix.android.sdk.internal.auth.db.SessionParamsEntityFields -import org.matrix.android.sdk.internal.auth.login.LoginType import org.matrix.android.sdk.internal.util.database.RealmMigrator import timber.log.Timber diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt index 489751c1e3..eebe058a83 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DefaultLoginWizard.kt @@ -17,6 +17,7 @@ package org.matrix.android.sdk.internal.auth.login import android.util.Patterns +import org.matrix.android.sdk.api.auth.LoginType import org.matrix.android.sdk.api.auth.login.LoginProfileInfo import org.matrix.android.sdk.api.auth.login.LoginWizard import org.matrix.android.sdk.api.auth.registration.RegisterThreePid diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt index 787ea45eeb..3e382054e4 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/DirectLoginTask.kt @@ -18,6 +18,7 @@ package org.matrix.android.sdk.internal.auth.login import dagger.Lazy import okhttp3.OkHttpClient +import org.matrix.android.sdk.api.auth.LoginType import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.api.failure.Failure import org.matrix.android.sdk.api.session.Session diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt index ff7bcb0303..787ae9af7d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt @@ -17,6 +17,7 @@ package org.matrix.android.sdk.internal.auth.registration import kotlinx.coroutines.delay +import org.matrix.android.sdk.api.auth.LoginType import org.matrix.android.sdk.api.auth.data.Credentials import org.matrix.android.sdk.api.auth.data.LoginFlowTypes import org.matrix.android.sdk.api.auth.registration.RegisterThreePid @@ -31,7 +32,6 @@ import org.matrix.android.sdk.internal.auth.AuthAPI import org.matrix.android.sdk.internal.auth.PendingSessionStore import org.matrix.android.sdk.internal.auth.SessionCreator import org.matrix.android.sdk.internal.auth.db.PendingSessionData -import org.matrix.android.sdk.internal.auth.login.LoginType /** * This class execute the registration request and is responsible to keep the session of interactive authentication. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/DefaultLegacySessionImporter.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/DefaultLegacySessionImporter.kt index 74a534e1fd..155ef02ead 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/DefaultLegacySessionImporter.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/DefaultLegacySessionImporter.kt @@ -20,6 +20,7 @@ import android.content.Context import io.realm.Realm import io.realm.RealmConfiguration import kotlinx.coroutines.runBlocking +import org.matrix.android.sdk.api.auth.LoginType import org.matrix.android.sdk.api.auth.data.Credentials import org.matrix.android.sdk.api.auth.data.DiscoveryInformation import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig @@ -29,7 +30,6 @@ import org.matrix.android.sdk.api.legacy.LegacySessionImporter import org.matrix.android.sdk.api.network.ssl.Fingerprint import org.matrix.android.sdk.api.util.md5 import org.matrix.android.sdk.internal.auth.SessionParamsStore -import org.matrix.android.sdk.internal.auth.login.LoginType import org.matrix.android.sdk.internal.crypto.store.db.RealmCryptoStoreMigration import org.matrix.android.sdk.internal.crypto.store.db.RealmCryptoStoreModule import org.matrix.android.sdk.internal.database.RealmKeysUtils diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt index 341d09765c..495302acb2 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/auth/login/LoginTypeTest.kt @@ -19,6 +19,7 @@ package org.matrix.android.sdk.internal.auth.login import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldNotBeEqualTo import org.junit.Test +import org.matrix.android.sdk.api.auth.LoginType class LoginTypeTest { diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt index 79a3053f70..f64e5a451d 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/FakeSessionParamsCreator.kt @@ -21,10 +21,10 @@ import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import io.mockk.mockkStatic +import org.matrix.android.sdk.api.auth.LoginType import org.matrix.android.sdk.api.auth.data.Credentials import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.internal.auth.SessionParamsCreator -import org.matrix.android.sdk.internal.auth.login.LoginType import org.matrix.android.sdk.test.fixtures.SessionParamsFixture.aSessionParams internal class FakeSessionParamsCreator { diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt index bc5a2fa7ca..ed0ddb1179 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/internal/auth/db/sessionparams/FakeSessionParamsMapperMoshi.kt @@ -23,12 +23,12 @@ import io.mockk.mockk import io.mockk.mockkStatic import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeNull +import org.matrix.android.sdk.api.auth.LoginType import org.matrix.android.sdk.api.auth.data.Credentials import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.api.auth.data.SessionParams import org.matrix.android.sdk.api.auth.data.sessionId import org.matrix.android.sdk.internal.auth.db.SessionParamsEntity -import org.matrix.android.sdk.internal.auth.login.LoginType import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeCredentialsJsonAdapter.Companion.CREDENTIALS_JSON import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeCredentialsJsonAdapter.Companion.credentials import org.matrix.android.sdk.test.fakes.internal.auth.db.sessionparams.FakeHomeServerConnectionConfigJsonAdapter.Companion.HOME_SERVER_CONNECTION_CONFIG_JSON @@ -39,8 +39,8 @@ import org.matrix.android.sdk.test.fixtures.SessionParamsFixture.aSessionParams internal class FakeSessionParamsMapperMoshi { val instance: Moshi = mockk() - val credentialsJsonAdapter = FakeCredentialsJsonAdapter() - val homeServerConnectionConfigAdapter = FakeHomeServerConnectionConfigJsonAdapter() + private val credentialsJsonAdapter = FakeCredentialsJsonAdapter() + private val homeServerConnectionConfigAdapter = FakeHomeServerConnectionConfigJsonAdapter() init { mockkStatic(Uri::class) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt index dad4b84fd0..5cbbe1a47a 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fixtures/SessionParamsFixture.kt @@ -16,10 +16,10 @@ package org.matrix.android.sdk.test.fixtures +import org.matrix.android.sdk.api.auth.LoginType import org.matrix.android.sdk.api.auth.data.Credentials import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.api.auth.data.SessionParams -import org.matrix.android.sdk.internal.auth.login.LoginType import org.matrix.android.sdk.test.fixtures.CredentialsFixture.aCredentials object SessionParamsFixture { diff --git a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt index 301d0af187..265cf3199e 100644 --- a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt +++ b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutController.kt @@ -36,12 +36,12 @@ import im.vector.app.features.signout.soft.epoxy.loginRedButtonItem import im.vector.app.features.signout.soft.epoxy.loginTextItem import im.vector.app.features.signout.soft.epoxy.loginTitleItem import im.vector.app.features.signout.soft.epoxy.loginTitleSmallItem -import org.matrix.android.sdk.internal.auth.login.LoginType +import org.matrix.android.sdk.api.auth.LoginType import javax.inject.Inject class SoftLogoutController @Inject constructor( - private val stringProvider: StringProvider, - private val errorFormatter: ErrorFormatter + private val stringProvider: StringProvider, + private val errorFormatter: ErrorFormatter ) : EpoxyController() { var listener: Listener? = null @@ -94,10 +94,10 @@ class SoftLogoutController @Inject constructor( } private fun buildForm(state: SoftLogoutViewState) = when (state.asyncHomeServerLoginFlowRequest) { - is Fail -> buildLoginErrorWithRetryItem(state.asyncHomeServerLoginFlowRequest.error) - is Success -> buildLoginSuccessItem(state) + is Fail -> buildLoginErrorWithRetryItem(state.asyncHomeServerLoginFlowRequest.error) + is Success -> buildLoginSuccessItem(state) is Loading, Uninitialized -> buildLoadingItem() - is Incomplete -> Unit + is Incomplete -> Unit } private fun buildLoadingItem() { @@ -116,11 +116,11 @@ class SoftLogoutController @Inject constructor( } private fun buildLoginSuccessItem(state: SoftLogoutViewState) = when (state.asyncHomeServerLoginFlowRequest.invoke()) { - LoginMode.Password -> buildLoginPasswordForm(state) - is LoginMode.Sso -> buildLoginSSOForm() + LoginMode.Password -> buildLoginPasswordForm(state) + is LoginMode.Sso -> buildLoginSSOForm() is LoginMode.SsoAndPassword -> disambiguateLoginSSOAndPasswordForm(state) - LoginMode.Unsupported -> buildLoginUnsupportedForm() - LoginMode.Unknown, null -> Unit // Should not happen + LoginMode.Unsupported -> buildLoginUnsupportedForm() + LoginMode.Unknown, null -> Unit // Should not happen } private fun buildLoginPasswordForm(state: SoftLogoutViewState) { @@ -148,12 +148,12 @@ class SoftLogoutController @Inject constructor( private fun disambiguateLoginSSOAndPasswordForm(state: SoftLogoutViewState) { when (state.loginType) { - LoginType.PASSWORD -> buildLoginPasswordForm(state) - LoginType.SSO -> buildLoginSSOForm() + LoginType.PASSWORD -> buildLoginPasswordForm(state) + LoginType.SSO -> buildLoginSSOForm() LoginType.DIRECT, LoginType.CUSTOM, LoginType.UNSUPPORTED -> buildLoginUnsupportedForm() - LoginType.UNKNOWN -> Unit + LoginType.UNKNOWN -> Unit } } diff --git a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewModel.kt b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewModel.kt index d0a810976d..6ae076408a 100644 --- a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewModel.kt @@ -35,15 +35,13 @@ import im.vector.app.core.platform.VectorViewModel import im.vector.app.features.login.LoginMode import kotlinx.coroutines.launch import org.matrix.android.sdk.api.auth.AuthenticationService +import org.matrix.android.sdk.api.auth.LoginType import org.matrix.android.sdk.api.auth.data.LoginFlowTypes import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.getUser -import org.matrix.android.sdk.internal.auth.login.LoginType import timber.log.Timber -/** - * TODO Test push: disable the pushers? - */ + class SoftLogoutViewModel @AssistedInject constructor( @Assisted initialState: SoftLogoutViewState, private val session: Session, diff --git a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewState.kt b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewState.kt index f13b089ac5..28c8273412 100644 --- a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewState.kt +++ b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewState.kt @@ -22,7 +22,7 @@ import com.airbnb.mvrx.MavericksState import com.airbnb.mvrx.Success import com.airbnb.mvrx.Uninitialized import im.vector.app.features.login.LoginMode -import org.matrix.android.sdk.internal.auth.login.LoginType +import org.matrix.android.sdk.api.auth.LoginType data class SoftLogoutViewState( val asyncHomeServerLoginFlowRequest: Async = Uninitialized, From a71c50c6381f0439f1f02dea786524e6bf2c3e30 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Wed, 18 May 2022 11:38:38 +0200 Subject: [PATCH 045/291] Fixes lint error --- .../im/vector/app/features/signout/soft/SoftLogoutViewModel.kt | 1 - 1 file changed, 1 deletion(-) diff --git a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewModel.kt b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewModel.kt index 6ae076408a..d44c408173 100644 --- a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewModel.kt @@ -41,7 +41,6 @@ import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.getUser import timber.log.Timber - class SoftLogoutViewModel @AssistedInject constructor( @Assisted initialState: SoftLogoutViewState, private val session: Session, From fe274515323b7512c41145c82cd7a3410fa43880 Mon Sep 17 00:00:00 2001 From: ericdecanini Date: Wed, 18 May 2022 12:09:34 +0200 Subject: [PATCH 046/291] Fixes lint error --- .../java/org/matrix/android/sdk/api/auth/data/SessionParams.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt index 860c982eab..de227631ed 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt @@ -39,7 +39,7 @@ data class SessionParams( val isTokenValid: Boolean, /** - * Which authentication method was used to create the session + * The authentication method that was used to create the session. */ val loginType: LoginType, ) { From 2d654da691861f1b4fe4fbc7c1c88df534ec4ad2 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 23 May 2022 23:18:18 +0000 Subject: [PATCH 047/291] Bump realm-gradle-plugin from 10.9.0 to 10.11.0 Bumps [realm-gradle-plugin](https://github.com/realm/realm-java) from 10.9.0 to 10.11.0. - [Release notes](https://github.com/realm/realm-java/releases) - [Changelog](https://github.com/realm/realm-java/blob/v10.11.0/CHANGELOG.md) - [Commits](https://github.com/realm/realm-java/compare/v10.9.0...v10.11.0) --- updated-dependencies: - dependency-name: io.realm:realm-gradle-plugin dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- matrix-sdk-android/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix-sdk-android/build.gradle b/matrix-sdk-android/build.gradle index ec376effbe..be1d247f7b 100644 --- a/matrix-sdk-android/build.gradle +++ b/matrix-sdk-android/build.gradle @@ -13,7 +13,7 @@ buildscript { } } dependencies { - classpath "io.realm:realm-gradle-plugin:10.9.0" + classpath "io.realm:realm-gradle-plugin:10.11.0" } } From 0c3ea4f92333c3c8412e1d4a990366bb3ef6d9e3 Mon Sep 17 00:00:00 2001 From: Nicolas Werner Date: Sun, 12 Jun 2022 15:05:15 +0200 Subject: [PATCH 048/291] Use stable endpoint for alias management This increases compatibility with homeservers and allows them to remove Element Android specific workaround. fixes #4830 see https://github.com/ruma/ruma/pull/936 see https://github.com/matrix-org/synapse/issues/8334 see https://github.com/matrix-org/synapse/pull/9224 Signed-off-by: Nicolas Werner --- .../org/matrix/android/sdk/internal/session/room/RoomAPI.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAPI.kt index ac2880de69..9bcb7b8e4c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAPI.kt @@ -377,7 +377,7 @@ internal interface RoomAPI { * Get a list of aliases maintained by the local server for the given room. * Ref: https://matrix.org/docs/spec/client_server/r0.6.1#get-matrix-client-r0-rooms-roomid-aliases */ - @GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "org.matrix.msc2432/rooms/{roomId}/aliases") + @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/aliases") suspend fun getAliases(@Path("roomId") roomId: String): GetAliasesResponse /** From a7bb0efc9305cf355c0941bc28c08697d00cf86a Mon Sep 17 00:00:00 2001 From: Nicolas Werner Date: Sun, 12 Jun 2022 15:13:27 +0200 Subject: [PATCH 049/291] Add changelog Signed-off-by: Nicolas Werner --- changelog.d/6288.bugfix | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/6288.bugfix diff --git a/changelog.d/6288.bugfix b/changelog.d/6288.bugfix new file mode 100644 index 0000000000..fc01597ed8 --- /dev/null +++ b/changelog.d/6288.bugfix @@ -0,0 +1 @@ +Use stable endpoint for alias management instead of MSC2432. Contributed by Nico. From d07557a5ee87dca0c5b8e2ea73d0de22df6ba9c8 Mon Sep 17 00:00:00 2001 From: Nicolas Werner Date: Sun, 12 Jun 2022 18:05:17 +0200 Subject: [PATCH 050/291] Fix overlooked path as well Signed-off-by: Nicolas Werner --- .../src/main/java/org/matrix/android/sdk/api/network/ApiPath.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/network/ApiPath.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/network/ApiPath.kt index baf33a59c5..f5e5628566 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/network/ApiPath.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/network/ApiPath.kt @@ -162,7 +162,7 @@ enum class ApiPath(val path: String, val method: String) { KICK_USER(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/kick", "POST"), REDACT_EVENT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/redact/{eventId}/{txnId}", "PUT"), REPORT_CONTENT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/report/{eventId}", "POST"), - GET_ALIASES(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "org.matrix.msc2432/rooms/{roomId}/aliases", "GET"), + GET_ALIASES(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/aliases", "GET"), SEND_TYPING_STATE(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/typing/{userId}", "PUT"), PUT_TAG(NetworkConstants.URI_API_PREFIX_PATH_R0 + "user/{userId}/rooms/{roomId}/tags/{tag}", "PUT"), DELETE_TAG(NetworkConstants.URI_API_PREFIX_PATH_R0 + "user/{userId}/rooms/{roomId}/tags/{tag}", "DELETE"), From 75a698677096e83dd671957e27c5b9ebb5728acb Mon Sep 17 00:00:00 2001 From: Nicolas Werner Date: Mon, 13 Jun 2022 09:57:33 +0200 Subject: [PATCH 051/291] Remove comment referencing msc2432 Signed-off-by: Nicolas Werner --- .../sdk/internal/session/room/alias/GetRoomLocalAliasesTask.kt | 1 - 1 file changed, 1 deletion(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/alias/GetRoomLocalAliasesTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/alias/GetRoomLocalAliasesTask.kt index 1ff4156ed3..62681c89d8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/alias/GetRoomLocalAliasesTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/alias/GetRoomLocalAliasesTask.kt @@ -34,7 +34,6 @@ internal class DefaultGetRoomLocalAliasesTask @Inject constructor( ) : GetRoomLocalAliasesTask { override suspend fun execute(params: GetRoomLocalAliasesTask.Params): List { - // We do not check for "org.matrix.msc2432", so the API may be missing val response = executeRequest(globalErrorReceiver) { roomAPI.getAliases(roomId = params.roomId) } From c9ab0927f06309f56f71b460321c54abadbd9c47 Mon Sep 17 00:00:00 2001 From: Florian Renaud Date: Wed, 11 May 2022 16:19:33 +0200 Subject: [PATCH 052/291] Start DM - Add feature flag --- .../debug/features/DebugFeaturesStateFactory.kt | 5 +++++ .../features/debug/features/DebugVectorFeatures.kt | 4 ++++ .../java/im/vector/app/features/VectorFeatures.kt | 2 ++ .../createdirect/CreateDirectRoomViewModel.kt | 11 +++++++++-- 4 files changed, 20 insertions(+), 2 deletions(-) diff --git a/vector/src/debug/java/im/vector/app/features/debug/features/DebugFeaturesStateFactory.kt b/vector/src/debug/java/im/vector/app/features/debug/features/DebugFeaturesStateFactory.kt index 248d9d232b..5506c2497c 100644 --- a/vector/src/debug/java/im/vector/app/features/debug/features/DebugFeaturesStateFactory.kt +++ b/vector/src/debug/java/im/vector/app/features/debug/features/DebugFeaturesStateFactory.kt @@ -70,6 +70,11 @@ class DebugFeaturesStateFactory @Inject constructor( key = DebugFeatureKeys.allowExternalUnifiedPushDistributors, factory = VectorFeatures::allowExternalUnifiedPushDistributors ), + createBooleanFeature( + label = "Start DM on first message", + key = DebugFeatureKeys.startDmOnFirstMsg, + factory = VectorFeatures::shouldStartDmOnFirstMessage + ), ) ) } diff --git a/vector/src/debug/java/im/vector/app/features/debug/features/DebugVectorFeatures.kt b/vector/src/debug/java/im/vector/app/features/debug/features/DebugVectorFeatures.kt index 919cc6635e..617284d9e4 100644 --- a/vector/src/debug/java/im/vector/app/features/debug/features/DebugVectorFeatures.kt +++ b/vector/src/debug/java/im/vector/app/features/debug/features/DebugVectorFeatures.kt @@ -66,6 +66,9 @@ class DebugVectorFeatures( override fun isScreenSharingEnabled(): Boolean = read(DebugFeatureKeys.screenSharing) ?: vectorFeatures.isScreenSharingEnabled() + override fun shouldStartDmOnFirstMessage(): Boolean = read(DebugFeatureKeys.startDmOnFirstMsg) + ?: vectorFeatures.shouldStartDmOnFirstMessage() + fun override(value: T?, key: Preferences.Key) = updatePreferences { if (value == null) { it.remove(key) @@ -123,4 +126,5 @@ object DebugFeatureKeys { val allowExternalUnifiedPushDistributors = booleanPreferencesKey("allow-external-unified-push-distributors") val liveLocationSharing = booleanPreferencesKey("live-location-sharing") val screenSharing = booleanPreferencesKey("screen-sharing") + val startDmOnFirstMsg = booleanPreferencesKey("start-dm-on-first-msg") } diff --git a/vector/src/main/java/im/vector/app/features/VectorFeatures.kt b/vector/src/main/java/im/vector/app/features/VectorFeatures.kt index 6fe4beff95..ad49916a07 100644 --- a/vector/src/main/java/im/vector/app/features/VectorFeatures.kt +++ b/vector/src/main/java/im/vector/app/features/VectorFeatures.kt @@ -30,6 +30,7 @@ interface VectorFeatures { fun isOnboardingCombinedLoginEnabled(): Boolean fun allowExternalUnifiedPushDistributors(): Boolean fun isScreenSharingEnabled(): Boolean + fun shouldStartDmOnFirstMessage(): Boolean enum class OnboardingVariant { LEGACY, @@ -48,4 +49,5 @@ class DefaultVectorFeatures : VectorFeatures { override fun isOnboardingCombinedLoginEnabled() = false override fun allowExternalUnifiedPushDistributors(): Boolean = Config.ALLOW_EXTERNAL_UNIFIED_PUSH_DISTRIBUTORS override fun isScreenSharingEnabled(): Boolean = true + override fun shouldStartDmOnFirstMessage(): Boolean = false } diff --git a/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewModel.kt b/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewModel.kt index 8374f9d513..5574ce3e63 100644 --- a/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewModel.kt @@ -26,6 +26,7 @@ import im.vector.app.core.di.MavericksAssistedViewModelFactory import im.vector.app.core.di.hiltMavericksViewModelFactory import im.vector.app.core.mvrx.runCatchingToAsync import im.vector.app.core.platform.VectorViewModel +import im.vector.app.features.VectorFeatures import im.vector.app.features.analytics.AnalyticsTracker import im.vector.app.features.analytics.plan.CreatedRoom import im.vector.app.features.raw.wellknown.getElementWellknown @@ -46,7 +47,8 @@ class CreateDirectRoomViewModel @AssistedInject constructor( @Assisted initialState: CreateDirectRoomViewState, private val rawService: RawService, val session: Session, - val analyticsTracker: AnalyticsTracker + val analyticsTracker: AnalyticsTracker, + val vectorFeatures: VectorFeatures ) : VectorViewModel(initialState) { @@ -124,7 +126,12 @@ class CreateDirectRoomViewModel @AssistedInject constructor( } val result = runCatchingToAsync { - session.roomService().createRoom(roomParams) + if (vectorFeatures.shouldStartDmOnFirstMessage()) { + // Todo: Prepare direct room creation + throw Throwable("Start DM on first message is not implemented yet.") + } else { + session.roomService().createRoom(roomParams) + } } analyticsTracker.capture(CreatedRoom(isDM = roomParams.isDirect.orFalse())) From ba3d3501274bd7c2f372f54a87ee04f3527a4f81 Mon Sep 17 00:00:00 2001 From: Florian Renaud Date: Wed, 11 May 2022 16:20:27 +0200 Subject: [PATCH 053/291] Fix VectorFeature pref key --- .../vector/app/features/debug/features/DebugVectorFeatures.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vector/src/debug/java/im/vector/app/features/debug/features/DebugVectorFeatures.kt b/vector/src/debug/java/im/vector/app/features/debug/features/DebugVectorFeatures.kt index 617284d9e4..7f74737719 100644 --- a/vector/src/debug/java/im/vector/app/features/debug/features/DebugVectorFeatures.kt +++ b/vector/src/debug/java/im/vector/app/features/debug/features/DebugVectorFeatures.kt @@ -119,7 +119,7 @@ private fun > enumPreferencesKey(type: KClass) = stringPreference object DebugFeatureKeys { val onboardingAlreadyHaveAnAccount = booleanPreferencesKey("onboarding-already-have-an-account") val onboardingSplashCarousel = booleanPreferencesKey("onboarding-splash-carousel") - val onboardingUseCase = booleanPreferencesKey("onboarding-splash-carousel") + val onboardingUseCase = booleanPreferencesKey("onboarding-use-case") val onboardingPersonalize = booleanPreferencesKey("onboarding-personalize") val onboardingCombinedRegister = booleanPreferencesKey("onboarding-combined-register") val onboardingCombinedLogin = booleanPreferencesKey("onboarding-combined-login") From 26d1a12b74955df839ef513b6987d5d520662ec9 Mon Sep 17 00:00:00 2001 From: Florian Renaud Date: Wed, 16 Mar 2022 17:43:29 +0100 Subject: [PATCH 054/291] Start DM - Rename action button to "go" --- vector/src/main/res/menu/vector_create_direct_room.xml | 2 +- vector/src/main/res/values/strings.xml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/vector/src/main/res/menu/vector_create_direct_room.xml b/vector/src/main/res/menu/vector_create_direct_room.xml index 8c6eab1c52..10b2adf23d 100755 --- a/vector/src/main/res/menu/vector_create_direct_room.xml +++ b/vector/src/main/res/menu/vector_create_direct_room.xml @@ -4,7 +4,7 @@ diff --git a/vector/src/main/res/values/strings.xml b/vector/src/main/res/values/strings.xml index f60da53c09..b507ed473f 100644 --- a/vector/src/main/res/values/strings.xml +++ b/vector/src/main/res/values/strings.xml @@ -1623,6 +1623,7 @@ "CREATE" + Go "Room name" "Name" "Room topic (optional)" From 10d683ad5d1bf931b7578cfa558108826c7fb407 Mon Sep 17 00:00:00 2001 From: Florian Renaud Date: Thu, 17 Mar 2022 10:37:04 +0100 Subject: [PATCH 055/291] Start DM - display a local room before creating the real one Add CreateLocalRoomTask interface and remove DI annotations --- .../sdk/api/session/room/RoomService.kt | 7 + .../room/model/localecho/RoomLocalEcho.kt | 28 ++ .../session/room/DefaultRoomService.kt | 6 + .../sdk/internal/session/room/RoomModule.kt | 5 + .../room/create/CreateLocalRoomTask.kt | 267 ++++++++++++++++++ .../session/room/create/CreateRoomBody.kt | 17 ++ .../session/room/create/CreateRoomTask.kt | 29 +- .../session/room/timeline/DefaultTimeline.kt | 2 + .../createdirect/CreateDirectRoomAction.kt | 4 +- .../createdirect/CreateDirectRoomActivity.kt | 2 +- .../createdirect/CreateDirectRoomViewModel.kt | 20 +- .../createdirect/CreateDirectRoomViewState.kt | 2 + 12 files changed, 352 insertions(+), 37 deletions(-) create mode 100644 matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/localecho/RoomLocalEcho.kt create mode 100644 matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateLocalRoomTask.kt diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt index 5dfb8961e3..41a215636d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt @@ -40,6 +40,13 @@ interface RoomService { */ suspend fun createRoom(createRoomParams: CreateRoomParams): String + /** + * Create a room locally. + * This room will not be synchronized with the server and will not come back from the sync, so all the events related to this room will be generated + * locally. + */ + suspend fun createLocalRoom(createRoomParams: CreateRoomParams): String + /** * Create a direct room asynchronously. This is a facility method to create a direct room with the necessary parameters. */ diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/localecho/RoomLocalEcho.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/localecho/RoomLocalEcho.kt new file mode 100644 index 0000000000..a9804c6dac --- /dev/null +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/localecho/RoomLocalEcho.kt @@ -0,0 +1,28 @@ +/* + * Copyright 2020 The Matrix.org Foundation C.I.C. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.api.session.room.model.localecho + +import java.util.UUID + +object RoomLocalEcho { + + private const val PREFIX = "!local." + + fun isLocalEchoId(roomId: String) = roomId.startsWith(PREFIX) + + fun createLocalEchoId() = "${PREFIX}${UUID.randomUUID()}" +} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomService.kt index 5e6d052443..cc5e935f87 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomService.kt @@ -43,6 +43,7 @@ import org.matrix.android.sdk.internal.database.model.RoomMemberSummaryEntityFie import org.matrix.android.sdk.internal.di.SessionDatabase import org.matrix.android.sdk.internal.session.room.alias.DeleteRoomAliasTask import org.matrix.android.sdk.internal.session.room.alias.GetRoomIdByAliasTask +import org.matrix.android.sdk.internal.session.room.create.CreateLocalRoomTask import org.matrix.android.sdk.internal.session.room.create.CreateRoomTask import org.matrix.android.sdk.internal.session.room.membership.RoomChangeMembershipStateDataSource import org.matrix.android.sdk.internal.session.room.membership.RoomMemberHelper @@ -60,6 +61,7 @@ import javax.inject.Inject internal class DefaultRoomService @Inject constructor( @SessionDatabase private val monarchy: Monarchy, private val createRoomTask: CreateRoomTask, + private val createLocalRoomTask: CreateLocalRoomTask, private val joinRoomTask: JoinRoomTask, private val markAllRoomsReadTask: MarkAllRoomsReadTask, private val updateBreadcrumbsTask: UpdateBreadcrumbsTask, @@ -78,6 +80,10 @@ internal class DefaultRoomService @Inject constructor( return createRoomTask.executeRetry(createRoomParams, 3) } + override suspend fun createLocalRoom(createRoomParams: CreateRoomParams): String { + return createLocalRoomTask.execute(createRoomParams) + } + override fun getRoom(roomId: String): Room? { return roomGetter.getRoom(roomId) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomModule.kt index f3845f1f15..bb92287ead 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomModule.kt @@ -43,7 +43,9 @@ import org.matrix.android.sdk.internal.session.room.alias.DefaultGetRoomLocalAli import org.matrix.android.sdk.internal.session.room.alias.DeleteRoomAliasTask import org.matrix.android.sdk.internal.session.room.alias.GetRoomIdByAliasTask import org.matrix.android.sdk.internal.session.room.alias.GetRoomLocalAliasesTask +import org.matrix.android.sdk.internal.session.room.create.CreateLocalRoomTask import org.matrix.android.sdk.internal.session.room.create.CreateRoomTask +import org.matrix.android.sdk.internal.session.room.create.DefaultCreateLocalRoomTask import org.matrix.android.sdk.internal.session.room.create.DefaultCreateRoomTask import org.matrix.android.sdk.internal.session.room.directory.DefaultGetPublicRoomTask import org.matrix.android.sdk.internal.session.room.directory.DefaultGetRoomDirectoryVisibilityTask @@ -192,6 +194,9 @@ internal abstract class RoomModule { @Binds abstract fun bindCreateRoomTask(task: DefaultCreateRoomTask): CreateRoomTask + @Binds + abstract fun bindCreateLocalRoomTask(task: DefaultCreateLocalRoomTask): CreateLocalRoomTask + @Binds abstract fun bindGetPublicRoomTask(task: DefaultGetPublicRoomTask): GetPublicRoomTask diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateLocalRoomTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateLocalRoomTask.kt new file mode 100644 index 0000000000..e650039d75 --- /dev/null +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateLocalRoomTask.kt @@ -0,0 +1,267 @@ +/* + * Copyright 2022 The Matrix.org Foundation C.I.C. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.internal.session.room.create + +import com.zhuinden.monarchy.Monarchy +import io.realm.Realm +import io.realm.RealmConfiguration +import io.realm.kotlin.createObject +import kotlinx.coroutines.TimeoutCancellationException +import org.matrix.android.sdk.api.extensions.orFalse +import org.matrix.android.sdk.api.extensions.tryOrNull +import org.matrix.android.sdk.api.session.events.model.Content +import org.matrix.android.sdk.api.session.events.model.Event +import org.matrix.android.sdk.api.session.events.model.EventType +import org.matrix.android.sdk.api.session.events.model.toContent +import org.matrix.android.sdk.api.session.room.failure.CreateRoomFailure +import org.matrix.android.sdk.api.session.room.model.GuestAccess +import org.matrix.android.sdk.api.session.room.model.Membership +import org.matrix.android.sdk.api.session.room.model.RoomDirectoryVisibility +import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibility +import org.matrix.android.sdk.api.session.room.model.RoomMemberContent +import org.matrix.android.sdk.api.session.room.model.create.CreateRoomParams +import org.matrix.android.sdk.api.session.room.model.create.RoomCreateContent +import org.matrix.android.sdk.api.session.room.model.localecho.RoomLocalEcho +import org.matrix.android.sdk.api.session.room.send.SendState +import org.matrix.android.sdk.api.session.sync.model.RoomSyncSummary +import org.matrix.android.sdk.api.session.user.UserService +import org.matrix.android.sdk.api.session.user.model.User +import org.matrix.android.sdk.internal.database.awaitNotEmptyResult +import org.matrix.android.sdk.internal.database.helper.addTimelineEvent +import org.matrix.android.sdk.internal.database.mapper.asDomain +import org.matrix.android.sdk.internal.database.mapper.toEntity +import org.matrix.android.sdk.internal.database.model.ChunkEntity +import org.matrix.android.sdk.internal.database.model.CurrentStateEventEntity +import org.matrix.android.sdk.internal.database.model.EventInsertType +import org.matrix.android.sdk.internal.database.model.RoomEntity +import org.matrix.android.sdk.internal.database.model.RoomSummaryEntity +import org.matrix.android.sdk.internal.database.model.RoomSummaryEntityFields +import org.matrix.android.sdk.internal.database.query.copyToRealmOrIgnore +import org.matrix.android.sdk.internal.database.query.getOrCreate +import org.matrix.android.sdk.internal.database.query.getOrNull +import org.matrix.android.sdk.internal.di.SessionDatabase +import org.matrix.android.sdk.internal.di.UserId +import org.matrix.android.sdk.internal.session.events.getFixedRoomMemberContent +import org.matrix.android.sdk.internal.session.room.membership.RoomMemberEventHandler +import org.matrix.android.sdk.internal.session.room.summary.RoomSummaryUpdater +import org.matrix.android.sdk.internal.session.room.timeline.PaginationDirection +import org.matrix.android.sdk.internal.task.Task +import org.matrix.android.sdk.internal.util.awaitTransaction +import org.matrix.android.sdk.internal.util.time.Clock +import java.util.UUID +import java.util.concurrent.TimeUnit +import javax.inject.Inject + +internal interface CreateLocalRoomTask : Task + +internal class DefaultCreateLocalRoomTask @Inject constructor( + @UserId private val userId: String, + @SessionDatabase private val monarchy: Monarchy, + private val roomMemberEventHandler: RoomMemberEventHandler, + private val roomSummaryUpdater: RoomSummaryUpdater, + @SessionDatabase private val realmConfiguration: RealmConfiguration, + private val createRoomBodyBuilder: CreateRoomBodyBuilder, + private val userService: UserService, + private val clock: Clock, +) : CreateLocalRoomTask { + + override suspend fun execute(params: CreateRoomParams): String { + val createRoomBody = createRoomBodyBuilder.build(params.withDefault()) + val roomId = RoomLocalEcho.createLocalEchoId() + monarchy.awaitTransaction { realm -> + createLocalRoomEntity(realm, roomId, createRoomBody) + createLocalRoomSummaryEntity(realm, roomId, createRoomBody) + } + + // Wait for room to be created in DB + try { + awaitNotEmptyResult(realmConfiguration, TimeUnit.MINUTES.toMillis(1L)) { realm -> + realm.where(RoomSummaryEntity::class.java) + .equalTo(RoomSummaryEntityFields.ROOM_ID, roomId) + .equalTo(RoomSummaryEntityFields.MEMBERSHIP_STR, Membership.JOIN.name) + } + } catch (exception: TimeoutCancellationException) { + throw CreateRoomFailure.CreatedWithTimeout(roomId) + } + + return roomId + } + + /** + * Create a local room entity from the given room creation params. + * This will also generate and store in database the chunk and the events related to the room params in order to retrieve and display the local room. + */ + private suspend fun createLocalRoomEntity(realm: Realm, roomId: String, createRoomBody: CreateRoomBody) { + RoomEntity.getOrCreate(realm, roomId).apply { + membership = Membership.JOIN + chunks.add(createLocalRoomChunk(realm, roomId, createRoomBody)) + } + } + + private fun createLocalRoomSummaryEntity(realm: Realm, roomId: String, createRoomBody: CreateRoomBody) { + val otherUserId = createRoomBody.getDirectUserId() + if (otherUserId != null) { + RoomSummaryEntity.getOrCreate(realm, roomId).apply { + isDirect = true + directUserId = otherUserId + } + } + roomSummaryUpdater.update( + realm = realm, + roomId = roomId, + membership = Membership.JOIN, + roomSummary = RoomSyncSummary( + heroes = createRoomBody.invitedUserIds.orEmpty().take(5), + joinedMembersCount = 1, + invitedMembersCount = createRoomBody.invitedUserIds?.size ?: 0 + ), + updateMembers = !createRoomBody.invitedUserIds.isNullOrEmpty() + ) + } + + /** + * Create a single chunk containing the necessary events to display the local room. + * + * @param realm the current instance of realm + * @param roomId the id of the local room + * @param createRoomBody the room creation params + * + * @return a chunk entity + */ + private suspend fun createLocalRoomChunk(realm: Realm, roomId: String, createRoomBody: CreateRoomBody): ChunkEntity { + val chunkEntity = realm.createObject().apply { + isLastBackward = true + isLastForward = true + } + + val eventList = createLocalRoomEvents(createRoomBody) + val eventIds = ArrayList(eventList.size) + val roomMemberContentsByUser = HashMap() + + for (event in eventList) { + if (event.eventId == null || event.senderId == null || event.type == null) { + continue + } + + eventIds.add(event.eventId) + + val eventEntity = event.toEntity(roomId, SendState.SYNCED, null).copyToRealmOrIgnore(realm, EventInsertType.INCREMENTAL_SYNC) + if (event.stateKey != null) { + CurrentStateEventEntity.getOrCreate(realm, roomId, event.stateKey, event.type).apply { + eventId = event.eventId + root = eventEntity + } + if (event.type == EventType.STATE_ROOM_MEMBER) { + roomMemberContentsByUser[event.stateKey] = event.getFixedRoomMemberContent() + roomMemberEventHandler.handle(realm, roomId, event, false) + } + } + + roomMemberContentsByUser.getOrPut(event.senderId) { + // If we don't have any new state on this user, get it from db + val rootStateEvent = CurrentStateEventEntity.getOrNull(realm, roomId, event.senderId, EventType.STATE_ROOM_MEMBER)?.root + rootStateEvent?.asDomain()?.getFixedRoomMemberContent() + } + + chunkEntity.addTimelineEvent( + roomId = roomId, + eventEntity = eventEntity, + direction = PaginationDirection.FORWARDS, + roomMemberContentsByUser = roomMemberContentsByUser + ) + } + + return chunkEntity + } + + /** + * Build the list of the events related to the room creation params. + * + * @param createRoomBody the room creation params + * + * @return the list of events + */ + private suspend fun createLocalRoomEvents(createRoomBody: CreateRoomBody): List { + val myUser = userService.getUser(userId) ?: User(userId) + val invitedUsers = createRoomBody.invitedUserIds.orEmpty() + .mapNotNull { tryOrNull { userService.resolveUser(it) } } + + val createRoomEvent = createFakeEvent( + type = EventType.STATE_ROOM_CREATE, + content = RoomCreateContent( + creator = userId + ).toContent() + ) + val myRoomMemberEvent = createFakeEvent( + type = EventType.STATE_ROOM_MEMBER, + content = RoomMemberContent( + membership = Membership.JOIN, + displayName = myUser.displayName, + avatarUrl = myUser.avatarUrl + ).toContent(), + stateKey = userId + ) + val roomMemberEvents = invitedUsers.map { + createFakeEvent( + type = EventType.STATE_ROOM_MEMBER, + content = RoomMemberContent( + isDirect = createRoomBody.isDirect.orFalse(), + membership = Membership.INVITE, + displayName = it.displayName, + avatarUrl = it.avatarUrl + ).toContent(), + stateKey = it.userId + ) + } + + return buildList { + add(createRoomEvent) + add(myRoomMemberEvent) + addAll(createRoomBody.initialStates.orEmpty().map { createFakeEvent(it.type, it.content, it.stateKey) }) + addAll(roomMemberEvents) + } + } + + /** + * Generate a local event from the given parameters. + * + * @param type the event type, see [EventType] + * @param content the content of the Event + * @param stateKey the stateKey, if any + * + * @return a fake event + */ + private fun createFakeEvent(type: String?, content: Content?, stateKey: String? = ""): Event { + return Event( + type = type, + senderId = userId, + stateKey = stateKey, + content = content, + originServerTs = clock.epochMillis(), + eventId = UUID.randomUUID().toString() + ) + } + + /** + * Setup default values to the CreateRoomParams as the room is created locally (the default values will not be defined by the server). + */ + private fun CreateRoomParams.withDefault() = this.apply { + if (visibility == null) visibility = RoomDirectoryVisibility.PRIVATE + if (historyVisibility == null) historyVisibility = RoomHistoryVisibility.SHARED + if (guestAccess == null) guestAccess = GuestAccess.Forbidden + } +} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateRoomBody.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateRoomBody.kt index cffa632768..b326c3618c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateRoomBody.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateRoomBody.kt @@ -120,3 +120,20 @@ internal data class CreateRoomBody( @Json(name = "room_version") val roomVersion: String? ) + +/** + * Tells if the created room can be a direct chat one. + * + * @return true if it is a direct chat + */ +private fun CreateRoomBody.isDirect(): Boolean { + return preset == CreateRoomPreset.PRESET_TRUSTED_PRIVATE_CHAT && isDirect == true +} + +internal fun CreateRoomBody.getDirectUserId(): String? { + return if (isDirect()) { + invitedUserIds?.firstOrNull() + ?: invite3pids?.firstOrNull()?.address + ?: throw IllegalStateException("You can't create a direct room without an invitedUser") + } else null +} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateRoomTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateRoomTask.kt index 6dd2c91048..d76640573f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateRoomTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateRoomTask.kt @@ -62,11 +62,6 @@ internal class DefaultCreateRoomTask @Inject constructor( ) : CreateRoomTask { override suspend fun execute(params: CreateRoomParams): String { - val otherUserId = if (params.isDirect()) { - params.getFirstInvitedUserId() - ?: throw IllegalStateException("You can't create a direct room without an invitedUser") - } else null - if (params.preset == CreateRoomPreset.PRESET_PUBLIC_CHAT) { try { aliasAvailabilityChecker.check(params.roomAliasName) @@ -111,14 +106,13 @@ internal class DefaultCreateRoomTask @Inject constructor( RoomSummaryEntity.where(it, roomId).findFirst()?.lastActivityTime = clock.epochMillis() } - if (otherUserId != null) { - handleDirectChatCreation(roomId, otherUserId) - } + handleDirectChatCreation(roomId, createRoomBody.getDirectUserId()) setReadMarkers(roomId) return roomId } - private suspend fun handleDirectChatCreation(roomId: String, otherUserId: String) { + private suspend fun handleDirectChatCreation(roomId: String, otherUserId: String?) { + otherUserId ?: return // This is not a direct room monarchy.awaitTransaction { realm -> RoomSummaryEntity.where(realm, roomId).findFirst()?.apply { this.directUserId = otherUserId @@ -133,21 +127,4 @@ internal class DefaultCreateRoomTask @Inject constructor( val setReadMarkerParams = SetReadMarkersTask.Params(roomId, forceReadReceipt = true, forceReadMarker = true) return readMarkersTask.execute(setReadMarkerParams) } - - /** - * Tells if the created room can be a direct chat one. - * - * @return true if it is a direct chat - */ - private fun CreateRoomParams.isDirect(): Boolean { - return preset == CreateRoomPreset.PRESET_TRUSTED_PRIVATE_CHAT && - isDirect == true - } - - /** - * @return the first invited user id - */ - private fun CreateRoomParams.getFirstInvitedUserId(): String? { - return invitedUserIds.firstOrNull() ?: invite3pids.firstOrNull()?.value - } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimeline.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimeline.kt index 44a786a95d..05379a1a7b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimeline.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimeline.kt @@ -32,6 +32,7 @@ import kotlinx.coroutines.withContext import okhttp3.internal.closeQuietly import org.matrix.android.sdk.api.MatrixCoroutineDispatchers import org.matrix.android.sdk.api.extensions.tryOrNull +import org.matrix.android.sdk.api.session.room.model.localecho.RoomLocalEcho import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings @@ -383,6 +384,7 @@ internal class DefaultTimeline( } private suspend fun loadRoomMembersIfNeeded() { + if (RoomLocalEcho.isLocalEchoId(roomId)) return val loadRoomMembersParam = LoadRoomMembersTask.Params(roomId) try { loadRoomMembersTask.execute(loadRoomMembersParam) diff --git a/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomAction.kt b/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomAction.kt index 83c7f0a13b..b5657598ee 100644 --- a/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomAction.kt +++ b/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomAction.kt @@ -20,10 +20,12 @@ import im.vector.app.core.platform.VectorViewModelAction import im.vector.app.features.userdirectory.PendingSelection sealed class CreateDirectRoomAction : VectorViewModelAction { - data class CreateRoomAndInviteSelectedUsers( + data class PrepareRoomWithSelectedUsers( val selections: Set ) : CreateDirectRoomAction() + object CreateRoomAndInviteSelectedUsers : CreateDirectRoomAction() + data class QrScannedAction( val result: String ) : CreateDirectRoomAction() diff --git a/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomActivity.kt b/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomActivity.kt index 6292217b67..377acd2271 100644 --- a/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomActivity.kt +++ b/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomActivity.kt @@ -161,7 +161,7 @@ class CreateDirectRoomActivity : SimpleFragmentActivity() { private fun onMenuItemSelected(action: UserListSharedAction.OnMenuItemSelected) { if (action.itemId == R.id.action_create_direct_room) { - viewModel.handle(CreateDirectRoomAction.CreateRoomAndInviteSelectedUsers(action.selections)) + viewModel.handle(CreateDirectRoomAction.PrepareRoomWithSelectedUsers(action.selections)) } } diff --git a/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewModel.kt b/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewModel.kt index 5574ce3e63..b306cb6e03 100644 --- a/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewModel.kt @@ -61,7 +61,8 @@ class CreateDirectRoomViewModel @AssistedInject constructor( override fun handle(action: CreateDirectRoomAction) { when (action) { - is CreateDirectRoomAction.CreateRoomAndInviteSelectedUsers -> onSubmitInvitees(action.selections) + is CreateDirectRoomAction.PrepareRoomWithSelectedUsers -> onSubmitInvitees(action.selections) + is CreateDirectRoomAction.CreateRoomAndInviteSelectedUsers -> onCreateRoomWithInvitees() is CreateDirectRoomAction.QrScannedAction -> onCodeParsed(action) } } @@ -96,16 +97,18 @@ class CreateDirectRoomViewModel @AssistedInject constructor( } if (existingRoomId != null) { // Do not create a new DM, just tell that the creation is successful by passing the existing roomId - setState { - copy(createAndInviteState = Success(existingRoomId)) - } + setState { copy(createAndInviteState = Success(existingRoomId)) } } else { - // Create the DM - createRoomAndInviteSelectedUsers(selections) + createLocalRoomWithSelectedUsers(selections) } } - private fun createRoomAndInviteSelectedUsers(selections: Set) { + private fun onCreateRoomWithInvitees() { + // Create the DM + withState { createLocalRoomWithSelectedUsers(it.pendingSelections) } + } + + private fun createLocalRoomWithSelectedUsers(selections: Set) { setState { copy(createAndInviteState = Loading()) } viewModelScope.launch(Dispatchers.IO) { @@ -127,8 +130,7 @@ class CreateDirectRoomViewModel @AssistedInject constructor( val result = runCatchingToAsync { if (vectorFeatures.shouldStartDmOnFirstMessage()) { - // Todo: Prepare direct room creation - throw Throwable("Start DM on first message is not implemented yet.") + session.roomService().createLocalRoom(roomParams) } else { session.roomService().createRoom(roomParams) } diff --git a/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewState.kt b/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewState.kt index 41366a7110..33360ac20c 100644 --- a/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewState.kt +++ b/vector/src/main/java/im/vector/app/features/createdirect/CreateDirectRoomViewState.kt @@ -19,7 +19,9 @@ package im.vector.app.features.createdirect import com.airbnb.mvrx.Async import com.airbnb.mvrx.MavericksState import com.airbnb.mvrx.Uninitialized +import im.vector.app.features.userdirectory.PendingSelection data class CreateDirectRoomViewState( + val pendingSelections: Set = emptySet(), val createAndInviteState: Async = Uninitialized ) : MavericksState From 7ea2d0a86da9da63a9bab8ce8d33a66416649e94 Mon Sep 17 00:00:00 2001 From: Florian Renaud Date: Thu, 12 May 2022 11:32:31 +0200 Subject: [PATCH 056/291] Delete the local rooms when the room list is shown --- .../sdk/api/session/room/RoomService.kt | 5 ++ .../query/CurrentStateEventEntityQueries.kt | 11 ++- .../session/room/DefaultRoomService.kt | 6 ++ .../sdk/internal/session/room/RoomModule.kt | 5 ++ .../room/delete/DeleteLocalRoomTask.kt | 77 +++++++++++++++++++ .../home/room/detail/RoomDetailViewState.kt | 3 + .../home/room/detail/TimelineFragment.kt | 61 +++++++++------ .../home/room/detail/TimelineViewModel.kt | 42 +++++----- .../home/room/list/RoomListFragment.kt | 4 + .../home/room/list/RoomListViewModel.kt | 29 +++++++ .../home/room/list/RoomListViewState.kt | 3 +- 11 files changed, 201 insertions(+), 45 deletions(-) create mode 100644 matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/delete/DeleteLocalRoomTask.kt diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt index 41a215636d..90f3f323b2 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt @@ -47,6 +47,11 @@ interface RoomService { */ suspend fun createLocalRoom(createRoomParams: CreateRoomParams): String + /** + * Delete a local room with all its related events. + */ + suspend fun deleteLocalRoom(roomId: String) + /** * Create a direct room asynchronously. This is a facility method to create a direct room with the necessary parameters. */ diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/CurrentStateEventEntityQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/CurrentStateEventEntityQueries.kt index e0dbf2eee8..e17d07c584 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/CurrentStateEventEntityQueries.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/CurrentStateEventEntityQueries.kt @@ -23,13 +23,20 @@ import io.realm.kotlin.createObject import org.matrix.android.sdk.internal.database.model.CurrentStateEventEntity import org.matrix.android.sdk.internal.database.model.CurrentStateEventEntityFields +internal fun CurrentStateEventEntity.Companion.whereRoomId( + realm: Realm, + roomId: String +): RealmQuery { + return realm.where(CurrentStateEventEntity::class.java) + .equalTo(CurrentStateEventEntityFields.ROOM_ID, roomId) +} + internal fun CurrentStateEventEntity.Companion.whereType( realm: Realm, roomId: String, type: String ): RealmQuery { - return realm.where(CurrentStateEventEntity::class.java) - .equalTo(CurrentStateEventEntityFields.ROOM_ID, roomId) + return whereRoomId(realm = realm, roomId = roomId) .equalTo(CurrentStateEventEntityFields.TYPE, type) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomService.kt index cc5e935f87..6fd4f752a8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/DefaultRoomService.kt @@ -45,6 +45,7 @@ import org.matrix.android.sdk.internal.session.room.alias.DeleteRoomAliasTask import org.matrix.android.sdk.internal.session.room.alias.GetRoomIdByAliasTask import org.matrix.android.sdk.internal.session.room.create.CreateLocalRoomTask import org.matrix.android.sdk.internal.session.room.create.CreateRoomTask +import org.matrix.android.sdk.internal.session.room.delete.DeleteLocalRoomTask import org.matrix.android.sdk.internal.session.room.membership.RoomChangeMembershipStateDataSource import org.matrix.android.sdk.internal.session.room.membership.RoomMemberHelper import org.matrix.android.sdk.internal.session.room.membership.joining.JoinRoomTask @@ -62,6 +63,7 @@ internal class DefaultRoomService @Inject constructor( @SessionDatabase private val monarchy: Monarchy, private val createRoomTask: CreateRoomTask, private val createLocalRoomTask: CreateLocalRoomTask, + private val deleteLocalRoomTask: DeleteLocalRoomTask, private val joinRoomTask: JoinRoomTask, private val markAllRoomsReadTask: MarkAllRoomsReadTask, private val updateBreadcrumbsTask: UpdateBreadcrumbsTask, @@ -84,6 +86,10 @@ internal class DefaultRoomService @Inject constructor( return createLocalRoomTask.execute(createRoomParams) } + override suspend fun deleteLocalRoom(roomId: String) { + deleteLocalRoomTask.execute(DeleteLocalRoomTask.Params(roomId)) + } + override fun getRoom(roomId: String): Room? { return roomGetter.getRoom(roomId) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomModule.kt index bb92287ead..556e31356e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomModule.kt @@ -47,6 +47,8 @@ import org.matrix.android.sdk.internal.session.room.create.CreateLocalRoomTask import org.matrix.android.sdk.internal.session.room.create.CreateRoomTask import org.matrix.android.sdk.internal.session.room.create.DefaultCreateLocalRoomTask import org.matrix.android.sdk.internal.session.room.create.DefaultCreateRoomTask +import org.matrix.android.sdk.internal.session.room.delete.DefaultDeleteLocalRoomTask +import org.matrix.android.sdk.internal.session.room.delete.DeleteLocalRoomTask import org.matrix.android.sdk.internal.session.room.directory.DefaultGetPublicRoomTask import org.matrix.android.sdk.internal.session.room.directory.DefaultGetRoomDirectoryVisibilityTask import org.matrix.android.sdk.internal.session.room.directory.DefaultSetRoomDirectoryVisibilityTask @@ -197,6 +199,9 @@ internal abstract class RoomModule { @Binds abstract fun bindCreateLocalRoomTask(task: DefaultCreateLocalRoomTask): CreateLocalRoomTask + @Binds + abstract fun bindDeleteLocalRoomTask(task: DefaultDeleteLocalRoomTask): DeleteLocalRoomTask + @Binds abstract fun bindGetPublicRoomTask(task: DefaultGetPublicRoomTask): GetPublicRoomTask diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/delete/DeleteLocalRoomTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/delete/DeleteLocalRoomTask.kt new file mode 100644 index 0000000000..689fd24a97 --- /dev/null +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/delete/DeleteLocalRoomTask.kt @@ -0,0 +1,77 @@ +/* + * Copyright 2022 The Matrix.org Foundation C.I.C. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.internal.session.room.delete + +import com.zhuinden.monarchy.Monarchy +import org.matrix.android.sdk.api.session.room.model.localecho.RoomLocalEcho +import org.matrix.android.sdk.internal.database.model.ChunkEntity +import org.matrix.android.sdk.internal.database.model.CurrentStateEventEntity +import org.matrix.android.sdk.internal.database.model.EventEntity +import org.matrix.android.sdk.internal.database.model.RoomEntity +import org.matrix.android.sdk.internal.database.model.RoomMemberSummaryEntity +import org.matrix.android.sdk.internal.database.model.RoomSummaryEntity +import org.matrix.android.sdk.internal.database.model.TimelineEventEntity +import org.matrix.android.sdk.internal.database.query.where +import org.matrix.android.sdk.internal.database.query.whereRoomId +import org.matrix.android.sdk.internal.di.SessionDatabase +import org.matrix.android.sdk.internal.session.room.delete.DeleteLocalRoomTask.Params +import org.matrix.android.sdk.internal.task.Task +import org.matrix.android.sdk.internal.util.awaitTransaction +import timber.log.Timber +import javax.inject.Inject + +internal interface DeleteLocalRoomTask : Task { + data class Params(val roomId: String) +} + +internal class DefaultDeleteLocalRoomTask @Inject constructor( + @SessionDatabase private val monarchy: Monarchy, +) : DeleteLocalRoomTask { + + override suspend fun execute(params: Params) { + val roomId = params.roomId + + if (RoomLocalEcho.isLocalEchoId(roomId)) { + monarchy.awaitTransaction { realm -> + Timber.i("## DeleteLocalRoomTask - delete local room id $roomId") + RoomMemberSummaryEntity.where(realm, roomId = roomId).findAll() + ?.also { Timber.i("## DeleteLocalRoomTask - RoomMemberSummaryEntity - delete ${it.size} entries") } + ?.deleteAllFromRealm() + CurrentStateEventEntity.whereRoomId(realm, roomId = roomId).findAll() + ?.also { Timber.i("## DeleteLocalRoomTask - CurrentStateEventEntity - delete ${it.size} entries") } + ?.deleteAllFromRealm() + EventEntity.whereRoomId(realm, roomId = roomId).findAll() + ?.also { Timber.i("## DeleteLocalRoomTask - EventEntity - delete ${it.size} entries") } + ?.deleteAllFromRealm() + TimelineEventEntity.whereRoomId(realm, roomId = roomId).findAll() + ?.also { Timber.i("## DeleteLocalRoomTask - TimelineEventEntity - delete ${it.size} entries") } + ?.deleteAllFromRealm() + ChunkEntity.where(realm, roomId = roomId).findAll() + ?.also { Timber.i("## DeleteLocalRoomTask - RoomMemberSummaryEntity - delete ${it.size} entries") } + ?.deleteAllFromRealm() + RoomSummaryEntity.where(realm, roomId = roomId).findAll() + ?.also { Timber.i("## DeleteLocalRoomTask - RoomSummaryEntity - delete ${it.size} entries") } + ?.deleteAllFromRealm() + RoomEntity.where(realm, roomId = roomId).findAll() + ?.also { Timber.i("## DeleteLocalRoomTask - RoomEntity - delete ${it.size} entries") } + ?.deleteAllFromRealm() + } + } else { + Timber.i("## DeleteLocalRoomTask - Failed to remove room id $roomId: not a local room") + } + } +} diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewState.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewState.kt index 47db50d0d4..3ec7166739 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewState.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewState.kt @@ -25,6 +25,7 @@ import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.api.session.room.members.ChangeMembershipState import org.matrix.android.sdk.api.session.room.model.RoomMemberSummary import org.matrix.android.sdk.api.session.room.model.RoomSummary +import org.matrix.android.sdk.api.session.room.model.localecho.RoomLocalEcho import org.matrix.android.sdk.api.session.room.sender.SenderInfo import org.matrix.android.sdk.api.session.sync.SyncRequestState import org.matrix.android.sdk.api.session.sync.SyncState @@ -103,4 +104,6 @@ data class RoomDetailViewState( fun isDm() = asyncRoomSummary()?.isDirect == true fun isThreadTimeline() = rootThreadEventId != null + + fun isLocalRoom() = RoomLocalEcho.isLocalEchoId(roomId) } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt index 2b99bc67ef..0e818acec3 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt @@ -1695,31 +1695,41 @@ class TimelineFragment @Inject constructor( } private fun renderToolbar(roomSummary: RoomSummary?) { - if (!isThreadTimeLine()) { - views.includeRoomToolbar.roomToolbarContentView.isVisible = true - views.includeThreadToolbar.roomToolbarThreadConstraintLayout.isVisible = false - if (roomSummary == null) { - views.includeRoomToolbar.roomToolbarContentView.isClickable = false - } else { - views.includeRoomToolbar.roomToolbarContentView.isClickable = roomSummary.membership == Membership.JOIN - views.includeRoomToolbar.roomToolbarTitleView.text = roomSummary.displayName - avatarRenderer.render(roomSummary.toMatrixItem(), views.includeRoomToolbar.roomToolbarAvatarImageView) - val showPresence = roomSummary.isDirect - views.includeRoomToolbar.roomToolbarPresenceImageView.render(showPresence, roomSummary.directUserPresence) - val shieldView = if (showPresence) views.includeRoomToolbar.roomToolbarTitleShield else views.includeRoomToolbar.roomToolbarAvatarShield - shieldView.render(roomSummary.roomEncryptionTrustLevel) - views.includeRoomToolbar.roomToolbarPublicImageView.isVisible = roomSummary.isPublic && !roomSummary.isDirect + when { + isLocalRoom() -> { + views.includeRoomToolbar.roomToolbarContentView.isVisible = false + views.includeThreadToolbar.roomToolbarThreadConstraintLayout.isVisible = false + setupToolbar(views.roomToolbar) + .setTitle(R.string.fab_menu_create_chat) + .allowBack(useCross = true) } - } else { - views.includeRoomToolbar.roomToolbarContentView.isVisible = false - views.includeThreadToolbar.roomToolbarThreadConstraintLayout.isVisible = true - timelineArgs.threadTimelineArgs?.let { - val matrixItem = MatrixItem.RoomItem(it.roomId, it.displayName, it.avatarUrl) - avatarRenderer.render(matrixItem, views.includeThreadToolbar.roomToolbarThreadImageView) - views.includeThreadToolbar.roomToolbarThreadShieldImageView.render(it.roomEncryptionTrustLevel) - views.includeThreadToolbar.roomToolbarThreadSubtitleTextView.text = it.displayName + isThreadTimeLine() -> { + views.includeRoomToolbar.roomToolbarContentView.isVisible = false + views.includeThreadToolbar.roomToolbarThreadConstraintLayout.isVisible = true + timelineArgs.threadTimelineArgs?.let { + val matrixItem = MatrixItem.RoomItem(it.roomId, it.displayName, it.avatarUrl) + avatarRenderer.render(matrixItem, views.includeThreadToolbar.roomToolbarThreadImageView) + views.includeThreadToolbar.roomToolbarThreadShieldImageView.render(it.roomEncryptionTrustLevel) + views.includeThreadToolbar.roomToolbarThreadSubtitleTextView.text = it.displayName + } + views.includeThreadToolbar.roomToolbarThreadTitleTextView.text = resources.getText(R.string.thread_timeline_title) + } + else -> { + views.includeRoomToolbar.roomToolbarContentView.isVisible = true + views.includeThreadToolbar.roomToolbarThreadConstraintLayout.isVisible = false + if (roomSummary == null) { + views.includeRoomToolbar.roomToolbarContentView.isClickable = false + } else { + views.includeRoomToolbar.roomToolbarContentView.isClickable = roomSummary.membership == Membership.JOIN + views.includeRoomToolbar.roomToolbarTitleView.text = roomSummary.displayName + avatarRenderer.render(roomSummary.toMatrixItem(), views.includeRoomToolbar.roomToolbarAvatarImageView) + val showPresence = roomSummary.isDirect + views.includeRoomToolbar.roomToolbarPresenceImageView.render(showPresence, roomSummary.directUserPresence) + val shieldView = if (showPresence) views.includeRoomToolbar.roomToolbarTitleShield else views.includeRoomToolbar.roomToolbarAvatarShield + shieldView.render(roomSummary.roomEncryptionTrustLevel) + views.includeRoomToolbar.roomToolbarPublicImageView.isVisible = roomSummary.isPublic && !roomSummary.isDirect + } } - views.includeThreadToolbar.roomToolbarThreadTitleTextView.text = resources.getText(R.string.thread_timeline_title) } } @@ -2658,6 +2668,11 @@ class TimelineFragment @Inject constructor( */ private fun isThreadTimeLine(): Boolean = timelineArgs.threadTimelineArgs?.rootThreadEventId != null + /** + * Returns true if the current room is a local room, false otherwise. + */ + private fun isLocalRoom(): Boolean = withState(timelineViewModel) { it.isLocalRoom() } + /** * Returns the root thread event if we are in a thread room, otherwise returns null. */ diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineViewModel.kt index 07b20b4914..6ad356e82d 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineViewModel.kt @@ -732,26 +732,30 @@ class TimelineViewModel @AssistedInject constructor( return@withState false } - if (initialState.isThreadTimeline()) { - when (itemId) { - R.id.menu_thread_timeline_view_in_room, - R.id.menu_thread_timeline_copy_link, - R.id.menu_thread_timeline_share -> true - else -> false + when { + initialState.isLocalRoom() -> false + initialState.isThreadTimeline() -> { + when (itemId) { + R.id.menu_thread_timeline_view_in_room, + R.id.menu_thread_timeline_copy_link, + R.id.menu_thread_timeline_share -> true + else -> false + } } - } else { - when (itemId) { - R.id.timeline_setting -> true - R.id.invite -> state.canInvite - R.id.open_matrix_apps -> true - R.id.voice_call -> state.isCallOptionAvailable() - R.id.video_call -> state.isCallOptionAvailable() || state.jitsiState.confId == null || state.jitsiState.hasJoined - // Show Join conference button only if there is an active conf id not joined. Otherwise fallback to default video disabled. ^ - R.id.join_conference -> !state.isCallOptionAvailable() && state.jitsiState.confId != null && !state.jitsiState.hasJoined - R.id.search -> state.isSearchAvailable() - R.id.menu_timeline_thread_list -> vectorPreferences.areThreadMessagesEnabled() - R.id.dev_tools -> vectorPreferences.developerMode() - else -> false + else -> { + when (itemId) { + R.id.timeline_setting -> true + R.id.invite -> state.canInvite + R.id.open_matrix_apps -> true + R.id.voice_call -> state.isCallOptionAvailable() + R.id.video_call -> state.isCallOptionAvailable() || state.jitsiState.confId == null || state.jitsiState.hasJoined + // Show Join conference button only if there is an active conf id not joined. Otherwise fallback to default video disabled. ^ + R.id.join_conference -> !state.isCallOptionAvailable() && state.jitsiState.confId != null && !state.jitsiState.hasJoined + R.id.search -> state.isSearchAvailable() + R.id.menu_timeline_thread_list -> vectorPreferences.areThreadMessagesEnabled() + R.id.dev_tools -> vectorPreferences.developerMode() + else -> false + } } } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListFragment.kt b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListFragment.kt index 5539986118..c25fe546c3 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListFragment.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListFragment.kt @@ -146,6 +146,10 @@ class RoomListFragment @Inject constructor( (it.contentEpoxyController as? RoomSummaryPagedController)?.roomChangeMembershipStates = ms } } + roomListViewModel.onEach(RoomListViewState::localRoomIds) { + // Local rooms should not exist anymore when the room list is shown + roomListViewModel.deleteLocalRooms(it) + } } private fun refreshCollapseStates() { diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewModel.kt index 49467c0531..cd4bb06949 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewModel.kt @@ -48,7 +48,10 @@ import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.getRoomSummary import org.matrix.android.sdk.api.session.room.UpdatableLivePageResult import org.matrix.android.sdk.api.session.room.members.ChangeMembershipState +import org.matrix.android.sdk.api.session.room.model.Membership +import org.matrix.android.sdk.api.session.room.model.localecho.RoomLocalEcho import org.matrix.android.sdk.api.session.room.model.tag.RoomTag +import org.matrix.android.sdk.api.session.room.roomSummaryQueryParams import org.matrix.android.sdk.api.session.room.state.isPublic import org.matrix.android.sdk.api.util.toMatrixItem import org.matrix.android.sdk.flow.flow @@ -96,6 +99,7 @@ class RoomListViewModel @AssistedInject constructor( init { observeMembershipChanges() + observeLocalRooms() appStateHandler.selectedRoomGroupingFlow .distinctUntilChanged() @@ -123,6 +127,23 @@ class RoomListViewModel @AssistedInject constructor( } } + private fun observeLocalRooms() { + val queryParams = roomSummaryQueryParams { + memberships = listOf(Membership.JOIN) + } + session + .flow() + .liveRoomSummaries(queryParams) + .map { roomSummaries -> + roomSummaries.mapNotNull { summary -> + summary.roomId.takeIf { RoomLocalEcho.isLocalEchoId(it) } + }.toSet() + } + .setOnEach { roomIds -> + copy(localRoomIds = roomIds) + } + } + companion object : MavericksViewModelFactory by hiltMavericksViewModelFactory() private val roomListSectionBuilder = if (appStateHandler.getCurrentRoomGroupingMethod() is RoomGroupingMethod.BySpace) { @@ -173,6 +194,14 @@ class RoomListViewModel @AssistedInject constructor( return session.getRoom(roomId)?.stateService()?.isPublic().orFalse() } + fun deleteLocalRooms(roomsIds: Set) { + viewModelScope.launch { + roomsIds.forEach { + session.roomService().deleteLocalRoom(it) + } + } + } + // PRIVATE METHODS ***************************************************************************** private fun handleSelectRoom(action: RoomListAction.SelectRoom) = withState { diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewState.kt b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewState.kt index 46ff6c242b..9d386b679a 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewState.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewState.kt @@ -30,7 +30,8 @@ data class RoomListViewState( val roomMembershipChanges: Map = emptyMap(), val asyncSuggestedRooms: Async> = Uninitialized, val currentUserName: String? = null, - val currentRoomGrouping: Async = Uninitialized + val currentRoomGrouping: Async = Uninitialized, + val localRoomIds: Set = emptySet() ) : MavericksState { constructor(args: RoomListParams) : this(displayMode = args.displayMode) From e86f9193dd61c08c80dffb8aea354bbeba2a1029 Mon Sep 17 00:00:00 2001 From: Florian Renaud Date: Fri, 13 May 2022 18:09:39 +0200 Subject: [PATCH 057/291] Display timeline from the top of the screen for local rooms --- .../app/features/home/room/detail/TimelineFragment.kt | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt index 0e818acec3..a3d342ef48 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt @@ -1426,6 +1426,9 @@ class TimelineFragment @Inject constructor( updateJumpToReadMarkerViewVisibility() jumpToBottomViewVisibilityManager.maybeShowJumpToBottomViewVisibilityWithDelay() } + }.apply { + // For local rooms, pin the view's content to the top edge (the layout is reversed) + stackFromEnd = isLocalRoom() } val stateRestorer = LayoutManagerStateRestorer(layoutManager).register() scrollOnNewMessageCallback = ScrollOnNewMessageCallback(layoutManager, timelineEventController) @@ -1696,14 +1699,14 @@ class TimelineFragment @Inject constructor( private fun renderToolbar(roomSummary: RoomSummary?) { when { - isLocalRoom() -> { + isLocalRoom() -> { views.includeRoomToolbar.roomToolbarContentView.isVisible = false views.includeThreadToolbar.roomToolbarThreadConstraintLayout.isVisible = false setupToolbar(views.roomToolbar) .setTitle(R.string.fab_menu_create_chat) .allowBack(useCross = true) } - isThreadTimeLine() -> { + isThreadTimeLine() -> { views.includeRoomToolbar.roomToolbarContentView.isVisible = false views.includeThreadToolbar.roomToolbarThreadConstraintLayout.isVisible = true timelineArgs.threadTimelineArgs?.let { @@ -1714,7 +1717,7 @@ class TimelineFragment @Inject constructor( } views.includeThreadToolbar.roomToolbarThreadTitleTextView.text = resources.getText(R.string.thread_timeline_title) } - else -> { + else -> { views.includeRoomToolbar.roomToolbarContentView.isVisible = true views.includeThreadToolbar.roomToolbarThreadConstraintLayout.isVisible = false if (roomSummary == null) { From b144bac578c721e2593d6f02556657d7fad7503c Mon Sep 17 00:00:00 2001 From: Florian Renaud Date: Fri, 13 May 2022 13:56:56 +0200 Subject: [PATCH 058/291] Update wordings for local room timeline --- .../timeline/factory/EncryptionItemFactory.kt | 16 +++++-- .../factory/MergedHeaderItemFactory.kt | 2 + .../detail/timeline/item/BasedMergedItem.kt | 1 + .../timeline/item/MergedRoomCreationItem.kt | 45 +++++++++++++------ vector/src/main/res/values/strings.xml | 4 +- 5 files changed, 50 insertions(+), 18 deletions(-) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/EncryptionItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/EncryptionItemFactory.kt index dd058197b4..5f32696334 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/EncryptionItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/EncryptionItemFactory.kt @@ -30,6 +30,7 @@ import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.events.model.content.EncryptionEventContent import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoomSummary +import org.matrix.android.sdk.api.session.room.model.localecho.RoomLocalEcho import javax.inject.Inject class EncryptionItemFactory @Inject constructor( @@ -55,12 +56,19 @@ class EncryptionItemFactory @Inject constructor( val description: String val shield: StatusTileTimelineItem.ShieldUIState if (isSafeAlgorithm) { + val isDirect = session.getRoomSummary(event.root.roomId.orEmpty())?.isDirect.orFalse() title = stringProvider.getString(R.string.encryption_enabled) description = stringProvider.getString( - if (session.getRoomSummary(event.root.roomId ?: "")?.isDirect.orFalse()) { - R.string.direct_room_encryption_enabled_tile_description - } else { - R.string.encryption_enabled_tile_description + when { + isDirect && RoomLocalEcho.isLocalEchoId(event.root.roomId.orEmpty()) -> { + R.string.direct_room_encryption_enabled_tile_description_future + } + isDirect -> { + R.string.direct_room_encryption_enabled_tile_description + } + else -> { + R.string.encryption_enabled_tile_description + } } ) shield = StatusTileTimelineItem.ShieldUIState.BLACK diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MergedHeaderItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MergedHeaderItemFactory.kt index 771e42b63c..800fc27e77 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MergedHeaderItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MergedHeaderItemFactory.kt @@ -117,6 +117,7 @@ class MergedHeaderItemFactory @Inject constructor( highlighted = true } val data = BasedMergedItem.Data( + roomId = mergedEvent.root.roomId, userId = mergedEvent.root.senderId ?: "", avatarUrl = mergedEvent.senderInfo.avatarUrl, memberName = mergedEvent.senderInfo.disambiguatedDisplayName, @@ -199,6 +200,7 @@ class MergedHeaderItemFactory @Inject constructor( highlighted = true } val data = BasedMergedItem.Data( + roomId = mergedEvent.root.roomId, userId = mergedEvent.root.senderId ?: "", avatarUrl = mergedEvent.senderInfo.avatarUrl, memberName = mergedEvent.senderInfo.disambiguatedDisplayName, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/BasedMergedItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/BasedMergedItem.kt index 1c56a0809e..4999036e9d 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/BasedMergedItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/BasedMergedItem.kt @@ -54,6 +54,7 @@ abstract class BasedMergedItem : BaseEventItem() } data class Data( + val roomId: String?, val localId: Long, val eventId: String, val userId: String, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MergedRoomCreationItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MergedRoomCreationItem.kt index f41c17d9e7..5b8d973a04 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MergedRoomCreationItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MergedRoomCreationItem.kt @@ -40,6 +40,7 @@ import im.vector.app.features.home.room.detail.timeline.TimelineEventController import im.vector.app.features.home.room.detail.timeline.tools.linkify import me.gujun.android.span.span import org.matrix.android.sdk.api.session.room.model.RoomSummary +import org.matrix.android.sdk.api.session.room.model.localecho.RoomLocalEcho import org.matrix.android.sdk.api.util.toMatrixItem @EpoxyModelClass(layout = R.layout.item_timeline_event_base_noinfo) @@ -102,10 +103,16 @@ abstract class MergedRoomCreationItem : BasedMergedItem { + holder.expandView.resources.getString(R.string.direct_room_encryption_enabled_tile_description_future) + } + data?.isDirectRoom == true -> { + holder.expandView.resources.getString(R.string.direct_room_encryption_enabled_tile_description) + } + else -> { + holder.expandView.resources.getString(R.string.encryption_enabled_tile_description) + } } holder.e2eTitleDescriptionView.textAlignment = View.TEXT_ALIGNMENT_CENTER holder.e2eTitleTextView.setCompoundDrawablesWithIntrinsicBounds( @@ -130,17 +137,29 @@ abstract class MergedRoomCreationItem : BasedMergedItem { + if (isLocalRoom) { + holder.roomDescriptionText.text = holder.view.resources.getString( + R.string.send_your_first_msg_to_invite, + roomSummary?.displayName.orEmpty() + ) + } else { + holder.roomDescriptionText.text = holder.view.resources.getString( + R.string.this_is_the_beginning_of_dm, + roomSummary?.displayName.orEmpty() + ) + } + } + roomDisplayName.isNullOrBlank() || roomSummary.name.isBlank() -> { + holder.roomDescriptionText.text = holder.view.resources.getString(R.string.this_is_the_beginning_of_room_no_name) + } + else -> { + holder.roomDescriptionText.text = holder.view.resources.getString(R.string.this_is_the_beginning_of_room, roomDisplayName) + } } val topic = roomSummary?.topic diff --git a/vector/src/main/res/values/strings.xml b/vector/src/main/res/values/strings.xml index b507ed473f..f684ccadad 100644 --- a/vector/src/main/res/values/strings.xml +++ b/vector/src/main/res/values/strings.xml @@ -2399,7 +2399,8 @@ Encryption enabled Messages in this room are end-to-end encrypted. Learn more & verify users in their profile. - Messages in this room are end-to-end encrypted. + Messages in this chat are end-to-end encrypted. + Messages in this chat will be end-to-end encrypted. Encryption not enabled Encryption is misconfigured The encryption used by this room is not supported @@ -2411,6 +2412,7 @@ This is the beginning of %s. This is the beginning of this conversation. This is the beginning of your direct message history with %s. + Send your first message to invite %s to chat %s to let people know what this room is about. Add a topic From a46d7ed8dd17064abde7e78ec1a16baddfd90f5b Mon Sep 17 00:00:00 2001 From: Florian Renaud Date: Fri, 13 May 2022 17:48:30 +0200 Subject: [PATCH 059/291] Hide unwanted events from local room timeline --- .../detail/timeline/TimelineEventController.kt | 15 +++++++++------ .../helper/TimelineEventVisibilityHelper.kt | 8 ++++++++ .../timeline/item/MergedRoomCreationItem.kt | 6 ++++++ 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/TimelineEventController.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/TimelineEventController.kt index a02eaa3202..6ef4b21387 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/TimelineEventController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/TimelineEventController.kt @@ -69,6 +69,7 @@ import org.matrix.android.sdk.api.session.room.model.Membership import org.matrix.android.sdk.api.session.room.model.ReadReceipt import org.matrix.android.sdk.api.session.room.model.RoomMemberContent import org.matrix.android.sdk.api.session.room.model.RoomSummary +import org.matrix.android.sdk.api.session.room.model.localecho.RoomLocalEcho import org.matrix.android.sdk.api.session.room.model.message.MessageAudioContent import org.matrix.android.sdk.api.session.room.model.message.MessageImageInfoContent import org.matrix.android.sdk.api.session.room.model.message.MessageVideoContent @@ -603,12 +604,14 @@ class TimelineEventController @Inject constructor( } private fun wantsDateSeparator(event: TimelineEvent, nextEvent: TimelineEvent?): Boolean { - return if (hasReachedInvite && hasUTD) { - true - } else { - val date = event.root.localDateTime() - val nextDate = nextEvent?.root?.localDateTime() - date.toLocalDate() != nextDate?.toLocalDate() + return when { + RoomLocalEcho.isLocalEchoId(partialState.roomSummary?.roomId.orEmpty()) -> false + hasReachedInvite && hasUTD -> true + else -> { + val date = event.root.localDateTime() + val nextDate = nextEvent?.root?.localDateTime() + date.toLocalDate() != nextDate?.toLocalDate() + } } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineEventVisibilityHelper.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineEventVisibilityHelper.kt index e4e0ea8352..488aebde13 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineEventVisibilityHelper.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineEventVisibilityHelper.kt @@ -26,6 +26,7 @@ import org.matrix.android.sdk.api.session.events.model.isThread import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.room.model.Membership import org.matrix.android.sdk.api.session.room.model.RoomMemberContent +import org.matrix.android.sdk.api.session.room.model.localecho.RoomLocalEcho import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import javax.inject.Inject @@ -176,6 +177,13 @@ class TimelineEventVisibilityHelper @Inject constructor(private val userPreferen return true } + // Hide fake events for local rooms + if (RoomLocalEcho.isLocalEchoId(roomId) && + root.getClearType() == EventType.STATE_ROOM_MEMBER || + root.getClearType() == EventType.STATE_ROOM_HISTORY_VISIBILITY) { + return true + } + // Allow only the the threads within the rootThreadEventId along with the root event if (userPreferencesProvider.areThreadMessagesEnabled() && isFromThreadTimeline) { return if (root.getRootThreadEventId() == rootThreadEventId) { diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MergedRoomCreationItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MergedRoomCreationItem.kt index 5b8d973a04..5b7c4efc7f 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MergedRoomCreationItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MergedRoomCreationItem.kt @@ -58,7 +58,12 @@ abstract class MergedRoomCreationItem : BasedMergedItem(R.id.mergedSumContainer) val summaryView by bind(R.id.itemNoticeTextView) val avatarView by bind(R.id.itemNoticeAvatarView) val encryptionTile by bind(R.id.creationEncryptionTile) From 554d35fe96712e0faa64f5e83e66ff7a649cbf10 Mon Sep 17 00:00:00 2001 From: Florian Renaud Date: Sat, 21 May 2022 00:18:27 +0200 Subject: [PATCH 060/291] Add changelog --- changelog.d/5525.wip | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/5525.wip diff --git a/changelog.d/5525.wip b/changelog.d/5525.wip new file mode 100644 index 0000000000..c4ac0ff008 --- /dev/null +++ b/changelog.d/5525.wip @@ -0,0 +1 @@ +Create DM room only on first message - Design implementation & debug feature flag From 398e98ae85a387eead479b695bf800fa65352fa3 Mon Sep 17 00:00:00 2001 From: Florian Renaud Date: Tue, 24 May 2022 00:32:16 +0200 Subject: [PATCH 061/291] Remove useless variable --- .../sdk/internal/session/room/create/CreateLocalRoomTask.kt | 3 --- 1 file changed, 3 deletions(-) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateLocalRoomTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateLocalRoomTask.kt index e650039d75..1fa2cfe35b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateLocalRoomTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateLocalRoomTask.kt @@ -149,7 +149,6 @@ internal class DefaultCreateLocalRoomTask @Inject constructor( } val eventList = createLocalRoomEvents(createRoomBody) - val eventIds = ArrayList(eventList.size) val roomMemberContentsByUser = HashMap() for (event in eventList) { @@ -157,8 +156,6 @@ internal class DefaultCreateLocalRoomTask @Inject constructor( continue } - eventIds.add(event.eventId) - val eventEntity = event.toEntity(roomId, SendState.SYNCED, null).copyToRealmOrIgnore(realm, EventInsertType.INCREMENTAL_SYNC) if (event.stateKey != null) { CurrentStateEventEntity.getOrCreate(realm, roomId, event.stateKey, event.type).apply { From d42a3da5b7b5dc664fd0f01f847fe5f0d013f07c Mon Sep 17 00:00:00 2001 From: Florian Renaud Date: Tue, 14 Jun 2022 15:16:17 +0200 Subject: [PATCH 062/291] Reduce code smell --- .../timeline/item/MergedRoomCreationItem.kt | 82 +++++++++++-------- 1 file changed, 46 insertions(+), 36 deletions(-) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MergedRoomCreationItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MergedRoomCreationItem.kt index 5b7c4efc7f..cd60057379 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MergedRoomCreationItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MergedRoomCreationItem.kt @@ -16,6 +16,7 @@ package im.vector.app.features.home.room.detail.timeline.item +import android.content.res.Resources import android.text.SpannableString import android.text.method.MovementMethod import android.text.style.ClickableSpan @@ -25,7 +26,6 @@ import android.widget.ImageView import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat -import androidx.core.view.isGone import androidx.core.view.isVisible import androidx.core.view.updateLayoutParams import com.airbnb.epoxy.EpoxyAttribute @@ -39,6 +39,7 @@ import im.vector.app.features.home.room.detail.RoomDetailAction import im.vector.app.features.home.room.detail.timeline.TimelineEventController import im.vector.app.features.home.room.detail.timeline.tools.linkify import me.gujun.android.span.span +import org.matrix.android.sdk.api.extensions.orFalse import org.matrix.android.sdk.api.session.room.model.RoomSummary import org.matrix.android.sdk.api.session.room.model.localecho.RoomLocalEcho import org.matrix.android.sdk.api.util.toMatrixItem @@ -62,44 +63,45 @@ abstract class MergedRoomCreationItem : BasedMergedItem { - holder.expandView.resources.getString(R.string.direct_room_encryption_enabled_tile_description_future) - } - data?.isDirectRoom == true -> { - holder.expandView.resources.getString(R.string.direct_room_encryption_enabled_tile_description) - } - else -> { - holder.expandView.resources.getString(R.string.encryption_enabled_tile_description) - } - } + holder.e2eTitleDescriptionView.text = getE2ESecureDescriptionText(holder.expandView.resources, data) holder.e2eTitleDescriptionView.textAlignment = View.TEXT_ALIGNMENT_CENTER holder.e2eTitleTextView.setCompoundDrawablesWithIntrinsicBounds( ContextCompat.getDrawable(holder.view.context, R.drawable.ic_shield_black), @@ -137,17 +129,32 @@ abstract class MergedRoomCreationItem : BasedMergedItem { + if (attributes.isLocalRoom) { + resources.getString(R.string.direct_room_encryption_enabled_tile_description_future) + } else { + resources.getString(R.string.direct_room_encryption_enabled_tile_description) + } + } + else -> { + resources.getString(R.string.encryption_enabled_tile_description) + } + } + } + private fun bindCreationSummaryTile(holder: Holder) { val roomSummary = attributes.roomSummary val roomDisplayName = roomSummary?.displayName holder.roomNameText.setTextOrHide(roomDisplayName) val isDirect = roomSummary?.isDirect == true - val isLocalRoom = RoomLocalEcho.isLocalEchoId(roomSummary?.roomId.orEmpty()) val membersCount = roomSummary?.otherMemberIds?.size ?: 0 when { isDirect -> { - if (isLocalRoom) { + if (attributes.isLocalRoom) { holder.roomDescriptionText.text = holder.view.resources.getString( R.string.send_your_first_msg_to_invite, roomSummary?.displayName.orEmpty() @@ -261,5 +268,8 @@ abstract class MergedRoomCreationItem : BasedMergedItem Date: Tue, 10 May 2022 13:02:49 +0100 Subject: [PATCH 063/291] adding forgot password button to login screen --- .../layout/fragment_ftue_combined_login.xml | 18 ++++++++++++++++-- vector/src/main/res/values/donottranslate.xml | 1 + 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/vector/src/main/res/layout/fragment_ftue_combined_login.xml b/vector/src/main/res/layout/fragment_ftue_combined_login.xml index 8037f207fc..d50fdb6394 100644 --- a/vector/src/main/res/layout/fragment_ftue_combined_login.xml +++ b/vector/src/main/res/layout/fragment_ftue_combined_login.xml @@ -170,7 +170,7 @@ android:layout_width="0dp" android:layout_height="wrap_content" android:hint="@string/login_signup_password_hint" - app:layout_constraintBottom_toTopOf="@id/actionSpacing" + app:layout_constraintBottom_toTopOf="@id/loginForgotPassword" app:layout_constraintEnd_toEndOf="@id/loginGutterEnd" app:layout_constraintStart_toStartOf="@id/loginGutterStart" app:layout_constraintTop_toBottomOf="@id/entrySpacing"> @@ -184,13 +184,27 @@ +