Merge pull request #2500 from aqulu/feature/state_service_coroutines

Convert StateService to suspend functions
This commit is contained in:
Benoit Marty 2020-12-11 18:04:25 +01:00 committed by GitHub
commit 3eba43f3fa
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 130 additions and 134 deletions

View file

@ -23,6 +23,7 @@ Translations 🗣:
- -
SDK API changes ⚠️: SDK API changes ⚠️:
- StateService now exposes suspendable function instead of using MatrixCallback.
- RawCacheStrategy has been moved and renamed to CacheStrategy - RawCacheStrategy has been moved and renamed to CacheStrategy
- FileService: remove useless FileService.DownloadMode - FileService: remove useless FileService.DownloadMode

View file

@ -38,6 +38,7 @@ dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'io.reactivex.rxjava2:rxkotlin:2.3.0' implementation 'io.reactivex.rxjava2:rxkotlin:2.3.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-rx2:$kotlin_coroutines_version"
// Paging // Paging
implementation "androidx.paging:paging-runtime-ktx:2.1.2" implementation "androidx.paging:paging-runtime-ktx:2.1.2"

View file

@ -17,14 +17,20 @@
package org.matrix.android.sdk.rx package org.matrix.android.sdk.rx
import android.net.Uri import android.net.Uri
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Single
import kotlinx.coroutines.rx2.rxCompletable
import org.matrix.android.sdk.api.query.QueryStringValue import org.matrix.android.sdk.api.query.QueryStringValue
import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.api.session.events.model.Event
import org.matrix.android.sdk.api.session.identity.ThreePid import org.matrix.android.sdk.api.session.identity.ThreePid
import org.matrix.android.sdk.api.session.room.Room import org.matrix.android.sdk.api.session.room.Room
import org.matrix.android.sdk.api.session.room.members.RoomMemberQueryParams import org.matrix.android.sdk.api.session.room.members.RoomMemberQueryParams
import org.matrix.android.sdk.api.session.room.model.EventAnnotationsSummary import org.matrix.android.sdk.api.session.room.model.EventAnnotationsSummary
import org.matrix.android.sdk.api.session.room.model.GuestAccess
import org.matrix.android.sdk.api.session.room.model.ReadReceipt import org.matrix.android.sdk.api.session.room.model.ReadReceipt
import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibility import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibility
import org.matrix.android.sdk.api.session.room.model.RoomJoinRules
import org.matrix.android.sdk.api.session.room.model.RoomMemberSummary 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.RoomSummary
import org.matrix.android.sdk.api.session.room.notification.RoomNotificationState import org.matrix.android.sdk.api.session.room.notification.RoomNotificationState
@ -32,11 +38,6 @@ import org.matrix.android.sdk.api.session.room.send.UserDraft
import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent
import org.matrix.android.sdk.api.util.Optional import org.matrix.android.sdk.api.util.Optional
import org.matrix.android.sdk.api.util.toOptional import org.matrix.android.sdk.api.util.toOptional
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Single
import org.matrix.android.sdk.api.session.room.model.GuestAccess
import org.matrix.android.sdk.api.session.room.model.RoomJoinRules
class RxRoom(private val room: Room) { class RxRoom(private val room: Room) {
@ -121,28 +122,28 @@ class RxRoom(private val room: Room) {
room.invite3pid(threePid, it) room.invite3pid(threePid, it)
} }
fun updateTopic(topic: String): Completable = completableBuilder<Unit> { fun updateTopic(topic: String): Completable = rxCompletable {
room.updateTopic(topic, it) room.updateTopic(topic)
} }
fun updateName(name: String): Completable = completableBuilder<Unit> { fun updateName(name: String): Completable = rxCompletable {
room.updateName(name, it) room.updateName(name)
} }
fun updateHistoryReadability(readability: RoomHistoryVisibility): Completable = completableBuilder<Unit> { fun updateHistoryReadability(readability: RoomHistoryVisibility): Completable = rxCompletable {
room.updateHistoryReadability(readability, it) room.updateHistoryReadability(readability)
} }
fun updateJoinRule(joinRules: RoomJoinRules?, guestAccess: GuestAccess?): Completable = completableBuilder<Unit> { fun updateJoinRule(joinRules: RoomJoinRules?, guestAccess: GuestAccess?): Completable = rxCompletable {
room.updateJoinRule(joinRules, guestAccess, it) room.updateJoinRule(joinRules, guestAccess)
} }
fun updateAvatar(avatarUri: Uri, fileName: String): Completable = completableBuilder<Unit> { fun updateAvatar(avatarUri: Uri, fileName: String): Completable = rxCompletable {
room.updateAvatar(avatarUri, fileName, it) room.updateAvatar(avatarUri, fileName)
} }
fun deleteAvatar(): Completable = completableBuilder<Unit> { fun deleteAvatar(): Completable = rxCompletable {
room.deleteAvatar(it) room.deleteAvatar()
} }
} }

