fix: Review changes

This commit is contained in:
Deven Joshi
2021-04-16 13:41:05 +05:30
parent 834e29c3cc
commit be9c841c8a
12 changed files with 98 additions and 88 deletions
+13 -13
View File
@@ -249,13 +249,13 @@ class Channel {
Future<String> 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<UpdateMessageResponse?> 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<SendFileResponse?> sendFile(
AttachmentFile? file, {
AttachmentFile file, {
ProgressCallback? onSendProgress,
CancelToken? cancelToken,
}) =>
@@ -499,7 +500,7 @@ class Channel {
/// Send an image to this channel
Future<SendImageResponse?> 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<QueryRepliesResponse>(
response.data,
QueryRepliesResponse.fromJson,
)!;
);
state?.updateThreadInfo(parentId, repliesResponse.messages);
@@ -911,7 +912,7 @@ class Channel {
final res = _client.decode<GetMessagesByIdResponse>(
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() {
@@ -40,16 +40,17 @@ class RetryQueue {
}));
}
final HeapPriorityQueue<Message?> _messageQueue = HeapPriorityQueue(_byDate);
final HeapPriorityQueue<Message> _messageQueue = HeapPriorityQueue(_byDate);
bool _isRetrying = false;
RetryPolicy? _retryPolicy;
/// Add a list of messages
void add(List<Message?> messages) {
void add(List<Message> 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);
}
@@ -11,8 +11,8 @@ abstract class AttachmentFileUploader {
///
/// Optionally, access upload progress using [onSendProgress]
/// and cancel the request using [cancelToken]
Future<SendImageResponse?> sendImage(
AttachmentFile? image,
Future<SendImageResponse> 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<SendFileResponse?> sendFile(
AttachmentFile? file,
Future<SendFileResponse> 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<EmptyResponse?> deleteImage(
Future<EmptyResponse> 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<EmptyResponse?> deleteFile(
Future<EmptyResponse> deleteFile(
String url,
String? channelId,
String? channelType, {
@@ -63,14 +63,14 @@ class StreamAttachmentFileUploader implements AttachmentFileUploader {
final StreamChatClient _client;
@override
Future<SendImageResponse?> sendImage(
AttachmentFile? file,
Future<SendImageResponse> 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<SendFileResponse?> sendFile(
AttachmentFile? file,
Future<SendFileResponse> 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<EmptyResponse?> deleteImage(
Future<EmptyResponse> deleteImage(
String url,
String? channelId,
String? channelType, {
@@ -152,7 +152,7 @@ class StreamAttachmentFileUploader implements AttachmentFileUploader {
}
@override
Future<EmptyResponse?> deleteFile(
Future<EmptyResponse> deleteFile(
String url,
String? channelId,
String? channelType, {
+40 -41
View File
@@ -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<SyncResponse>(
rawRes.data,
SyncResponse.fromJson,
)!;
);
res.events!.sort((a, b) => a.createdAt!.compareTo(b.createdAt!));
@@ -737,7 +738,7 @@ class StreamChatClient {
final res = decode<QueryChannelsResponse>(
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<T>(String? j, DecoderFunction<T> decoderFunction) {
T decode<T>(String? j, DecoderFunction<T> 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<QueryUsersResponse>(
rawRes.data,
QueryUsersResponse.fromJson,
)!;
);
state?._updateUsers(response.users!);
@@ -1060,7 +1059,7 @@ class StreamChatClient {
}
/// A message search.
Future<SearchMessagesResponse?> search(
Future<SearchMessagesResponse> search(
Map<String, dynamic> filters, {
String? query,
List<SortOption>? sort,
@@ -1099,8 +1098,8 @@ class StreamChatClient {
}
/// Send a [file] to the [channelId] of type [channelType]
Future<SendFileResponse?> sendFile(
AttachmentFile? file,
Future<SendFileResponse> 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<SendImageResponse?> sendImage(
AttachmentFile? image,
Future<SendImageResponse> sendImage(
AttachmentFile image,
String? channelId,
String? channelType, {
ProgressCallback? onSendProgress,
@@ -1131,7 +1130,7 @@ class StreamChatClient {
);
/// Delete a file from this channel
Future<EmptyResponse?> deleteFile(
Future<EmptyResponse> deleteFile(
String url,
String? channelId,
String? channelType, {
@@ -1145,7 +1144,7 @@ class StreamChatClient {
);
/// Delete an image from this channel
Future<EmptyResponse?> deleteImage(
Future<EmptyResponse> deleteImage(
String url,
String? channelId,
String? channelType, {
@@ -1159,7 +1158,7 @@ class StreamChatClient {
);
/// Add a device for Push Notifications.
Future<EmptyResponse?> addDevice(String id, PushProvider pushProvider) async {
Future<EmptyResponse> 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<ListDevicesResponse?> getDevices() async {
Future<ListDevicesResponse> getDevices() async {
final response = await get('/devices');
return decode<ListDevicesResponse>(
response.data, ListDevicesResponse.fromJson);
}
/// Remove a user's device.
Future<EmptyResponse?> removeDevice(String id) async {
Future<EmptyResponse> 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<UpdateUsersResponse?> updateUser(User user) async =>
Future<UpdateUsersResponse> updateUser(User user) async =>
updateUsers([user]);
/// Batch update a list of users
Future<UpdateUsersResponse?> updateUsers(List<User> users) async {
Future<UpdateUsersResponse> updateUsers(List<User> 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<EmptyResponse?> banUser(
Future<EmptyResponse> banUser(
String targetUserID, [
Map<String, dynamic> options = const {},
]) async {
@@ -1237,7 +1236,7 @@ class StreamChatClient {
}
/// Remove global ban for a user
Future<EmptyResponse?> unbanUser(
Future<EmptyResponse> unbanUser(
String targetUserID, [
Map<String, dynamic> options = const {},
]) async {
@@ -1253,7 +1252,7 @@ class StreamChatClient {
}
/// Shadow bans a user
Future<EmptyResponse?> shadowBan(
Future<EmptyResponse> shadowBan(
String targetID, [
Map<String, dynamic> options = const {},
]) async =>
@@ -1263,7 +1262,7 @@ class StreamChatClient {
});
/// Removes shadow ban from a user
Future<EmptyResponse?> removeShadowBan(
Future<EmptyResponse> removeShadowBan(
String targetID, [
Map<String, dynamic> options = const {},
]) async =>
@@ -1273,7 +1272,7 @@ class StreamChatClient {
});
/// Mutes a user
Future<EmptyResponse?> muteUser(String targetID) async {
Future<EmptyResponse> muteUser(String targetID) async {
final response = await post('/moderation/mute', data: {
'target_id': targetID,
});
@@ -1281,7 +1280,7 @@ class StreamChatClient {
}
/// Unmutes a user
Future<EmptyResponse?> unmuteUser(String targetID) async {
Future<EmptyResponse> unmuteUser(String targetID) async {
final response = await post('/moderation/unmute', data: {
'target_id': targetID,
});
@@ -1289,7 +1288,7 @@ class StreamChatClient {
}
/// Flag a message
Future<EmptyResponse?> flagMessage(String messageID) async {
Future<EmptyResponse> 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<EmptyResponse?> unflagMessage(String messageId) async {
Future<EmptyResponse> 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<EmptyResponse?> flagUser(String userId) async {
Future<EmptyResponse> 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<EmptyResponse?> unflagUser(String userId) async {
Future<EmptyResponse> 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<EmptyResponse?> markAllRead() async {
Future<EmptyResponse> markAllRead() async {
final response = await post('/channels/read');
return decode(response.data, EmptyResponse.fromJson);
}
/// Sends the message to the given channel
Future<SendMessageResponse?> sendMessage(
Future<SendMessageResponse> 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<UpdateMessageResponse?> updateMessage(Message message) async {
Future<UpdateMessageResponse> 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<EmptyResponse?> deleteMessage(Message message) async {
Future<EmptyResponse> deleteMessage(Message message) async {
final response = await delete('/messages/${message.id}');
return decode(response.data, EmptyResponse.fromJson);
}
/// Get a message by id
Future<GetMessageResponse?> getMessage(String messageId) async {
Future<GetMessageResponse> getMessage(String messageId) async {
final response = await get('/messages/$messageId');
return decode(response.data, GetMessageResponse.fromJson);
}
/// Pins provided message
Future<UpdateMessageResponse?> pinMessage(
Future<UpdateMessageResponse> pinMessage(
Message message,
Object timeoutOrExpirationDate,
) {
@@ -1384,7 +1383,7 @@ class StreamChatClient {
}
/// Unpins provided message
Future<UpdateMessageResponse?> unpinMessage(Message message) =>
Future<UpdateMessageResponse> unpinMessage(Message message) =>
updateMessage(message.copyWith(pinned: false));
}
@@ -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<void> connect(String? userId);
Future<void> 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<void> updateConnectionInfo(Event event);
/// Update stored lastSyncAt
Future<void> updateLastSyncAt(DateTime? lastSyncAt);
Future<void> updateLastSyncAt(DateTime lastSyncAt);
/// Get the channel cids saved in the offline storage
Future<List<String>> getChannelCids();
@@ -638,7 +638,6 @@ void main() {
Reaction(
type: 'test',
createdAt: DateTime.now(),
score: 0,
user: User(
id: client.state?.user?.id ?? '',
),
@@ -777,7 +777,7 @@ void main() {
),
);
await client.deleteMessage(Message(id: messageId, text: ''));
await client.deleteMessage(Message(id: messageId));
verify(() => mockDio.delete<String>('/messages/$messageId')).called(1);
});
@@ -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",
@@ -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",
@@ -44,7 +44,6 @@ void main() {
id: 'id',
cid: 'a:a',
extraData: {'name': 'cool'},
frozen: false,
);
expect(
@@ -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"
}''';
@@ -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(