-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathIndividualCallService.swift
1343 lines (1129 loc) · 54.2 KB
/
IndividualCallService.swift
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
//
// Copyright 2016 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
//
import CallKit
import Foundation
import LibSignalClient
import SignalRingRTC
import SignalServiceKit
import SignalUI
import WebRTC
// MARK: - CallService
// This class' state should only be accessed on the main queue.
final class IndividualCallService: CallServiceStateObserver {
// MARK: Class
private let callManager: CallService.CallManagerType
private let callServiceState: CallServiceState
@MainActor
init(
callManager: CallService.CallManagerType,
callServiceState: CallServiceState
) {
self.callManager = callManager
self.callServiceState = callServiceState
SwiftSingletons.register(self)
self.callServiceState.addObserver(self)
}
private var audioSession: AudioSession { SUIEnvironment.shared.audioSessionRef }
private var callService: CallService { AppEnvironment.shared.callService }
@MainActor
private var callUIAdapter: CallUIAdapter { AppEnvironment.shared.callService.callUIAdapter }
private var contactManager: any ContactManager { SSKEnvironment.shared.contactManagerRef }
private var databaseStorage: SDSDatabaseStorage { SSKEnvironment.shared.databaseStorageRef }
private var networkManager: NetworkManager { SSKEnvironment.shared.networkManagerRef }
private var notificationPresenter: NotificationPresenter { SSKEnvironment.shared.notificationPresenterRef }
private var preferences: Preferences { SSKEnvironment.shared.preferencesRef }
private var profileManager: any ProfileManager { SSKEnvironment.shared.profileManagerRef }
private var tsAccountManager: any TSAccountManager { DependenciesBridge.shared.tsAccountManager }
private var identityManager: any OWSIdentityManager { DependenciesBridge.shared.identityManager }
@MainActor
func didUpdateCall(from oldValue: SignalCall?, to newValue: SignalCall?) {
stopAnyCallTimer()
if let newValue {
switch newValue.mode {
case .individual:
startCallTimer(for: newValue)
case .groupThread, .callLink:
break
}
}
}
// MARK: - Call Control Actions
/**
* Initiate an outgoing call.
*/
@MainActor
func handleOutgoingCall(_ call: SignalCall) {
Logger.info("call: \(call)")
guard callServiceState.currentCall == nil else {
owsFailDebug("call already exists: \(String(describing: callServiceState.currentCall))")
return
}
// Create a call interaction for outgoing calls immediately.
call.individualCall.createOrUpdateCallInteractionAsync(callType: .outgoingIncomplete)
do {
try callManager.placeCall(call: call, callMediaType: call.individualCall.offerMediaType.asCallMediaType, localDevice: call.individualCall.localDeviceId.uint32Value)
} catch {
self.handleFailedCall(failedCall: call, error: error, shouldResetUI: true, shouldResetRingRTC: true)
}
}
/**
* User chose to answer the call. Used by the Callee only.
*/
@MainActor
public func handleAcceptCall(_ call: SignalCall) {
Logger.info("\(call)")
defer {
// This should only be non-nil if we had to defer accepting the call while waiting for RingRTC
// If it's set, we need to make sure we call it before returning.
call.individualCall.deferredAnswerCompletion?()
call.individualCall.deferredAnswerCompletion = nil
}
guard callServiceState.currentCall === call else {
let error = OWSAssertionError("accepting call: \(call) which is different from currentCall: \(callServiceState.currentCall as Optional)")
handleFailedCall(failedCall: call, error: error, shouldResetUI: true, shouldResetRingRTC: true)
return
}
guard let callId = call.individualCall.callId else {
handleFailedCall(failedCall: call, error: OWSAssertionError("no callId for call: \(call)"), shouldResetUI: true, shouldResetRingRTC: true)
return
}
Logger.info("Creating call interaction: \(call)")
call.individualCall.createOrUpdateCallInteractionAsync(callType: .incomingIncomplete)
// It's key that we configure the AVAudioSession for a call *before* we fulfill the
// CXAnswerCallAction.
//
// Otherwise CallKit has been seen not to activate the audio session.
// That is, `provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession)`
// was sometimes not called.`
//
// That is why we connect here, rather than waiting for a racy async response from
// CallManager, confirming that the call has connected. It is also safer to do the
// audio session configuration before WebRTC starts operating on the audio resources
// via CallManager.accept().
handleConnected(call: call)
// Update the interaction now that we've accepted.
call.individualCall.createOrUpdateCallInteractionAsync(callType: .incoming)
do {
try callManager.accept(callId: callId)
} catch {
self.handleFailedCall(failedCall: call, error: error, shouldResetUI: true, shouldResetRingRTC: true)
}
}
/**
* Local user chose to end the call.
*/
@MainActor
func handleLocalHangupCall(_ call: SignalCall) {
Logger.info("\(call)")
guard call === callServiceState.currentCall else {
Logger.info("ignoring hangup for obsolete call: \(call)")
return
}
do {
try callManager.hangup()
} catch {
// no point in "failing" the call if the user expressed their intent to hang up
// and we've already called: `terminate(call: cal)`
owsFailDebug("error: \(error)")
}
}
// MARK: - Signaling Functions
/**
* Received an incoming call Offer from call initiator.
*/
public func handleReceivedOffer(
caller: Aci,
sourceDevice: DeviceId,
localIdentity: OWSIdentity,
callId: UInt64,
opaque: Data?,
sentAtTimestamp: UInt64,
serverReceivedTimestamp: UInt64,
serverDeliveryTimestamp: UInt64,
callType: SSKProtoCallMessageOfferType,
tx: DBWriteTransaction
) {
Logger.info("callId: \(callId), \(caller)")
guard let opaque else {
return
}
let callOfferHandler = CallOfferHandlerImpl(
identityManager: identityManager,
notificationPresenter: notificationPresenter,
profileManager: profileManager,
tsAccountManager: tsAccountManager
)
let partialResult = callOfferHandler.startHandlingOffer(
caller: caller,
sourceDevice: sourceDevice,
localIdentity: localIdentity,
callId: callId,
callType: callType,
sentAtTimestamp: sentAtTimestamp,
tx: tx
)
guard let partialResult else {
return
}
let individualCall = IndividualCall.incomingIndividualCall(
callId: callId,
thread: partialResult.thread,
sentAtTimestamp: sentAtTimestamp,
offerMediaType: partialResult.offerMediaType,
localDeviceId: partialResult.localDeviceId
)
// Get the current local device Id, must be valid for lifetime of the call.
let localDeviceId = partialResult.localDeviceId
let newCall = SignalCall(individualCall: individualCall)
DispatchQueue.main.async {
let backgroundTask: OWSBackgroundTask? = OWSBackgroundTask(label: "\(#function)", completionBlock: { [weak newCall] status in
AssertIsOnMainThread()
guard status == .expired else {
return
}
// See if the newCall actually became the currentCall.
guard
case .individual(let currentCall) = self.callServiceState.currentCall?.mode,
let newCall,
newCall === currentCall
else {
Logger.warn("ignoring obsolete call")
return
}
let error = CallError.timeout(description: "background task time ran out before call connected")
self.handleFailedCall(failedCall: newCall, error: error, shouldResetUI: true, shouldResetRingRTC: true)
})
newCall.individualCall.backgroundTask = backgroundTask
var messageAgeSec: UInt64 = 0
if serverReceivedTimestamp > 0 && serverDeliveryTimestamp >= serverReceivedTimestamp {
messageAgeSec = (serverDeliveryTimestamp - serverReceivedTimestamp) / 1000
}
do {
try self.callManager.receivedOffer(
call: newCall,
sourceDevice: sourceDevice.uint32Value,
callId: callId,
opaque: opaque,
messageAgeSec: messageAgeSec,
callMediaType: newCall.individualCall.offerMediaType.asCallMediaType,
localDevice: localDeviceId.uint32Value,
senderIdentityKey: partialResult.identityKeys.contactIdentityKey.publicKey.keyBytes.asData,
receiverIdentityKey: partialResult.identityKeys.localIdentityKey.publicKey.keyBytes.asData
)
} catch {
self.handleFailedCall(failedCall: newCall, error: error, shouldResetUI: true, shouldResetRingRTC: true)
}
}
}
/**
* Called by the call initiator after receiving an Answer from the callee.
*/
public func handleReceivedAnswer(
caller: Aci,
callId: UInt64,
sourceDevice: DeviceId,
opaque: Data?,
tx: DBReadTransaction
) {
Logger.info("callId: \(callId), \(caller)")
guard let opaque else {
return
}
let identityKeys = identityManager.getCallIdentityKeys(remoteAci: caller, tx: tx)
DispatchQueue.main.async {
self._handleReceivedAnswer(callId: callId, sourceDevice: sourceDevice, opaque: opaque, identityKeys: identityKeys)
}
}
@MainActor
private func _handleReceivedAnswer(
callId: UInt64,
sourceDevice: DeviceId,
opaque: Data,
identityKeys: CallIdentityKeys?
) {
guard let identityKeys else {
if let currentCall = callServiceState.currentCall, currentCall.individualCall?.callId == callId {
handleFailedCall(failedCall: currentCall, error: OWSAssertionError("missing identity keys"), shouldResetUI: true, shouldResetRingRTC: true)
}
return
}
do {
try callManager.receivedAnswer(
sourceDevice: sourceDevice.uint32Value,
callId: callId,
opaque: opaque,
senderIdentityKey: identityKeys.contactIdentityKey.publicKey.keyBytes.asData,
receiverIdentityKey: identityKeys.localIdentityKey.publicKey.keyBytes.asData
)
} catch {
owsFailDebug("error: \(error)")
if let currentCall = callServiceState.currentCall, currentCall.individualCall?.callId == callId {
handleFailedCall(failedCall: currentCall, error: error, shouldResetUI: true, shouldResetRingRTC: true)
}
}
}
/**
* Remote client (could be caller or callee) sent us a connectivity update.
*/
public func handleReceivedIceCandidates(caller: Aci, callId: UInt64, sourceDevice: DeviceId, candidates: [SSKProtoCallMessageIceUpdate]) {
Logger.info("callId: \(callId), \(caller)")
let iceCandidates = candidates.filter { $0.id == callId && $0.opaque != nil }.map { $0.opaque! }
if iceCandidates.isEmpty {
return
}
DispatchQueue.main.async {
self._handleReceivedIceCandidates(callId: callId, sourceDevice: sourceDevice, iceCandidates: iceCandidates)
}
}
@MainActor
private func _handleReceivedIceCandidates(callId: UInt64, sourceDevice: DeviceId, iceCandidates: [Data]) {
do {
try callManager.receivedIceCandidates(sourceDevice: sourceDevice.uint32Value, callId: callId, candidates: iceCandidates)
} catch {
owsFailDebug("error: \(error)")
// we don't necessarily want to fail the call just because CallManager errored on an
// ICE candidate
}
}
/**
* The remote client (caller or callee) ended the call.
*/
public func handleReceivedHangup(caller: Aci, callId: UInt64, sourceDevice: DeviceId, type: SSKProtoCallMessageHangupType, deviceId: UInt32) {
Logger.info("callId: \(callId), \(caller)")
let hangupType: HangupType
switch type {
case .hangupNormal: hangupType = .normal
case .hangupAccepted: hangupType = .accepted
case .hangupDeclined: hangupType = .declined
case .hangupBusy: hangupType = .busy
case .hangupNeedPermission: hangupType = .needPermission
}
DispatchQueue.main.async {
self._handleReceivedHangup(callId: callId, sourceDevice: sourceDevice, hangupType: hangupType, deviceId: deviceId)
}
}
@MainActor
private func _handleReceivedHangup(callId: UInt64, sourceDevice: DeviceId, hangupType: HangupType, deviceId: UInt32) {
do {
try callManager.receivedHangup(sourceDevice: sourceDevice.uint32Value, callId: callId, hangupType: hangupType, deviceId: deviceId)
} catch {
owsFailDebug("\(error)")
if let currentCall = callServiceState.currentCall, currentCall.individualCall?.callId == callId {
handleFailedCall(failedCall: currentCall, error: error, shouldResetUI: true, shouldResetRingRTC: true)
}
}
}
/**
* The callee was already in another call.
*/
public func handleReceivedBusy(caller: Aci, callId: UInt64, sourceDevice: DeviceId) {
Logger.info("callId: \(callId), \(caller)")
DispatchQueue.main.async {
self._handleReceivedBusy(callId: callId, sourceDevice: sourceDevice)
}
}
@MainActor
private func _handleReceivedBusy(callId: UInt64, sourceDevice: DeviceId) {
do {
try callManager.receivedBusy(sourceDevice: sourceDevice.uint32Value, callId: callId)
} catch {
owsFailDebug("\(error)")
if let currentCall = callServiceState.currentCall, currentCall.individualCall?.callId == callId {
handleFailedCall(failedCall: currentCall, error: error, shouldResetUI: true, shouldResetRingRTC: true)
}
}
}
// MARK: - Call Manager Events
@MainActor
public func callManager(_ callManager: CallService.CallManagerType, shouldStartCall call: SignalCall, callId: UInt64, isOutgoing: Bool, callMediaType: CallMediaType, shouldEarlyRing: Bool) {
Logger.info("call: \(call)")
if shouldEarlyRing {
if !isOutgoing {
// If we are using the NSE, we need to kick off a ring ASAP in case this incoming call
// has resulted in the NSE waking up the main app.
Logger.info("Performing early ring")
handleRinging(call: call, isAnticipatory: true)
} else {
owsFailDebug("Cannot early ring an outgoing call")
}
}
// Start the call, asynchronously.
Task { @MainActor in
do {
let iceServers = try await RTCIceServerFetcher(networkManager: networkManager)
.getIceServers()
guard self.callServiceState.currentCall === call else {
Logger.debug("call has since ended")
return
}
let isSignalConnection = self.databaseStorage.read { tx in
return profileManager.isThread(inProfileWhitelist: call.individualCall.thread, transaction: tx)
}
if !isSignalConnection {
Logger.warn("Using relay server because remote user is not a Signal Connection")
}
let useTurnOnly = !isSignalConnection || self.preferences.doCallsHideIPAddress
let useLowData = self.callService.shouldUseLowDataWithSneakyTransaction(for: NetworkRoute(localAdapterType: .unknown))
Logger.info("Configuring call for \(useLowData ? "low" : "standard") data")
// Tell the Call Manager to proceed with its active call.
try self.callManager.proceed(callId: callId, iceServers: iceServers, hideIp: useTurnOnly, videoCaptureController: call.videoCaptureController, dataMode: useLowData ? .low : .normal, audioLevelsIntervalMillis: nil)
} catch {
owsFailDebug("\(error)")
guard call === self.callServiceState.currentCall else {
return
}
callManager.drop(callId: callId)
self.handleFailedCall(failedCall: call, error: error, shouldResetUI: true, shouldResetRingRTC: false)
}
}
}
@MainActor
public func callManager(_ callManager: CallService.CallManagerType, onEvent call: SignalCall, event: CallManagerEvent) {
Logger.info("call: \(call), onEvent: \(event)")
switch event {
case .ringingLocal:
handleRinging(call: call)
case .ringingRemote:
handleRinging(call: call)
case .connectedLocal:
Logger.debug("")
// nothing further to do - already handled in handleAcceptCall().
case .connectedRemote:
defer {
callUIAdapter.recipientAcceptedCall(call.mode)
}
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
// Set the audio session configuration before audio is enabled in WebRTC
// via recipientAcceptedCall().
handleConnected(call: call)
// Update the call interaction now that we've connected.
call.individualCall.createOrUpdateCallInteractionAsync(callType: .outgoing)
case .endedLocalHangup:
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
switch call.individualCall.callType {
case .some(.outgoingIncomplete):
call.individualCall.createOrUpdateCallInteractionAsync(callType: .outgoingMissed)
case .some:
break
case .none where [.localRinging_Anticipatory, .localRinging_ReadyToAnswer, .accepting].contains(call.individualCall.state):
call.individualCall.createOrUpdateCallInteractionAsync(callType: .incomingDeclined)
case .none:
owsFailDebug("missing call record")
}
// Make RTC audio inactive early in the hangup process before the state
// change resulting in any change to the default AudioSession.
audioSession.isRTCAudioEnabled = false
call.individualCall.state = .localHangup
ensureAudioState(call: call)
callServiceState.terminateCall(call)
case .endedRemoteHangup:
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
// Make RTC audio inactive early in the hangup process before the state
// change resulting in any change to the default AudioSession.
audioSession.isRTCAudioEnabled = false
switch call.individualCall.state {
case .idle, .dialing, .answering, .localRinging_Anticipatory, .localRinging_ReadyToAnswer, .accepting, .localFailure, .remoteBusy, .remoteRinging:
handleMissedCall(call)
case .connected, .reconnecting, .localHangup, .remoteHangup, .remoteHangupNeedPermission, .answeredElsewhere, .declinedElsewhere, .busyElsewhere:
Logger.info("call is finished")
}
call.individualCall.state = .remoteHangup
// Notify UI
callUIAdapter.remoteDidHangupCall(call)
callServiceState.terminateCall(call)
case .endedRemoteHangupNeedPermission:
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
audioSession.isRTCAudioEnabled = false
switch call.individualCall.state {
case .idle, .dialing, .answering, .localRinging_Anticipatory, .localRinging_ReadyToAnswer, .accepting, .localFailure, .remoteBusy, .remoteRinging:
handleMissedCall(call)
case .connected, .reconnecting, .localHangup, .remoteHangup, .remoteHangupNeedPermission, .answeredElsewhere, .declinedElsewhere, .busyElsewhere:
Logger.info("call is finished")
}
call.individualCall.state = .remoteHangupNeedPermission
// Notify UI
callUIAdapter.remoteDidHangupCall(call)
callServiceState.terminateCall(call)
case .endedRemoteHangupAccepted:
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
audioSession.isRTCAudioEnabled = false
switch call.individualCall.state {
case .idle, .dialing, .remoteBusy, .remoteRinging, .answeredElsewhere, .declinedElsewhere, .busyElsewhere, .remoteHangup, .remoteHangupNeedPermission:
handleFailedCall(failedCall: call, error: OWSAssertionError("unexpected state for endedRemoteHangupAccepted: \(call.individualCall.state)"), shouldResetUI: true, shouldResetRingRTC: true)
return
case .answering, .accepting, .connected:
Logger.info("tried answering locally, but answered somewhere else first. state: \(call.individualCall.state)")
handleAnsweredElsewhere(call: call)
case .localRinging_Anticipatory, .localRinging_ReadyToAnswer, .reconnecting:
handleAnsweredElsewhere(call: call)
case .localFailure, .localHangup:
Logger.info("ignoring 'endedRemoteHangupAccepted' since call is already finished")
}
case .endedRemoteHangupDeclined:
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
audioSession.isRTCAudioEnabled = false
switch call.individualCall.state {
case .idle, .dialing, .remoteBusy, .remoteRinging, .answeredElsewhere, .declinedElsewhere, .busyElsewhere, .remoteHangup, .remoteHangupNeedPermission:
handleFailedCall(failedCall: call, error: OWSAssertionError("unexpected state for endedRemoteHangupDeclined: \(call.individualCall.state)"), shouldResetUI: true, shouldResetRingRTC: true)
return
case .answering, .accepting, .connected:
Logger.info("tried answering locally, but declined somewhere else first. state: \(call.individualCall.state)")
handleDeclinedElsewhere(call: call)
case .localRinging_Anticipatory, .localRinging_ReadyToAnswer, .reconnecting:
handleDeclinedElsewhere(call: call)
case .localFailure, .localHangup:
Logger.info("ignoring 'endedRemoteHangupDeclined' since call is already finished")
}
case .endedRemoteHangupBusy:
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
audioSession.isRTCAudioEnabled = false
switch call.individualCall.state {
case .idle, .dialing, .remoteBusy, .remoteRinging, .answeredElsewhere, .declinedElsewhere, .busyElsewhere, .remoteHangup, .remoteHangupNeedPermission:
handleFailedCall(failedCall: call, error: OWSAssertionError("unexpected state for endedRemoteHangupBusy: \(call.individualCall.state)"), shouldResetUI: true, shouldResetRingRTC: true)
return
case .answering, .accepting, .connected:
Logger.info("tried answering locally, but already in a call somewhere else first. state: \(call.individualCall.state)")
handleBusyElsewhere(call: call)
case .localRinging_Anticipatory, .localRinging_ReadyToAnswer, .reconnecting:
handleBusyElsewhere(call: call)
case .localFailure, .localHangup:
Logger.info("ignoring 'endedRemoteHangupBusy' since call is already finished")
}
case .endedRemoteBusy:
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
assert(call.individualCall.direction == .outgoing)
call.individualCall.createOrUpdateCallInteractionAsync(callType: .outgoingMissed)
call.individualCall.state = .remoteBusy
// Notify UI
callUIAdapter.remoteBusy(call)
callServiceState.terminateCall(call)
case .endedRemoteGlare, .endedRemoteReCall:
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
if let callType = call.individualCall.callType {
switch callType {
case .outgoingMissed, .incomingDeclined, .incomingMissed, .incomingMissedBecauseOfChangedIdentity, .incomingAnsweredElsewhere, .incomingDeclinedElsewhere, .incomingBusyElsewhere, .incomingMissedBecauseOfDoNotDisturb, .incomingMissedBecauseBlockedSystemContact:
// already handled and ended, don't update the call record.
break
case .incomingIncomplete, .incoming:
call.individualCall.createOrUpdateCallInteractionAsync(callType: .incomingMissed)
callUIAdapter.reportMissedCall(call, individualCall: call.individualCall)
case .outgoingIncomplete:
call.individualCall.createOrUpdateCallInteractionAsync(callType: .outgoingMissed)
callUIAdapter.remoteBusy(call)
case .outgoing:
call.individualCall.createOrUpdateCallInteractionAsync(callType: .outgoingMissed)
callUIAdapter.reportMissedCall(call, individualCall: call.individualCall)
@unknown default:
owsFailDebug("unknown RPRecentCallType: \(callType)")
}
} else {
assert(call.individualCall.direction == .incoming)
call.individualCall.createOrUpdateCallInteractionAsync(callType: .incomingMissed)
callUIAdapter.reportMissedCall(call, individualCall: call.individualCall)
}
call.individualCall.state = .localHangup
callServiceState.terminateCall(call)
case .endedTimeout:
let description: String
if call.individualCall.direction == .outgoing {
description = "timeout for outgoing call"
} else {
description = "timeout for incoming call"
}
handleFailedCall(failedCall: call, error: CallError.timeout(description: description), shouldResetUI: true, shouldResetRingRTC: false)
case .endedSignalingFailure, .endedGlareHandlingFailure:
handleFailedCall(failedCall: call, error: CallError.signaling, shouldResetUI: true, shouldResetRingRTC: false)
case .endedInternalFailure:
handleFailedCall(failedCall: call, error: OWSAssertionError("call manager internal error"), shouldResetUI: true, shouldResetRingRTC: false)
case .endedConnectionFailure:
handleFailedCall(failedCall: call, error: CallError.disconnected, shouldResetUI: true, shouldResetRingRTC: false)
case .endedDropped:
Logger.debug("")
// An incoming call was dropped, ignoring because we have already
// failed the call on the screen.
case .remoteAudioEnable:
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
call.individualCall.isRemoteAudioMuted = false
case .remoteAudioDisable:
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
call.individualCall.isRemoteAudioMuted = true
case .remoteVideoEnable:
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
call.individualCall.isRemoteVideoEnabled = true
case .remoteVideoDisable:
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
call.individualCall.isRemoteVideoEnabled = false
case .remoteSharingScreenEnable:
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
call.individualCall.isRemoteSharingScreen = true
case .remoteSharingScreenDisable:
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
call.individualCall.isRemoteSharingScreen = false
case .reconnecting:
self.handleReconnecting(call: call)
case .reconnected:
self.handleReconnected(call: call)
case .receivedOfferExpired:
// TODO - This is the case where an incoming offer's timestamp is
// not within the range +/- 120 seconds of the current system time.
// At the moment, this is not an issue since we are currently setting
// the timestamp separately when we receive the offer (above).
// This should not be a failure, it is just an 'old' call.
handleMissedCall(call)
call.individualCall.state = .localFailure
callServiceState.terminateCall(call)
case .receivedOfferWhileActive:
handleMissedCall(call)
// TODO - This should not be a failure.
call.individualCall.state = .localFailure
callServiceState.terminateCall(call)
case .receivedOfferWithGlare:
handleMissedCall(call)
// TODO - This should not be a failure.
call.individualCall.state = .localFailure
callServiceState.terminateCall(call)
}
}
@MainActor
public func callManager(_ callManager: CallService.CallManagerType, onUpdateLocalVideoSession call: SignalCall, session: AVCaptureSession?) {
Logger.info("onUpdateLocalVideoSession")
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
}
@MainActor
public func callManager(_ callManager: CallService.CallManagerType, onAddRemoteVideoTrack call: SignalCall, track: RTCVideoTrack) {
Logger.info("onAddRemoteVideoTrack")
guard call === callServiceState.currentCall else {
cleanUpStaleCall(call)
return
}
call.individualCall.remoteVideoTrack = track
}
// MARK: - Call Manager Signaling
@MainActor
public func callManager(_ callManager: CallService.CallManagerType, shouldSendOffer callId: UInt64, call: SignalCall, destinationDeviceId: UInt32?, opaque: Data, callMediaType: CallMediaType) {
Logger.info("shouldSendOffer")
Task {
do {
let offerBuilder = SSKProtoCallMessageOffer.builder(id: callId)
offerBuilder.setOpaque(opaque)
switch callMediaType {
case .audioCall: offerBuilder.setType(.offerAudioCall)
case .videoCall: offerBuilder.setType(.offerVideoCall)
}
let sendPromise = try await self.databaseStorage.awaitableWrite { tx -> Promise<Void> in
let callMessage = OWSOutgoingCallMessage(
thread: call.individualCall.thread,
offerMessage: try offerBuilder.build(),
destinationDeviceId: NSNumber(value: destinationDeviceId),
transaction: tx
)
let preparedMessage = PreparedOutgoingMessage.preprepared(
transientMessageWithoutAttachments: callMessage
)
return ThreadUtil.enqueueMessagePromise(
message: preparedMessage,
limitToCurrentProcessLifetime: true,
isHighPriority: true,
transaction: tx
)
}
try await sendPromise.awaitable()
Logger.info("sent offer message to \(call.individualCall.thread.contactAddress) device: \((destinationDeviceId != nil) ? String(destinationDeviceId!) : "nil")")
try self.callManager.signalingMessageDidSend(callId: callId)
} catch {
Logger.error("failed to send offer message to \(call.individualCall.thread.contactAddress) with error: \(error)")
self.callManager.signalingMessageDidFail(callId: callId)
}
}
}
@MainActor
public func callManager(_ callManager: CallService.CallManagerType, shouldSendAnswer callId: UInt64, call: SignalCall, destinationDeviceId: UInt32?, opaque: Data) {
Logger.info("shouldSendAnswer")
Task {
do {
let answerBuilder = SSKProtoCallMessageAnswer.builder(id: callId)
answerBuilder.setOpaque(opaque)
let sendPromise = try await self.databaseStorage.awaitableWrite { tx -> Promise<Void> in
let callMessage = OWSOutgoingCallMessage(
thread: call.individualCall.thread,
answerMessage: try answerBuilder.build(),
destinationDeviceId: NSNumber(value: destinationDeviceId),
transaction: tx
)
let preparedMessage = PreparedOutgoingMessage.preprepared(
transientMessageWithoutAttachments: callMessage
)
return ThreadUtil.enqueueMessagePromise(
message: preparedMessage,
limitToCurrentProcessLifetime: true,
isHighPriority: true,
transaction: tx
)
}
try await sendPromise.awaitable()
Logger.debug("sent answer message to \(call.individualCall.thread.contactAddress) device: \((destinationDeviceId != nil) ? String(destinationDeviceId!) : "nil")")
try self.callManager.signalingMessageDidSend(callId: callId)
} catch {
Logger.error("failed to send answer message to \(call.individualCall.thread.contactAddress) with error: \(error)")
self.callManager.signalingMessageDidFail(callId: callId)
}
}
}
@MainActor
public func callManager(_ callManager: CallService.CallManagerType, shouldSendIceCandidates callId: UInt64, call: SignalCall, destinationDeviceId: UInt32?, candidates: [Data]) {
Logger.info("shouldSendIceCandidates")
Task {
do {
var iceUpdateProtos = [SSKProtoCallMessageIceUpdate]()
for iceCandidate in candidates {
let iceUpdateProto: SSKProtoCallMessageIceUpdate
let iceUpdateBuilder = SSKProtoCallMessageIceUpdate.builder(id: callId)
iceUpdateBuilder.setOpaque(iceCandidate)
iceUpdateProto = try iceUpdateBuilder.build()
iceUpdateProtos.append(iceUpdateProto)
}
guard !iceUpdateProtos.isEmpty else {
throw OWSAssertionError("no ice updates to send")
}
let sendPromise = await self.databaseStorage.awaitableWrite { tx -> Promise<Void> in
let callMessage = OWSOutgoingCallMessage(
thread: call.individualCall.thread,
iceUpdateMessages: iceUpdateProtos,
destinationDeviceId: NSNumber(value: destinationDeviceId),
transaction: tx
)
let preparedMessage = PreparedOutgoingMessage.preprepared(
transientMessageWithoutAttachments: callMessage
)
return ThreadUtil.enqueueMessagePromise(
message: preparedMessage,
limitToCurrentProcessLifetime: true,
isHighPriority: true,
transaction: tx
)
}
try await sendPromise.awaitable()
Logger.debug("sent ice update message to \(call.individualCall.thread.contactAddress) device: \((destinationDeviceId != nil) ? String(destinationDeviceId!) : "nil")")
try self.callManager.signalingMessageDidSend(callId: callId)
} catch {
Logger.error("failed to send ice update message to \(call.individualCall.thread.contactAddress) with error: \(error)")
callManager.signalingMessageDidFail(callId: callId)
}
}
}
@MainActor
public func callManager(_ callManager: CallService.CallManagerType, shouldSendHangup callId: UInt64, call: SignalCall, destinationDeviceId: UInt32?, hangupType: HangupType, deviceId: UInt32) {
Logger.info("shouldSendHangup")
// At time of writing, destinationDeviceId is always nil and deviceId is
// sometimes 0.
Task {
do {
let sendPromise = await self.databaseStorage.awaitableWrite { tx in
return CallHangupSender.sendHangup(
thread: call.individualCall.thread,
callId: callId,
hangupType: { () -> SSKProtoCallMessageHangupType in
switch hangupType {
case .normal: return .hangupNormal
case .accepted: return .hangupAccepted
case .declined: return .hangupDeclined
case .busy: return .hangupBusy
case .needPermission: return .hangupNeedPermission
}
}(),
localDeviceId: deviceId,
remoteDeviceId: destinationDeviceId,
tx: tx
)
}
try await sendPromise.awaitable()
Logger.debug("sent hangup message to \(call.individualCall.thread.contactAddress) device: \(destinationDeviceId as Optional)")
try self.callManager.signalingMessageDidSend(callId: callId)
} catch {
Logger.error("failed to send hangup message to \(call.individualCall.thread.contactAddress) with error: \(error)")
self.callManager.signalingMessageDidFail(callId: callId)
}
}
}
@MainActor
public func callManager(_ callManager: CallService.CallManagerType, shouldSendBusy callId: UInt64, call: SignalCall, destinationDeviceId: UInt32?) {
Logger.info("shouldSendBusy")
Task {
do {
let busyBuilder = SSKProtoCallMessageBusy.builder(id: callId)
let sendPromise = try await self.databaseStorage.awaitableWrite { tx -> Promise<Void> in
let callMessage = OWSOutgoingCallMessage(
thread: call.individualCall.thread,
busyMessage: try busyBuilder.build(),
destinationDeviceId: NSNumber(value: destinationDeviceId),
transaction: tx
)
let preparedMessage = PreparedOutgoingMessage.preprepared(
transientMessageWithoutAttachments: callMessage
)
return ThreadUtil.enqueueMessagePromise(
message: preparedMessage,
limitToCurrentProcessLifetime: true,
isHighPriority: true,
transaction: tx
)
}
try await sendPromise.awaitable()
Logger.debug("sent busy message to \(call.individualCall.thread.contactAddress) device: \((destinationDeviceId != nil) ? String(destinationDeviceId!) : "nil")")
try self.callManager.signalingMessageDidSend(callId: callId)
} catch {
Logger.error("failed to send busy message to \(call.individualCall.thread.contactAddress) with error: \(error)")
self.callManager.signalingMessageDidFail(callId: callId)
}
}
}
// MARK: - Support Functions
/**
* User didn't answer incoming call
*/
@MainActor
public func handleMissedCall(_ call: SignalCall, error: CallError? = nil) {
Logger.info("call: \(call)")
let callType: RPRecentCallType
switch error {
case .doNotDisturbEnabled?:
callType = .incomingMissedBecauseOfDoNotDisturb
case .contactIsBlocked:
callType = .incomingMissedBecauseBlockedSystemContact
default:
if call.individualCall?.direction == .outgoing {