View file

@ -17,13 +17,13 @@
package org.matrix.android.sdk.internal.crypto.encryption package org.matrix.android.sdk.internal.crypto.encryption
import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.ext.junit.runners.AndroidJUnit4
import kotlinx.coroutines.runBlocking
import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldBe
import org.junit.FixMethodOrder import org.junit.FixMethodOrder
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.junit.runners.MethodSorters import org.junit.runners.MethodSorters
import org.matrix.android.sdk.InstrumentedTest import org.matrix.android.sdk.InstrumentedTest
import org.matrix.android.sdk.api.NoOpMatrixCallback
import org.matrix.android.sdk.api.session.events.model.EventType import org.matrix.android.sdk.api.session.events.model.EventType
import org.matrix.android.sdk.api.session.events.model.toContent import org.matrix.android.sdk.api.session.events.model.toContent
import org.matrix.android.sdk.api.session.room.Room import org.matrix.android.sdk.api.session.room.Room
@ -57,13 +57,14 @@ class EncryptionTest : InstrumentedTest {
@Test @Test
fun test_EncryptionStateEvent() { fun test_EncryptionStateEvent() {
performTest(roomShouldBeEncrypted = true) { room -> performTest(roomShouldBeEncrypted = true) { room ->
// Send an encryption Event as a State Event runBlocking {
room.sendStateEvent( // Send an encryption Event as a State Event
eventType = EventType.STATE_ROOM_ENCRYPTION, room.sendStateEvent(
stateKey = null, eventType = EventType.STATE_ROOM_ENCRYPTION,
body = EncryptionEventContent(algorithm = MXCRYPTO_ALGORITHM_MEGOLM).toContent(), stateKey = null,
callback = NoOpMatrixCallback() body = EncryptionEventContent(algorithm = MXCRYPTO_ALGORITHM_MEGOLM).toContent()
) )
}
} }
} }

View file

