refactor: Remove duplicated copyMap method and fix type error

dynamic.copy returned a type
error so I reverted the previous
change of the copyMap
method to an extension. Also
I found out that we have used
two copyMap methods in the
SDK which did exactly the same.
I deleted the old one and
changed the tests.
This commit is contained in:
Krille 2023-12-11 10:29:06 +01:00
parent 0b29c3a034
commit c3c770bc33
No known key found for this signature in database
7 changed files with 77 additions and 110 deletions

View File

@ -28,6 +28,7 @@ import 'package:matrix/encryption/olm_manager.dart';
import 'package:matrix/encryption/ssss.dart';
import 'package:matrix/encryption/utils/bootstrap.dart';
import 'package:matrix/matrix.dart';
import 'package:matrix/src/utils/copy_map.dart';
import 'package:matrix/src/utils/run_in_root.dart';
class Encryption {

View File

@ -672,7 +672,7 @@ class HiveCollectionsDatabase extends DatabaseApi {
final copiedRaws = raws.entries.map((entry) {
final copiedRaw = copyMap(entry.value);
copiedRaw['id'] = int.parse(entry.key);
copiedRaw['content'] = jsonDecode(copiedRaw['content']);
copiedRaw['content'] = jsonDecode(copiedRaw['content'] as String);
return copiedRaw;
}).toList();
return copiedRaws.map((raw) => QueuedToDeviceEvent.fromJson(raw)).toList();
@ -1620,5 +1620,3 @@ class TupleKey {
@override
int get hashCode => Object.hashAll(parts);
}
Map<String, dynamic> copyMap(Map map) => map.copy;

View File

@ -28,6 +28,7 @@ import 'package:matrix/encryption/utils/outbound_group_session.dart';
import 'package:matrix/encryption/utils/ssss_cache.dart';
import 'package:matrix/encryption/utils/stored_inbound_group_session.dart';
import 'package:matrix/matrix.dart';
import 'package:matrix/src/utils/copy_map.dart';
import 'package:matrix/src/utils/queued_to_device_event.dart';
import 'package:matrix/src/utils/run_benchmarked.dart';

View File

@ -354,7 +354,7 @@ class MatrixSdkDatabase extends DatabaseApi {
for (final entry in raws.entries) {
accountData[entry.key] = BasicEvent(
type: entry.key,
content: entry.value.copy,
content: copyMap(entry.value),
);
}
return accountData;
@ -378,7 +378,7 @@ class MatrixSdkDatabase extends DatabaseApi {
Future<Event?> getEventById(String eventId, Room room) async {
final raw = await _eventsBox.get(TupleKey(room.id, eventId).toString());
if (raw == null) return null;
return Event.fromJson(raw.copy, room);
return Event.fromJson(copyMap(raw), room);
}
/// Loads a whole list of events at once from the store for a specific room
@ -391,7 +391,7 @@ class MatrixSdkDatabase extends DatabaseApi {
final rawEvents = await _eventsBox.getAll(keys);
return rawEvents
.whereType<Map>()
.map((rawEvent) => Event.fromJson(rawEvent.copy, room))
.map((rawEvent) => Event.fromJson(copyMap(rawEvent), room))
.toList();
}
@ -448,7 +448,7 @@ class MatrixSdkDatabase extends DatabaseApi {
) async {
final raw = await _inboundGroupSessionsBox.get(sessionId);
if (raw == null) return null;
return StoredInboundGroupSession.fromJson(raw.copy);
return StoredInboundGroupSession.fromJson(copyMap(raw));
}
@override
@ -460,7 +460,7 @@ class MatrixSdkDatabase extends DatabaseApi {
.take(50)
.map(
(json) => StoredInboundGroupSession.fromJson(
json.copy,
copyMap(json),
),
)
.toList();
@ -479,7 +479,7 @@ class MatrixSdkDatabase extends DatabaseApi {
@override
Future<void> storeOlmSession(String identityKey, String sessionId,
String pickle, int lastReceived) async {
final rawSessions = (await _olmSessionsBox.get(identityKey))?.copy ?? {};
final rawSessions = copyMap((await _olmSessionsBox.get(identityKey)) ?? {});
rawSessions[sessionId] = {
'identity_key': identityKey,
'pickle': pickle,
@ -517,7 +517,7 @@ class MatrixSdkDatabase extends DatabaseApi {
String roomId, String userId) async {
final raw = await _outboundGroupSessionsBox.get(roomId);
if (raw == null) return null;
return OutboundGroupSession.fromJson(raw.copy, userId);
return OutboundGroupSession.fromJson(copyMap(raw), userId);
}
@override
@ -526,7 +526,7 @@ class MatrixSdkDatabase extends DatabaseApi {
// Get raw room from database:
final roomData = await _roomsBox.get(roomId);
if (roomData == null) return null;
final room = Room.fromJson(roomData.copy, client);
final room = Room.fromJson(copyMap(roomData), client);
// Get important states:
if (loadImportantStates) {
@ -536,7 +536,7 @@ class MatrixSdkDatabase extends DatabaseApi {
final rawStates = await _preloadRoomStateBox.getAll(dbKeys);
for (final rawState in rawStates) {
if (rawState == null || rawState[''] == null) continue;
room.setState(Event.fromJson(rawState[''].copy, room));
room.setState(Event.fromJson(copyMap(rawState['']), room));
}
}
@ -552,7 +552,7 @@ class MatrixSdkDatabase extends DatabaseApi {
for (final raw in rawRooms.values) {
// Get the room
final room = Room.fromJson(raw.copy, client);
final room = Room.fromJson(copyMap(raw), client);
// Add to the list and continue.
rooms[room.id] = room;
@ -569,7 +569,7 @@ class MatrixSdkDatabase extends DatabaseApi {
}
final states = entry.value;
final stateEvents = states.values
.map((raw) => Event.fromJson(raw.copy, room))
.map((raw) => Event.fromJson(copyMap(raw), room))
.toList();
for (final state in stateEvents) {
room.setState(state);
@ -581,7 +581,7 @@ class MatrixSdkDatabase extends DatabaseApi {
for (final entry in roomAccountDataRaws.entries) {
final keys = TupleKey.fromString(entry.key);
final basicRoomEvent = BasicRoomEvent.fromJson(
entry.value.copy,
copyMap(entry.value),
);
final roomId = keys.parts.first;
if (rooms.containsKey(roomId)) {
@ -602,14 +602,14 @@ class MatrixSdkDatabase extends DatabaseApi {
Future<SSSSCache?> getSSSSCache(String type) async {
final raw = await _ssssCacheBox.get(type);
if (raw == null) return null;
return SSSSCache.fromJson(raw.copy);
return SSSSCache.fromJson(copyMap(raw));
}
@override
Future<List<QueuedToDeviceEvent>> getToDeviceEventQueue() async {
final raws = await _toDeviceQueueBox.getAllValues();
final copiedRaws = raws.entries.map((entry) {
final copiedRaw = entry.value.copy;
final copiedRaw = copyMap(entry.value);
copiedRaw['id'] = int.parse(entry.key);
copiedRaw['content'] = jsonDecode(copiedRaw['content'] as String);
return copiedRaw;
@ -629,8 +629,8 @@ class MatrixSdkDatabase extends DatabaseApi {
for (final key in keys) {
final states = await _nonPreloadRoomStateBox.get(key);
if (states == null) continue;
unimportantEvents
.addAll(states.values.map((raw) => Event.fromJson(raw.copy, room)));
unimportantEvents.addAll(
states.values.map((raw) => Event.fromJson(copyMap(raw), room)));
}
return unimportantEvents;
}
@ -640,7 +640,7 @@ class MatrixSdkDatabase extends DatabaseApi {
final state =
await _roomMembersBox.get(TupleKey(room.id, userId).toString());
if (state == null) return null;
return Event.fromJson(state.copy, room).asUser;
return Event.fromJson(copyMap(state), room).asUser;
}
@override
@ -670,14 +670,14 @@ class MatrixSdkDatabase extends DatabaseApi {
(key) {
final userDeviceKey = userDeviceKeys[key];
if (userDeviceKey == null) return null;
return userDeviceKey.copy;
return copyMap(userDeviceKey);
},
);
final crossSigningEntries = crossSigningKeysBoxKeys.map(
(key) {
final crossSigningKey = userCrossSigningKeys[key];
if (crossSigningKey == null) return null;
return crossSigningKey.copy;
return copyMap(crossSigningKey);
},
);
res[userId] = DeviceKeysList.fromDbJson(
@ -708,7 +708,7 @@ class MatrixSdkDatabase extends DatabaseApi {
final states = await _roomMembersBox.getAll(keys);
states.removeWhere((state) => state == null);
for (final state in states) {
users.add(Event.fromJson(state!.copy, room).asUser);
users.add(Event.fromJson(copyMap(state!), room).asUser);
}
return users;
@ -768,7 +768,9 @@ class MatrixSdkDatabase extends DatabaseApi {
@override
Future<void> markInboundGroupSessionAsUploaded(
String roomId, String sessionId) async {
final raw = (await _inboundGroupSessionsBox.get(sessionId) ?? {}).copy;
final raw = copyMap(
await _inboundGroupSessionsBox.get(sessionId) ?? {},
);
if (raw.isEmpty) {
Logs().w(
'Tried to mark inbound group session as uploaded which was not found in the database!');
@ -783,7 +785,9 @@ class MatrixSdkDatabase extends DatabaseApi {
Future<void> markInboundGroupSessionsAsNeedingUpload() async {
final keys = await _inboundGroupSessionsBox.getAllKeys();
for (final sessionId in keys) {
final raw = (await _inboundGroupSessionsBox.get(sessionId) ?? {}).copy;
final raw = copyMap(
await _inboundGroupSessionsBox.get(sessionId) ?? {},
);
if (raw.isEmpty) continue;
raw['uploaded'] = false;
await _inboundGroupSessionsBox.put(sessionId, raw);
@ -831,10 +835,11 @@ class MatrixSdkDatabase extends DatabaseApi {
@override
Future<void> setBlockedUserCrossSigningKey(
bool blocked, String userId, String publicKey) async {
final raw = (await _userCrossSigningKeysBox
final raw = copyMap(
await _userCrossSigningKeysBox
.get(TupleKey(userId, publicKey).toString()) ??
{})
.copy;
{},
);
raw['blocked'] = blocked;
await _userCrossSigningKeysBox.put(
TupleKey(userId, publicKey).toString(),
@ -846,10 +851,9 @@ class MatrixSdkDatabase extends DatabaseApi {
@override
Future<void> setBlockedUserDeviceKey(
bool blocked, String userId, String deviceId) async {
final raw =
(await _userDeviceKeysBox.get(TupleKey(userId, deviceId).toString()) ??
{})
.copy;
final raw = copyMap(
await _userDeviceKeysBox.get(TupleKey(userId, deviceId).toString()) ?? {},
);
raw['blocked'] = blocked;
await _userDeviceKeysBox.put(
TupleKey(userId, deviceId).toString(),
@ -861,10 +865,9 @@ class MatrixSdkDatabase extends DatabaseApi {
@override
Future<void> setLastActiveUserDeviceKey(
int lastActive, String userId, String deviceId) async {
final raw =
(await _userDeviceKeysBox.get(TupleKey(userId, deviceId).toString()) ??
{})
.copy;
final raw = copyMap(
await _userDeviceKeysBox.get(TupleKey(userId, deviceId).toString()) ?? {},
);
raw['last_active'] = lastActive;
await _userDeviceKeysBox.put(
@ -876,10 +879,9 @@ class MatrixSdkDatabase extends DatabaseApi {
@override
Future<void> setLastSentMessageUserDeviceKey(
String lastSentMessage, String userId, String deviceId) async {
final raw =
(await _userDeviceKeysBox.get(TupleKey(userId, deviceId).toString()) ??
{})
.copy;
final raw = copyMap(
await _userDeviceKeysBox.get(TupleKey(userId, deviceId).toString()) ?? {},
);
raw['last_sent_message'] = lastSentMessage;
await _userDeviceKeysBox.put(
TupleKey(userId, deviceId).toString(),
@ -892,7 +894,7 @@ class MatrixSdkDatabase extends DatabaseApi {
String? prevBatch, String roomId, Client client) async {
final raw = await _roomsBox.get(roomId);
if (raw == null) return;
final room = Room.fromJson(raw.copy, client);
final room = Room.fromJson(copyMap(raw), client);
room.prev_batch = prevBatch;
await _roomsBox.put(roomId, room.toJson());
return;
@ -901,10 +903,11 @@ class MatrixSdkDatabase extends DatabaseApi {
@override
Future<void> setVerifiedUserCrossSigningKey(
bool verified, String userId, String publicKey) async {
final raw = ((await _userCrossSigningKeysBox
final raw = copyMap(
(await _userCrossSigningKeysBox
.get(TupleKey(userId, publicKey).toString())) ??
{})
.copy;
{},
);
raw['verified'] = verified;
await _userCrossSigningKeysBox.put(
TupleKey(userId, publicKey).toString(),
@ -916,10 +919,9 @@ class MatrixSdkDatabase extends DatabaseApi {
@override
Future<void> setVerifiedUserDeviceKey(
bool verified, String userId, String deviceId) async {
final raw =
(await _userDeviceKeysBox.get(TupleKey(userId, deviceId).toString()) ??
{})
.copy;
final raw = copyMap(
await _userDeviceKeysBox.get(TupleKey(userId, deviceId).toString()) ?? {},
);
raw['verified'] = verified;
await _userDeviceKeysBox.put(
TupleKey(userId, deviceId).toString(),
@ -978,7 +980,7 @@ class MatrixSdkDatabase extends DatabaseApi {
final prevStatus = prevEvent == null
? null
: () {
final json = prevEvent.copy;
final json = copyMap(prevEvent);
final statusInt = json.tryGet<int>('status') ??
json
.tryGetMap<String, dynamic>('unsigned')
@ -1087,7 +1089,7 @@ class MatrixSdkDatabase extends DatabaseApi {
eventUpdate.roomID,
type,
).toString();
final stateMap = (await roomStateBox.get(key) ?? {}).copy;
final stateMap = copyMap(await roomStateBox.get(key) ?? {});
// store state events and new messages, that either are not an edit or an edit of the lastest message
// An edit is an event, that has an edit relation to the latest event. In some cases for the second edit, we need to compare if both have an edit relation to the same event instead.
if (eventUpdate.content
@ -1240,7 +1242,7 @@ class MatrixSdkDatabase extends DatabaseApi {
membership: membership,
).toJson());
} else if (roomUpdate is JoinedRoomUpdate) {
final currentRoom = Room.fromJson((currentRawRoom).copy, client);
final currentRoom = Room.fromJson(copyMap(currentRawRoom), client);
await _roomsBox.put(
roomId,
Room(
@ -1397,7 +1399,7 @@ class MatrixSdkDatabase extends DatabaseApi {
'Tried to update inbound group session indexes of a session which was not found in the database!');
return;
}
final json = raw.copy;
final json = copyMap(raw);
json['indexes'] = indexes;
await _inboundGroupSessionsBox.put(sessionId, json);
return;
@ -1407,7 +1409,7 @@ class MatrixSdkDatabase extends DatabaseApi {
Future<List<StoredInboundGroupSession>> getAllInboundGroupSessions() async {
final rawSessions = await _inboundGroupSessionsBox.getAllValues();
return rawSessions.values
.map((raw) => StoredInboundGroupSession.fromJson(raw.copy))
.map((raw) => StoredInboundGroupSession.fromJson(copyMap(raw)))
.toList();
}
@ -1592,6 +1594,6 @@ class MatrixSdkDatabase extends DatabaseApi {
final rawPresence = await _presencesBox.get(userId);
if (rawPresence == null) return null;
return CachedPresence.fromJson(rawPresence.copy);
return CachedPresence.fromJson(copyMap(rawPresence));
}
}

View File

@ -1,9 +1,8 @@
/// The database always gives back an `_InternalLinkedHasMap<dynamic, dynamic>`.
/// This creates a deep copy of the json and makes sure that the format is
/// always `Map<String, Object?>`.
extension CopyMapExtension on Map {
Map<String, Object?> get copy {
final copy = Map<String, dynamic>.from(this);
Map<String, Object?> copyMap(Map map) {
final copy = Map<String, dynamic>.from(map);
for (final entry in copy.entries) {
copy[entry.key] = _castValue(entry.value);
}
@ -12,11 +11,10 @@ extension CopyMapExtension on Map {
dynamic _castValue(dynamic value) {
if (value is Map) {
return value.copy;
return copyMap(value);
}
if (value is List) {
return value.map(_castValue).toList();
}
return value;
}
}

View File

@ -1,33 +0,0 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
extension MapCopyExtension on Map<String, dynamic> {
/// Deep-copies a given json map
Map<String, dynamic> copy() {
final copy = Map<String, dynamic>.from(this);
for (final entry in copy.entries) {
if (entry.value is Map<String, dynamic>) {
copy[entry.key] = (entry.value as Map<String, dynamic>).copy();
}
if (entry.value is List) {
copy[entry.key] = List.from(entry.value);
}
}
return copy;
}
}

View File

@ -18,7 +18,7 @@
import 'package:test/test.dart';
import 'package:matrix/src/utils/map_copy_extension.dart';
import 'package:matrix/src/utils/copy_map.dart';
void main() {
group('Map-copy-extension', () {
@ -30,11 +30,11 @@ void main() {
'list': [1, 2],
},
};
final copy = original.copy();
final copy = copyMap(original);
original['child']['attr'] = 'raccoon';
expect(copy['child']['attr'], 'bunny');
expect((copy['child'] as Map)['attr'], 'bunny');
original['child']['list'].add(3);
expect(copy['child']['list'], [1, 2]);
expect((copy['child'] as Map)['list'], [1, 2]);
});
});
}