-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcall_bloc.dart
More file actions
4068 lines (3565 loc) · 172 KB
/
call_bloc.dart
File metadata and controls
4068 lines (3565 loc) · 172 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 'dart:io';
import 'package:flutter/widgets.dart' hide Notification;
import 'package:bloc/bloc.dart';
import 'package:bloc_concurrency/bloc_concurrency.dart';
import 'package:clock/clock.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_webrtc/flutter_webrtc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:logging/logging.dart';
import 'package:async/async.dart';
import 'package:webtrit_api/webtrit_api.dart';
import 'package:webtrit_callkeep/webtrit_callkeep.dart';
import 'package:webtrit_phone/mappers/signaling/signaling.dart';
import 'package:webtrit_signaling/webtrit_signaling.dart';
import 'package:webtrit_phone/app/constants.dart';
import 'package:webtrit_phone/app/notifications/notifications.dart';
import 'package:webtrit_phone/extensions/extensions.dart';
import 'package:webtrit_phone/models/models.dart';
import 'package:webtrit_phone/push_notification/push_notifications.dart';
import 'package:webtrit_phone/repositories/repositories.dart';
import 'package:webtrit_phone/utils/utils.dart';
import 'package:webtrit_signaling_service/webtrit_signaling_service.dart';
import '../extensions/extensions.dart';
import '../models/models.dart';
import '../services/services.dart';
import '../utils/utils.dart';
export 'package:webtrit_callkeep/webtrit_callkeep.dart' show CallkeepHandle, CallkeepHandleType;
part 'call_bloc.freezed.dart';
part 'call_event.dart';
part 'call_state.dart';
const int _kUndefinedLine = -1;
final _logger = Logger('CallBloc');
/// A callback function type for handling diagnostic reports for call request errors.
/// It takes the [callId] of the failed call and the specific [CallkeepCallRequestError]
/// as parameters, allowing for detailed error logging or reporting.
typedef OnDiagnosticReportRequested = void Function(String callId, CallkeepCallRequestError error);
/// Callback triggered when the signaling session is determined to be invalid
/// (e.g., session revoked remotely, expired, or deleted), requiring a forced
/// application-level logout to resolve the state.
typedef SignalingSessionInvalidatedCallback = void Function();
const _getUserMediaPushKitTimeout = Duration(seconds: 8);
class CallBloc extends Bloc<CallEvent, CallState> with WidgetsBindingObserver implements CallkeepDelegate {
final CallLogsRepository callLogsRepository;
final LocalPushRepository localPushRepository;
final UserRepository userRepository;
final LinesStateRepository linesStateRepository;
final PresenceInfoRepository presenceInfoRepository;
final DialogInfoRepository dialogInfoRepository;
final PresenceSettingsRepository presenceSettingsRepository;
final QueuedTerminationRequestsRepository queuedTerminationRequestsRepository;
final Function(Notification) submitNotification;
/// Callback invoked when the signaling client reports a critical session error
/// (e.g. [SignalingDisconnectCode.sessionMissedError]), indicating the
/// current session is no longer valid on the server.
final SignalingSessionInvalidatedCallback onSessionInvalidated;
final Callkeep callkeep;
final CallkeepConnections callkeepConnections;
late final CallMediaManager _mediaManager;
final SDPMunger? sdpMunger;
final SdpSanitizer? sdpSanitizer;
final WebrtcOptionsBuilder? webRtcOptionsBuilder;
final IceFilter? iceFilter;
final UserMediaBuilder userMediaBuilder;
final PeerConnectionPolicyApplier? peerConnectionPolicyApplier;
final ContactNameResolver contactNameResolver;
final CallErrorReporter callErrorReporter;
final bool sendPresenceSettings;
final VoidCallback? onCallEnded;
final OnDiagnosticReportRequested onDiagnosticReportRequested;
StreamSubscription<List<ConnectivityResult>>? _connectivityChangedSubscription;
StreamSubscription<void>? _foregroundCallPushSubscription;
final _iceRestartDebounce = DebounceMap<String>(const Duration(seconds: 2));
late final SignalingModule _signalingModule;
late final StreamSubscription<SignalingModuleEvent> _signalingSubscription;
late final SignalingReconnectController _reconnectController;
Timer? _presenceInfoSyncTimer;
late final PeerConnectionManager _peerConnectionManager;
final Map<String, RenegotiationHandler> _renegotiationHandlers = {};
late final HandshakeProcessor _handshakeProcessor;
final _callkeepSound = WebtritCallkeepSound();
CallBloc({
required this.callLogsRepository,
required this.localPushRepository,
required this.linesStateRepository,
required this.presenceInfoRepository,
required this.dialogInfoRepository,
required this.presenceSettingsRepository,
required this.queuedTerminationRequestsRepository,
required this.onSessionInvalidated,
required this.userRepository,
required this.submitNotification,
required this.callkeep,
required this.callkeepConnections,
required this.userMediaBuilder,
required this.contactNameResolver,
required this.callErrorReporter,
required this.sendPresenceSettings,
required this.onDiagnosticReportRequested,
this.sdpMunger,
this.sdpSanitizer,
this.webRtcOptionsBuilder,
this.iceFilter,
this.peerConnectionPolicyApplier,
required SignalingModule signalingModule,
required PeerConnectionManager peerConnectionManager,
this.onCallEnded,
Stream<void>? foregroundCallPushSignal,
}) : super(const CallState()) {
_mediaManager = CallMediaManager(callkeep: callkeep);
_signalingModule = signalingModule;
_peerConnectionManager = peerConnectionManager;
_handshakeProcessor = HandshakeProcessor(
callkeepConnections: callkeepConnections,
queuedTerminationRequestsRepository: queuedTerminationRequestsRepository,
);
_reconnectController = SignalingReconnectController(
signalingModule: signalingModule,
onConnectionFailed: _handleConnectionFailed,
onConnectionPresenceChanged: (isAvailable) =>
_logger.info('signaling presence changed: isAvailable=$isAvailable'),
);
_foregroundCallPushSubscription = foregroundCallPushSignal?.listen(
(_) => _reconnectController.notifyForceReconnect(),
);
// Translates SignalingModule events into BLoC state-transition events.
// Reconnect scheduling and notification decisions are fully handled by
// [_reconnectController] — this listener only drives [CallState] changes.
_signalingSubscription = _signalingModule.events.listen((event) {
switch (event) {
case SignalingConnecting():
add(const _SignalingClientEvent.connecting());
case SignalingConnected():
add(const _SignalingClientEvent.connected());
case SignalingConnectionFailed(:final error):
add(_SignalingClientEvent.failed(error));
case SignalingDisconnecting():
add(const _SignalingClientEvent.disconnecting());
case SignalingDisconnected(:final code, :final reason):
add(_SignalingClientEvent.disconnected(code, reason));
case SignalingHandshakeReceived(:final handshake):
_handleHandshakeReceived(handshake);
case SignalingProtocolEvent(:final event):
_handleSignalingEvent(event);
}
});
on<CallStarted>(_onCallStarted, transformer: sequential());
on<_AppLifecycleStateChanged>(_onAppLifecycleStateChanged, transformer: sequential());
on<_ConnectivityResultChanged>(_onConnectivityResultChanged, transformer: sequential());
on<_NavigatorMediaDevicesChange>(_onNavigatorMediaDevicesChange, transformer: debounce());
on<_IceRestartTriggered>(_onIceRestartTriggered, transformer: sequential());
on<_RegistrationChange>(_onRegistrationChange, transformer: droppable());
on<_ResetStateEvent>(_onResetStateEvent, transformer: droppable());
on<_SignalingClientEvent>(_onSignalingClientEvent, transformer: restartable());
on<_HandshakeSignalingEventState>(_onHandshakeSignalingEventState, transformer: sequential());
on<_CallSignalingEvent>(_onCallSignalingEvent, transformer: sequential());
on<_CallPushEventIncoming>(_onCallPushEventIncoming, transformer: sequential());
on<_RestoreAcceptedCall>(_onRestoreAcceptedCall, transformer: sequential());
on<CallControlEvent>(
_onCallControlEvent,
transformer: (events, mapper) => StreamGroup.merge([
droppable<CallControlEvent>().call(events.where((e) => e is _CallControlEventStarted), mapper),
sequential<CallControlEvent>().call(events.where((e) => e is! _CallControlEventStarted), mapper),
]),
);
on<_CallPerformEvent>(_onCallPerformEvent, transformer: sequential());
on<_PeerConnectionEvent>(_onPeerConnectionEvent, transformer: sequential());
on<CallScreenEvent>(_onCallScreenEvent, transformer: sequential());
on<CallConfigEvent>(_onConfigEvent, transformer: sequential());
on<_GlobalEvent>(_onGlobalEvent, transformer: sequential());
on<_CallMutationEvent>(_onCallMutationEvent, transformer: sequential());
navigator.mediaDevices.ondevicechange = (event) {
add(const _NavigatorMediaDevicesChange());
};
WidgetsBinding.instance.addObserver(this);
callkeep.setDelegate(this);
if (sendPresenceSettings) {
_presenceInfoSyncTimer = Timer.periodic(const Duration(seconds: 5), (_) => syncPresenceSettings());
}
}
@override
Future<void> close() async {
callkeep.setDelegate(null);
WidgetsBinding.instance.removeObserver(this);
navigator.mediaDevices.ondevicechange = null;
await _connectivityChangedSubscription?.cancel();
await _foregroundCallPushSubscription?.cancel();
_reconnectController.dispose();
_presenceInfoSyncTimer?.cancel();
_iceRestartDebounce.dispose();
await _signalingSubscription.cancel();
await _stopRingbackSound();
for (final activeCall in state.activeCalls) {
await _releaseLocalStream(activeCall.localStream);
}
await _peerConnectionManager.dispose();
_clearRenegotiationHandlers();
await super.close();
}
@override
void onError(Object error, StackTrace stackTrace) {
super.onError(error, stackTrace);
_logger.warning('onError', error, stackTrace);
// TODO: analise error and finalize necessary active call
}
@override
void onChange(Change<CallState> change) {
super.onChange(change);
// TODO: add detailed explanation of the following code and why it is necessary to initialize signaling client in background
if (change.currentState.isActive != change.nextState.isActive) {
final appLifecycleState = change.nextState.currentAppLifecycleState;
final appInactive =
appLifecycleState == AppLifecycleState.paused ||
appLifecycleState == AppLifecycleState.detached ||
appLifecycleState == AppLifecycleState.inactive;
final hasActiveCalls = change.nextState.isActive;
final connected = _signalingModule.isConnected;
if (appInactive) {
_reconnectController.notifyHasActiveCalls(hasActiveCalls: hasActiveCalls);
if (hasActiveCalls && !connected) {
_reconnectController.notifyForceReconnect();
}
if (!hasActiveCalls && connected) {
_reconnectController.notifyAppPaused(hasActiveCalls: false);
}
}
}
final currentActiveCallUuids = Set.from(change.currentState.activeCalls.map((e) => e.callId));
_logger.fine('onChange currentActiveCallUuids: $currentActiveCallUuids');
final nextActiveCallUuids = Set.from(change.nextState.activeCalls.map((e) => e.callId));
_logger.fine('onChange nextActiveCallUuids: $nextActiveCallUuids');
for (final removeUuid in currentActiveCallUuids.difference(nextActiveCallUuids)) {
_clearRenegotiationHandler(removeUuid);
// Disposal is intentionally not awaited to avoid blocking the Bloc processing loop.
// The PeerConnectionManager implements an internal "disposal barrier" (via _pendingDisposals)
// which guarantees that any subsequent createPeerConnection() for this CallId will
// automatically wait for this disposal to finish before proceeding.
_peerConnectionManager.disposePeerConnection(removeUuid).catchError((error, stackTrace) {
_logger.warning('Error disposing peer connection for $removeUuid', error, stackTrace);
});
}
for (final addUuid in nextActiveCallUuids.difference(currentActiveCallUuids)) {
_peerConnectionManager.add(addUuid);
}
final currentProcessingStatuses = Set.from(
change.currentState.activeCalls.map((e) => '${e.line}:${e.processingStatus.name}'),
).join(', ');
final nextProcessingStatuses = Set.from(
change.nextState.activeCalls.map((e) => '${e.line}:${e.processingStatus.name}'),
).join(', ');
if (currentProcessingStatuses != nextProcessingStatuses) {
_logger.info(() => 'status transitions: $currentProcessingStatuses -> $nextProcessingStatuses');
}
/// RegistrationStatus can be null if the signaling state
/// was not yet fully initialized. In this case, RegistrationStatus was made nullable to indicate that signaling has not been initialized yet.
///
/// This scenario is particularly relevant when a call is triggered before the app
/// is fully active, such as via [CallkeepDelegate.continueStartCallIntent]
/// (e.g., from phone recents).
final newRegistration = change.nextState.callServiceState.registration;
final previousRegistration = change.currentState.callServiceState.registration;
if (newRegistration != previousRegistration && newRegistration != null) {
_logger.fine('_onRegistrationChange: $newRegistration to $previousRegistration');
final newRegistrationStatus = newRegistration.status;
final previousRegistrationStatus = previousRegistration?.status;
if (previousRegistrationStatus?.isRegistered == false && newRegistrationStatus.isRegistered == true) {
presenceSettingsRepository.resetLastSettingsSync();
// submitNotification(AppOnlineNotification());
}
if (previousRegistrationStatus?.isRegistered == true && newRegistrationStatus.isRegistered == false) {
// submitNotification(AppOfflineNotification());
}
if (newRegistrationStatus.isFailed == true || newRegistrationStatus.isUnregistered == true) {
add(const _ResetStateEvent.completeCalls());
}
if (newRegistrationStatus.isFailed == true) {
_logger.severe('Registration failed - code: ${newRegistration.code}, reason: ${newRegistration.reason}');
final knownCode = SignalingRegistrationFailedCode.values.byCode(newRegistration.code);
if (knownCode != SignalingRegistrationFailedCode.sipServerUnavailable) {
// TODO?: maybe not skip serviceUnavaliable error recodring,
// skipping for maintance windows is ok, but if this error happens in the wild it can be a sign of a bigger issue that we want to be aware
CrashlyticsUtils.recordError(
'CallBloc.Registration failed - code: ${newRegistration.code}, reason: ${newRegistration.reason}',
information: [
'newRegistration.code: ${newRegistration.code}',
'newRegistration.reason: ${newRegistration.reason}',
'newRegistration.status: ${newRegistration.status}',
'previousRegistration?.code: ${previousRegistration?.code}',
'previousRegistration?.reason: ${previousRegistration?.reason}',
'previousRegistration?.status: ${previousRegistration?.status}',
],
);
}
}
}
linesStateRepository.setState(change.nextState.toLinesState());
_handleSignalingSessionError(
previous: change.currentState.callServiceState,
current: change.nextState.callServiceState,
);
if (change.nextState.activeCalls.length < change.currentState.activeCalls.length) {
onCallEnded?.call();
}
/// Manages global side effects triggered by call lifecycle transitions.
/// Key responsibility:
/// - **iOS Audio Reset:** On the start of the *first* call, it forces the
/// audio route back to the Receiver (Earpiece). This prevents the "sticky speaker"
/// issue where iOS remembers the Speaker output from a previous session.
_handleCallLifecycleTransitions(
previousCalls: change.currentState.activeCalls,
currentCalls: change.nextState.activeCalls,
);
}
/// Analyzes changes in the active call list to trigger specific lifecycle hooks.
///
/// This method identifies keys transitions:
/// * **First Call Started (`0 -> 1`):** A cold start of the calling session.
/// Crucial for initializing hardware resources (e.g., resetting speaker output on iOS).
/// * **Last Call Ended (`N -> 0`):** The termination of the calling session.
/// Used for global cleanup and resource release.
void _handleCallLifecycleTransitions({
required List<ActiveCall> previousCalls,
required List<ActiveCall> currentCalls,
}) {
final wasEmpty = previousCalls.isEmpty;
final isEmpty = currentCalls.isEmpty;
// First call started (0 → 1).
if (wasEmpty && !isEmpty) unawaited(_mediaManager.setSpeaker(enabled: false));
// Last call ended (N → 0).
if (!wasEmpty && isEmpty) {
unawaited(_mediaManager.setSpeaker(enabled: false));
_mediaManager.clearCommunicationDevice();
}
}
/// Reacts to mid-call video state transitions and adjusts audio routing.
///
/// Only handles transitions for EXISTING calls (prevCall != null).
/// Called once after getUserMedia completes for a video call.
///
/// At this point AudioSwitch has been activated (getUserMedia triggers
/// AudioSwitchManager.start → activate) and the PhoneConnection exists
/// in Telecom, so setAudioDevice can route to speaker safely.
Future<void> _onVideoStreamReady(String callId) async {
final call = state.retrieveActiveCall(callId);
if (call?.video == true) {
await _mediaManager.onVideoEnabled(callId, speakerDevice: state.availableAudioDevices.getSpeaker);
}
}
void _handleConnectionFailed(SignalingFailureInfo failure) {
final (:knownCode, :systemCode, :systemReason) = failure;
// Skip logging and notification for expected disconnect scenarios that trigger automatic reconnects without user impact.
switch (knownCode) {
case SignalingDisconnectCode.signalingKeepaliveTimeoutError:
case SignalingDisconnectCode.controllerForceAttachClose:
case SignalingDisconnectCode.appUnregisteredError:
// Expected silent reconnect: keepalive timeout on lock-screen, duplicate-session
// cleanup, or SIP unregistration after the user toggles Online off.
_logger.fine('onConnectionFailed: silent reconnect for code=$knownCode');
return;
case SignalingDisconnectCode.controllerUnknownError:
// controllerUnknownError (4400): the server-side Controller process died because
// the Janus connection went down. The new WebSocket timed out (GenServer.call,
// 5s default) waiting for the Controller to finish re-initializing (new Janus
// session + SIP registration). The Controller continues initializing in the
// background — the next reconnect attempt will succeed once it is ready.
//
// Silent reconnect: no user-visible notification needed.
_logger.warning('onConnectionFailed: silent reconnect for code=$knownCode');
return;
default:
break;
}
// Record unexpected disconnects with as much detail as possible to facilitate debugging and resolution.
//
// If you encounter a new disconnect code in the wild, add it to the above switch statement
// and monitor its frequency and impact before deciding whether to log it as a warning or fine level.
_logger.severe('onConnectionFailed: $failure');
CrashlyticsUtils.recordError(
'CallBloc - onConnectionFailed ${knownCode?.name ?? 'unknown code'}',
information: ['knownCode: $knownCode', 'systemCode: $systemCode', 'systemReason: $systemReason'],
);
}
void _handleSignalingSessionError({required CallServiceState previous, required CallServiceState current}) {
final signalingChanged =
previous.signalingClientStatus != current.signalingClientStatus ||
previous.lastSignalingDisconnectCode != current.lastSignalingDisconnectCode;
if (!signalingChanged) return;
if (current.signalingClientStatus == SignalingClientStatus.disconnect &&
current.lastSignalingDisconnectCode is int) {
final code = SignalingDisconnectCode.values.byCode(current.lastSignalingDisconnectCode as int);
if (code == SignalingDisconnectCode.sessionMissedError) {
_logger.info('Signaling session listener: session is missing ${current.lastSignalingDisconnectCode}');
unawaited(_notifyAccountErrorSafely());
onSessionInvalidated();
}
}
}
// TODO: Consider moving this method to a separate repository
Future<void> _notifyAccountErrorSafely() async {
try {
await userRepository.getRemoteInfo();
} on RequestFailure catch (e) {
final errorCode = AccountErrorCode.values.firstWhereOrNull((it) => it.value == e.error?.code);
switch (errorCode) {
case AccountErrorCode.passwordChangeRequired:
_logger.info('Account session revoked');
submitNotification(const SelfCarePasswordExpiredNotification());
break;
default:
_logger.warning('Account error code: $errorCode');
break;
}
} catch (e, st) {
_logger.warning('Unexpected error during account info refresh', e, st);
}
}
//
Future<void> _onCallStarted(CallStarted event, Emitter<CallState> emit) async {
// Initialize app lifecycle state
final lifecycleState = WidgetsFlutterBinding.ensureInitialized().lifecycleState;
emit(state.copyWith(currentAppLifecycleState: lifecycleState));
_logger.fine('_onCallStarted initial lifecycle state: $lifecycleState');
// Initialize connectivity state
final connectivityState = (await Connectivity().checkConnectivity()).first;
emit(
state.copyWith(
callServiceState: state.callServiceState.copyWith(networkStatus: connectivityState.toNetworkStatus()),
),
);
_logger.finer('_onCallStarted initial connectivity state: $connectivityState');
// Subscribe to future connectivity changes
_connectivityChangedSubscription = Connectivity().onConnectivityChanged.listen((result) {
final currentConnectivityResult = result.first;
add(_ConnectivityResultChanged(currentConnectivityResult));
});
if (connectivityState == ConnectivityResult.none) {
_reconnectController.notifyNetworkUnavailable();
} else {
_reconnectController.notifyNetworkAvailable();
}
WebRTC.initialize(options: webRtcOptionsBuilder?.build());
}
Future<void> _onAppLifecycleStateChanged(_AppLifecycleStateChanged event, Emitter<CallState> emit) async {
final appLifecycleState = event.state;
_logger.fine('_onAppLifecycleStateChanged: $appLifecycleState');
emit(state.copyWith(currentAppLifecycleState: appLifecycleState));
if (appLifecycleState == AppLifecycleState.paused || appLifecycleState == AppLifecycleState.detached) {
_reconnectController.notifyAppPaused(hasActiveCalls: state.isActive);
} else if (appLifecycleState == AppLifecycleState.resumed) {
_reconnectController.notifyAppResumed();
}
}
Future<void> _onConnectivityResultChanged(_ConnectivityResultChanged event, Emitter<CallState> emit) async {
final connectivityResult = event.result;
_logger.fine('_onConnectivityResultChanged: $connectivityResult');
if (connectivityResult == ConnectivityResult.none) {
_reconnectController.notifyNetworkUnavailable();
} else {
_reconnectController.notifyNetworkAvailable();
// Restart ICE for all active calls to trigger faster recovery from connectivity loss.
//
// - in network loss scenario restarts RTP from almost imediately compating to built-in WebRTC connectivity checks which can take around 10-20 seconds
// - in double network scenario (e.g already has mobile network, but also connected to wifi)
// it helps to switch to better network instead of staying on old until rtp breaks.
//
// ICE restart is debounced to allow the new network interface (e.g. VPN tunnel) to fully
// initialize before probing starts. Calling restartIce() immediately after onConnectivityChanged
// can cause ICE failure because the interface is registered but not yet ready to carry traffic.
for (var activeCall in state.activeCalls) {
if (!activeCall.processingStatus.hasPeerConnectionReady) {
_logger.info(
'_onConnectivityResultChanged: skipping ICE restart for call ${activeCall.callId} — PC not ready (status: ${activeCall.processingStatus})',
);
continue;
}
_logger.info(
'_onConnectivityResultChanged: scheduling ICE restart for call ${activeCall.callId} (status: ${activeCall.processingStatus})',
);
_scheduleIceRestart(activeCall.callId);
}
}
emit(
state.copyWith(
callServiceState: state.callServiceState.copyWith(networkStatus: connectivityResult.toNetworkStatus()),
),
);
}
Future<void> _onNavigatorMediaDevicesChange(_NavigatorMediaDevicesChange event, Emitter<CallState> emit) async {
if (Platform.isIOS) {
// Cleanup devices info if change happened after hangup
// to avoid presenting stale data on next call initialization
if (state.activeCalls.isEmpty) return emit(state.copyWith(availableAudioDevices: [], audioDevice: null));
final devices = await navigator.mediaDevices.enumerateDevices();
final output = devices.where((d) => d.kind == 'audiooutput').toList();
final input = devices.where((d) => d.kind == 'audioinput').toList();
_logger.info('Devices change - out:${output.map((e) => e.str).toList()}, in:${input.map((e) => e.str).toList()}');
final available = [
CallAudioDevice(type: CallAudioDeviceType.speaker),
...input.map(CallAudioDevice.fromMediaInput),
];
CallAudioDevice current;
if (output.isNotEmpty) {
current = CallAudioDevice.fromMediaOutput(output.first);
} else {
// Fallback behavior for iOS when out:[]
// We prioritize the Earpiece (Receiver) if available (derived from MicrophoneBuiltIn),
// otherwise fallback to the first available device (which is Speaker based on the list above).
current = available.firstWhere(
(device) => device.type == CallAudioDeviceType.earpiece,
orElse: () => available.first,
);
_logger.warning(
'No "audiooutput" devices reported. Fallback selected: ${current.name} (type: ${current.type})',
);
}
emit(state.copyWith(availableAudioDevices: available, audioDevice: current));
}
}
// processing the registration event change
Future<void> _onRegistrationChange(_RegistrationChange event, Emitter<CallState> emit) async {
emit(state.copyWith(callServiceState: state.callServiceState.copyWith(registration: event.registration)));
}
// processing the handling of the app state
Future<void> _onResetStateEvent(_ResetStateEvent event, Emitter<CallState> emit) {
return switch (event) {
_ResetStateEventCompleteCalls() => __onResetStateEventCompleteCalls(event, emit),
_ResetStateEventCompleteCall() => __onResetStateEventCompleteCall(event, emit),
};
}
Future<void> __onResetStateEventCompleteCalls(_ResetStateEventCompleteCalls event, Emitter<CallState> emit) async {
_logger.warning('__onResetStateEventCompleteCalls: ${state.activeCalls}');
for (var element in state.activeCalls) {
add(_ResetStateEvent.completeCall(element.callId));
}
}
Future<void> __onResetStateEventCompleteCall(_ResetStateEventCompleteCall event, Emitter<CallState> emit) async {
_logger.warning('__onResetStateEventCompleteCall: ${event.callId}');
_iceRestartDebounce.cancel(event.callId);
await _stopRingbackSound();
try {
emit(
state.copyWithMappedActiveCall(event.callId, (activeCall) {
return activeCall.copyWith(processingStatus: CallProcessingStatus.disconnecting);
}),
);
await state.performOnActiveCall(event.callId, (activeCall) async {
// Dispose the peer connection first. If it was already completed with an error
// (e.g. UserMediaError in the answer path), disposePeerConnection may throw.
// Wrap it so that callkeep notification and stream release always run.
try {
await _peerConnectionManager.disposePeerConnection(activeCall.callId);
} catch (e) {
_logger.warning('__onResetStateEventCompleteCall: disposePeerConnection error $e');
}
await callkeep.reportEndCall(
activeCall.callId,
activeCall.displayName ?? activeCall.handle.value,
event.endReason,
);
await _releaseLocalStream(activeCall.localStream);
});
emit(state.copyWithPopActiveCall(event.callId));
} catch (e) {
_logger.warning('__onResetStateEventCompleteCall: $e');
}
}
// processing signaling client events
Future<void> _onSignalingClientEvent(_SignalingClientEvent event, Emitter<CallState> emit) {
return switch (event) {
_SignalingClientEventConnecting() => __onSignalingClientEventConnecting(event, emit),
_SignalingClientEventConnected() => __onSignalingClientEventConnected(event, emit),
_SignalingClientEventFailed() => __onSignalingClientEventFailed(event, emit),
_SignalingClientEventDisconnecting() => __onSignalingClientEventDisconnecting(event, emit),
_SignalingClientEventDisconnected() => __onSignalingClientEventDisconnected(event, emit),
};
}
Future<void> __onSignalingClientEventConnecting(
_SignalingClientEventConnecting event,
Emitter<CallState> emit,
) async {
emit(
state.copyWith(
callServiceState: state.callServiceState.copyWith(
signalingClientStatus: SignalingClientStatus.connecting,
lastSignalingClientConnectError: null,
lastSignalingClientDisconnectError: null,
lastSignalingDisconnectCode: null,
),
),
);
}
Future<void> __onSignalingClientEventConnected(_SignalingClientEventConnected event, Emitter<CallState> emit) async {
// Renegotiate active calls if there was reconnect
//
// Important to do in case if there was connection loss for a while and then webrtc detects network loss and restarts ice e.g
// user turn off all network interfaces >> __onPeerConnectionEventIceConnectionStateChanged >> RTCIceConnectionStateFailed >> peerConnection.restartIce() >> onRenegotiationNeeded >> _safeRenegotiate >> if(!signalingConnected) return;
// user turn on network interfaces >> _onSignalingClientEventConnected >> safeRenegotiate
for (final call in state.activeCalls.where((c) => c.processingStatus == CallProcessingStatus.connected)) {
_logger.warning('__onSignalingClientEventConnected: triggering safe renegotiation for call ${call.callId}');
add(_CallMutationEvent.renegotiate(call.callId, call.line));
}
emit(
state.copyWith(
callServiceState: state.callServiceState.copyWith(
signalingClientStatus: SignalingClientStatus.connect,
lastSignalingClientConnectError: null,
lastSignalingDisconnectCode: null,
),
),
);
}
Future<void> __onSignalingClientEventFailed(_SignalingClientEventFailed event, Emitter<CallState> emit) async {
if (emit.isDone) return;
emit(
state.copyWith(
callServiceState: state.callServiceState.copyWith(
signalingClientStatus: SignalingClientStatus.failure,
lastSignalingClientConnectError: event.error,
),
),
);
}
Future<void> __onSignalingClientEventDisconnecting(
_SignalingClientEventDisconnecting event,
Emitter<CallState> emit,
) async {
emit(
state.copyWith(
callServiceState: state.callServiceState.copyWith(
signalingClientStatus: SignalingClientStatus.disconnecting,
lastSignalingClientConnectError: null,
),
),
);
}
Future<void> __onSignalingClientEventDisconnected(
_SignalingClientEventDisconnected event,
Emitter<CallState> emit,
) async {
final code = SignalingDisconnectCode.values.byCode(event.code ?? -1);
// Notification decisions are handled by SignalingReconnectController via its
// onConnectionFailed callback. This method only updates [CallState].
CallState newState = state.copyWith(
callServiceState: state.callServiceState.copyWith(
signalingClientStatus: SignalingClientStatus.disconnect,
lastSignalingDisconnectCode: event.code,
),
);
if (code == SignalingDisconnectCode.appUnregisteredError) {
add(const _CallSignalingEvent.registration(RegistrationStatus.unregistered));
} else if (code == SignalingDisconnectCode.requestCallIdError) {
state.activeCalls.where((e) => e.wasHungUp).forEach((e) => add(_ResetStateEvent.completeCall(e.callId)));
} else if (code == SignalingDisconnectCode.controllerExitError) {
_logger.info('__onSignalingClientEventDisconnected: skipping expected system unregistration notification');
} else if (code == SignalingDisconnectCode.signalingKeepaliveTimeoutError) {
// Keepalive timeout while backgrounded (Android network restrictions).
// Keep lastSignalingDisconnectCode null so connectIssue is never shown.
newState = state.copyWith(
callServiceState: state.callServiceState.copyWith(
signalingClientStatus: SignalingClientStatus.disconnect,
lastSignalingDisconnectCode: null,
),
);
} else if (code == SignalingDisconnectCode.controllerForceAttachClose) {
// Server closed the connection because a duplicate signaling session was detected
// (e.g. background push isolate still connected when main engine reconnects).
// Keep lastSignalingDisconnectCode null so connectIssue is never shown.
_logger.warning(
'__onSignalingClientEventDisconnected: signaling race detected - '
'server force-closed duplicate session (code=${event.code}, reason="${event.reason}").',
);
newState = state.copyWith(
callServiceState: state.callServiceState.copyWith(
signalingClientStatus: SignalingClientStatus.disconnect,
lastSignalingDisconnectCode: null,
),
);
} else if (code == SignalingDisconnectCode.controllerUnknownError) {
// Server-side transient state after long inactivity or multi-device reconnect.
// The subsequent reconnect resolves it; keep lastSignalingDisconnectCode null
// so connectIssue status is never shown to the user.
_logger.warning(
'__onSignalingClientEventDisconnected: transient controllerUnknownError - '
'silent reconnect (code=${event.code}, reason="${event.reason}").',
);
newState = state.copyWith(
callServiceState: state.callServiceState.copyWith(
signalingClientStatus: SignalingClientStatus.disconnect,
lastSignalingDisconnectCode: null,
),
);
} else if (code.type == SignalingDisconnectCodeType.auxiliary) {
/// Fun facts
/// - in case of network disconnection on android this section is evaluating faster than [_onConnectivityResultChanged].
/// - also in case of network disconnection error code is protocolError instead of normalClosure by unknown reason
/// so we need to handle it here as regular disconnection
_logger.info('__onSignalingClientEventDisconnected: socket goes down');
}
emit(newState);
}
// processing call push events
Future<void> _onCallPushEventIncoming(_CallPushEventIncoming event, Emitter<CallState> emit) async {
final eventError = event.error;
if (eventError != null) {
// iOS only: CXProvider rejected the incoming call registration before it was
// ever presented to the user (e.g. DND / Focus active, Call Directory blocklist,
// missing VoIP entitlement, or unexpected CXProvider failure).
//
// Consequences:
// - performEndCall will NOT fire (CallKit never registered the call).
// - _signalingModule is very likely disconnected: VoIP push wakes the app
// before the WebSocket is established, so the CXProvider completion fires
// before signaling reconnects.
//
// Recovery path: when signaling reconnects the server replays the incoming
// call event via the handshake. HandshakeProcessor generates a
// HandleIncomingCallAction for the unknown callId, which re-enters
// __onCallSignalingEventIncoming. At that point we have the SIP line and
// can send a DeclineRequest immediately (see that method below).
_logger.warning(
'_onCallPushEventIncoming: OS rejected call registration '
'(callId: ${event.callId}, error: $eventError) — server will be notified on next handshake',
);
return;
}
final contactName = await contactNameResolver.resolveWithNumber(event.handle.value);
final displayName = contactName ?? (event.displayName?.isEmpty == true ? null : event.displayName);
// Re-check after the async gap: the signaling path may have created an entry
// for this callId while contact resolution was in progress.
if (state.activeCalls.any((c) => c.callId == event.callId)) {
_logger.fine(
'_onCallPushEventIncoming: callId ${event.callId} handled during contact resolution - skipping push duplicate',
);
return;
}
emit(
state.copyWithPushActiveCall(
ActiveCall(
direction: CallDirection.incoming,
line: _kUndefinedLine,
callId: event.callId,
handle: event.handle,
displayName: displayName,
video: event.video,
createdTime: clock.now(),
processingStatus: CallProcessingStatus.incomingFromPush,
),
),
);
// Replace the display name in Callkeep if it differs from the one in the event
// mostly needed for ios, coz android can do it on background fcm isolate directly before push
// TODO:
// - do it on backend side same as for messaging
// currently push notification contain display name from sip header
if (displayName != event.displayName) {
await callkeep.reportUpdateCall(event.callId, displayName: displayName);
}
// Function to verify speaker availability for the upcoming event, ensuring the speaker button is correctly enabled or disabled
add(const _NavigatorMediaDevicesChange());
// the rest logic implemented within _onSignalingStateHandshake on IncomingCallEvent from call logs processing
}
// processing handshake signaling events
Future<void> _onHandshakeSignalingEventState(_HandshakeSignalingEventState event, Emitter<CallState> emit) async {
emit(state.copyWith(linesCount: event.linesCount));
add(_RegistrationChange(registration: event.registration));
}
// processing call signaling events
Future<void> _onCallSignalingEvent(_CallSignalingEvent event, Emitter<CallState> emit) {
return switch (event) {
_CallSignalingEventIncoming() => __onCallSignalingEventIncoming(event, emit),
_CallSignalingEventRinging() => __onCallSignalingEventRinging(event, emit),
_CallSignalingEventProgress() => __onCallSignalingEventProgress(event, emit),
_CallSignalingEventAccepted() => __onCallSignalingEventAccepted(event, emit),
_CallSignalingEventHangup() => __onCallSignalingEventHangup(event, emit),
_CallSignalingEventUpdating() => __onCallSignalingEventUpdating(event, emit),
_CallSignalingEventCallUpdating() => __onCallSignalingEventCallUpdating(event, emit),
_CallSignalingEventUpdated() => __onCallSignalingEventUpdated(event, emit),
_CallSignalingEventTransfer() => __onCallSignalingEventTransfer(event, emit),
_CallSignalingEventTransferring() => __onCallSignalingEventTransfering(event, emit),
_CallSignalingEventNotifyRefer() => __onCallSignalingEventNotifyRefer(event, emit),
_CallSignalingEventNotifyUnknown() => __onCallSignalingEventNotifyUnknown(event, emit),
_CallSignalingEventRegistration() => __onCallSignalingEventRegistration(event, emit),
_CallSignalingEventCallError() => __onCallSignalingEventCallError(event, emit),
};
}
// processing global events
Future<void> _onGlobalEvent(_GlobalEvent event, Emitter<CallState> emit) {
return switch (event) {
_GlobalEventNumberPresenceUpdate() => __onGlobalEventNumberPresenceUpdate(event, emit),
_GlobalEventNumberDialogsUpdate() => __onGlobalEventNumberDialogsUpdate(event, emit),
};
}
/// Handles incoming call offer.
///
/// - Creates a new full [ActiveCall] with offer and line.
/// - Or enriches existing [ActiveCall] with line and offer if
/// its placed by push [__onCallPushEventIncoming] before the signaling was initialized.
///
/// - continues in [__onCallControlEventAnswered], [__onCallPerformEventAnswered] or [__onCallControlEventEnded], [__onCallPerformEventEnded]
///
/// Be aware the answering intent can be submitted before the full [ActiveCall].
/// So the answering method [__onCallPerformEventAnswered] will wait until offer and line is assigned
/// to the [ActiveCall] by logic below, do not change status in that case.
Future<void> __onCallSignalingEventIncoming(_CallSignalingEventIncoming event, Emitter<CallState> emit) async {
_logger.infoPretty(event.jsep?.sdp, tag: '__onCallSignalingEventIncoming');
final handle = CallkeepHandle.number(event.caller);
final contactName = await contactNameResolver.resolveWithNumber(handle.value);
final displayName = contactName ?? (event.callerDisplayName?.isEmpty == true ? null : event.callerDisplayName);
final activeCallWithSameId = state.retrieveActiveCall(event.callId);
// Skip the "call to myself" check when the existing call was registered via push
// with an undefined line (_kUndefinedLine). In that case the signaling event carries
// the real line and should update the call rather than decline it.
if (activeCallWithSameId != null &&
activeCallWithSameId.line != _kUndefinedLine &&
activeCallWithSameId.line != event.line) {
_logger.info(
'__onCallSignalingEventIncoming: received incoming call with existing callId but different line - callId: ${event.callId}, probably call to myself or transfer to myself',
);
try {
await _dispatchTerminationRequest(
request: QueuedTerminationRequest(
type: QueuedTerminationRequestType.decline,
line: event.line,
callId: event.callId,
),
source: '__onCallSignalingEventIncoming',
);
} catch (e, s) {
callErrorReporter.handle(e, s, '__onCallSignalingEventIncoming declineRequest error');
}
return;
}
// Glare detection: check if there is an active outgoing call with the same caller which is not yet connected or disconnecting.
// Typical useccase is when two devices with the same account are calling each other at the same time, e.g. by pressing "call" button in recents or notifications.
final nonConnectedCallWithSameCaller = state.activeCalls
.where(
(call) =>
call.handle.value == event.caller &&
call.callId != event.callId &&
call.direction == CallDirection.outgoing &&
call.processingStatus != CallProcessingStatus.connected &&
call.processingStatus != CallProcessingStatus.disconnecting,
)
.firstOrNull;
if (nonConnectedCallWithSameCaller != null) {
// Polite glare resolution: compare call IDs lexicographically so both sides independently
// reach the same deterministic decision - exactly one device yields.
// The side whose outgoing callId is lexicographically greater yields: it ends its outgoing
// call and lets the incoming proceed. The other side declines the incoming and keeps its outgoing.
final q = [nonConnectedCallWithSameCaller.callId, event.callId]..sort();
final shouldYield = q.first == event.callId;
_logger.info(
'__onCallSignalingEventIncoming: glare detected - nonConnectedCallWithSameCaller.callId: ${nonConnectedCallWithSameCaller.callId}, event.callId: ${event.callId}, shouldYield: $shouldYield',
);
if (shouldYield) {
_logger.info(
'__onCallSignalingEventIncoming: glare detected - yielding, ending outgoing call '
'(callId: ${nonConnectedCallWithSameCaller.callId}), letting incoming (${event.callId}) proceed',
);
add(CallControlEvent.ended(nonConnectedCallWithSameCaller.callId));