@ -18,13 +18,11 @@ package org.matrix.android.sdk.api.session.room.state
import android.net.Uri import android.net.Uri
import androidx.lifecycle.LiveData import androidx.lifecycle.LiveData
import org.matrix.android.sdk.api.MatrixCallback
import org.matrix.android.sdk.api.query.QueryStringValue import org.matrix.android.sdk.api.query.QueryStringValue
import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.api.session.events.model.Event
import org.matrix.android.sdk.api.session.room.model.GuestAccess import org.matrix.android.sdk.api.session.room.model.GuestAccess
import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibility import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibility
import org.matrix.android.sdk.api.session.room.model.RoomJoinRules import org.matrix.android.sdk.api.session.room.model.RoomJoinRules
import org.matrix.android.sdk.api.util.Cancelable
import org.matrix.android.sdk.api.util.JsonDict import org.matrix.android.sdk.api.util.JsonDict
import org.matrix.android.sdk.api.util.Optional import org.matrix.android.sdk.api.util.Optional
@ -33,41 +31,41 @@ interface StateService {
/** /**
* Update the topic of the room * Update the topic of the room
*/ */
fun updateTopic(topic: String, callback: MatrixCallback<Unit>): Cancelable suspend fun updateTopic(topic: String)
/** /**
* Update the name of the room * Update the name of the room
*/ */
fun updateName(name: String, callback: MatrixCallback<Unit>): Cancelable suspend fun updateName(name: String)
/** /**
* Update the canonical alias of the room * Update the canonical alias of the room
* @param alias the canonical alias, or null to reset the canonical alias of this room * @param alias the canonical alias, or null to reset the canonical alias of this room
* @param altAliases the alternative aliases for this room. It should include the canonical alias if any. * @param altAliases the alternative aliases for this room. It should include the canonical alias if any.
*/ */
fun updateCanonicalAlias(alias: String?, altAliases: List<String>, callback: MatrixCallback<Unit>): Cancelable suspend fun updateCanonicalAlias(alias: String?, altAliases: List<String>)
/** /**
* Update the history readability of the room * Update the history readability of the room
*/ */
fun updateHistoryReadability(readability: RoomHistoryVisibility, callback: MatrixCallback<Unit>): Cancelable suspend fun updateHistoryReadability(readability: RoomHistoryVisibility)
/** /**
* Update the join rule and/or the guest access * Update the join rule and/or the guest access
*/ */
fun updateJoinRule(joinRules: RoomJoinRules?, guestAccess: GuestAccess?, callback: MatrixCallback<Unit>): Cancelable suspend fun updateJoinRule(joinRules: RoomJoinRules?, guestAccess: GuestAccess?)
/** /**
* Update the avatar of the room * Update the avatar of the room
*/ */
fun updateAvatar(avatarUri: Uri, fileName: String, callback: MatrixCallback<Unit>): Cancelable suspend fun updateAvatar(avatarUri: Uri, fileName: String)
/** /**
* Delete the avatar of the room * Delete the avatar of the room
*/ */
fun deleteAvatar(callback: MatrixCallback<Unit>): Cancelable suspend fun deleteAvatar()
fun sendStateEvent(eventType: String, stateKey: String?, body: JsonDict, callback: MatrixCallback<Unit>): Cancelable suspend fun sendStateEvent(eventType: String, stateKey: String?, body: JsonDict)
fun getStateEvent(eventType: String, stateKey: QueryStringValue = QueryStringValue.NoCondition): Event? fun getStateEvent(eventType: String, stateKey: QueryStringValue = QueryStringValue.NoCondition): Event?

View file

@ -20,7 +20,6 @@ import android.net.Uri
import androidx.lifecycle.LiveData import androidx.lifecycle.LiveData
import com.squareup.inject.assisted.Assisted import com.squareup.inject.assisted.Assisted
import com.squareup.inject.assisted.AssistedInject import com.squareup.inject.assisted.AssistedInject
import org.matrix.android.sdk.api.MatrixCallback
import org.matrix.android.sdk.api.query.QueryStringValue import org.matrix.android.sdk.api.query.QueryStringValue
import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.api.session.events.model.Event
import org.matrix.android.sdk.api.session.events.model.EventType import org.matrix.android.sdk.api.session.events.model.EventType
@ -32,23 +31,15 @@ import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibility
import org.matrix.android.sdk.api.session.room.model.RoomJoinRules import org.matrix.android.sdk.api.session.room.model.RoomJoinRules
import org.matrix.android.sdk.api.session.room.model.RoomJoinRulesContent import org.matrix.android.sdk.api.session.room.model.RoomJoinRulesContent
import org.matrix.android.sdk.api.session.room.state.StateService import org.matrix.android.sdk.api.session.room.state.StateService
import org.matrix.android.sdk.api.util.Cancelable
import org.matrix.android.sdk.api.util.JsonDict import org.matrix.android.sdk.api.util.JsonDict
import org.matrix.android.sdk.api.util.MimeTypes import org.matrix.android.sdk.api.util.MimeTypes
import org.matrix.android.sdk.api.util.Optional import org.matrix.android.sdk.api.util.Optional
import org.matrix.android.sdk.internal.session.content.FileUploader import org.matrix.android.sdk.internal.session.content.FileUploader
import org.matrix.android.sdk.internal.session.room.alias.AddRoomAliasTask import org.matrix.android.sdk.internal.session.room.alias.AddRoomAliasTask
import org.matrix.android.sdk.internal.task.TaskExecutor
import org.matrix.android.sdk.internal.task.configureWith
import org.matrix.android.sdk.internal.task.launchToCallback
import org.matrix.android.sdk.internal.util.MatrixCoroutineDispatchers
import org.matrix.android.sdk.internal.util.awaitCallback
internal class DefaultStateService @AssistedInject constructor(@Assisted private val roomId: String, internal class DefaultStateService @AssistedInject constructor(@Assisted private val roomId: String,
private val stateEventDataSource: StateEventDataSource, private val stateEventDataSource: StateEventDataSource,
private val taskExecutor: TaskExecutor,
private val sendStateTask: SendStateTask, private val sendStateTask: SendStateTask,
private val coroutineDispatchers: MatrixCoroutineDispatchers,
private val fileUploader: FileUploader, private val fileUploader: FileUploader,
private val addRoomAliasTask: AddRoomAliasTask private val addRoomAliasTask: AddRoomAliasTask
) : StateService { ) : StateService {
@ -74,45 +65,38 @@ internal class DefaultStateService @AssistedInject constructor(@Assisted private
return stateEventDataSource.getStateEventsLive(roomId, eventTypes, stateKey) return stateEventDataSource.getStateEventsLive(roomId, eventTypes, stateKey)
} }
override fun sendStateEvent( override suspend fun sendStateEvent(
eventType: String, eventType: String,
stateKey: String?, stateKey: String?,
body: JsonDict, body: JsonDict
callback: MatrixCallback<Unit> ) {
): Cancelable {
val params = SendStateTask.Params( val params = SendStateTask.Params(
roomId = roomId, roomId = roomId,
stateKey = stateKey, stateKey = stateKey,
eventType = eventType, eventType = eventType,
body = body body = body
) )
return sendStateTask sendStateTask.execute(params)
.configureWith(params) {
this.callback = callback
}
.executeBy(taskExecutor)
} }
override fun updateTopic(topic: String, callback: MatrixCallback<Unit>): Cancelable { override suspend fun updateTopic(topic: String) {
return sendStateEvent( sendStateEvent(
eventType = EventType.STATE_ROOM_TOPIC, eventType = EventType.STATE_ROOM_TOPIC,
body = mapOf("topic" to topic), body = mapOf("topic" to topic),
callback = callback,
stateKey = null stateKey = null
) )
} }
override fun updateName(name: String, callback: MatrixCallback<Unit>): Cancelable { override suspend fun updateName(name: String) {
return sendStateEvent( sendStateEvent(
eventType = EventType.STATE_ROOM_NAME, eventType = EventType.STATE_ROOM_NAME,
body = mapOf("name" to name), body = mapOf("name" to name),
callback = callback,
stateKey = null stateKey = null
) )
} }
override fun updateCanonicalAlias(alias: String?, altAliases: List<String>, callback: MatrixCallback<Unit>): Cancelable { override suspend fun updateCanonicalAlias(alias: String?, altAliases: List<String>) {
return sendStateEvent( sendStateEvent(
eventType = EventType.STATE_ROOM_CANONICAL_ALIAS, eventType = EventType.STATE_ROOM_CANONICAL_ALIAS,
body = RoomCanonicalAliasContent( body = RoomCanonicalAliasContent(
canonicalAlias = alias, canonicalAlias = alias,
@ -124,64 +108,48 @@ internal class DefaultStateService @AssistedInject constructor(@Assisted private
// Sort for the cleanup // Sort for the cleanup
.sorted() .sorted()
).toContent(), ).toContent(),
callback = callback,
stateKey = null stateKey = null
) )
} }
override fun updateHistoryReadability(readability: RoomHistoryVisibility, callback: MatrixCallback<Unit>): Cancelable { override suspend fun updateHistoryReadability(readability: RoomHistoryVisibility) {
return sendStateEvent( sendStateEvent(
eventType = EventType.STATE_ROOM_HISTORY_VISIBILITY, eventType = EventType.STATE_ROOM_HISTORY_VISIBILITY,
body = mapOf("history_visibility" to readability), body = mapOf("history_visibility" to readability),
callback = callback,
stateKey = null stateKey = null
) )
} }
override fun updateJoinRule(joinRules: RoomJoinRules?, guestAccess: GuestAccess?, callback: MatrixCallback<Unit>): Cancelable { override suspend fun updateJoinRule(joinRules: RoomJoinRules?, guestAccess: GuestAccess?) {
return taskExecutor.executorScope.launchToCallback(coroutineDispatchers.main, callback) { if (joinRules != null) {
if (joinRules != null) { sendStateEvent(
awaitCallback<Unit> { eventType = EventType.STATE_ROOM_JOIN_RULES,
sendStateEvent( body = RoomJoinRulesContent(joinRules).toContent(),
eventType = EventType.STATE_ROOM_JOIN_RULES, stateKey = null
body = RoomJoinRulesContent(joinRules).toContent(), )
callback = it, }
stateKey = null if (guestAccess != null) {
) sendStateEvent(
} eventType = EventType.STATE_ROOM_GUEST_ACCESS,
} body = RoomGuestAccessContent(guestAccess).toContent(),
if (guestAccess != null) { stateKey = null
awaitCallback<Unit> { )
sendStateEvent(
eventType = EventType.STATE_ROOM_GUEST_ACCESS,
body = RoomGuestAccessContent(guestAccess).toContent(),
callback = it,
stateKey = null
)
}
}
} }
} }
override fun updateAvatar(avatarUri: Uri, fileName: String, callback: MatrixCallback<Unit>): Cancelable { override suspend fun updateAvatar(avatarUri: Uri, fileName: String) {
return taskExecutor.executorScope.launchToCallback(coroutineDispatchers.main, callback) { val response = fileUploader.uploadFromUri(avatarUri, fileName, MimeTypes.Jpeg)
val response = fileUploader.uploadFromUri(avatarUri, fileName, MimeTypes.Jpeg) sendStateEvent(
awaitCallback<Unit> { eventType = EventType.STATE_ROOM_AVATAR,
sendStateEvent( body = mapOf("url" to response.contentUri),
eventType = EventType.STATE_ROOM_AVATAR, stateKey = null
body = mapOf("url" to response.contentUri), )
callback = it,
stateKey = null
)
}
}
} }
override fun deleteAvatar(callback: MatrixCallback<Unit>): Cancelable { override suspend fun deleteAvatar() {
return sendStateEvent( sendStateEvent(
eventType = EventType.STATE_ROOM_AVATAR, eventType = EventType.STATE_ROOM_AVATAR,
body = emptyMap(), body = emptyMap(),
callback = callback,
stateKey = null stateKey = null
) )
} }

View file

@ -292,9 +292,7 @@ class RoomDetailViewModel @AssistedInject constructor(
private fun handleSetNewAvatar(action: RoomDetailAction.SetAvatarAction) { private fun handleSetNewAvatar(action: RoomDetailAction.SetAvatarAction) {
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
try { try {
awaitCallback<Unit> { room.updateAvatar(action.newAvatarUri, action.newAvatarFileName)
room.updateAvatar(action.newAvatarUri, action.newAvatarFileName, it)
}
_viewEvents.post(RoomDetailViewEvents.ActionSuccess(action)) _viewEvents.post(RoomDetailViewEvents.ActionSuccess(action))
} catch (failure: Throwable) { } catch (failure: Throwable) {
_viewEvents.post(RoomDetailViewEvents.ActionFailure(action, failure)) _viewEvents.post(RoomDetailViewEvents.ActionFailure(action, failure))
@ -854,8 +852,8 @@ class RoomDetailViewModel @AssistedInject constructor(
} }
private fun handleChangeTopicSlashCommand(changeTopic: ParsedCommand.ChangeTopic) { private fun handleChangeTopicSlashCommand(changeTopic: ParsedCommand.ChangeTopic) {
launchSlashCommandFlow { launchSlashCommandFlowSuspendable {
room.updateTopic(changeTopic.topic, it) room.updateTopic(changeTopic.topic)
} }
} }
@ -876,9 +874,9 @@ class RoomDetailViewModel @AssistedInject constructor(
?.content ?.content
?.toModel<PowerLevelsContent>() ?: return ?.toModel<PowerLevelsContent>() ?: return
launchSlashCommandFlow { launchSlashCommandFlowSuspendable {
currentPowerLevelsContent.setUserPowerLevel(setUserPowerLevel.userId, setUserPowerLevel.powerLevel) currentPowerLevelsContent.setUserPowerLevel(setUserPowerLevel.userId, setUserPowerLevel.powerLevel)
room.sendStateEvent(EventType.STATE_ROOM_POWER_LEVELS, null, currentPowerLevelsContent.toContent(), it) room.sendStateEvent(EventType.STATE_ROOM_POWER_LEVELS, null, currentPowerLevelsContent.toContent())
} }
} }
@ -920,6 +918,19 @@ class RoomDetailViewModel @AssistedInject constructor(
lambda.invoke(matrixCallback) lambda.invoke(matrixCallback)
} }
private fun launchSlashCommandFlowSuspendable(block: suspend () -> Unit) {
_viewEvents.post(RoomDetailViewEvents.SlashCommandHandled())
viewModelScope.launch {
val event = try {
block()
RoomDetailViewEvents.SlashCommandResultOk
} catch (failure: Exception) {
RoomDetailViewEvents.SlashCommandResultError(failure)
}
_viewEvents.post(event)
}
}
private fun handleSendReaction(action: RoomDetailAction.SendReaction) { private fun handleSendReaction(action: RoomDetailAction.SendReaction) {
room.sendReaction(action.targetEventId, action.reaction) room.sendReaction(action.targetEventId, action.reaction)
} }

View file

@ -166,9 +166,7 @@ class RoomMemberProfileViewModel @AssistedInject constructor(@Assisted private v
viewModelScope.launch { viewModelScope.launch {
_viewEvents.post(RoomMemberProfileViewEvents.Loading()) _viewEvents.post(RoomMemberProfileViewEvents.Loading())
try { try {
awaitCallback<Unit> { room.sendStateEvent(EventType.STATE_ROOM_POWER_LEVELS, null, currentPowerLevelsContent.toContent())
room.sendStateEvent(EventType.STATE_ROOM_POWER_LEVELS, null, currentPowerLevelsContent.toContent(), it)
}
_viewEvents.post(RoomMemberProfileViewEvents.OnSetPowerLevelSuccess) _viewEvents.post(RoomMemberProfileViewEvents.OnSetPowerLevelSuccess)
} catch (failure: Throwable) { } catch (failure: Throwable) {
_viewEvents.post(RoomMemberProfileViewEvents.Failure(failure)) _viewEvents.post(RoomMemberProfileViewEvents.Failure(failure))

View file

@ -30,7 +30,6 @@ import im.vector.app.core.extensions.exhaustive
import im.vector.app.core.platform.VectorViewModel import im.vector.app.core.platform.VectorViewModel
import im.vector.app.features.powerlevel.PowerLevelsObservableFactory import im.vector.app.features.powerlevel.PowerLevelsObservableFactory
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.MatrixCallback
import org.matrix.android.sdk.api.query.QueryStringValue import org.matrix.android.sdk.api.query.QueryStringValue
import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.events.model.EventType import org.matrix.android.sdk.api.session.events.model.EventType
@ -301,21 +300,20 @@ class RoomAliasViewModel @AssistedInject constructor(@Assisted initialState: Roo
private fun updateCanonicalAlias(canonicalAlias: String?, alternativeAliases: List<String>, closeForm: Boolean) { private fun updateCanonicalAlias(canonicalAlias: String?, alternativeAliases: List<String>, closeForm: Boolean) {
postLoading(true) postLoading(true)
room.updateCanonicalAlias(canonicalAlias, alternativeAliases, object : MatrixCallback<Unit> { viewModelScope.launch {
override fun onSuccess(data: Unit) { try {
room.updateCanonicalAlias(canonicalAlias, alternativeAliases)
setState { setState {
copy( copy(
isLoading = false, isLoading = false,
publishManuallyState = if (closeForm) RoomAliasViewState.AddAliasState.Closed else publishManuallyState publishManuallyState = if (closeForm) RoomAliasViewState.AddAliasState.Closed else publishManuallyState
) )
} }
} } catch (failure: Throwable) {
override fun onFailure(failure: Throwable) {
postLoading(false) postLoading(false)
_viewEvents.post(RoomAliasViewEvents.Failure(failure)) _viewEvents.post(RoomAliasViewEvents.Failure(failure))
} }
}) }
} }
private fun handleAddLocalAlias() = withState { state -> private fun handleAddLocalAlias() = withState { state ->

View file

@ -30,7 +30,6 @@ import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.BiFunction import io.reactivex.functions.BiFunction
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.NoOpMatrixCallback
import org.matrix.android.sdk.api.crypto.RoomEncryptionTrustLevel import org.matrix.android.sdk.api.crypto.RoomEncryptionTrustLevel
import org.matrix.android.sdk.api.extensions.orFalse import org.matrix.android.sdk.api.extensions.orFalse
import org.matrix.android.sdk.api.query.QueryStringValue import org.matrix.android.sdk.api.query.QueryStringValue
@ -197,8 +196,7 @@ class RoomMemberListViewModel @AssistedInject constructor(@Assisted initialState
room.sendStateEvent( room.sendStateEvent(
eventType = EventType.STATE_ROOM_THIRD_PARTY_INVITE, eventType = EventType.STATE_ROOM_THIRD_PARTY_INVITE,
stateKey = action.stateKey, stateKey = action.stateKey,
body = emptyMap(), body = emptyMap()
callback = NoOpMatrixCallback()
) )
} }
} }

View file

@ -21,6 +21,9 @@ import com.squareup.inject.assisted.Assisted
import com.squareup.inject.assisted.AssistedInject import com.squareup.inject.assisted.AssistedInject
import im.vector.app.R import im.vector.app.R
import im.vector.app.core.resources.StringProvider import im.vector.app.core.resources.StringProvider
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.query.QueryStringValue import org.matrix.android.sdk.api.query.QueryStringValue
import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.accountdata.UserAccountDataTypes import org.matrix.android.sdk.api.session.accountdata.UserAccountDataTypes
@ -310,12 +313,13 @@ class WidgetPostAPIHandler @AssistedInject constructor(@Assisted private val roo
val params = HashMap<String, Any>() val params = HashMap<String, Any>()
params["status"] = status params["status"] = status
room.sendStateEvent( launchWidgetAPIAction(widgetPostAPIMediator, eventData) {
eventType = EventType.PLUMBING, room.sendStateEvent(
stateKey = null, eventType = EventType.PLUMBING,
body = params, stateKey = null,
callback = createWidgetAPICallback(widgetPostAPIMediator, eventData) body = params
) )
}
} }
/** /**
@ -333,12 +337,14 @@ class WidgetPostAPIHandler @AssistedInject constructor(@Assisted private val roo
Timber.d(description) Timber.d(description)
val content = eventData["content"] as JsonDict val content = eventData["content"] as JsonDict
val stateKey = "_$userId" val stateKey = "_$userId"
room.sendStateEvent(
eventType = EventType.BOT_OPTIONS, launchWidgetAPIAction(widgetPostAPIMediator, eventData) {
stateKey = stateKey, room.sendStateEvent(
body = content, eventType = EventType.BOT_OPTIONS,
callback = createWidgetAPICallback(widgetPostAPIMediator, eventData) stateKey = stateKey,
) body = content
)
}
} }
/** /**
@ -456,4 +462,19 @@ class WidgetPostAPIHandler @AssistedInject constructor(@Assisted private val roo
private fun createWidgetAPICallback(widgetPostAPIMediator: WidgetPostAPIMediator, eventData: JsonDict): WidgetAPICallback { private fun createWidgetAPICallback(widgetPostAPIMediator: WidgetPostAPIMediator, eventData: JsonDict): WidgetAPICallback {
return WidgetAPICallback(widgetPostAPIMediator, eventData, stringProvider) return WidgetAPICallback(widgetPostAPIMediator, eventData, stringProvider)
} }
private fun launchWidgetAPIAction(widgetPostAPIMediator: WidgetPostAPIMediator, eventData: JsonDict, block: suspend () -> Unit): Job {
return GlobalScope.launch {
kotlin.runCatching {
block()
}.fold(
onSuccess = {
widgetPostAPIMediator.sendSuccess(eventData)
},
onFailure = {
widgetPostAPIMediator.sendError(stringProvider.getString(R.string.widget_integration_failed_to_send_request), eventData)
}
)
}
}
} }