feat: Converted to ios models

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