Merge branch 'develop' into feature/bma/displayname_fallback

This commit is contained in:
Benoit Marty 2021-04-06 14:31:32 +02:00 committed by GitHub
commit 8b15008eba
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
187 changed files with 1846 additions and 1244 deletions

View file

@ -15,6 +15,7 @@ Improvements 🙌:
- Be more robust when parsing some enums
- Improve timeline filtering (dissociate membership and profile events, display hidden events when highlighted, fix hidden item/read receipts behavior)
- Add better support for empty room name fallback (#3106)
- Room list improvements (paging)
Bugfix 🐛:
- Fix bad theme change for the MainActivity
@ -37,6 +38,7 @@ Test:
Other changes:
- Add version details on the login screen, in debug or developer mode
- Migrate Retrofit interface to coroutine calls
Changes in Element 1.1.3 (2021-03-18)
===================================================

View file

@ -16,7 +16,7 @@ buildscript {
classpath 'com.google.gms:google-services:4.3.5'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:3.1.1'
classpath 'com.google.android.gms:oss-licenses-plugin:0.10.2'
classpath 'com.google.android.gms:oss-licenses-plugin:0.10.3'
classpath "com.likethesalad.android:string-reference:1.2.1"
// NOTE: Do not place your application dependencies here; they belong

View file

@ -108,7 +108,7 @@ static def gitRevisionDate() {
dependencies {
def arrow_version = "0.8.2"
def moshi_version = '1.11.0'
def moshi_version = '1.12.0'
def lifecycle_version = '2.2.0'
def arch_version = '2.1.0'
def markwon_version = '3.1.0'
@ -166,7 +166,7 @@ dependencies {
implementation 'com.facebook.stetho:stetho-okhttp3:1.6.0'
// Phone number https://github.com/google/libphonenumber
implementation 'com.googlecode.libphonenumber:libphonenumber:8.12.20'
implementation 'com.googlecode.libphonenumber:libphonenumber:8.12.21'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.robolectric:robolectric:4.5.1'

View file

@ -37,6 +37,18 @@ fun Throwable.shouldBeRetried(): Boolean {
|| (this is Failure.ServerError && error.code == MatrixError.M_LIMIT_EXCEEDED)
}
/**
* Get the retry delay in case of rate limit exceeded error, adding 100 ms, of defaultValue otherwise
*/
fun Throwable.getRetryDelay(defaultValue: Long): Long {
return (this as? Failure.ServerError)
?.error
?.takeIf { it.code == MatrixError.M_LIMIT_EXCEEDED }
?.retryAfterMillis
?.plus(100L)
?: defaultValue
}
fun Throwable.isInvalidPassword(): Boolean {
return this is Failure.ServerError
&& error.code == MatrixError.M_FORBIDDEN

View file

@ -0,0 +1,24 @@
/*
* Copyright (c) 2021 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.query
enum class RoomCategoryFilter {
ONLY_DM,
ONLY_ROOMS,
ONLY_WITH_NOTIFICATIONS,
ALL
}

View file

@ -0,0 +1,23 @@
/*
* Copyright 2021 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.query
data class RoomTagQueryFilter(
val isFavorite: Boolean?,
val isLowPriority: Boolean?,
val isServerNotice: Boolean?
)

View file

@ -17,6 +17,7 @@
package org.matrix.android.sdk.api.session.room
import androidx.lifecycle.LiveData
import androidx.paging.PagedList
import org.matrix.android.sdk.api.MatrixCallback
import org.matrix.android.sdk.api.session.events.model.Event
import org.matrix.android.sdk.api.session.room.members.ChangeMembershipState
@ -24,6 +25,7 @@ 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.create.CreateRoomParams
import org.matrix.android.sdk.api.session.room.peeking.PeekResult
import org.matrix.android.sdk.api.session.room.summary.RoomAggregateNotificationCount
import org.matrix.android.sdk.api.util.Cancelable
import org.matrix.android.sdk.api.util.Optional
import org.matrix.android.sdk.internal.session.room.alias.RoomAliasDescription
@ -178,4 +180,29 @@ interface RoomService {
* This call will try to gather some information on this room, but it could fail and get nothing more
*/
fun peekRoom(roomIdOrAlias: String, callback: MatrixCallback<PeekResult>)
/**
* TODO Doc
*/
fun getPagedRoomSummariesLive(queryParams: RoomSummaryQueryParams,
pagedListConfig: PagedList.Config = defaultPagedListConfig): LiveData<PagedList<RoomSummary>>
/**
* TODO Doc
*/
fun getFilteredPagedRoomSummariesLive(queryParams: RoomSummaryQueryParams,
pagedListConfig: PagedList.Config = defaultPagedListConfig): UpdatableFilterLivePageResult
/**
* TODO Doc
*/
fun getNotificationCountForRooms(queryParams: RoomSummaryQueryParams): RoomAggregateNotificationCount
private val defaultPagedListConfig
get() = PagedList.Config.Builder()
.setPageSize(10)
.setInitialLoadSizeHint(20)
.setEnablePlaceholders(false)
.setPrefetchDistance(10)
.build()
}

View file

@ -17,6 +17,8 @@
package org.matrix.android.sdk.api.session.room
import org.matrix.android.sdk.api.query.QueryStringValue
import org.matrix.android.sdk.api.query.RoomCategoryFilter
import org.matrix.android.sdk.api.query.RoomTagQueryFilter
import org.matrix.android.sdk.api.session.room.model.Membership
fun roomSummaryQueryParams(init: (RoomSummaryQueryParams.Builder.() -> Unit) = {}): RoomSummaryQueryParams {
@ -31,7 +33,9 @@ data class RoomSummaryQueryParams(
val roomId: QueryStringValue,
val displayName: QueryStringValue,
val canonicalAlias: QueryStringValue,
val memberships: List<Membership>
val memberships: List<Membership>,
val roomCategoryFilter: RoomCategoryFilter?,
val roomTagQueryFilter: RoomTagQueryFilter?
) {
class Builder {
@ -40,12 +44,16 @@ data class RoomSummaryQueryParams(
var displayName: QueryStringValue = QueryStringValue.IsNotEmpty
var canonicalAlias: QueryStringValue = QueryStringValue.NoCondition
var memberships: List<Membership> = Membership.all()
var roomCategoryFilter: RoomCategoryFilter? = RoomCategoryFilter.ALL
var roomTagQueryFilter: RoomTagQueryFilter? = null
fun build() = RoomSummaryQueryParams(
roomId = roomId,
displayName = displayName,
canonicalAlias = canonicalAlias,
memberships = memberships
memberships = memberships,
roomCategoryFilter = roomCategoryFilter,
roomTagQueryFilter = roomTagQueryFilter
)
}
}

View file

@ -1,11 +1,11 @@
/*
* Copyright 2019 New Vector Ltd
* Copyright (c) 2021 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
* 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,
@ -14,12 +14,14 @@
* limitations under the License.
*/
package im.vector.app.features.home
package org.matrix.android.sdk.api.session.room
import im.vector.app.core.utils.BehaviorDataSource
import androidx.lifecycle.LiveData
import androidx.paging.PagedList
import org.matrix.android.sdk.api.session.room.model.RoomSummary
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class HomeRoomListDataSource @Inject constructor() : BehaviorDataSource<List<RoomSummary>>()
interface UpdatableFilterLivePageResult {
val livePagedList: LiveData<PagedList<RoomSummary>>
fun updateQuery(queryParams: RoomSummaryQueryParams)
}

View file

@ -0,0 +1,25 @@
/*
* Copyright 2021 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.summary
data class RoomAggregateNotificationCount(
val notificationCount: Int,
val highlightCount: Int
) {
val totalCount = notificationCount + highlightCount
val isHighlight = highlightCount > 0
}

View file

@ -29,7 +29,6 @@ import org.matrix.android.sdk.internal.auth.registration.SuccessResult
import org.matrix.android.sdk.internal.auth.registration.ValidationCodeBody
import org.matrix.android.sdk.internal.auth.version.Versions
import org.matrix.android.sdk.internal.network.NetworkConstants
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.Headers
@ -45,26 +44,26 @@ internal interface AuthAPI {
* Get a Riot config file, using the name including the domain
*/
@GET("config.{domain}.json")
fun getRiotConfigDomain(@Path("domain") domain: String): Call<RiotConfig>
suspend fun getRiotConfigDomain(@Path("domain") domain: String): RiotConfig
/**
* Get a Riot config file
*/
@GET("config.json")
fun getRiotConfig(): Call<RiotConfig>
suspend fun getRiotConfig(): RiotConfig
/**
* Get the version information of the homeserver
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_ + "versions")
fun versions(): Call<Versions>
suspend fun versions(): Versions
/**
* Register to the homeserver, or get error 401 with a RegistrationFlowResponse object if registration is incomplete
* Ref: https://matrix.org/docs/spec/client_server/latest#account-registration-and-management
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "register")
fun register(@Body registrationParams: RegistrationParams): Call<Credentials>
suspend fun register(@Body registrationParams: RegistrationParams): Credentials
/**
* Add 3Pid during registration
@ -72,22 +71,22 @@ internal interface AuthAPI {
* https://github.com/matrix-org/matrix-doc/pull/2290
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "register/{threePid}/requestToken")
fun add3Pid(@Path("threePid") threePid: String,
@Body params: AddThreePidRegistrationParams): Call<AddThreePidRegistrationResponse>
suspend fun add3Pid(@Path("threePid") threePid: String,
@Body params: AddThreePidRegistrationParams): AddThreePidRegistrationResponse
/**
* Validate 3pid
*/
@POST
fun validate3Pid(@Url url: String,
@Body params: ValidationCodeBody): Call<SuccessResult>
suspend fun validate3Pid(@Url url: String,
@Body params: ValidationCodeBody): SuccessResult
/**
* Get the supported login flow
* Ref: https://matrix.org/docs/spec/client_server/latest#get-matrix-client-r0-login
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "login")
fun getLoginFlows(): Call<LoginFlowResponse>
suspend fun getLoginFlows(): LoginFlowResponse
/**
* Pass params to the server for the current login phase.
@ -97,22 +96,22 @@ internal interface AuthAPI {
*/
@Headers("CONNECT_TIMEOUT:60000", "READ_TIMEOUT:60000", "WRITE_TIMEOUT:60000")
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "login")
fun login(@Body loginParams: PasswordLoginParams): Call<Credentials>
suspend fun login(@Body loginParams: PasswordLoginParams): Credentials
// Unfortunately we cannot use interface for @Body parameter, so I duplicate the method for the type TokenLoginParams
@Headers("CONNECT_TIMEOUT:60000", "READ_TIMEOUT:60000", "WRITE_TIMEOUT:60000")
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "login")
fun login(@Body loginParams: TokenLoginParams): Call<Credentials>
suspend fun login(@Body loginParams: TokenLoginParams): Credentials
/**
* Ask the homeserver to reset the password associated with the provided email.
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "account/password/email/requestToken")
fun resetPassword(@Body params: AddThreePidRegistrationParams): Call<AddThreePidRegistrationResponse>
suspend fun resetPassword(@Body params: AddThreePidRegistrationParams): AddThreePidRegistrationResponse
/**
* Ask the homeserver to reset the password with the provided new password once the email is validated.
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "account/password")
fun resetPasswordMailConfirmed(@Body params: ResetPasswordMailConfirmed): Call<Unit>
suspend fun resetPasswordMailConfirmed(@Body params: ResetPasswordMailConfirmed)
}

View file

@ -31,7 +31,6 @@ import org.matrix.android.sdk.api.failure.Failure
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.util.appendParamToUrl
import org.matrix.android.sdk.internal.SessionManager
import org.matrix.android.sdk.internal.auth.data.LoginFlowResponse
import org.matrix.android.sdk.internal.auth.data.RiotConfig
import org.matrix.android.sdk.internal.auth.db.PendingSessionData
import org.matrix.android.sdk.internal.auth.login.DefaultLoginWizard
@ -172,8 +171,8 @@ internal class DefaultAuthenticationService @Inject constructor(
// First check the homeserver version
return runCatching {
executeRequest<Versions>(null) {
apiCall = authAPI.versions()
executeRequest(null) {
authAPI.versions()
}
}
.map { versions ->
@ -204,8 +203,8 @@ internal class DefaultAuthenticationService @Inject constructor(
// Ok, try to get the config.domain.json file of a RiotWeb client
return runCatching {
executeRequest<RiotConfig>(null) {
apiCall = authAPI.getRiotConfigDomain(domain)
executeRequest(null) {
authAPI.getRiotConfigDomain(domain)
}
}
.map { riotConfig ->
@ -232,8 +231,8 @@ internal class DefaultAuthenticationService @Inject constructor(
// Ok, try to get the config.json file of a RiotWeb client
return runCatching {
executeRequest<RiotConfig>(null) {
apiCall = authAPI.getRiotConfig()
executeRequest(null) {
authAPI.getRiotConfig()
}
}
.map { riotConfig ->
@ -265,8 +264,8 @@ internal class DefaultAuthenticationService @Inject constructor(
val newAuthAPI = buildAuthAPI(newHomeServerConnectionConfig)
val versions = executeRequest<Versions>(null) {
apiCall = newAuthAPI.versions()
val versions = executeRequest(null) {
newAuthAPI.versions()
}
return getLoginFlowResult(newAuthAPI, versions, defaultHomeServerUrl)
@ -293,8 +292,8 @@ internal class DefaultAuthenticationService @Inject constructor(
val newAuthAPI = buildAuthAPI(newHomeServerConnectionConfig)
val versions = executeRequest<Versions>(null) {
apiCall = newAuthAPI.versions()
val versions = executeRequest(null) {
newAuthAPI.versions()
}
getLoginFlowResult(newAuthAPI, versions, wellknownResult.homeServerUrl)
@ -305,8 +304,8 @@ internal class DefaultAuthenticationService @Inject constructor(
private suspend fun getLoginFlowResult(authAPI: AuthAPI, versions: Versions, homeServerUrl: String): LoginFlowResult {
// Get the login flow
val loginFlowResponse = executeRequest<LoginFlowResponse>(null) {
apiCall = authAPI.getLoginFlows()
val loginFlowResponse = executeRequest(null) {
authAPI.getLoginFlows()
}
return LoginFlowResult.Success(
loginFlowResponse.flows.orEmpty().mapNotNull { it.type },

View file

@ -20,7 +20,6 @@ import dagger.Lazy
import okhttp3.OkHttpClient
import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig
import org.matrix.android.sdk.api.failure.Failure
import org.matrix.android.sdk.internal.auth.data.LoginFlowResponse
import org.matrix.android.sdk.internal.di.Unauthenticated
import org.matrix.android.sdk.internal.network.RetrofitFactory
import org.matrix.android.sdk.internal.network.executeRequest
@ -49,8 +48,8 @@ internal class DefaultIsValidClientServerApiTask @Inject constructor(
.create(AuthAPI::class.java)
return try {
executeRequest<LoginFlowResponse>(null) {
apiCall = authAPI.getLoginFlows()
executeRequest(null) {
authAPI.getLoginFlows()
}
// We get a response, so the API is valid
true

View file

@ -17,7 +17,6 @@
package org.matrix.android.sdk.internal.auth.login
import android.util.Patterns
import org.matrix.android.sdk.api.auth.data.Credentials
import org.matrix.android.sdk.api.auth.login.LoginWizard
import org.matrix.android.sdk.api.auth.registration.RegisterThreePid
import org.matrix.android.sdk.api.session.Session
@ -29,7 +28,6 @@ import org.matrix.android.sdk.internal.auth.data.ThreePidMedium
import org.matrix.android.sdk.internal.auth.data.TokenLoginParams
import org.matrix.android.sdk.internal.auth.db.PendingSessionData
import org.matrix.android.sdk.internal.auth.registration.AddThreePidRegistrationParams
import org.matrix.android.sdk.internal.auth.registration.AddThreePidRegistrationResponse
import org.matrix.android.sdk.internal.auth.registration.RegisterAddThreePidTask
import org.matrix.android.sdk.internal.network.executeRequest
@ -49,8 +47,8 @@ internal class DefaultLoginWizard(
} else {
PasswordLoginParams.userIdentifier(login, password, deviceName)
}
val credentials = executeRequest<Credentials>(null) {
apiCall = authAPI.login(loginParams)
val credentials = executeRequest(null) {
authAPI.login(loginParams)
}
return sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig)
@ -63,8 +61,8 @@ internal class DefaultLoginWizard(
val loginParams = TokenLoginParams(
token = loginToken
)
val credentials = executeRequest<Credentials>(null) {
apiCall = authAPI.login(loginParams)
val credentials = executeRequest(null) {
authAPI.login(loginParams)
}
return sessionCreator.createSession(credentials, pendingSessionData.homeServerConnectionConfig)
@ -80,8 +78,8 @@ internal class DefaultLoginWizard(
pendingSessionData = pendingSessionData.copy(sendAttempt = pendingSessionData.sendAttempt + 1)
.also { pendingSessionStore.savePendingSessionData(it) }
val result = executeRequest<AddThreePidRegistrationResponse>(null) {
apiCall = authAPI.resetPassword(AddThreePidRegistrationParams.from(param))
val result = executeRequest(null) {
authAPI.resetPassword(AddThreePidRegistrationParams.from(param))
}
pendingSessionData = pendingSessionData.copy(resetPasswordData = ResetPasswordData(newPassword, result))
@ -98,8 +96,8 @@ internal class DefaultLoginWizard(
safeResetPasswordData.newPassword
)
executeRequest<Unit>(null) {
apiCall = authAPI.resetPasswordMailConfirmed(param)
executeRequest(null) {
authAPI.resetPasswordMailConfirmed(param)
}
// Set to null?

View file

@ -17,7 +17,6 @@
package org.matrix.android.sdk.internal.auth.login
import dagger.Lazy
import org.matrix.android.sdk.api.auth.data.Credentials
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
@ -59,19 +58,16 @@ internal class DefaultDirectLoginTask @Inject constructor(
val loginParams = PasswordLoginParams.userIdentifier(params.userId, params.password, params.deviceName)
val credentials = try {
executeRequest<Credentials>(null) {
apiCall = authAPI.login(loginParams)
executeRequest(null) {
authAPI.login(loginParams)
}
} catch (throwable: Throwable) {
when (throwable) {
is UnrecognizedCertificateException -> {
throw Failure.UnrecognizedCertificateFailure(
homeServerUrl,
throwable.fingerprint
)
}
else ->
throw throwable
throw when (throwable) {
is UnrecognizedCertificateException -> Failure.UnrecognizedCertificateFailure(
homeServerUrl,
throwable.fingerprint
)
else -> throwable
}
}

View file

@ -35,7 +35,7 @@ internal class DefaultRegisterAddThreePidTask(
override suspend fun execute(params: RegisterAddThreePidTask.Params): AddThreePidRegistrationResponse {
return executeRequest(null) {
apiCall = authAPI.add3Pid(params.threePid.toPath(), AddThreePidRegistrationParams.from(params))
authAPI.add3Pid(params.threePid.toPath(), AddThreePidRegistrationParams.from(params))
}
}

View file

@ -36,7 +36,7 @@ internal class DefaultRegisterTask(
override suspend fun execute(params: RegisterTask.Params): Credentials {
try {
return executeRequest(null) {
apiCall = authAPI.register(params.registrationParams)
authAPI.register(params.registrationParams)
}
} catch (throwable: Throwable) {
throw throwable.toRegistrationFlowResponse()

View file

@ -33,7 +33,7 @@ internal class DefaultValidateCodeTask(
override suspend fun execute(params: ValidateCodeTask.Params): SuccessResult {
return executeRequest(null) {
apiCall = authAPI.validate3Pid(params.url, params.body)
authAPI.validate3Pid(params.url, params.body)
}
}
}

View file

@ -30,7 +30,6 @@ import org.matrix.android.sdk.internal.crypto.model.rest.SignatureUploadResponse
import org.matrix.android.sdk.internal.crypto.model.rest.UpdateDeviceInfoBody
import org.matrix.android.sdk.internal.crypto.model.rest.UploadSigningKeysBody
import org.matrix.android.sdk.internal.network.NetworkConstants
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.HTTP
@ -46,14 +45,14 @@ internal interface CryptoApi {
* Doc: https://matrix.org/docs/spec/client_server/latest#get-matrix-client-r0-devices
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "devices")
fun getDevices(): Call<DevicesListResponse>
suspend fun getDevices(): DevicesListResponse
/**
* Get the device info by id
* Doc: https://matrix.org/docs/spec/client_server/latest#get-matrix-client-r0-devices-deviceid
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "devices/{deviceId}")
fun getDeviceInfo(@Path("deviceId") deviceId: String): Call<DeviceInfo>
suspend fun getDeviceInfo(@Path("deviceId") deviceId: String): DeviceInfo
/**
* Upload device and/or one-time keys.
@ -62,7 +61,7 @@ internal interface CryptoApi {
* @param body the keys to be sent.
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "keys/upload")
fun uploadKeys(@Body body: KeysUploadBody): Call<KeysUploadResponse>
suspend fun uploadKeys(@Body body: KeysUploadBody): KeysUploadResponse
/**
* Download device keys.
@ -71,7 +70,7 @@ internal interface CryptoApi {
* @param params the params.
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "keys/query")
fun downloadKeysForUsers(@Body params: KeysQueryBody): Call<KeysQueryResponse>
suspend fun downloadKeysForUsers(@Body params: KeysQueryBody): KeysQueryResponse
/**
* CrossSigning - Uploading signing keys
@ -79,7 +78,7 @@ internal interface CryptoApi {
* This endpoint requires UI Auth.
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "keys/device_signing/upload")
fun uploadSigningKeys(@Body params: UploadSigningKeysBody): Call<KeysQueryResponse>
suspend fun uploadSigningKeys(@Body params: UploadSigningKeysBody): KeysQueryResponse
/**
* CrossSigning - Uploading signatures
@ -98,7 +97,7 @@ internal interface CryptoApi {
* However, signatures made for other users' keys, made by her user-signing key, will not be included.
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "keys/signatures/upload")
fun uploadSignatures(@Body params: Map<String, @JvmSuppressWildcards Any>?): Call<SignatureUploadResponse>
suspend fun uploadSignatures(@Body params: Map<String, @JvmSuppressWildcards Any>?): SignatureUploadResponse
/**
* Claim one-time keys.
@ -107,7 +106,7 @@ internal interface CryptoApi {
* @param params the params.
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "keys/claim")
fun claimOneTimeKeysForUsersDevices(@Body body: KeysClaimBody): Call<KeysClaimResponse>
suspend fun claimOneTimeKeysForUsersDevices(@Body body: KeysClaimBody): KeysClaimResponse
/**
* Send an event to a specific list of devices
@ -118,9 +117,9 @@ internal interface CryptoApi {
* @param body the body
*/
@PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "sendToDevice/{eventType}/{txnId}")
fun sendToDevice(@Path("eventType") eventType: String,
@Path("txnId") transactionId: String,
@Body body: SendToDeviceBody): Call<Unit>
suspend fun sendToDevice(@Path("eventType") eventType: String,
@Path("txnId") transactionId: String,
@Body body: SendToDeviceBody)
/**
* Delete a device.
@ -130,8 +129,8 @@ internal interface CryptoApi {
* @param params the deletion parameters
*/
@HTTP(path = NetworkConstants.URI_API_PREFIX_PATH_R0 + "devices/{device_id}", method = "DELETE", hasBody = true)
fun deleteDevice(@Path("device_id") deviceId: String,
@Body params: DeleteDeviceParams): Call<Unit>
suspend fun deleteDevice(@Path("device_id") deviceId: String,
@Body params: DeleteDeviceParams)
/**
* Update the device information.
@ -141,8 +140,8 @@ internal interface CryptoApi {
* @param params the params
*/
@PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "devices/{device_id}")
fun updateDeviceInfo(@Path("device_id") deviceId: String,
@Body params: UpdateDeviceInfoBody): Call<Unit>
suspend fun updateDeviceInfo(@Path("device_id") deviceId: String,
@Body params: UpdateDeviceInfoBody)
/**
* Get the update devices list from two sync token.
@ -152,6 +151,6 @@ internal interface CryptoApi {
* @param newToken the up-to token.
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "keys/changes")
fun getKeyChanges(@Query("from") oldToken: String,
@Query("to") newToken: String): Call<KeyChangesResponse>
suspend fun getKeyChanges(@Query("from") oldToken: String,
@Query("to") newToken: String): KeyChangesResponse
}

View file

@ -25,7 +25,6 @@ import org.matrix.android.sdk.internal.crypto.keysbackup.model.rest.KeysVersionR
import org.matrix.android.sdk.internal.crypto.keysbackup.model.rest.RoomKeysBackupData
import org.matrix.android.sdk.internal.crypto.keysbackup.model.rest.UpdateKeysBackupVersionBody
import org.matrix.android.sdk.internal.network.NetworkConstants
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
@ -48,14 +47,14 @@ internal interface RoomKeysApi {
* @param createKeysBackupVersionBody the body
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/version")
fun createKeysBackupVersion(@Body createKeysBackupVersionBody: CreateKeysBackupVersionBody): Call<KeysVersion>
suspend fun createKeysBackupVersion(@Body createKeysBackupVersionBody: CreateKeysBackupVersionBody): KeysVersion
/**
* Get the key backup last version
* If not supported by the server, an error is returned: {"errcode":"M_NOT_FOUND","error":"No backup found"}
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/version")
fun getKeysBackupLastVersion(): Call<KeysVersionResult>
suspend fun getKeysBackupLastVersion(): KeysVersionResult
/**
* Get information about the given version.
@ -64,7 +63,7 @@ internal interface RoomKeysApi {
* @param version version
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/version/{version}")
fun getKeysBackupVersion(@Path("version") version: String): Call<KeysVersionResult>
suspend fun getKeysBackupVersion(@Path("version") version: String): KeysVersionResult
/**
* Update information about the given version.
@ -72,8 +71,8 @@ internal interface RoomKeysApi {
* @param updateKeysBackupVersionBody the body
*/
@PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/version/{version}")
fun updateKeysBackupVersion(@Path("version") version: String,
@Body keysBackupVersionBody: UpdateKeysBackupVersionBody): Call<Unit>
suspend fun updateKeysBackupVersion(@Path("version") version: String,
@Body keysBackupVersionBody: UpdateKeysBackupVersionBody)
/* ==========================================================================================
* Storing keys
@ -94,10 +93,10 @@ internal interface RoomKeysApi {
* @param keyBackupData the data to send
*/
@PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}/{sessionId}")
fun storeRoomSessionData(@Path("roomId") roomId: String,
@Path("sessionId") sessionId: String,
@Query("version") version: String,
@Body keyBackupData: KeyBackupData): Call<BackupKeysResult>
suspend fun storeRoomSessionData(@Path("roomId") roomId: String,
@Path("sessionId") sessionId: String,
@Query("version") version: String,
@Body keyBackupData: KeyBackupData): BackupKeysResult
/**
* Store several keys for the given room, using the given backup version.
@ -107,9 +106,9 @@ internal interface RoomKeysApi {
* @param roomKeysBackupData the data to send
*/
@PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}")
fun storeRoomSessionsData(@Path("roomId") roomId: String,
@Query("version") version: String,
@Body roomKeysBackupData: RoomKeysBackupData): Call<BackupKeysResult>
suspend fun storeRoomSessionsData(@Path("roomId") roomId: String,
@Query("version") version: String,
@Body roomKeysBackupData: RoomKeysBackupData): BackupKeysResult
/**
* Store several keys, using the given backup version.
@ -118,8 +117,8 @@ internal interface RoomKeysApi {
* @param keysBackupData the data to send
*/
@PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys")
fun storeSessionsData(@Query("version") version: String,
@Body keysBackupData: KeysBackupData): Call<BackupKeysResult>
suspend fun storeSessionsData(@Query("version") version: String,
@Body keysBackupData: KeysBackupData): BackupKeysResult
/* ==========================================================================================
* Retrieving keys
@ -133,9 +132,9 @@ internal interface RoomKeysApi {
* @param version the version of the backup, or empty String to retrieve the last version
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}/{sessionId}")
fun getRoomSessionData(@Path("roomId") roomId: String,
@Path("sessionId") sessionId: String,
@Query("version") version: String): Call<KeyBackupData>
suspend fun getRoomSessionData(@Path("roomId") roomId: String,
@Path("sessionId") sessionId: String,
@Query("version") version: String): KeyBackupData
/**
* Retrieve all the keys for the given room from the backup.
@ -144,8 +143,8 @@ internal interface RoomKeysApi {
* @param version the version of the backup, or empty String to retrieve the last version
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}")
fun getRoomSessionsData(@Path("roomId") roomId: String,
@Query("version") version: String): Call<RoomKeysBackupData>
suspend fun getRoomSessionsData(@Path("roomId") roomId: String,
@Query("version") version: String): RoomKeysBackupData
/**
* Retrieve all the keys from the backup.
@ -153,7 +152,7 @@ internal interface RoomKeysApi {
* @param version the version of the backup, or empty String to retrieve the last version
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys")
fun getSessionsData(@Query("version") version: String): Call<KeysBackupData>
suspend fun getSessionsData(@Query("version") version: String): KeysBackupData
/* ==========================================================================================
* Deleting keys
@ -163,22 +162,22 @@ internal interface RoomKeysApi {
* Deletes keys from the backup.
*/
@DELETE(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}/{sessionId}")
fun deleteRoomSessionData(@Path("roomId") roomId: String,
@Path("sessionId") sessionId: String,
@Query("version") version: String): Call<Unit>
suspend fun deleteRoomSessionData(@Path("roomId") roomId: String,
@Path("sessionId") sessionId: String,
@Query("version") version: String)
/**
* Deletes keys from the backup.
*/
@DELETE(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}")
fun deleteRoomSessionsData(@Path("roomId") roomId: String,
@Query("version") version: String): Call<Unit>
suspend fun deleteRoomSessionsData(@Path("roomId") roomId: String,
@Query("version") version: String)
/**
* Deletes keys from the backup.
*/
@DELETE(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys")
fun deleteSessionsData(@Query("version") version: String): Call<Unit>
suspend fun deleteSessionsData(@Query("version") version: String)
/* ==========================================================================================
* Deleting backup
@ -188,5 +187,5 @@ internal interface RoomKeysApi {
* Deletes a backup.
*/
@DELETE(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/version/{version}")
fun deleteBackup(@Path("version") version: String): Call<Unit>
suspend fun deleteBackup(@Path("version") version: String)
}

View file

@ -33,7 +33,7 @@ internal class DefaultCreateKeysBackupVersionTask @Inject constructor(
override suspend fun execute(params: CreateKeysBackupVersionBody): KeysVersion {
return executeRequest(globalErrorReceiver) {
apiCall = roomKeysApi.createKeysBackupVersion(params)
roomKeysApi.createKeysBackupVersion(params)
}
}
}

View file

@ -35,7 +35,7 @@ internal class DefaultDeleteBackupTask @Inject constructor(
override suspend fun execute(params: DeleteBackupTask.Params) {
return executeRequest(globalErrorReceiver) {
apiCall = roomKeysApi.deleteBackup(params.version)
roomKeysApi.deleteBackup(params.version)
}
}
}

View file

@ -37,7 +37,7 @@ internal class DefaultDeleteRoomSessionDataTask @Inject constructor(
override suspend fun execute(params: DeleteRoomSessionDataTask.Params) {
return executeRequest(globalErrorReceiver) {
apiCall = roomKeysApi.deleteRoomSessionData(
roomKeysApi.deleteRoomSessionData(
params.roomId,
params.sessionId,
params.version)

View file

@ -36,7 +36,7 @@ internal class DefaultDeleteRoomSessionsDataTask @Inject constructor(
override suspend fun execute(params: DeleteRoomSessionsDataTask.Params) {
return executeRequest(globalErrorReceiver) {
apiCall = roomKeysApi.deleteRoomSessionsData(
roomKeysApi.deleteRoomSessionsData(
params.roomId,
params.version)
}

View file

@ -35,7 +35,7 @@ internal class DefaultDeleteSessionsDataTask @Inject constructor(
override suspend fun execute(params: DeleteSessionsDataTask.Params) {
return executeRequest(globalErrorReceiver) {
apiCall = roomKeysApi.deleteSessionsData(params.version)
roomKeysApi.deleteSessionsData(params.version)
}
}
}

View file

@ -32,7 +32,7 @@ internal class DefaultGetKeysBackupLastVersionTask @Inject constructor(
override suspend fun execute(params: Unit): KeysVersionResult {
return executeRequest(globalErrorReceiver) {
apiCall = roomKeysApi.getKeysBackupLastVersion()
roomKeysApi.getKeysBackupLastVersion()
}
}
}

View file

@ -32,7 +32,7 @@ internal class DefaultGetKeysBackupVersionTask @Inject constructor(
override suspend fun execute(params: String): KeysVersionResult {
return executeRequest(globalErrorReceiver) {
apiCall = roomKeysApi.getKeysBackupVersion(params)
roomKeysApi.getKeysBackupVersion(params)
}
}
}

View file

@ -38,7 +38,7 @@ internal class DefaultGetRoomSessionDataTask @Inject constructor(
override suspend fun execute(params: GetRoomSessionDataTask.Params): KeyBackupData {
return executeRequest(globalErrorReceiver) {
apiCall = roomKeysApi.getRoomSessionData(
roomKeysApi.getRoomSessionData(
params.roomId,
params.sessionId,
params.version)

View file

@ -37,7 +37,7 @@ internal class DefaultGetRoomSessionsDataTask @Inject constructor(
override suspend fun execute(params: GetRoomSessionsDataTask.Params): RoomKeysBackupData {
return executeRequest(globalErrorReceiver) {
apiCall = roomKeysApi.getRoomSessionsData(
roomKeysApi.getRoomSessionsData(
params.roomId,
params.version)
}

View file

@ -36,7 +36,7 @@ internal class DefaultGetSessionsDataTask @Inject constructor(
override suspend fun execute(params: GetSessionsDataTask.Params): KeysBackupData {
return executeRequest(globalErrorReceiver) {
apiCall = roomKeysApi.getSessionsData(params.version)
roomKeysApi.getSessionsData(params.version)
}
}
}

View file

@ -40,7 +40,7 @@ internal class DefaultStoreRoomSessionDataTask @Inject constructor(
override suspend fun execute(params: StoreRoomSessionDataTask.Params): BackupKeysResult {
return executeRequest(globalErrorReceiver) {
apiCall = roomKeysApi.storeRoomSessionData(
roomKeysApi.storeRoomSessionData(
params.roomId,
params.sessionId,
params.version,

View file

@ -39,7 +39,7 @@ internal class DefaultStoreRoomSessionsDataTask @Inject constructor(
override suspend fun execute(params: StoreRoomSessionsDataTask.Params): BackupKeysResult {
return executeRequest(globalErrorReceiver) {
apiCall = roomKeysApi.storeRoomSessionsData(
roomKeysApi.storeRoomSessionsData(
params.roomId,
params.version,
params.roomKeysBackupData)

View file

@ -38,7 +38,7 @@ internal class DefaultStoreSessionsDataTask @Inject constructor(
override suspend fun execute(params: StoreSessionsDataTask.Params): BackupKeysResult {
return executeRequest(globalErrorReceiver) {
apiCall = roomKeysApi.storeSessionsData(
roomKeysApi.storeSessionsData(
params.version,
params.keysBackupData)
}

View file

@ -37,7 +37,7 @@ internal class DefaultUpdateKeysBackupVersionTask @Inject constructor(
override suspend fun execute(params: UpdateKeysBackupVersionTask.Params) {
return executeRequest(globalErrorReceiver) {
apiCall = roomKeysApi.updateKeysBackupVersion(params.version, params.keysBackupVersionBody)
roomKeysApi.updateKeysBackupVersion(params.version, params.keysBackupVersionBody)
}
}
}

View file

@ -20,7 +20,6 @@ import org.matrix.android.sdk.internal.crypto.api.CryptoApi
import org.matrix.android.sdk.internal.crypto.model.MXKey
import org.matrix.android.sdk.internal.crypto.model.MXUsersDevicesMap
import org.matrix.android.sdk.internal.crypto.model.rest.KeysClaimBody
import org.matrix.android.sdk.internal.crypto.model.rest.KeysClaimResponse
import org.matrix.android.sdk.internal.network.GlobalErrorReceiver
import org.matrix.android.sdk.internal.network.executeRequest
import org.matrix.android.sdk.internal.task.Task
@ -42,8 +41,8 @@ internal class DefaultClaimOneTimeKeysForUsersDevice @Inject constructor(
override suspend fun execute(params: ClaimOneTimeKeysForUsersDeviceTask.Params): MXUsersDevicesMap<MXKey> {
val body = KeysClaimBody(oneTimeKeys = params.usersDevicesKeyTypesMap.map)
val keysClaimResponse = executeRequest<KeysClaimResponse>(globalErrorReceiver) {
apiCall = cryptoApi.claimOneTimeKeysForUsersDevices(body)
val keysClaimResponse = executeRequest(globalErrorReceiver) {
cryptoApi.claimOneTimeKeysForUsersDevices(body)
}
val map = MXUsersDevicesMap<MXKey>()
keysClaimResponse.oneTimeKeys?.let { oneTimeKeys ->

View file

@ -42,8 +42,8 @@ internal class DefaultDeleteDeviceTask @Inject constructor(
override suspend fun execute(params: DeleteDeviceTask.Params) {
try {
executeRequest<Unit>(globalErrorReceiver) {
apiCall = cryptoApi.deleteDevice(params.deviceId, DeleteDeviceParams(params.userAuthParam?.asMap()))
executeRequest(globalErrorReceiver) {
cryptoApi.deleteDevice(params.deviceId, DeleteDeviceParams(params.userAuthParam?.asMap()))
}
} catch (throwable: Throwable) {
if (params.userInteractiveAuthInterceptor == null

View file

@ -72,8 +72,8 @@ internal class DefaultDownloadKeysForUsers @Inject constructor(
}
.map { body ->
async {
val result = executeRequest<KeysQueryResponse>(globalErrorReceiver) {
apiCall = cryptoApi.downloadKeysForUsers(body)
val result = executeRequest(globalErrorReceiver) {
cryptoApi.downloadKeysForUsers(body)
}
mutex.withLock {
@ -98,7 +98,7 @@ internal class DefaultDownloadKeysForUsers @Inject constructor(
} else {
// No need to chunk, direct request
executeRequest(globalErrorReceiver) {
apiCall = cryptoApi.downloadKeysForUsers(
cryptoApi.downloadKeysForUsers(
KeysQueryBody(
deviceKeys = params.userIds.associateWith { emptyList() },
token = token

View file

@ -34,7 +34,7 @@ internal class DefaultGetDeviceInfoTask @Inject constructor(
override suspend fun execute(params: GetDeviceInfoTask.Params): DeviceInfo {
return executeRequest(globalErrorReceiver) {
apiCall = cryptoApi.getDeviceInfo(params.deviceId)
cryptoApi.getDeviceInfo(params.deviceId)
}
}
}

View file

@ -32,7 +32,7 @@ internal class DefaultGetDevicesTask @Inject constructor(
override suspend fun execute(params: Unit): DevicesListResponse {
return executeRequest(globalErrorReceiver) {
apiCall = cryptoApi.getDevices()
cryptoApi.getDevices()
}
}
}

View file

@ -39,7 +39,7 @@ internal class DefaultGetKeyChangesTask @Inject constructor(
override suspend fun execute(params: GetKeyChangesTask.Params): KeyChangesResponse {
return executeRequest(globalErrorReceiver) {
apiCall = cryptoApi.getKeyChanges(params.from, params.to)
cryptoApi.getKeyChanges(params.from, params.to)
}
}
}

View file

@ -18,7 +18,6 @@ package org.matrix.android.sdk.internal.crypto.tasks
import org.matrix.android.sdk.internal.network.GlobalErrorReceiver
import org.matrix.android.sdk.internal.network.executeRequest
import org.matrix.android.sdk.internal.session.room.RoomAPI
import org.matrix.android.sdk.internal.session.room.send.SendResponse
import org.matrix.android.sdk.internal.task.Task
import javax.inject.Inject
@ -36,14 +35,14 @@ internal class DefaultRedactEventTask @Inject constructor(
private val globalErrorReceiver: GlobalErrorReceiver) : RedactEventTask {
override suspend fun execute(params: RedactEventTask.Params): String {
val executeRequest = executeRequest<SendResponse>(globalErrorReceiver) {
apiCall = roomAPI.redactEvent(
val response = executeRequest(globalErrorReceiver) {
roomAPI.redactEvent(
txId = params.txID,
roomId = params.roomId,
eventId = params.eventId,
reason = if (params.reason == null) emptyMap() else mapOf("reason" to params.reason)
)
}
return executeRequest.eventId
return response.eventId
}
}

View file

@ -22,7 +22,6 @@ import org.matrix.android.sdk.internal.network.executeRequest
import org.matrix.android.sdk.internal.session.room.RoomAPI
import org.matrix.android.sdk.internal.session.room.membership.LoadRoomMembersTask
import org.matrix.android.sdk.internal.session.room.send.LocalEchoRepository
import org.matrix.android.sdk.internal.session.room.send.SendResponse
import org.matrix.android.sdk.internal.task.Task
import javax.inject.Inject
@ -52,8 +51,8 @@ internal class DefaultSendEventTask @Inject constructor(
val event = handleEncryption(params)
val localId = event.eventId!!
localEchoRepository.updateSendState(localId, params.event.roomId, SendState.SENDING)
val executeRequest = executeRequest<SendResponse>(globalErrorReceiver) {
apiCall = roomAPI.send(
val response = executeRequest(globalErrorReceiver) {
roomAPI.send(
localId,
roomId = event.roomId ?: "",
content = event.content,
@ -61,7 +60,7 @@ internal class DefaultSendEventTask @Inject constructor(
)
}
localEchoRepository.updateSendState(localId, params.event.roomId, SendState.SENT)
return executeRequest.eventId
return response.eventId
} catch (e: Throwable) {
// localEchoRepository.updateSendState(params.event.eventId!!, SendState.UNDELIVERED)
throw e

View file

@ -46,14 +46,16 @@ internal class DefaultSendToDeviceTask @Inject constructor(
messages = params.contentMap.map
)
return executeRequest(globalErrorReceiver) {
apiCall = cryptoApi.sendToDevice(
return executeRequest(
globalErrorReceiver,
canRetry = true,
maxRetriesCount = 3
) {
cryptoApi.sendToDevice(
params.eventType,
params.transactionId ?: Random.nextInt(Integer.MAX_VALUE).toString(),
sendToDeviceBody
)
isRetryable = true
maxRetryCount = 3
}
}
}

View file

@ -22,7 +22,6 @@ import org.matrix.android.sdk.internal.network.GlobalErrorReceiver
import org.matrix.android.sdk.internal.network.executeRequest
import org.matrix.android.sdk.internal.session.room.RoomAPI
import org.matrix.android.sdk.internal.session.room.send.LocalEchoRepository
import org.matrix.android.sdk.internal.session.room.send.SendResponse
import org.matrix.android.sdk.internal.task.Task
import javax.inject.Inject
@ -45,8 +44,8 @@ internal class DefaultSendVerificationMessageTask @Inject constructor(
try {
localEchoRepository.updateSendState(localId, event.roomId, SendState.SENDING)
val executeRequest = executeRequest<SendResponse>(globalErrorReceiver) {
apiCall = roomAPI.send(
val response = executeRequest(globalErrorReceiver) {
roomAPI.send(
localId,
roomId = event.roomId ?: "",
content = event.content,
@ -54,7 +53,7 @@ internal class DefaultSendVerificationMessageTask @Inject constructor(
)
}
localEchoRepository.updateSendState(localId, event.roomId, SendState.SENT)
return executeRequest.eventId
return response.eventId
} catch (e: Throwable) {
localEchoRepository.updateSendState(localId, event.roomId, SendState.UNDELIVERED)
throw e

View file

@ -42,7 +42,7 @@ internal class DefaultSetDeviceNameTask @Inject constructor(
displayName = params.deviceName
)
return executeRequest(globalErrorReceiver) {
apiCall = cryptoApi.updateDeviceInfo(params.deviceId, body)
cryptoApi.updateDeviceInfo(params.deviceId, body)
}
}
}

View file

@ -50,7 +50,7 @@ internal class DefaultUploadKeysTask @Inject constructor(
Timber.i("## Uploading device keys -> $body")
return executeRequest(globalErrorReceiver) {
apiCall = cryptoApi.uploadKeys(body)
cryptoApi.uploadKeys(body)
}
}
}

View file

@ -17,7 +17,6 @@ package org.matrix.android.sdk.internal.crypto.tasks
import org.matrix.android.sdk.api.failure.Failure
import org.matrix.android.sdk.internal.crypto.api.CryptoApi
import org.matrix.android.sdk.internal.crypto.model.rest.SignatureUploadResponse
import org.matrix.android.sdk.internal.network.GlobalErrorReceiver
import org.matrix.android.sdk.internal.network.executeRequest
import org.matrix.android.sdk.internal.task.Task
@ -36,10 +35,12 @@ internal class DefaultUploadSignaturesTask @Inject constructor(
override suspend fun execute(params: UploadSignaturesTask.Params) {
try {
val response = executeRequest<SignatureUploadResponse>(globalErrorReceiver) {
this.isRetryable = true
this.maxRetryCount = 10
this.apiCall = cryptoApi.uploadSignatures(params.signatures)
val response = executeRequest(
globalErrorReceiver,
canRetry = true,
maxRetriesCount = 10
) {
cryptoApi.uploadSignatures(params.signatures)
}
if (response.failures?.isNotEmpty() == true) {
throw Throwable(response.failures.toString())

View file

@ -19,7 +19,6 @@ package org.matrix.android.sdk.internal.crypto.tasks
import org.matrix.android.sdk.api.failure.Failure
import org.matrix.android.sdk.internal.crypto.api.CryptoApi
import org.matrix.android.sdk.internal.crypto.model.CryptoCrossSigningKey
import org.matrix.android.sdk.internal.crypto.model.rest.KeysQueryResponse
import org.matrix.android.sdk.api.auth.UIABaseAuth
import org.matrix.android.sdk.internal.crypto.model.rest.UploadSigningKeysBody
import org.matrix.android.sdk.internal.crypto.model.toRest
@ -61,8 +60,8 @@ internal class DefaultUploadSigningKeysTask @Inject constructor(
}
private suspend fun doRequest(uploadQuery: UploadSigningKeysBody) {
val keysQueryResponse = executeRequest<KeysQueryResponse>(globalErrorReceiver) {
apiCall = cryptoApi.uploadSigningKeys(uploadQuery)
val keysQueryResponse = executeRequest(globalErrorReceiver) {
cryptoApi.uploadSigningKeys(uploadQuery)
}
if (keysQueryResponse.failures?.isNotEmpty() == true) {
throw UploadSigningKeys(keysQueryResponse.failures)

View file

@ -17,22 +17,27 @@
package org.matrix.android.sdk.internal.database
import io.realm.DynamicRealm
import io.realm.FieldAttribute
import io.realm.RealmMigration
import org.matrix.android.sdk.api.session.room.model.tag.RoomTag
import org.matrix.android.sdk.internal.database.model.EditAggregatedSummaryEntityFields
import org.matrix.android.sdk.internal.database.model.EditionOfEventFields
import org.matrix.android.sdk.internal.database.model.EventEntityFields
import org.matrix.android.sdk.internal.database.model.HomeServerCapabilitiesEntityFields
import org.matrix.android.sdk.internal.database.model.PendingThreePidEntityFields
import org.matrix.android.sdk.internal.database.model.PreviewUrlCacheEntityFields
import org.matrix.android.sdk.internal.database.model.RoomEntityFields
import org.matrix.android.sdk.internal.database.model.RoomMembersLoadStatusType
import org.matrix.android.sdk.internal.database.model.RoomSummaryEntityFields
import org.matrix.android.sdk.internal.database.model.RoomTagEntityFields
import org.matrix.android.sdk.internal.database.model.TimelineEventEntityFields
import timber.log.Timber
import javax.inject.Inject
class RealmSessionStoreMigration @Inject constructor() : RealmMigration {
companion object {
const val SESSION_STORE_SCHEMA_VERSION = 8L
const val SESSION_STORE_SCHEMA_VERSION = 9L
}
override fun migrate(realm: DynamicRealm, oldVersion: Long, newVersion: Long) {
@ -46,6 +51,7 @@ class RealmSessionStoreMigration @Inject constructor() : RealmMigration {
if (oldVersion <= 5) migrateTo6(realm)
if (oldVersion <= 6) migrateTo7(realm)
if (oldVersion <= 7) migrateTo8(realm)
if (oldVersion <= 8) migrateTo9(realm)
}
private fun migrateTo1(realm: DynamicRealm) {
@ -149,4 +155,43 @@ class RealmSessionStoreMigration @Inject constructor() : RealmMigration {
?.removeField("sourceLocalEchoEvents")
?.addRealmListField(EditAggregatedSummaryEntityFields.EDITIONS.`$`, editionOfEventSchema)
}
fun migrateTo9(realm: DynamicRealm) {
Timber.d("Step 8 -> 9")
realm.schema.get("RoomSummaryEntity")
?.addField(RoomSummaryEntityFields.LAST_ACTIVITY_TIME, Long::class.java, FieldAttribute.INDEXED)
?.setNullable(RoomSummaryEntityFields.LAST_ACTIVITY_TIME, true)
?.addIndex(RoomSummaryEntityFields.MEMBERSHIP_STR)
?.addIndex(RoomSummaryEntityFields.IS_DIRECT)
?.addIndex(RoomSummaryEntityFields.VERSIONING_STATE_STR)
?.addField(RoomSummaryEntityFields.IS_FAVOURITE, Boolean::class.java)
?.addIndex(RoomSummaryEntityFields.IS_FAVOURITE)
?.addField(RoomSummaryEntityFields.IS_LOW_PRIORITY, Boolean::class.java)
?.addIndex(RoomSummaryEntityFields.IS_LOW_PRIORITY)
?.addField(RoomSummaryEntityFields.IS_SERVER_NOTICE, Boolean::class.java)
?.addIndex(RoomSummaryEntityFields.IS_SERVER_NOTICE)
?.transform { obj ->
val isFavorite = obj.getList(RoomSummaryEntityFields.TAGS.`$`).any {
it.getString(RoomTagEntityFields.TAG_NAME) == RoomTag.ROOM_TAG_FAVOURITE
}
obj.setBoolean(RoomSummaryEntityFields.IS_FAVOURITE, isFavorite)
val isLowPriority = obj.getList(RoomSummaryEntityFields.TAGS.`$`).any {
it.getString(RoomTagEntityFields.TAG_NAME) == RoomTag.ROOM_TAG_LOW_PRIORITY
}
obj.setBoolean(RoomSummaryEntityFields.IS_LOW_PRIORITY, isLowPriority)
// XXX migrate last message origin server ts
obj.getObject(RoomSummaryEntityFields.LATEST_PREVIEWABLE_EVENT.`$`)
?.getObject(TimelineEventEntityFields.ROOT.`$`)
?.getLong(EventEntityFields.ORIGIN_SERVER_TS)?.let {
obj.setLong(RoomSummaryEntityFields.LAST_ACTIVITY_TIME, it)
}
}
}
}

View file

@ -26,7 +26,7 @@ internal class RoomSummaryMapper @Inject constructor(private val timelineEventMa
private val typingUsersTracker: DefaultTypingUsersTracker) {
fun map(roomSummaryEntity: RoomSummaryEntity): RoomSummary {
val tags = roomSummaryEntity.tags.map {
val tags = roomSummaryEntity.tags().map {
RoomTag(it.tagName, it.tagOrder)
}

View file

@ -16,61 +16,217 @@
package org.matrix.android.sdk.internal.database.model
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.Index
import io.realm.annotations.PrimaryKey
import org.matrix.android.sdk.api.crypto.RoomEncryptionTrustLevel
import org.matrix.android.sdk.api.session.room.model.Membership
import org.matrix.android.sdk.api.session.room.model.RoomSummary
import org.matrix.android.sdk.api.session.room.model.VersioningState
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import org.matrix.android.sdk.api.session.room.model.tag.RoomTag
internal open class RoomSummaryEntity(
@PrimaryKey var roomId: String = "",
var displayName: String? = "",
var avatarUrl: String? = "",
var name: String? = "",
var topic: String? = "",
var latestPreviewableEvent: TimelineEventEntity? = null,
var heroes: RealmList<String> = RealmList(),
var joinedMembersCount: Int? = 0,
var invitedMembersCount: Int? = 0,
var isDirect: Boolean = false,
var directUserId: String? = null,
var otherMemberIds: RealmList<String> = RealmList(),
var notificationCount: Int = 0,
var highlightCount: Int = 0,
var readMarkerId: String? = null,
var hasUnreadMessages: Boolean = false,
var tags: RealmList<RoomTagEntity> = RealmList(),
var userDrafts: UserDraftsEntity? = null,
var breadcrumbsIndex: Int = RoomSummary.NOT_IN_BREADCRUMBS,
var canonicalAlias: String? = null,
var aliases: RealmList<String> = RealmList(),
// this is required for querying
var flatAliases: String = "",
var isEncrypted: Boolean = false,
var encryptionEventTs: Long? = 0,
var roomEncryptionTrustLevelStr: String? = null,
var inviterId: String? = null,
var hasFailedSending: Boolean = false
@PrimaryKey var roomId: String = ""
) : RealmObject() {
var displayName: String? = ""
set(value) {
if (value != field) field = value
}
var avatarUrl: String? = ""
set(value) {
if (value != field) field = value
}
var name: String? = ""
set(value) {
if (value != field) field = value
}
var topic: String? = ""
set(value) {
if (value != field) field = value
}
var latestPreviewableEvent: TimelineEventEntity? = null
set(value) {
if (value != field) field = value
}
@Index
var lastActivityTime: Long? = null
set(value) {
if (value != field) field = value
}
var heroes: RealmList<String> = RealmList()
var joinedMembersCount: Int? = 0
set(value) {
if (value != field) field = value
}
var invitedMembersCount: Int? = 0
set(value) {
if (value != field) field = value
}
@Index
var isDirect: Boolean = false
set(value) {
if (value != field) field = value
}
var directUserId: String? = null
set(value) {
if (value != field) field = value
}
var otherMemberIds: RealmList<String> = RealmList()
var notificationCount: Int = 0
set(value) {
if (value != field) field = value
}
var highlightCount: Int = 0
set(value) {
if (value != field) field = value
}
var readMarkerId: String? = null
set(value) {
if (value != field) field = value
}
var hasUnreadMessages: Boolean = false
set(value) {
if (value != field) field = value
}
private var tags: RealmList<RoomTagEntity> = RealmList()
fun tags(): List<RoomTagEntity> = tags
fun updateTags(newTags: List<Pair<String, Double?>>) {
val toDelete = mutableListOf<RoomTagEntity>()
tags.forEach { existingTag ->
val updatedTag = newTags.firstOrNull { it.first == existingTag.tagName }
if (updatedTag == null) {
toDelete.add(existingTag)
} else {
existingTag.tagOrder = updatedTag.second
}
}
toDelete.forEach { it.deleteFromRealm() }
newTags.forEach { newTag ->
if (tags.all { it.tagName != newTag.first }) {
// we must add it
tags.add(
RoomTagEntity(newTag.first, newTag.second)
)
}
}
isFavourite = newTags.any { it.first == RoomTag.ROOM_TAG_FAVOURITE }
isLowPriority = newTags.any { it.first == RoomTag.ROOM_TAG_LOW_PRIORITY }
isServerNotice = newTags.any { it.first == RoomTag.ROOM_TAG_SERVER_NOTICE }
}
@Index
var isFavourite: Boolean = false
set(value) {
if (value != field) field = value
}
@Index
var isLowPriority: Boolean = false
set(value) {
if (value != field) field = value
}
@Index
var isServerNotice: Boolean = false
set(value) {
if (value != field) field = value
}
var userDrafts: UserDraftsEntity? = null
set(value) {
if (value != field) field = value
}
var breadcrumbsIndex: Int = RoomSummary.NOT_IN_BREADCRUMBS
set(value) {
if (value != field) field = value
}
var canonicalAlias: String? = null
set(value) {
if (value != field) field = value
}
var aliases: RealmList<String> = RealmList()
fun updateAliases(newAliases: List<String>) {
// only update underlying field if there is a diff
if (newAliases.distinct().sorted() != aliases.distinct().sorted()) {
aliases.clear()
aliases.addAll(newAliases)
flatAliases = newAliases.joinToString(separator = "|", prefix = "|")
}
}
// this is required for querying
var flatAliases: String = ""
var isEncrypted: Boolean = false
set(value) {
if (value != field) field = value
}
var encryptionEventTs: Long? = 0
set(value) {
if (value != field) field = value
}
var roomEncryptionTrustLevelStr: String? = null
set(value) {
if (value != field) field = value
}
var inviterId: String? = null
set(value) {
if (value != field) field = value
}
var hasFailedSending: Boolean = false
set(value) {
if (value != field) field = value
}
@Index
private var membershipStr: String = Membership.NONE.name
var membership: Membership
get() {
return Membership.valueOf(membershipStr)
}
set(value) {
membershipStr = value.name
if (value.name != membershipStr) {
membershipStr = value.name
}
}
@Index
private var versioningStateStr: String = VersioningState.NONE.name
var versioningState: VersioningState
get() {
return VersioningState.valueOf(versioningStateStr)
}
set(value) {
versioningStateStr = value.name
if (value.name != versioningStateStr) {
versioningStateStr = value.name
}
}
var roomEncryptionTrustLevel: RoomEncryptionTrustLevel?
@ -84,7 +240,9 @@ internal open class RoomSummaryEntity(
}
}
set(value) {
roomEncryptionTrustLevelStr = value?.name
if (value?.name != roomEncryptionTrustLevelStr) {
roomEncryptionTrustLevelStr = value?.name
}
}
companion object

View file

@ -18,10 +18,9 @@
package org.matrix.android.sdk.internal.federation
import org.matrix.android.sdk.internal.network.NetworkConstants
import retrofit2.Call
import retrofit2.http.GET
internal interface FederationAPI {
@GET(NetworkConstants.URI_FEDERATION_PATH + "version")
fun getVersion(): Call<FederationGetVersionResult>
suspend fun getVersion(): FederationGetVersionResult
}

View file

@ -28,8 +28,8 @@ internal class DefaultGetFederationVersionTask @Inject constructor(
) : GetFederationVersionTask {
override suspend fun execute(params: Unit): FederationVersion {
val result = executeRequest<FederationGetVersionResult>(null) {
apiCall = federationAPI.getVersion()
val result = executeRequest(null) {
federationAPI.getVersion()
}
return FederationVersion(

View file

@ -19,38 +19,45 @@ package org.matrix.android.sdk.internal.network
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import org.matrix.android.sdk.api.failure.Failure
import org.matrix.android.sdk.api.failure.getRetryDelay
import org.matrix.android.sdk.api.failure.shouldBeRetried
import org.matrix.android.sdk.internal.network.ssl.CertUtil
import retrofit2.Call
import retrofit2.awaitResponse
import retrofit2.HttpException
import timber.log.Timber
import java.io.IOException
internal suspend inline fun <DATA : Any> executeRequest(globalErrorReceiver: GlobalErrorReceiver?,
block: Request<DATA>.() -> Unit) = Request<DATA>(globalErrorReceiver).apply(block).execute()
/**
* Execute a request from the requestBlock and handle some of the Exception it could generate
*
* @param globalErrorReceiver will be use to notify error such as invalid token error. See [GlobalError]
* @param canRetry if set to true, the request will be executed again in case of error, after a delay
* @param initialDelayBeforeRetry the first delay to wait before a request is retried. Will be doubled after each retry
* @param maxDelayBeforeRetry the max delay to wait before a retry
* @param maxRetriesCount the max number of retries
* @param requestBlock a suspend lambda to perform the network request
*/
internal suspend inline fun <DATA> executeRequest(globalErrorReceiver: GlobalErrorReceiver?,
canRetry: Boolean = false,
initialDelayBeforeRetry: Long = 100L,
maxDelayBeforeRetry: Long = 10_000L,
maxRetriesCount: Int = Int.MAX_VALUE,
noinline requestBlock: suspend () -> DATA): DATA {
var currentRetryCount = 0
var currentDelay = initialDelayBeforeRetry
internal class Request<DATA : Any>(private val globalErrorReceiver: GlobalErrorReceiver?) {
var isRetryable = false
var initialDelay: Long = 100L
var maxDelay: Long = 10_000L
var maxRetryCount = Int.MAX_VALUE
private var currentRetryCount = 0
private var currentDelay = initialDelay
lateinit var apiCall: Call<DATA>
suspend fun execute(): DATA {
return try {
val response = apiCall.clone().awaitResponse()
if (response.isSuccessful) {
response.body()
?: throw IllegalStateException("The request returned a null body")
} else {
throw response.toFailure(globalErrorReceiver)
while (true) {
try {
return requestBlock()
} catch (throwable: Throwable) {
val exception = when (throwable) {
is KotlinNullPointerException -> IllegalStateException("The request returned a null body")
is HttpException -> throwable.toFailure(globalErrorReceiver)
else -> throwable
}
} catch (exception: Throwable) {
// Log some details about the request which has failed
Timber.e("Exception when executing request ${apiCall.request().method} ${apiCall.request().url.toString().substringBefore("?")}")
// Log some details about the request which has failed. This is less useful than before...
// Timber.e("Exception when executing request ${apiCall.request().method} ${apiCall.request().url.toString().substringBefore("?")}")
Timber.e("Exception when executing request")
// Check if this is a certificateException
CertUtil.getCertificateException(exception)
@ -61,10 +68,11 @@ internal class Request<DATA : Any>(private val globalErrorReceiver: GlobalErrorR
// }
?.also { unrecognizedCertificateException -> throw unrecognizedCertificateException }
if (isRetryable && currentRetryCount++ < maxRetryCount && exception.shouldBeRetried()) {
delay(currentDelay)
currentDelay = (currentDelay * 2L).coerceAtMost(maxDelay)
return execute()
if (canRetry && currentRetryCount++ < maxRetriesCount && exception.shouldBeRetried()) {
// In case of 429, ensure we wait enough
delay(currentDelay.coerceAtLeast(exception.getRetryDelay(0)))
currentDelay = currentDelay.times(2L).coerceAtMost(maxDelayBeforeRetry)
// Try again (loop)
} else {
throw when (exception) {
is IOException -> Failure.NetworkConnection(exception)

View file

@ -25,6 +25,7 @@ import org.matrix.android.sdk.api.failure.MatrixError
import org.matrix.android.sdk.internal.di.MoshiProvider
import kotlinx.coroutines.suspendCancellableCoroutine
import okhttp3.ResponseBody
import retrofit2.HttpException
import retrofit2.Response
import timber.log.Timber
import java.io.IOException
@ -57,6 +58,13 @@ internal fun <T> Response<T>.toFailure(globalErrorReceiver: GlobalErrorReceiver?
return toFailure(errorBody(), code(), globalErrorReceiver)
}
/**
* Convert a HttpException to a Failure, and eventually parse errorBody to convert it to a MatrixError
*/
internal fun HttpException.toFailure(globalErrorReceiver: GlobalErrorReceiver?): Failure {
return toFailure(response()?.errorBody(), code(), globalErrorReceiver)
}
/**
* Convert a okhttp3 Response to a Failure, and eventually parse errorBody to convert it to a MatrixError
*/

View file

@ -17,7 +17,6 @@
package org.matrix.android.sdk.internal.raw
import com.zhuinden.monarchy.Monarchy
import okhttp3.ResponseBody
import org.matrix.android.sdk.api.cache.CacheStrategy
import org.matrix.android.sdk.internal.database.model.RawCacheEntity
import org.matrix.android.sdk.internal.database.query.get
@ -58,8 +57,8 @@ internal class DefaultGetUrlTask @Inject constructor(
}
private suspend fun doRequest(url: String): String {
return executeRequest<ResponseBody>(null) {
apiCall = rawAPI.getUrl(url)
return executeRequest(null) {
rawAPI.getUrl(url)
}
.string()
}

View file

@ -18,11 +18,10 @@
package org.matrix.android.sdk.internal.raw
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Url
internal interface RawAPI {
@GET
fun getUrl(@Url url: String): Call<ResponseBody>
suspend fun getUrl(@Url url: String): ResponseBody
}

View file

@ -17,7 +17,6 @@
package org.matrix.android.sdk.internal.session.account
import org.matrix.android.sdk.internal.network.NetworkConstants
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.POST
@ -28,7 +27,7 @@ internal interface AccountAPI {
* @param params parameters to change password.
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "account/password")
fun changePassword(@Body params: ChangePasswordParams): Call<Unit>
suspend fun changePassword(@Body params: ChangePasswordParams)
/**
* Deactivate the user account
@ -36,5 +35,5 @@ internal interface AccountAPI {
* @param params the deactivate account params
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "account/deactivate")
fun deactivate(@Body params: DeactivateAccountParams): Call<Unit>
suspend fun deactivate(@Body params: DeactivateAccountParams)
}

View file

@ -39,8 +39,8 @@ internal class DefaultChangePasswordTask @Inject constructor(
override suspend fun execute(params: ChangePasswordTask.Params) {
val changePasswordParams = ChangePasswordParams.create(userId, params.password, params.newPassword)
try {
executeRequest<Unit>(globalErrorReceiver) {
apiCall = accountAPI.changePassword(changePasswordParams)
executeRequest(globalErrorReceiver) {
accountAPI.changePassword(changePasswordParams)
}
} catch (throwable: Throwable) {
val registrationFlowResponse = throwable.toRegistrationFlowResponse()
@ -49,8 +49,8 @@ internal class DefaultChangePasswordTask @Inject constructor(
/* Avoid infinite loop */
&& changePasswordParams.auth?.session == null) {
// Retry with authentication
executeRequest<Unit>(globalErrorReceiver) {
apiCall = accountAPI.changePassword(
executeRequest(globalErrorReceiver) {
accountAPI.changePassword(
changePasswordParams.copy(auth = changePasswordParams.auth?.copy(session = registrationFlowResponse.session))
)
}

View file

@ -46,8 +46,8 @@ internal class DefaultDeactivateAccountTask @Inject constructor(
val deactivateAccountParams = DeactivateAccountParams.create(params.userAuthParam, params.eraseAllData)
val canCleanup = try {
executeRequest<Unit>(globalErrorReceiver) {
apiCall = accountAPI.deactivate(deactivateAccountParams)
executeRequest(globalErrorReceiver) {
accountAPI.deactivate(deactivateAccountParams)
}
true
} catch (throwable: Throwable) {

View file

@ -31,7 +31,7 @@ internal class DefaultGetTurnServerTask @Inject constructor(private val voipAPI:
override suspend fun execute(params: Params): TurnServerResponse {
return executeRequest(globalErrorReceiver) {
apiCall = voipAPI.getTurnServer()
voipAPI.getTurnServer()
}
}
}

View file

@ -18,11 +18,10 @@ package org.matrix.android.sdk.internal.session.call
import org.matrix.android.sdk.api.session.call.TurnServerResponse
import org.matrix.android.sdk.internal.network.NetworkConstants
import retrofit2.Call
import retrofit2.http.GET
internal interface VoipApi {
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "voip/turnServer")
fun getTurnServer(): Call<TurnServerResponse>
suspend fun getTurnServer(): TurnServerResponse
}

View file

@ -19,7 +19,6 @@ package org.matrix.android.sdk.internal.session.directory
import org.matrix.android.sdk.internal.network.NetworkConstants
import org.matrix.android.sdk.internal.session.room.alias.AddRoomAliasBody
import org.matrix.android.sdk.internal.session.room.alias.RoomAliasDescription
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
@ -33,7 +32,7 @@ internal interface DirectoryAPI {
* @param roomAlias the room alias.
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "directory/room/{roomAlias}")
fun getRoomIdByAlias(@Path("roomAlias") roomAlias: String): Call<RoomAliasDescription>
suspend fun getRoomIdByAlias(@Path("roomAlias") roomAlias: String): RoomAliasDescription
/**
* Get the room directory visibility.
@ -41,7 +40,7 @@ internal interface DirectoryAPI {
* @param roomId the room id.
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "directory/list/room/{roomId}")
fun getRoomDirectoryVisibility(@Path("roomId") roomId: String): Call<RoomDirectoryVisibilityJson>
suspend fun getRoomDirectoryVisibility(@Path("roomId") roomId: String): RoomDirectoryVisibilityJson
/**
* Set the room directory visibility.
@ -50,21 +49,21 @@ internal interface DirectoryAPI {
* @param body the body containing the new directory visibility
*/
@PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "directory/list/room/{roomId}")
fun setRoomDirectoryVisibility(@Path("roomId") roomId: String,
@Body body: RoomDirectoryVisibilityJson): Call<Unit>
suspend fun setRoomDirectoryVisibility(@Path("roomId") roomId: String,
@Body body: RoomDirectoryVisibilityJson)
/**
* Add alias to the room.
* @param roomAlias the room alias.
*/
@PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "directory/room/{roomAlias}")
fun addRoomAlias(@Path("roomAlias") roomAlias: String,
@Body body: AddRoomAliasBody): Call<Unit>
suspend fun addRoomAlias(@Path("roomAlias") roomAlias: String,
@Body body: AddRoomAliasBody)
/**
* Delete a room alias
* @param roomAlias the room alias.
*/
@DELETE(NetworkConstants.URI_API_PREFIX_PATH_R0 + "directory/room/{roomAlias}")
fun deleteRoomAlias(@Path("roomAlias") roomAlias: String): Call<Unit>
suspend fun deleteRoomAlias(@Path("roomAlias") roomAlias: String)
}

View file

@ -17,7 +17,6 @@
package org.matrix.android.sdk.internal.session.filter
import org.matrix.android.sdk.internal.network.NetworkConstants
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
@ -32,8 +31,8 @@ internal interface FilterApi {
* @param body the Json representation of a FilterBody object
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "user/{userId}/filter")
fun uploadFilter(@Path("userId") userId: String,
@Body body: Filter): Call<FilterResponse>
suspend fun uploadFilter(@Path("userId") userId: String,
@Body body: Filter): FilterResponse
/**
* Gets a filter with a given filterId from the homeserver
@ -43,6 +42,6 @@ internal interface FilterApi {
* @return Filter
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "user/{userId}/filter/{filterId}")
fun getFilterById(@Path("userId") userId: String,
@Path("filterId") filterId: String): Call<Filter>
suspend fun getFilterById(@Path("userId") userId: String,
@Path("filterId") filterId: String): Filter
}

View file

@ -59,9 +59,9 @@ internal class DefaultSaveFilterTask @Inject constructor(
}
val updated = filterRepository.storeFilter(filterBody, roomFilter)
if (updated) {
val filterResponse = executeRequest<FilterResponse>(globalErrorReceiver) {
val filterResponse = executeRequest(globalErrorReceiver) {
// TODO auto retry
apiCall = filterAPI.uploadFilter(userId, filterBody)
filterAPI.uploadFilter(userId, filterBody)
}
filterRepository.storeFilterId(filterBody, filterResponse.filterId)
}

View file

@ -64,14 +64,14 @@ internal class DefaultGetGroupDataTask @Inject constructor(
}
Timber.v("Fetch data for group with ids: ${groupIds.joinToString(";")}")
val data = groupIds.map { groupId ->
val groupSummary = executeRequest<GroupSummaryResponse>(globalErrorReceiver) {
apiCall = groupAPI.getSummary(groupId)
val groupSummary = executeRequest(globalErrorReceiver) {
groupAPI.getSummary(groupId)
}
val groupRooms = executeRequest<GroupRooms>(globalErrorReceiver) {
apiCall = groupAPI.getRooms(groupId)
val groupRooms = executeRequest(globalErrorReceiver) {
groupAPI.getRooms(groupId)
}
val groupUsers = executeRequest<GroupUsers>(globalErrorReceiver) {
apiCall = groupAPI.getUsers(groupId)
val groupUsers = executeRequest(globalErrorReceiver) {
groupAPI.getUsers(groupId)
}
GroupData(groupId, groupSummary, groupRooms, groupUsers)
}

View file

@ -20,7 +20,6 @@ import org.matrix.android.sdk.internal.network.NetworkConstants
import org.matrix.android.sdk.internal.session.group.model.GroupRooms
import org.matrix.android.sdk.internal.session.group.model.GroupSummaryResponse
import org.matrix.android.sdk.internal.session.group.model.GroupUsers
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path
@ -32,7 +31,7 @@ internal interface GroupAPI {
* @param groupId the group id
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "groups/{groupId}/summary")
fun getSummary(@Path("groupId") groupId: String): Call<GroupSummaryResponse>
suspend fun getSummary(@Path("groupId") groupId: String): GroupSummaryResponse
/**
* Request the rooms list.
@ -40,7 +39,7 @@ internal interface GroupAPI {
* @param groupId the group id
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "groups/{groupId}/rooms")
fun getRooms(@Path("groupId") groupId: String): Call<GroupRooms>
suspend fun getRooms(@Path("groupId") groupId: String): GroupRooms
/**
* Request the users list.
@ -48,5 +47,5 @@ internal interface GroupAPI {
* @param groupId the group id
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "groups/{groupId}/users")
fun getUsers(@Path("groupId") groupId: String): Call<GroupUsers>
suspend fun getUsers(@Path("groupId") groupId: String): GroupUsers
}

View file

@ -18,7 +18,6 @@ package org.matrix.android.sdk.internal.session.homeserver
import org.matrix.android.sdk.internal.auth.version.Versions
import org.matrix.android.sdk.internal.network.NetworkConstants
import retrofit2.Call
import retrofit2.http.GET
internal interface CapabilitiesAPI {
@ -26,17 +25,17 @@ internal interface CapabilitiesAPI {
* Request the homeserver capabilities
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "capabilities")
fun getCapabilities(): Call<GetCapabilitiesResult>
suspend fun getCapabilities(): GetCapabilitiesResult
/**
* Request the versions
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_ + "versions")
fun getVersions(): Call<Versions>
suspend fun getVersions(): Versions
/**
* Ping the homeserver. We do not care about the returned data, so there is no use to parse them
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_ + "versions")
fun ping(): Call<Unit>
suspend fun ping()
}

View file

@ -71,20 +71,20 @@ internal class DefaultGetHomeServerCapabilitiesTask @Inject constructor(
}
val capabilities = runCatching {
executeRequest<GetCapabilitiesResult>(globalErrorReceiver) {
apiCall = capabilitiesAPI.getCapabilities()
executeRequest(globalErrorReceiver) {
capabilitiesAPI.getCapabilities()
}
}.getOrNull()
val mediaConfig = runCatching {
executeRequest<GetMediaConfigResult>(globalErrorReceiver) {
apiCall = mediaAPI.getMediaConfig()
executeRequest(globalErrorReceiver) {
mediaAPI.getMediaConfig()
}
}.getOrNull()
val versions = runCatching {
executeRequest<Versions>(null) {
apiCall = capabilitiesAPI.getVersions()
executeRequest(null) {
capabilitiesAPI.getVersions()
}
}.getOrNull()

View file

@ -34,8 +34,8 @@ internal class HomeServerPinger @Inject constructor(private val taskExecutor: Ta
suspend fun canReachHomeServer(): Boolean {
return try {
executeRequest<Unit>(null) {
apiCall = capabilitiesAPI.ping()
executeRequest(null) {
capabilitiesAPI.ping()
}
true
} catch (throwable: Throwable) {

View file

@ -26,7 +26,6 @@ import org.matrix.android.sdk.internal.session.identity.model.IdentityRequestOwn
import org.matrix.android.sdk.internal.session.identity.model.IdentityRequestTokenForEmailBody
import org.matrix.android.sdk.internal.session.identity.model.IdentityRequestTokenForMsisdnBody
import org.matrix.android.sdk.internal.session.identity.model.IdentityRequestTokenResponse
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
@ -43,20 +42,20 @@ internal interface IdentityAPI {
* Ref: https://matrix.org/docs/spec/identity_service/latest#get-matrix-identity-v2-account
*/
@GET(NetworkConstants.URI_IDENTITY_PATH_V2 + "account")
fun getAccount(): Call<IdentityAccountResponse>
suspend fun getAccount(): IdentityAccountResponse
/**
* Logs out the access token, preventing it from being used to authenticate future requests to the server.
*/
@POST(NetworkConstants.URI_IDENTITY_PATH_V2 + "account/logout")
fun logout(): Call<Unit>
suspend fun logout()
/**
* Request the hash detail to request a bunch of 3PIDs
* Ref: https://matrix.org/docs/spec/identity_service/latest#get-matrix-identity-v2-hash-details
*/
@GET(NetworkConstants.URI_IDENTITY_PATH_V2 + "hash_details")
fun hashDetails(): Call<IdentityHashDetailResponse>
suspend fun hashDetails(): IdentityHashDetailResponse
/**
* Request a bunch of 3PIDs
@ -65,7 +64,7 @@ internal interface IdentityAPI {
* @param body the body request
*/
@POST(NetworkConstants.URI_IDENTITY_PATH_V2 + "lookup")
fun lookup(@Body body: IdentityLookUpParams): Call<IdentityLookUpResponse>
suspend fun lookup(@Body body: IdentityLookUpParams): IdentityLookUpResponse
/**
* Create a session to change the bind status of an email to an identity server
@ -75,7 +74,7 @@ internal interface IdentityAPI {
* @return the sid
*/
@POST(NetworkConstants.URI_IDENTITY_PATH_V2 + "validate/email/requestToken")
fun requestTokenToBindEmail(@Body body: IdentityRequestTokenForEmailBody): Call<IdentityRequestTokenResponse>
suspend fun requestTokenToBindEmail(@Body body: IdentityRequestTokenForEmailBody): IdentityRequestTokenResponse
/**
* Create a session to change the bind status of an phone number to an identity server
@ -85,7 +84,7 @@ internal interface IdentityAPI {
* @return the sid
*/
@POST(NetworkConstants.URI_IDENTITY_PATH_V2 + "validate/msisdn/requestToken")
fun requestTokenToBindMsisdn(@Body body: IdentityRequestTokenForMsisdnBody): Call<IdentityRequestTokenResponse>
suspend fun requestTokenToBindMsisdn(@Body body: IdentityRequestTokenForMsisdnBody): IdentityRequestTokenResponse
/**
* Validate ownership of an email address, or a phone number.
@ -94,6 +93,6 @@ internal interface IdentityAPI {
* - https://matrix.org/docs/spec/identity_service/latest#post-matrix-identity-v2-validate-email-submittoken
*/
@POST(NetworkConstants.URI_IDENTITY_PATH_V2 + "validate/{medium}/submitToken")
fun submitToken(@Path("medium") medium: String,
@Body body: IdentityRequestOwnershipParams): Call<SuccessResult>
suspend fun submitToken(@Path("medium") medium: String,
@Body body: IdentityRequestOwnershipParams): SuccessResult
}

View file

@ -19,7 +19,6 @@ package org.matrix.android.sdk.internal.session.identity
import org.matrix.android.sdk.internal.network.NetworkConstants
import org.matrix.android.sdk.internal.session.identity.model.IdentityRegisterResponse
import org.matrix.android.sdk.internal.session.openid.RequestOpenIdTokenResponse
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
@ -40,18 +39,18 @@ internal interface IdentityAuthAPI {
* @return 200 in case of success
*/
@GET(NetworkConstants.URI_IDENTITY_PREFIX_PATH)
fun ping(): Call<Unit>
suspend fun ping()
/**
* Ping v1 will be used to check outdated Identity server
*/
@GET("_matrix/identity/api/v1")
fun pingV1(): Call<Unit>
suspend fun pingV1()
/**
* Exchanges an OpenID token from the homeserver for an access token to access the identity server.
* The request body is the same as the values returned by /openid/request_token in the Client-Server API.
*/
@POST(NetworkConstants.URI_IDENTITY_PATH_V2 + "account/register")
fun register(@Body openIdToken: RequestOpenIdTokenResponse): Call<IdentityRegisterResponse>
suspend fun register(@Body openIdToken: RequestOpenIdTokenResponse): IdentityRegisterResponse
}

View file

@ -83,7 +83,7 @@ internal class DefaultIdentityBulkLookupTask @Inject constructor(
return try {
LookUpData(hashedAddresses,
executeRequest(null) {
apiCall = identityAPI.lookup(IdentityLookUpParams(
identityAPI.lookup(IdentityLookUpParams(
hashedAddresses,
IdentityHashDetailResponse.ALGORITHM_SHA256,
hashDetailResponse.pepper
@ -126,7 +126,7 @@ internal class DefaultIdentityBulkLookupTask @Inject constructor(
private suspend fun fetchHashDetails(identityAPI: IdentityAPI): IdentityHashDetailResponse {
return executeRequest(null) {
apiCall = identityAPI.hashDetails()
identityAPI.hashDetails()
}
}

View file

@ -42,8 +42,8 @@ internal class DefaultIdentityDisconnectTask @Inject constructor(
return
}
executeRequest<Unit>(null) {
apiCall = identityAPI.logout()
executeRequest(null) {
identityAPI.logout()
}
}
}

View file

@ -33,14 +33,14 @@ internal class DefaultIdentityPingTask @Inject constructor() : IdentityPingTask
override suspend fun execute(params: IdentityPingTask.Params) {
try {
executeRequest<Unit>(null) {
apiCall = params.identityAuthAPI.ping()
executeRequest(null) {
params.identityAuthAPI.ping()
}
} catch (throwable: Throwable) {
if (throwable is Failure.ServerError && throwable.httpCode == HttpsURLConnection.HTTP_NOT_FOUND /* 404 */) {
// Check if API v1 is available
executeRequest<Unit>(null) {
apiCall = params.identityAuthAPI.pingV1()
executeRequest(null) {
params.identityAuthAPI.pingV1()
}
// API V1 is responding, but not V2 -> Outdated
throw IdentityServiceError.OutdatedIdentityServer

View file

@ -33,7 +33,7 @@ internal class DefaultIdentityRegisterTask @Inject constructor() : IdentityRegis
override suspend fun execute(params: IdentityRegisterTask.Params): IdentityRegisterResponse {
return executeRequest(null) {
apiCall = params.identityAuthAPI.register(params.openIdTokenResponse)
params.identityAuthAPI.register(params.openIdTokenResponse)
}
}
}

View file

@ -25,7 +25,6 @@ import org.matrix.android.sdk.internal.session.identity.data.IdentityPendingBind
import org.matrix.android.sdk.internal.session.identity.data.IdentityStore
import org.matrix.android.sdk.internal.session.identity.model.IdentityRequestTokenForEmailBody
import org.matrix.android.sdk.internal.session.identity.model.IdentityRequestTokenForMsisdnBody
import org.matrix.android.sdk.internal.session.identity.model.IdentityRequestTokenResponse
import org.matrix.android.sdk.internal.task.Task
import java.util.UUID
import javax.inject.Inject
@ -56,8 +55,8 @@ internal class DefaultIdentityRequestTokenForBindingTask @Inject constructor(
val clientSecret = identityPendingBinding?.clientSecret ?: UUID.randomUUID().toString()
val sendAttempt = identityPendingBinding?.sendAttempt?.inc() ?: 1
val tokenResponse = executeRequest<IdentityRequestTokenResponse>(null) {
apiCall = when (params.threePid) {
val tokenResponse = executeRequest(null) {
when (params.threePid) {
is ThreePid.Email -> identityAPI.requestTokenToBindEmail(IdentityRequestTokenForEmailBody(
clientSecret = clientSecret,
sendAttempt = sendAttempt,

View file

@ -19,7 +19,6 @@ package org.matrix.android.sdk.internal.session.identity
import org.matrix.android.sdk.api.session.identity.IdentityServiceError
import org.matrix.android.sdk.api.session.identity.ThreePid
import org.matrix.android.sdk.api.session.identity.toMedium
import org.matrix.android.sdk.internal.auth.registration.SuccessResult
import org.matrix.android.sdk.internal.di.UserId
import org.matrix.android.sdk.internal.network.executeRequest
import org.matrix.android.sdk.internal.session.identity.data.IdentityStore
@ -44,8 +43,8 @@ internal class DefaultIdentitySubmitTokenForBindingTask @Inject constructor(
val identityAPI = getIdentityApiAndEnsureTerms(identityApiProvider, userId)
val identityPendingBinding = identityStore.getPendingBinding(params.threePid) ?: throw IdentityServiceError.NoCurrentBindingError
val tokenResponse = executeRequest<SuccessResult>(null) {
apiCall = identityAPI.submitToken(
val tokenResponse = executeRequest(null) {
identityAPI.submitToken(
params.threePid.toMedium(),
IdentityRequestOwnershipParams(
clientSecret = identityPendingBinding.clientSecret,

View file

@ -18,14 +18,13 @@ package org.matrix.android.sdk.internal.session.identity
import org.matrix.android.sdk.api.session.identity.IdentityServiceError
import org.matrix.android.sdk.internal.network.executeRequest
import org.matrix.android.sdk.internal.session.identity.model.IdentityAccountResponse
internal suspend fun getIdentityApiAndEnsureTerms(identityApiProvider: IdentityApiProvider, userId: String): IdentityAPI {
val identityAPI = identityApiProvider.identityApi ?: throw IdentityServiceError.NoIdentityServerConfigured
// Always check that we have access to the service (regarding terms)
val identityAccountResponse = executeRequest<IdentityAccountResponse>(null) {
apiCall = identityAPI.getAccount()
val identityAccountResponse = executeRequest(null) {
identityAPI.getAccount()
}
assert(userId == identityAccountResponse.userId)

View file

@ -65,8 +65,8 @@ internal class DefaultGetPreviewUrlTask @Inject constructor(
}
private suspend fun doRequest(url: String, timestamp: Long?): PreviewUrlData {
return executeRequest<JsonDict>(globalErrorReceiver) {
apiCall = mediaAPI.getPreviewUrlData(url, timestamp)
return executeRequest(globalErrorReceiver) {
mediaAPI.getPreviewUrlData(url, timestamp)
}
.toPreviewUrlData(url)
}

View file

@ -36,7 +36,7 @@ internal class DefaultGetRawPreviewUrlTask @Inject constructor(
override suspend fun execute(params: GetRawPreviewUrlTask.Params): JsonDict {
return executeRequest(globalErrorReceiver) {
apiCall = mediaAPI.getPreviewUrlData(params.url, params.timestamp)
mediaAPI.getPreviewUrlData(params.url, params.timestamp)
}
}
}

View file

@ -18,7 +18,6 @@ package org.matrix.android.sdk.internal.session.media
import org.matrix.android.sdk.api.util.JsonDict
import org.matrix.android.sdk.internal.network.NetworkConstants
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
@ -28,7 +27,7 @@ internal interface MediaAPI {
* Ref: https://matrix.org/docs/spec/client_server/r0.6.1#get-matrix-media-r0-config
*/
@GET(NetworkConstants.URI_API_MEDIA_PREFIX_PATH_R0 + "config")
fun getMediaConfig(): Call<GetMediaConfigResult>
suspend fun getMediaConfig(): GetMediaConfigResult
/**
* Get information about a URL for the client. Typically this is called when a client
@ -39,5 +38,5 @@ internal interface MediaAPI {
* if it does not have the requested version available.
*/
@GET(NetworkConstants.URI_API_MEDIA_PREFIX_PATH_R0 + "preview_url")
fun getPreviewUrlData(@Query("url") url: String, @Query("ts") ts: Long?): Call<JsonDict>
suspend fun getPreviewUrlData(@Query("url") url: String, @Query("ts") ts: Long?): JsonDict
}

View file

@ -31,7 +31,7 @@ internal class DefaultGetOpenIdTokenTask @Inject constructor(
override suspend fun execute(params: Unit): RequestOpenIdTokenResponse {
return executeRequest(globalErrorReceiver) {
apiCall = openIdAPI.openIdToken(userId)
openIdAPI.openIdToken(userId)
}
}
}

View file

@ -18,7 +18,6 @@ package org.matrix.android.sdk.internal.session.openid
import org.matrix.android.sdk.api.util.JsonDict
import org.matrix.android.sdk.internal.network.NetworkConstants
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.POST
import retrofit2.http.Path
@ -34,6 +33,6 @@ internal interface OpenIdAPI {
* @param userId the user id
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "user/{userId}/openid/request_token")
fun openIdToken(@Path("userId") userId: String,
@Body body: JsonDict = emptyMap()): Call<RequestOpenIdTokenResponse>
suspend fun openIdToken(@Path("userId") userId: String,
@Body body: JsonDict = emptyMap()): RequestOpenIdTokenResponse
}

View file

@ -50,13 +50,14 @@ internal class DefaultAddThreePidTask @Inject constructor(
val clientSecret = UUID.randomUUID().toString()
val sendAttempt = 1
val result = executeRequest<AddEmailResponse>(globalErrorReceiver) {
val body = AddEmailBody(
clientSecret = clientSecret,
email = threePid.email,
sendAttempt = sendAttempt
)
apiCall = profileAPI.addEmail(body)
val body = AddEmailBody(
clientSecret = clientSecret,
email = threePid.email,
sendAttempt = sendAttempt
)
val result = executeRequest(globalErrorReceiver) {
profileAPI.addEmail(body)
}
// Store as a pending three pid
@ -84,14 +85,15 @@ internal class DefaultAddThreePidTask @Inject constructor(
val countryCode = parsedNumber.countryCode
val country = phoneNumberUtil.getRegionCodeForCountryCode(countryCode)
val result = executeRequest<AddMsisdnResponse>(globalErrorReceiver) {
val body = AddMsisdnBody(
clientSecret = clientSecret,
country = country,
phoneNumber = parsedNumber.nationalNumber.toString(),
sendAttempt = sendAttempt
)
apiCall = profileAPI.addMsisdn(body)
val body = AddMsisdnBody(
clientSecret = clientSecret,
country = country,
phoneNumber = parsedNumber.nationalNumber.toString(),
sendAttempt = sendAttempt
)
val result = executeRequest(globalErrorReceiver) {
profileAPI.addMsisdn(body)
}
// Store as a pending three pid

View file

@ -43,8 +43,8 @@ internal class DefaultBindThreePidsTask @Inject constructor(private val profileA
val identityServerAccessToken = accessTokenProvider.getToken() ?: throw IdentityServiceError.NoIdentityServerConfigured
val identityPendingBinding = identityStore.getPendingBinding(params.threePid) ?: throw IdentityServiceError.NoCurrentBindingError
executeRequest<Unit>(globalErrorReceiver) {
apiCall = profileAPI.bindThreePid(
executeRequest(globalErrorReceiver) {
profileAPI.bindThreePid(
BindThreePidBody(
clientSecret = identityPendingBinding.clientSecret,
identityServerUrlWithoutProtocol = identityServerUrlWithoutProtocol,

View file

@ -34,12 +34,12 @@ internal class DefaultDeleteThreePidTask @Inject constructor(
private val globalErrorReceiver: GlobalErrorReceiver) : DeleteThreePidTask() {
override suspend fun execute(params: Params) {
executeRequest<DeleteThreePidResponse>(globalErrorReceiver) {
val body = DeleteThreePidBody(
medium = params.threePid.toMedium(),
address = params.threePid.value
)
apiCall = profileAPI.deleteThreePid(body)
val body = DeleteThreePidBody(
medium = params.threePid.toMedium(),
address = params.threePid.value
)
executeRequest(globalErrorReceiver) {
profileAPI.deleteThreePid(body)
}
// We do not really care about the result for the moment

View file

@ -61,13 +61,13 @@ internal class DefaultFinalizeAddingThreePidTask @Inject constructor(
?: throw IllegalArgumentException("unknown threepid")
try {
executeRequest<Unit>(globalErrorReceiver) {
executeRequest(globalErrorReceiver) {
val body = FinalizeAddThreePidBody(
clientSecret = pendingThreePids.clientSecret,
sid = pendingThreePids.sid,
auth = params.userAuthParam?.asMap()
)
apiCall = profileAPI.finalizeAddThreePid(body)
profileAPI.finalizeAddThreePid(body)
}
true
} catch (throwable: Throwable) {

View file

@ -34,7 +34,7 @@ internal class DefaultGetProfileInfoTask @Inject constructor(private val profile
override suspend fun execute(params: Params): JsonDict {
return executeRequest(globalErrorReceiver) {
apiCall = profileAPI.getProfile(params.userId)
profileAPI.getProfile(params.userId)
}
}
}

View file

@ -21,7 +21,6 @@ import org.matrix.android.sdk.api.util.JsonDict
import org.matrix.android.sdk.internal.auth.registration.SuccessResult
import org.matrix.android.sdk.internal.auth.registration.ValidationCodeBody
import org.matrix.android.sdk.internal.network.NetworkConstants
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
@ -37,70 +36,70 @@ internal interface ProfileAPI {
* @param userId the user id to fetch profile info
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "profile/{userId}")
fun getProfile(@Path("userId") userId: String): Call<JsonDict>
suspend fun getProfile(@Path("userId") userId: String): JsonDict
/**
* List all 3PIDs linked to the Matrix user account.
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "account/3pid")
fun getThreePIDs(): Call<AccountThreePidsResponse>
suspend fun getThreePIDs(): AccountThreePidsResponse
/**
* Change user display name
*/
@PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "profile/{userId}/displayname")
fun setDisplayName(@Path("userId") userId: String,
@Body body: SetDisplayNameBody): Call<Unit>
suspend fun setDisplayName(@Path("userId") userId: String,
@Body body: SetDisplayNameBody)
/**
* Change user avatar url.
*/
@PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "profile/{userId}/avatar_url")
fun setAvatarUrl(@Path("userId") userId: String,
@Body body: SetAvatarUrlBody): Call<Unit>
suspend fun setAvatarUrl(@Path("userId") userId: String,
@Body body: SetAvatarUrlBody)
/**
* Bind a threePid
* Ref: https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-account-3pid-bind
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "account/3pid/bind")
fun bindThreePid(@Body body: BindThreePidBody): Call<Unit>
suspend fun bindThreePid(@Body body: BindThreePidBody)
/**
* Unbind a threePid
* Ref: https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-account-3pid-unbind
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "account/3pid/unbind")
fun unbindThreePid(@Body body: UnbindThreePidBody): Call<UnbindThreePidResponse>
suspend fun unbindThreePid(@Body body: UnbindThreePidBody): UnbindThreePidResponse
/**
* Ref: https://matrix.org/docs/spec/client_server/r0.6.1#post-matrix-client-r0-account-3pid-email-requesttoken
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "account/3pid/email/requestToken")
fun addEmail(@Body body: AddEmailBody): Call<AddEmailResponse>
suspend fun addEmail(@Body body: AddEmailBody): AddEmailResponse
/**
* Ref: https://matrix.org/docs/spec/client_server/r0.6.1#post-matrix-client-r0-account-3pid-msisdn-requesttoken
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "account/3pid/msisdn/requestToken")
fun addMsisdn(@Body body: AddMsisdnBody): Call<AddMsisdnResponse>
suspend fun addMsisdn(@Body body: AddMsisdnBody): AddMsisdnResponse
/**
* Validate Msisdn code (same model than for Identity server API)
*/
@POST
fun validateMsisdn(@Url url: String,
@Body params: ValidationCodeBody): Call<SuccessResult>
suspend fun validateMsisdn(@Url url: String,
@Body params: ValidationCodeBody): SuccessResult
/**
* Ref: https://matrix.org/docs/spec/client_server/r0.6.1#post-matrix-client-r0-account-3pid-add
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "account/3pid/add")
fun finalizeAddThreePid(@Body body: FinalizeAddThreePidBody): Call<Unit>
suspend fun finalizeAddThreePid(@Body body: FinalizeAddThreePidBody)
/**
* Ref: https://matrix.org/docs/spec/client_server/r0.6.1#post-matrix-client-r0-account-3pid-delete
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "account/3pid/delete")
fun deleteThreePid(@Body body: DeleteThreePidBody): Call<DeleteThreePidResponse>
suspend fun deleteThreePid(@Body body: DeleteThreePidBody): DeleteThreePidResponse
}

View file

@ -33,8 +33,8 @@ internal class DefaultRefreshUserThreePidsTask @Inject constructor(private val p
private val globalErrorReceiver: GlobalErrorReceiver) : RefreshUserThreePidsTask() {
override suspend fun execute(params: Unit) {
val accountThreePidsResponse = executeRequest<AccountThreePidsResponse>(globalErrorReceiver) {
apiCall = profileAPI.getThreePIDs()
val accountThreePidsResponse = executeRequest(globalErrorReceiver) {
profileAPI.getThreePIDs()
}
Timber.d("Get ${accountThreePidsResponse.threePids?.size} threePids")

View file

@ -33,11 +33,11 @@ internal class DefaultSetAvatarUrlTask @Inject constructor(
private val globalErrorReceiver: GlobalErrorReceiver) : SetAvatarUrlTask() {
override suspend fun execute(params: Params) {
val body = SetAvatarUrlBody(
avatarUrl = params.newAvatarUrl
)
return executeRequest(globalErrorReceiver) {
val body = SetAvatarUrlBody(
avatarUrl = params.newAvatarUrl
)
apiCall = profileAPI.setAvatarUrl(params.userId, body)
profileAPI.setAvatarUrl(params.userId, body)
}
}
}

View file

@ -33,11 +33,11 @@ internal class DefaultSetDisplayNameTask @Inject constructor(
private val globalErrorReceiver: GlobalErrorReceiver) : SetDisplayNameTask() {
override suspend fun execute(params: Params) {
val body = SetDisplayNameBody(
displayName = params.newDisplayName
)
return executeRequest(globalErrorReceiver) {
val body = SetDisplayNameBody(
displayName = params.newDisplayName
)
apiCall = profileAPI.setDisplayName(params.userId, body)
profileAPI.setDisplayName(params.userId, body)
}
}
}

View file

@ -39,8 +39,8 @@ internal class DefaultUnbindThreePidsTask @Inject constructor(private val profil
val identityServerUrlWithoutProtocol = identityStore.getIdentityServerUrlWithoutProtocol()
?: throw IdentityServiceError.NoIdentityServerConfigured
return executeRequest<UnbindThreePidResponse>(globalErrorReceiver) {
apiCall = profileAPI.unbindThreePid(
return executeRequest(globalErrorReceiver) {
profileAPI.unbindThreePid(
UnbindThreePidBody(
identityServerUrlWithoutProtocol,
params.threePid.toMedium(),

View file

@ -19,7 +19,6 @@ package org.matrix.android.sdk.internal.session.profile
import com.zhuinden.monarchy.Monarchy
import org.matrix.android.sdk.api.failure.Failure
import org.matrix.android.sdk.api.session.identity.ThreePid
import org.matrix.android.sdk.internal.auth.registration.SuccessResult
import org.matrix.android.sdk.internal.auth.registration.ValidationCodeBody
import org.matrix.android.sdk.internal.database.model.PendingThreePidEntity
import org.matrix.android.sdk.internal.di.SessionDatabase
@ -58,8 +57,8 @@ internal class DefaultValidateSmsCodeTask @Inject constructor(
sid = pendingThreePids.sid,
code = params.code
)
val result = executeRequest<SuccessResult>(globalErrorReceiver) {
apiCall = profileAPI.validateMsisdn(url, body)
val result = executeRequest(globalErrorReceiver) {
profileAPI.validateMsisdn(url, body)
}
if (!result.isSuccess()) {

View file

@ -81,8 +81,8 @@ internal class AddHttpPusherWorker(context: Context, params: WorkerParameters)
}
private suspend fun setPusher(pusher: JsonPusher) {
executeRequest<Unit>(globalErrorReceiver) {
apiCall = pushersAPI.setPusher(pusher)
executeRequest(globalErrorReceiver) {
pushersAPI.setPusher(pusher)
}
monarchy.awaitTransaction { realm ->
val echo = PusherEntity.where(realm, pusher.pushKey).findFirst()

View file

@ -36,7 +36,7 @@ internal class DefaultAddPushRuleTask @Inject constructor(
override suspend fun execute(params: AddPushRuleTask.Params) {
return executeRequest(globalErrorReceiver) {
apiCall = pushRulesApi.addRule(params.kind.value, params.pushRule.ruleId, params.pushRule)
pushRulesApi.addRule(params.kind.value, params.pushRule.ruleId, params.pushRule)
}
}
}

View file

@ -15,7 +15,6 @@
*/
package org.matrix.android.sdk.internal.session.pushers
import org.matrix.android.sdk.api.pushrules.rest.GetPushRulesResponse
import org.matrix.android.sdk.internal.network.GlobalErrorReceiver
import org.matrix.android.sdk.internal.network.executeRequest
import org.matrix.android.sdk.internal.task.Task
@ -35,8 +34,8 @@ internal class DefaultGetPushRulesTask @Inject constructor(
) : GetPushRulesTask {
override suspend fun execute(params: GetPushRulesTask.Params) {
val response = executeRequest<GetPushRulesResponse>(globalErrorReceiver) {
apiCall = pushRulesApi.getAllRules()
val response = executeRequest(globalErrorReceiver) {
pushRulesApi.getAllRules()
}
savePushRulesTask.execute(SavePushRulesTask.Params(response))

View file

@ -36,8 +36,8 @@ internal class DefaultGetPushersTask @Inject constructor(
) : GetPushersTask {
override suspend fun execute(params: Unit) {
val response = executeRequest<GetPushersResponse>(globalErrorReceiver) {
apiCall = pushersAPI.getPushers()
val response = executeRequest(globalErrorReceiver) {
pushersAPI.getPushers()
}
monarchy.awaitTransaction { realm ->
// clear existings?

View file

@ -18,7 +18,6 @@ package org.matrix.android.sdk.internal.session.pushers
import org.matrix.android.sdk.api.pushrules.rest.GetPushRulesResponse
import org.matrix.android.sdk.api.pushrules.rest.PushRule
import org.matrix.android.sdk.internal.network.NetworkConstants
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
@ -30,7 +29,7 @@ internal interface PushRulesApi {
* Get all push rules
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "pushrules/")
fun getAllRules(): Call<GetPushRulesResponse>
suspend fun getAllRules(): GetPushRulesResponse
/**
* Update the ruleID enable status
@ -40,10 +39,9 @@ internal interface PushRulesApi {
* @param enable the new enable status
*/
@PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "pushrules/global/{kind}/{ruleId}/enabled")
fun updateEnableRuleStatus(@Path("kind") kind: String,
@Path("ruleId") ruleId: String,
@Body enable: Boolean?)
: Call<Unit>
suspend fun updateEnableRuleStatus(@Path("kind") kind: String,
@Path("ruleId") ruleId: String,
@Body enable: Boolean?)
/**
* Update the ruleID action
@ -54,10 +52,9 @@ internal interface PushRulesApi {
* @param actions the actions
*/
@PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "pushrules/global/{kind}/{ruleId}/actions")
fun updateRuleActions(@Path("kind") kind: String,
@Path("ruleId") ruleId: String,
@Body actions: Any)
: Call<Unit>
suspend fun updateRuleActions(@Path("kind") kind: String,
@Path("ruleId") ruleId: String,
@Body actions: Any)
/**
* Delete a rule
@ -66,9 +63,8 @@ internal interface PushRulesApi {
* @param ruleId the ruleId
*/
@DELETE(NetworkConstants.URI_API_PREFIX_PATH_R0 + "pushrules/global/{kind}/{ruleId}")
fun deleteRule(@Path("kind") kind: String,
@Path("ruleId") ruleId: String)
: Call<Unit>
suspend fun deleteRule(@Path("kind") kind: String,
@Path("ruleId") ruleId: String)
/**
* Add the ruleID enable status
@ -78,8 +74,7 @@ internal interface PushRulesApi {
* @param rule the rule to add.
*/
@PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "pushrules/global/{kind}/{ruleId}")
fun addRule(@Path("kind") kind: String,
@Path("ruleId") ruleId: String,
@Body rule: PushRule)
: Call<Unit>
suspend fun addRule(@Path("kind") kind: String,
@Path("ruleId") ruleId: String,
@Body rule: PushRule)
}

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