fix: Make Client.findDM return a Result (#4816)

This commit is contained in:
Jorge Martin Espinosa 2025-06-04 10:41:26 +02:00 committed by GitHub
parent 0aa1a258e4
commit c02c1ae1bd
7 changed files with 44 additions and 22 deletions

View file

@ -55,7 +55,7 @@ interface MatrixClient {
val ignoredUsersFlow: StateFlow<ImmutableList<UserId>>
suspend fun getJoinedRoom(roomId: RoomId): JoinedRoom?
suspend fun getRoom(roomId: RoomId): BaseRoom?
suspend fun findDM(userId: UserId): RoomId?
suspend fun findDM(userId: UserId): Result<RoomId?>
suspend fun ignoreUser(userId: UserId): Result<Unit>
suspend fun unignoreUser(userId: UserId): Result<Unit>
suspend fun createRoom(createRoomParams: CreateRoomParameters): Result<RoomId>

View file

@ -18,17 +18,24 @@ suspend fun MatrixClient.startDM(
userId: UserId,
createIfDmDoesNotExist: Boolean,
): StartDMResult {
val existingDM = findDM(userId)
return if (existingDM != null) {
StartDMResult.Success(existingDM, isNew = false)
} else if (createIfDmDoesNotExist) {
createDM(userId).fold(
{ StartDMResult.Success(it, isNew = true) },
{ StartDMResult.Failure(it) }
return findDM(userId)
.fold(
onSuccess = { existingDM ->
if (existingDM != null) {
StartDMResult.Success(existingDM, isNew = false)
} else if (createIfDmDoesNotExist) {
createDM(userId).fold(
{ StartDMResult.Success(it, isNew = true) },
{ StartDMResult.Failure(it) }
)
} else {
StartDMResult.DmDoesNotExist
}
},
onFailure = { error ->
StartDMResult.Failure(error)
}
)
} else {
StartDMResult.DmDoesNotExist
}
}
sealed interface StartDMResult {

View file

@ -297,8 +297,10 @@ class RustMatrixClient(
}
}
override suspend fun findDM(userId: UserId): RoomId? = withContext(sessionDispatcher) {
innerClient.getDmRoom(userId.value)?.use { RoomId(it.id()) }
override suspend fun findDM(userId: UserId): Result<RoomId?> = withContext(sessionDispatcher) {
runCatchingExceptions {
innerClient.getDmRoom(userId.value)?.use { RoomId(it.id()) }
}
}
override suspend fun ignoreUser(userId: UserId): Result<Unit> = withContext(sessionDispatcher) {

View file

@ -103,7 +103,7 @@ class FakeMatrixClient(
private var createRoomResult: Result<RoomId> = Result.success(A_ROOM_ID)
private var createDmResult: Result<RoomId> = Result.success(A_ROOM_ID)
private var findDmResult: RoomId? = A_ROOM_ID
private var findDmResult: Result<RoomId?> = Result.success(A_ROOM_ID)
private val getRoomResults = mutableMapOf<RoomId, BaseRoom>()
private val searchUserResults = mutableMapOf<String, Result<MatrixSearchUserResults>>()
private val getProfileResults = mutableMapOf<UserId, Result<MatrixUser>>()
@ -133,7 +133,7 @@ class FakeMatrixClient(
return getRoomResults[roomId] as? JoinedRoom
}
override suspend fun findDM(userId: UserId): RoomId? {
override suspend fun findDM(userId: UserId): Result<RoomId?> {
return findDmResult
}
@ -248,7 +248,7 @@ class FakeMatrixClient(
createDmResult = result
}
fun givenFindDmResult(result: RoomId?) {
fun givenFindDmResult(result: Result<RoomId?>) {
findDmResult = result
}