From 252d7cbeb781690474e04ba5c55512e83c7964c4 Mon Sep 17 00:00:00 2001 From: Malin Errenst Date: Tue, 3 Sep 2024 22:17:37 +0200 Subject: [PATCH] fix: Delete empty dm room on createRoom error --- lib/src/client.dart | 56 +++++++++++++++++++++++++++++++-------------- 1 file changed, 39 insertions(+), 17 deletions(-) diff --git a/lib/src/client.dart b/lib/src/client.dart index 77fbb5f5..08b6bacf 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -795,27 +795,49 @@ class Client extends MatrixApi { )); } } + try { + // Start a new direct chat + final roomId = await createRoom( + invite: [mxid], + isDirect: true, + preset: preset, + initialState: initialState, + powerLevelContentOverride: powerLevelContentOverride, + ); - // Start a new direct chat - final roomId = await createRoom( - invite: [mxid], - isDirect: true, - preset: preset, - initialState: initialState, - powerLevelContentOverride: powerLevelContentOverride, - ); - - if (waitForSync) { - final room = getRoomById(roomId); - if (room == null || room.membership != Membership.join) { - // Wait for room actually appears in sync - await waitForRoomInSync(roomId, join: true); + if (waitForSync) { + final room = getRoomById(roomId); + if (room == null || room.membership != Membership.join) { + // Wait for room actually appears in sync + await waitForRoomInSync(roomId, join: true); + } } - } - await Room(id: roomId, client: this).addToDirectChat(mxid); + await Room(id: roomId, client: this).addToDirectChat(mxid); - return roomId; + return roomId; + } catch (e) { + /// This looks up the room id of the room that was just created. + /// The room is empty since createRoom threw an error. To make sure not to + /// delete other empty rooms by accident, the creation time is checked. + /// Should be fixed in Synapse and then be removed + final sortedRooms = rooms.sortedBy((room) => room.timeCreated).reversed; + final emptyRoom = sortedRooms.firstWhereOrNull((room) => + room.name.isEmpty && + !room.isDirectChat && + room.summary.mJoinedMemberCount == 1 && + room.summary.mInvitedMemberCount == 0 && + room.timeCreated + .isAfter(DateTime.now().subtract(Duration(seconds: 20)))); + final roomId = emptyRoom?.id; + + /// If we can find an empty unnamed room that was recently created, we leave and delete it + if (roomId != null) { + await leaveRoom(roomId); + await forgetRoom(roomId); + } + rethrow; + } } /// Simplified method to create a new group chat. By default it is a private