-
Notifications
You must be signed in to change notification settings - Fork 350
/
Copy pathchannel.dart
3089 lines (2665 loc) · 91.2 KB
/
channel.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:async';
import 'dart:math';
import 'package:collection/collection.dart';
import 'package:rxdart/rxdart.dart';
import 'package:stream_chat/src/client/retry_queue.dart';
import 'package:stream_chat/src/core/util/utils.dart';
import 'package:stream_chat/stream_chat.dart';
import 'package:synchronized/synchronized.dart';
/// The maximum time the incoming [Event.typingStart] event is valid before a
/// [Event.typingStop] event is emitted automatically.
const incomingTypingStartEventTimeout = 7;
/// Class that manages a specific channel.
///
/// #### Channel name
///
/// {@template name}
/// If an optional [name] argument is provided in the constructor then it
/// will be set on [extraData] with a key of 'name'.
///
/// ```dart
/// final channel = Channel(client, type, id, name: 'Channel name');
/// print(channel.name == channel.extraData['name']); // true
/// ```
///
/// Before the channel is initialized the name can be set directly:
/// ```dart
/// channel.name = 'New channel name';
/// ```
///
/// To update the name after the channel has been initialized, call:
/// ```dart
/// channel.updateName('Updated channel name');
/// ```
///
/// This will do a partial update to update the name.
/// {@endtemplate}
///
/// #### Channel image
///
/// {@template image}
/// If an optional [image] argument is provided in the constructor then it
/// will be set on [extraData] with a key of 'image'.
///
/// ```dart
/// final channel = Channel(client, type, id, image: 'https://getstream.io/image.png');
/// print(channel.image == channel.extraData['image']); // true
/// ```
///
/// Before the channel is initialized the image can be set directly:
/// ```dart
/// channel.image = 'https://getstream.io/new-image';
/// ```
///
/// To update the image after the channel has been initialized, call:
/// ```dart
/// channel.updateImage('https://getstream.io/new-image');
/// ```
///
/// This will do a partial update to update the image.
/// {@endtemplate}
class Channel {
/// Class that manages a specific channel.
///
/// Optional [extraData] and [image] properties can be provided. The [image]
/// is exposed to easily set a key of 'image' on [extraData].
Channel(
this._client,
this._type,
this._id, {
String? name,
String? image,
Map<String, Object?>? extraData,
}) : _cid = _id != null ? '$_type:$_id' : null,
_extraData = {
...?extraData,
if (name != null) 'name': name,
if (image != null) 'image': image,
} {
_client.logger.info('New Channel instance created, not yet initialized');
}
/// Create a channel client instance from a [ChannelState] object.
Channel.fromState(this._client, ChannelState channelState)
: assert(
channelState.channel != null,
'No channel found inside channel state',
),
_id = channelState.channel!.id,
_type = channelState.channel!.type,
_cid = channelState.channel!.cid,
_extraData = channelState.channel!.extraData {
state = ChannelClientState(this, channelState);
_initializedCompleter.complete(true);
_client.logger.info('New Channel instance initialized');
}
/// This client state
ChannelClientState? state;
/// The channel type
final String _type;
String? _id;
String? _cid;
final Map<String, Object?> _extraData;
/// Shortcut to set channel name.
///
/// {@macro name}
set name(String? name) {
if (_initializedCompleter.isCompleted) {
throw StateError(
'Once the channel is initialized you should use `channel.updateName` '
'to update the channel name',
);
}
_extraData.addAll({'name': name});
}
/// Shortcut to set channel image.
///
/// {@macro image}
set image(String? image) {
if (_initializedCompleter.isCompleted) {
throw StateError(
'Once the channel is initialized you should use `channel.updateImage` '
'to update the channel image',
);
}
_extraData.addAll({'image': image});
}
set extraData(Map<String, Object?> extraData) {
if (_initializedCompleter.isCompleted) {
throw StateError(
'Once the channel is initialized you should use `channel.update` '
'to update channel data',
);
}
_extraData.addAll(extraData);
}
/// Returns true if the channel is muted.
bool get isMuted =>
_client.state.currentUser?.channelMutes
.any((element) => element.channel.cid == cid) ==
true;
/// Returns true if the channel is muted, as a stream.
Stream<bool> get isMutedStream => _client.state.currentUserStream
.map((event) =>
event?.channelMutes.any((element) => element.channel.cid == cid) ==
true)
.distinct();
/// True if the channel is a group.
bool get isGroup => memberCount != 2;
/// True if the channel is distinct.
bool get isDistinct => id?.startsWith('!members') == true;
/// Channel configuration.
ChannelConfig? get config {
_checkInitialized();
return state!._channelState.channel?.config;
}
/// Channel configuration as a stream.
Stream<ChannelConfig?> get configStream {
_checkInitialized();
return state!.channelStateStream.map((cs) => cs.channel?.config);
}
/// Relationship of the current user to this channel.
Member? get membership {
_checkInitialized();
return state!._channelState.membership;
}
/// Relationship of the current user to this channel as a stream.
Stream<Member?> get membershipStream {
_checkInitialized();
return state!.channelStateStream.map((cs) => cs.membership);
}
/// Channel user creator.
User? get createdBy {
_checkInitialized();
return state!._channelState.channel?.createdBy;
}
/// Channel user creator as a stream.
Stream<User?> get createdByStream {
_checkInitialized();
return state!.channelStateStream.map((cs) => cs.channel?.createdBy);
}
/// Channel frozen status.
bool get frozen {
_checkInitialized();
return state!._channelState.channel?.frozen == true;
}
/// Channel frozen status as a stream.
Stream<bool> get frozenStream {
_checkInitialized();
return state!.channelStateStream.map((cs) => cs.channel?.frozen == true);
}
/// Channel disabled status.
bool get disabled {
_checkInitialized();
return state!._channelState.channel?.disabled == true;
}
/// Channel disabled status as a stream.
Stream<bool> get disabledStream {
_checkInitialized();
return state!.channelStateStream.map((cs) => cs.channel?.disabled == true);
}
/// Channel hidden status.
bool get hidden {
_checkInitialized();
return state!._channelState.channel?.hidden == true;
}
/// Channel hidden status as a stream.
Stream<bool> get hiddenStream {
_checkInitialized();
return state!.channelStateStream.map((cs) => cs.channel?.hidden == true);
}
/// The last date at which the channel got truncated.
DateTime? get truncatedAt {
_checkInitialized();
return state!._channelState.channel?.truncatedAt;
}
/// The last date at which the channel got truncated as a stream.
Stream<DateTime?> get truncatedAtStream {
_checkInitialized();
return state!.channelStateStream.map((cs) => cs.channel?.truncatedAt);
}
/// Cooldown count
int get cooldown {
_checkInitialized();
return state!._channelState.channel?.cooldown ?? 0;
}
/// Cooldown count as a stream
Stream<int> get cooldownStream {
_checkInitialized();
return state!.channelStateStream.map((cs) => cs.channel?.cooldown ?? 0);
}
/// Stores time at which cooldown was started
DateTime? cooldownStartedAt;
/// Channel creation date.
DateTime? get createdAt {
_checkInitialized();
return state!._channelState.channel?.createdAt;
}
/// Channel creation date as a stream.
Stream<DateTime?> get createdAtStream {
_checkInitialized();
return state!.channelStateStream.map((cs) => cs.channel?.createdAt);
}
/// Channel last message date.
DateTime? get lastMessageAt {
_checkInitialized();
return state!._channelState.channel?.lastMessageAt;
}
/// Channel last message date as a stream.
Stream<DateTime?> get lastMessageAtStream {
_checkInitialized();
return state!.channelStateStream.map((cs) => cs.channel?.lastMessageAt);
}
/// Channel updated date.
DateTime? get updatedAt {
_checkInitialized();
return state!._channelState.channel?.updatedAt;
}
/// Channel updated date as a stream.
Stream<DateTime?> get updatedAtStream {
_checkInitialized();
return state!.channelStateStream.map((cs) => cs.channel?.updatedAt);
}
/// Channel deletion date.
DateTime? get deletedAt {
_checkInitialized();
return state!._channelState.channel?.deletedAt;
}
/// Channel deletion date as a stream.
Stream<DateTime?> get deletedAtStream {
_checkInitialized();
return state!.channelStateStream.map((cs) => cs.channel?.deletedAt);
}
/// Channel member count.
int? get memberCount {
_checkInitialized();
return state!._channelState.channel?.memberCount;
}
/// Channel member count as a stream.
Stream<int?> get memberCountStream {
_checkInitialized();
return state!.channelStateStream.map((cs) => cs.channel?.memberCount);
}
/// Channel id.
String? get id => state?._channelState.channel?.id ?? _id;
/// Channel type.
String get type => state?._channelState.channel?.type ?? _type;
/// Channel cid.
String? get cid => state?._channelState.channel?.cid ?? _cid;
/// Channel team.
String? get team {
_checkInitialized();
return state!._channelState.channel?.team;
}
/// Channel extra data.
Map<String, Object?> get extraData {
var data = state?._channelState.channel?.extraData;
if (data == null || data.isEmpty) {
data = _extraData;
}
return data;
}
/// List of user permissions on this channel
List<String> get ownCapabilities =>
state?._channelState.channel?.ownCapabilities ?? [];
/// List of user permissions on this channel
Stream<List<String>> get ownCapabilitiesStream {
_checkInitialized();
return state!.channelStateStream
.map((cs) => cs.channel?.ownCapabilities ?? [])
.distinct();
}
/// Channel extra data as a stream.
Stream<Map<String, Object?>> get extraDataStream {
_checkInitialized();
return state!.channelStateStream.map(
(cs) => cs.channel?.extraData ?? _extraData,
);
}
/// Shortcut to get channel name.
///
/// {@macro name}
String? get name => extraData['name'] as String?;
/// Channel [name] as a stream.
///
/// The channel needs to be initialized.
///
/// {@macro name}
Stream<String?> get nameStream {
_checkInitialized();
return extraDataStream.map((it) => it['name'] as String?);
}
/// Shortcut to get channel image.
///
/// {@macro image}
String? get image => extraData['image'] as String?;
/// Channel [image] as a stream.
///
/// The channel needs to be initialized.
///
/// {@macro image}
Stream<String?> get imageStream {
_checkInitialized();
return extraDataStream.map((it) => it['image'] as String?);
}
/// The main Stream chat client.
StreamChatClient get client => _client;
final StreamChatClient _client;
final Completer<bool> _initializedCompleter = Completer();
/// True if this is initialized.
///
/// Call [watch] to initialize the client or instantiate it using
/// [Channel.fromState].
Future<bool> get initialized => _initializedCompleter.future;
final _cancelableAttachmentUploadRequest = <String, CancelToken>{};
final _messageAttachmentsUploadCompleter = <String, Completer<Message>>{};
/// Cancels [attachmentId] upload request. Throws exception if the request
/// hasn't even started yet, Already completed or Already cancelled.
///
/// Optionally, provide a [reason] for the cancellation.
void cancelAttachmentUpload(
String attachmentId, {
String? reason,
}) {
final cancelToken = _cancelableAttachmentUploadRequest[attachmentId];
if (cancelToken == null) {
throw const StreamChatError(
"Upload request for this Attachment hasn't started yet or maybe "
'Already completed',
);
}
if (cancelToken.isCancelled) {
throw const StreamChatError('Upload request already cancelled');
}
cancelToken.cancel(reason);
}
/// Retries the failed [attachmentId] upload request.
Future<void> retryAttachmentUpload(String messageId, String attachmentId) =>
_uploadAttachments(messageId, [attachmentId]);
Future<void> _uploadAttachments(
String messageId,
Iterable<String> attachmentIds,
) {
var message = [
...state!.messages,
...state!.threads.values.expand((messages) => messages),
].firstWhereOrNull((it) => it.id == messageId);
if (message == null) {
throw const StreamChatError('Error, Message not found');
}
final attachments = message.attachments.where((it) {
if (it.uploadState.isSuccess) return false;
return attachmentIds.contains(it.id);
});
if (attachments.isEmpty) {
client.logger.info('No attachments available to upload');
if (message.attachments.every((it) => it.uploadState.isSuccess)) {
_messageAttachmentsUploadCompleter.remove(messageId)?.complete(message);
}
return Future.value();
}
client.logger.info('Found ${attachments.length} attachments');
void updateAttachment(Attachment attachment, {bool remove = false}) {
final index = message!.attachments.indexWhere(
(it) => it.id == attachment.id,
);
if (index != -1) {
// update or remove attachment from message.
final List<Attachment> newAttachments;
if (remove) {
newAttachments = [...message!.attachments]..removeAt(index);
} else {
newAttachments = [...message!.attachments]..[index] = attachment;
}
final updatedMessage = message!.copyWith(attachments: newAttachments);
state?.updateMessage(updatedMessage);
// updating original message for next iteration
message = message!.merge(updatedMessage);
}
}
return Future.wait(attachments.map((it) {
client.logger.info('Uploading ${it.id} attachment...');
final throttledUpdateAttachment = updateAttachment.throttled(
const Duration(milliseconds: 500),
);
void onSendProgress(int sent, int total) {
throttledUpdateAttachment([
it.copyWith(
uploadState: UploadState.inProgress(uploaded: sent, total: total),
),
]);
}
final isImage = it.type == AttachmentType.image;
final cancelToken = CancelToken();
Future<SendAttachmentResponse> future;
if (isImage) {
future = sendImage(
it.file!,
onSendProgress: onSendProgress,
cancelToken: cancelToken,
extraData: it.extraData,
);
} else {
future = sendFile(
it.file!,
onSendProgress: onSendProgress,
cancelToken: cancelToken,
extraData: it.extraData,
);
}
_cancelableAttachmentUploadRequest[it.id] = cancelToken;
return future.then((response) {
client.logger.info('Attachment ${it.id} uploaded successfully...');
// If the response is SendFileResponse, then we might also be getting
// thumbUrl in case of video. So we need to update the attachment with
// both the assetUrl and thumbUrl.
if (response is SendFileResponse) {
updateAttachment(
it.copyWith(
assetUrl: response.file,
thumbUrl: response.thumbUrl,
uploadState: const UploadState.success(),
),
);
} else {
updateAttachment(
it.copyWith(
imageUrl: response.file,
uploadState: const UploadState.success(),
),
);
}
}).catchError((e, stk) {
if (e is StreamChatNetworkError && e.isRequestCancelledError) {
client.logger.info('Attachment ${it.id} upload cancelled');
// remove attachment from message if cancelled.
updateAttachment(it, remove: true);
return;
}
client.logger.severe('error uploading the attachment', e, stk);
updateAttachment(
it.copyWith(uploadState: UploadState.failed(error: e.toString())),
);
}).whenComplete(() {
throttledUpdateAttachment.cancel();
_cancelableAttachmentUploadRequest.remove(it.id);
});
})).whenComplete(() {
if (message!.attachments.every((it) => it.uploadState.isSuccess)) {
_messageAttachmentsUploadCompleter.remove(messageId)?.complete(message);
}
});
}
final _sendMessageLock = Lock();
/// Send a [message] to this channel.
///
/// If [skipPush] is true the message will not send a push notification.
///
/// Waits for a [_messageAttachmentsUploadCompleter] to complete
/// before actually sending the message.
Future<SendMessageResponse> sendMessage(
Message message, {
bool skipPush = false,
bool skipEnrichUrl = false,
}) async {
_checkInitialized();
// Cancelling previous completer in case it's called again in the process
// Eg. Updating the message while the previous call is in progress.
_messageAttachmentsUploadCompleter
.remove(message.id)
?.completeError(const StreamChatError('Message cancelled'));
final quotedMessage = state!.messages.firstWhereOrNull(
(m) => m.id == message.quotedMessageId,
);
// ignore: parameter_assignments
message = message.copyWith(
localCreatedAt: DateTime.now(),
user: _client.state.currentUser,
quotedMessage: quotedMessage,
state: MessageState.sending,
attachments: message.attachments.map(
(it) {
if (it.uploadState.isSuccess) return it;
return it.copyWith(uploadState: const UploadState.preparing());
},
).toList(),
);
state!.updateMessage(message);
try {
if (message.attachments.any((it) => !it.uploadState.isSuccess)) {
final attachmentsUploadCompleter = Completer<Message>();
_messageAttachmentsUploadCompleter[message.id] =
attachmentsUploadCompleter;
_uploadAttachments(
message.id,
message.attachments.map((it) => it.id),
);
// ignore: parameter_assignments
message = await attachmentsUploadCompleter.future;
}
// Wait for the previous sendMessage call to finish. Otherwise, the order
// of messages will not be maintained.
final response = await _sendMessageLock.synchronized(
() => _client.sendMessage(
message,
id!,
type,
skipPush: skipPush,
skipEnrichUrl: skipEnrichUrl,
),
);
final sentMessage = response.message.syncWith(message).copyWith(
// Update the message state to sent.
state: MessageState.sent,
);
state!.updateMessage(sentMessage);
if (cooldown > 0) cooldownStartedAt = DateTime.now();
return response;
} catch (e) {
if (e is StreamChatNetworkError && e.isRetriable) {
state!._retryQueue.add([
message.copyWith(
// Update the message state to failed.
state: MessageState.sendingFailed,
),
]);
}
rethrow;
}
}
final _updateMessageLock = Lock();
/// Updates the [message] in this channel.
///
/// Waits for a [_messageAttachmentsUploadCompleter] to complete
/// before actually updating the message.
Future<UpdateMessageResponse> updateMessage(
Message message, {
bool skipEnrichUrl = false,
}) async {
_checkInitialized();
final originalMessage = message;
// Cancelling previous completer in case it's called again in the process
// Eg. Updating the message while the previous call is in progress.
_messageAttachmentsUploadCompleter
.remove(message.id)
?.completeError(const StreamChatError('Message cancelled'));
// ignore: parameter_assignments
message = message.copyWith(
state: MessageState.updating,
localUpdatedAt: DateTime.now(),
attachments: message.attachments.map(
(it) {
if (it.uploadState.isSuccess) return it;
return it.copyWith(uploadState: const UploadState.preparing());
},
).toList(),
);
state?.updateMessage(message);
try {
if (message.attachments.any((it) => !it.uploadState.isSuccess)) {
final attachmentsUploadCompleter = Completer<Message>();
_messageAttachmentsUploadCompleter[message.id] =
attachmentsUploadCompleter;
_uploadAttachments(
message.id,
message.attachments.map((it) => it.id),
);
// ignore: parameter_assignments
message = await attachmentsUploadCompleter.future;
}
// Wait for the previous update call to finish. Otherwise, the order of
// messages will not be maintained.
final response = await _updateMessageLock.synchronized(
() => _client.updateMessage(
message,
skipEnrichUrl: skipEnrichUrl,
),
);
final updateMessage = response.message.syncWith(message).copyWith(
// Update the message state to updated.
state: MessageState.updated,
ownReactions: message.ownReactions,
);
state?.updateMessage(updateMessage);
return response;
} catch (e) {
if (e is StreamChatNetworkError) {
if (e.isRetriable) {
state!._retryQueue.add([
message.copyWith(
// Update the message state to failed.
state: MessageState.updatingFailed,
),
]);
} else {
// Reset the message to original state if the update fails and is not
// retriable.
state?.updateMessage(originalMessage.copyWith(
state: MessageState.updatingFailed,
));
}
}
rethrow;
}
}
/// Partially updates the [message] in this channel.
///
/// Use [set] to define values to be set.
///
/// Use [unset] to define values to be unset.
Future<UpdateMessageResponse> partialUpdateMessage(
Message message, {
Map<String, Object?>? set,
List<String>? unset,
bool skipEnrichUrl = false,
}) async {
_checkInitialized();
final originalMessage = message;
// Cancelling previous completer in case it's called again in the process
// Eg. Updating the message while the previous call is in progress.
_messageAttachmentsUploadCompleter
.remove(message.id)
?.completeError(const StreamChatError('Message cancelled'));
// ignore: parameter_assignments
message = message.copyWith(
state: MessageState.updating,
localUpdatedAt: DateTime.now(),
);
state?.updateMessage(message);
try {
// Wait for the previous update call to finish. Otherwise, the order of
// messages will not be maintained.
final response = await _updateMessageLock.synchronized(
() => _client.partialUpdateMessage(
message.id,
set: set,
unset: unset,
skipEnrichUrl: skipEnrichUrl,
),
);
final updatedMessage = response.message.syncWith(message).copyWith(
// Update the message state to updated.
state: MessageState.updated,
ownReactions: message.ownReactions,
);
state?.updateMessage(updatedMessage);
return response;
} catch (e) {
if (e is StreamChatNetworkError) {
if (e.isRetriable) {
state!._retryQueue.add([
message.copyWith(
// Update the message state to failed.
state: MessageState.updatingFailed,
),
]);
} else {
// Reset the message to original state if the update fails and is not
// retriable.
state?.updateMessage(originalMessage.copyWith(
state: MessageState.updatingFailed,
));
}
}
rethrow;
}
}
final _deleteMessageLock = Lock();
/// Deletes the [message] from the channel.
Future<EmptyResponse> deleteMessage(
Message message, {
bool hard = false,
}) async {
_checkInitialized();
// Directly deleting the local messages which are not yet sent to server.
if (message.remoteCreatedAt == null) {
state!.deleteMessage(
message.copyWith(
type: 'deleted',
localDeletedAt: DateTime.now(),
state: MessageState.deleted(hard: hard),
),
hardDelete: hard,
);
// Removing the attachments upload completer to stop the `sendMessage`
// waiting for attachments to complete.
_messageAttachmentsUploadCompleter
.remove(message.id)
?.completeError(const StreamChatError('Message deleted'));
// Returning empty response to mark the api call as success.
return EmptyResponse();
}
// ignore: parameter_assignments
message = message.copyWith(
type: 'deleted',
deletedAt: DateTime.now(),
state: MessageState.deleting(hard: hard),
);
state?.deleteMessage(message, hardDelete: hard);
try {
// Wait for the previous delete call to finish. Otherwise, the order of
// messages will not be maintained.
final response = await _deleteMessageLock.synchronized(
() => _client.deleteMessage(message.id, hard: hard),
);
final deletedMessage = message.copyWith(
state: MessageState.deleted(hard: hard),
);
state?.deleteMessage(deletedMessage, hardDelete: hard);
if (hard) {
deletedMessage.attachments.forEach((attachment) {
if (attachment.uploadState.isSuccess) {
if (attachment.type == AttachmentType.image) {
deleteImage(attachment.imageUrl!);
} else if (attachment.type == AttachmentType.file) {
deleteFile(attachment.assetUrl!);
}
}
});
}
return response;
} catch (e) {
if (e is StreamChatNetworkError && e.isRetriable) {
state!._retryQueue.add([
message.copyWith(
// Update the message state to failed.
state: MessageState.deletingFailed(hard: hard),
),
]);
}
rethrow;
}
}
/// Retry the operation on the message based on the failed state.
///
/// For example, if the message failed to send, it will retry sending the
/// message and vice-versa.
Future<Object> retryMessage(Message message) async {
assert(message.state.isFailed, 'Message state is not failed');
return message.state.maybeWhen(
failed: (state, _) => state.when(
sendingFailed: () => sendMessage(message),
updatingFailed: () => updateMessage(message),
deletingFailed: (hard) => deleteMessage(message, hard: hard),
),
orElse: () => throw StateError('Message state is not failed'),
);
}
/// Pins provided message
Future<UpdateMessageResponse> pinMessage(
Message message, {
Object? /*num|DateTime*/ timeoutOrExpirationDate,
}) {
assert(() {
if (timeoutOrExpirationDate is! DateTime &&
timeoutOrExpirationDate != null &&
timeoutOrExpirationDate is! num) {
throw ArgumentError('Invalid timeout or Expiration date');
}
return true;
}(), 'Check for invalid timeout or expiration date');
DateTime? pinExpires;
if (timeoutOrExpirationDate is DateTime) {
pinExpires = timeoutOrExpirationDate;
} else if (timeoutOrExpirationDate is num) {
pinExpires = DateTime.now().add(
Duration(seconds: timeoutOrExpirationDate.toInt()),
);
}
return partialUpdateMessage(
message,
set: {
'pinned': true,
'pin_expires': pinExpires?.toUtc().toIso8601String(),
},
);
}
/// Unpins provided message.
Future<UpdateMessageResponse> unpinMessage(Message message) =>
partialUpdateMessage(
message,
set: {
'pinned': false,
},
);
/// Send a file to this channel.
Future<SendFileResponse> sendFile(
AttachmentFile file, {
ProgressCallback? onSendProgress,
CancelToken? cancelToken,
Map<String, Object?>? extraData,
}) {
_checkInitialized();
return _client.sendFile(
file,
id!,
type,
onSendProgress: onSendProgress,
cancelToken: cancelToken,
extraData: extraData,
);
}
/// Send an image to this channel.
Future<SendImageResponse> sendImage(
AttachmentFile file, {
ProgressCallback? onSendProgress,
CancelToken? cancelToken,
Map<String, Object?>? extraData,
}) {
_checkInitialized();
return _client.sendImage(
file,
id!,
type,
onSendProgress: onSendProgress,
cancelToken: cancelToken,
extraData: extraData,
);
}
/// Search for a message with the given options.
Future<SearchMessagesResponse> search({
String? query,
Filter? messageFilters,
List<SortOption>? sort,
PaginationParams? paginationParams,
}) {
_checkInitialized();
return _client.search(
Filter.in_('cid', [cid!]),
sort: sort,
query: query,
paginationParams: paginationParams,
messageFilters: messageFilters,
);
}
/// Delete a file from this channel.