From fe07b8dbb0010bdcb809bf7700cd8759a5a463a1 Mon Sep 17 00:00:00 2001 From: Deven Joshi Date: Tue, 13 Apr 2021 18:20:43 +0530 Subject: [PATCH] feat: Converted to ios models --- packages/stream_chat/example/lib/main.dart | 2 +- packages/stream_chat/lib/src/api/channel.dart | 102 +++++++++--------- packages/stream_chat/lib/src/client.dart | 6 +- .../lib/src/db/chat_persistence_client.dart | 31 +++--- .../lib/src/models/attachment.dart | 4 +- .../lib/src/models/attachment.g.dart | 7 +- .../lib/src/models/channel_model.dart | 39 ++++--- .../lib/src/models/channel_model.g.dart | 22 ++-- .../lib/src/models/channel_state.dart | 10 +- .../lib/src/models/channel_state.g.dart | 30 +++--- .../stream_chat/lib/src/models/device.dart | 4 +- .../stream_chat/lib/src/models/device.g.dart | 2 +- .../stream_chat/lib/src/models/event.dart | 12 +-- .../stream_chat/lib/src/models/event.g.dart | 22 ++-- .../stream_chat/lib/src/models/member.dart | 24 ++--- .../stream_chat/lib/src/models/member.g.dart | 20 ++-- .../stream_chat/lib/src/models/message.dart | 57 ++++++++-- .../stream_chat/lib/src/models/message.g.dart | 12 +-- .../stream_chat/lib/src/models/own_user.dart | 50 ++++++--- .../lib/src/models/own_user.g.dart | 37 +++---- .../stream_chat/lib/src/models/reaction.dart | 18 ++-- .../lib/src/models/reaction.g.dart | 16 ++- packages/stream_chat/lib/src/models/read.dart | 12 +-- .../stream_chat/lib/src/models/read.g.dart | 18 ++-- packages/stream_chat/lib/src/models/user.dart | 64 ++++++----- .../stream_chat/lib/src/models/user.g.dart | 24 ++--- .../test/src/api/channel_test.dart | 41 ++++--- .../test/src/api/websocket_test.dart | 16 +-- .../stream_chat/test/src/client_test.dart | 24 +++-- .../test/src/models/channel_state_test.dart | 4 +- .../test/src/models/channel_test.dart | 4 +- .../test/src/models/event_test.dart | 4 +- .../test/src/models/message_test.dart | 2 +- .../test/src/models/reaction_test.dart | 6 +- .../test/src/models/read_test.dart | 2 +- .../test/src/models/user_test.dart | 2 +- 36 files changed, 406 insertions(+), 344 deletions(-) diff --git a/packages/stream_chat/example/lib/main.dart b/packages/stream_chat/example/lib/main.dart index d13dda4c..878b5fa1 100644 --- a/packages/stream_chat/example/lib/main.dart +++ b/packages/stream_chat/example/lib/main.dart @@ -11,7 +11,7 @@ Future main() async { /// Please see the following for more information: /// https://getstream.io/chat/docs/ios_user_setup_and_tokens/ await client.connectUser( - User( + User.temp( id: 'cool-shadow-7', extraData: { 'image': diff --git a/packages/stream_chat/lib/src/api/channel.dart b/packages/stream_chat/lib/src/api/channel.dart index 7421daa7..80f34ccb 100644 --- a/packages/stream_chat/lib/src/api/channel.dart +++ b/packages/stream_chat/lib/src/api/channel.dart @@ -59,12 +59,12 @@ class Channel { /// Returns true if the channel is muted bool get isMuted => _client.state!.user?.channelMutes - ?.any((element) => element.channel!.cid == cid) == + .any((element) => element.channel!.cid == cid) == true; /// Returns true if the channel is muted as a stream Stream? get isMutedStream => _client.state!.userStream.map((event) => - event!.channelMutes?.any((element) => element.channel!.cid == cid) == + event!.channelMutes.any((element) => element.channel!.cid == cid) == true); /// True if the channel is a group @@ -309,7 +309,7 @@ class Channel { ); // ignore: parameter_assignments message = message.copyWith( - createdAt: message.createdAt ?? DateTime.now(), + createdAt: message.createdAt, user: _client.state!.user, quotedMessage: quotedMessage, status: MessageSendingStatus.sending, @@ -363,7 +363,7 @@ class Channel { // ignore: parameter_assignments message = message.copyWith( status: MessageSendingStatus.updating, - updatedAt: message.updatedAt ?? DateTime.now(), + updatedAt: message.updatedAt, attachments: message.attachments?.map( (it) { if (it.uploadState.isSuccess) return it; @@ -574,7 +574,7 @@ class Channel { messageId: messageId, createdAt: now, type: type, - user: user, + user: user!, score: 1, extraData: extraData, ); @@ -582,7 +582,7 @@ class Channel { // Inserting at the 0th index as it's the latest reaction latestReactions.insert(0, newReaction); final ownReactions = [...latestReactions] - ..removeWhere((it) => it.userId != user!.id); + ..removeWhere((it) => it.userId != user.id); final newMessage = message.copyWith( reactionCounts: {...message.reactionCounts ?? {}} @@ -632,15 +632,11 @@ class Channel { final reactionCounts = {...message.reactionCounts ?? {}}; if (reactionCounts.containsKey(type)) { - if (type != null) { - reactionCounts.update(type, (value) => value - 1); - } + reactionCounts.update(type, (value) => value - 1); } final reactionScores = {...message.reactionScores ?? {}}; if (reactionScores.containsKey(type)) { - if (type != null) { - reactionScores.update(type, (value) => value - 1); - } + reactionScores.update(type, (value) => value - 1); } final latestReactions = [...message.latestReactions ?? []] @@ -917,7 +913,11 @@ class Channel { GetMessagesByIdResponse.fromJson, )!; - state?.updateChannelState(ChannelState(messages: res.messages)); + final messages = res.messages; + + if (messages != null) { + state?.updateChannelState(ChannelState(messages: messages)); + } return res; } @@ -987,7 +987,7 @@ class Channel { cid, messagePagination: messagesPagination, ))!; - if (updatedState.messages!.isNotEmpty) { + if (updatedState.messages.isNotEmpty) { if (state == null) { _initState(updatedState); } else { @@ -1270,17 +1270,17 @@ class ChannelClientState { final _subscriptions = []; void _computeInitialUnread() { - final userRead = channelState?.read?.firstWhereOrNull( - (r) => r.user!.id == _channel._client.state?.user?.id, + final userRead = channelState?.read.firstWhereOrNull( + (r) => r.user.id == _channel._client.state?.user?.id, ); if (userRead != null) { - _unreadCountController.add(userRead.unreadMessages ?? 0); + _unreadCountController.add(userRead.unreadMessages); } } void _checkExpiredAttachmentMessages(ChannelState channelState) { final expiredAttachmentMessagesId = channelState.messages - ?.where((m) => + .where((m) => !_updatedMessagesIds.contains(m.id) && m.attachments?.isNotEmpty == true && m.attachments?.any((e) { @@ -1300,8 +1300,8 @@ class ChannelClientState { true) .map((e) => e.id) .toList(); - if (expiredAttachmentMessagesId?.isNotEmpty == true) { - _channel.getMessagesById(expiredAttachmentMessagesId!); + if (expiredAttachmentMessagesId.isNotEmpty == true) { + _channel.getMessagesById(expiredAttachmentMessagesId); _updatedMessagesIds.addAll(expiredAttachmentMessagesId); } } @@ -1311,7 +1311,7 @@ class ChannelClientState { final member = e.member; updateChannelState(channelState!.copyWith( members: [ - ...channelState!.members!, + ...channelState!.members, member, ], )); @@ -1323,7 +1323,7 @@ class ChannelClientState { final user = e.user; updateChannelState(channelState!.copyWith( members: List.from( - channelState!.members!..removeWhere((m) => m!.userId == user!.id)), + channelState!.members..removeWhere((m) => m!.userId == user!.id)), )); })); } @@ -1373,7 +1373,7 @@ class ChannelClientState { .where( (message) => message.status != MessageSendingStatus.sent && - message.createdAt!.isBefore( + message.createdAt.isBefore( DateTime.now().subtract( const Duration( seconds: 1, @@ -1425,7 +1425,7 @@ class ChannelClientState { if (message.pinned == true) { _channelState = _channelState!.copyWith( pinnedMessages: [ - ..._channelState!.pinnedMessages ?? [], + ..._channelState!.pinnedMessages, message, ], ); @@ -1462,7 +1462,7 @@ class ChannelClientState { /// Add a message to this channel void addMessage(Message message) { if (message.parentId == null || message.showInChannel == true) { - final newMessages = List.from(_channelState!.messages!); + final newMessages = List.from(_channelState!.messages); final oldIndex = newMessages.indexWhere((m) => m.id == message.id); if (oldIndex != -1) { Message? m; @@ -1505,16 +1505,17 @@ class ChannelClientState { (event) { final readList = List.from(_channelState?.read ?? []); final userReadIndex = - read?.indexWhere((r) => r.user!.id == event.user!.id); + read?.indexWhere((r) => r.user.id == event.user!.id); if (userReadIndex != null && userReadIndex != -1) { final userRead = readList.removeAt(userReadIndex); - if (userRead.user?.id == _channel._client.state!.user!.id) { + if (userRead.user.id == _channel._client.state!.user!.id) { _unreadCountController.add(0); } readList.add(Read( - user: event.user, - lastRead: event.createdAt, + user: event.user!, + lastRead: event.createdAt!, + unreadMessages: event.totalUnreadCount!, )); _channelState = _channelState!.copyWith(read: readList); } @@ -1531,15 +1532,15 @@ class ChannelClientState { channelStateStream.map((cs) => cs!.messages); /// Channel pinned message list - List? get pinnedMessages => _channelState!.pinnedMessages?.toList(); + List? get pinnedMessages => _channelState!.pinnedMessages.toList(); /// Channel pinned message list as a stream Stream?> get pinnedMessagesStream => - channelStateStream.map((cs) => cs!.pinnedMessages?.toList()); + channelStateStream.map((cs) => cs!.pinnedMessages.toList()); /// Get channel last message - Message? get lastMessage => _channelState!.messages?.isNotEmpty == true - ? _channelState!.messages!.last + Message? get lastMessage => _channelState!.messages.isNotEmpty == true + ? _channelState!.messages.last : null; /// Get channel last message @@ -1547,8 +1548,8 @@ class ChannelClientState { .map((event) => event?.isNotEmpty == true ? event!.last : null); /// Channel members list - List get members => _channelState!.members! - .map((e) => e!.copyWith(user: _channel.client.state!.users[e.user!.id!])) + List get members => _channelState!.members + .map((e) => e!.copyWith(user: _channel.client.state!.users[e.user!.id])) .toList(); /// Channel members list as a stream @@ -1568,8 +1569,8 @@ class ChannelClientState { channelStateStream.map((cs) => cs!.watcherCount); /// Channel watchers list - List get watchers => _channelState!.watchers! - .map((e) => _channel.client.state!.users[e.id!] ?? e) + List get watchers => _channelState!.watchers + .map((e) => _channel.client.state!.users[e.id] ?? e) .toList(); /// Channel watchers list as a stream @@ -1597,7 +1598,7 @@ class ChannelClientState { bool _countMessageAsUnread(Message message) { final userId = _channel.client.state?.user?.id; - final userIsMuted = _channel.client.state?.user?.mutes?.firstWhereOrNull( + final userIsMuted = _channel.client.state?.user?.mutes.firstWhereOrNull( (m) => m.user?.id == message.user!.id, ) != null; @@ -1642,37 +1643,37 @@ class ChannelClientState { /// Update channelState with updated information void updateChannelState(ChannelState updatedState) { final newMessages = [ - ...updatedState.messages ?? [], + ...updatedState.messages, ..._channelState?.messages - ?.where((m) => + .where((m) => updatedState.messages - ?.any((newMessage) => newMessage.id == m.id) != + .any((newMessage) => newMessage.id == m.id) != true) .toList() ?? [], ]..sort(_sortByCreatedAt as int Function(Message, Message)?); final newWatchers = [ - ...updatedState.watchers ?? [], + ...updatedState.watchers, ..._channelState?.watchers - ?.where((w) => + .where((w) => updatedState.watchers - ?.any((newWatcher) => newWatcher.id == w.id) != + .any((newWatcher) => newWatcher.id == w.id) != true) .toList() ?? [], ]; final newMembers = [ - ...updatedState.members ?? [], + ...updatedState.members, ]; final newReads = [ - ...updatedState.read ?? [], + ...updatedState.read, ..._channelState?.read - ?.where((r) => + .where((r) => updatedState.read - ?.any((newRead) => newRead.user!.id == r.user!.id) != + .any((newRead) => newRead.user.id == r.user.id) != true) .toList() ?? [], @@ -1828,9 +1829,8 @@ class ChannelClientState { _pinnedMessagesTimer = Timer.periodic(const Duration(seconds: 30), (_) { final now = DateTime.now(); var expiredMessages = channelState!.pinnedMessages - ?.where((m) => m.pinExpires?.isBefore(now) == true) - .toList() ?? - []; + .where((m) => m.pinExpires?.isBefore(now) == true) + .toList(); if (expiredMessages.isNotEmpty) { expiredMessages = expiredMessages .map((m) => m.copyWith( diff --git a/packages/stream_chat/lib/src/client.dart b/packages/stream_chat/lib/src/client.dart index f6b9da79..4b06788e 100644 --- a/packages/stream_chat/lib/src/client.dart +++ b/packages/stream_chat/lib/src/client.dart @@ -311,7 +311,7 @@ class StreamChatClient { httpClient.unlock(); - await connectUser(User(id: userId), newToken); + await connectUser(User.temp(id: userId), newToken); try { handler.resolve( @@ -750,7 +750,7 @@ class StreamChatClient { final channels = res.channels!; final users = channels - .expand((it) => it.members!) + .expand((it) => it.members) .map((it) => it!.user) .toList(growable: false); @@ -954,7 +954,7 @@ class StreamChatClient { _anonymous = true; const uuid = Uuid(); - state!.user = OwnUser(id: uuid.v4()); + state!.user = OwnUser.temp(id: uuid.v4()); return connect().then((event) { _connectCompleter!.complete(event); 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 b3ea7c7e..7911a986 100644 --- a/packages/stream_chat/lib/src/db/chat_persistence_client.dart +++ b/packages/stream_chat/lib/src/db/chat_persistence_client.dart @@ -76,11 +76,11 @@ abstract class ChatPersistenceClient { getPinnedMessagesByCid(cid, messagePagination: pinnedMessagePagination), ]); return ChannelState( - members: data[0] as List?, - read: data[1] as List?, + members: (data[0] as List?)!, + read: (data[1] as List?)!, channel: data[2] as ChannelModel?, - messages: data[3] as List?, - pinnedMessages: data[4] as List?, + messages: (data[3] as List?)!, + pinnedMessages: (data[4] as List?)!, ); } @@ -176,7 +176,7 @@ abstract class ChatPersistenceClient { /// Update list of channel states Future updateChannelStates(List channelStates) async { final deleteReactions = deleteReactionsByMessageId(channelStates - .expand((it) => it.messages!) + .expand((it) => it.messages) .map((m) => m.id) .toList(growable: false)); @@ -193,20 +193,19 @@ abstract class ChatPersistenceClient { channelStates.map((it) => it.channel).where((it) => it != null); final reactions = channelStates - .expand((it) => it.messages!) + .expand((it) => it.messages) .expand((it) => [ if (it.ownReactions != null) ...it.ownReactions!.where((r) => r.userId != null), if (it.latestReactions != null) ...it.latestReactions!.where((r) => r.userId != null) - ]) - .where((it) => it != null); + ]); final users = channelStates .map((cs) => [ cs.channel?.createdBy, - ...?cs.messages - ?.map((m) => [ + ...cs.messages + .map((m) => [ m.user, if (m.latestReactions != null) ...m.latestReactions!.map((r) => r.user), @@ -214,33 +213,33 @@ abstract class ChatPersistenceClient { ...m.ownReactions!.map((r) => r.user), ]) .expand((v) => v), - if (cs.read != null) ...cs.read!.map((r) => r.user), - if (cs.members != null) ...cs.members!.map((m) => m!.user), + ...cs.read.map((r) => r.user), + ...cs.members.map((m) => m!.user), ]) .expand((it) => it) .where((it) => it != null); final updateMessagesFuture = channelStates.map((it) { final cid = it.channel!.cid; - final messages = it.messages!.where((it) => it != null); + final messages = it.messages; return updateMessages(cid, messages.toList(growable: false)); }).toList(growable: false); final updatePinnedMessagesFuture = channelStates.map((it) { final cid = it.channel!.cid; - final messages = it.pinnedMessages!.where((it) => it != null); + final messages = it.pinnedMessages; return updatePinnedMessages(cid, messages.toList(growable: false)); }).toList(growable: false); final updateReadsFuture = channelStates.map((it) { final cid = it.channel!.cid; - final reads = it.read?.where((it) => it != null) ?? []; + final reads = it.read; return updateReads(cid, reads.toList(growable: false)); }).toList(growable: false); final updateMembersFuture = channelStates.map((it) { final cid = it.channel!.cid; - final members = it.members!.where((it) => it != null); + final members = it.members.where((it) => it != null); return updateMembers(cid, members.toList(growable: false)); }).toList(growable: false); diff --git a/packages/stream_chat/lib/src/models/attachment.dart b/packages/stream_chat/lib/src/models/attachment.dart index 0ba66667..61f7afdf 100644 --- a/packages/stream_chat/lib/src/models/attachment.dart +++ b/packages/stream_chat/lib/src/models/attachment.dart @@ -15,7 +15,7 @@ class Attachment extends Equatable { /// Constructor used for json serialization Attachment({ String? id, - this.type, + required this.type, this.titleLink, String? title, this.thumbUrl, @@ -57,7 +57,7 @@ class Attachment extends Equatable { ///The attachment type based on the URL resource. This can be: audio, ///image or video - final String? type; + final String type; ///The link to which the attachment message points to. final String? titleLink; diff --git a/packages/stream_chat/lib/src/models/attachment.g.dart b/packages/stream_chat/lib/src/models/attachment.g.dart index a992096f..207cc02f 100644 --- a/packages/stream_chat/lib/src/models/attachment.g.dart +++ b/packages/stream_chat/lib/src/models/attachment.g.dart @@ -9,7 +9,7 @@ part of 'attachment.dart'; Attachment _$AttachmentFromJson(Map json) { return Attachment( id: json['id'] as String?, - type: json['type'] as String?, + type: json['type'] as String, titleLink: json['title_link'] as String?, title: json['title'] as String?, thumbUrl: json['thumb_url'] as String?, @@ -44,7 +44,9 @@ Attachment _$AttachmentFromJson(Map json) { } Map _$AttachmentToJson(Attachment instance) { - final val = {}; + final val = { + 'type': instance.type, + }; void writeNotNull(String key, dynamic value) { if (value != null) { @@ -52,7 +54,6 @@ Map _$AttachmentToJson(Attachment instance) { } } - writeNotNull('type', instance.type); writeNotNull('title_link', instance.titleLink); writeNotNull('title', instance.title); writeNotNull('thumb_url', instance.thumbUrl); diff --git a/packages/stream_chat/lib/src/models/channel_model.dart b/packages/stream_chat/lib/src/models/channel_model.dart index 827f1246..caffc30a 100644 --- a/packages/stream_chat/lib/src/models/channel_model.dart +++ b/packages/stream_chat/lib/src/models/channel_model.dart @@ -12,19 +12,34 @@ class ChannelModel { ChannelModel({ this.id, this.type, - this.cid, - this.config, + required this.cid, + required this.config, this.createdBy, - this.frozen, + this.frozen = false, this.lastMessageAt, - this.createdAt, - this.updatedAt, + required this.createdAt, + required this.updatedAt, this.deletedAt, - this.memberCount, + this.memberCount = 0, this.extraData, this.team, }); + ChannelModel.temp({ + this.id, + this.type, + required this.cid, + this.createdBy, + this.frozen = false, + this.lastMessageAt, + this.deletedAt, + this.memberCount = 0, + this.extraData, + this.team, + }) : createdAt = DateTime.now(), + updatedAt = DateTime.now(), + config = ChannelConfig(); + /// Create a new instance from a json factory ChannelModel.fromJson(Map? json) => _$ChannelModelFromJson( @@ -38,11 +53,11 @@ class ChannelModel { /// The cid of this channel @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final String? cid; + final String cid; /// The channel configuration data @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final ChannelConfig? config; + final ChannelConfig config; /// The user that created this channel @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) @@ -50,7 +65,7 @@ class ChannelModel { /// True if this channel is frozen @JsonKey(includeIfNull: false) - final bool? frozen; + final bool frozen; /// The date of the last message @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) @@ -58,11 +73,11 @@ class ChannelModel { /// The date of channel creation @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final DateTime? createdAt; + final DateTime createdAt; /// The date of the last channel update @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final DateTime? updatedAt; + final DateTime updatedAt; /// The date of channel deletion @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) @@ -70,7 +85,7 @@ class ChannelModel { /// The count of this channel members @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final int? memberCount; + final int memberCount; /// Map of custom channel extraData @JsonKey(includeIfNull: false) diff --git a/packages/stream_chat/lib/src/models/channel_model.g.dart b/packages/stream_chat/lib/src/models/channel_model.g.dart index 9b1a6aeb..098a22e8 100644 --- a/packages/stream_chat/lib/src/models/channel_model.g.dart +++ b/packages/stream_chat/lib/src/models/channel_model.g.dart @@ -10,30 +10,24 @@ ChannelModel _$ChannelModelFromJson(Map json) { return ChannelModel( id: json['id'] as String?, type: json['type'] as String?, - cid: json['cid'] as String?, - config: json['config'] == null - ? null - : ChannelConfig.fromJson( - Map.from(json['config'] as Map)), + cid: json['cid'] as String, + config: ChannelConfig.fromJson( + Map.from(json['config'] as Map)), createdBy: json['created_by'] == null ? null : User.fromJson((json['created_by'] as Map?)?.map( (k, e) => MapEntry(k as String, e), )), - frozen: json['frozen'] as bool?, + frozen: json['frozen'] as bool, lastMessageAt: json['last_message_at'] == null ? null : DateTime.parse(json['last_message_at'] as String), - createdAt: json['created_at'] == null - ? null - : DateTime.parse(json['created_at'] as String), - updatedAt: json['updated_at'] == null - ? null - : DateTime.parse(json['updated_at'] as String), + createdAt: DateTime.parse(json['created_at'] as String), + updatedAt: DateTime.parse(json['updated_at'] as String), deletedAt: json['deleted_at'] == null ? null : DateTime.parse(json['deleted_at'] as String), - memberCount: json['member_count'] as int?, + memberCount: json['member_count'] as int, extraData: (json['extra_data'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ), @@ -56,7 +50,7 @@ Map _$ChannelModelToJson(ChannelModel instance) { writeNotNull('cid', readonly(instance.cid)); writeNotNull('config', readonly(instance.config)); writeNotNull('created_by', readonly(instance.createdBy)); - writeNotNull('frozen', instance.frozen); + val['frozen'] = instance.frozen; writeNotNull('last_message_at', readonly(instance.lastMessageAt)); writeNotNull('created_at', readonly(instance.createdAt)); writeNotNull('updated_at', readonly(instance.updatedAt)); diff --git a/packages/stream_chat/lib/src/models/channel_state.dart b/packages/stream_chat/lib/src/models/channel_state.dart index c90e6298..5f9f02bf 100644 --- a/packages/stream_chat/lib/src/models/channel_state.dart +++ b/packages/stream_chat/lib/src/models/channel_state.dart @@ -25,22 +25,22 @@ class ChannelState { final ChannelModel? channel; /// A paginated list of channel messages - final List? messages; + final List messages; /// A paginated list of channel members - final List? members; + final List members; /// A paginated list of pinned messages - final List? pinnedMessages; + final List pinnedMessages; /// The count of users watching the channel final int? watcherCount; /// A paginated list of users watching the channel - final List? watchers; + final List watchers; /// The list of channel reads - final List? read; + final List read; /// Create a new instance from a json static ChannelState fromJson(Map json) => diff --git a/packages/stream_chat/lib/src/models/channel_state.g.dart b/packages/stream_chat/lib/src/models/channel_state.g.dart index 2eaa02d2..c207a2f6 100644 --- a/packages/stream_chat/lib/src/models/channel_state.g.dart +++ b/packages/stream_chat/lib/src/models/channel_state.g.dart @@ -13,29 +13,29 @@ ChannelState _$ChannelStateFromJson(Map json) { : ChannelModel.fromJson((json['channel'] as Map?)?.map( (k, e) => MapEntry(k as String, e), )), - messages: (json['messages'] as List?) - ?.map((e) => Message.fromJson((e as Map?)?.map( + messages: (json['messages'] as List) + .map((e) => Message.fromJson((e as Map?)?.map( (k, e) => MapEntry(k as String, e), ))) .toList(), - members: (json['members'] as List?) - ?.map((e) => e == null + members: (json['members'] as List) + .map((e) => e == null ? null : Member.fromJson(Map.from(e as Map))) .toList(), - pinnedMessages: (json['pinned_messages'] as List?) - ?.map((e) => Message.fromJson((e as Map?)?.map( + pinnedMessages: (json['pinned_messages'] as List) + .map((e) => Message.fromJson((e as Map?)?.map( (k, e) => MapEntry(k as String, e), ))) .toList(), watcherCount: json['watcher_count'] as int?, - watchers: (json['watchers'] as List?) - ?.map((e) => User.fromJson((e as Map?)?.map( + watchers: (json['watchers'] as List) + .map((e) => User.fromJson((e as Map?)?.map( (k, e) => MapEntry(k as String, e), ))) .toList(), - read: (json['read'] as List?) - ?.map((e) => Read.fromJson(Map.from(e as Map))) + read: (json['read'] as List) + .map((e) => Read.fromJson(Map.from(e as Map))) .toList(), ); } @@ -43,11 +43,11 @@ ChannelState _$ChannelStateFromJson(Map json) { Map _$ChannelStateToJson(ChannelState instance) => { 'channel': instance.channel?.toJson(), - 'messages': instance.messages?.map((e) => e.toJson()).toList(), - 'members': instance.members?.map((e) => e?.toJson()).toList(), + 'messages': instance.messages.map((e) => e.toJson()).toList(), + 'members': instance.members.map((e) => e?.toJson()).toList(), 'pinned_messages': - instance.pinnedMessages?.map((e) => e.toJson()).toList(), + instance.pinnedMessages.map((e) => e.toJson()).toList(), 'watcher_count': instance.watcherCount, - 'watchers': instance.watchers?.map((e) => e.toJson()).toList(), - 'read': instance.read?.map((e) => e.toJson()).toList(), + 'watchers': instance.watchers.map((e) => e.toJson()).toList(), + 'read': instance.read.map((e) => e.toJson()).toList(), }; diff --git a/packages/stream_chat/lib/src/models/device.dart b/packages/stream_chat/lib/src/models/device.dart index 28481282..dc613b3c 100644 --- a/packages/stream_chat/lib/src/models/device.dart +++ b/packages/stream_chat/lib/src/models/device.dart @@ -7,7 +7,7 @@ part 'device.g.dart'; class Device { /// Constructor used for json serialization Device({ - this.id, + required this.id, this.pushProvider, }); @@ -15,7 +15,7 @@ class Device { factory Device.fromJson(Map json) => _$DeviceFromJson(json); /// The id of the device - final String? id; + final String id; /// The notification push provider final String? pushProvider; diff --git a/packages/stream_chat/lib/src/models/device.g.dart b/packages/stream_chat/lib/src/models/device.g.dart index ff4acc89..343ec0e5 100644 --- a/packages/stream_chat/lib/src/models/device.g.dart +++ b/packages/stream_chat/lib/src/models/device.g.dart @@ -8,7 +8,7 @@ part of 'device.dart'; Device _$DeviceFromJson(Map json) { return Device( - id: json['id'] as String?, + id: json['id'] as String, pushProvider: json['push_provider'] as String?, ); } diff --git a/packages/stream_chat/lib/src/models/event.dart b/packages/stream_chat/lib/src/models/event.dart index ab97d86f..295d6d8d 100644 --- a/packages/stream_chat/lib/src/models/event.dart +++ b/packages/stream_chat/lib/src/models/event.dart @@ -171,15 +171,15 @@ class EventChannel extends ChannelModel { this.members, String? id, String? type, - String? cid, - ChannelConfig? config, + required String cid, + required ChannelConfig config, User? createdBy, - bool? frozen, + bool frozen = false, DateTime? lastMessageAt, - DateTime? createdAt, - DateTime? updatedAt, + required DateTime createdAt, + required DateTime updatedAt, DateTime? deletedAt, - int? memberCount, + required int memberCount, Map? extraData, }) : super( id: id, diff --git a/packages/stream_chat/lib/src/models/event.g.dart b/packages/stream_chat/lib/src/models/event.g.dart index 71566caf..5e1e7e58 100644 --- a/packages/stream_chat/lib/src/models/event.g.dart +++ b/packages/stream_chat/lib/src/models/event.g.dart @@ -92,30 +92,24 @@ EventChannel _$EventChannelFromJson(Map json) { .toList(), id: json['id'] as String?, type: json['type'] as String?, - cid: json['cid'] as String?, - config: json['config'] == null - ? null - : ChannelConfig.fromJson( - Map.from(json['config'] as Map)), + cid: json['cid'] as String, + config: ChannelConfig.fromJson( + Map.from(json['config'] as Map)), createdBy: json['created_by'] == null ? null : User.fromJson((json['created_by'] as Map?)?.map( (k, e) => MapEntry(k as String, e), )), - frozen: json['frozen'] as bool?, + frozen: json['frozen'] as bool, lastMessageAt: json['last_message_at'] == null ? null : DateTime.parse(json['last_message_at'] as String), - createdAt: json['created_at'] == null - ? null - : DateTime.parse(json['created_at'] as String), - updatedAt: json['updated_at'] == null - ? null - : DateTime.parse(json['updated_at'] as String), + createdAt: DateTime.parse(json['created_at'] as String), + updatedAt: DateTime.parse(json['updated_at'] as String), deletedAt: json['deleted_at'] == null ? null : DateTime.parse(json['deleted_at'] as String), - memberCount: json['member_count'] as int?, + memberCount: json['member_count'] as int, extraData: (json['extra_data'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ), @@ -137,7 +131,7 @@ Map _$EventChannelToJson(EventChannel instance) { writeNotNull('cid', readonly(instance.cid)); writeNotNull('config', readonly(instance.config)); writeNotNull('created_by', readonly(instance.createdBy)); - writeNotNull('frozen', instance.frozen); + val['frozen'] = instance.frozen; writeNotNull('last_message_at', readonly(instance.lastMessageAt)); writeNotNull('created_at', readonly(instance.createdAt)); writeNotNull('updated_at', readonly(instance.updatedAt)); diff --git a/packages/stream_chat/lib/src/models/member.dart b/packages/stream_chat/lib/src/models/member.dart index bd2bed8a..735e4ff3 100644 --- a/packages/stream_chat/lib/src/models/member.dart +++ b/packages/stream_chat/lib/src/models/member.dart @@ -12,14 +12,14 @@ class Member { this.user, this.inviteAcceptedAt, this.inviteRejectedAt, - this.invited, - this.role, + this.invited = false, + required this.role, this.userId, this.isModerator, - this.createdAt, - this.updatedAt, - this.banned, - this.shadowBanned, + required this.createdAt, + required this.updatedAt, + this.banned = false, + this.shadowBanned = false, }); /// Create a new instance from a json @@ -40,10 +40,10 @@ class Member { final DateTime? inviteRejectedAt; /// True if the user has been invited to the channel - final bool? invited; + final bool invited; /// The role of the user in the channel - final String? role; + final String role; /// The id of the interested user final String? userId; @@ -52,16 +52,16 @@ class Member { final bool? isModerator; /// True if the member is banned from the channel - final bool? banned; + final bool banned; /// True if the member is shadow banned from the channel - final bool? shadowBanned; + final bool shadowBanned; /// The date of creation - final DateTime? createdAt; + final DateTime createdAt; /// The last date of update - final DateTime? updatedAt; + final DateTime updatedAt; /// Creates a copy of [Member] with specified attributes overridden. Member copyWith({ diff --git a/packages/stream_chat/lib/src/models/member.g.dart b/packages/stream_chat/lib/src/models/member.g.dart index 52391699..f6716e3d 100644 --- a/packages/stream_chat/lib/src/models/member.g.dart +++ b/packages/stream_chat/lib/src/models/member.g.dart @@ -19,18 +19,14 @@ Member _$MemberFromJson(Map json) { inviteRejectedAt: json['invite_rejected_at'] == null ? null : DateTime.parse(json['invite_rejected_at'] as String), - invited: json['invited'] as bool?, - role: json['role'] as String?, + invited: json['invited'] as bool, + role: json['role'] as String, userId: json['user_id'] as String?, isModerator: json['is_moderator'] as bool?, - createdAt: json['created_at'] == null - ? null - : DateTime.parse(json['created_at'] as String), - updatedAt: json['updated_at'] == null - ? null - : DateTime.parse(json['updated_at'] as String), - banned: json['banned'] as bool?, - shadowBanned: json['shadow_banned'] as bool?, + createdAt: DateTime.parse(json['created_at'] as String), + updatedAt: DateTime.parse(json['updated_at'] as String), + banned: json['banned'] as bool, + shadowBanned: json['shadow_banned'] as bool, ); } @@ -44,6 +40,6 @@ Map _$MemberToJson(Member instance) => { 'is_moderator': instance.isModerator, 'banned': instance.banned, 'shadow_banned': instance.shadowBanned, - 'created_at': instance.createdAt?.toIso8601String(), - 'updated_at': instance.updatedAt?.toIso8601String(), + 'created_at': instance.createdAt.toIso8601String(), + 'updated_at': instance.updatedAt.toIso8601String(), }; diff --git a/packages/stream_chat/lib/src/models/message.dart b/packages/stream_chat/lib/src/models/message.dart index 1849eb81..8f260b1b 100644 --- a/packages/stream_chat/lib/src/models/message.dart +++ b/packages/stream_chat/lib/src/models/message.dart @@ -46,8 +46,8 @@ class Message extends Equatable { /// Constructor used for json serialization Message({ String? id, - this.text, - this.type, + required this.text, + required this.type, this.attachments, this.mentionedUsers, this.silent, @@ -63,8 +63,8 @@ class Message extends Equatable { this.threadParticipants, this.showInChannel, this.command, - this.createdAt, - this.updatedAt, + required this.createdAt, + required this.updatedAt, this.user, this.pinned = false, this.pinnedAt, @@ -77,6 +77,40 @@ class Message extends Equatable { }) : id = id ?? const Uuid().v4(), pinExpires = pinExpires?.toUtc(); + /// Constructor for creating temporary/throwaway message with id and text + Message.temp({ + String? id, + required this.text, + this.attachments, + this.mentionedUsers, + this.silent, + this.shadowed, + this.reactionCounts, + this.reactionScores, + this.latestReactions, + this.ownReactions, + this.parentId, + this.quotedMessage, + this.quotedMessageId, + this.replyCount = 0, + this.threadParticipants, + this.showInChannel, + this.command, + this.user, + this.pinned = false, + this.pinnedAt, + DateTime? pinExpires, + this.pinnedBy, + this.extraData, + this.deletedAt, + this.status = MessageSendingStatus.sent, + this.skipPush, + }) : id = id ?? const Uuid().v4(), + pinExpires = pinExpires?.toUtc(), + createdAt = DateTime.now(), + updatedAt = DateTime.now(), + type = ''; + /// Create a new instance from a json factory Message.fromJson(Map? json) => _$MessageFromJson( Serialization.moveToExtraDataFromRoot(json, topLevelFields)!); @@ -86,7 +120,7 @@ class Message extends Equatable { final String id; /// The text of this message - final String? text; + final String text; /// The status of a sending message @JsonKey(ignore: true) @@ -94,7 +128,7 @@ class Message extends Equatable { /// The message type @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final String? type; + final String type; /// The list of attachments, either provided by the user or generated from a /// command or as a result of URL scraping. @@ -158,11 +192,11 @@ class Message extends Equatable { /// Reserved field indicating when the message was created. @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final DateTime? createdAt; + final DateTime createdAt; /// Reserved field indicating when the message was updated last time. @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final DateTime? updatedAt; + final DateTime updatedAt; /// User who sent the message @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) @@ -384,7 +418,12 @@ class Message extends Equatable { @JsonSerializable() class TranslatedMessage extends Message { /// Constructor used for json serialization - TranslatedMessage(this.i18n); + TranslatedMessage(this.i18n) + : super( + createdAt: DateTime.now(), + updatedAt: DateTime.now(), + text: '', + type: ''); /// Create a new instance from a json factory TranslatedMessage.fromJson(Map? json) => diff --git a/packages/stream_chat/lib/src/models/message.g.dart b/packages/stream_chat/lib/src/models/message.g.dart index 72d2ea1f..cac1b1df 100644 --- a/packages/stream_chat/lib/src/models/message.g.dart +++ b/packages/stream_chat/lib/src/models/message.g.dart @@ -9,8 +9,8 @@ part of 'message.dart'; Message _$MessageFromJson(Map json) { return Message( id: json['id'] as String?, - text: json['text'] as String?, - type: json['type'] as String?, + text: json['text'] as String, + type: json['type'] as String, attachments: (json['attachments'] as List?) ?.map((e) => Attachment.fromJson(Map.from(e as Map))) .toList(), @@ -52,12 +52,8 @@ Message _$MessageFromJson(Map json) { .toList(), showInChannel: json['show_in_channel'] as bool?, command: json['command'] as String?, - createdAt: json['created_at'] == null - ? null - : DateTime.parse(json['created_at'] as String), - updatedAt: json['updated_at'] == null - ? null - : DateTime.parse(json['updated_at'] as String), + createdAt: DateTime.parse(json['created_at'] as String), + updatedAt: DateTime.parse(json['updated_at'] as String), user: json['user'] == null ? null : User.fromJson((json['user'] as Map?)?.map( diff --git a/packages/stream_chat/lib/src/models/own_user.dart b/packages/stream_chat/lib/src/models/own_user.dart index 041c4e95..9ebc633b 100644 --- a/packages/stream_chat/lib/src/models/own_user.dart +++ b/packages/stream_chat/lib/src/models/own_user.dart @@ -12,19 +12,19 @@ part 'own_user.g.dart'; class OwnUser extends User { /// Constructor used for json serialization OwnUser({ - this.devices, - this.mutes, - this.totalUnreadCount, + this.devices = const [], + this.mutes = const [], + this.totalUnreadCount = 0, this.unreadChannels, - this.channelMutes, - String? id, - String? role, - DateTime? createdAt, - DateTime? updatedAt, + this.channelMutes = const [], + required String id, + required String role, + required DateTime createdAt, + required DateTime updatedAt, DateTime? lastActive, - bool? online, - Map? extraData, - bool? banned, + bool online = false, + Map extraData = const {}, + bool banned = false, }) : super( id: id, role: role, @@ -36,25 +36,45 @@ class OwnUser extends User { banned: banned, ); + /// Create a temporary/throwaway user with an ID + OwnUser.temp({ + required String id, + this.devices = const [], + this.mutes = const [], + this.totalUnreadCount = 0, + this.unreadChannels, + this.channelMutes = const [], + DateTime? lastActive, + bool online = false, + Map extraData = const {}, + bool banned = false, + }) : super.temp( + id: id, + lastActive: lastActive, + online: online, + extraData: extraData, + banned: banned, + ); + /// Create a new instance from a json factory OwnUser.fromJson(Map? json) => _$OwnUserFromJson( Serialization.moveToExtraDataFromRoot(json, topLevelFields)!); /// List of user devices @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final List? devices; + final List devices; /// List of users muted by the user @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final List? mutes; + final List mutes; /// List of users muted by the user @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final List? channelMutes; + final List channelMutes; /// Total unread messages by the user @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final int? totalUnreadCount; + final int totalUnreadCount; /// Total unread channels by the user @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) diff --git a/packages/stream_chat/lib/src/models/own_user.g.dart b/packages/stream_chat/lib/src/models/own_user.g.dart index ce265308..5cc0bd53 100644 --- a/packages/stream_chat/lib/src/models/own_user.g.dart +++ b/packages/stream_chat/lib/src/models/own_user.g.dart @@ -7,34 +7,29 @@ part of 'own_user.dart'; // ************************************************************************** OwnUser _$OwnUserFromJson(Map json) { + print(json); return OwnUser( - devices: (json['devices'] as List?) - ?.map((e) => Device.fromJson(Map.from(e as Map))) + devices: (json['devices'] as List) + .map((e) => Device.fromJson(Map.from(e as Map))) .toList(), - mutes: (json['mutes'] as List?) - ?.map((e) => Mute.fromJson(Map.from(e as Map))) + mutes: (json['mutes'] as List) + .map((e) => Mute.fromJson(Map.from(e as Map))) .toList(), - totalUnreadCount: json['total_unread_count'] as int?, + totalUnreadCount: json['total_unread_count'] as int, unreadChannels: json['unread_channels'] as int?, - channelMutes: (json['channel_mutes'] as List?) - ?.map((e) => Mute.fromJson(Map.from(e as Map))) + channelMutes: (json['channel_mutes'] as List) + .map((e) => Mute.fromJson(Map.from(e as Map))) .toList(), - id: json['id'] as String?, - role: json['role'] as String?, - createdAt: json['created_at'] == null - ? null - : DateTime.parse(json['created_at'] as String), - updatedAt: json['updated_at'] == null - ? null - : DateTime.parse(json['updated_at'] as String), + id: json['id'] as String, + role: json['role'] as String, + createdAt: DateTime.parse(json['created_at'] as String), + updatedAt: DateTime.parse(json['updated_at'] as String), lastActive: json['last_active'] == null ? null : DateTime.parse(json['last_active'] as String), - online: json['online'] as bool?, - extraData: (json['extra_data'] as Map?)?.map( - (k, e) => MapEntry(k as String, e), - ), - banned: json['banned'] as bool?, + online: json['online'] as bool, + extraData: Map.from(json['extra_data'] as Map), + banned: json['banned'] as bool, ); } @@ -55,7 +50,7 @@ Map _$OwnUserToJson(OwnUser instance) { writeNotNull('last_active', readonly(instance.lastActive)); writeNotNull('online', readonly(instance.online)); writeNotNull('banned', readonly(instance.banned)); - writeNotNull('extra_data', instance.extraData); + val['extra_data'] = instance.extraData; writeNotNull('devices', readonly(instance.devices)); writeNotNull('mutes', readonly(instance.mutes)); writeNotNull('channel_mutes', readonly(instance.channelMutes)); diff --git a/packages/stream_chat/lib/src/models/reaction.dart b/packages/stream_chat/lib/src/models/reaction.dart index 9f7b5851..cea2eaef 100644 --- a/packages/stream_chat/lib/src/models/reaction.dart +++ b/packages/stream_chat/lib/src/models/reaction.dart @@ -10,13 +10,13 @@ class Reaction { /// Constructor used for json serialization Reaction({ this.messageId, - this.createdAt, - this.type, - this.user, + required this.createdAt, + required this.type, + required this.user, String? userId, - this.score, + required this.score, this.extraData, - }) : userId = userId ?? user?.id; + }) : userId = userId ?? user.id; /// Create a new instance from a json factory Reaction.fromJson(Map? json) => _$ReactionFromJson( @@ -26,18 +26,18 @@ class Reaction { final String? messageId; /// The type of the reaction - final String? type; + final String type; /// The date of the reaction @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final DateTime? createdAt; + final DateTime createdAt; /// The user that sent the reaction @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final User? user; + final User user; /// The score of the reaction (ie. number of reactions sent) - final int? score; + final int score; /// The userId that sent the reaction @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) diff --git a/packages/stream_chat/lib/src/models/reaction.g.dart b/packages/stream_chat/lib/src/models/reaction.g.dart index 644c643a..2f1d1eb8 100644 --- a/packages/stream_chat/lib/src/models/reaction.g.dart +++ b/packages/stream_chat/lib/src/models/reaction.g.dart @@ -9,17 +9,13 @@ part of 'reaction.dart'; Reaction _$ReactionFromJson(Map json) { return Reaction( messageId: json['message_id'] as String?, - createdAt: json['created_at'] == null - ? null - : DateTime.parse(json['created_at'] as String), - type: json['type'] as String?, - user: json['user'] == null - ? null - : User.fromJson((json['user'] as Map?)?.map( - (k, e) => MapEntry(k as String, e), - )), + createdAt: DateTime.parse(json['created_at'] as String), + type: json['type'] as String, + user: User.fromJson((json['user'] as Map?)?.map( + (k, e) => MapEntry(k as String, e), + )), userId: json['user_id'] as String?, - score: json['score'] as int?, + score: json['score'] as int, extraData: (json['extra_data'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ), diff --git a/packages/stream_chat/lib/src/models/read.dart b/packages/stream_chat/lib/src/models/read.dart index 87b3dc89..3fccc20b 100644 --- a/packages/stream_chat/lib/src/models/read.dart +++ b/packages/stream_chat/lib/src/models/read.dart @@ -8,22 +8,22 @@ part 'read.g.dart'; class Read { /// Constructor used for json serialization Read({ - this.lastRead, - this.user, - this.unreadMessages, + required this.lastRead, + required this.user, + required this.unreadMessages, }); /// Create a new instance from a json factory Read.fromJson(Map json) => _$ReadFromJson(json); /// Date of the read event - final DateTime? lastRead; + final DateTime lastRead; /// User who sent the event - final User? user; + final User user; /// Number of unread messages - final int? unreadMessages; + final int unreadMessages; /// Serialize to json Map toJson() => _$ReadToJson(this); diff --git a/packages/stream_chat/lib/src/models/read.g.dart b/packages/stream_chat/lib/src/models/read.g.dart index 83c822e5..7b2a6f48 100644 --- a/packages/stream_chat/lib/src/models/read.g.dart +++ b/packages/stream_chat/lib/src/models/read.g.dart @@ -8,20 +8,16 @@ part of 'read.dart'; Read _$ReadFromJson(Map json) { return Read( - lastRead: json['last_read'] == null - ? null - : DateTime.parse(json['last_read'] as String), - user: json['user'] == null - ? null - : User.fromJson((json['user'] as Map?)?.map( - (k, e) => MapEntry(k as String, e), - )), - unreadMessages: json['unread_messages'] as int?, + lastRead: DateTime.parse(json['last_read'] as String), + user: User.fromJson((json['user'] as Map?)?.map( + (k, e) => MapEntry(k as String, e), + )), + unreadMessages: json['unread_messages'] as int, ); } Map _$ReadToJson(Read instance) => { - 'last_read': instance.lastRead?.toIso8601String(), - 'user': instance.user?.toJson(), + 'last_read': instance.lastRead.toIso8601String(), + 'user': instance.user.toJson(), 'unread_messages': instance.unreadMessages, }; diff --git a/packages/stream_chat/lib/src/models/user.dart b/packages/stream_chat/lib/src/models/user.dart index 97411a3e..1488696a 100644 --- a/packages/stream_chat/lib/src/models/user.dart +++ b/packages/stream_chat/lib/src/models/user.dart @@ -8,17 +8,29 @@ part 'user.g.dart'; class User { /// Constructor used for json serialization User({ - this.id, - this.role, - this.createdAt, - this.updatedAt, + required this.id, + required this.role, + required this.createdAt, + required this.updatedAt, this.lastActive, - this.online, - this.extraData, - this.banned, - this.teams, + this.online = false, + this.extraData = const {}, + this.banned = false, + this.teams = const [], }); + /// Use constructor for a temporary/throwaway user with an ID + User.temp({ + required this.id, + this.role = '', + this.lastActive, + this.online = false, + this.extraData = const {}, + this.banned = false, + this.teams = const [], + }) : createdAt = DateTime.now(), + updatedAt = DateTime.now(); + /// Create a new instance from a json factory User.fromJson(Map? json) => _$UserFromJson( Serialization.moveToExtraDataFromRoot(json, topLevelFields)!); @@ -26,14 +38,14 @@ class User { /// Use this named constructor to create a new user instance User.init( this.id, { - this.online, - this.extraData, - }) : createdAt = null, - updatedAt = null, - lastActive = null, - banned = null, - teams = null, - role = null; + this.online = false, + this.extraData = const {}, + required this.createdAt, + required this.updatedAt, + this.teams = const [], + required this.role, + }) : lastActive = null, + banned = false; /// Known top level fields. /// Useful for [Serialization] methods. @@ -49,23 +61,23 @@ class User { ]; /// User id - final String? id; + final String id; /// User role @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final String? role; + final String role; /// User role @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final List? teams; + final List teams; /// Date of user creation @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final DateTime? createdAt; + final DateTime createdAt; /// Date of last user update @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final DateTime? updatedAt; + final DateTime updatedAt; /// Date of last user connection @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) @@ -73,23 +85,23 @@ class User { /// True if user is online @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final bool? online; + final bool online; /// True if user is banned from the chat @JsonKey(includeIfNull: false, toJson: Serialization.readOnly) - final bool? banned; + final bool banned; /// Map of custom user extraData @JsonKey(includeIfNull: false) - final Map? extraData; + final Map extraData; @override int get hashCode => id.hashCode; /// Shortcut for user name String? get name => - (extraData?.containsKey('name') == true && extraData!['name'] != '') - ? extraData!['name'] + (extraData.containsKey('name') == true && extraData['name'] != '') + ? extraData['name'] : id; @override diff --git a/packages/stream_chat/lib/src/models/user.g.dart b/packages/stream_chat/lib/src/models/user.g.dart index 06989395..f1e4088f 100644 --- a/packages/stream_chat/lib/src/models/user.g.dart +++ b/packages/stream_chat/lib/src/models/user.g.dart @@ -8,23 +8,17 @@ part of 'user.dart'; User _$UserFromJson(Map json) { return User( - id: json['id'] as String?, - role: json['role'] as String?, - createdAt: json['created_at'] == null - ? null - : DateTime.parse(json['created_at'] as String), - updatedAt: json['updated_at'] == null - ? null - : DateTime.parse(json['updated_at'] as String), + id: json['id'] as String, + role: json['role'] as String, + createdAt: DateTime.parse(json['created_at'] as String), + updatedAt: DateTime.parse(json['updated_at'] as String), lastActive: json['last_active'] == null ? null : DateTime.parse(json['last_active'] as String), - online: json['online'] as bool?, - extraData: (json['extra_data'] as Map?)?.map( - (k, e) => MapEntry(k as String, e), - ), - banned: json['banned'] as bool?, - teams: (json['teams'] as List?)?.map((e) => e as String).toList(), + online: json['online'] as bool, + extraData: Map.from(json['extra_data'] as Map), + banned: json['banned'] as bool, + teams: (json['teams'] as List).map((e) => e as String).toList(), ); } @@ -46,6 +40,6 @@ Map _$UserToJson(User instance) { writeNotNull('last_active', readonly(instance.lastActive)); writeNotNull('online', readonly(instance.online)); writeNotNull('banned', readonly(instance.banned)); - writeNotNull('extra_data', instance.extraData); + val['extra_data'] = instance.extraData; return val; } diff --git a/packages/stream_chat/test/src/api/channel_test.dart b/packages/stream_chat/test/src/api/channel_test.dart index 94990a7b..5d7c61f0 100644 --- a/packages/stream_chat/test/src/api/channel_test.dart +++ b/packages/stream_chat/test/src/api/channel_test.dart @@ -35,7 +35,7 @@ void main() { tokenProvider: (_) async => '', ); final channelClient = client.channel('messaging', id: 'testid'); - final message = Message(text: 'hey', id: 'test'); + final message = Message.temp(text: 'hey', id: 'test'); when( () => mockDio.post( @@ -168,7 +168,7 @@ void main() { requestOptions: FakeRequestOptions(), )); - await channelClient.sendAction(Message(id: 'messageid'), data); + await channelClient.sendAction(Message.temp(id: 'messageid', text: ''), data); verify(() => mockDio.post('/messages/messageid/action', data: { 'id': 'testid', @@ -334,7 +334,7 @@ void main() { final channelClient = client.channel('messaging', id: 'testid'); - final message = Message(text: 'Hello'); + final message = Message.temp(text: 'Hello'); expect( () => channelClient.pinMessage(message, 'InvalidType'), @@ -354,7 +354,7 @@ void main() { tokenProvider: (_) async => '', ); final channelClient = client.channel('messaging', id: 'testid'); - final message = Message(text: 'Hello', id: 'test'); + final message = Message.temp(text: 'Hello', id: 'test'); when( () => mockDio.post( @@ -388,7 +388,7 @@ void main() { tokenProvider: (_) async => '', ); final channelClient = client.channel('messaging', id: 'testid'); - final message = Message(text: 'Hello', id: 'test'); + final message = Message.temp(text: 'Hello', id: 'test'); when( () => mockDio.post( @@ -566,7 +566,7 @@ void main() { tokenProvider: (_) async => '', ); - client.state?.user = OwnUser(id: 'test-id'); + client.state?.user = OwnUser.temp(id: 'test-id'); final channelClient = client.channel('messaging', id: 'testid'); const reactionType = 'test'; @@ -590,8 +590,9 @@ void main() { ); await channelClient.sendReaction( - Message( + Message.temp( id: 'messageid', + text: '', reactionCounts: const {}, reactionScores: const {}, latestReactions: const [], @@ -621,7 +622,7 @@ void main() { tokenProvider: (_) async => '', ); - client.state?.user = OwnUser(id: 'test-id'); + client.state?.user = OwnUser.temp(id: 'test-id'); final channelClient = client.channel('messaging', id: 'testid'); @@ -636,14 +637,22 @@ void main() { ); await channelClient.deleteReaction( - Message( + Message.temp( id: 'messageid', + text: '', reactionCounts: const {}, reactionScores: const {}, latestReactions: const [], ownReactions: const [], ), - Reaction(type: 'test'), + Reaction( + type: 'test', + createdAt: DateTime.now(), + score: 0, + user: User.temp( + id: client.state?.user?.id ?? '', + ), + ), ); verify(() => @@ -699,7 +708,7 @@ void main() { ); final channelClient = client.channel('messaging', id: 'testid'); final members = ['vishal']; - final message = Message(text: 'test'); + final message = Message.temp(text: 'test'); when( () => mockDio.post( @@ -733,7 +742,7 @@ void main() { tokenProvider: (_) async => '', ); final channelClient = client.channel('messaging', id: 'testid'); - final message = Message(text: 'test'); + final message = Message.temp(text: 'test'); when( () => mockDio.post( @@ -2081,7 +2090,7 @@ void main() { tokenProvider: (_) async => '', ); final channelClient = client.channel('messaging', id: 'testid'); - final message = Message(text: 'test'); + final message = Message.temp(text: 'test'); when( () => mockDio.post( @@ -2180,7 +2189,7 @@ void main() { tokenProvider: (_) async => '', ); final channelClient = client.channel('messaging', id: 'testid'); - final message = Message(text: 'test'); + final message = Message.temp(text: 'test'); when( () => mockDio.post( @@ -2215,7 +2224,7 @@ void main() { ); final channelClient = client.channel('messaging', id: 'testid'); final members = ['vishal']; - final message = Message(text: 'test'); + final message = Message.temp(text: 'test'); when( () => mockDio.post( @@ -2249,7 +2258,7 @@ void main() { ); final channelClient = client.channel('messaging', id: 'testid'); final members = ['vishal']; - final message = Message(text: 'test'); + final message = Message.temp(text: 'test'); when( () => mockDio.post( diff --git a/packages/stream_chat/test/src/api/websocket_test.dart b/packages/stream_chat/test/src/api/websocket_test.dart index 0f3bd5d6..f6616beb 100644 --- a/packages/stream_chat/test/src/api/websocket_test.dart +++ b/packages/stream_chat/test/src/api/websocket_test.dart @@ -38,7 +38,7 @@ void main() { final ConnectWebSocket connectFunc = MockFunctions().connectFunc; final ws = WebSocket( baseUrl: 'baseurl', - user: User(id: 'testid'), + user: User.temp(id: 'testid'), logger: Logger('ws'), connectParams: {'test': 'true'}, connectPayload: {'payload': 'test'}, @@ -76,7 +76,7 @@ void main() { final ConnectWebSocket connectFunc = MockFunctions().connectFunc; final ws = WebSocket( baseUrl: 'baseurl', - user: User(id: 'testid'), + user: User.temp(id: 'testid'), logger: Logger('ws'), connectParams: {'test': 'true'}, connectPayload: {'payload': 'test'}, @@ -112,7 +112,7 @@ void main() { final ConnectWebSocket connectFunc = MockFunctions().connectFunc; final ws = WebSocket( baseUrl: 'baseurl', - user: User(id: 'testid'), + user: User.temp(id: 'testid'), logger: Logger('ws'), connectParams: {'test': 'true'}, connectPayload: {'payload': 'test'}, @@ -150,7 +150,7 @@ void main() { final ws = WebSocket( baseUrl: 'baseurl', - user: User(id: 'testid'), + user: User.temp(id: 'testid'), logger: Logger('ws'), connectParams: {'test': 'true'}, connectPayload: {'payload': 'test'}, @@ -184,7 +184,7 @@ void main() { final ConnectWebSocket connectFunc = MockFunctions().connectFunc; final ws = WebSocket( baseUrl: 'baseurl', - user: User(id: 'testid'), + user: User.temp(id: 'testid'), logger: Logger('ws'), connectParams: {'test': 'true'}, connectPayload: {'payload': 'test'}, @@ -229,7 +229,7 @@ void main() { Logger.root.level = Level.ALL; final ws = WebSocket( baseUrl: 'baseurl', - user: User(id: 'testid'), + user: User.temp(id: 'testid'), logger: Logger('ws'), connectParams: {'test': 'true'}, connectPayload: {'payload': 'test'}, @@ -273,7 +273,7 @@ void main() { final ConnectWebSocket connectFunc = MockFunctions().connectFunc; final ws = WebSocket( baseUrl: 'baseurl', - user: User(id: 'testid'), + user: User.temp(id: 'testid'), logger: Logger('ws'), connectParams: {'test': 'true'}, connectPayload: {'payload': 'test'}, @@ -310,7 +310,7 @@ void main() { final ConnectWebSocket connectFunc = MockFunctions().connectFunc; final ws = WebSocket( baseUrl: 'baseurl', - user: User(id: 'testid'), + user: User.temp(id: 'testid'), logger: Logger('ws'), connectParams: {'test': 'true'}, connectPayload: {'payload': 'test'}, diff --git a/packages/stream_chat/test/src/client_test.dart b/packages/stream_chat/test/src/client_test.dart index 3c0a325c..775d68b0 100644 --- a/packages/stream_chat/test/src/client_test.dart +++ b/packages/stream_chat/test/src/client_test.dart @@ -479,7 +479,7 @@ void main() { final client = StreamChatClient('api-key', httpClient: mockDio); - expect(() => client.connectUserWithProvider(User(id: 'test-id')), + expect(() => client.connectUserWithProvider(User.temp(id: 'test-id')), throwsA(isA())); }); @@ -517,7 +517,7 @@ void main() { when(() => mockDio.interceptors).thenReturn(Interceptors()); final client = StreamChatClient('api-key', httpClient: mockDio); - final user = User(id: 'test-id'); + final user = User.temp(id: 'test-id'); final data = { 'users': {user.id: user.toJson()}, }; @@ -542,8 +542,8 @@ void main() { when(() => mockDio.interceptors).thenReturn(Interceptors()); final client = StreamChatClient('api-key', httpClient: mockDio); - final user = User(id: 'test-id'); - final user2 = User(id: 'test-id2'); + final user = User.temp(id: 'test-id'); + final user2 = User.temp(id: 'test-id2'); final data = { 'users': { @@ -737,7 +737,13 @@ void main() { when(() => mockDio.interceptors).thenReturn(Interceptors()); final client = StreamChatClient('api-key', httpClient: mockDio); - final message = Message(id: 'test', updatedAt: DateTime.now()); + final message = Message( + id: 'test', + updatedAt: DateTime.now(), + createdAt: DateTime.now(), + text: '', + type: '', + ); when( () => mockDio.post( @@ -775,7 +781,7 @@ void main() { ), ); - await client.deleteMessage(Message(id: messageId)); + await client.deleteMessage(Message.temp(id: messageId, text: '')); verify(() => mockDio.delete('/messages/$messageId')).called(1); }); @@ -1095,7 +1101,7 @@ void main() { ); test('should throw argument error', () { - final message = Message(text: 'Hello'); + final message = Message.temp(text: 'Hello'); expect( () => client.pinMessage(message, 'InvalidType'), throwsArgumentError, @@ -1104,7 +1110,7 @@ void main() { test('should complete successfully', () async { const timeout = 30; - final message = Message(text: 'Hello'); + final message = Message.temp(text: 'Hello'); when( () => mockDio.post( @@ -1126,7 +1132,7 @@ void main() { }); test('should unpin message successfully', () async { - final message = Message(text: 'Hello'); + final message = Message.temp(text: 'Hello'); when( () => mockDio.post( diff --git a/packages/stream_chat/test/src/models/channel_state_test.dart b/packages/stream_chat/test/src/models/channel_state_test.dart index 9aa2b2d6..79b8b0fa 100644 --- a/packages/stream_chat/test/src/models/channel_state_test.dart +++ b/packages/stream_chat/test/src/models/channel_state_test.dart @@ -1330,10 +1330,10 @@ void main() { members: [], messages: (j['messages'] as List).map((m) => Message.fromJson(m)).toList(), - read: null, + read: [], watcherCount: 5, pinnedMessages: [], - watchers: null, + watchers: [], ); expect( diff --git a/packages/stream_chat/test/src/models/channel_test.dart b/packages/stream_chat/test/src/models/channel_test.dart index 4a221a8a..6d0475e0 100644 --- a/packages/stream_chat/test/src/models/channel_test.dart +++ b/packages/stream_chat/test/src/models/channel_test.dart @@ -25,7 +25,7 @@ void main() { }); test('should serialize to json correctly', () { - final channel = ChannelModel( + final channel = ChannelModel.temp( type: 'type', id: 'id', cid: 'a:a', @@ -39,7 +39,7 @@ void main() { }); test('should serialize to json correctly when frozen is provided', () { - final channel = ChannelModel( + final channel = ChannelModel.temp( type: 'type', id: 'id', cid: 'a:a', diff --git a/packages/stream_chat/test/src/models/event_test.dart b/packages/stream_chat/test/src/models/event_test.dart index a7c669df..4e657bdb 100644 --- a/packages/stream_chat/test/src/models/event_test.dart +++ b/packages/stream_chat/test/src/models/event_test.dart @@ -51,12 +51,12 @@ void main() { test('should serialize to json correctly', () { final event = Event( - user: User(id: 'id'), + user: User.temp(id: 'id'), type: 'type', cid: 'cid', connectionId: 'connectionId', createdAt: DateTime.parse('2020-01-29T03:22:47.63613Z'), - me: OwnUser(id: 'id2'), + me: OwnUser.temp(id: 'id2'), totalUnreadCount: 1, unreadChannels: 1, online: true, diff --git a/packages/stream_chat/test/src/models/message_test.dart b/packages/stream_chat/test/src/models/message_test.dart index 0898e902..72b9ba09 100644 --- a/packages/stream_chat/test/src/models/message_test.dart +++ b/packages/stream_chat/test/src/models/message_test.dart @@ -97,7 +97,7 @@ void main() { }); test('should serialize to json correctly', () { - final message = Message( + final message = Message.temp( id: '4637f7e4-a06b-42db-ba5a-8d8270dd926f', text: 'https://giphy.com/gifs/the-lion-king-live-action-5zvN79uTGfLMOVfQaA', diff --git a/packages/stream_chat/test/src/models/reaction_test.dart b/packages/stream_chat/test/src/models/reaction_test.dart index 80d2964b..e82dcc79 100644 --- a/packages/stream_chat/test/src/models/reaction_test.dart +++ b/packages/stream_chat/test/src/models/reaction_test.dart @@ -33,8 +33,8 @@ void main() { expect(reaction.createdAt, DateTime.parse('2020-01-28T22:17:31.108742Z')); expect(reaction.type, 'wow'); expect( - reaction.user?.toJson(), - User.init('2de0297c-f3f2-489d-b930-ef77342edccf', extraData: { + reaction.user.toJson(), + User.temp(id:'2de0297c-f3f2-489d-b930-ef77342edccf', extraData: { 'image': 'https://randomuser.me/api/portraits/women/45.jpg', 'name': 'Daisy Morgan' }).toJson(), @@ -49,7 +49,7 @@ void main() { messageId: '76cd8c82-b557-4e48-9d12-87995d3a0e04', createdAt: DateTime.parse('2020-01-28T22:17:31.108742Z'), type: 'wow', - user: User.init('2de0297c-f3f2-489d-b930-ef77342edccf', extraData: { + user: User.temp(id:'2de0297c-f3f2-489d-b930-ef77342edccf', extraData: { 'image': 'https://randomuser.me/api/portraits/women/45.jpg', 'name': 'Daisy Morgan' }), diff --git a/packages/stream_chat/test/src/models/read_test.dart b/packages/stream_chat/test/src/models/read_test.dart index 7575d35f..24b56cd8 100644 --- a/packages/stream_chat/test/src/models/read_test.dart +++ b/packages/stream_chat/test/src/models/read_test.dart @@ -26,7 +26,7 @@ void main() { test('should serialize to json correctly', () { final read = Read( lastRead: DateTime.parse('2020-01-28T22:17:30.966485504Z'), - user: User.init('bbb19d9a-ee50-45bc-84e5-0584e79d0c9e'), + user: User.temp(id: 'bbb19d9a-ee50-45bc-84e5-0584e79d0c9e'), unreadMessages: 10, ); diff --git a/packages/stream_chat/test/src/models/user_test.dart b/packages/stream_chat/test/src/models/user_test.dart index 0a307126..8a30ad4d 100644 --- a/packages/stream_chat/test/src/models/user_test.dart +++ b/packages/stream_chat/test/src/models/user_test.dart @@ -17,7 +17,7 @@ void main() { }); test('should serialize to json correctly', () { - final user = User( + final user = User.temp( id: 'bbb19d9a-ee50-45bc-84e5-0584e79d0c9e', role: 'abc', );