From be9c841c8aea91946e46ca0ba23dec08faa08bc4 Mon Sep 17 00:00:00 2001 From: Deven Joshi Date: Fri, 16 Apr 2021 13:41:05 +0530 Subject: [PATCH] fix: Review changes --- packages/stream_chat/lib/src/api/channel.dart | 26 +++--- .../stream_chat/lib/src/api/retry_queue.dart | 27 ++++--- .../lib/src/attachment_file_uploader.dart | 28 +++---- packages/stream_chat/lib/src/client.dart | 81 +++++++++---------- .../lib/src/db/chat_persistence_client.dart | 4 +- .../test/src/api/channel_test.dart | 1 - .../stream_chat/test/src/client_test.dart | 2 +- .../test/src/models/action_test.dart | 3 +- .../test/src/models/attachment_test.dart | 3 +- .../test/src/models/channel_test.dart | 1 - .../test/src/models/device_test.dart | 3 +- .../test/src/models/message_test.dart | 7 +- 12 files changed, 98 insertions(+), 88 deletions(-) diff --git a/packages/stream_chat/lib/src/api/channel.dart b/packages/stream_chat/lib/src/api/channel.dart index 01d8399e..c4bcef33 100644 --- a/packages/stream_chat/lib/src/api/channel.dart +++ b/packages/stream_chat/lib/src/api/channel.dart @@ -249,13 +249,13 @@ class Channel { Future future; if (isImage) { future = sendImage( - it.file, + it.file!, onSendProgress: onSendProgress, cancelToken: cancelToken, ).then((it) => it!.file!); } else { future = sendFile( - it.file, + it.file!, onSendProgress: onSendProgress, cancelToken: cancelToken, ).then((it) => it!.file!); @@ -340,7 +340,7 @@ class Channel { } final response = await _client.sendMessage(message, id, type); - state?.addMessage(response!.message!); + state?.addMessage(response.message!); return response; } catch (error) { if (error is DioError && error.type != DioErrorType.response) { @@ -392,7 +392,7 @@ class Channel { final response = await _client.updateMessage(message); - final m = response?.message?.copyWith( + final m = response.message?.copyWith( ownReactions: message.ownReactions, ); @@ -453,10 +453,11 @@ class Channel { /// Pins provided message Future pinMessage( Message message, - Object timeoutOrExpirationDate, + Object? timeoutOrExpirationDate, ) { assert(() { if (timeoutOrExpirationDate is! DateTime && + timeoutOrExpirationDate != null && timeoutOrExpirationDate is! num) { throw ArgumentError('Invalid timeout or Expiration date'); } @@ -485,7 +486,7 @@ class Channel { /// Send a file to this channel Future sendFile( - AttachmentFile? file, { + AttachmentFile file, { ProgressCallback? onSendProgress, CancelToken? cancelToken, }) => @@ -499,7 +500,7 @@ class Channel { /// Send an image to this channel Future sendImage( - AttachmentFile? file, { + AttachmentFile file, { ProgressCallback? onSendProgress, CancelToken? cancelToken, }) => @@ -765,7 +766,7 @@ class Channel { 'message_id': messageId, }); - final res = _client.decode(response.data, SendActionResponse.fromJson)!; + final res = _client.decode(response.data, SendActionResponse.fromJson); if (res.message != null) { state!.addMessage(res.message!); @@ -880,7 +881,7 @@ class Channel { final repliesResponse = _client.decode( response.data, QueryRepliesResponse.fromJson, - )!; + ); state?.updateThreadInfo(parentId, repliesResponse.messages); @@ -911,7 +912,7 @@ class Channel { final res = _client.decode( response.data, GetMessagesByIdResponse.fromJson, - )!; + ); final messages = res.messages; @@ -999,8 +1000,7 @@ class Channel { try { final response = await _client.post(path, data: payload); - final updatedState = - _client.decode(response.data, ChannelState.fromJson)!; + final updatedState = _client.decode(response.data, ChannelState.fromJson); if (_id == null) { _id = updatedState.channel!.id; @@ -1191,7 +1191,7 @@ class Channel { /// Call this method to dispose the channel client void dispose() { - state!.dispose(); + state?.dispose(); } void _checkInitialized() { diff --git a/packages/stream_chat/lib/src/api/retry_queue.dart b/packages/stream_chat/lib/src/api/retry_queue.dart index e09c367b..c13db9c6 100644 --- a/packages/stream_chat/lib/src/api/retry_queue.dart +++ b/packages/stream_chat/lib/src/api/retry_queue.dart @@ -40,16 +40,17 @@ class RetryQueue { })); } - final HeapPriorityQueue _messageQueue = HeapPriorityQueue(_byDate); + final HeapPriorityQueue _messageQueue = HeapPriorityQueue(_byDate); bool _isRetrying = false; RetryPolicy? _retryPolicy; /// Add a list of messages - void add(List messages) { + void add(List messages) { logger?.info('added ${messages.length} messages'); final messageList = _messageQueue.toList(); + _messageQueue.addAll(messages - .where((element) => !messageList.any((m) => m!.id == element!.id))); + .where((element) => !messageList.any((m) => m.id == element.id))); if (_messageQueue.isNotEmpty && !_isRetrying) { _startRetrying(); @@ -62,7 +63,7 @@ class RetryQueue { final retryPolicy = _retryPolicy!.copyWith(attempt: 0); while (_messageQueue.isNotEmpty) { - final message = _messageQueue.first!; + final message = _messageQueue.first; try { logger?.info('retry attempt ${retryPolicy.attempt}'); await _sendMessage(message); @@ -141,7 +142,7 @@ class RetryQueue { final messageList = _messageQueue.toList(); if (event.message != null) { final messageIndex = - messageList.indexWhere((m) => m!.id == event.message!.id); + messageList.indexWhere((m) => m.id == event.message!.id); if (messageIndex == -1 && [ MessageSendingStatus.failed_update, @@ -149,7 +150,11 @@ class RetryQueue { MessageSendingStatus.failed_delete, ].contains(event.message!.status)) { logger?.info('add message from events'); - add([event.message]); + final m = event.message; + + if (m != null) { + add([m]); + } } else if (messageIndex != -1 && [ MessageSendingStatus.sent, @@ -167,9 +172,13 @@ class RetryQueue { _subscriptions.forEach((s) => s.cancel()); } - static int _byDate(Message? m1, Message? m2) { - final date1 = _getMessageDate(m1!)!; - final date2 = _getMessageDate(m2!)!; + static int _byDate(Message m1, Message m2) { + final date1 = _getMessageDate(m1); + final date2 = _getMessageDate(m2); + + if (date1 == null || date2 == null) { + return 0; + } return date1.compareTo(date2); } diff --git a/packages/stream_chat/lib/src/attachment_file_uploader.dart b/packages/stream_chat/lib/src/attachment_file_uploader.dart index 42df3fb2..70976d40 100644 --- a/packages/stream_chat/lib/src/attachment_file_uploader.dart +++ b/packages/stream_chat/lib/src/attachment_file_uploader.dart @@ -11,8 +11,8 @@ abstract class AttachmentFileUploader { /// /// Optionally, access upload progress using [onSendProgress] /// and cancel the request using [cancelToken] - Future sendImage( - AttachmentFile? image, + Future sendImage( + AttachmentFile image, String? channelId, String? channelType, { ProgressCallback? onSendProgress, @@ -24,8 +24,8 @@ abstract class AttachmentFileUploader { /// /// Optionally, access upload progress using [onSendProgress] /// and cancel the request using [cancelToken] - Future sendFile( - AttachmentFile? file, + Future sendFile( + AttachmentFile file, String? channelId, String? channelType, { ProgressCallback? onSendProgress, @@ -36,7 +36,7 @@ abstract class AttachmentFileUploader { /// Returns [EmptyResponse] once deleted successfully. /// /// Optionally, cancel the request using [cancelToken] - Future deleteImage( + Future deleteImage( String url, String? channelId, String? channelType, { @@ -47,7 +47,7 @@ abstract class AttachmentFileUploader { /// Returns [EmptyResponse] once deleted successfully. /// /// Optionally, cancel the request using [cancelToken] - Future deleteFile( + Future deleteFile( String url, String? channelId, String? channelType, { @@ -63,14 +63,14 @@ class StreamAttachmentFileUploader implements AttachmentFileUploader { final StreamChatClient _client; @override - Future sendImage( - AttachmentFile? file, + Future sendImage( + AttachmentFile file, String? channelId, String? channelType, { ProgressCallback? onSendProgress, CancelToken? cancelToken, }) async { - final filename = file!.path?.split('/').last ?? file.name; + final filename = file.path?.split('/').last ?? file.name; final mimeType = filename.mimeType; MultipartFile? multiPartFile; @@ -100,14 +100,14 @@ class StreamAttachmentFileUploader implements AttachmentFileUploader { } @override - Future sendFile( - AttachmentFile? file, + Future sendFile( + AttachmentFile file, String? channelId, String? channelType, { ProgressCallback? onSendProgress, CancelToken? cancelToken, }) async { - final filename = file!.path?.split('/').last ?? file.name; + final filename = file.path?.split('/').last ?? file.name; final mimeType = filename.mimeType; MultipartFile? multiPartFile; @@ -137,7 +137,7 @@ class StreamAttachmentFileUploader implements AttachmentFileUploader { } @override - Future deleteImage( + Future deleteImage( String url, String? channelId, String? channelType, { @@ -152,7 +152,7 @@ class StreamAttachmentFileUploader implements AttachmentFileUploader { } @override - Future deleteFile( + Future deleteFile( String url, String? channelId, String? channelType, { diff --git a/packages/stream_chat/lib/src/client.dart b/packages/stream_chat/lib/src/client.dart index e951ed78..1066c670 100644 --- a/packages/stream_chat/lib/src/client.dart +++ b/packages/stream_chat/lib/src/client.dart @@ -482,9 +482,10 @@ class StreamChatClient { } if (!event.isLocal!) { - if (_synced && event.createdAt != null) { + final createdAt = event.createdAt; + if (_synced && createdAt != null) { await _chatPersistenceClient?.updateConnectionInfo(event); - await _chatPersistenceClient?.updateLastSyncAt(event.createdAt); + await _chatPersistenceClient?.updateLastSyncAt(createdAt); } } @@ -615,7 +616,7 @@ class StreamChatClient { final res = decode( rawRes.data, SyncResponse.fromJson, - )!; + ); res.events!.sort((a, b) => a.createdAt!.compareTo(b.createdAt!)); @@ -737,7 +738,7 @@ class StreamChatClient { final res = decode( response.data, QueryChannelsResponse.fromJson, - )!; + ); if ((res.channels ?? []).isEmpty && paginationParams.offset == 0) { logger.warning( @@ -914,12 +915,10 @@ class StreamChatClient { } /// Used to log errors and stacktrace in case of bad json deserialization - T? decode(String? j, DecoderFunction decoderFunction) { + T decode(String? j, DecoderFunction decoderFunction) { try { - if (j == null) { - return null; - } - return decoderFunction(json.decode(j)); + final data = j ?? '{}'; + return decoderFunction(json.decode(data)); } catch (error, stacktrace) { logger.severe('Error decoding response', error, stacktrace); rethrow; @@ -983,8 +982,8 @@ class StreamChatClient { .whenComplete(() => _anonymous = false); return connectUser( - response?.user, - response?.accessToken, + response.user, + response.accessToken, ); } @@ -1052,7 +1051,7 @@ class StreamChatClient { final response = decode( rawRes.data, QueryUsersResponse.fromJson, - )!; + ); state?._updateUsers(response.users!); @@ -1060,7 +1059,7 @@ class StreamChatClient { } /// A message search. - Future search( + Future search( Map filters, { String? query, List? sort, @@ -1099,8 +1098,8 @@ class StreamChatClient { } /// Send a [file] to the [channelId] of type [channelType] - Future sendFile( - AttachmentFile? file, + Future sendFile( + AttachmentFile file, String? channelId, String? channelType, { ProgressCallback? onSendProgress, @@ -1115,8 +1114,8 @@ class StreamChatClient { ); /// Send a [image] to the [channelId] of type [channelType] - Future sendImage( - AttachmentFile? image, + Future sendImage( + AttachmentFile image, String? channelId, String? channelType, { ProgressCallback? onSendProgress, @@ -1131,7 +1130,7 @@ class StreamChatClient { ); /// Delete a file from this channel - Future deleteFile( + Future deleteFile( String url, String? channelId, String? channelType, { @@ -1145,7 +1144,7 @@ class StreamChatClient { ); /// Delete an image from this channel - Future deleteImage( + Future deleteImage( String url, String? channelId, String? channelType, { @@ -1159,7 +1158,7 @@ class StreamChatClient { ); /// Add a device for Push Notifications. - Future addDevice(String id, PushProvider pushProvider) async { + Future addDevice(String id, PushProvider pushProvider) async { final response = await post('/devices', data: { 'id': id, 'push_provider': pushProvider.name, @@ -1168,14 +1167,14 @@ class StreamChatClient { } /// Gets a list of user devices. - Future getDevices() async { + Future getDevices() async { final response = await get('/devices'); return decode( response.data, ListDevicesResponse.fromJson); } /// Remove a user's device. - Future removeDevice(String id) async { + Future removeDevice(String id) async { final response = await delete('/devices', queryParameters: { 'id': id, }); @@ -1206,11 +1205,11 @@ class StreamChatClient { } /// Update or Create the given user object. - Future updateUser(User user) async => + Future updateUser(User user) async => updateUsers([user]); /// Batch update a list of users - Future updateUsers(List users) async { + Future updateUsers(List users) async { final response = await post('/users', data: { 'users': users.asMap().map((_, u) => MapEntry(u.id, u.toJson())), }); @@ -1221,7 +1220,7 @@ class StreamChatClient { } /// Bans a user from all channels - Future banUser( + Future banUser( String targetUserID, [ Map options = const {}, ]) async { @@ -1237,7 +1236,7 @@ class StreamChatClient { } /// Remove global ban for a user - Future unbanUser( + Future unbanUser( String targetUserID, [ Map options = const {}, ]) async { @@ -1253,7 +1252,7 @@ class StreamChatClient { } /// Shadow bans a user - Future shadowBan( + Future shadowBan( String targetID, [ Map options = const {}, ]) async => @@ -1263,7 +1262,7 @@ class StreamChatClient { }); /// Removes shadow ban from a user - Future removeShadowBan( + Future removeShadowBan( String targetID, [ Map options = const {}, ]) async => @@ -1273,7 +1272,7 @@ class StreamChatClient { }); /// Mutes a user - Future muteUser(String targetID) async { + Future muteUser(String targetID) async { final response = await post('/moderation/mute', data: { 'target_id': targetID, }); @@ -1281,7 +1280,7 @@ class StreamChatClient { } /// Unmutes a user - Future unmuteUser(String targetID) async { + Future unmuteUser(String targetID) async { final response = await post('/moderation/unmute', data: { 'target_id': targetID, }); @@ -1289,7 +1288,7 @@ class StreamChatClient { } /// Flag a message - Future flagMessage(String messageID) async { + Future flagMessage(String messageID) async { final response = await post('/moderation/flag', data: { 'target_message_id': messageID, }); @@ -1297,7 +1296,7 @@ class StreamChatClient { } /// Unflag a message - Future unflagMessage(String messageId) async { + Future unflagMessage(String messageId) async { final response = await post('/moderation/unflag', data: { 'target_message_id': messageId, }); @@ -1305,7 +1304,7 @@ class StreamChatClient { } /// Flag a user - Future flagUser(String userId) async { + Future flagUser(String userId) async { final response = await post('/moderation/flag', data: { 'target_user_id': userId, }); @@ -1313,7 +1312,7 @@ class StreamChatClient { } /// Unflag a message - Future unflagUser(String userId) async { + Future unflagUser(String userId) async { final response = await post('/moderation/unflag', data: { 'target_user_id': userId, }); @@ -1321,13 +1320,13 @@ class StreamChatClient { } /// Mark all channels for this user as read - Future markAllRead() async { + Future markAllRead() async { final response = await post('/channels/read'); return decode(response.data, EmptyResponse.fromJson); } /// Sends the message to the given channel - Future sendMessage( + Future sendMessage( Message message, String? channelId, String? channelType) async { final response = await post( '/channels/$channelType/$channelId/message', @@ -1337,7 +1336,7 @@ class StreamChatClient { } /// Update the given message - Future updateMessage(Message message) async { + Future updateMessage(Message message) async { final response = await post( '/messages/${message.id}', data: {'message': message.toJson()}, @@ -1346,19 +1345,19 @@ class StreamChatClient { } /// Deletes the given message - Future deleteMessage(Message message) async { + Future deleteMessage(Message message) async { final response = await delete('/messages/${message.id}'); return decode(response.data, EmptyResponse.fromJson); } /// Get a message by id - Future getMessage(String messageId) async { + Future getMessage(String messageId) async { final response = await get('/messages/$messageId'); return decode(response.data, GetMessageResponse.fromJson); } /// Pins provided message - Future pinMessage( + Future pinMessage( Message message, Object timeoutOrExpirationDate, ) { @@ -1384,7 +1383,7 @@ class StreamChatClient { } /// Unpins provided message - Future unpinMessage(Message message) => + Future unpinMessage(Message message) => updateMessage(message.copyWith(pinned: false)); } diff --git a/packages/stream_chat/lib/src/db/chat_persistence_client.dart b/packages/stream_chat/lib/src/db/chat_persistence_client.dart index 3f999ed8..2dc2521c 100644 --- a/packages/stream_chat/lib/src/db/chat_persistence_client.dart +++ b/packages/stream_chat/lib/src/db/chat_persistence_client.dart @@ -11,7 +11,7 @@ import 'package:stream_chat/src/models/user.dart'; /// A simple client used for persisting chat data locally. abstract class ChatPersistenceClient { /// Creates a new connection to the client - Future connect(String? userId); + Future connect(String userId); /// Closes the client connection /// If [flush] is true, the data will also be deleted @@ -33,7 +33,7 @@ abstract class ChatPersistenceClient { Future updateConnectionInfo(Event event); /// Update stored lastSyncAt - Future updateLastSyncAt(DateTime? lastSyncAt); + Future updateLastSyncAt(DateTime lastSyncAt); /// Get the channel cids saved in the offline storage Future> getChannelCids(); diff --git a/packages/stream_chat/test/src/api/channel_test.dart b/packages/stream_chat/test/src/api/channel_test.dart index 5eee577e..cdeae39d 100644 --- a/packages/stream_chat/test/src/api/channel_test.dart +++ b/packages/stream_chat/test/src/api/channel_test.dart @@ -638,7 +638,6 @@ void main() { Reaction( type: 'test', createdAt: DateTime.now(), - score: 0, user: User( id: client.state?.user?.id ?? '', ), diff --git a/packages/stream_chat/test/src/client_test.dart b/packages/stream_chat/test/src/client_test.dart index 8f95b3a4..4e880bed 100644 --- a/packages/stream_chat/test/src/client_test.dart +++ b/packages/stream_chat/test/src/client_test.dart @@ -777,7 +777,7 @@ void main() { ), ); - await client.deleteMessage(Message(id: messageId, text: '')); + await client.deleteMessage(Message(id: messageId)); verify(() => mockDio.delete('/messages/$messageId')).called(1); }); diff --git a/packages/stream_chat/test/src/models/action_test.dart b/packages/stream_chat/test/src/models/action_test.dart index 5d142953..22e66078 100644 --- a/packages/stream_chat/test/src/models/action_test.dart +++ b/packages/stream_chat/test/src/models/action_test.dart @@ -5,7 +5,8 @@ import 'package:stream_chat/src/models/action.dart'; void main() { group('src/models/action', () { - const jsonExample = '''{ + const jsonExample = ''' + { "name": "name", "style": "style", "text": "text", diff --git a/packages/stream_chat/test/src/models/attachment_test.dart b/packages/stream_chat/test/src/models/attachment_test.dart index 899aec73..1ca45132 100644 --- a/packages/stream_chat/test/src/models/attachment_test.dart +++ b/packages/stream_chat/test/src/models/attachment_test.dart @@ -6,7 +6,8 @@ import 'package:test/test.dart'; void main() { group('src/models/attachment', () { - const jsonExample = '''{ + const jsonExample = ''' + { "type": "giphy", "title": "awesome", "title_link": "https://giphy.com/gifs/nrkp3-dance-happy-3o7TKnCdBx5cMg0qti", diff --git a/packages/stream_chat/test/src/models/channel_test.dart b/packages/stream_chat/test/src/models/channel_test.dart index d2d78fd5..a48c5a23 100644 --- a/packages/stream_chat/test/src/models/channel_test.dart +++ b/packages/stream_chat/test/src/models/channel_test.dart @@ -44,7 +44,6 @@ void main() { id: 'id', cid: 'a:a', extraData: {'name': 'cool'}, - frozen: false, ); expect( diff --git a/packages/stream_chat/test/src/models/device_test.dart b/packages/stream_chat/test/src/models/device_test.dart index 27a94982..5cbf015d 100644 --- a/packages/stream_chat/test/src/models/device_test.dart +++ b/packages/stream_chat/test/src/models/device_test.dart @@ -5,7 +5,8 @@ import 'package:stream_chat/src/models/device.dart'; void main() { group('src/models/device', () { - const jsonExample = '''{ + const jsonExample = ''' + { "id": "device-id", "push_provider": "push-provider" }'''; diff --git a/packages/stream_chat/test/src/models/message_test.dart b/packages/stream_chat/test/src/models/message_test.dart index 0898e902..a34911cf 100644 --- a/packages/stream_chat/test/src/models/message_test.dart +++ b/packages/stream_chat/test/src/models/message_test.dart @@ -8,7 +8,8 @@ import 'package:stream_chat/src/models/user.dart'; void main() { group('src/models/message', () { - const jsonExample = r'''{ + const jsonExample = r''' + { "id": "4637f7e4-a06b-42db-ba5a-8d8270dd926f", "text": "https://giphy.com/gifs/the-lion-king-live-action-5zvN79uTGfLMOVfQaA", "type": "regular", @@ -103,7 +104,7 @@ void main() { 'https://giphy.com/gifs/the-lion-king-live-action-5zvN79uTGfLMOVfQaA', silent: false, attachments: [ - Attachment.fromJson({ + Attachment.fromJson(const { 'type': 'video', 'author_name': 'GIPHY', 'title': 'The Lion King Disney GIF - Find \u0026 Share on GIPHY', @@ -123,7 +124,7 @@ void main() { ], showInChannel: true, parentId: 'parentId', - extraData: {'hey': 'test'}, + extraData: const {'hey': 'test'}, ); expect(