Skip to content

Commit

Permalink
refactor: Make direct chat getter type safe
Browse files Browse the repository at this point in the history
This also makes sure that we
do not accidentally change
it in RAM before the
change comes from the server
when calling
addToDirectChat()
  • Loading branch information
krille-chan committed Jan 20, 2025
1 parent e0c1c7b commit c0a1002
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 13 deletions.
9 changes: 7 additions & 2 deletions lib/src/client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -442,8 +442,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 which is a private chat with the user [userId].
/// Returns null if there is none.
Expand Down
22 changes: 11 additions & 11 deletions lib/src/room.dart
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,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;
}
}
Expand Down Expand Up @@ -1372,21 +1372,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;
}
Expand Down

0 comments on commit c0a1002

Please sign in to comment.