refactor: Make direct chat getter type safe

This also makes sure that we
do not accidentally change
it in RAM before the
change comes from the server
when calling
addToDirectChat()
This commit is contained in:
Christian Kußowski 2025-11-11 09:16:30 +01:00
parent c839b95e31
commit 4a4ccfd4e8
No known key found for this signature in database
GPG Key ID: E067ECD60F1A0652
4 changed files with 19 additions and 15 deletions

View File

@ -2735,8 +2735,6 @@ class FakeMatrixApi extends BaseClient {
(var req) => {},
'/client/v3/user/%40test%3AfakeServer.notExisting/rooms/!localpart%3Aserver.abc/account_data/m.marked_unread':
(var req) => {},
'/client/v3/user/%40test%3AfakeServer.notExisting/account_data/m.direct':
(var req) => {},
'/client/v3/user/%40othertest%3AfakeServer.notExisting/account_data/m.direct':
(var req) => {},
'/client/v3/profile/%40alice%3Aexample.com/displayname': (var reqI) => {},

View File

@ -439,8 +439,13 @@ class Client extends MatrixApi {
return null;
}
Map<String, dynamic> get directChats =>
_accountData['m.direct']?.content ?? {};
Map<String, List<String>> get directChats =>
(_accountData['m.direct']?.content ?? {}).map(
(userId, list) => MapEntry(
userId,
(list is! List) ? [] : list.whereType<String>().toList(),
),
);
/// Returns the first room ID from the store (the room with the latest event)
/// which is a private chat with the user [userId].

View File

@ -349,7 +349,7 @@ class Room {
final cache = _cachedDirectChatMatrixId;
if (cache != null) {
final roomIds = client.directChats[cache];
if (roomIds is List && roomIds.contains(id)) {
if (roomIds != null && roomIds.contains(id)) {
return cache;
}
}
@ -1519,21 +1519,21 @@ class Room {
/// Sets this room as a direct chat for this user if not already.
Future<void> addToDirectChat(String userID) async {
final directChats = client.directChats;
if (directChats[userID] is List) {
if (!directChats[userID].contains(id)) {
directChats[userID].add(id);
} else {
return;
} // Is already in direct chats
} else {
directChats[userID] = [id];
final dmRooms = List<String>.from(client.directChats[userID] ?? []);
if (dmRooms.contains(id)) {
Logs().d('Already a direct chat.');
return;
}
dmRooms.add(id);
await client.setAccountData(
client.userID!,
'm.direct',
directChats,
{
...client.directChats,
userID: dmRooms,
},
);
return;
}

View File

@ -139,6 +139,7 @@ void main() async {
await user1.setPower(50);
});
test('startDirectChat', () async {
FakeMatrixApi.client = user1.room.client;
await user1.startDirectChat(waitForSync: false);
});
test('getPresence', () async {