From ffef73210329f205e2ed9ca0500a868a1271b141 Mon Sep 17 00:00:00 2001 From: Christian Pauly Date: Wed, 14 Apr 2021 10:29:12 +0200 Subject: [PATCH] refactor: enable more linter rules enable prefer_final_locals and prefer_final_in_for_each linter rules --- analysis_options.yaml | 2 + lib/encryption/encryption.dart | 5 +- lib/encryption/key_manager.dart | 4 +- lib/encryption/olm_manager.dart | 19 ++++---- lib/src/client.dart | 48 +++++++++---------- lib/src/event.dart | 10 ++-- lib/src/room.dart | 32 ++++++------- lib/src/timeline.dart | 8 ++-- lib/src/user.dart | 4 +- lib/src/utils/event_localizations.dart | 6 +-- lib/src/utils/event_update.dart | 2 +- lib/src/utils/markdown.dart | 2 +- test/canonical_json_test.dart | 2 +- test/client_test.dart | 28 +++++------ test/commands_test.dart | 12 ++--- test/encryption/cross_signing_test.dart | 2 +- .../encrypt_decrypt_to_device_test.dart | 2 +- test/encryption/key_request_test.dart | 8 ++-- test/encryption/key_verification_test.dart | 2 +- test/encryption/online_key_backup_test.dart | 2 +- test/event_test.dart | 47 +++++++++--------- test/matrix_database_test.dart | 2 +- test/mxc_uri_extension_test.dart | 2 +- test/room_test.dart | 8 ++-- test/sync_filter_test.dart | 6 +-- test/timeline_test.dart | 2 +- test/uia_test.dart | 2 +- test/user_test.dart | 4 +- test_driver/famedlysdk_test.dart | 11 +++-- 29 files changed, 145 insertions(+), 139 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index bb697490..0affb20f 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -5,6 +5,8 @@ linter: - camel_case_types - avoid_print - constant_identifier_names + - prefer_final_locals + - prefer_final_in_for_each analyzer: errors: diff --git a/lib/encryption/encryption.dart b/lib/encryption/encryption.dart index 721b0e3e..c2a5a566 100644 --- a/lib/encryption/encryption.dart +++ b/lib/encryption/encryption.dart @@ -199,7 +199,8 @@ class Encryption { final messageIndexValue = event.eventId + '|' + event.originServerTs.millisecondsSinceEpoch.toString(); - var haveIndex = inboundGroupSession.indexes.containsKey(messageIndexKey); + final haveIndex = + inboundGroupSession.indexes.containsKey(messageIndexKey); if (haveIndex && inboundGroupSession.indexes[messageIndexKey] != messageIndexValue) { Logs().e('[Decrypt] Could not decrypt due to a corrupted session.'); @@ -342,7 +343,7 @@ class Encryption { 'type': type, 'room_id': roomId, }; - var encryptedPayload = { + final encryptedPayload = { 'algorithm': AlgorithmTypes.megolmV1AesSha2, 'ciphertext': sess.outboundGroupSession.encrypt(json.encode(payloadContent)), diff --git a/lib/encryption/key_manager.dart b/lib/encryption/key_manager.dart index e6994fee..1ae95baf 100644 --- a/lib/encryption/key_manager.dart +++ b/lib/encryption/key_manager.dart @@ -625,7 +625,7 @@ class KeyManager { }) async { if (tryOnlineBackup && await isCached()) { // let's first check our online key backup store thingy... - var hadPreviously = + final hadPreviously = getInboundGroupSession(room.id, sessionId, senderKey) != null; try { await loadSingleKey(room.id, sessionId); @@ -894,7 +894,7 @@ class KeyManager { 'request_id': request.requestId, 'requesting_device_id': client.deviceID, }; - var data = >>{}; + final data = >>{}; for (final device in request.devices) { if (!data.containsKey(device.userId)) { data[device.userId] = {}; diff --git a/lib/encryption/olm_manager.dart b/lib/encryption/olm_manager.dart index 529e7587..9ad55d7c 100644 --- a/lib/encryption/olm_manager.dart +++ b/lib/encryption/olm_manager.dart @@ -338,7 +338,7 @@ class OlmManager { } }); if (existingSessions != null) { - for (var session in existingSessions) { + for (final session in existingSessions) { if (type == 0 && session.session.matches_inbound(body) == true) { try { plaintext = session.session.decrypt(type, body); @@ -365,7 +365,7 @@ class OlmManager { } if (plaintext == null) { - var newSession = olm.Session(); + final newSession = olm.Session(); try { newSession.create_inbound_from(_olmAccount, senderKey, body); _olmAccount.remove_one_time_keys(newSession); @@ -518,8 +518,8 @@ class OlmManager { Future startOutgoingOlmSessions(List deviceKeys) async { Logs().v( '[OlmManager] Starting session with ${deviceKeys.length} devices...'); - var requestingKeysFrom = >{}; - for (var device in deviceKeys) { + final requestingKeysFrom = >{}; + for (final device in deviceKeys) { if (requestingKeysFrom[device.userId] == null) { requestingKeysFrom[device.userId] = {}; } @@ -529,20 +529,21 @@ class OlmManager { final response = await client.requestOneTimeKeys(requestingKeysFrom, timeout: 10000); - for (var userKeysEntry in response.oneTimeKeys.entries) { + for (final userKeysEntry in response.oneTimeKeys.entries) { final userId = userKeysEntry.key; - for (var deviceKeysEntry in userKeysEntry.value.entries) { + for (final deviceKeysEntry in userKeysEntry.value.entries) { final deviceId = deviceKeysEntry.key; final fingerprintKey = client.userDeviceKeys[userId].deviceKeys[deviceId].ed25519Key; final identityKey = client.userDeviceKeys[userId].deviceKeys[deviceId].curve25519Key; - for (Map deviceKey in deviceKeysEntry.value.values) { + for (final Map deviceKey + in deviceKeysEntry.value.values) { if (!deviceKey.checkJsonSignature(fingerprintKey, userId, deviceId)) { continue; } Logs().v('[OlmManager] Starting session with $userId:$deviceId'); - var session = olm.Session(); + final session = olm.Session(); try { session.create_outbound(_olmAccount, identityKey, deviceKey['key']); await storeOlmSession(OlmSession( @@ -608,7 +609,7 @@ class OlmManager { List deviceKeys, String type, Map payload) async { - var data = >>{}; + final data = >>{}; // first check if any of our sessions we want to encrypt for are in the database if (client.database != null) { await getOlmSessionsForDevicesFromDatabase( diff --git a/lib/src/client.dart b/lib/src/client.dart index 961bd6c0..1b0d475a 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -560,8 +560,8 @@ class Client extends MatrixApi { /// profile will be requested from the homserver. Future get ownProfile async { if (rooms.isNotEmpty) { - var profileSet = {}; - for (var room in rooms) { + final profileSet = {}; + for (final room in rooms) { final user = room.getUserByMXIDSync(userID); profileSet.add(Profile.fromJson(user.content)); } @@ -604,16 +604,16 @@ class Client extends MatrixApi { } Future> get archive async { - var archiveList = []; + final archiveList = []; final syncResp = await sync( filter: '{"room":{"include_leave":true,"timeline":{"limit":10}}}', timeout: 0, ); if (syncResp.rooms.leave is Map) { - for (var entry in syncResp.rooms.leave.entries) { + for (final entry in syncResp.rooms.leave.entries) { final id = entry.key; final room = entry.value; - var leftRoom = Room( + final leftRoom = Room( id: id, membership: Membership.leave, client: this, @@ -622,7 +622,7 @@ class Client extends MatrixApi { {}, mHeroes: []); if (room.timeline?.events != null) { - for (var event in room.timeline.events) { + for (final event in room.timeline.events) { leftRoom.setState(Event.fromMatrixEvent( event, leftRoom, @@ -631,7 +631,7 @@ class Client extends MatrixApi { } } if (room.state != null) { - for (var event in room.state) { + for (final event in room.state) { leftRoom.setState(Event.fromMatrixEvent( event, leftRoom, @@ -1161,7 +1161,7 @@ class Client extends MatrixApi { final id = entry.key; final room = entry.value; - var update = RoomUpdate.fromSyncRoomUpdate(room, id); + final update = RoomUpdate.fromSyncRoomUpdate(room, id); if (database != null) { // TODO: This method seems to be rather slow for some updates // Perhaps don't dynamically build that one query? @@ -1251,14 +1251,14 @@ class Client extends MatrixApi { var room = getRoomById(id); room ??= Room(id: id); - var receiptStateContent = + final receiptStateContent = room.roomAccountData['m.receipt']?.content ?? {}; - for (var eventEntry in event['content'].entries) { + for (final eventEntry in event['content'].entries) { final String eventID = eventEntry.key; if (event['content'][eventID]['m.read'] != null) { final Map userTimestampMap = event['content'][eventID]['m.read']; - for (var userTimestampMapEntry in userTimestampMap.entries) { + for (final userTimestampMapEntry in userTimestampMap.entries) { final mxid = userTimestampMapEntry.key; // Remove previous receipt event from this user @@ -1372,9 +1372,9 @@ class Client extends MatrixApi { // Does the chat already exist in the list rooms? if (!found && !isLeftRoom) { - var position = chatUpdate.membership == Membership.invite ? 0 : j; + final position = chatUpdate.membership == Membership.invite ? 0 : j; // Add the new chat to the list - var newRoom = Room( + final newRoom = Room( id: chatUpdate.id, membership: chatUpdate.membership, prev_batch: chatUpdate.prev_batch, @@ -1434,9 +1434,9 @@ class Client extends MatrixApi { case EventUpdateType.timeline: case EventUpdateType.state: case EventUpdateType.inviteState: - var stateEvent = + final stateEvent = Event.fromJson(eventUpdate.content, room, eventUpdate.sortOrder); - var prevState = room.getState(stateEvent.type, stateEvent.stateKey); + final prevState = room.getState(stateEvent.type, stateEvent.stateKey); if (eventUpdate.type == EventUpdateType.timeline && prevState != null && prevState.sortOrder > stateEvent.sortOrder) { @@ -1514,12 +1514,12 @@ sort order of ${prevState.sortOrder}. This should never happen...'''); } Future> _getUserIdsInEncryptedRooms() async { - var userIds = {}; + final userIds = {}; for (final room in rooms) { if (room.encrypted) { try { - var userList = await room.requestParticipants(); - for (var user in userList) { + final userList = await room.requestParticipants(); + for (final user in userList) { if ([Membership.join, Membership.invite] .contains(user.membership)) { userIds.add(user.id); @@ -1539,7 +1539,7 @@ sort order of ${prevState.sortOrder}. This should never happen...'''); try { if (!isLogged()) return; final dbActions = Function()>[]; - var trackedUserIds = await _getUserIdsInEncryptedRooms(); + final trackedUserIds = await _getUserIdsInEncryptedRooms(); if (!isLogged()) return; trackedUserIds.add(userID); @@ -1548,12 +1548,12 @@ sort order of ${prevState.sortOrder}. This should never happen...'''); .removeWhere((String userId, v) => !trackedUserIds.contains(userId)); // Check if there are outdated device key lists. Add it to the set. - var outdatedLists = {}; - for (var userId in trackedUserIds) { + final outdatedLists = {}; + for (final userId in trackedUserIds) { if (!userDeviceKeys.containsKey(userId)) { _userDeviceKeys[userId] = DeviceKeysList(userId, this); } - var deviceKeysList = userDeviceKeys[userId]; + final deviceKeysList = userDeviceKeys[userId]; if (deviceKeysList.outdated && (!_keyQueryFailures.containsKey(userId.domain) || DateTime.now() @@ -1791,8 +1791,8 @@ sort order of ${prevState.sortOrder}. This should never happen...'''); String messageId, }) async { // Send with send-to-device messaging - var data = >>{}; - for (var user in users) { + final data = >>{}; + for (final user in users) { data[user] = {}; data[user]['*'] = message; } diff --git a/lib/src/event.dart b/lib/src/event.dart index 413f90a3..b1706a52 100644 --- a/lib/src/event.dart +++ b/lib/src/event.dart @@ -244,7 +244,7 @@ class Event extends MatrixEvent { 'redacted_because': redactedBecause.toJson(), }; prevContent = null; - var contentKeyWhiteList = []; + final contentKeyWhiteList = []; switch (type) { case EventTypes.RoomMember: contentKeyWhiteList.add('membership'); @@ -295,8 +295,8 @@ class Event extends MatrixEvent { /// Returns a list of [Receipt] instances for this event. List get receipts { if (!(room.roomAccountData.containsKey('m.receipt'))) return []; - var receiptsList = []; - for (var entry in room.roomAccountData['m.receipt'].content.entries) { + final receiptsList = []; + for (final entry in room.roomAccountData['m.receipt'].content.entries) { if (entry.value['event_id'] == eventId) { receiptsList.add(Receipt(room.getUserByMXIDSync(entry.key), DateTime.fromMillisecondsSinceEpoch(entry.value['ts']))); @@ -486,7 +486,7 @@ class Event extends MatrixEvent { getThumbnail = mxcUrl != attachmentMxcUrl; // Is this file storeable? final thisInfoMap = getThumbnail ? thumbnailInfoMap : infoMap; - var storeable = room.client.database != null && + final storeable = room.client.database != null && thisInfoMap['size'] is int && thisInfoMap['size'] <= room.client.database.maxFileSize; @@ -676,7 +676,7 @@ class Event extends MatrixEvent { // aggregated edits if (allEditEvents.isNotEmpty) { allEditEvents.sort((a, b) => a.sortOrder - b.sortOrder > 0 ? 1 : -1); - var rawEvent = allEditEvents.last.toJson(); + final rawEvent = allEditEvents.last.toJson(); // update the content of the new event to render if (rawEvent['content']['m.new_content'] is Map) { rawEvent['content'] = rawEvent['content']['m.new_content']; diff --git a/lib/src/room.dart b/lib/src/room.dart index eb18b95e..08f52786 100644 --- a/lib/src/room.dart +++ b/lib/src/room.dart @@ -318,7 +318,7 @@ class Room { /// Returns a list of all current typing users. List get typingUsers { if (!ephemerals.containsKey('m.typing')) return []; - List typingMxid = ephemerals['m.typing'].content['user_ids']; + final List typingMxid = ephemerals['m.typing'].content['user_ids']; return typingMxid.cast().map(getUserByMXIDSync).toList(); } @@ -367,7 +367,7 @@ class Room { heroes = mHeroes; } else { if (states[EventTypes.RoomMember] is Map) { - for (var entry in states[EventTypes.RoomMember].entries) { + for (final entry in states[EventTypes.RoomMember].entries) { final state = entry.value; if (state.type == EventTypes.RoomMember && state.stateKey != client?.userID) heroes.add(state.stateKey); @@ -679,7 +679,7 @@ class Room { : null; // Send event - var content = { + final content = { 'msgtype': file.msgType, 'body': file.name, 'filename': file.name, @@ -992,7 +992,7 @@ class Room { /// Sets this room as a direct chat for this user if not already. Future addToDirectChat(String userID) async { - var directChats = client.directChats; + final directChats = client.directChats; if (directChats[userID] is List) { if (!directChats[userID].contains(id)) { directChats[userID].add(id); @@ -1013,7 +1013,7 @@ class Room { /// Removes this room from all direct chat tags. Future removeFromDirectChat() async { - var directChats = client.directChats; + final directChats = client.directChats; if (directChats[directChatMatrixID] is List && directChats[directChatMatrixID].contains(id)) { directChats[directChatMatrixID].remove(id); @@ -1112,7 +1112,7 @@ class Room { } } - var newRoomAccountData = {}; + final newRoomAccountData = {}; if (roomAccountData != null) { var rawRoomAccountData; if (roomAccountData is Future) { @@ -1160,7 +1160,7 @@ class Room { }); } - var timeline = Timeline( + final timeline = Timeline( room: this, events: events, onUpdate: onUpdate, @@ -1177,9 +1177,9 @@ class Room { /// list may not be complete. User [requestParticipants] in this /// case. List getParticipants() { - var userList = []; + final userList = []; if (states[EventTypes.RoomMember] is Map) { - for (var entry in states[EventTypes.RoomMember].entries) { + for (final entry in states[EventTypes.RoomMember].entries) { final state = entry.value; if (state.type == EventTypes.RoomMember) userList.add(state.asUser); } @@ -1216,7 +1216,7 @@ class Room { /// Checks if the local participant list of joined and invited users is complete. bool get participantListComplete { - var knownParticipants = getParticipants(); + final knownParticipants = getParticipants(); knownParticipants.removeWhere( (u) => ![Membership.join, Membership.invite].contains(u.membership)); return knownParticipants.length == @@ -1539,7 +1539,7 @@ class Room { } else { messageID = txid; } - var data = {}; + final data = {}; if (reason != null) data['reason'] = reason; return await client.redact( id, @@ -1660,8 +1660,8 @@ class Room { /// Returns all aliases for this room. List get aliases { - var aliases = []; - for (var aliasEvent in states[EventTypes.RoomAliases].values) { + final aliases = []; + for (final aliasEvent in states[EventTypes.RoomAliases].values) { if (aliasEvent.content['aliases'] is List) { aliases.addAll(aliasEvent.content['aliases']); } @@ -1765,12 +1765,12 @@ class Room { /// Returns all known device keys for all participants in this room. Future> getUserDeviceKeys() async { - var deviceKeys = []; - var users = await requestParticipants(); + final deviceKeys = []; + final users = await requestParticipants(); for (final user in users) { if ([Membership.invite, Membership.join].contains(user.membership) && client.userDeviceKeys.containsKey(user.id)) { - for (var deviceKeyEntry + for (final deviceKeyEntry in client.userDeviceKeys[user.id].deviceKeys.values) { deviceKeys.add(deviceKeyEntry); } diff --git a/lib/src/timeline.dart b/lib/src/timeline.dart index 8a347451..cb31bd58 100644 --- a/lib/src/timeline.dart +++ b/lib/src/timeline.dart @@ -262,7 +262,7 @@ class Timeline { eventUpdate.type != EventUpdateType.history) { return; } - var status = eventUpdate.content['status'] ?? + final status = eventUpdate.content['status'] ?? (eventUpdate.content['unsigned'] is Map ? eventUpdate.content['unsigned'][messageSendingStatusKey] : null) ?? @@ -276,13 +276,13 @@ class Timeline { Event.fromJson(eventUpdate.content, room, eventUpdate.sortOrder)); } } else if (status == -2) { - var i = _findEvent(event_id: eventUpdate.content['event_id']); + final i = _findEvent(event_id: eventUpdate.content['event_id']); if (i < events.length) { removeAggregatedEvent(events[i]); events.removeAt(i); } } else { - var i = _findEvent( + final i = _findEvent( event_id: eventUpdate.content['event_id'], unsigned_txid: eventUpdate.content['unsigned'] is Map ? eventUpdate.content['unsigned']['transaction_id'] @@ -303,7 +303,7 @@ class Timeline { } addAggregatedEvent(events[i]); } else { - var newEvent = + final newEvent = Event.fromJson(eventUpdate.content, room, eventUpdate.sortOrder); if (eventUpdate.type == EventUpdateType.history && diff --git a/lib/src/user.dart b/lib/src/user.dart index b404d94f..597a7cc0 100644 --- a/lib/src/user.dart +++ b/lib/src/user.dart @@ -30,7 +30,7 @@ class User extends Event { String avatarUrl, Room room, }) { - var content = {}; + final content = {}; if (membership != null) content['membership'] = membership; if (displayName != null) content['displayname'] = displayName; if (avatarUrl != null) content['avatar_url'] = avatarUrl; @@ -119,7 +119,7 @@ class User extends Event { if (!formatLocalpart) { return stateKey.localpart; } - var words = stateKey.localpart.replaceAll('_', ' ').split(' '); + final words = stateKey.localpart.replaceAll('_', ' ').split(' '); for (var i = 0; i < words.length; i++) { if (words[i].isNotEmpty) { words[i] = words[i][0].toUpperCase() + words[i].substring(1); diff --git a/lib/src/utils/event_localizations.dart b/lib/src/utils/event_localizations.dart index 6418d54b..f7654f29 100644 --- a/lib/src/utils/event_localizations.dart +++ b/lib/src/utils/event_localizations.dart @@ -85,7 +85,7 @@ abstract class EventLocalizations { i18n.createdTheChat(event.sender.calcDisplayname()), EventTypes.RoomTombstone: (event, i18n) => i18n.roomHasBeenUpgraded, EventTypes.RoomJoinRules: (event, i18n) { - var joinRules = JoinRules.values.firstWhere( + final joinRules = JoinRules.values.firstWhere( (r) => r.toString().replaceAll('JoinRules.', '') == event.content['join_rule'], @@ -170,7 +170,7 @@ abstract class EventLocalizations { EventTypes.RoomAvatar: (event, i18n) => i18n.changedTheChatAvatar(event.sender.calcDisplayname()), EventTypes.GuestAccess: (event, i18n) { - var guestAccess = GuestAccess.values.firstWhere( + final guestAccess = GuestAccess.values.firstWhere( (r) => r.toString().replaceAll('GuestAccess.', '') == event.content['guest_access'], @@ -183,7 +183,7 @@ abstract class EventLocalizations { } }, EventTypes.HistoryVisibility: (event, i18n) { - var historyVisibility = HistoryVisibility.values.firstWhere( + final historyVisibility = HistoryVisibility.values.firstWhere( (r) => r.toString().replaceAll('HistoryVisibility.', '') == event.content['history_visibility'], diff --git a/lib/src/utils/event_update.dart b/lib/src/utils/event_update.dart index 7d307a63..9d9a7091 100644 --- a/lib/src/utils/event_update.dart +++ b/lib/src/utils/event_update.dart @@ -53,7 +53,7 @@ class EventUpdate { return this; } try { - var decrpytedEvent = await room.client.encryption.decryptRoomEvent( + final decrpytedEvent = await room.client.encryption.decryptRoomEvent( room.id, Event.fromJson(content, room, sortOrder), store: store, updateType: type); return EventUpdate( diff --git a/lib/src/utils/markdown.dart b/lib/src/utils/markdown.dart index 383d3080..9084a0d0 100644 --- a/lib/src/utils/markdown.dart +++ b/lib/src/utils/markdown.dart @@ -114,7 +114,7 @@ class BlockLatexSyntax extends BlockSyntax { @override List parseChildLines(BlockParser parser) { - var childLines = []; + final childLines = []; var first = true; while (!parser.isDone) { final match = endPattern.firstMatch(parser.current); diff --git a/test/canonical_json_test.dart b/test/canonical_json_test.dart index 3b11d00e..15c222e8 100644 --- a/test/canonical_json_test.dart +++ b/test/canonical_json_test.dart @@ -25,7 +25,7 @@ void main() { /// All Tests related to the ChatTime group('Canonical Json', () { Logs().level = Level.error; - var textMap = >{ + final textMap = >{ '{}': {}, '{"one":1,"two":"Two"}': {'one': 1, 'two': 'Two'}, '{"a":"1","b":"2"}': {'b': '2', 'a': '1'}, diff --git a/test/client_test.dart b/test/client_test.dart index 0469ce24..4834cea2 100644 --- a/test/client_test.dart +++ b/test/client_test.dart @@ -95,9 +95,9 @@ void main() { final available = await matrix.usernameAvailable('testuser'); expect(available, true); - var loginStateFuture = matrix.onLoginStateChanged.stream.first; - var firstSyncFuture = matrix.onFirstSync.stream.first; - var syncFuture = matrix.onSync.stream.first; + final loginStateFuture = matrix.onLoginStateChanged.stream.first; + final firstSyncFuture = matrix.onFirstSync.stream.first; + final syncFuture = matrix.onSync.stream.first; await matrix.init( newToken: 'abcd', @@ -110,9 +110,9 @@ void main() { await Future.delayed(Duration(milliseconds: 50)); - var loginState = await loginStateFuture; - var firstSync = await firstSyncFuture; - var sync = await syncFuture; + final loginState = await loginStateFuture; + final firstSync = await firstSyncFuture; + final sync = await syncFuture; expect(loginState, LoginState.logged); expect(firstSync, true); @@ -203,7 +203,7 @@ void main() { }); test('Logout', () async { - var loginStateFuture = matrix.onLoginStateChanged.stream.first; + final loginStateFuture = matrix.onLoginStateChanged.stream.first; await matrix.logout(); expect(matrix.accessToken == null, true); @@ -213,14 +213,14 @@ void main() { expect(matrix.deviceName == null, true); expect(matrix.prevBatch == null, true); - var loginState = await loginStateFuture; + final loginState = await loginStateFuture; expect(loginState, LoginState.loggedOut); }); test('Room Update Test', () async { await matrix.onRoomUpdate.close(); - var roomUpdateList = await roomUpdateListFuture; + final roomUpdateList = await roomUpdateListFuture; expect(roomUpdateList.length, 4); @@ -242,7 +242,7 @@ void main() { test('Event Update Test', () async { await matrix.onEvent.close(); - var eventUpdateList = await eventUpdateListFuture; + final eventUpdateList = await eventUpdateListFuture; expect(eventUpdateList.length, 14); @@ -303,7 +303,7 @@ void main() { test('To Device Update Test', () async { await matrix.onToDeviceEvent.close(); - var eventUpdateList = await toDeviceUpdateListFuture; + final eventUpdateList = await toDeviceUpdateListFuture; expect(eventUpdateList.length, 2); @@ -351,7 +351,7 @@ void main() { }); test('get archive', () async { - var archive = await matrix.archive; + final archive = await matrix.archive; await Future.delayed(Duration(milliseconds: 50)); expect(archive.length, 2); @@ -526,7 +526,7 @@ void main() { }); test('Test the fake store api', () async { final database = await getDatabase(null); - var client1 = Client( + final client1 = Client( 'testclient', httpClient: FakeMatrixApi(), databaseBuilder: (_) => database, @@ -546,7 +546,7 @@ void main() { expect(client1.isLogged(), true); expect(client1.rooms.length, 2); - var client2 = Client( + final client2 = Client( 'testclient', httpClient: FakeMatrixApi(), databaseBuilder: (_) => database, diff --git a/test/commands_test.dart b/test/commands_test.dart index d44c3875..d2b98d76 100644 --- a/test/commands_test.dart +++ b/test/commands_test.dart @@ -94,7 +94,7 @@ void main() { test('me', () async { FakeMatrixApi.calledEndpoints.clear(); await room.sendTextEvent('/me heya'); - var sent = getLastMessagePayload(); + final sent = getLastMessagePayload(); expect(sent, { 'msgtype': 'm.emote', 'body': 'heya', @@ -104,7 +104,7 @@ void main() { test('plain', () async { FakeMatrixApi.calledEndpoints.clear(); await room.sendTextEvent('/plain *floof*'); - var sent = getLastMessagePayload(); + final sent = getLastMessagePayload(); expect(sent, { 'msgtype': 'm.text', 'body': '*floof*', @@ -114,7 +114,7 @@ void main() { test('html', () async { FakeMatrixApi.calledEndpoints.clear(); await room.sendTextEvent('/html yay'); - var sent = getLastMessagePayload(); + final sent = getLastMessagePayload(); expect(sent, { 'msgtype': 'm.text', 'body': 'yay', @@ -127,7 +127,7 @@ void main() { FakeMatrixApi.calledEndpoints.clear(); await room.sendTextEvent('/react 🦊', inReplyTo: Event(eventId: '\$event')); - var sent = getLastMessagePayload('m.reaction'); + final sent = getLastMessagePayload('m.reaction'); expect(sent, { 'm.relates_to': { 'rel_type': 'm.annotation', @@ -231,7 +231,7 @@ void main() { test('myroomnick', () async { FakeMatrixApi.calledEndpoints.clear(); await room.sendTextEvent('/myroomnick Foxies~'); - var sent = getLastMessagePayload('m.room.member', client.userID); + final sent = getLastMessagePayload('m.room.member', client.userID); expect(sent, { 'displayname': 'Foxies~', 'membership': 'join', @@ -241,7 +241,7 @@ void main() { test('myroomavatar', () async { FakeMatrixApi.calledEndpoints.clear(); await room.sendTextEvent('/myroomavatar mxc://beep/boop'); - var sent = getLastMessagePayload('m.room.member', client.userID); + final sent = getLastMessagePayload('m.room.member', client.userID); expect(sent, { 'avatar_url': 'mxc://beep/boop', 'membership': 'join', diff --git a/test/encryption/cross_signing_test.dart b/test/encryption/cross_signing_test.dart index 0d8ffc18..7c83d752 100644 --- a/test/encryption/cross_signing_test.dart +++ b/test/encryption/cross_signing_test.dart @@ -96,7 +96,7 @@ void main() { client.userDeviceKeys[client.userID].deviceKeys['OTHERDEVICE'], client.userDeviceKeys['@othertest:fakeServer.notExisting'].masterKey ]); - var body = json.decode(FakeMatrixApi + final body = json.decode(FakeMatrixApi .calledEndpoints['/client/r0/keys/signatures/upload'].first); expect(body['@test:fakeServer.notExisting'].containsKey('OTHERDEVICE'), true); diff --git a/test/encryption/encrypt_decrypt_to_device_test.dart b/test/encryption/encrypt_decrypt_to_device_test.dart index cb9d85dd..cd0701c7 100644 --- a/test/encryption/encrypt_decrypt_to_device_test.dart +++ b/test/encryption/encrypt_decrypt_to_device_test.dart @@ -35,7 +35,7 @@ void main() { var olmEnabled = true; Client client; - var otherClient = Client('othertestclient', + final otherClient = Client('othertestclient', httpClient: FakeMatrixApi(), databaseBuilder: getDatabase); DeviceKeys device; Map payload; diff --git a/test/encryption/key_request_test.dart b/test/encryption/key_request_test.dart index 0e687daf..703db23b 100644 --- a/test/encryption/key_request_test.dart +++ b/test/encryption/key_request_test.dart @@ -56,13 +56,13 @@ void main() { Logs().i('[LibOlm] Enabled: $olmEnabled'); if (!olmEnabled) return; - var matrix = await getClient(); + final matrix = await getClient(); final requestRoom = matrix.getRoomById('!726s6s6q:example.com'); await matrix.encryption.keyManager.request( requestRoom, 'sessionId', validSenderKey, tryOnlineBackup: false); var foundEvent = false; - for (var entry in FakeMatrixApi.calledEndpoints.entries) { + for (final entry in FakeMatrixApi.calledEndpoints.entries) { final payload = jsonDecode(entry.value.first); if (entry.key .startsWith('/client/r0/sendToDevice/m.room_key_request') && @@ -84,7 +84,7 @@ void main() { }); test('Reply To Request', () async { if (!olmEnabled) return; - var matrix = await getClient(); + final matrix = await getClient(); matrix.setUserId('@alice:example.com'); // we need to pretend to be alice FakeMatrixApi.calledEndpoints.clear(); await matrix @@ -279,7 +279,7 @@ void main() { }); test('Receive shared keys', () async { if (!olmEnabled) return; - var matrix = await getClient(); + final matrix = await getClient(); final requestRoom = matrix.getRoomById('!726s6s6q:example.com'); await matrix.encryption.keyManager.request( requestRoom, validSessionId, validSenderKey, diff --git a/test/encryption/key_verification_test.dart b/test/encryption/key_verification_test.dart index e5223aee..c6aa3173 100644 --- a/test/encryption/key_verification_test.dart +++ b/test/encryption/key_verification_test.dart @@ -425,7 +425,7 @@ void main() { client1.userDeviceKeys[client1.userID].masterKey.setDirectVerified(false); final req1 = await client1.userDeviceKeys[client2.userID].startVerification(); - var evt = getLastSentEvent(req1); + final evt = getLastSentEvent(req1); expect(req1.state, KeyVerificationState.waitingAccept); KeyVerification req2; diff --git a/test/encryption/online_key_backup_test.dart b/test/encryption/online_key_backup_test.dart index 97eb4e98..cdd915cf 100644 --- a/test/encryption/online_key_backup_test.dart +++ b/test/encryption/online_key_backup_test.dart @@ -83,7 +83,7 @@ void main() { final roomId = '!someroom:example.org'; final sessionId = inbound.session_id(); // set a payload... - var sessionPayload = { + final sessionPayload = { 'algorithm': AlgorithmTypes.megolmV1AesSha2, 'room_id': roomId, 'forwarding_curve25519_key_chain': [client.identityKey], diff --git a/test/event_test.dart b/test/event_test.dart index e5fb2f73..2523101a 100644 --- a/test/event_test.dart +++ b/test/event_test.dart @@ -47,7 +47,7 @@ void main() { final contentJson = '{"msgtype":"$msgtype","body":"$body","formatted_body":"$formatted_body","m.relates_to":{"m.in_reply_to":{"event_id":"\$1234:example.com"}}}'; - var jsonObj = { + final jsonObj = { 'event_id': id, 'sender': senderID, 'origin_server_ts': timestamp, @@ -56,8 +56,8 @@ void main() { 'status': 2, 'content': contentJson, }; - var client = Client('testclient', httpClient: FakeMatrixApi()); - var event = Event.fromJson( + final client = Client('testclient', httpClient: FakeMatrixApi()); + final event = Event.fromJson( jsonObj, Room(id: '!localpart:server.abc', client: client)); test('setup', () async { @@ -86,7 +86,7 @@ void main() { expect(event.type, EventTypes.Message); expect(event.relationshipType, RelationshipTypes.reply); jsonObj['state_key'] = ''; - var state = Event.fromJson(jsonObj, null); + final state = Event.fromJson(jsonObj, null); expect(state.eventId, id); expect(state.stateKey, ''); expect(state.status, 2); @@ -244,8 +244,8 @@ void main() { 'type': 'm.room.redaction', 'unsigned': {'age': 1234} }; - var redactedBecause = Event.fromJson(redactionEventJson, room); - var event = Event.fromJson(redactJsonObj, room); + final redactedBecause = Event.fromJson(redactionEventJson, room); + final event = Event.fromJson(redactJsonObj, room); event.setRedactionEvent(redactedBecause); expect(event.redacted, true); expect(event.redactedBecause.toJson(), redactedBecause.toJson()); @@ -256,7 +256,7 @@ void main() { }); test('remove', () async { - var event = Event.fromJson( + final event = Event.fromJson( jsonObj, Room(id: '1234', client: Client('testclient'))); final removed1 = await event.remove(); event.status = 0; @@ -266,14 +266,14 @@ void main() { }); test('sendAgain', () async { - var matrix = Client('testclient', httpClient: FakeMatrixApi()); + final matrix = Client('testclient', httpClient: FakeMatrixApi()); await matrix.checkHomeserver('https://fakeserver.notexisting', checkWellKnown: false); await matrix.login( identifier: AuthenticationUserIdentifier(user: 'test'), password: '1234'); - var event = Event.fromJson( + final event = Event.fromJson( jsonObj, Room(id: '!1234:example.com', client: matrix)); final resp1 = await event.sendAgain(); event.status = -1; @@ -285,14 +285,14 @@ void main() { }); test('requestKey', () async { - var matrix = Client('testclient', httpClient: FakeMatrixApi()); + final matrix = Client('testclient', httpClient: FakeMatrixApi()); await matrix.checkHomeserver('https://fakeserver.notexisting', checkWellKnown: false); await matrix.login( identifier: AuthenticationUserIdentifier(user: 'test'), password: '1234'); - var event = Event.fromJson( + final event = Event.fromJson( jsonObj, Room(id: '!1234:example.com', client: matrix)); String exception; try { @@ -302,7 +302,7 @@ void main() { } expect(exception, 'Session key not requestable'); - var event2 = Event.fromJson({ + final event2 = Event.fromJson({ 'event_id': id, 'sender': senderID, 'origin_server_ts': timestamp, @@ -327,7 +327,7 @@ void main() { }); test('requestKey', () async { jsonObj['state_key'] = '@alice:example.com'; - var event = Event.fromJson( + final event = Event.fromJson( jsonObj, Room(id: '!localpart:server.abc', client: client)); expect(event.stateKeyUser.id, '@alice:example.com'); }); @@ -895,14 +895,14 @@ void main() { }); test('aggregations', () { - var event = Event.fromJson({ + final event = Event.fromJson({ 'content': { 'body': 'blah', 'msgtype': 'm.text', }, 'event_id': '\$source', }, null); - var edit1 = Event.fromJson({ + final edit1 = Event.fromJson({ 'content': { 'body': 'blah', 'msgtype': 'm.text', @@ -913,7 +913,7 @@ void main() { }, 'event_id': '\$edit1', }, null); - var edit2 = Event.fromJson({ + final edit2 = Event.fromJson({ 'content': { 'body': 'blah', 'msgtype': 'm.text', @@ -924,8 +924,9 @@ void main() { }, 'event_id': '\$edit2', }, null); - var room = Room(client: client); - var timeline = Timeline(events: [event, edit1, edit2], room: room); + final room = Room(client: client); + final timeline = + Timeline(events: [event, edit1, edit2], room: room); expect(event.hasAggregatedEvents(timeline, RelationshipTypes.edit), true); expect(event.aggregatedEvents(timeline, RelationshipTypes.edit), {edit1, edit2}); @@ -955,7 +956,7 @@ void main() { 'sender': '@alice:example.org', }, null); event.sortOrder = 0; - var edit1 = Event.fromJson({ + final edit1 = Event.fromJson({ 'type': EventTypes.Message, 'content': { 'body': '* edit 1', @@ -973,7 +974,7 @@ void main() { 'sender': '@alice:example.org', }, null); edit1.sortOrder = 1; - var edit2 = Event.fromJson({ + final edit2 = Event.fromJson({ 'type': EventTypes.Message, 'content': { 'body': '* edit 2', @@ -991,7 +992,7 @@ void main() { 'sender': '@alice:example.org', }, null); edit2.sortOrder = 2; - var edit3 = Event.fromJson({ + final edit3 = Event.fromJson({ 'type': EventTypes.Message, 'content': { 'body': '* edit 3', @@ -1009,7 +1010,7 @@ void main() { 'sender': '@bob:example.org', }, null); edit3.sortOrder = 3; - var room = Room(client: client); + final room = Room(client: client); // no edits var displayEvent = event.getDisplayEvent(Timeline(events: [event], room: room)); @@ -1246,7 +1247,7 @@ void main() { await client.checkHomeserver('https://fakeserver.notexisting', checkWellKnown: false); final room = Room(id: '!localpart:server.abc', client: await getClient()); - var event = Event.fromJson({ + final event = Event.fromJson({ 'type': EventTypes.Message, 'content': { 'body': 'image', diff --git a/test/matrix_database_test.dart b/test/matrix_database_test.dart index e8ceca60..2531bed6 100644 --- a/test/matrix_database_test.dart +++ b/test/matrix_database_test.dart @@ -26,7 +26,7 @@ void main() { group('Databse', () { Logs().level = Level.error; var clientId = -1; - var room = Room(id: '!room:blubb'); + final room = Room(id: '!room:blubb'); test('setupDatabase', () async { final database = await getDatabase(null); clientId = await database.insertClient( diff --git a/test/mxc_uri_extension_test.dart b/test/mxc_uri_extension_test.dart index 5510216b..38d2f4d1 100644 --- a/test/mxc_uri_extension_test.dart +++ b/test/mxc_uri_extension_test.dart @@ -29,7 +29,7 @@ void main() { group('MxContent', () { Logs().level = Level.error; test('Formatting', () async { - var client = Client('testclient', httpClient: FakeMatrixApi()); + final client = Client('testclient', httpClient: FakeMatrixApi()); await client.checkHomeserver('https://fakeserver.notexisting', checkWellKnown: false); final mxc = 'mxc://exampleserver.abc/abcdefghijklmn'; diff --git a/test/room_test.dart b/test/room_test.dart index c4c6c4f7..1ad8355a 100644 --- a/test/room_test.dart +++ b/test/room_test.dart @@ -55,7 +55,7 @@ void main() { '@charley:example.org' ]; - var dbRoom = DbRoom( + final dbRoom = DbRoom( clientId: 1, roomId: id, membership: membership.toString().split('.').last, @@ -69,7 +69,7 @@ void main() { heroes: heroes.join(','), ); - var states = [ + final states = [ DbRoomState( clientId: 1, eventId: '143273582443PhrSn:example.org', @@ -85,7 +85,7 @@ void main() { ), ]; - var roomAccountData = [ + final roomAccountData = [ DbRoomAccountData( clientId: 1, type: 'com.test.foo', @@ -229,7 +229,7 @@ void main() { test('requestParticipants', () async { final participants = await room.requestParticipants(); expect(participants.length, 1); - var user = participants[0]; + final user = participants[0]; expect(user.id, '@alice:example.org'); expect(user.displayName, 'Alice Margatroid'); expect(user.membership, Membership.join); diff --git a/test/sync_filter_test.dart b/test/sync_filter_test.dart index 818240c1..2eabe4b4 100644 --- a/test/sync_filter_test.dart +++ b/test/sync_filter_test.dart @@ -129,7 +129,7 @@ const updates = { void testUpdates(bool Function(SyncUpdate s) test, Map expected) { for (final update in updates.entries) { - var sync = SyncUpdate.fromJson(update.value); + final sync = SyncUpdate.fromJson(update.value); expect(test(sync), expected[update.key]); } } @@ -138,7 +138,7 @@ void main() { group('Sync Filters', () { Logs().level = Level.error; test('room update', () { - var testFn = (SyncUpdate s) => s.hasRoomUpdate; + final testFn = (SyncUpdate s) => s.hasRoomUpdate; final expected = { 'empty': false, 'presence': false, @@ -152,7 +152,7 @@ void main() { }); test('presence update', () { - var testFn = (SyncUpdate s) => s.hasPresenceUpdate; + final testFn = (SyncUpdate s) => s.hasPresenceUpdate; final expected = { 'empty': false, 'presence': true, diff --git a/test/timeline_test.dart b/test/timeline_test.dart index 4b569844..ec077bb2 100644 --- a/test/timeline_test.dart +++ b/test/timeline_test.dart @@ -33,7 +33,7 @@ void main() { final roomID = '!1234:example.com'; final testTimeStamp = DateTime.now().millisecondsSinceEpoch; var updateCount = 0; - var insertList = []; + final insertList = []; var olmEnabled = true; Client client; diff --git a/test/uia_test.dart b/test/uia_test.dart index 800ea67a..e8d8adea 100644 --- a/test/uia_test.dart +++ b/test/uia_test.dart @@ -26,7 +26,7 @@ void main() { group('UIA', () { Logs().level = Level.error; test('it should work', () async { - var completed = []; + final completed = []; var updated = 0; var finished = false; final request = UiaRequest( diff --git a/test/user_test.dart b/test/user_test.dart index 3cbbd1b6..113eb353 100644 --- a/test/user_test.dart +++ b/test/user_test.dart @@ -28,7 +28,7 @@ void main() { /// All Tests related to the Event group('User', () { Logs().level = Level.error; - var client = Client('testclient', httpClient: FakeMatrixApi()); + final client = Client('testclient', httpClient: FakeMatrixApi()); final user1 = User( '@alice:example.com', membership: 'join', @@ -65,7 +65,7 @@ void main() { 'state_key': id }; - var user = Event.fromJson(jsonObj, null).asUser; + final user = Event.fromJson(jsonObj, null).asUser; expect(user.id, id); expect(user.membership, membership); diff --git a/test_driver/famedlysdk_test.dart b/test_driver/famedlysdk_test.dart index ba318bba..41740ece 100644 --- a/test_driver/famedlysdk_test.dart +++ b/test_driver/famedlysdk_test.dart @@ -37,7 +37,7 @@ void test() async { Logs().i('++++ (Alice) Leave all rooms ++++'); while (testClientA.rooms.isNotEmpty) { - var room = testClientA.rooms.first; + final room = testClientA.rooms.first; if (room.canonicalAlias?.isNotEmpty ?? false) { break; } @@ -50,7 +50,7 @@ void test() async { Logs().i('++++ (Bob) Leave all rooms ++++'); for (var i = 0; i < 3; i++) { if (testClientB.rooms.isNotEmpty) { - var room = testClientB.rooms.first; + final room = testClientB.rooms.first; try { await room.leave(); await room.forget(); @@ -77,12 +77,12 @@ void test() async { Logs().i('++++ (Alice) Create room and invite Bob ++++'); await testClientA.createRoom(invite: [TestUser.username2]); await Future.delayed(Duration(seconds: 1)); - var room = testClientA.rooms.first; + final room = testClientA.rooms.first; assert(room != null); final roomId = room.id; Logs().i('++++ (Bob) Join room ++++'); - var inviteRoom = testClientB.getRoomById(roomId); + final inviteRoom = testClientB.getRoomById(roomId); await inviteRoom.join(); await Future.delayed(Duration(seconds: 1)); assert(inviteRoom.membership == Membership.join); @@ -197,7 +197,8 @@ void test() async { .outboundGroupSession .session_id() == currentSessionIdA); - var inviteRoomOutboundGroupSession = inviteRoom.client.encryption.keyManager + final inviteRoomOutboundGroupSession = inviteRoom + .client.encryption.keyManager .getOutboundGroupSession(inviteRoom.id); assert(inviteRoomOutboundGroupSession != null);