move on with the migration

This commit is contained in:
Salvatore Giordano
2021-04-19 12:40:00 +02:00
parent 8a92392914
commit af135ecb9c
37 changed files with 653 additions and 535 deletions
+146 -89
View File
@@ -59,13 +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
bool get isGroup => memberCount != 2; bool get isGroup => memberCount != 2;
@@ -74,85 +73,130 @@ class Channel {
bool get isDistinct => id?.startsWith('!members') == true; bool get isDistinct => id?.startsWith('!members') == true;
/// Channel configuration /// Channel configuration
ChannelConfig? get config => state?._channelState?.channel?.config; ChannelConfig? get config {
_checkInitialized();
return state?._channelState?.channel?.config;
}
/// Channel configuration as a stream /// Channel configuration as a stream
Stream<ChannelConfig?>? get configStream => Stream<ChannelConfig?>? get configStream {
state?.channelStateStream.map((cs) => cs!.channel?.config); _checkInitialized();
return state?.channelStateStream.map((cs) => cs!.channel?.config);
}
/// Channel user creator /// Channel user creator
User? get createdBy => state?._channelState?.channel?.createdBy; User? get createdBy {
_checkInitialized();
return state?._channelState?.channel?.createdBy;
}
/// Channel user creator as a stream /// Channel user creator as a stream
Stream<User?>? get createdByStream => Stream<User?>? get createdByStream {
state?.channelStateStream.map((cs) => cs!.channel?.createdBy); _checkInitialized();
return state?.channelStateStream.map((cs) => cs!.channel?.createdBy);
}
/// Channel frozen status /// Channel frozen status
bool? get frozen => state?._channelState?.channel?.frozen; bool? get frozen {
_checkInitialized();
return state?._channelState?.channel?.frozen;
}
/// Channel frozen status as a stream /// Channel frozen status as a stream
Stream<bool?>? get frozenStream => Stream<bool?>? get frozenStream {
state?.channelStateStream.map((cs) => cs!.channel?.frozen); _checkInitialized();
return state?.channelStateStream.map((cs) => cs!.channel?.frozen);
}
/// Channel creation date /// Channel creation date
DateTime? get createdAt => state?._channelState?.channel?.createdAt; DateTime? get createdAt {
_checkInitialized();
return state?._channelState?.channel?.createdAt;
}
/// Channel creation date as a stream /// Channel creation date as a stream
Stream<DateTime?>? get createdAtStream => Stream<DateTime?>? get createdAtStream {
state?.channelStateStream.map((cs) => cs!.channel?.createdAt); _checkInitialized();
return state?.channelStateStream.map((cs) => cs!.channel?.createdAt);
}
/// Channel last message date /// Channel last message date
DateTime? get lastMessageAt => state?._channelState?.channel?.lastMessageAt; DateTime? get lastMessageAt {
_checkInitialized();
return state?._channelState?.channel?.lastMessageAt;
}
/// Channel last message date as a stream /// Channel last message date as a stream
Stream<DateTime?>? get lastMessageAtStream => Stream<DateTime?>? get lastMessageAtStream {
state?.channelStateStream.map((cs) => cs!.channel?.lastMessageAt); _checkInitialized();
return state?.channelStateStream.map((cs) => cs!.channel?.lastMessageAt);
}
/// Channel updated date /// Channel updated date
DateTime? get updatedAt => state?._channelState?.channel?.updatedAt; DateTime? get updatedAt {
_checkInitialized();
return state?._channelState?.channel?.updatedAt;
}
/// Channel updated date as a stream /// Channel updated date as a stream
Stream<DateTime?>? get updatedAtStream => Stream<DateTime?>? get updatedAtStream {
state?.channelStateStream.map((cs) => cs!.channel?.updatedAt); _checkInitialized();
return state?.channelStateStream.map((cs) => cs!.channel?.updatedAt);
}
/// Channel deletion date /// Channel deletion date
DateTime? get deletedAt => state?._channelState?.channel?.deletedAt; DateTime? get deletedAt {
_checkInitialized();
return state?._channelState?.channel?.deletedAt;
}
/// Channel deletion date as a stream /// Channel deletion date as a stream
Stream<DateTime?>? get deletedAtStream => Stream<DateTime?>? get deletedAtStream {
state?.channelStateStream.map((cs) => cs!.channel?.deletedAt); _checkInitialized();
return state?.channelStateStream.map((cs) => cs!.channel?.deletedAt);
}
/// Channel member count /// Channel member count
int? get memberCount => state?._channelState?.channel?.memberCount; int? get memberCount {
_checkInitialized();
return state?._channelState?.channel?.memberCount;
}
/// Channel member count as a stream /// Channel member count as a stream
Stream<int?>? get memberCountStream => Stream<int?>? get memberCountStream {
state?.channelStateStream.map((cs) => cs!.channel?.memberCount); _checkInitialized();
return state?.channelStateStream.map((cs) => cs!.channel?.memberCount);
}
/// Channel id /// Channel id
String? get id => state?._channelState?.channel?.id ?? _id; String? get id => state?._channelState?.channel?.id ?? _id;
/// Channel id as a stream
Stream<String?>? get idStream =>
state?.channelStateStream.map((cs) => cs!.channel?.id ?? _id);
/// Channel cid /// Channel cid
String? get cid => state?._channelState?.channel?.cid ?? _cid; String? get cid => state?._channelState?.channel?.cid ?? _cid;
/// Channel team /// Channel team
String? get team => state?._channelState?.channel?.team; String? get team {
_checkInitialized();
/// Channel cid as a stream return state?._channelState?.channel?.team;
Stream<String?>? get cidStream => }
state?.channelStateStream.map((cs) => cs!.channel?.cid ?? _cid);
/// Channel extra data /// Channel extra data
Map<String, dynamic>? get extraData => Map<String, dynamic>? get extraData =>
state?._channelState?.channel?.extraData ?? _extraData; state?._channelState?.channel?.extraData ?? _extraData;
/// Channel extra data as a stream /// Channel extra data as a stream
Stream<Map<String, dynamic>?>? get extraDataStream => Stream<Map<String, dynamic>?>? get extraDataStream {
state?.channelStateStream.map((cs) => cs!.channel?.extraData); _checkInitialized();
return state?.channelStateStream.map((cs) => cs!.channel?.extraData);
}
/// The main Stream chat client /// The main Stream chat client
StreamChatClient get client => _client; StreamChatClient get client => _client;
@@ -205,14 +249,14 @@ class Channel {
throw Exception('Error, Message not found'); throw Exception('Error, Message not found');
} }
final attachments = message.attachments!.where((it) { final attachments = message.attachments.where((it) {
if (it.uploadState.isSuccess) return false; if (it.uploadState.isSuccess) return false;
return attachmentIds.contains(it.id); return attachmentIds.contains(it.id);
}); });
if (attachments.isEmpty) { if (attachments.isEmpty) {
client.logger.info('No attachments available to upload'); client.logger.info('No attachments available to upload');
if (message.attachments!.every((it) => it.uploadState.isSuccess)) { if (message.attachments.every((it) => it.uploadState.isSuccess)) {
_messageAttachmentsUploadCompleter.remove(messageId)?.complete(message); _messageAttachmentsUploadCompleter.remove(messageId)?.complete(message);
} }
return Future.value(); return Future.value();
@@ -222,9 +266,9 @@ class Channel {
void updateAttachment(Attachment attachment) { void updateAttachment(Attachment attachment) {
final index = final index =
message.attachments!.indexWhere((it) => it.id == attachment.id); message.attachments.indexWhere((it) => it.id == attachment.id);
if (index != -1) { if (index != -1) {
message.attachments![index] = attachment; message.attachments[index] = attachment;
state?.addMessage(message); state?.addMessage(message);
} }
} }
@@ -252,13 +296,13 @@ class Channel {
it.file!, it.file!,
onSendProgress: onSendProgress, onSendProgress: onSendProgress,
cancelToken: cancelToken, cancelToken: cancelToken,
).then((it) => it!.file!); ).then((it) => it!.file);
} else { } else {
future = sendFile( future = sendFile(
it.file!, it.file!,
onSendProgress: onSendProgress, onSendProgress: onSendProgress,
cancelToken: cancelToken, cancelToken: cancelToken,
).then((it) => it!.file!); ).then((it) => it!.file);
} }
_cancelableAttachmentUploadRequest[it.id] = cancelToken; _cancelableAttachmentUploadRequest[it.id] = cancelToken;
return future.then((url) { return future.then((url) {
@@ -288,7 +332,7 @@ class Channel {
_cancelableAttachmentUploadRequest.remove(it.id); _cancelableAttachmentUploadRequest.remove(it.id);
}); });
})).whenComplete(() { })).whenComplete(() {
if (message.attachments!.every((it) => it.uploadState.isSuccess)) { if (message.attachments.every((it) => it.uploadState.isSuccess)) {
_messageAttachmentsUploadCompleter.remove(messageId)?.complete(message); _messageAttachmentsUploadCompleter.remove(messageId)?.complete(message);
} }
}); });
@@ -313,7 +357,7 @@ class Channel {
user: _client.state.user, user: _client.state.user,
quotedMessage: quotedMessage, quotedMessage: quotedMessage,
status: MessageSendingStatus.sending, status: MessageSendingStatus.sending,
attachments: message.attachments?.map( attachments: message.attachments.map(
(it) { (it) {
if (it.uploadState.isSuccess) return it; if (it.uploadState.isSuccess) return it;
return it.copyWith(uploadState: const UploadState.preparing()); return it.copyWith(uploadState: const UploadState.preparing());
@@ -324,7 +368,7 @@ class Channel {
state?.addMessage(message); state?.addMessage(message);
try { try {
if (message.attachments?.any((it) => !it.uploadState.isSuccess) == true) { if (message.attachments.any((it) => !it.uploadState.isSuccess) == true) {
final attachmentsUploadCompleter = Completer<Message>(); final attachmentsUploadCompleter = Completer<Message>();
_messageAttachmentsUploadCompleter[message.id] = _messageAttachmentsUploadCompleter[message.id] =
attachmentsUploadCompleter; attachmentsUploadCompleter;
@@ -332,15 +376,15 @@ class Channel {
// ignore: unawaited_futures // ignore: unawaited_futures
_uploadAttachments( _uploadAttachments(
message.id, message.id,
message.attachments!.map((it) => it.id), message.attachments.map((it) => it.id),
); );
// ignore: parameter_assignments // ignore: parameter_assignments
message = await attachmentsUploadCompleter.future; message = await attachmentsUploadCompleter.future;
} }
final response = await _client.sendMessage(message, id, type); final response = await _client.sendMessage(message, id!, type!);
state?.addMessage(response.message!); state?.addMessage(response.message);
return response; return response;
} catch (error) { } catch (error) {
if (error is DioError && error.type != DioErrorType.response) { if (error is DioError && error.type != DioErrorType.response) {
@@ -364,7 +408,7 @@ class Channel {
message = message.copyWith( message = message.copyWith(
status: MessageSendingStatus.updating, status: MessageSendingStatus.updating,
updatedAt: message.updatedAt, 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;
return it.copyWith(uploadState: const UploadState.preparing()); return it.copyWith(uploadState: const UploadState.preparing());
@@ -375,7 +419,7 @@ class Channel {
state?.addMessage(message); state?.addMessage(message);
try { try {
if (message.attachments?.any((it) => !it.uploadState.isSuccess) == true) { if (message.attachments.any((it) => !it.uploadState.isSuccess) == true) {
final attachmentsUploadCompleter = Completer<Message>(); final attachmentsUploadCompleter = Completer<Message>();
_messageAttachmentsUploadCompleter[message.id] = _messageAttachmentsUploadCompleter[message.id] =
attachmentsUploadCompleter; attachmentsUploadCompleter;
@@ -383,7 +427,7 @@ class Channel {
// ignore: unawaited_futures // ignore: unawaited_futures
_uploadAttachments( _uploadAttachments(
message.id, message.id,
message.attachments!.map((it) => it.id), message.attachments.map((it) => it.id),
); );
// ignore: parameter_assignments // ignore: parameter_assignments
@@ -392,13 +436,11 @@ class Channel {
final response = await _client.updateMessage(message); final response = await _client.updateMessage(message);
final m = response.message?.copyWith( final m = response.message.copyWith(
ownReactions: message.ownReactions, ownReactions: message.ownReactions,
); );
if (m != null) { state?.addMessage(m);
state?.addMessage(m);
}
return response; return response;
} catch (error) { } catch (error) {
@@ -489,28 +531,32 @@ class Channel {
AttachmentFile file, { AttachmentFile file, {
ProgressCallback? onSendProgress, ProgressCallback? onSendProgress,
CancelToken? cancelToken, CancelToken? cancelToken,
}) => }) {
_client.sendFile( _checkInitialized();
file, return _client.sendFile(
id, file,
type, id!,
onSendProgress: onSendProgress, type!,
cancelToken: cancelToken, onSendProgress: onSendProgress,
); cancelToken: cancelToken,
);
}
/// Send an image to this channel /// Send an image to this channel
Future<SendImageResponse?> sendImage( Future<SendImageResponse?> sendImage(
AttachmentFile file, { AttachmentFile file, {
ProgressCallback? onSendProgress, ProgressCallback? onSendProgress,
CancelToken? cancelToken, CancelToken? cancelToken,
}) => }) {
_client.sendImage( _checkInitialized();
file, return _client.sendImage(
id, file,
type, id!,
onSendProgress: onSendProgress, type!,
cancelToken: cancelToken, onSendProgress: onSendProgress,
); cancelToken: cancelToken,
);
}
/// A message search. /// A message search.
Future<SearchMessagesResponse?> search({ Future<SearchMessagesResponse?> search({
@@ -535,15 +581,29 @@ class Channel {
Future<EmptyResponse?> deleteFile( Future<EmptyResponse?> deleteFile(
String url, { String url, {
CancelToken? cancelToken, CancelToken? cancelToken,
}) => }) {
_client.deleteFile(url, id, type, cancelToken: cancelToken); _checkInitialized();
return _client.deleteFile(
url,
id!,
type!,
cancelToken: cancelToken,
);
}
/// Delete an image from this channel /// Delete an image from this channel
Future<EmptyResponse?> deleteImage( Future<EmptyResponse?> deleteImage(
String url, { String url, {
CancelToken? cancelToken, CancelToken? cancelToken,
}) => }) {
_client.deleteImage(url, id, type, cancelToken: cancelToken); _checkInitialized();
return _client.deleteImage(
url,
id!,
type!,
cancelToken: cancelToken,
);
}
/// Send an event on this channel /// Send an event on this channel
Future<EmptyResponse> sendEvent(Event event) { Future<EmptyResponse> sendEvent(Event event) {
@@ -916,9 +976,7 @@ class Channel {
final messages = res.messages; final messages = res.messages;
if (messages != null) { state?.updateChannelState(ChannelState(messages: messages));
state?.updateChannelState(ChannelState(messages: messages));
}
return res; return res;
} }
@@ -1198,11 +1256,10 @@ class Channel {
} }
void _checkInitialized() { void _checkInitialized() {
if (!_initializedCompleter.isCompleted) { assert(
throw Exception( !_initializedCompleter.isCompleted,
"Channel $cid hasn't been initialized yet. Make sure to call .watch()" "Channel $cid hasn't been initialized yet. Make sure to call .watch()"
' or to instantiate the client using [Channel.fromState]'); ' or to instantiate the client using [Channel.fromState]');
}
} }
} }
@@ -1285,8 +1342,8 @@ class ChannelClientState {
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) {
final url = e.imageUrl ?? e.assetUrl; final url = e.imageUrl ?? e.assetUrl;
if (url == null || !url.contains('')) { if (url == null || !url.contains('')) {
return false; return false;
@@ -1602,12 +1659,12 @@ 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;
return message.silent != true && return message.silent != true &&
message.shadowed != true && message.shadowed != true &&
message.user!.id != userId && message.user?.id != userId &&
!userIsMuted; !userIsMuted;
} }
+112 -93
View File
@@ -20,186 +20,194 @@ class _BaseResponse {
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class SyncResponse extends _BaseResponse { class SyncResponse extends _BaseResponse {
/// The list of events /// The list of events
List<Event>? events; @JsonKey(defaultValue: [])
late List<Event> events;
/// Create a new instance from a json /// Create a new instance from a json
static SyncResponse fromJson(Map<String, dynamic>? json) => static SyncResponse fromJson(Map<String, dynamic> json) =>
_$SyncResponseFromJson(json!); _$SyncResponseFromJson(json);
} }
/// Model response for [StreamChatClient.queryChannels] api call /// Model response for [StreamChatClient.queryChannels] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class QueryChannelsResponse extends _BaseResponse { class QueryChannelsResponse extends _BaseResponse {
/// List of channels state returned by the query /// List of channels state returned by the query
List<ChannelState>? channels; @JsonKey(defaultValue: [])
late List<ChannelState> channels;
/// Create a new instance from a json /// Create a new instance from a json
static QueryChannelsResponse fromJson(Map<String, dynamic>? json) => static QueryChannelsResponse fromJson(Map<String, dynamic> json) =>
_$QueryChannelsResponseFromJson(json!); _$QueryChannelsResponseFromJson(json);
} }
/// Model response for [StreamChatClient.queryChannels] api call /// Model response for [StreamChatClient.queryChannels] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class TranslateMessageResponse extends _BaseResponse { class TranslateMessageResponse extends _BaseResponse {
/// List of channels state returned by the query /// Translated message
TranslatedMessage? message; late TranslatedMessage message;
/// Create a new instance from a json /// Create a new instance from a json
static TranslateMessageResponse fromJson(Map<String, dynamic>? json) => static TranslateMessageResponse fromJson(Map<String, dynamic> json) =>
_$TranslateMessageResponseFromJson(json!); _$TranslateMessageResponseFromJson(json);
} }
/// Model response for [StreamChatClient.queryChannels] api call /// Model response for [StreamChatClient.queryChannels] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class QueryMembersResponse extends _BaseResponse { class QueryMembersResponse extends _BaseResponse {
/// List of channels state returned by the query /// List of channels state returned by the query
List<Member>? members; @JsonKey(defaultValue: [])
late List<Member> members;
/// Create a new instance from a json /// Create a new instance from a json
static QueryMembersResponse fromJson(Map<String, dynamic>? json) => static QueryMembersResponse fromJson(Map<String, dynamic> json) =>
_$QueryMembersResponseFromJson(json!); _$QueryMembersResponseFromJson(json);
} }
/// Model response for [StreamChatClient.queryUsers] api call /// Model response for [StreamChatClient.queryUsers] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class QueryUsersResponse extends _BaseResponse { class QueryUsersResponse extends _BaseResponse {
/// List of users returned by the query /// List of users returned by the query
List<User>? users; @JsonKey(defaultValue: [])
late List<User> users;
/// Create a new instance from a json /// Create a new instance from a json
static QueryUsersResponse fromJson(Map<String, dynamic>? json) => static QueryUsersResponse fromJson(Map<String, dynamic> json) =>
_$QueryUsersResponseFromJson(json!); _$QueryUsersResponseFromJson(json);
} }
/// Model response for [channel.getReactions] api call /// Model response for [channel.getReactions] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class QueryReactionsResponse extends _BaseResponse { class QueryReactionsResponse extends _BaseResponse {
/// List of reactions returned by the query /// List of reactions returned by the query
List<Reaction>? reactions; @JsonKey(defaultValue: [])
late List<Reaction> reactions;
/// Create a new instance from a json /// Create a new instance from a json
static QueryReactionsResponse fromJson(Map<String, dynamic>? json) => static QueryReactionsResponse fromJson(Map<String, dynamic> json) =>
_$QueryReactionsResponseFromJson(json!); _$QueryReactionsResponseFromJson(json);
} }
/// Model response for [Channel.getReplies] api call /// Model response for [Channel.getReplies] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class QueryRepliesResponse extends _BaseResponse { class QueryRepliesResponse extends _BaseResponse {
/// List of messages returned by the api call /// List of messages returned by the api call
List<Message>? messages; @JsonKey(defaultValue: [])
late List<Message> messages;
/// Create a new instance from a json /// Create a new instance from a json
static QueryRepliesResponse fromJson(Map<String, dynamic>? json) => static QueryRepliesResponse fromJson(Map<String, dynamic> json) =>
_$QueryRepliesResponseFromJson(json!); _$QueryRepliesResponseFromJson(json);
} }
/// Model response for [StreamChatClient.getDevices] api call /// Model response for [StreamChatClient.getDevices] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class ListDevicesResponse extends _BaseResponse { class ListDevicesResponse extends _BaseResponse {
/// List of user devices /// List of user devices
List<Device>? devices; @JsonKey(defaultValue: [])
late List<Device> devices;
/// Create a new instance from a json /// Create a new instance from a json
static ListDevicesResponse fromJson(Map<String, dynamic>? json) => static ListDevicesResponse fromJson(Map<String, dynamic> json) =>
_$ListDevicesResponseFromJson(json!); _$ListDevicesResponseFromJson(json);
} }
/// Model response for [Channel.sendFile] api call /// Model response for [Channel.sendFile] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class SendFileResponse extends _BaseResponse { class SendFileResponse extends _BaseResponse {
/// The url of the uploaded file /// The url of the uploaded file
String? file; late String file;
/// Create a new instance from a json /// Create a new instance from a json
static SendFileResponse fromJson(Map<String, dynamic>? json) => static SendFileResponse fromJson(Map<String, dynamic> json) =>
_$SendFileResponseFromJson(json!); _$SendFileResponseFromJson(json);
} }
/// Model response for [Channel.sendImage] api call /// Model response for [Channel.sendImage] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class SendImageResponse extends _BaseResponse { class SendImageResponse extends _BaseResponse {
/// The url of the uploaded file /// The url of the uploaded file
String? file; late String file;
/// Create a new instance from a json /// Create a new instance from a json
static SendImageResponse fromJson(Map<String, dynamic>? json) => static SendImageResponse fromJson(Map<String, dynamic> json) =>
_$SendImageResponseFromJson(json!); _$SendImageResponseFromJson(json);
} }
/// Model response for [Channel.sendReaction] api call /// Model response for [Channel.sendReaction] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class SendReactionResponse extends _BaseResponse { class SendReactionResponse extends _BaseResponse {
/// Message returned by the api call /// Message returned by the api call
Message? message; late Message message;
/// The reaction created by the api call /// The reaction created by the api call
Reaction? reaction; late Reaction reaction;
/// Create a new instance from a json /// Create a new instance from a json
static SendReactionResponse fromJson(Map<String, dynamic>? json) => static SendReactionResponse fromJson(Map<String, dynamic> json) =>
_$SendReactionResponseFromJson(json!); _$SendReactionResponseFromJson(json);
} }
/// Model response for [StreamChatClient.connectGuestUser] api call /// Model response for [StreamChatClient.connectGuestUser] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class ConnectGuestUserResponse extends _BaseResponse { class ConnectGuestUserResponse extends _BaseResponse {
/// Guest user access token /// Guest user access token
String? accessToken; late String accessToken;
/// Guest user /// Guest user
User? user; late User user;
/// Create a new instance from a json /// Create a new instance from a json
static ConnectGuestUserResponse fromJson(Map<String, dynamic>? json) => static ConnectGuestUserResponse fromJson(Map<String, dynamic> json) =>
_$ConnectGuestUserResponseFromJson(json!); _$ConnectGuestUserResponseFromJson(json);
} }
/// Model response for [StreamChatClient.updateUser] api call /// Model response for [StreamChatClient.updateUser] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class UpdateUsersResponse extends _BaseResponse { class UpdateUsersResponse extends _BaseResponse {
/// Updated users /// Updated users
Map<String, User>? users; @JsonKey(defaultValue: {})
late Map<String, User> users;
/// Create a new instance from a json /// Create a new instance from a json
static UpdateUsersResponse fromJson(Map<String, dynamic>? json) => static UpdateUsersResponse fromJson(Map<String, dynamic> json) =>
_$UpdateUsersResponseFromJson(json!); _$UpdateUsersResponseFromJson(json);
} }
/// Model response for [StreamChatClient.updateMessage] api call /// Model response for [StreamChatClient.updateMessage] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class UpdateMessageResponse extends _BaseResponse { class UpdateMessageResponse extends _BaseResponse {
/// Message returned by the api call /// Message returned by the api call
Message? message; late Message message;
/// Create a new instance from a json /// Create a new instance from a json
static UpdateMessageResponse fromJson(Map<String, dynamic>? json) => static UpdateMessageResponse fromJson(Map<String, dynamic> json) =>
_$UpdateMessageResponseFromJson(json!); _$UpdateMessageResponseFromJson(json);
} }
/// Model response for [Channel.sendMessage] api call /// Model response for [Channel.sendMessage] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class SendMessageResponse extends _BaseResponse { class SendMessageResponse extends _BaseResponse {
/// Message returned by the api call /// Message returned by the api call
Message? message; late Message message;
/// Create a new instance from a json /// Create a new instance from a json
static SendMessageResponse fromJson(Map<String, dynamic>? json) => static SendMessageResponse fromJson(Map<String, dynamic> json) =>
_$SendMessageResponseFromJson(json!); _$SendMessageResponseFromJson(json);
} }
/// Model response for [StreamChatClient.getMessage] api call /// Model response for [StreamChatClient.getMessage] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class GetMessageResponse extends _BaseResponse { class GetMessageResponse extends _BaseResponse {
/// Message returned by the api call /// Message returned by the api call
Message? message; late Message message;
/// Channel of the message /// Channel of the message
ChannelModel? channel; ChannelModel? channel;
/// Create a new instance from a json /// Create a new instance from a json
static GetMessageResponse fromJson(Map<String, dynamic>? json) { static GetMessageResponse fromJson(Map<String, dynamic> json) {
final res = _$GetMessageResponseFromJson(json!); final res = _$GetMessageResponseFromJson(json);
final jsonChannel = res.message?.extraData?.remove('channel'); final jsonChannel = res.message.extraData.remove('channel');
if (jsonChannel != null) { if (jsonChannel != null) {
res.channel = ChannelModel.fromJson(jsonChannel); res.channel = ChannelModel.fromJson(jsonChannel);
} }
@@ -211,29 +219,31 @@ class GetMessageResponse extends _BaseResponse {
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class SearchMessagesResponse extends _BaseResponse { class SearchMessagesResponse extends _BaseResponse {
/// List of messages returned by the api call /// List of messages returned by the api call
List<GetMessageResponse>? results; @JsonKey(defaultValue: [])
late List<GetMessageResponse> results;
/// Create a new instance from a json /// Create a new instance from a json
static SearchMessagesResponse fromJson(Map<String, dynamic>? json) => static SearchMessagesResponse fromJson(Map<String, dynamic> json) =>
_$SearchMessagesResponseFromJson(json!); _$SearchMessagesResponseFromJson(json);
} }
/// Model response for [Channel.getMessagesById] api call /// Model response for [Channel.getMessagesById] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class GetMessagesByIdResponse extends _BaseResponse { class GetMessagesByIdResponse extends _BaseResponse {
/// Message returned by the api call /// Message returned by the api call
List<Message>? messages; @JsonKey(defaultValue: [])
late List<Message> messages;
/// Create a new instance from a json /// Create a new instance from a json
static GetMessagesByIdResponse fromJson(Map<String, dynamic>? json) => static GetMessagesByIdResponse fromJson(Map<String, dynamic> json) =>
_$GetMessagesByIdResponseFromJson(json!); _$GetMessagesByIdResponseFromJson(json);
} }
/// Model response for [Channel.update] api call /// Model response for [Channel.update] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class UpdateChannelResponse extends _BaseResponse { class UpdateChannelResponse extends _BaseResponse {
/// Updated channel /// Updated channel
ChannelModel? channel; late ChannelModel channel;
/// Channel members /// Channel members
List<Member>? members; List<Member>? members;
@@ -242,56 +252,58 @@ class UpdateChannelResponse extends _BaseResponse {
Message? message; Message? message;
/// Create a new instance from a json /// Create a new instance from a json
static UpdateChannelResponse fromJson(Map<String, dynamic>? json) => static UpdateChannelResponse fromJson(Map<String, dynamic> json) =>
_$UpdateChannelResponseFromJson(json!); _$UpdateChannelResponseFromJson(json);
} }
/// Model response for [Channel.updatePartial] api call /// Model response for [Channel.updatePartial] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class PartialUpdateChannelResponse extends _BaseResponse { class PartialUpdateChannelResponse extends _BaseResponse {
/// Updated channel /// Updated channel
ChannelModel? channel; late ChannelModel channel;
/// Channel members /// Channel members
List<Member>? members; List<Member>? members;
/// Create a new instance from a json /// Create a new instance from a json
static PartialUpdateChannelResponse fromJson(Map<String, dynamic>? json) => static PartialUpdateChannelResponse fromJson(Map<String, dynamic> json) =>
_$PartialUpdateChannelResponseFromJson(json!); _$PartialUpdateChannelResponseFromJson(json);
} }
/// Model response for [Channel.inviteMembers] api call /// Model response for [Channel.inviteMembers] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class InviteMembersResponse extends _BaseResponse { class InviteMembersResponse extends _BaseResponse {
/// Updated channel /// Updated channel
ChannelModel? channel; late ChannelModel channel;
/// Channel members /// Channel members
List<Member>? members; @JsonKey(defaultValue: [])
late List<Member> members;
/// Message returned by the api call /// Message returned by the api call
Message? message; Message? message;
/// Create a new instance from a json /// Create a new instance from a json
static InviteMembersResponse fromJson(Map<String, dynamic>? json) => static InviteMembersResponse fromJson(Map<String, dynamic> json) =>
_$InviteMembersResponseFromJson(json!); _$InviteMembersResponseFromJson(json);
} }
/// Model response for [Channel.removeMembers] api call /// Model response for [Channel.removeMembers] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class RemoveMembersResponse extends _BaseResponse { class RemoveMembersResponse extends _BaseResponse {
/// Updated channel /// Updated channel
ChannelModel? channel; late ChannelModel channel;
/// Channel members /// Channel members
List<Member>? members; @JsonKey(defaultValue: [])
late List<Member> members;
/// Message returned by the api call /// Message returned by the api call
Message? message; Message? message;
/// Create a new instance from a json /// Create a new instance from a json
static RemoveMembersResponse fromJson(Map<String, dynamic>? json) => static RemoveMembersResponse fromJson(Map<String, dynamic> json) =>
_$RemoveMembersResponseFromJson(json!); _$RemoveMembersResponseFromJson(json);
} }
/// Model response for [Channel.sendAction] api call /// Model response for [Channel.sendAction] api call
@@ -301,86 +313,93 @@ class SendActionResponse extends _BaseResponse {
Message? message; Message? message;
/// Create a new instance from a json /// Create a new instance from a json
static SendActionResponse fromJson(Map<String, dynamic>? json) => static SendActionResponse fromJson(Map<String, dynamic> json) =>
_$SendActionResponseFromJson(json!); _$SendActionResponseFromJson(json);
} }
/// Model response for [Channel.addMembers] api call /// Model response for [Channel.addMembers] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class AddMembersResponse extends _BaseResponse { class AddMembersResponse extends _BaseResponse {
/// Updated channel /// Updated channel
ChannelModel? channel; late ChannelModel channel;
/// Channel members /// Channel members
List<Member>? members; @JsonKey(defaultValue: [])
late List<Member> members;
/// Message returned by the api call /// Message returned by the api call
Message? message; Message? message;
/// Create a new instance from a json /// Create a new instance from a json
static AddMembersResponse fromJson(Map<String, dynamic>? json) => static AddMembersResponse fromJson(Map<String, dynamic> json) =>
_$AddMembersResponseFromJson(json!); _$AddMembersResponseFromJson(json);
} }
/// Model response for [Channel.acceptInvite] api call /// Model response for [Channel.acceptInvite] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class AcceptInviteResponse extends _BaseResponse { class AcceptInviteResponse extends _BaseResponse {
/// Updated channel /// Updated channel
ChannelModel? channel; late ChannelModel channel;
/// Channel members /// Channel members
List<Member>? members; @JsonKey(defaultValue: [])
late List<Member> members;
/// Message returned by the api call /// Message returned by the api call
Message? message; Message? message;
/// Create a new instance from a json /// Create a new instance from a json
static AcceptInviteResponse fromJson(Map<String, dynamic>? json) => static AcceptInviteResponse fromJson(Map<String, dynamic> json) =>
_$AcceptInviteResponseFromJson(json!); _$AcceptInviteResponseFromJson(json);
} }
/// Model response for [Channel.rejectInvite] api call /// Model response for [Channel.rejectInvite] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class RejectInviteResponse extends _BaseResponse { class RejectInviteResponse extends _BaseResponse {
/// Updated channel /// Updated channel
ChannelModel? channel; late ChannelModel channel;
/// Channel members /// Channel members
List<Member>? members; @JsonKey(defaultValue: [])
late List<Member> members;
/// Message returned by the api call /// Message returned by the api call
Message? message; Message? message;
/// Create a new instance from a json /// Create a new instance from a json
static RejectInviteResponse fromJson(Map<String, dynamic>? json) => static RejectInviteResponse fromJson(Map<String, dynamic> json) =>
_$RejectInviteResponseFromJson(json!); _$RejectInviteResponseFromJson(json);
} }
/// Model response for empty responses /// Model response for empty responses
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class EmptyResponse extends _BaseResponse { class EmptyResponse extends _BaseResponse {
/// Create a new instance from a json /// Create a new instance from a json
static EmptyResponse fromJson(Map<String, dynamic>? json) => static EmptyResponse fromJson(Map<String, dynamic> json) =>
_$EmptyResponseFromJson(json!); _$EmptyResponseFromJson(json);
} }
/// Model response for [Channel.query] api call /// Model response for [Channel.query] api call
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class ChannelStateResponse extends _BaseResponse { class ChannelStateResponse extends _BaseResponse {
/// Updated channel /// Updated channel
ChannelModel? channel; late ChannelModel channel;
/// List of messages returned by the api call /// List of messages returned by the api call
List<Message>? messages; @JsonKey(defaultValue: [])
late List<Message> messages;
/// Channel members /// Channel members
List<Member>? members; @JsonKey(defaultValue: [])
late List<Member> members;
/// Number of users watching the channel /// Number of users watching the channel
int? watcherCount; @JsonKey(defaultValue: 0)
late int watcherCount;
/// List of read states /// List of read states
List<Read>? read; @JsonKey(defaultValue: [])
late List<Read> read;
/// Create a new instance from a json /// Create a new instance from a json
static ChannelStateResponse fromJson(Map<String, dynamic> json) => static ChannelStateResponse fromJson(Map<String, dynamic> json) =>
@@ -10,8 +10,9 @@ SyncResponse _$SyncResponseFromJson(Map<String, dynamic> json) {
return SyncResponse() return SyncResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..events = (json['events'] as List<dynamic>?) ..events = (json['events'] as List<dynamic>?)
?.map((e) => Event.fromJson(e as Map<String, dynamic>)) ?.map((e) => Event.fromJson(e as Map<String, dynamic>))
.toList(); .toList() ??
[];
} }
QueryChannelsResponse _$QueryChannelsResponseFromJson( QueryChannelsResponse _$QueryChannelsResponseFromJson(
@@ -19,33 +20,35 @@ QueryChannelsResponse _$QueryChannelsResponseFromJson(
return QueryChannelsResponse() return QueryChannelsResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..channels = (json['channels'] as List<dynamic>?) ..channels = (json['channels'] as List<dynamic>?)
?.map((e) => ChannelState.fromJson(e as Map<String, dynamic>)) ?.map((e) => ChannelState.fromJson(e as Map<String, dynamic>))
.toList(); .toList() ??
[];
} }
TranslateMessageResponse _$TranslateMessageResponseFromJson( TranslateMessageResponse _$TranslateMessageResponseFromJson(
Map<String, dynamic> json) { Map<String, dynamic> json) {
return TranslateMessageResponse() return TranslateMessageResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..message = json['message'] == null ..message =
? null TranslatedMessage.fromJson(json['message'] as Map<String, dynamic>);
: TranslatedMessage.fromJson(json['message'] as Map<String, dynamic>);
} }
QueryMembersResponse _$QueryMembersResponseFromJson(Map<String, dynamic> json) { QueryMembersResponse _$QueryMembersResponseFromJson(Map<String, dynamic> json) {
return QueryMembersResponse() return QueryMembersResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..members = (json['members'] as List<dynamic>?) ..members = (json['members'] as List<dynamic>?)
?.map((e) => Member.fromJson(e as Map<String, dynamic>)) ?.map((e) => Member.fromJson(e as Map<String, dynamic>))
.toList(); .toList() ??
[];
} }
QueryUsersResponse _$QueryUsersResponseFromJson(Map<String, dynamic> json) { QueryUsersResponse _$QueryUsersResponseFromJson(Map<String, dynamic> json) {
return QueryUsersResponse() return QueryUsersResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..users = (json['users'] as List<dynamic>?) ..users = (json['users'] as List<dynamic>?)
?.map((e) => User.fromJson(e as Map<String, dynamic>)) ?.map((e) => User.fromJson(e as Map<String, dynamic>))
.toList(); .toList() ??
[];
} }
QueryReactionsResponse _$QueryReactionsResponseFromJson( QueryReactionsResponse _$QueryReactionsResponseFromJson(
@@ -53,90 +56,82 @@ QueryReactionsResponse _$QueryReactionsResponseFromJson(
return QueryReactionsResponse() return QueryReactionsResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..reactions = (json['reactions'] as List<dynamic>?) ..reactions = (json['reactions'] as List<dynamic>?)
?.map((e) => Reaction.fromJson(e as Map<String, dynamic>)) ?.map((e) => Reaction.fromJson(e as Map<String, dynamic>))
.toList(); .toList() ??
[];
} }
QueryRepliesResponse _$QueryRepliesResponseFromJson(Map<String, dynamic> json) { QueryRepliesResponse _$QueryRepliesResponseFromJson(Map<String, dynamic> json) {
return QueryRepliesResponse() return QueryRepliesResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..messages = (json['messages'] as List<dynamic>?) ..messages = (json['messages'] as List<dynamic>?)
?.map((e) => Message.fromJson(e as Map<String, dynamic>)) ?.map((e) => Message.fromJson(e as Map<String, dynamic>))
.toList(); .toList() ??
[];
} }
ListDevicesResponse _$ListDevicesResponseFromJson(Map<String, dynamic> json) { ListDevicesResponse _$ListDevicesResponseFromJson(Map<String, dynamic> json) {
return ListDevicesResponse() return ListDevicesResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..devices = (json['devices'] as List<dynamic>?) ..devices = (json['devices'] as List<dynamic>?)
?.map((e) => Device.fromJson(e as Map<String, dynamic>)) ?.map((e) => Device.fromJson(e as Map<String, dynamic>))
.toList(); .toList() ??
[];
} }
SendFileResponse _$SendFileResponseFromJson(Map<String, dynamic> json) { SendFileResponse _$SendFileResponseFromJson(Map<String, dynamic> json) {
return SendFileResponse() return SendFileResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..file = json['file'] as String?; ..file = json['file'] as String;
} }
SendImageResponse _$SendImageResponseFromJson(Map<String, dynamic> json) { SendImageResponse _$SendImageResponseFromJson(Map<String, dynamic> json) {
return SendImageResponse() return SendImageResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..file = json['file'] as String?; ..file = json['file'] as String;
} }
SendReactionResponse _$SendReactionResponseFromJson(Map<String, dynamic> json) { SendReactionResponse _$SendReactionResponseFromJson(Map<String, dynamic> json) {
return SendReactionResponse() return SendReactionResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..message = json['message'] == null ..message = Message.fromJson(json['message'] as Map<String, dynamic>)
? null ..reaction = Reaction.fromJson(json['reaction'] as Map<String, dynamic>);
: Message.fromJson(json['message'] as Map<String, dynamic>)
..reaction = json['reaction'] == null
? null
: Reaction.fromJson(json['reaction'] as Map<String, dynamic>);
} }
ConnectGuestUserResponse _$ConnectGuestUserResponseFromJson( ConnectGuestUserResponse _$ConnectGuestUserResponseFromJson(
Map<String, dynamic> json) { Map<String, dynamic> json) {
return ConnectGuestUserResponse() return ConnectGuestUserResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..accessToken = json['access_token'] as String? ..accessToken = json['access_token'] as String
..user = json['user'] == null ..user = User.fromJson(json['user'] as Map<String, dynamic>);
? null
: User.fromJson(json['user'] as Map<String, dynamic>);
} }
UpdateUsersResponse _$UpdateUsersResponseFromJson(Map<String, dynamic> json) { UpdateUsersResponse _$UpdateUsersResponseFromJson(Map<String, dynamic> json) {
return UpdateUsersResponse() return UpdateUsersResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..users = (json['users'] as Map<String, dynamic>?)?.map( ..users = (json['users'] as Map<String, dynamic>?)?.map(
(k, e) => MapEntry(k, User.fromJson(e as Map<String, dynamic>)), (k, e) => MapEntry(k, User.fromJson(e as Map<String, dynamic>)),
); ) ??
{};
} }
UpdateMessageResponse _$UpdateMessageResponseFromJson( UpdateMessageResponse _$UpdateMessageResponseFromJson(
Map<String, dynamic> json) { Map<String, dynamic> json) {
return UpdateMessageResponse() return UpdateMessageResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..message = json['message'] == null ..message = Message.fromJson(json['message'] as Map<String, dynamic>);
? null
: Message.fromJson(json['message'] as Map<String, dynamic>);
} }
SendMessageResponse _$SendMessageResponseFromJson(Map<String, dynamic> json) { SendMessageResponse _$SendMessageResponseFromJson(Map<String, dynamic> json) {
return SendMessageResponse() return SendMessageResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..message = json['message'] == null ..message = Message.fromJson(json['message'] as Map<String, dynamic>);
? null
: Message.fromJson(json['message'] as Map<String, dynamic>);
} }
GetMessageResponse _$GetMessageResponseFromJson(Map<String, dynamic> json) { GetMessageResponse _$GetMessageResponseFromJson(Map<String, dynamic> json) {
return GetMessageResponse() return GetMessageResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..message = json['message'] == null ..message = Message.fromJson(json['message'] as Map<String, dynamic>)
? null
: Message.fromJson(json['message'] as Map<String, dynamic>)
..channel = json['channel'] == null ..channel = json['channel'] == null
? null ? null
: ChannelModel.fromJson(json['channel'] as Map<String, dynamic>); : ChannelModel.fromJson(json['channel'] as Map<String, dynamic>);
@@ -147,8 +142,9 @@ SearchMessagesResponse _$SearchMessagesResponseFromJson(
return SearchMessagesResponse() return SearchMessagesResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..results = (json['results'] as List<dynamic>?) ..results = (json['results'] as List<dynamic>?)
?.map((e) => GetMessageResponse.fromJson(e as Map<String, dynamic>)) ?.map((e) => GetMessageResponse.fromJson(e as Map<String, dynamic>))
.toList(); .toList() ??
[];
} }
GetMessagesByIdResponse _$GetMessagesByIdResponseFromJson( GetMessagesByIdResponse _$GetMessagesByIdResponseFromJson(
@@ -156,17 +152,16 @@ GetMessagesByIdResponse _$GetMessagesByIdResponseFromJson(
return GetMessagesByIdResponse() return GetMessagesByIdResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..messages = (json['messages'] as List<dynamic>?) ..messages = (json['messages'] as List<dynamic>?)
?.map((e) => Message.fromJson(e as Map<String, dynamic>)) ?.map((e) => Message.fromJson(e as Map<String, dynamic>))
.toList(); .toList() ??
[];
} }
UpdateChannelResponse _$UpdateChannelResponseFromJson( UpdateChannelResponse _$UpdateChannelResponseFromJson(
Map<String, dynamic> json) { Map<String, dynamic> json) {
return UpdateChannelResponse() return UpdateChannelResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..channel = json['channel'] == null ..channel = ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
? null
: ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
..members = (json['members'] as List<dynamic>?) ..members = (json['members'] as List<dynamic>?)
?.map((e) => Member.fromJson(e as Map<String, dynamic>)) ?.map((e) => Member.fromJson(e as Map<String, dynamic>))
.toList() .toList()
@@ -179,9 +174,7 @@ PartialUpdateChannelResponse _$PartialUpdateChannelResponseFromJson(
Map<String, dynamic> json) { Map<String, dynamic> json) {
return PartialUpdateChannelResponse() return PartialUpdateChannelResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..channel = json['channel'] == null ..channel = ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
? null
: ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
..members = (json['members'] as List<dynamic>?) ..members = (json['members'] as List<dynamic>?)
?.map((e) => Member.fromJson(e as Map<String, dynamic>)) ?.map((e) => Member.fromJson(e as Map<String, dynamic>))
.toList(); .toList();
@@ -191,12 +184,11 @@ InviteMembersResponse _$InviteMembersResponseFromJson(
Map<String, dynamic> json) { Map<String, dynamic> json) {
return InviteMembersResponse() return InviteMembersResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..channel = json['channel'] == null ..channel = ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
? null
: ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
..members = (json['members'] as List<dynamic>?) ..members = (json['members'] as List<dynamic>?)
?.map((e) => Member.fromJson(e as Map<String, dynamic>)) ?.map((e) => Member.fromJson(e as Map<String, dynamic>))
.toList() .toList() ??
[]
..message = json['message'] == null ..message = json['message'] == null
? null ? null
: Message.fromJson(json['message'] as Map<String, dynamic>); : Message.fromJson(json['message'] as Map<String, dynamic>);
@@ -206,12 +198,11 @@ RemoveMembersResponse _$RemoveMembersResponseFromJson(
Map<String, dynamic> json) { Map<String, dynamic> json) {
return RemoveMembersResponse() return RemoveMembersResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..channel = json['channel'] == null ..channel = ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
? null
: ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
..members = (json['members'] as List<dynamic>?) ..members = (json['members'] as List<dynamic>?)
?.map((e) => Member.fromJson(e as Map<String, dynamic>)) ?.map((e) => Member.fromJson(e as Map<String, dynamic>))
.toList() .toList() ??
[]
..message = json['message'] == null ..message = json['message'] == null
? null ? null
: Message.fromJson(json['message'] as Map<String, dynamic>); : Message.fromJson(json['message'] as Map<String, dynamic>);
@@ -228,12 +219,11 @@ SendActionResponse _$SendActionResponseFromJson(Map<String, dynamic> json) {
AddMembersResponse _$AddMembersResponseFromJson(Map<String, dynamic> json) { AddMembersResponse _$AddMembersResponseFromJson(Map<String, dynamic> json) {
return AddMembersResponse() return AddMembersResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..channel = json['channel'] == null ..channel = ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
? null
: ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
..members = (json['members'] as List<dynamic>?) ..members = (json['members'] as List<dynamic>?)
?.map((e) => Member.fromJson(e as Map<String, dynamic>)) ?.map((e) => Member.fromJson(e as Map<String, dynamic>))
.toList() .toList() ??
[]
..message = json['message'] == null ..message = json['message'] == null
? null ? null
: Message.fromJson(json['message'] as Map<String, dynamic>); : Message.fromJson(json['message'] as Map<String, dynamic>);
@@ -242,12 +232,11 @@ AddMembersResponse _$AddMembersResponseFromJson(Map<String, dynamic> json) {
AcceptInviteResponse _$AcceptInviteResponseFromJson(Map<String, dynamic> json) { AcceptInviteResponse _$AcceptInviteResponseFromJson(Map<String, dynamic> json) {
return AcceptInviteResponse() return AcceptInviteResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..channel = json['channel'] == null ..channel = ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
? null
: ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
..members = (json['members'] as List<dynamic>?) ..members = (json['members'] as List<dynamic>?)
?.map((e) => Member.fromJson(e as Map<String, dynamic>)) ?.map((e) => Member.fromJson(e as Map<String, dynamic>))
.toList() .toList() ??
[]
..message = json['message'] == null ..message = json['message'] == null
? null ? null
: Message.fromJson(json['message'] as Map<String, dynamic>); : Message.fromJson(json['message'] as Map<String, dynamic>);
@@ -256,12 +245,11 @@ AcceptInviteResponse _$AcceptInviteResponseFromJson(Map<String, dynamic> json) {
RejectInviteResponse _$RejectInviteResponseFromJson(Map<String, dynamic> json) { RejectInviteResponse _$RejectInviteResponseFromJson(Map<String, dynamic> json) {
return RejectInviteResponse() return RejectInviteResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..channel = json['channel'] == null ..channel = ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
? null
: ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
..members = (json['members'] as List<dynamic>?) ..members = (json['members'] as List<dynamic>?)
?.map((e) => Member.fromJson(e as Map<String, dynamic>)) ?.map((e) => Member.fromJson(e as Map<String, dynamic>))
.toList() .toList() ??
[]
..message = json['message'] == null ..message = json['message'] == null
? null ? null
: Message.fromJson(json['message'] as Map<String, dynamic>); : Message.fromJson(json['message'] as Map<String, dynamic>);
@@ -274,17 +262,18 @@ EmptyResponse _$EmptyResponseFromJson(Map<String, dynamic> json) {
ChannelStateResponse _$ChannelStateResponseFromJson(Map<String, dynamic> json) { ChannelStateResponse _$ChannelStateResponseFromJson(Map<String, dynamic> json) {
return ChannelStateResponse() return ChannelStateResponse()
..duration = json['duration'] as String? ..duration = json['duration'] as String?
..channel = json['channel'] == null ..channel = ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
? null
: ChannelModel.fromJson(json['channel'] as Map<String, dynamic>)
..messages = (json['messages'] as List<dynamic>?) ..messages = (json['messages'] as List<dynamic>?)
?.map((e) => Message.fromJson(e as Map<String, dynamic>)) ?.map((e) => Message.fromJson(e as Map<String, dynamic>))
.toList() .toList() ??
[]
..members = (json['members'] as List<dynamic>?) ..members = (json['members'] as List<dynamic>?)
?.map((e) => Member.fromJson(e as Map<String, dynamic>)) ?.map((e) => Member.fromJson(e as Map<String, dynamic>))
.toList() .toList() ??
..watcherCount = json['watcher_count'] as int? []
..watcherCount = json['watcher_count'] as int? ?? 0
..read = (json['read'] as List<dynamic>?) ..read = (json['read'] as List<dynamic>?)
?.map((e) => Read.fromJson(e as Map<String, dynamic>)) ?.map((e) => Read.fromJson(e as Map<String, dynamic>))
.toList(); .toList() ??
[];
} }
@@ -1,8 +1,8 @@
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:stream_chat/src/api/responses.dart'; import 'package:stream_chat/src/api/responses.dart';
import 'package:stream_chat/src/client.dart'; import 'package:stream_chat/src/client.dart';
import 'package:stream_chat/src/models/attachment_file.dart';
import 'package:stream_chat/src/extensions/string_extension.dart'; import 'package:stream_chat/src/extensions/string_extension.dart';
import 'package:stream_chat/src/models/attachment_file.dart';
/// Class responsible for uploading images and files to a given channel /// Class responsible for uploading images and files to a given channel
abstract class AttachmentFileUploader { abstract class AttachmentFileUploader {
@@ -13,8 +13,8 @@ abstract class AttachmentFileUploader {
/// and cancel the request using [cancelToken] /// and cancel the request using [cancelToken]
Future<SendImageResponse> sendImage( Future<SendImageResponse> sendImage(
AttachmentFile image, AttachmentFile image,
String? channelId, String channelId,
String? channelType, { String channelType, {
ProgressCallback? onSendProgress, ProgressCallback? onSendProgress,
CancelToken? cancelToken, CancelToken? cancelToken,
}); });
@@ -26,8 +26,8 @@ abstract class AttachmentFileUploader {
/// and cancel the request using [cancelToken] /// and cancel the request using [cancelToken]
Future<SendFileResponse> sendFile( Future<SendFileResponse> sendFile(
AttachmentFile file, AttachmentFile file,
String? channelId, String channelId,
String? channelType, { String channelType, {
ProgressCallback? onSendProgress, ProgressCallback? onSendProgress,
CancelToken? cancelToken, CancelToken? cancelToken,
}); });
@@ -38,8 +38,8 @@ abstract class AttachmentFileUploader {
/// Optionally, cancel the request using [cancelToken] /// Optionally, cancel the request using [cancelToken]
Future<EmptyResponse> deleteImage( Future<EmptyResponse> deleteImage(
String url, String url,
String? channelId, String channelId,
String? channelType, { String channelType, {
CancelToken? cancelToken, CancelToken? cancelToken,
}); });
@@ -49,8 +49,8 @@ abstract class AttachmentFileUploader {
/// Optionally, cancel the request using [cancelToken] /// Optionally, cancel the request using [cancelToken]
Future<EmptyResponse> deleteFile( Future<EmptyResponse> deleteFile(
String url, String url,
String? channelId, String channelId,
String? channelType, { String channelType, {
CancelToken? cancelToken, CancelToken? cancelToken,
}); });
} }
@@ -65,8 +65,8 @@ class StreamAttachmentFileUploader implements AttachmentFileUploader {
@override @override
Future<SendImageResponse> sendImage( Future<SendImageResponse> sendImage(
AttachmentFile file, AttachmentFile file,
String? channelId, String channelId,
String? channelType, { String channelType, {
ProgressCallback? onSendProgress, ProgressCallback? onSendProgress,
CancelToken? cancelToken, CancelToken? cancelToken,
}) async { }) async {
@@ -102,8 +102,8 @@ class StreamAttachmentFileUploader implements AttachmentFileUploader {
@override @override
Future<SendFileResponse> sendFile( Future<SendFileResponse> sendFile(
AttachmentFile file, AttachmentFile file,
String? channelId, String channelId,
String? channelType, { String channelType, {
ProgressCallback? onSendProgress, ProgressCallback? onSendProgress,
CancelToken? cancelToken, CancelToken? cancelToken,
}) async { }) async {
@@ -139,8 +139,8 @@ class StreamAttachmentFileUploader implements AttachmentFileUploader {
@override @override
Future<EmptyResponse> deleteImage( Future<EmptyResponse> deleteImage(
String url, String url,
String? channelId, String channelId,
String? channelType, { String channelType, {
CancelToken? cancelToken, CancelToken? cancelToken,
}) async { }) async {
final response = await _client.delete( final response = await _client.delete(
@@ -154,8 +154,8 @@ class StreamAttachmentFileUploader implements AttachmentFileUploader {
@override @override
Future<EmptyResponse> deleteFile( Future<EmptyResponse> deleteFile(
String url, String url,
String? channelId, String channelId,
String? channelType, { String channelType, {
CancelToken? cancelToken, CancelToken? cancelToken,
}) async { }) async {
final response = await _client.delete( final response = await _client.delete(
+27 -24
View File
@@ -82,7 +82,7 @@ class StreamChatClient {
this.tokenProvider, this.tokenProvider,
this.baseURL = _defaultBaseURL, this.baseURL = _defaultBaseURL,
this.logLevel = Level.WARNING, this.logLevel = Level.WARNING,
this.logHandlerFunction, LogHandlerFunction? logHandlerFunction,
Duration connectTimeout = const Duration(seconds: 6), Duration connectTimeout = const Duration(seconds: 6),
Duration receiveTimeout = const Duration(seconds: 6), Duration receiveTimeout = const Duration(seconds: 6),
Dio? httpClient, Dio? httpClient,
@@ -103,7 +103,7 @@ class StreamChatClient {
state = ClientState(this); state = ClientState(this);
_setupLogger(); _setupLogger(logHandlerFunction);
_setupDio(httpClient, receiveTimeout, connectTimeout); _setupDio(httpClient, receiveTimeout, connectTimeout);
logger.info('instantiating new client'); logger.info('instantiating new client');
@@ -134,7 +134,7 @@ class StreamChatClient {
RetryPolicy? get retryPolicy => _retryPolicy; RetryPolicy? get retryPolicy => _retryPolicy;
/// This client state /// This client state
late final ClientState state; late ClientState state;
/// By default the Chat client will write all messages with level Warn or /// By default the Chat client will write all messages with level Warn or
/// Error to stdout. /// Error to stdout.
@@ -170,7 +170,7 @@ class StreamChatClient {
/// final client = StreamChatClient("stream-chat-api-key", /// final client = StreamChatClient("stream-chat-api-key",
/// logHandlerFunction: myLogHandlerFunction); /// logHandlerFunction: myLogHandlerFunction);
///``` ///```
LogHandlerFunction? logHandlerFunction; late LogHandlerFunction logHandlerFunction;
/// Your project Stream Chat api key. /// Your project Stream Chat api key.
/// Find your API keys here https://getstream.io/dashboard/ /// Find your API keys here https://getstream.io/dashboard/
@@ -371,14 +371,14 @@ class StreamChatClient {
) => ) =>
Logger.detached(name) Logger.detached(name)
..level = logLevel ..level = logLevel
..onRecord.listen(logHandlerFunction ?? _getDefaultLogHandler()); ..onRecord.listen(logHandlerFunction);
void _setupLogger() { void _setupLogger(LogHandlerFunction? logHandlerFunction) {
logger.level = logLevel; logger.level = logLevel;
logHandlerFunction ??= _getDefaultLogHandler(); this.logHandlerFunction = logHandlerFunction ?? _getDefaultLogHandler();
logger.onRecord.listen(logHandlerFunction); logger.onRecord.listen(this.logHandlerFunction);
logger.info('logger setup'); logger.info('logger setup');
} }
@@ -618,15 +618,15 @@ class StreamChatClient {
SyncResponse.fromJson, SyncResponse.fromJson,
); );
res.events!.sort((a, b) => a.createdAt!.compareTo(b.createdAt!)); res.events.sort((a, b) => a.createdAt!.compareTo(b.createdAt!));
res.events!.forEach((element) { res.events.forEach((element) {
logger logger
..fine('element.type: ${element.type}') ..fine('element.type: ${element.type}')
..fine('element.message.text: ${element.message?.text}'); ..fine('element.message.text: ${element.message?.text}');
}); });
res.events!.forEach(handleEvent); res.events.forEach(handleEvent);
await _chatPersistenceClient?.updateLastSyncAt(DateTime.now()); await _chatPersistenceClient?.updateLastSyncAt(DateTime.now());
_synced = true; _synced = true;
@@ -740,7 +740,7 @@ class StreamChatClient {
QueryChannelsResponse.fromJson, QueryChannelsResponse.fromJson,
); );
if ((res.channels ?? []).isEmpty && paginationParams.offset == 0) { if (res.channels.isEmpty && paginationParams.offset == 0) {
logger.warning( logger.warning(
''' '''
We could not find any channel for this query. We could not find any channel for this query.
@@ -750,7 +750,7 @@ class StreamChatClient {
return <Channel>[]; return <Channel>[];
} }
final channels = res.channels!; final channels = res.channels;
final users = channels final users = channels
.expand((it) => it.members) .expand((it) => it.members)
@@ -759,7 +759,7 @@ class StreamChatClient {
state._updateUsers(users); state._updateUsers(users);
logger.info('Got ${res.channels?.length} channels from api'); logger.info('Got ${res.channels.length} channels from api');
final updateData = _mapChannelStateToChannel(channels); final updateData = _mapChannelStateToChannel(channels);
@@ -1053,7 +1053,7 @@ class StreamChatClient {
QueryUsersResponse.fromJson, QueryUsersResponse.fromJson,
); );
state._updateUsers(response.users!); state._updateUsers(response.users);
return response; return response;
} }
@@ -1100,8 +1100,8 @@ class StreamChatClient {
/// Send a [file] to the [channelId] of type [channelType] /// Send a [file] to the [channelId] of type [channelType]
Future<SendFileResponse> sendFile( Future<SendFileResponse> sendFile(
AttachmentFile file, AttachmentFile file,
String? channelId, String channelId,
String? channelType, { String channelType, {
ProgressCallback? onSendProgress, ProgressCallback? onSendProgress,
CancelToken? cancelToken, CancelToken? cancelToken,
}) => }) =>
@@ -1116,8 +1116,8 @@ class StreamChatClient {
/// Send a [image] to the [channelId] of type [channelType] /// Send a [image] to the [channelId] of type [channelType]
Future<SendImageResponse> sendImage( Future<SendImageResponse> sendImage(
AttachmentFile image, AttachmentFile image,
String? channelId, String channelId,
String? channelType, { String channelType, {
ProgressCallback? onSendProgress, ProgressCallback? onSendProgress,
CancelToken? cancelToken, CancelToken? cancelToken,
}) => }) =>
@@ -1132,8 +1132,8 @@ class StreamChatClient {
/// Delete a file from this channel /// Delete a file from this channel
Future<EmptyResponse> deleteFile( Future<EmptyResponse> deleteFile(
String url, String url,
String? channelId, String channelId,
String? channelType, { String channelType, {
CancelToken? cancelToken, CancelToken? cancelToken,
}) => }) =>
attachmentFileUploader!.deleteFile( attachmentFileUploader!.deleteFile(
@@ -1146,8 +1146,8 @@ class StreamChatClient {
/// Delete an image from this channel /// Delete an image from this channel
Future<EmptyResponse> deleteImage( Future<EmptyResponse> deleteImage(
String url, String url,
String? channelId, String channelId,
String? channelType, { String channelType, {
CancelToken? cancelToken, CancelToken? cancelToken,
}) => }) =>
attachmentFileUploader!.deleteImage( attachmentFileUploader!.deleteImage(
@@ -1327,7 +1327,10 @@ class StreamChatClient {
/// Sends the message to the given channel /// Sends the message to the given channel
Future<SendMessageResponse> sendMessage( Future<SendMessageResponse> sendMessage(
Message message, String? channelId, String? channelType) async { Message message,
String channelId,
String channelType,
) async {
final response = await post( final response = await post(
'/channels/$channelType/$channelId/message', '/channels/$channelType/$channelId/message',
data: {'message': message.toJson()}, data: {'message': message.toJson()},
@@ -6,22 +6,29 @@ part 'action.g.dart';
@JsonSerializable() @JsonSerializable()
class Action { class Action {
/// Constructor used for json serialization /// Constructor used for json serialization
Action({this.name, this.style, this.text, this.type, this.value}); Action({
required this.name,
this.style = 'default',
required this.text,
required this.type,
this.value,
});
/// Create a new instance from a json /// Create a new instance from a json
factory Action.fromJson(Map<String, dynamic> json) => _$ActionFromJson(json); factory Action.fromJson(Map<String, dynamic> json) => _$ActionFromJson(json);
/// The name of the action /// The name of the action
final String? name; final String name;
/// The style of the action /// The style of the action
final String? style; @JsonKey(defaultValue: 'default')
final String style;
/// The test of the action /// The test of the action
final String? text; final String text;
/// The type of the action /// The type of the action
final String? type; final String type;
/// The value of the action /// The value of the action
final String? value; final String? value;
@@ -8,10 +8,10 @@ part of 'action.dart';
Action _$ActionFromJson(Map<String, dynamic> json) { Action _$ActionFromJson(Map<String, dynamic> json) {
return Action( return Action(
name: json['name'] as String?, name: json['name'] as String,
style: json['style'] as String?, style: json['style'] as String? ?? 'default',
text: json['text'] as String?, text: json['text'] as String,
type: json['type'] as String?, type: json['type'] as String,
value: json['value'] as String?, value: json['value'] as String?,
); );
} }
@@ -15,7 +15,7 @@ class Attachment extends Equatable {
/// Constructor used for json serialization /// Constructor used for json serialization
Attachment({ Attachment({
String? id, String? id,
String? type, this.type,
this.titleLink, this.titleLink,
String? title, String? title,
this.thumbUrl, this.thumbUrl,
@@ -32,14 +32,14 @@ class Attachment extends Equatable {
this.authorLink, this.authorLink,
this.authorIcon, this.authorIcon,
this.assetUrl, this.assetUrl,
this.actions, List<Action>? actions,
this.extraData, this.extraData,
this.file, this.file,
UploadState? uploadState, UploadState? uploadState,
}) : id = id ?? const Uuid().v4(), }) : id = id ?? const Uuid().v4(),
title = title ?? file?.name, title = title ?? file?.name,
type = type ?? '', localUri = file?.path != null ? Uri.parse(file!.path!) : null,
localUri = file?.path != null ? Uri.parse(file!.path!) : null { actions = actions ?? [] {
this.uploadState = uploadState ?? this.uploadState = uploadState ??
((assetUrl != null || imageUrl != null) ((assetUrl != null || imageUrl != null)
? const UploadState.success() ? const UploadState.success()
@@ -58,7 +58,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;
@@ -98,7 +98,8 @@ class Attachment extends Equatable {
final String? assetUrl; final String? assetUrl;
/// Actions from a command /// Actions from a command
final List<Action>? actions; @JsonKey(defaultValue: [])
final List<Action> actions;
final Uri? localUri; final Uri? localUri;
@@ -106,7 +107,7 @@ class Attachment extends Equatable {
final AttachmentFile? file; final AttachmentFile? file;
/// The current upload state of the attachment /// The current upload state of the attachment
late final UploadState? uploadState; late final UploadState uploadState;
/// Map of custom channel extraData /// Map of custom channel extraData
@JsonKey(includeIfNull: false) @JsonKey(includeIfNull: false)
@@ -149,13 +150,13 @@ class Attachment extends Equatable {
]; ];
/// Serialize to json /// Serialize to json
Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot( Map<String, dynamic> toJson() =>
_$AttachmentToJson(this), topLevelFields) Serialization.moveFromExtraDataToRoot(_$AttachmentToJson(this))
..removeWhere((key, value) => dbSpecificTopLevelFields.contains(key)); ..removeWhere((key, value) => dbSpecificTopLevelFields.contains(key));
/// Serialize to db data /// Serialize to db data
Map<String, dynamic> toData() => Serialization.moveFromExtraDataToRoot( Map<String, dynamic> toData() =>
_$AttachmentToJson(this), topLevelFields + dbSpecificTopLevelFields); Serialization.moveFromExtraDataToRoot(_$AttachmentToJson(this));
Attachment copyWith({ Attachment copyWith({
String? id, String? id,
@@ -27,8 +27,9 @@ Attachment _$AttachmentFromJson(Map<String, dynamic> json) {
authorIcon: json['author_icon'] as String?, authorIcon: json['author_icon'] as String?,
assetUrl: json['asset_url'] as String?, assetUrl: json['asset_url'] as String?,
actions: (json['actions'] as List<dynamic>?) actions: (json['actions'] as List<dynamic>?)
?.map((e) => Action.fromJson(e as Map<String, dynamic>)) ?.map((e) => Action.fromJson(e as Map<String, dynamic>))
.toList(), .toList() ??
[],
extraData: json['extra_data'] as Map<String, dynamic>?, extraData: json['extra_data'] as Map<String, dynamic>?,
file: json['file'] == null file: json['file'] == null
? null ? null
@@ -40,9 +41,7 @@ Attachment _$AttachmentFromJson(Map<String, dynamic> 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) {
@@ -50,6 +49,7 @@ 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);
@@ -66,9 +66,9 @@ Map<String, dynamic> _$AttachmentToJson(Attachment instance) {
writeNotNull('author_link', instance.authorLink); writeNotNull('author_link', instance.authorLink);
writeNotNull('author_icon', instance.authorIcon); writeNotNull('author_icon', instance.authorIcon);
writeNotNull('asset_url', instance.assetUrl); writeNotNull('asset_url', instance.assetUrl);
writeNotNull('actions', instance.actions?.map((e) => e.toJson()).toList()); val['actions'] = instance.actions.map((e) => e.toJson()).toList();
writeNotNull('file', instance.file?.toJson()); writeNotNull('file', instance.file?.toJson());
writeNotNull('upload_state', instance.uploadState?.toJson()); val['upload_state'] = instance.uploadState.toJson();
writeNotNull('extra_data', instance.extraData); writeNotNull('extra_data', instance.extraData);
val['id'] = instance.id; val['id'] = instance.id;
return val; return val;
@@ -4,7 +4,6 @@ import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
part 'attachment_file.freezed.dart'; part 'attachment_file.freezed.dart';
part 'attachment_file.g.dart'; part 'attachment_file.g.dart';
/// Union class to hold various [UploadState] of a attachment. /// Union class to hold various [UploadState] of a attachment.
@@ -14,8 +13,10 @@ class UploadState with _$UploadState {
const factory UploadState.preparing() = Preparing; const factory UploadState.preparing() = Preparing;
/// InProgress state of the union /// InProgress state of the union
const factory UploadState.inProgress( const factory UploadState.inProgress({
{required int uploaded, required int total}) = InProgress; required int uploaded,
required int total,
}) = InProgress;
/// Success state of the union /// Success state of the union
const factory UploadState.success() = Success; const factory UploadState.success() = Success;
@@ -62,7 +63,10 @@ class AttachmentFile {
this.name, this.name,
this.bytes, this.bytes,
this.size, this.size,
}); }) : assert(
path != null || bytes != null,
'Either path or bytes should be != null',
);
/// Create a new instance from a json /// Create a new instance from a json
factory AttachmentFile.fromJson(Map<String, dynamic> json) => factory AttachmentFile.fromJson(Map<String, dynamic> json) =>
@@ -1,5 +1,6 @@
import 'package:json_annotation/json_annotation.dart'; import 'package:json_annotation/json_annotation.dart';
import 'package:stream_chat/src/models/command.dart'; import 'package:stream_chat/src/models/command.dart';
part 'channel_config.g.dart'; part 'channel_config.g.dart';
/// The class that contains the information about the configuration of a channel /// The class that contains the information about the configuration of a channel
@@ -7,75 +8,85 @@ part 'channel_config.g.dart';
class ChannelConfig { class ChannelConfig {
/// Constructor used for json serialization /// Constructor used for json serialization
ChannelConfig({ ChannelConfig({
this.automod, this.automod = 'flag',
this.commands, this.commands = const [],
this.connectEvents, this.connectEvents = false,
this.createdAt, DateTime? createdAt,
this.updatedAt, DateTime? updatedAt,
this.maxMessageLength, this.maxMessageLength = 0,
this.messageRetention, this.messageRetention = '',
this.mutes, this.mutes = false,
this.name, this.reactions = false,
this.reactions, this.readEvents = false,
this.readEvents, this.replies = false,
this.replies, this.search = false,
this.search, this.typingEvents = false,
this.typingEvents, this.uploads = false,
this.uploads, this.urlEnrichment = false,
this.urlEnrichment, }) : createdAt = createdAt ?? DateTime.now(),
}); updatedAt = updatedAt ?? DateTime.now();
/// Create a new instance from a json /// Create a new instance from a json
factory ChannelConfig.fromJson(Map<String, dynamic> json) => factory ChannelConfig.fromJson(Map<String, dynamic> json) =>
_$ChannelConfigFromJson(json); _$ChannelConfigFromJson(json);
/// Moderation configuration /// Moderation configuration
final String? automod; @JsonKey(defaultValue: 'flag')
final String automod;
/// List of available commands /// List of available commands
final List<Command>? commands; @JsonKey(defaultValue: [])
final List<Command> commands;
/// True if the channel should send connect events /// True if the channel should send connect events
final bool? connectEvents; @JsonKey(defaultValue: false)
final bool connectEvents;
/// Date of channel creation /// Date of channel creation
final DateTime? createdAt; final DateTime createdAt;
/// Date of last channel update /// Date of last channel update
final DateTime? updatedAt; final DateTime updatedAt;
/// Max channel message length /// Max channel message length
final int? maxMessageLength; @JsonKey(defaultValue: 0)
final int maxMessageLength;
/// Duration of message retention /// Duration of message retention
final String? messageRetention; @JsonKey(defaultValue: '')
final String messageRetention;
/// True if users can be muted /// True if users can be muted
final bool? mutes; @JsonKey(defaultValue: false)
final bool mutes;
/// Name of the channel
final String? name;
/// True if reaction are active for this channel /// True if reaction are active for this channel
final bool? reactions; @JsonKey(defaultValue: false)
final bool reactions;
/// True if readEvents are active for this channel /// True if readEvents are active for this channel
final bool? readEvents; @JsonKey(defaultValue: false)
final bool readEvents;
/// True if reply message are active for this channel /// True if reply message are active for this channel
final bool? replies; @JsonKey(defaultValue: false)
final bool replies;
/// True if it's possible to perform a search in this channel /// True if it's possible to perform a search in this channel
final bool? search; @JsonKey(defaultValue: false)
final bool search;
/// True if typing events should be sent for this channel /// True if typing events should be sent for this channel
final bool? typingEvents; @JsonKey(defaultValue: false)
final bool typingEvents;
/// True if it's possible to upload files to this channel /// True if it's possible to upload files to this channel
final bool? uploads; @JsonKey(defaultValue: false)
final bool uploads;
/// True if urls appears as attachments /// True if urls appears as attachments
final bool? urlEnrichment; @JsonKey(defaultValue: false)
final bool urlEnrichment;
/// Serialize to json /// Serialize to json
Map<String, dynamic> toJson() => _$ChannelConfigToJson(this); Map<String, dynamic> toJson() => _$ChannelConfigToJson(this);
@@ -8,42 +8,41 @@ part of 'channel_config.dart';
ChannelConfig _$ChannelConfigFromJson(Map<String, dynamic> json) { ChannelConfig _$ChannelConfigFromJson(Map<String, dynamic> json) {
return ChannelConfig( return ChannelConfig(
automod: json['automod'] as String?, automod: json['automod'] as String? ?? 'flag',
commands: (json['commands'] as List<dynamic>?) commands: (json['commands'] as List<dynamic>?)
?.map((e) => Command.fromJson(e as Map<String, dynamic>)) ?.map((e) => Command.fromJson(e as Map<String, dynamic>))
.toList(), .toList() ??
connectEvents: json['connect_events'] as bool?, [],
connectEvents: json['connect_events'] as bool? ?? false,
createdAt: json['created_at'] == null createdAt: json['created_at'] == null
? null ? null
: DateTime.parse(json['created_at'] as String), : DateTime.parse(json['created_at'] as String),
updatedAt: json['updated_at'] == null updatedAt: json['updated_at'] == null
? null ? null
: DateTime.parse(json['updated_at'] as String), : DateTime.parse(json['updated_at'] as String),
maxMessageLength: json['max_message_length'] as int?, maxMessageLength: json['max_message_length'] as int? ?? 0,
messageRetention: json['message_retention'] as String?, messageRetention: json['message_retention'] as String? ?? '',
mutes: json['mutes'] as bool?, mutes: json['mutes'] as bool? ?? false,
name: json['name'] as String?, reactions: json['reactions'] as bool? ?? false,
reactions: json['reactions'] as bool?, readEvents: json['read_events'] as bool? ?? false,
readEvents: json['read_events'] as bool?, replies: json['replies'] as bool? ?? false,
replies: json['replies'] as bool?, search: json['search'] as bool? ?? false,
search: json['search'] as bool?, typingEvents: json['typing_events'] as bool? ?? false,
typingEvents: json['typing_events'] as bool?, uploads: json['uploads'] as bool? ?? false,
uploads: json['uploads'] as bool?, urlEnrichment: json['url_enrichment'] as bool? ?? false,
urlEnrichment: json['url_enrichment'] as bool?,
); );
} }
Map<String, dynamic> _$ChannelConfigToJson(ChannelConfig instance) => Map<String, dynamic> _$ChannelConfigToJson(ChannelConfig instance) =>
<String, dynamic>{ <String, dynamic>{
'automod': instance.automod, 'automod': instance.automod,
'commands': instance.commands?.map((e) => e.toJson()).toList(), 'commands': instance.commands.map((e) => e.toJson()).toList(),
'connect_events': instance.connectEvents, 'connect_events': instance.connectEvents,
'created_at': instance.createdAt?.toIso8601String(), 'created_at': instance.createdAt.toIso8601String(),
'updated_at': instance.updatedAt?.toIso8601String(), 'updated_at': instance.updatedAt.toIso8601String(),
'max_message_length': instance.maxMessageLength, 'max_message_length': instance.maxMessageLength,
'message_retention': instance.messageRetention, 'message_retention': instance.messageRetention,
'mutes': instance.mutes, 'mutes': instance.mutes,
'name': instance.name,
'reactions': instance.reactions, 'reactions': instance.reactions,
'read_events': instance.readEvents, 'read_events': instance.readEvents,
'replies': instance.replies, 'replies': instance.replies,
@@ -10,9 +10,9 @@ part 'channel_model.g.dart';
class ChannelModel { class ChannelModel {
/// Constructor used for json serialization /// Constructor used for json serialization
ChannelModel({ ChannelModel({
this.id, String? id,
this.type, String? type,
this.cid = '', String? cid,
ChannelConfig? config, ChannelConfig? config,
this.createdBy, this.createdBy,
this.frozen = false, this.frozen = false,
@@ -25,7 +25,14 @@ class ChannelModel {
this.team, this.team,
}) : config = config ?? ChannelConfig(), }) : config = config ?? ChannelConfig(),
createdAt = createdAt ?? DateTime.now(), createdAt = createdAt ?? DateTime.now(),
updatedAt = updatedAt ?? DateTime.now(); updatedAt = updatedAt ?? DateTime.now(),
assert(
cid != null || (id != null && type != null),
'provide either a cid or an id and type',
),
id = id ?? cid!.split(':')[1],
type = type ?? cid!.split(':')[0],
cid = cid ?? '$type:$id';
/// 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) =>
@@ -33,10 +40,10 @@ class ChannelModel {
Serialization.moveToExtraDataFromRoot(json, topLevelFields)); Serialization.moveToExtraDataFromRoot(json, topLevelFields));
/// The id of this channel /// The id of this channel
final String? id; final String id;
/// The type of this channel /// The type of this channel
final String? type; final String type;
/// The cid of this channel /// The cid of this channel
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly) @JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
@@ -107,7 +114,6 @@ class ChannelModel {
/// Serialize to json /// Serialize to json
Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot( Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot(
_$ChannelModelToJson(this), _$ChannelModelToJson(this),
topLevelFields,
); );
/// Creates a copy of [ChannelModel] with specified attributes overridden. /// Creates a copy of [ChannelModel] with specified attributes overridden.
@@ -10,7 +10,7 @@ ChannelModel _$ChannelModelFromJson(Map<String, dynamic> 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: json['config'] == null
? null ? null
: ChannelConfig.fromJson(json['config'] as Map<String, dynamic>), : ChannelConfig.fromJson(json['config'] as Map<String, dynamic>),
@@ -7,9 +7,9 @@ part 'command.g.dart';
class Command { class Command {
/// Constructor used for json serialization /// Constructor used for json serialization
Command({ Command({
this.name, required this.name,
this.description, required this.description,
this.args, required this.args,
}); });
/// Create a new instance from a json /// Create a new instance from a json
@@ -17,13 +17,13 @@ class Command {
_$CommandFromJson(json); _$CommandFromJson(json);
/// The name of the command /// The name of the command
final String? name; final String name;
/// The description explaining the command /// The description explaining the command
final String? description; final String description;
/// The arguments of the command /// The arguments of the command
final String? args; final String args;
/// Serialize to json /// Serialize to json
Map<String, dynamic> toJson() => _$CommandToJson(this); Map<String, dynamic> toJson() => _$CommandToJson(this);
@@ -8,9 +8,9 @@ part of 'command.dart';
Command _$CommandFromJson(Map<String, dynamic> json) { Command _$CommandFromJson(Map<String, dynamic> json) {
return Command( return Command(
name: json['name'] as String?, name: json['name'] as String,
description: json['description'] as String?, description: json['description'] as String,
args: json['args'] as String?, args: json['args'] as String,
); );
} }
@@ -7,8 +7,8 @@ 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, required this.pushProvider,
}); });
/// Create a new instance from a json /// Create a new instance from a json
@@ -18,7 +18,7 @@ class Device {
final String id; final String id;
/// The notification push provider /// The notification push provider
final String? pushProvider; final String pushProvider;
/// Serialize to json /// Serialize to json
Map<String, dynamic> toJson() => _$DeviceToJson(this); Map<String, dynamic> toJson() => _$DeviceToJson(this);
@@ -9,7 +9,7 @@ part of 'device.dart';
Device _$DeviceFromJson(Map<String, dynamic> json) { Device _$DeviceFromJson(Map<String, dynamic> 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,
); );
} }
@@ -119,7 +119,6 @@ class Event {
/// Serialize to json /// Serialize to json
Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot( Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot(
_$EventToJson(this), _$EventToJson(this),
topLevelFields,
); );
/// Creates a copy of [Event] with specified attributes overridden. /// Creates a copy of [Event] with specified attributes overridden.
@@ -217,6 +216,5 @@ class EventChannel extends ChannelModel {
@override @override
Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot( Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot(
_$EventChannelToJson(this), _$EventChannelToJson(this),
topLevelFields,
); );
} }
@@ -13,9 +13,9 @@ class Member {
this.inviteAcceptedAt, this.inviteAcceptedAt,
this.inviteRejectedAt, this.inviteRejectedAt,
this.invited = false, this.invited = false,
this.role = '', this.role,
this.userId, this.userId,
this.isModerator, this.isModerator = false,
DateTime? createdAt, DateTime? createdAt,
DateTime? updatedAt, DateTime? updatedAt,
this.banned = false, this.banned = false,
@@ -45,14 +45,14 @@ class Member {
final bool invited; final bool invited;
/// The role of the user in the channel /// The role of the user in the channel
@JsonKey(defaultValue: '') final String? role;
final String role;
/// The id of the interested user /// The id of the interested user
final String? userId; final String? userId;
/// True if the user is a moderator of the channel /// True if the user is a moderator of the channel
final bool? isModerator; @JsonKey(defaultValue: false)
final bool isModerator;
/// True if the member is banned from the channel /// True if the member is banned from the channel
@JsonKey(defaultValue: false) @JsonKey(defaultValue: false)
@@ -18,9 +18,9 @@ Member _$MemberFromJson(Map<String, dynamic> json) {
? null ? null
: DateTime.parse(json['invite_rejected_at'] as String), : DateTime.parse(json['invite_rejected_at'] as String),
invited: json['invited'] as bool? ?? false, invited: json['invited'] as bool? ?? false,
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? ?? false,
createdAt: json['created_at'] == null createdAt: json['created_at'] == null
? null ? null
: DateTime.parse(json['created_at'] as String), : DateTime.parse(json['created_at'] as String),
@@ -46,12 +46,12 @@ class Message extends Equatable {
/// Constructor used for json serialization /// Constructor used for json serialization
Message({ Message({
String? id, String? id,
this.text = '', this.text,
this.type = '', this.type = 'regular',
this.attachments, this.attachments = const [],
this.mentionedUsers, this.mentionedUsers = const [],
this.silent, this.silent = false,
this.shadowed, this.shadowed = false,
this.reactionCounts, this.reactionCounts,
this.reactionScores, this.reactionScores,
this.latestReactions, this.latestReactions,
@@ -70,10 +70,10 @@ class Message extends Equatable {
this.pinnedAt, this.pinnedAt,
DateTime? pinExpires, DateTime? pinExpires,
this.pinnedBy, this.pinnedBy,
this.extraData, this.extraData = const {},
this.deletedAt, this.deletedAt,
this.status = MessageSendingStatus.sent, this.status = MessageSendingStatus.sent,
this.skipPush, this.skipPush = false,
}) : id = id ?? const Uuid().v4(), }) : id = id ?? const Uuid().v4(),
pinExpires = pinExpires?.toUtc(), pinExpires = pinExpires?.toUtc(),
createdAt = createdAt ?? DateTime.now(), createdAt = createdAt ?? DateTime.now(),
@@ -88,24 +88,34 @@ 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)
final MessageSendingStatus status; final MessageSendingStatus status;
/// The message type /// The message type
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly) @JsonKey(
includeIfNull: false,
toJson: Serialization.readOnly,
defaultValue: 'regular',
)
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.
@JsonKey(includeIfNull: false) @JsonKey(
final List<Attachment>? attachments; includeIfNull: false,
defaultValue: [],
)
final List<Attachment> attachments;
/// The list of user mentioned in the message /// The list of user mentioned in the message
@JsonKey(toJson: Serialization.userIds) @JsonKey(
final List<User>? mentionedUsers; toJson: Serialization.userIds,
defaultValue: [],
)
final List<User> mentionedUsers;
/// A map describing the count of number of every reaction /// A map describing the count of number of every reaction
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly) @JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
@@ -145,14 +155,20 @@ class Message extends Equatable {
final bool? showInChannel; final bool? showInChannel;
/// If true the message is silent /// If true the message is silent
final bool? silent; @JsonKey(defaultValue: false)
final bool silent;
/// If true the message will not send a push notification /// If true the message will not send a push notification
final bool? skipPush; @JsonKey(defaultValue: false)
final bool skipPush;
/// If true the message is shadowed /// If true the message is shadowed
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly) @JsonKey(
final bool? shadowed; includeIfNull: false,
toJson: Serialization.readOnly,
defaultValue: false,
)
final bool shadowed;
/// A used command name. /// A used command name.
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly) @JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
@@ -171,7 +187,8 @@ class Message extends Equatable {
final User? user; final User? user;
/// If true the message is pinned /// If true the message is pinned
final bool? pinned; @JsonKey(defaultValue: false)
final bool pinned;
/// Reserved field indicating when the message was pinned /// Reserved field indicating when the message was pinned
@JsonKey(toJson: Serialization.readOnly) @JsonKey(toJson: Serialization.readOnly)
@@ -187,8 +204,11 @@ class Message extends Equatable {
final User? pinnedBy; final User? pinnedBy;
/// Message custom extraData /// Message custom extraData
@JsonKey(includeIfNull: false) @JsonKey(
final Map<String, dynamic>? extraData; includeIfNull: false,
defaultValue: {},
)
final Map<String, dynamic> extraData;
/// True if the message is a system info /// True if the message is a system info
bool get isSystem => type == 'system'; bool get isSystem => type == 'system';
@@ -238,7 +258,8 @@ class Message extends Equatable {
/// Serialize to json /// Serialize to json
Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot( Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot(
_$MessageToJson(this), topLevelFields); _$MessageToJson(this),
);
/// Creates a copy of [Message] with specified attributes overridden. /// Creates a copy of [Message] with specified attributes overridden.
Message copyWith({ Message copyWith({
@@ -408,6 +429,5 @@ class TranslatedMessage extends Message {
@override @override
Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot( Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot(
_$TranslatedMessageToJson(this), _$TranslatedMessageToJson(this),
topLevelFields,
); );
} }
@@ -9,16 +9,18 @@ part of 'message.dart';
Message _$MessageFromJson(Map<String, dynamic> json) { Message _$MessageFromJson(Map<String, dynamic> 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? ?? 'regular',
attachments: (json['attachments'] as List<dynamic>?) attachments: (json['attachments'] as List<dynamic>?)
?.map((e) => Attachment.fromJson(e as Map<String, dynamic>)) ?.map((e) => Attachment.fromJson(e as Map<String, dynamic>))
.toList(), .toList() ??
[],
mentionedUsers: (json['mentioned_users'] as List<dynamic>?) mentionedUsers: (json['mentioned_users'] as List<dynamic>?)
?.map((e) => User.fromJson(e as Map<String, dynamic>)) ?.map((e) => User.fromJson(e as Map<String, dynamic>))
.toList(), .toList() ??
silent: json['silent'] as bool?, [],
shadowed: json['shadowed'] as bool?, silent: json['silent'] as bool? ?? false,
shadowed: json['shadowed'] as bool? ?? false,
reactionCounts: (json['reaction_counts'] as Map<String, dynamic>?)?.map( reactionCounts: (json['reaction_counts'] as Map<String, dynamic>?)?.map(
(k, e) => MapEntry(k, e as int), (k, e) => MapEntry(k, e as int),
), ),
@@ -51,7 +53,7 @@ Message _$MessageFromJson(Map<String, dynamic> json) {
user: json['user'] == null user: json['user'] == null
? null ? null
: User.fromJson(json['user'] as Map<String, dynamic>), : User.fromJson(json['user'] as Map<String, dynamic>),
pinned: json['pinned'] as bool?, pinned: json['pinned'] as bool? ?? false,
pinnedAt: json['pinned_at'] == null pinnedAt: json['pinned_at'] == null
? null ? null
: DateTime.parse(json['pinned_at'] as String), : DateTime.parse(json['pinned_at'] as String),
@@ -61,11 +63,11 @@ Message _$MessageFromJson(Map<String, dynamic> json) {
pinnedBy: json['pinned_by'] == null pinnedBy: json['pinned_by'] == null
? null ? null
: User.fromJson(json['pinned_by'] as Map<String, dynamic>), : User.fromJson(json['pinned_by'] as Map<String, dynamic>),
extraData: json['extra_data'] as Map<String, dynamic>?, extraData: json['extra_data'] as Map<String, dynamic>? ?? {},
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),
skipPush: json['skip_push'] as bool?, skipPush: json['skip_push'] as bool? ?? false,
); );
} }
@@ -82,8 +84,7 @@ Map<String, dynamic> _$MessageToJson(Message instance) {
} }
writeNotNull('type', readonly(instance.type)); writeNotNull('type', readonly(instance.type));
writeNotNull( val['attachments'] = instance.attachments.map((e) => e.toJson()).toList();
'attachments', instance.attachments?.map((e) => e.toJson()).toList());
val['mentioned_users'] = Serialization.userIds(instance.mentionedUsers); val['mentioned_users'] = Serialization.userIds(instance.mentionedUsers);
writeNotNull('reaction_counts', readonly(instance.reactionCounts)); writeNotNull('reaction_counts', readonly(instance.reactionCounts));
writeNotNull('reaction_scores', readonly(instance.reactionScores)); writeNotNull('reaction_scores', readonly(instance.reactionScores));
@@ -106,7 +107,7 @@ Map<String, dynamic> _$MessageToJson(Message instance) {
val['pinned_at'] = readonly(instance.pinnedAt); val['pinned_at'] = readonly(instance.pinnedAt);
val['pin_expires'] = instance.pinExpires?.toIso8601String(); val['pin_expires'] = instance.pinExpires?.toIso8601String();
val['pinned_by'] = readonly(instance.pinnedBy); val['pinned_by'] = readonly(instance.pinnedBy);
writeNotNull('extra_data', instance.extraData); val['extra_data'] = instance.extraData;
writeNotNull('deleted_at', readonly(instance.deletedAt)); writeNotNull('deleted_at', readonly(instance.deletedAt));
return val; return val;
} }
+10 -5
View File
@@ -9,26 +9,31 @@ part 'mute.g.dart';
@JsonSerializable() @JsonSerializable()
class Mute { class Mute {
/// Constructor used for json serialization /// Constructor used for json serialization
Mute({this.user, this.channel, this.createdAt, this.updatedAt}); Mute({
required this.user,
required this.channel,
required this.createdAt,
required this.updatedAt,
});
/// Create a new instance from a json /// Create a new instance from a json
factory Mute.fromJson(Map<String, dynamic> json) => _$MuteFromJson(json); factory Mute.fromJson(Map<String, dynamic> json) => _$MuteFromJson(json);
/// The user that performed the muting action /// The user that performed the muting action
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly) @JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final User? user; final User user;
/// The target user /// The target user
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly) @JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final ChannelModel? channel; final ChannelModel channel;
/// The date in which the use was muted /// The date in which the use was muted
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly) @JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final DateTime? createdAt; final DateTime createdAt;
/// The date of the last update /// The date of the last update
@JsonKey(includeIfNull: false, toJson: Serialization.readOnly) @JsonKey(includeIfNull: false, toJson: Serialization.readOnly)
final DateTime? updatedAt; final DateTime updatedAt;
/// Serialize to json /// Serialize to json
Map<String, dynamic> toJson() => _$MuteToJson(this); Map<String, dynamic> toJson() => _$MuteToJson(this);
@@ -8,18 +8,10 @@ part of 'mute.dart';
Mute _$MuteFromJson(Map<String, dynamic> json) { Mute _$MuteFromJson(Map<String, dynamic> json) {
return Mute( return Mute(
user: json['user'] == null user: User.fromJson(json['user'] as Map<String, dynamic>),
? null channel: ChannelModel.fromJson(json['channel'] as Map<String, dynamic>),
: User.fromJson(json['user'] as Map<String, dynamic>), createdAt: DateTime.parse(json['created_at'] as String),
channel: json['channel'] == null updatedAt: DateTime.parse(json['updated_at'] as String),
? null
: ChannelModel.fromJson(json['channel'] as Map<String, dynamic>),
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),
); );
} }
@@ -84,5 +84,6 @@ class OwnUser extends User {
/// Serialize to json /// Serialize to json
@override @override
Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot( Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot(
_$OwnUserToJson(this), topLevelFields); _$OwnUserToJson(this),
);
} }
@@ -11,7 +11,7 @@ class Reaction {
Reaction({ Reaction({
this.messageId, this.messageId,
DateTime? createdAt, DateTime? createdAt,
this.type = '', required this.type,
required this.user, required this.user,
String? userId, String? userId,
this.score = 0, this.score = 0,
@@ -64,7 +64,8 @@ class Reaction {
/// Serialize to json /// Serialize to json
Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot( Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot(
_$ReactionToJson(this), topLevelFields); _$ReactionToJson(this),
);
/// Creates a copy of [Reaction] with specified attributes overridden. /// Creates a copy of [Reaction] with specified attributes overridden.
Reaction copyWith({ Reaction copyWith({
@@ -10,7 +10,7 @@ class Read {
Read({ Read({
required this.lastRead, required this.lastRead,
required this.user, required this.user,
required this.unreadMessages, this.unreadMessages = 0,
}); });
/// Create a new instance from a json /// Create a new instance from a json
@@ -10,7 +10,7 @@ class Serialization {
static const Function readOnly = readonly; static const Function readOnly = readonly;
/// List of users to list of userIds /// List of users to list of userIds
static List<String?>? userIds(List<User>? users) => static List<String>? userIds(List<User>? users) =>
users?.map((u) => u.id).toList(); users?.map((u) => u.id).toList();
/// Takes unknown json keys and puts them in the `extra_data` key /// Takes unknown json keys and puts them in the `extra_data` key
@@ -36,7 +36,6 @@ class Serialization {
/// the json map /// the json map
static Map<String, dynamic> moveFromExtraDataToRoot( static Map<String, dynamic> moveFromExtraDataToRoot(
Map<String, dynamic> json, Map<String, dynamic> json,
List<String> topLevelFields,
) { ) {
final jsonClone = Map<String, dynamic>.from(json); final jsonClone = Map<String, dynamic>.from(json);
return jsonClone return jsonClone
@@ -105,8 +105,9 @@ class User {
other is User && runtimeType == other.runtimeType && id == other.id; other is User && runtimeType == other.runtimeType && id == other.id;
/// Serialize to json /// Serialize to json
Map<String, dynamic> toJson() => Map<String, dynamic> toJson() => Serialization.moveFromExtraDataToRoot(
Serialization.moveFromExtraDataToRoot(_$UserToJson(this), topLevelFields); _$UserToJson(this),
);
/// Creates a copy of [User] with specified attributes overridden. /// Creates a copy of [User] with specified attributes overridden.
User copyWith({ User copyWith({
@@ -1,3 +1,5 @@
import 'dart:convert';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:dio/native_imp.dart'; import 'package:dio/native_imp.dart';
import 'package:mocktail/mocktail.dart'; import 'package:mocktail/mocktail.dart';
@@ -6,11 +8,10 @@ import 'package:stream_chat/src/client.dart';
import 'package:stream_chat/src/event_type.dart'; import 'package:stream_chat/src/event_type.dart';
import 'package:stream_chat/src/models/event.dart'; import 'package:stream_chat/src/models/event.dart';
import 'package:stream_chat/src/models/message.dart'; import 'package:stream_chat/src/models/message.dart';
import 'package:stream_chat/src/models/reaction.dart';
import 'package:stream_chat/src/models/own_user.dart'; import 'package:stream_chat/src/models/own_user.dart';
import 'package:test/test.dart'; import 'package:stream_chat/src/models/reaction.dart';
import 'package:stream_chat/stream_chat.dart'; import 'package:stream_chat/stream_chat.dart';
import 'package:test/test.dart';
class MockDio extends Mock implements DioForNative {} class MockDio extends Mock implements DioForNative {}
@@ -76,7 +77,7 @@ void main() {
any(), any(),
data: any(named: 'data'), data: any(named: 'data'),
)).thenAnswer((_) async => Response( )).thenAnswer((_) async => Response(
data: '{}', data: jsonEncode(ChannelState()),
statusCode: 200, statusCode: 200,
requestOptions: FakeRequestOptions(), requestOptions: FakeRequestOptions(),
)); ));
@@ -9,9 +9,9 @@ import 'package:mocktail/mocktail.dart';
import 'package:stream_chat/src/api/requests.dart'; import 'package:stream_chat/src/api/requests.dart';
import 'package:stream_chat/src/client.dart'; import 'package:stream_chat/src/client.dart';
import 'package:stream_chat/src/exceptions.dart'; import 'package:stream_chat/src/exceptions.dart';
import 'package:stream_chat/src/models/channel_model.dart';
import 'package:stream_chat/src/models/message.dart'; import 'package:stream_chat/src/models/message.dart';
import 'package:stream_chat/src/models/user.dart'; import 'package:stream_chat/src/models/user.dart';
import 'package:stream_chat/src/models/channel_model.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
class MockDio extends Mock implements DioForNative {} class MockDio extends Mock implements DioForNative {}
@@ -748,7 +748,7 @@ void main() {
), ),
).thenAnswer( ).thenAnswer(
(_) async => Response( (_) async => Response(
data: '{}', data: jsonEncode({'message': message}),
statusCode: 200, statusCode: 200,
requestOptions: FakeRequestOptions(), requestOptions: FakeRequestOptions(),
), ),
@@ -793,7 +793,7 @@ void main() {
when(() => mockDio.get<String>('/messages/$messageId')).thenAnswer( when(() => mockDio.get<String>('/messages/$messageId')).thenAnswer(
(_) async => Response( (_) async => Response(
data: '{}', data: jsonEncode({'message': Message(id: messageId)}),
statusCode: 200, statusCode: 200,
requestOptions: FakeRequestOptions(), requestOptions: FakeRequestOptions(),
), ),
@@ -1115,7 +1115,7 @@ void main() {
), ),
).thenAnswer( ).thenAnswer(
(_) async => Response( (_) async => Response(
data: '{}', data: jsonEncode({'message': message}),
statusCode: 200, statusCode: 200,
requestOptions: FakeRequestOptions(), requestOptions: FakeRequestOptions(),
), ),
@@ -1137,7 +1137,7 @@ void main() {
), ),
).thenAnswer( ).thenAnswer(
(_) async => Response( (_) async => Response(
data: '{}', data: jsonEncode({'message': message}),
statusCode: 200, statusCode: 200,
requestOptions: FakeRequestOptions(), requestOptions: FakeRequestOptions(),
), ),
@@ -1177,7 +1177,7 @@ void main() {
), ),
).thenAnswer( ).thenAnswer(
(_) async => Response( (_) async => Response(
data: '{}', data: jsonEncode({'channel': ChannelModel(cid: 'messaging:test')}),
statusCode: 200, statusCode: 200,
requestOptions: FakeRequestOptions(), requestOptions: FakeRequestOptions(),
), ),
@@ -1,7 +1,7 @@
import 'dart:convert'; import 'dart:convert';
import 'package:stream_chat/src/models/attachment.dart';
import 'package:stream_chat/src/models/action.dart';
import 'package:stream_chat/src/models/action.dart';
import 'package:stream_chat/src/models/attachment.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
void main() { void main() {
@@ -50,7 +50,7 @@ void main() {
'https://media0.giphy.com/media/3o7TKnCdBx5cMg0qti/giphy.gif', 'https://media0.giphy.com/media/3o7TKnCdBx5cMg0qti/giphy.gif',
); );
expect(attachment.actions, hasLength(3)); expect(attachment.actions, hasLength(3));
expect(attachment.actions![0], isA<Action>()); expect(attachment.actions[0], isA<Action>());
}); });
test('should serialize to json correctly', () { test('should serialize to json correctly', () {
@@ -67,7 +67,8 @@ void main() {
'type': 'image', 'type': 'image',
'title': 'soo', 'title': 'soo',
'title_link': 'title_link':
'https://giphy.com/gifs/nrkp3-dance-happy-3o7TKnCdBx5cMg0qti' 'https://giphy.com/gifs/nrkp3-dance-happy-3o7TKnCdBx5cMg0qti',
'actions': [],
}, },
); );
}); });
@@ -1,12 +1,12 @@
import 'dart:convert'; import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/models/channel_config.dart'; import 'package:stream_chat/src/models/channel_config.dart';
import 'package:stream_chat/src/models/channel_state.dart'; import 'package:stream_chat/src/models/channel_state.dart';
import 'package:stream_chat/src/models/command.dart'; import 'package:stream_chat/src/models/command.dart';
import 'package:stream_chat/src/models/message.dart'; import 'package:stream_chat/src/models/message.dart';
import 'package:stream_chat/src/models/user.dart'; import 'package:stream_chat/src/models/user.dart';
import 'package:stream_chat/stream_chat.dart'; import 'package:stream_chat/stream_chat.dart';
import 'package:test/test.dart';
void main() { void main() {
group('src/models/channel_state', () { group('src/models/channel_state', () {
@@ -852,7 +852,7 @@ void main() {
expect(channelState.channel?.config, isA<ChannelConfig>()); expect(channelState.channel?.config, isA<ChannelConfig>());
expect(channelState.channel?.config, isNotNull); expect(channelState.channel?.config, isNotNull);
expect(channelState.channel?.config.commands, hasLength(1)); expect(channelState.channel?.config.commands, hasLength(1));
expect(channelState.channel?.config.commands![0], isA<Command>()); expect(channelState.channel?.config.commands[0], isA<Command>());
expect(channelState.channel?.lastMessageAt, expect(channelState.channel?.lastMessageAt,
DateTime.parse('2020-01-30T13:43:41.062362Z')); DateTime.parse('2020-01-30T13:43:41.062362Z'));
expect(channelState.channel?.createdAt, expect(channelState.channel?.createdAt,
@@ -902,7 +902,7 @@ void main() {
"show_in_channel": null, "show_in_channel": null,
"mentioned_users": [], "mentioned_users": [],
"status": "SENT", "status": "SENT",
"skip_push": null, "skip_push": false,
"silent": false, "silent": false,
"pinned": false, "pinned": false,
"pinned_at": null, "pinned_at": null,
@@ -919,7 +919,7 @@ void main() {
"show_in_channel": null, "show_in_channel": null,
"mentioned_users": [], "mentioned_users": [],
"status": "SENT", "status": "SENT",
"skip_push": null, "skip_push": false,
"silent": false, "silent": false,
"pinned": false, "pinned": false,
"pinned_at": null, "pinned_at": null,
@@ -929,7 +929,7 @@ void main() {
{ {
"id": "dry-meadow-0-53e6299f-9b97-4a9c-a27e-7e2dde49b7e0", "id": "dry-meadow-0-53e6299f-9b97-4a9c-a27e-7e2dde49b7e0",
"text": "test message", "text": "test message",
"skip_push": null, "skip_push": false,
"attachments": [], "attachments": [],
"parent_id": null, "parent_id": null,
"quoted_message": null, "quoted_message": null,
@@ -952,7 +952,7 @@ void main() {
"quoted_message_id": null, "quoted_message_id": null,
"show_in_channel": null, "show_in_channel": null,
"mentioned_users": [], "mentioned_users": [],
"skip_push": null, "skip_push": false,
"status": "SENT", "status": "SENT",
"silent": false, "silent": false,
"pinned": false, "pinned": false,
@@ -964,7 +964,7 @@ void main() {
"id": "dry-meadow-0-64d7970f-ede8-4b31-9738-1bc1756d2bfe", "id": "dry-meadow-0-64d7970f-ede8-4b31-9738-1bc1756d2bfe",
"text": "test", "text": "test",
"attachments": [], "attachments": [],
"skip_push": null, "skip_push": false,
"parent_id": null, "parent_id": null,
"quoted_message": null, "quoted_message": null,
"quoted_message_id": null, "quoted_message_id": null,
@@ -982,7 +982,7 @@ void main() {
"text": "hi", "text": "hi",
"attachments": [], "attachments": [],
"parent_id": null, "parent_id": null,
"skip_push": null, "skip_push": false,
"quoted_message": null, "quoted_message": null,
"quoted_message_id": null, "quoted_message_id": null,
"show_in_channel": null, "show_in_channel": null,
@@ -1000,7 +1000,7 @@ void main() {
"attachments": [], "attachments": [],
"parent_id": null, "parent_id": null,
"quoted_message": null, "quoted_message": null,
"skip_push": null, "skip_push": false,
"quoted_message_id": null, "quoted_message_id": null,
"show_in_channel": null, "show_in_channel": null,
"mentioned_users": [], "mentioned_users": [],
@@ -1023,7 +1023,7 @@ void main() {
"status": "SENT", "status": "SENT",
"silent": false, "silent": false,
"pinned": false, "pinned": false,
"skip_push": null, "skip_push": false,
"pinned_at": null, "pinned_at": null,
"pin_expires": null, "pin_expires": null,
"pinned_by": null "pinned_by": null
@@ -1041,7 +1041,7 @@ void main() {
"silent": false, "silent": false,
"pinned": false, "pinned": false,
"pinned_at": null, "pinned_at": null,
"skip_push": null, "skip_push": false,
"pin_expires": null, "pin_expires": null,
"pinned_by": null "pinned_by": null
}, },
@@ -1053,7 +1053,7 @@ void main() {
"quoted_message": null, "quoted_message": null,
"quoted_message_id": null, "quoted_message_id": null,
"show_in_channel": null, "show_in_channel": null,
"skip_push": null, "skip_push": false,
"mentioned_users": [], "mentioned_users": [],
"status": "SENT", "status": "SENT",
"silent": false, "silent": false,
@@ -1071,7 +1071,7 @@ void main() {
"quoted_message_id": null, "quoted_message_id": null,
"show_in_channel": null, "show_in_channel": null,
"mentioned_users": [], "mentioned_users": [],
"skip_push": null, "skip_push": false,
"status": "SENT", "status": "SENT",
"silent": false, "silent": false,
"pinned": false, "pinned": false,
@@ -1090,7 +1090,7 @@ void main() {
"mentioned_users": [], "mentioned_users": [],
"status": "SENT", "status": "SENT",
"silent": false, "silent": false,
"skip_push": null, "skip_push": false,
"pinned": false, "pinned": false,
"pinned_at": null, "pinned_at": null,
"pin_expires": null, "pin_expires": null,
@@ -1100,7 +1100,7 @@ void main() {
"id": "icy-recipe-7-935c396e-ddf8-4a9a-951c-0a12fa5bf055", "id": "icy-recipe-7-935c396e-ddf8-4a9a-951c-0a12fa5bf055",
"text": "what are you doing?", "text": "what are you doing?",
"attachments": [], "attachments": [],
"skip_push": null, "skip_push": false,
"parent_id": null, "parent_id": null,
"quoted_message": null, "quoted_message": null,
"quoted_message_id": null, "quoted_message_id": null,
@@ -1118,7 +1118,7 @@ void main() {
"text": "👍", "text": "👍",
"attachments": [], "attachments": [],
"parent_id": null, "parent_id": null,
"skip_push": null, "skip_push": false,
"quoted_message": null, "quoted_message": null,
"quoted_message_id": null, "quoted_message_id": null,
"show_in_channel": null, "show_in_channel": null,
@@ -1134,7 +1134,7 @@ void main() {
"id": "snowy-credit-3-3e0c1a0d-d22f-42ee-b2a1-f9f49477bf21", "id": "snowy-credit-3-3e0c1a0d-d22f-42ee-b2a1-f9f49477bf21",
"text": "sdasas", "text": "sdasas",
"attachments": [], "attachments": [],
"skip_push": null, "skip_push": false,
"parent_id": null, "parent_id": null,
"quoted_message": null, "quoted_message": null,
"quoted_message_id": null, "quoted_message_id": null,
@@ -1155,7 +1155,7 @@ void main() {
"quoted_message": null, "quoted_message": null,
"quoted_message_id": null, "quoted_message_id": null,
"show_in_channel": null, "show_in_channel": null,
"skip_push": null, "skip_push": false,
"mentioned_users": [], "mentioned_users": [],
"status": "SENT", "status": "SENT",
"silent": false, "silent": false,
@@ -1168,7 +1168,7 @@ void main() {
"id": "snowy-credit-3-cfaf0b46-1daa-49c5-947c-b16d6697487d", "id": "snowy-credit-3-cfaf0b46-1daa-49c5-947c-b16d6697487d",
"text": "nhisagdhsadz", "text": "nhisagdhsadz",
"attachments": [], "attachments": [],
"skip_push": null, "skip_push": false,
"parent_id": null, "parent_id": null,
"quoted_message": null, "quoted_message": null,
"quoted_message_id": null, "quoted_message_id": null,
@@ -1187,7 +1187,7 @@ void main() {
"attachments": [], "attachments": [],
"parent_id": null, "parent_id": null,
"quoted_message": null, "quoted_message": null,
"skip_push": null, "skip_push": false,
"quoted_message_id": null, "quoted_message_id": null,
"show_in_channel": null, "show_in_channel": null,
"mentioned_users": [], "mentioned_users": [],
@@ -1204,7 +1204,7 @@ void main() {
"attachments": [], "attachments": [],
"parent_id": null, "parent_id": null,
"quoted_message": null, "quoted_message": null,
"skip_push": null, "skip_push": false,
"quoted_message_id": null, "quoted_message_id": null,
"show_in_channel": null, "show_in_channel": null,
"mentioned_users": [], "mentioned_users": [],
@@ -1212,7 +1212,7 @@ void main() {
"silent": false, "silent": false,
"pinned": false, "pinned": false,
"pinned_at": null, "pinned_at": null,
"skip_push": null, "skip_push": false,
"pin_expires": null, "pin_expires": null,
"pinned_by": null "pinned_by": null
}, },
@@ -1229,7 +1229,7 @@ void main() {
"silent": false, "silent": false,
"pinned": false, "pinned": false,
"pinned_at": null, "pinned_at": null,
"skip_push": null, "skip_push": false,
"pin_expires": null, "pin_expires": null,
"pinned_by": null "pinned_by": null
}, },
@@ -1246,7 +1246,7 @@ void main() {
"silent": false, "silent": false,
"pinned": false, "pinned": false,
"pinned_at": null, "pinned_at": null,
"skip_push": null, "skip_push": false,
"pin_expires": null, "pin_expires": null,
"pinned_by": null "pinned_by": null
}, },
@@ -1263,7 +1263,7 @@ void main() {
"silent": false, "silent": false,
"pinned": false, "pinned": false,
"pinned_at": null, "pinned_at": null,
"skip_push": null, "skip_push": false,
"pin_expires": null, "pin_expires": null,
"pinned_by": null "pinned_by": null
}, },
@@ -1280,7 +1280,7 @@ void main() {
"silent": false, "silent": false,
"pinned": false, "pinned": false,
"pinned_at": null, "pinned_at": null,
"skip_push": null, "skip_push": false,
"pin_expires": null, "pin_expires": null,
"pinned_by": null "pinned_by": null
}, },
@@ -1297,7 +1297,7 @@ void main() {
"silent": false, "silent": false,
"pinned": false, "pinned": false,
"pinned_at": null, "pinned_at": null,
"skip_push": null, "skip_push": false,
"pin_expires": null, "pin_expires": null,
"pinned_by": null "pinned_by": null
}, },
@@ -1314,7 +1314,7 @@ void main() {
"silent": false, "silent": false,
"pinned": false, "pinned": false,
"pinned_at": null, "pinned_at": null,
"skip_push": null, "skip_push": false,
"pin_expires": null, "pin_expires": null,
"pinned_by": null "pinned_by": null
} }
@@ -1,7 +1,7 @@
import 'dart:convert'; import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/models/channel_model.dart'; import 'package:stream_chat/src/models/channel_model.dart';
import 'package:test/test.dart';
void main() { void main() {
group('src/models/channel', () { group('src/models/channel', () {
@@ -9,7 +9,7 @@ void main() {
{ {
"id": "test", "id": "test",
"type": "livestream", "type": "livestream",
"cid": "test:livestream", "cid": "livestream:test",
"cats": true, "cats": true,
"fruit": ["bananas", "apples"] "fruit": ["bananas", "apples"]
} }
@@ -19,7 +19,7 @@ void main() {
final channel = ChannelModel.fromJson(json.decode(jsonExample)); final channel = ChannelModel.fromJson(json.decode(jsonExample));
expect(channel.id, equals('test')); expect(channel.id, equals('test'));
expect(channel.type, equals('livestream')); expect(channel.type, equals('livestream'));
expect(channel.cid, equals('test:livestream')); expect(channel.cid, equals('livestream:test'));
expect(channel.extraData!['cats'], equals(true)); expect(channel.extraData!['cats'], equals(true));
expect(channel.extraData!['fruit'], equals(['bananas', 'apples'])); expect(channel.extraData!['fruit'], equals(['bananas', 'apples']));
}); });
@@ -1,10 +1,10 @@
import 'dart:convert'; import 'dart:convert';
import 'package:test/test.dart';
import 'package:stream_chat/src/models/attachment.dart'; import 'package:stream_chat/src/models/attachment.dart';
import 'package:stream_chat/src/models/message.dart'; import 'package:stream_chat/src/models/message.dart';
import 'package:stream_chat/src/models/reaction.dart'; import 'package:stream_chat/src/models/reaction.dart';
import 'package:stream_chat/src/models/user.dart'; import 'package:stream_chat/src/models/user.dart';
import 'package:test/test.dart';
void main() { void main() {
group('src/models/message', () { group('src/models/message', () {
@@ -134,7 +134,7 @@ void main() {
"id": "4637f7e4-a06b-42db-ba5a-8d8270dd926f", "id": "4637f7e4-a06b-42db-ba5a-8d8270dd926f",
"text": "https://giphy.com/gifs/the-lion-king-live-action-5zvN79uTGfLMOVfQaA", "text": "https://giphy.com/gifs/the-lion-king-live-action-5zvN79uTGfLMOVfQaA",
"silent": false, "silent": false,
"skip_push": null, "skip_push": false,
"attachments": [ "attachments": [
{ {
"type": "video", "type": "video",
@@ -145,10 +145,11 @@ void main() {
"og_scrape_url": "https://giphy.com/gifs/the-lion-king-live-action-5zvN79uTGfLMOVfQaA", "og_scrape_url": "https://giphy.com/gifs/the-lion-king-live-action-5zvN79uTGfLMOVfQaA",
"image_url": "https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.gif", "image_url": "https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.gif",
"author_name": "GIPHY", "author_name": "GIPHY",
"asset_url": "https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.mp4" "asset_url": "https://media.giphy.com/media/5zvN79uTGfLMOVfQaA/giphy.mp4",
"actions": []
} }
], ],
"mentioned_users": null, "mentioned_users": [],
"parent_id": "parentId", "parent_id": "parentId",
"quoted_message": null, "quoted_message": null,
"quoted_message_id": null, "quoted_message_id": null,
@@ -90,6 +90,7 @@ void main() {
Reaction( Reaction(
messageId: 'test', messageId: 'test',
user: User(id: 'testid'), user: User(id: 'testid'),
type: 'test',
), ),
], ],
); );