Skip to content

Commit

Permalink
fix: Change power level without changing memory
Browse files Browse the repository at this point in the history
The problem here is that we
have not created a deep copy
of the power level map. By using .copy() we create a
deep copy now.
  • Loading branch information
krille-chan committed Oct 4, 2024
1 parent 71180de commit 3de1c17
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
16 changes: 6 additions & 10 deletions lib/src/room.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1187,22 +1187,18 @@ class Room {
/// Set the power level of the user with the [userID] to the value [power].
/// Returns the event ID of the new state event. If there is no known
/// power level event, there might something broken and this returns null.
Future<String> setPower(String userID, int power) async {
final powerMap = Map<String, Object?>.from(
getState(EventTypes.RoomPowerLevels)?.content ?? {},
);

final usersPowerMap = powerMap['users'] is Map<String, Object?>
? powerMap['users'] as Map<String, Object?>
: (powerMap['users'] = <String, Object?>{});
Future<String> setPower(String userId, int power) async {
final powerLevelMapCopy =
getState(EventTypes.RoomPowerLevels)?.content.copy() ?? {};

usersPowerMap[userID] = power;
powerLevelMapCopy['users'] ??= <String, Object?>{};
powerLevelMapCopy.tryGetMap<String, Object?>('users')?[userId] = power;

return await client.setRoomStateWithKey(
id,
EventTypes.RoomPowerLevels,
'',
powerMap,
powerLevelMapCopy,
);
}

Expand Down
14 changes: 14 additions & 0 deletions test/room_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -786,6 +786,20 @@ void main() {
await room.invite('Testname');
});

test('setPower', () async {
final powerLevelMap =
room.getState(EventTypes.RoomPowerLevels, '')!.content.copy();

// Request to fake api does not update anything:
await room.setPower('@bob:fakeServer.notExisting', 100);

// Original power level map has not changed:
expect(
powerLevelMap,
room.getState(EventTypes.RoomPowerLevels, '')!.content.copy(),
);
});

test('getParticipants', () async {
var userList = room.getParticipants();
expect(userList.length, 4);
Expand Down

0 comments on commit 3de1c17

Please sign in to comment.