-
Notifications
You must be signed in to change notification settings - Fork 385
Expand file tree
/
Copy pathclient.dart
More file actions
2459 lines (2167 loc) · 72.8 KB
/
Copy pathclient.dart
File metadata and controls
2459 lines (2167 loc) · 72.8 KB
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 'package:collection/collection.dart';
import 'package:dio/dio.dart';
import 'package:logging/logging.dart';
import 'package:meta/meta.dart';
import 'package:rxdart/rxdart.dart';
import 'package:stream_chat/src/client/channel.dart';
import 'package:stream_chat/src/client/channel_delivery_reporter.dart';
import 'package:stream_chat/src/client/retry_policy.dart';
import 'package:stream_chat/src/core/api/attachment_file_uploader.dart';
import 'package:stream_chat/src/core/api/requests.dart';
import 'package:stream_chat/src/core/api/responses.dart';
import 'package:stream_chat/src/core/api/sort_order.dart';
import 'package:stream_chat/src/core/api/stream_chat_api.dart';
import 'package:stream_chat/src/core/error/error.dart';
import 'package:stream_chat/src/core/http/connection_id_manager.dart';
import 'package:stream_chat/src/core/http/stream_http_client.dart';
import 'package:stream_chat/src/core/http/system_environment_manager.dart';
import 'package:stream_chat/src/core/http/token.dart';
import 'package:stream_chat/src/core/http/token_manager.dart';
import 'package:stream_chat/src/core/models/attachment_file.dart';
import 'package:stream_chat/src/core/models/banned_user.dart';
import 'package:stream_chat/src/core/models/channel_state.dart';
import 'package:stream_chat/src/core/models/draft.dart';
import 'package:stream_chat/src/core/models/draft_message.dart';
import 'package:stream_chat/src/core/models/event.dart';
import 'package:stream_chat/src/core/models/filter.dart';
import 'package:stream_chat/src/core/models/member.dart';
import 'package:stream_chat/src/core/models/message.dart';
import 'package:stream_chat/src/core/models/message_delivery.dart';
import 'package:stream_chat/src/core/models/message_reminder.dart';
import 'package:stream_chat/src/core/models/own_user.dart';
import 'package:stream_chat/src/core/models/poll.dart';
import 'package:stream_chat/src/core/models/poll_option.dart';
import 'package:stream_chat/src/core/models/poll_vote.dart';
import 'package:stream_chat/src/core/models/push_preference.dart';
import 'package:stream_chat/src/core/models/thread.dart';
import 'package:stream_chat/src/core/models/user.dart';
import 'package:stream_chat/src/core/util/utils.dart';
import 'package:stream_chat/src/db/chat_persistence_client.dart';
import 'package:stream_chat/src/event_type.dart';
import 'package:stream_chat/src/system_environment.dart';
import 'package:stream_chat/src/ws/connection_status.dart';
import 'package:stream_chat/src/ws/websocket.dart';
import 'package:stream_chat/version.dart';
import 'package:synchronized/synchronized.dart';
/// Handler function used for logging records. Function requires a single
/// [LogRecord] as the only parameter.
typedef LogHandlerFunction = void Function(LogRecord record);
final _levelEmojiMapper = {
Level.INFO: 'ℹ️',
Level.WARNING: '⚠️',
Level.SEVERE: '🚨',
};
/// The official Dart client for Stream Chat,
/// a service for building chat applications.
/// This library can be used on any Dart project and on both mobile and web apps
/// with Flutter.
///
/// You can sign up for a Stream account at https://getstream.io/chat/
///
/// The Chat client will manage API call, event handling and manage the
/// websocket connection to Stream Chat servers.
///
/// ```dart
/// final client = StreamChatClient("stream-chat-api-key");
/// ```
class StreamChatClient {
/// Create a client instance with default options.
/// You should only create the client once and re-use it across your
/// application.
StreamChatClient(
String apiKey, {
this.logLevel = Level.WARNING,
this.logHandlerFunction = StreamChatClient.defaultLogHandler,
RetryPolicy? retryPolicy,
String? baseURL,
String? baseWsUrl,
Duration connectTimeout = const Duration(seconds: 6),
Duration receiveTimeout = const Duration(seconds: 6),
StreamChatApi? chatApi,
WebSocket? ws,
AttachmentFileUploaderProvider attachmentFileUploaderProvider =
StreamAttachmentFileUploader.new,
Iterable<Interceptor>? chatApiInterceptors,
HttpClientAdapter? httpClientAdapter,
}) {
logger.info('Initiating new StreamChatClient');
final options = StreamHttpClientOptions(
baseUrl: baseURL,
connectTimeout: connectTimeout,
receiveTimeout: receiveTimeout,
);
_chatApi = chatApi ??
StreamChatApi(
apiKey,
options: options,
tokenManager: _tokenManager,
connectionIdManager: _connectionIdManager,
systemEnvironmentManager: _systemEnvironmentManager,
attachmentFileUploaderProvider: attachmentFileUploaderProvider,
logger: detachedLogger('🕸️'),
interceptors: chatApiInterceptors,
httpClientAdapter: httpClientAdapter,
);
_ws = ws ??
WebSocket(
apiKey: apiKey,
baseUrl: baseWsUrl ?? options.baseUrl,
tokenManager: _tokenManager,
systemEnvironmentManager: _systemEnvironmentManager,
handler: handleEvent,
logger: detachedLogger('🔌'),
);
_retryPolicy = retryPolicy ??
RetryPolicy(
shouldRetry: (_, __, error) {
return error is StreamChatNetworkError && error.isRetriable;
},
);
_connectionStatusSubscription = wsConnectionStatusStream.pairwise().listen(
(statusPair) {
final [prevStatus, currStatus] = statusPair;
return _onConnectionStatusChanged(prevStatus, currStatus);
},
);
state = ClientState(this);
}
late final StreamChatApi _chatApi;
late final WebSocket _ws;
/// This client state
late ClientState state;
final _tokenManager = TokenManager();
final _connectionIdManager = ConnectionIdManager();
static final _systemEnvironmentManager = SystemEnvironmentManager();
/// Updates the system environment information used by the client.
///
/// It allows you to set environment-specific information that will be
/// included in API requests, such as the application name, platform details,
/// and version information.
///
/// Example:
/// ```dart
/// client.updateSystemEnvironment(
/// SystemEnvironment(
/// name: 'my_app',
/// version: '1.0.0',
/// ),
/// );
/// ```
///
/// See [SystemEnvironment] for more information on the available fields.
void updateSystemEnvironment(SystemEnvironment environment) {
_systemEnvironmentManager.updateEnvironment(environment);
}
/// Default user agent for all requests
static String defaultUserAgent = _systemEnvironmentManager.userAgent;
/// Additional headers for all requests
static Map<String, Object?> additionalHeaders = {};
/// The current package version
static const packageVersion = PACKAGE_VERSION;
/// Chat persistence client
ChatPersistenceClient? chatPersistenceClient;
/// Returns `True` if the [chatPersistenceClient] is available and connected.
/// Otherwise, returns `False`.
bool get persistenceEnabled {
final client = chatPersistenceClient;
return client != null && client.isConnected;
}
late final RetryPolicy _retryPolicy;
/// The retry policy options getter
RetryPolicy get retryPolicy => _retryPolicy;
/// By default the Chat client will write all messages with level Warn or
/// Error to stdout.
///
/// During development you might want to enable more logging information,
/// you can change the default log level when constructing the client.
///
/// ```dart
/// final client = StreamChatClient("stream-chat-api-key",
/// logLevel: Level.INFO);
/// ```
final Level logLevel;
/// Client specific logger instance.
/// Refer to the class [Logger] to learn more about the specific
/// implementation.
late final Logger logger = detachedLogger('📡');
/// A function that has a parameter of type [LogRecord].
/// This is called on every new log record.
/// By default the client will use the handler returned by
/// [_getDefaultLogHandler].
/// Setting it you can handle the log messages directly instead of have them
/// written to stdout,
/// this is very convenient if you use an error tracking tool or if you want
/// to centralize your logs into one facility.
///
/// ```dart
/// myLogHandlerFunction = (LogRecord record) {
/// // do something with the record (ie. send it to Sentry or Fabric)
/// }
///
/// final client = StreamChatClient("stream-chat-api-key",
/// logHandlerFunction: myLogHandlerFunction);
///```
final LogHandlerFunction logHandlerFunction;
StreamSubscription<List<ConnectionStatus>>? _connectionStatusSubscription;
/// Manages delivery receipt reporting for channel messages.
///
/// Collects and batches delivery receipts to acknowledge message delivery
/// to senders across multiple channels.
late final channelDeliveryReporter = ChannelDeliveryReporter(
logger: detachedLogger('🧾'),
onMarkChannelsDelivered: markChannelsDelivered,
);
final _eventController = PublishSubject<Event>();
/// Stream of [Event] coming from [_ws] connection
/// Listen to this or use the [on] method to filter specific event types
Stream<Event> get eventStream => _eventController.stream.map(
// If the poll vote is an answer, we should emit a different event
// to make it easier to handle in the state.
(event) => switch ((event.type, event.pollVote?.isAnswer == true)) {
(EventType.pollVoteCasted || EventType.pollVoteChanged, true) =>
event.copyWith(type: EventType.pollAnswerCasted),
(EventType.pollVoteRemoved, true) =>
event.copyWith(type: EventType.pollAnswerRemoved),
_ => event,
},
);
/// The current status value of the [_ws] connection
ConnectionStatus get wsConnectionStatus => _ws.connectionStatus;
/// This notifies the connection status of the [_ws] connection.
/// Listen to this to get notified when the [_ws] tries to reconnect.
Stream<ConnectionStatus> get wsConnectionStatusStream {
return _ws.connectionStatusStream.distinct();
}
/// Default log handler function for the [StreamChatClient] logger.
static void defaultLogHandler(LogRecord record) {
print(
'${record.time} '
'${_levelEmojiMapper[record.level] ?? record.level.name} '
'${record.loggerName} ${record.message} ',
);
if (record.error != null) print(record.error);
if (record.stackTrace != null) print(record.stackTrace);
}
/// Default logger for the [StreamChatClient].
Logger detachedLogger(String name) => Logger.detached(name)
..level = logLevel
..onRecord.listen(logHandlerFunction);
/// Connects the current user, this triggers a connection to the API.
/// It returns a [Future] that resolves when the connection is setup.
/// Pass [connectWebSocket]: false, if you want to connect to websocket
/// at a later stage or use the client in connection-less mode
Future<OwnUser> connectUser(
User user,
String token, {
bool connectWebSocket = true,
}) =>
_connectUser(
user,
token: Token.fromRawValue(token),
connectWebSocket: connectWebSocket,
);
/// Connects the current user using the [tokenProvider] to fetch the token.
/// It returns a [Future] that resolves when the connection is setup.
Future<OwnUser> connectUserWithProvider(
User user,
TokenProvider tokenProvider, {
bool connectWebSocket = true,
}) =>
_connectUser(
user,
provider: tokenProvider,
connectWebSocket: connectWebSocket,
);
/// Connects the current user with an anonymous id, this triggers a connection
/// to the API. It returns a [Future] that resolves when the connection is
/// setup.
Future<OwnUser> connectAnonymousUser({
bool connectWebSocket = true,
}) async {
final token = Token.anonymous();
final user = OwnUser(id: token.userId);
return _connectUser(
user,
token: token,
connectWebSocket: connectWebSocket,
);
}
/// Connects the current user as guest, this triggers a connection to the API.
/// It returns a [Future] that resolves when the connection is setup.
Future<OwnUser> connectGuestUser(
User user, {
bool connectWebSocket = true,
}) async {
final userId = user.id;
final anonymousToken = Token.anonymous(userId: userId);
// setting anonymous token so that getGuestUser works
_tokenManager.setTokenOrProvider(userId, token: anonymousToken);
final guestUser = await _chatApi.guest.getGuestUser(user);
// resetting tokenManager after successful request
_tokenManager.reset();
final guestUserToken = Token.fromRawValue(guestUser.accessToken);
return _connectUser(
guestUser.user,
token: guestUserToken,
connectWebSocket: connectWebSocket,
);
}
Future<OwnUser> _connectUser(
User user, {
Token? token,
TokenProvider? provider,
bool connectWebSocket = true,
}) async {
if (_ws.connectionCompleter?.isCompleted == false) {
throw const StreamChatError(
'User already getting connected, try calling `disconnectUser` '
'before trying to connect again',
);
}
logger.info('setting user : ${user.id}');
await _tokenManager.setTokenOrProvider(
user.id,
token: token,
provider: provider,
);
final ownUser = OwnUser.fromUser(user);
state.currentUser = ownUser;
try {
// Connect to persistence client if its set.
if (chatPersistenceClient != null) {
await openPersistenceConnection(ownUser);
}
// Connect to websocket if [connectWebSocket] is true.
//
// This is useful when you want to connect to websocket
// at a later stage or use the client in connection-less mode.
if (connectWebSocket) {
final connectedUser = await openConnection(
includeUserDetailsInConnectCall: true,
);
state.currentUser = connectedUser;
}
return state.currentUser!;
} catch (e, stk) {
if (e is StreamWebSocketError && e.isRetriable) {
final event = await chatPersistenceClient?.getConnectionInfo();
if (event != null) return ownUser.merge(event.me);
}
logger.severe('error connecting user : ${ownUser.id}', e, stk);
rethrow;
}
}
/// Connects the [chatPersistenceClient] to the given [user].
Future<void> openPersistenceConnection(User user) async {
final client = chatPersistenceClient;
if (client == null) {
throw const StreamChatError('Chat persistence client is not set');
}
if (client.isConnected) {
// If the persistence client is already connected to the userId,
// we don't need to connect again.
if (client.userId == user.id) return;
throw const StreamChatError('''
Chat persistence client is already connected to a different user,
please close the connection before connecting a new one.''');
}
// Connect the persistence client to the userId.
return client.connect(user.id);
}
/// Disconnects the [chatPersistenceClient] from the current user.
Future<void> closePersistenceConnection({bool flush = false}) async {
final client = chatPersistenceClient;
// If the persistence client is never connected, we don't need to close it.
if (client == null || !client.isConnected) {
logger.info('Chat persistence client is not connected');
return;
}
// Disconnect the persistence client.
return client.disconnect(flush: flush);
}
/// Creates a new WebSocket connection with the current user.
/// If [includeUserDetailsInConnectCall] is true it will include the current
/// user details in the connect call.
Future<OwnUser> openConnection({
bool includeUserDetailsInConnectCall = false,
}) async {
assert(
state.currentUser != null,
'User is not set on client, '
'use `connectUser` or `connectAnonymousUser` instead',
);
final user = state.currentUser!;
logger.info('Opening web-socket connection for ${user.id}');
if (wsConnectionStatus == ConnectionStatus.connecting) {
throw StreamChatError('Connection already in progress for ${user.id}');
}
if (wsConnectionStatus == ConnectionStatus.connected) {
throw StreamChatError('Connection already available for ${user.id}');
}
try {
final event = await _ws.connect(
user,
includeUserDetails: includeUserDetailsInConnectCall,
);
// Start listening to events
state.subscribeToEvents();
return user.merge(event.me);
} catch (e, stk) {
logger.severe('error connecting ws', e, stk);
rethrow;
}
}
/// Disconnects the [_ws] connection,
/// without removing the user set on client.
///
/// This will not trigger default auto-retry mechanism for reconnection.
/// You need to call [openConnection] to reconnect to [_ws].
void closeConnection() {
logger.info('Closing web-socket connection for ${state.currentUser?.id}');
// Stop listening to events
state.cancelEventSubscription();
_ws.disconnect();
}
void _handleHealthCheckEvent(Event event) {
final user = event.me;
if (user != null) state.currentUser = user;
final connectionId = event.connectionId;
if (connectionId != null) {
_connectionIdManager.setConnectionId(connectionId);
chatPersistenceClient?.updateConnectionInfo(event);
}
}
/// Method called to add a new event to the [_eventController].
void handleEvent(Event event) {
if (event.type == EventType.healthCheck) {
return _handleHealthCheckEvent(event);
}
state.updateUser(event.user);
return _eventController.add(event);
}
void _onConnectionStatusChanged(
ConnectionStatus prevStatus,
ConnectionStatus currStatus,
) async {
// If the status hasn't changed, we don't need to do anything.
if (prevStatus == currStatus) return;
final wasConnected = prevStatus == ConnectionStatus.connected;
final isConnected = currStatus == ConnectionStatus.connected;
// Notify the connection status change event
handleEvent(Event(
type: EventType.connectionChanged,
online: isConnected,
));
final connectionRecovered = !wasConnected && isConnected;
if (connectionRecovered) {
// connection recovered
final cids = [...state.channels.keys.toSet()];
if (cids.isNotEmpty) {
await queryChannelsOnline(
filter: Filter.in_('cid', cids),
paginationParams: const PaginationParams(limit: 30),
);
// Sync the persistence client if available
if (persistenceEnabled) await sync(cids: cids);
}
handleEvent(Event(
type: EventType.connectionRecovered,
online: true,
));
}
}
/// Stream of [Event] coming from [_ws] connection
/// Pass an eventType as parameter in order to filter just a type of event
Stream<Event> on([
String? eventType,
String? eventType2,
String? eventType3,
String? eventType4,
]) {
if (eventType == null || eventType == EventType.any) return eventStream;
return eventStream.where((event) =>
event.type == eventType ||
event.type == eventType2 ||
event.type == eventType3 ||
event.type == eventType4);
}
// Lock to make sure only one sync process is running at a time.
final _syncLock = Lock();
/// Get the events missed while offline to sync the offline storage
/// Will automatically fetch [cids] and [lastSyncedAt] if [persistenceEnabled]
Future<void> sync({List<String>? cids, DateTime? lastSyncAt}) {
return _syncLock.synchronized(() async {
final channels = cids ?? await chatPersistenceClient?.getChannelCids();
if (channels == null || channels.isEmpty) return;
final syncAt = lastSyncAt ?? await chatPersistenceClient?.getLastSyncAt();
if (syncAt == null) {
logger.info('Fresh sync start: lastSyncAt initialized to now.');
return chatPersistenceClient?.updateLastSyncAt(DateTime.now());
}
try {
logger.info('Syncing events since $syncAt for channels: $channels');
final res = await _chatApi.general.sync(channels, syncAt);
final events = res.events.sorted(
(a, b) => a.createdAt.compareTo(b.createdAt),
);
for (final event in events) {
logger.fine('Syncing event: ${event.type}');
handleEvent(event);
}
final updatedSyncAt = events.lastOrNull?.createdAt ?? DateTime.now();
return chatPersistenceClient?.updateLastSyncAt(updatedSyncAt);
} catch (error, stk) {
// If we got a 400 error, it means that either the sync time is too
// old or the channel list is too long or too many events need to be
// synced. In this case, we should just flush the persistence client
// and start over.
if (error is StreamChatNetworkError && error.statusCode == 400) {
logger.warning(
'Failed to sync events due to stale or oversized state. '
'Resetting the persistence client to enable a fresh start.',
);
await chatPersistenceClient?.flush();
return chatPersistenceClient?.updateLastSyncAt(DateTime.now());
}
logger.warning('Error syncing events', error, stk);
}
});
}
final _queryChannelsStreams = <String, Future<List<Channel>>>{};
/// Requests channels with a given query.
Stream<List<Channel>> queryChannels({
Filter? filter,
SortOrder<ChannelState>? channelStateSort,
bool state = true,
bool watch = true,
bool presence = false,
int? memberLimit,
int? messageLimit,
PaginationParams paginationParams = const PaginationParams(),
bool waitForConnect = true,
}) async* {
if (!_connectionIdManager.hasConnectionId) {
// ignore: parameter_assignments
watch = false;
}
final hash = generateHash([
filter,
channelStateSort,
state,
watch,
presence,
memberLimit,
messageLimit,
paginationParams,
]);
// Return results from cache if available
if (_queryChannelsStreams.containsKey(hash)) {
try {
yield await _queryChannelsStreams[hash]!;
return;
} catch (e, stk) {
logger.severe('Error retrieving cached query results', e, stk);
// Cache is invalid, continue with fresh query
_queryChannelsStreams.remove(hash);
}
}
// Get offline results first
var offlineChannels = <Channel>[];
try {
offlineChannels = await queryChannelsOffline(
filter: filter,
channelStateSort: channelStateSort,
paginationParams: paginationParams,
);
if (offlineChannels.isNotEmpty) yield offlineChannels;
} catch (e, stk) {
logger.warning('Error querying channels offline', e, stk);
// Continue to online query even if offline fails
}
try {
final newQueryChannelsFuture = queryChannelsOnline(
filter: filter,
sort: channelStateSort,
state: state,
watch: watch,
presence: presence,
memberLimit: memberLimit,
messageLimit: messageLimit,
paginationParams: paginationParams,
waitForConnect: waitForConnect,
).timeout(
const Duration(seconds: 30),
onTimeout: () {
logger.warning('Online channel query timed out');
throw TimeoutException('Channel query timed out');
},
).whenComplete(() {
// Always clean up cache reference when done
_queryChannelsStreams.remove(hash);
});
// Store the future in cache
_queryChannelsStreams[hash] = newQueryChannelsFuture;
yield await newQueryChannelsFuture;
} catch (e, stk) {
logger.severe('Error querying channels online', e, stk);
// Only rethrow if we have no channels to show the user
if (offlineChannels.isEmpty) rethrow;
}
}
/// Returns a token associated with the [callId].
@Deprecated('Will be removed in the next major version')
Future<CallTokenPayload> getCallToken(String callId) async =>
_chatApi.call.getCallToken(callId);
/// Creates a new call.
@Deprecated('Will be removed in the next major version')
Future<CreateCallPayload> createCall({
required String callId,
required String callType,
required String channelType,
required String channelId,
}) {
return _chatApi.call.createCall(
callId: callId,
callType: callType,
channelType: channelType,
channelId: channelId,
);
}
/// Requests channels with a given query from the API.
Future<List<Channel>> queryChannelsOnline({
Filter? filter,
SortOrder<ChannelState>? sort,
bool state = true,
bool watch = true,
bool presence = false,
int? memberLimit,
int? messageLimit,
bool waitForConnect = true,
PaginationParams paginationParams = const PaginationParams(),
}) async {
if (waitForConnect) {
if (_ws.connectionCompleter?.isCompleted == false) {
logger.info('awaiting connection completer');
await _ws.connectionCompleter?.future;
}
if (wsConnectionStatus != ConnectionStatus.connected) {
throw const StreamChatError(
'You cannot use queryChannels without an active connection. '
'Please call `connectUser` to connect the client.',
);
}
}
if (!_connectionIdManager.hasConnectionId) {
// ignore: parameter_assignments
watch = false;
}
logger.info('Query channel start');
final res = await _chatApi.channel.queryChannels(
filter: filter,
sort: sort,
state: state,
watch: watch,
presence: presence,
memberLimit: memberLimit,
messageLimit: messageLimit,
paginationParams: paginationParams,
);
if (res.channels.isEmpty && paginationParams.offset == 0) {
logger.warning('''
We could not find any channel for this query.
Please make sure to take a look at the Flutter tutorial: https://getstream.io/chat/flutter/tutorial
If your application already has users and channels, you might need to adjust your query channel as explained in the docs https://getstream.io/chat/docs/query_channels/?language=dart
''');
return <Channel>[];
}
final channels = res.channels;
final users = channels
.expand((it) => it.members ?? <Member>[])
.map((it) => it.user)
.toList(growable: false);
this.state.updateUsers(users);
logger.info('Got ${res.channels.length} channels from api');
final updateData = _mapChannelStateToChannel(channels);
// Submit delivery report for the channels fetched in this query.
await channelDeliveryReporter.submitForDelivery(updateData.value);
await chatPersistenceClient?.updateChannelQueries(
filter,
channels.map((c) => c.channel!.cid).toList(),
// Clear the query cache if we are refreshing.
clearQueryCache: (paginationParams.offset ?? 0) == 0,
);
this.state.addChannels(updateData.key);
return updateData.value;
}
/// Requests channels with a given query from the Persistence client.
Future<List<Channel>> queryChannelsOffline({
Filter? filter,
SortOrder<ChannelState>? channelStateSort,
PaginationParams paginationParams = const PaginationParams(),
}) async {
final offlineChannels = (await chatPersistenceClient?.getChannelStates(
filter: filter,
channelStateSort: channelStateSort,
paginationParams: paginationParams,
)) ??
[];
final updatedData = _mapChannelStateToChannel(offlineChannels);
state.addChannels(updatedData.key);
return updatedData.value;
}
MapEntry<Map<String, Channel>, List<Channel>> _mapChannelStateToChannel(
List<ChannelState> channelStates,
) {
final channels = {...state.channels};
final newChannels = <Channel>[];
for (final channelState in channelStates) {
final channel = channels[channelState.channel!.cid];
if (channel != null) {
channel.state?.updateChannelState(channelState);
newChannels.add(channel);
} else {
final newChannel = Channel.fromState(this, channelState);
if (newChannel.cid != null) {
channels[newChannel.cid!] = newChannel;
}
newChannels.add(newChannel);
}
}
return MapEntry(channels, newChannels);
}
/// Requests users with a given query.
Future<QueryUsersResponse> queryUsers({
bool? presence,
Filter? filter,
SortOrder<User>? sort,
PaginationParams? pagination,
}) async {
final response = await _chatApi.user.queryUsers(
presence: presence ?? _connectionIdManager.hasConnectionId,
filter: filter,
sort: sort,
pagination: pagination,
);
state.updateUsers(response.users);
return response;
}
/// Query banned users.
Future<QueryBannedUsersResponse> queryBannedUsers({
required Filter filter,
SortOrder<BannedUser>? sort,
PaginationParams? pagination,
}) =>
_chatApi.moderation.queryBannedUsers(
filter: filter,
sort: sort,
pagination: pagination,
);
/// A message search.
Future<SearchMessagesResponse> search(
Filter filter, {
String? query,
SortOrder? sort,
PaginationParams? paginationParams,
Filter? messageFilters,
}) =>
_chatApi.general.searchMessages(
filter,
query: query,
sort: sort,
pagination: paginationParams,
messageFilters: messageFilters,
);
/// Send a [file] to the [channelId] of type [channelType]
Future<SendFileResponse> sendFile(
AttachmentFile file,
String channelId,
String channelType, {
ProgressCallback? onSendProgress,
CancelToken? cancelToken,
Map<String, Object?>? extraData,
}) =>
_chatApi.fileUploader.sendFile(
file,
channelId,
channelType,
onSendProgress: onSendProgress,
cancelToken: cancelToken,
extraData: extraData,
);
/// Send a [image] to the [channelId] of type [channelType]
Future<SendImageResponse> sendImage(
AttachmentFile image,
String channelId,
String channelType, {
ProgressCallback? onSendProgress,
CancelToken? cancelToken,
Map<String, Object?>? extraData,
}) =>
_chatApi.fileUploader.sendImage(
image,
channelId,
channelType,
onSendProgress: onSendProgress,
cancelToken: cancelToken,
extraData: extraData,
);
/// Delete a file from this channel
Future<EmptyResponse> deleteFile(
String url,
String channelId,
String channelType, {
CancelToken? cancelToken,
Map<String, Object?>? extraData,
}) =>
_chatApi.fileUploader.deleteFile(
url,
channelId,
channelType,
cancelToken: cancelToken,
extraData: extraData,
);
/// Delete an image from this channel
Future<EmptyResponse> deleteImage(
String url,
String channelId,
String channelType, {
CancelToken? cancelToken,
Map<String, Object?>? extraData,
}) =>
_chatApi.fileUploader.deleteImage(
url,
channelId,
channelType,
cancelToken: cancelToken,
extraData: extraData,
);
/// Replaces the [channelId] of type [ChannelType] data with [data].
///
/// Use [updateChannelPartial] for a partial update.
Future<UpdateChannelResponse> updateChannel(
String channelId,
String channelType,
Map<String, Object?> data, {
Message? message,
}) =>
_chatApi.channel.updateChannel(
channelId,
channelType,
data,
message: message,
);
/// Partial update for the [channelId] of type [ChannelType]. Sets the
/// data provided in [set], and removes the attributes given in [unset].
///
/// Use [updateChannel] for a full update.
Future<PartialUpdateChannelResponse> updateChannelPartial(
String channelId,
String channelType, {
Map<String, Object?>? set,
List<String>? unset,
}) =>
_chatApi.channel.updateChannelPartial(
channelId,
channelType,
set: set,
unset: unset,
);
/// Add a device for Push Notifications.
Future<EmptyResponse> addDevice(
String id,
PushProvider pushProvider, {
String? pushProviderName,
}) =>
_chatApi.device.addDevice(
id,
pushProvider,
pushProviderName: pushProviderName,
);
/// Gets a list of user devices.