-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathstream_video.dart
More file actions
1486 lines (1295 loc) · 48.6 KB
/
stream_video.dart
File metadata and controls
1486 lines (1295 loc) · 48.6 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:async/async.dart' as async;
import 'package:collection/collection.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';
import 'package:meta/meta.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:rxdart/rxdart.dart';
import 'package:stream_webrtc_flutter/stream_webrtc_flutter.dart' as rtc;
import 'package:system_info2/system_info2.dart';
import 'package:uuid/uuid.dart';
import '../../../protobuf/video/sfu/models/models.pb.dart' as sfu_models;
import '../globals.dart';
import '../open_api/video/coordinator/api.dart';
import 'audio_processing/audio_processor.dart';
import 'call/call.dart';
import 'call/call_reject_reason.dart';
import 'call/call_ringing_state.dart';
import 'call/call_type.dart';
import 'coordinator/coordinator_client.dart';
import 'coordinator/models/coordinator_events.dart';
import 'coordinator/open_api/coordinator_client_open_api.dart';
import 'coordinator/retry/coordinator_client_retry.dart';
import 'core/client_state.dart';
import 'core/connection_state.dart';
import 'disposable.dart';
import 'errors/video_error.dart';
import 'errors/video_error_composer.dart';
import 'internal/_instance_holder.dart';
import 'latency/latency_service.dart';
import 'latency/latency_settings.dart';
import 'lifecycle/lifecycle_state.dart';
import 'lifecycle/lifecycle_utils.dart'
if (dart.library.io) 'lifecycle/lifecycle_utils_io.dart'
as lifecycle;
import 'logger/impl/console_logger.dart';
import 'logger/impl/external_logger.dart';
import 'logger/impl/tagged_logger.dart';
import 'logger/stream_log.dart';
import 'logger/stream_logger.dart';
import 'models/audio_configuration_policy.dart';
import 'models/call_cid.dart';
import 'models/call_preferences.dart';
import 'models/call_received_data.dart';
import 'models/call_ringing_data.dart';
import 'models/call_status.dart';
import 'models/disconnect_reason.dart';
import 'models/guest_created_data.dart';
import 'models/push_device.dart';
import 'models/push_provider.dart';
import 'models/queried_calls.dart';
import 'models/user.dart';
import 'models/user_info.dart';
import 'network_monitor_settings.dart';
import 'platform_detector/platform_detector.dart';
import 'push_notification/push_notification_manager.dart';
import 'retry/retry_policy.dart';
import 'token/token.dart';
import 'token/token_manager.dart';
import 'utils/cancelable_operation.dart';
import 'utils/future.dart';
import 'utils/none.dart';
import 'utils/result.dart';
import 'utils/standard.dart';
import 'utils/subscriptions.dart';
import 'webrtc/rtc_manager.dart';
import 'webrtc/rtc_media_device/rtc_media_device_notifier.dart';
import 'webrtc/sdp/policy/sdp_policy.dart';
const _tag = 'SV:Client';
const _idEvents = 1;
const _idAppState = 2;
const _defaultCoordinatorRpcUrl = 'https://video.stream-io-api.com';
const _defaultCoordinatorWsUrl = 'wss://video.stream-io-api.com/video/connect';
/// Handler function used for logging.
typedef LogHandlerFunction =
void Function(
Priority priority,
String tag,
MessageBuilder message, [
Object? error,
StackTrace? stk,
]);
/// The client responsible for handling config and maintaining calls
class StreamVideo extends Disposable {
/// Creates a new Stream Video client associated with the
/// Stream Video singleton instance
///
/// If [failIfSingletonExists] is set to false, the new instance will override and disconnect the existing singleton instance.
factory StreamVideo(
String apiKey, {
StreamVideoOptions? options,
required User user,
String? userToken,
TokenLoader? tokenLoader,
OnTokenUpdated? onTokenUpdated,
bool failIfSingletonExists = true,
PNManagerProvider? pushNotificationManagerProvider,
}) {
final instance = StreamVideo._(
apiKey,
options: options ?? StreamVideoOptions(),
user: user,
userToken: userToken,
tokenLoader: tokenLoader,
onTokenUpdated: onTokenUpdated,
pushNotificationManagerProvider: pushNotificationManagerProvider,
);
_instanceHolder.install(
instance,
failIfSingletonExists: failIfSingletonExists,
);
return instance;
}
/// Creates a new Stream Video client unassociated with the
/// Stream Video singleton instance
factory StreamVideo.create(
String apiKey, {
required User user,
StreamVideoOptions? options,
String? userToken,
TokenLoader? tokenLoader,
OnTokenUpdated? onTokenUpdated,
PNManagerProvider? pushNotificationManagerProvider,
bool precacheGenericSdps = true,
}) {
final instance = StreamVideo._(
apiKey,
user: user,
options: options ?? StreamVideoOptions(),
userToken: userToken,
tokenLoader: tokenLoader,
onTokenUpdated: onTokenUpdated,
pushNotificationManagerProvider: pushNotificationManagerProvider,
precacheGenericSdps: precacheGenericSdps,
);
return instance;
}
StreamVideo._(
this.apiKey, {
required User user,
required StreamVideoOptions options,
String? userToken,
TokenLoader? tokenLoader,
OnTokenUpdated? onTokenUpdated,
PNManagerProvider? pushNotificationManagerProvider,
bool precacheGenericSdps = true,
}) : _options = options,
_state = MutableClientState(user, options) {
_networkMonitor =
_options.networkMonitorSettings.internetConnectionInstance ??
InternetConnection.createInstance(
checkInterval: _options.networkMonitorSettings.checkInterval,
useDefaultOptions:
_options.networkMonitorSettings.customEndpoints.isEmpty,
customCheckOptions:
_options.networkMonitorSettings.customEndpoints.isEmpty
? null
: _options.networkMonitorSettings.customEndpoints
.map((option) => option.toInternetCheckOption())
.toList(),
);
_client = buildCoordinatorClient(
user: user,
apiKey: apiKey,
tokenManager: _tokenManager,
latencySettings: _options.latencySettings,
retryPolicy: _options.retryPolicy,
rpcUrl: _options.coordinatorRpcUrl,
wsUrl: _options.coordinatorWsUrl,
networkMonitor: _networkMonitor,
);
// Initialize the push notification manager if the provider is provided.
pushNotificationManager = pushNotificationManagerProvider?.call(
_client,
this,
);
_state.user.value = user;
if (CurrentPlatform.isAndroid || CurrentPlatform.isIos) {
RtcMediaDeviceNotifier.instance
.reinitializeAudioConfiguration(options.audioConfigurationPolicy)
.then((_) {
if (precacheGenericSdps) {
unawaited(RtcManager.cacheGenericSdp());
}
webrtcInitializationCompleter.complete();
})
.onError((_, _) {
webrtcInitializationCompleter.complete();
});
} else {
webrtcInitializationCompleter.complete();
}
final tokenProvider = switch (user.type) {
UserType.authenticated => TokenProvider.from(
userToken?.let(UserToken.jwt),
tokenLoader,
onTokenUpdated,
),
UserType.anonymous => TokenProvider.static(
UserToken.anonymous(),
onTokenUpdated: onTokenUpdated,
),
UserType.guest => TokenProvider.dynamic((userId) async {
final result = await _client.loadGuest(id: userId);
if (result is! Success<GuestCreatedData>) {
throw (result as Failure).error;
}
final updatedUser = result.data.user;
_state.user.value = User(
type: user.type,
info: updatedUser.toUserInfo(),
);
return result.data.accessToken;
}, onTokenUpdated: onTokenUpdated),
};
_tokenManager.setTokenProvider(user.id, tokenProvider: tokenProvider);
_setupLogger(options.logPriority, options.logHandlerFunction);
unawaited(
_setClientDetails().onError((dynamic error, StackTrace stackTrace) {
_logger.e(
() =>
'[StreamVideo] failed to set client details: $error with stackTrace: $stackTrace',
);
return null;
}),
);
if (options.autoConnect) {
unawaited(
connect(
includeUserDetails: options.includeUserDetailsForAutoConnect,
).onError((dynamic error, StackTrace stackTrace) {
_logger.e(
() =>
'[StreamVideo] failed to auto connect: $error with stackTrace: $stackTrace',
);
return Result.error('Failed to auto connect: $error');
}),
);
}
}
static final InstanceHolder _instanceHolder = InstanceHolder();
/// The singleton instance of the Stream Video client.
static StreamVideo get instance => _instanceHolder.instance;
/// Resets the singleton instance of the Stream Video client.
///
/// This is useful if you want to re-initialise the SDK with a different
/// API key.
static Future<void> reset({bool disconnect = false}) async {
if (disconnect && _instanceHolder.isInitialized()) {
await _instanceHolder.instance.disconnect();
}
return _instanceHolder.reset();
}
/// Return if the singleton instance of the Stream Video Client has already
/// been initialized.
static bool isInitialized() {
return _instanceHolder.isInitialized();
}
final _logger = taggedLogger(tag: _tag);
final StreamVideoOptions _options;
final String apiKey;
final MutableClientState _state;
StreamVideoOptions get options => _options;
@internal
Completer<void> webrtcInitializationCompleter = Completer();
final _tokenManager = TokenManager();
final _subscriptions = Subscriptions();
late final CoordinatorClient _client;
late final InternetConnection _networkMonitor;
late final PushNotificationManager? pushNotificationManager;
final Map<String, bool> _mutedCameraByStateChange = {};
final Map<String, bool> _mutedAudioByStateChange = {};
final Map<String, Timer> _incomingAutoRejectTimers = {};
/// Returns the current user.
UserInfo get currentUser => _state.currentUser.info;
/// Returns the current user type.
UserType get currentUserType => _state.currentUser.type;
/// Returns the [StreamVideo] state.
ClientState get state => _state;
/// Returns the active call if exists.
List<Call> get activeCalls => _state.activeCalls.value;
Call? get activeCall {
if (_options.allowMultipleActiveCalls) {
throw Exception(
'Multiple active calls are enabled, use activeCalls instead',
);
}
return _state.activeCalls.value.singleOrNull;
}
/// You can subscribe to WebSocket events provided by the API.
/// Please note that subscribing to WebSocket events is an advanced use-case,
/// for most use-cases it should be enough to watch for changes
/// in the reactive [Call.state].
Stream<CoordinatorEvent> get events => _client.events.asStream();
async.CancelableOperation<Result<UserToken>>? _connectOperation;
async.CancelableOperation<Result<None>>? _disconnectOperation;
set _connectionState(ConnectionState newState) {
final curState = _connectionState;
if (curState != newState) {
_logger.i(() => '[setConnectionState] #client; $newState <= $curState');
_state.connection.value = newState;
}
}
ConnectionState get _connectionState => _state.connection.value;
/// Connects the user to the Stream Video service.
Future<Result<UserToken>> connect({
bool includeUserDetails = true,
bool registerPushDevice = true,
}) async {
if (currentUserType == UserType.anonymous) {
_logger.w(() => '[connect] rejected (anonymous user)');
return Result.error(
'Cannot connect anonymous user to the WS due to Missing Permissions',
);
}
_connectOperation ??= _connect(
includeUserDetails: includeUserDetails,
registerPushDevice: registerPushDevice,
).asCancelable();
return _connectOperation!
.valueOrDefault(Result.error('connect was cancelled'))
.whenComplete(() {
_logger.i(() => '[connect] clear shared operation');
_connectOperation = null;
});
}
/// Disconnects the user from the Stream Video service.
Future<Result<None>> disconnect() async {
_disconnectOperation ??= _disconnect().asCancelable();
return _disconnectOperation!
.valueOrDefault(Result.error('disconnect was cancelled'))
.whenComplete(() {
_logger.i(() => '[disconnect] clear shared operation');
_disconnectOperation = null;
});
}
Future<Result<UserToken>> _connect({
bool includeUserDetails = false,
bool registerPushDevice = true,
}) async {
_logger.i(() => '[connect] currentUser.id: ${_state.currentUser.id}');
if (_connectionState.isConnected) {
_logger.w(() => '[connect] rejected (already connected)');
final token = _tokenManager.getCachedToken();
if (token == null) {
return Result.error('[connect] userToken is null in Connected state');
}
return Result.success(token);
}
_connectionState = ConnectionState.connecting(_state.currentUser.id);
// guest user will be updated when token gets fetched
final tokenResult = await _tokenManager.getToken();
if (tokenResult is! Success<UserToken>) {
_logger.e(() => '[connect] token fetching failed: $tokenResult');
_connectionState = ConnectionState.failed(
_state.currentUser.id,
error: (tokenResult as Failure).error,
);
return tokenResult;
}
final user = _state.user.value;
_logger.v(() => '[connect] currentUser.id : ${user.id}');
try {
await _disconnectOperation?.cancel();
final result = await _client.connectUser(
user.info,
includeUserDetails: includeUserDetails,
);
_logger.v(() => '[connect] completed: $result');
if (result is Failure) {
_connectionState = ConnectionState.failed(
_state.currentUser.id,
error: result.error,
);
return result;
}
_connectionState = ConnectionState.connected(_state.currentUser.id);
_subscriptions.add(_idEvents, _client.events.listen(_onEvent));
_subscriptions.add(_idAppState, lifecycle.appState.listen(_onAppState));
// Register device with push notification manager.
if (registerPushDevice) {
pushNotificationManager?.registerDevice();
}
return Result.success(tokenResult.data);
} catch (e, stk) {
_logger.e(() => '[connect] failed(${user.id}): $e');
return Result.failure(VideoErrors.compose(e, stk));
}
}
Future<Result<None>> _disconnect() async {
_logger.i(() => '[disconnect] currentUser.id: ${_state.currentUser.id}');
if (_connectionState.isDisconnected) {
_logger.w(() => '[disconnect] rejected (already disconnected)');
return const Result.success(none);
}
try {
await _connectOperation?.cancel();
// Unregister device from push notification manager.
await pushNotificationManager?.unregisterDevice();
await _client.disconnectUser();
_subscriptions.cancelAll();
// Resetting the state.
await _state.clear();
_connectionState = ConnectionState.disconnected(_state.currentUser.id);
_logger.v(() => '[disconnect] completed');
return const Result.success(none);
} catch (e, stk) {
_logger.e(() => '[disconnect] failed: $e');
return Result.failure(VideoErrors.compose(e, stk));
}
}
@override
Future<void> dispose() async {
_logger.i(() => '[dispose]');
if (!_connectionState.isDisconnected) {
await _client.disconnectUser();
}
for (final timer in _incomingAutoRejectTimers.values) {
timer.cancel();
}
_incomingAutoRejectTimers.clear();
_subscriptions.cancelAll();
await pushNotificationManager?.dispose();
await _state.clear();
return super.dispose();
}
void _onEvent(CoordinatorEvent event) {
final currentUserId = _state.currentUser.id;
_logger.v(() => '[onCoordinatorEvent] eventType: ${event.runtimeType}');
if (event is CoordinatorCallRingingEvent &&
event.metadata.details.createdBy.id != currentUserId &&
event.data.ringing) {
_logger.v(() => '[onCoordinatorEvent] onCallRinging: ${event.data}');
// In a edge case where call with the same CID as the incoming call is also an outgoing call
// we want to use the same Call instance.
if (state.outgoingCall.valueOrNull?.callCid.value ==
event.data.callCid.value) {
_state.incomingCall.value = state.outgoingCall.valueOrNull;
return;
}
final call = _makeCallFromRinging(data: event.data);
_state.incomingCall.value = call;
} else if (event is CoordinatorConnectedEvent) {
_logger.i(() => '[onCoordinatorEvent] connected ${event.userId}');
_connectionState = ConnectionState.connected(_state.currentUser.id);
} else if (event is CoordinatorDisconnectedEvent) {
_logger.i(() => '[onCoordinatorEvent] disconnected ${event.userId}');
_connectionState = ConnectionState.disconnected(_state.currentUser.id);
} else if (event is CoordinatorReconnectedEvent) {
_logger.i(() => '[onCoordinatorEvent] reconnected ${event.userId}');
if (state.watchedCalls.value.isNotEmpty) {
// Re-watch the previously watched calls.
unawaited(
queryCalls(
watch: true,
filterConditions: {
'cid': {
r'$in': state.watchedCalls.value
.map((call) => call.callCid.value)
.toList(),
},
},
).onError((error, stackTrace) {
_logger.e(
() => '[onCoordinatorEvent] re-watching calls failed: $error',
);
return Result.failure(VideoErrors.compose(error, stackTrace));
}),
);
}
}
}
Future<void> _onAppState(LifecycleState state) async {
_logger.d(() => '[onAppState] state: $state');
try {
final activeCalls = _state.activeCalls.value;
_state.appLifecycleState.value = state;
if (state.isPaused) {
for (final activeCall in activeCalls) {
activeCall.traceSessionLog('device.stateChange', 'paused');
}
// Handle app paused state
if (activeCalls.isEmpty &&
!_options.keepConnectionsAliveWhenInBackground) {
_logger.i(() => '[onAppState] close connection');
_subscriptions.cancel(_idEvents);
await _client.closeConnection();
} else if (activeCalls.isNotEmpty) {
for (final activeCall in activeCalls) {
final callState = activeCall.state.value;
final isVideoEnabled =
callState.localParticipant?.isVideoEnabled ?? false;
final isAudioEnabled =
callState.localParticipant?.isAudioEnabled ?? false;
if (_options.muteVideoWhenInBackground && isVideoEnabled) {
await activeCall.setCameraEnabled(enabled: false);
_mutedCameraByStateChange[activeCall.callCid.value] = true;
_logger.v(() => 'Muted camera track since app was paused.');
}
if (_options.muteAudioWhenInBackground && isAudioEnabled) {
await activeCall.setMicrophoneEnabled(enabled: false);
_mutedAudioByStateChange[activeCall.callCid.value] = true;
_logger.v(() => 'Muted audio track since app was paused.');
}
}
}
} else if (state.isResumed) {
// Handle app resumed state
_logger.i(() => '[onAppState] open connection');
await _client.openConnection();
_subscriptions.add(_idEvents, _client.events.listen(_onEvent));
for (final activeCall in activeCalls) {
activeCall.traceSessionLog('device.stateChange', 'resumed');
final wasCameraMuted =
_mutedCameraByStateChange[activeCall.callCid.value] ?? false;
if (wasCameraMuted) {
await activeCall.setCameraEnabled(enabled: true);
_mutedCameraByStateChange[activeCall.callCid.value] = false;
_logger.v(() => 'Unmuted camera track since app was unpaused.');
}
final wasAudioMuted =
_mutedAudioByStateChange[activeCall.callCid.value] ?? false;
if (wasAudioMuted) {
await activeCall.setMicrophoneEnabled(enabled: true);
_mutedAudioByStateChange[activeCall.callCid.value] = false;
_logger.v(() => 'Unmuted audio track since app was unpaused.');
}
}
}
} catch (e) {
_logger.e(() => '[onAppState] failed: $e');
}
}
StreamSubscription<Call?> listenActiveCall(
void Function(Call? value)? onActiveCall,
) {
if (_options.allowMultipleActiveCalls) {
throw Exception(
'Multiple active calls are enabled, use listenActiveCalls instead',
);
}
return _state.activeCall.listen(onActiveCall);
}
StreamSubscription<List<Call>> listenActiveCalls(
void Function(List<Call> value)? onActiveCalls,
) {
return _state.activeCalls.listen(onActiveCalls);
}
Call makeCall({
required StreamCallType callType,
required String id,
CallPreferences? preferences,
}) {
return Call(
callCid: StreamCallCid.from(type: callType, id: id),
coordinatorClient: _client,
streamVideo: this,
networkMonitor: _networkMonitor,
retryPolicy: _options.retryPolicy,
sdpPolicy: _options.sdpPolicy,
preferences: preferences ?? _options.defaultCallPreferences,
);
}
Call _makeCallFromRinging({
required CallRingingData data,
CallPreferences? preferences,
}) {
return Call.fromRinging(
data: data,
coordinatorClient: _client,
streamVideo: this,
networkMonitor: _networkMonitor,
retryPolicy: _options.retryPolicy,
sdpPolicy: _options.sdpPolicy,
preferences: preferences ?? _options.defaultCallPreferences,
);
}
/// Queries the API for calls.
Future<Result<QueriedCalls>> queryCalls({
required Map<String, Object> filterConditions,
String? next,
String? prev,
int? limit,
List<SortParamRequest>? sorts,
bool? watch,
}) {
return _client.queryCalls(
filterConditions: filterConditions,
next: next,
limit: limit,
prev: prev,
sorts: sorts ?? [],
watch: watch,
);
}
/// Adds a device that will be used to receive push notifications.
Future<Result<None>> addDevice({
required String pushToken,
required PushProvider pushProvider,
String? pushProviderName,
bool? voipToken,
}) {
_logger.d(
() =>
'[addDevice] pushProvider: $pushProvider'
', pushToken: $pushToken, pushProviderName: $pushProviderName'
', voipToken: $voipToken',
);
return _client.createDevice(
id: pushToken,
pushProvider: pushProvider,
pushProviderName: pushProviderName,
voipToken: voipToken,
);
}
/// Gets a list of devices used to receive push notifications.
Future<Result<List<PushDevice>>> getDevices() {
return _client.listDevices();
}
/// Removes a device used to receive push notifications.
Future<Result<None>> removeDevice({required String pushToken}) {
_logger.d(() => '[removeDevice] pushToken: $pushToken');
return _client.deleteDevice(id: pushToken, userId: currentUser.id);
}
Future<Result<List<CallRecording>>> listRecordings(
StreamCallCid callCid,
) async {
_logger.d(() => '[listRecordings] Call $callCid');
final result = await _client.listRecordings(callCid);
_logger.v(() => '[listRecordings] result: $result');
return result;
}
StreamSubscription<T>? onRingingEvent<T extends RingingEvent>(
void Function(T event)? onEvent,
) {
final manager = pushNotificationManager;
if (manager == null) {
_logger.e(() => '[onRingingEvent] rejected (no manager)');
return null;
}
return manager.on<T>(onEvent);
}
/// This method is used to dispose the StreamVideo instance after the ringing event is resolved.
/// It is used primarily for Firebase Messaging background handler where separate isolate is used to handle the message.
///
/// [disposingCallback] is a callback that allows to perform any additional disposing operations after the ringing event is resolved.
StreamSubscription<RingingEvent>? disposeAfterResolvingRinging({
void Function()? disposingCallback,
}) {
return onRingingEvent((event) {
if (event is ActionCallAccept ||
event is ActionCallDecline ||
event is ActionCallTimeout ||
event is ActionCallEnded) {
// Delay the callback to ensure the call is fully resolved.
Future<void>.delayed(const Duration(seconds: 1), () {
disposingCallback?.call();
dispose();
});
}
});
}
Future<bool> consumeAndAcceptActiveCall({
void Function(Call)? onCallAccepted,
CallPreferences? callPreferences,
}) async {
final allCalls = await pushNotificationManager?.activeCalls();
// Only consume calls that the user explicitly accepted via the native notification UI.
final calls = allCalls?.where((c) => c.isAccepted).toList();
if (calls == null || calls.isEmpty) return false;
// Ensure the coordinator WS is connected before proceeding.
// During cold start, autoConnect may still be in progress so we need to wait for it to complete.
final connectResult = await connect();
if (connectResult.isFailure) {
_logger.e(
() =>
'[consumeAndAcceptActiveCall] failed to connect: '
'${connectResult.getErrorOrNull()}',
);
return false;
}
final callResult = await consumeIncomingCall(
uuid: calls.first.uuid!,
cid: calls.first.callCid!,
preferences: callPreferences,
);
if (callResult.isFailure) {
_logger.d(
() =>
'[consumeAndAcceptActiveCall] error consuming incoming call: '
'${callResult.getErrorOrNull()}',
);
return false;
}
final call = callResult.getDataOrNull();
if (call == null) return false;
final acceptResult = await call.accept();
if (acceptResult.isFailure) {
_logger.d(
() =>
'[consumeAndAcceptActiveCall] error accepting call: '
'${acceptResult.getErrorOrNull()}',
);
return false;
}
onCallAccepted?.call(call);
return true;
}
@Deprecated('Use observeCoreRingingEvents instead.')
CompositeSubscription observeCoreCallKitEvents({
void Function(Call)? onCallAccepted,
CallPreferences? acceptCallPreferences,
}) {
return observeCoreRingingEvents(
onCallAccepted: onCallAccepted,
acceptCallPreferences: acceptCallPreferences,
);
}
/// Helper method to observe core ringing events.
/// Should be used as soon as the app is launched when handling incoming calls.
CompositeSubscription observeCoreRingingEvents({
void Function(Call)? onCallAccepted,
CallPreferences? acceptCallPreferences,
}) {
final ringingEventSubscriptions = CompositeSubscription();
observeCallIncomingRingingEvent()?.addTo(ringingEventSubscriptions);
observeCallAcceptRingingEvent(
onCallAccepted: onCallAccepted,
acceptCallPreferences: acceptCallPreferences,
)?.addTo(ringingEventSubscriptions);
observeCallDeclinedRingingEvent()?.addTo(ringingEventSubscriptions);
observeCallEndedRingingEvent()?.addTo(ringingEventSubscriptions);
return ringingEventSubscriptions;
}
/// Helper method to observe core ringing events for background.
/// Should be used in the background handler when handling incoming calls.
CompositeSubscription observeCoreRingingEventsForBackground() {
final ringingEventSubscriptions = CompositeSubscription();
observeCallIncomingRingingEvent()?.addTo(ringingEventSubscriptions);
observeCallDeclinedRingingEvent()?.addTo(ringingEventSubscriptions);
return ringingEventSubscriptions;
}
@Deprecated('Use observeCallAcceptRingingEvent instead.')
StreamSubscription<ActionCallAccept>? observeCallAcceptCallKitEvent({
void Function(Call)? onCallAccepted,
CallPreferences? acceptCallPreferences,
}) {
return observeCallAcceptRingingEvent(
onCallAccepted: onCallAccepted,
acceptCallPreferences: acceptCallPreferences,
);
}
StreamSubscription<ActionCallAccept>? observeCallAcceptRingingEvent({
void Function(Call)? onCallAccepted,
CallPreferences? acceptCallPreferences,
}) {
return onRingingEvent<ActionCallAccept>((event) {
// Ignore call accept event when app is in detached state on Android.
// The call flow should be handled by consuming the call like in the terminated state.
if (!CurrentPlatform.isAndroid ||
_state.appLifecycleState.value != LifecycleState.detached) {
_onCallAccept(
event,
onCallAccepted: onCallAccepted,
callPreferences: acceptCallPreferences,
);
}
});
}
StreamSubscription<ActionCallIncoming>? observeCallIncomingRingingEvent() {
return onRingingEvent<ActionCallIncoming>(_onCallIncoming);
}
@Deprecated('Use observeCallDeclinedRingingEvent instead.')
StreamSubscription<ActionCallDecline>? observeCallDeclinedCallKitEvent() {
return observeCallDeclinedRingingEvent();
}
StreamSubscription<ActionCallDecline>? observeCallDeclinedRingingEvent() {
return onRingingEvent<ActionCallDecline>(_onCallDecline);
}
@Deprecated('Use observeCallEndedRingingEvent instead.')
StreamSubscription<ActionCallEnded>? observeCallEndedCallKitEvent() {
return observeCallEndedRingingEvent();
}
StreamSubscription<ActionCallEnded>? observeCallEndedRingingEvent() {
return onRingingEvent<ActionCallEnded>(_onCallEnded);
}
Future<void> _onCallAccept(
ActionCallAccept event, {
void Function(Call)? onCallAccepted,
CallPreferences? callPreferences,
}) async {
_logger.d(() => '[onCallAccept] event: $event');
final uuid = event.data.uuid;
final cid = event.data.callCid;
if (uuid == null || cid == null) return;
_cancelIncomingAutoRejectTimerByCid(cid);
final consumeResult = await consumeIncomingCall(
uuid: uuid,
cid: cid,
preferences: callPreferences,
);
if (consumeResult.isFailure) {
_logger.w(
() =>
'[onCallAccept] error consuming incoming call: ${consumeResult.getErrorOrNull()}',
);
return;
}
final callToJoin = consumeResult.getDataOrNull();
if (callToJoin == null) return;
final acceptResult = await callToJoin.accept();
if (acceptResult.isFailure) {
_logger.d(() => '[onCallAccept] error accepting call: $callToJoin');
return;
}
unawaited(callToJoin.join());
onCallAccepted?.call(callToJoin);
}
Future<void> _onCallIncoming(ActionCallIncoming event) async {
_logger.d(() => '[onCallIncoming] event: $event');
final uuid = event.data.uuid;
final cid = event.data.callCid;
if (uuid == null || cid == null) return;
final consumeResult = await consumeIncomingCall(uuid: uuid, cid: cid);
final incomingCall = consumeResult.getDataOrNull();
if (incomingCall == null) return;
final timeout = incomingCall.state.value.settings.ring.autoRejectTimeout;
_startIncomingAutoRejectTimer(incomingCall, timeout);
}
Future<void> _onCallDecline(ActionCallDecline event) async {
_logger.d(() => '[onCallDecline] event: $event');
final uuid = event.data.uuid;
final cid = event.data.callCid;
if (uuid == null || cid == null) return;
_cancelIncomingAutoRejectTimerByCid(cid);
final call = await consumeIncomingCall(uuid: uuid, cid: cid);
final callToReject = call.getDataOrNull();
if (callToReject == null) return;
final result = await callToReject.reject(
reason: CallRejectReason.decline(),
);
if (result is Failure) {
_logger.d(() => '[onCallDecline] error rejecting call: ${result.error}');
}
}
/// ActionCallEnded event is sent by native side of stream_video_push_notification package when the call is ended.
/// On iOS this is connected to CallKit and should end active call or reject incoming call.
/// On Android this is connected to push notification being dismissed.
/// When app is terminated it can be send even when accepting the call. That's why we only handle it on iOS.
Future<void> _onCallEnded(ActionCallEnded event) async {
if (CurrentPlatform.isAndroid) return;
_logger.d(() => '[onCallEnded] event: $event');
final uuid = event.data.uuid;
final cid = event.data.callCid;
if (uuid == null || cid == null) return;
_cancelIncomingAutoRejectTimerByCid(cid);
final activeCall = activeCalls.firstWhereOrNull(
(call) => call.callCid.value == cid,
);
final incomingCall = _state.incomingCall.valueOrNull;
if (activeCall?.callCid.value == cid) {