-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathCallService.swift
1610 lines (1423 loc) · 62.5 KB
/
CallService.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 2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
//
import AVFoundation
import LibSignalClient
import SignalRingRTC
import SignalServiceKit
import SignalUI
import WebRTC
/// Manages events related to both 1:1 and group calls, while the main app is
/// running.
///
/// Responsible for the 1:1 or group call this device is currently active in, if
/// any, as well as any other updates to other calls that we learn about.
@MainActor
final class CallService: CallServiceStateObserver, CallServiceStateDelegate {
public typealias CallManagerType = CallManager<SignalCall, CallService>
public let callManager: CallManagerType
// Even though we never use this, we need to retain it to ensure
// `callManager` continues to work properly.
private let callManagerHttpClient: AnyObject
private var adHocCallRecordManager: any AdHocCallRecordManager { DependenciesBridge.shared.adHocCallRecordManager }
private let appReadiness: AppReadiness
private var audioSession: AudioSession { SUIEnvironment.shared.audioSessionRef }
private var callLinkStore: any CallLinkRecordStore { DependenciesBridge.shared.callLinkStore }
let authCredentialManager: any AuthCredentialManager
private var databaseStorage: SDSDatabaseStorage { SSKEnvironment.shared.databaseStorageRef }
private let db: any DB
private var groupCallManager: GroupCallManager { SSKEnvironment.shared.groupCallManagerRef }
private var messageSenderJobQueue: MessageSenderJobQueue { SSKEnvironment.shared.messageSenderJobQueueRef }
private var reachabilityManager: SSKReachabilityManager { SSKEnvironment.shared.reachabilityManagerRef }
public var callUIAdapter: CallUIAdapter
let deviceSleepManager: DeviceSleepManagerImpl
nonisolated let individualCallService: IndividualCallService
let groupCallRemoteVideoManager: GroupCallRemoteVideoManager
let callLinkManager: CallLinkManagerImpl
let callLinkFetcher: CallLinkFetcherImpl
let callLinkStateUpdater: CallLinkStateUpdater
private var adHocCallStateObserver: AdHocCallStateObserver?
/// Needs to be lazily initialized, because it uses singletons that are not
/// available when this class is initialized.
private lazy var groupCallAccessoryMessageDelegate: GroupCallAccessoryMessageDelegate = {
return GroupCallAccessoryMessageHandler(
databaseStorage: databaseStorage,
groupCallRecordManager: DependenciesBridge.shared.groupCallRecordManager,
messageSenderJobQueue: messageSenderJobQueue
)
}()
/// Needs to be lazily initialized, because it uses singletons that are not
/// available when this class is initialized.
private lazy var groupCallRecordRingUpdateDelegate: GroupCallRecordRingUpdateDelegate = {
return GroupCallRecordRingUpdateHandler(
callRecordStore: DependenciesBridge.shared.callRecordStore,
groupCallRecordManager: DependenciesBridge.shared.groupCallRecordManager,
interactionStore: DependenciesBridge.shared.interactionStore,
threadStore: DependenciesBridge.shared.threadStore
)
}()
private(set) lazy var audioService: CallAudioService = {
let result = CallAudioService(audioSession: self.audioSession)
callServiceState.addObserver(result, syncStateImmediately: true)
return result
}()
public let earlyRingNextIncomingCall = AtomicBool(false, lock: .init())
let callServiceState: CallServiceState
var notificationObservers: [any NSObjectProtocol] = []
public init(
appContext: any AppContext,
appReadiness: AppReadiness,
authCredentialManager: any AuthCredentialManager,
callLinkPublicParams: GenericServerPublicParams,
callLinkStore: any CallLinkRecordStore,
callRecordDeleteManager: any CallRecordDeleteManager,
callRecordStore: any CallRecordStore,
db: any DB,
deviceSleepManager: DeviceSleepManagerImpl,
mutableCurrentCall: AtomicValue<SignalCall?>,
networkManager: NetworkManager,
tsAccountManager: any TSAccountManager
) {
self.appReadiness = appReadiness
self.authCredentialManager = authCredentialManager
let httpClient = CallHTTPClient()
self.callManager = CallManager<SignalCall, CallService>(
httpClient: httpClient.ringRtcHttpClient,
fieldTrials: RingrtcFieldTrials.trials(with: appContext.appUserDefaults())
)
self.callManagerHttpClient = httpClient
let callUIAdapter = CallUIAdapter()
self.callUIAdapter = callUIAdapter
self.callServiceState = CallServiceState(currentCall: mutableCurrentCall)
self.individualCallService = IndividualCallService(
callManager: self.callManager,
callServiceState: self.callServiceState
)
self.groupCallRemoteVideoManager = GroupCallRemoteVideoManager(
callServiceState: self.callServiceState
)
self.callLinkFetcher = CallLinkFetcherImpl()
self.callLinkManager = CallLinkManagerImpl(
networkManager: networkManager,
serverParams: callLinkPublicParams,
tsAccountManager: tsAccountManager
)
self.callLinkStateUpdater = CallLinkStateUpdater(
authCredentialManager: authCredentialManager,
callLinkFetcher: self.callLinkFetcher,
callLinkManager: self.callLinkManager,
callLinkStore: callLinkStore,
callRecordDeleteManager: callRecordDeleteManager,
callRecordStore: callRecordStore,
db: db,
tsAccountManager: tsAccountManager
)
self.db = db
self.deviceSleepManager = deviceSleepManager
self.callManager.delegate = self
SwiftSingletons.register(self)
self.callServiceState.addObserver(self)
notificationObservers.append(NotificationCenter.default.addObserver(forName: .OWSApplicationDidEnterBackground, object: nil, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.didEnterBackground() }
})
notificationObservers.append(NotificationCenter.default.addObserver(forName: .OWSApplicationDidBecomeActive, object: nil, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.didBecomeActive() }
})
notificationObservers.append(NotificationCenter.default.addObserver(forName: Self.callServicePreferencesDidChange, object: nil, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.configureDataMode() }
})
notificationObservers.append(NotificationCenter.default.addObserver(forName: .registrationStateDidChange, object: nil, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.registrationChanged() }
})
// Note that we're not using the usual .owsReachabilityChanged
// We want to update our data mode if the app has been backgrounded
notificationObservers.append(NotificationCenter.default.addObserver(forName: .reachabilityChanged, object: nil, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.configureDataMode() }
})
// We don't support a rotating call screen on phones,
// but we do still want to rotate the various icons.
if !UIDevice.current.isIPad {
notificationObservers.append(NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.phoneOrientationDidChange() }
})
}
appReadiness.runNowOrWhenAppWillBecomeReady {
if let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci {
self.callManager.setSelfUuid(localAci.rawUUID)
}
}
appReadiness.runNowOrWhenAppDidBecomeReadyAsync {
DependenciesBridge.shared.databaseChangeObserver.appendDatabaseChangeDelegate(self)
self.callServiceState.addObserver(self.groupCallAccessoryMessageDelegate, syncStateImmediately: true)
self.callServiceState.addObserver(self.groupCallRemoteVideoManager, syncStateImmediately: true)
}
}
deinit {
for observer in notificationObservers {
NotificationCenter.default.removeObserver(observer)
}
}
/**
* Choose whether to use CallKit or a Notification backed interface for calling.
*/
public func rebuildCallUIAdapter() {
if let currentCall = callServiceState.currentCall {
Logger.warn("ending current call in. Did user toggle callkit preference while in a call?")
callServiceState.terminateCall(currentCall)
}
self.callUIAdapter = CallUIAdapter()
}
private let sleepBlockObject = DeviceSleepBlockObject(blockReason: "call")
func didUpdateCall(from oldValue: SignalCall?, to newValue: SignalCall?) {
switch oldValue?.mode {
case nil:
break
case .individual(let call):
call.removeObserver(self)
case .groupThread(let call):
call.removeObserver(self)
case .callLink(let call):
self.adHocCallStateObserver = nil
call.removeObserver(self)
}
switch newValue?.mode {
case nil:
break
case .individual(let call):
call.addObserverAndSyncState(self)
case .groupThread(let call):
call.addObserver(self, syncStateImmediately: true)
case .callLink(let call):
self.adHocCallStateObserver = AdHocCallStateObserver(
callLinkCall: call,
adHocCallRecordManager: adHocCallRecordManager,
callLinkStore: callLinkStore,
messageSenderJobQueue: messageSenderJobQueue,
db: db
)
call.addObserver(self, syncStateImmediately: true)
}
updateIsVideoEnabled()
// Prevent device from sleeping while we have an active call.
if oldValue != nil {
self.deviceSleepManager.removeBlock(blockObject: sleepBlockObject)
}
if newValue != nil {
self.deviceSleepManager.addBlock(blockObject: sleepBlockObject)
}
if !UIDevice.current.isIPad {
if oldValue != nil {
UIDevice.current.endGeneratingDeviceOrientationNotifications()
}
if newValue != nil {
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
}
}
switch newValue?.mode {
case .individual:
// By default, individual calls should start out with speakerphone disabled.
self.audioService.requestSpeakerphone(isEnabled: false)
case .groupThread, .callLink, nil:
break
}
// To be safe, we reset the early ring on any call change so it's not left set from an unexpected state change.
earlyRingNextIncomingCall.set(false)
}
func callServiceState(_ callServiceState: CallServiceState, didTerminateCall call: SignalCall) {
if callServiceState.currentCall == nil {
audioSession.isRTCAudioEnabled = false
}
audioSession.endAudioActivity(call.commonState.audioActivity)
switch call.mode {
case .individual:
break
case .groupThread(let call):
// Kick off a peek now that we've disconnected to get an updated participant state.
Task {
await self.groupCallManager.peekGroupCallAndUpdateThread(
forGroupId: call.groupId,
peekTrigger: .localEvent()
)
}
case .callLink:
break
}
}
// MARK: -
/**
* Local user toggled to mute audio.
*/
func updateIsLocalAudioMuted(isLocalAudioMuted: Bool) {
// Keep a reference to the call before permissions were requested...
guard let currentCall = callServiceState.currentCall else {
owsFailDebug("missing currentCall")
return
}
// If we're disabling the microphone, we don't need permission. Only need
// permission to *enable* the microphone.
guard !isLocalAudioMuted else {
return updateIsLocalAudioMutedWithMicrophonePermission(call: currentCall, isLocalAudioMuted: isLocalAudioMuted)
}
// This method can be initiated either from the CallViewController.videoButton or via CallKit
// in either case we want to show the alert on the callViewWindow.
guard let frontmostViewController = AppEnvironment.shared.windowManagerRef.callViewWindow.findFrontmostViewController(ignoringAlerts: true) else {
owsFailDebug("could not identify frontmostViewController")
return
}
frontmostViewController.ows_askForMicrophonePermissions { granted in
// Make sure the call is still valid (the one we asked permissions for).
guard self.callServiceState.currentCall === currentCall else {
Logger.info("ignoring microphone permissions for obsolete call")
return
}
if !granted {
frontmostViewController.ows_showNoMicrophonePermissionActionSheet()
}
let mutedAfterAskingForPermission = !granted
self.updateIsLocalAudioMutedWithMicrophonePermission(call: currentCall, isLocalAudioMuted: mutedAfterAskingForPermission)
}
}
private func updateIsLocalAudioMutedWithMicrophonePermission(call: SignalCall, isLocalAudioMuted: Bool) {
owsPrecondition(call === callServiceState.currentCall)
switch call.mode {
case .groupThread(let call as GroupCall), .callLink(let call as GroupCall):
call.ringRtcCall.isOutgoingAudioMuted = isLocalAudioMuted
call.groupCall(onLocalDeviceStateChanged: call.ringRtcCall)
case .individual(let individualCall):
individualCall.isMuted = isLocalAudioMuted
individualCallService.ensureAudioState(call: call)
}
}
/**
* Local user toggled video.
*/
func updateIsLocalVideoMuted(isLocalVideoMuted: Bool) {
// Keep a reference to the call before permissions were requested...
guard let currentCall = callServiceState.currentCall else {
owsFailDebug("missing currentCall")
return
}
// If we're disabling local video, we don't need permission. Only need
// permission to *enable* video.
guard !isLocalVideoMuted else {
return updateIsLocalVideoMutedWithCameraPermissions(call: currentCall, isLocalVideoMuted: isLocalVideoMuted)
}
// This method can be initiated either from the CallViewController.videoButton or via CallKit
// in either case we want to show the alert on the callViewWindow.
let frontmostViewController = AppEnvironment.shared.windowManagerRef.callViewWindow.findFrontmostViewController(ignoringAlerts: true)
guard let frontmostViewController else {
owsFailDebug("could not identify frontmostViewController")
return
}
frontmostViewController.ows_askForCameraPermissions { granted in
// Make sure the call is still valid (the one we asked permissions for).
guard self.callServiceState.currentCall === currentCall else {
Logger.info("ignoring camera permissions for obsolete call")
return
}
let mutedAfterAskingForPermission = !granted
self.updateIsLocalVideoMutedWithCameraPermissions(call: currentCall, isLocalVideoMuted: mutedAfterAskingForPermission)
}
}
private func updateIsLocalVideoMutedWithCameraPermissions(call: SignalCall, isLocalVideoMuted: Bool) {
owsPrecondition(call === callServiceState.currentCall)
switch call.mode {
case .groupThread(let call as GroupCall), .callLink(let call as GroupCall):
call.ringRtcCall.isOutgoingVideoMuted = isLocalVideoMuted
call.groupCall(onLocalDeviceStateChanged: call.ringRtcCall)
case .individual(let individualCall):
individualCall.hasLocalVideo = !isLocalVideoMuted
}
updateIsVideoEnabled()
}
func updateCameraSource(call: SignalCall, isUsingFrontCamera: Bool) {
call.videoCaptureController.switchCamera(isUsingFrontCamera: isUsingFrontCamera)
}
private func configureDataMode() {
guard appReadiness.isAppReady else { return }
guard let currentCall = callServiceState.currentCall else { return }
switch currentCall.mode {
case .groupThread(let call):
let useLowData = shouldUseLowDataWithSneakyTransaction(for: call.ringRtcCall.localDeviceState.networkRoute)
Logger.info("Configuring call for \(useLowData ? "low" : "standard") data")
call.ringRtcCall.updateDataMode(dataMode: useLowData ? .low : .normal)
case let .individual(call) where call.state == .connected:
let useLowData = shouldUseLowDataWithSneakyTransaction(for: call.networkRoute)
Logger.info("Configuring call for \(useLowData ? "low" : "standard") data")
callManager.updateDataMode(dataMode: useLowData ? .low : .normal)
default:
// Do nothing. We'll reapply the data mode once connected
break
}
}
func shouldUseLowDataWithSneakyTransaction(for networkRoute: NetworkRoute) -> Bool {
let highDataInterfaces = databaseStorage.read { readTx in
Self.highDataNetworkInterfaces(readTx: readTx)
}
if let allowsHighData = highDataInterfaces.includes(networkRoute.localAdapterType) {
return !allowsHighData
}
// If we aren't sure whether the current route's high-data, fall back to checking reachability.
// This also handles the situation where WebRTC doesn't know what interface we're on,
// which is always true on iOS 11.
return !reachabilityManager.isReachable(with: highDataInterfaces)
}
// MARK: -
// This method should be called when a fatal error occurred for a call.
//
// * If we know which call it was, we should update that call's state
// to reflect the error.
// * IFF that call is the current call, we want to terminate it.
public func handleFailedCall(failedCall: SignalCall, error: Error) {
switch failedCall.mode {
case .individual:
individualCallService.handleFailedCall(
failedCall: failedCall,
error: error,
shouldResetUI: false,
shouldResetRingRTC: true
)
case .groupThread(let groupCall as GroupCall), .callLink(let groupCall as GroupCall):
leaveAndTerminateGroupCall(failedCall, groupCall: groupCall)
}
}
func handleLocalHangupCall(_ call: SignalCall) {
switch call.mode {
case .individual:
individualCallService.handleLocalHangupCall(call)
case .groupThread(let groupThreadCall):
if case .incomingRing(_, let ringId) = groupThreadCall.groupCallRingState {
groupCallAccessoryMessageDelegate.localDeviceDeclinedGroupRing(
ringId: ringId,
groupId: groupThreadCall.groupId
)
do {
try callManager.cancelGroupRing(
groupId: groupThreadCall.groupId.serialize().asData,
ringId: ringId,
reason: .declinedByUser
)
} catch {
owsFailDebug("RingRTC failed to cancel group ring \(ringId): \(error)")
}
}
leaveAndTerminateGroupCall(call, groupCall: groupThreadCall)
case .callLink(let callLinkCall):
leaveAndTerminateGroupCall(call, groupCall: callLinkCall)
}
}
// MARK: - Video
var shouldHaveLocalVideoTrack: Bool {
guard let call = self.callServiceState.currentCall else {
return false
}
// The iOS simulator doesn't provide any sort of camera capture
// support or emulation (http://goo.gl/rHAnC1) so don't bother
// trying to open a local stream.
guard !Platform.isSimulator else { return false }
guard UIApplication.shared.applicationState != .background else { return false }
switch call.mode {
case .individual(let individualCall):
return individualCall.state == .connected && individualCall.hasLocalVideo
case .groupThread(let call as GroupCall), .callLink(let call as GroupCall):
return !call.ringRtcCall.isOutgoingVideoMuted
}
}
func updateIsVideoEnabled() {
guard let call = self.callServiceState.currentCall else { return }
switch call.mode {
case .individual(let individualCall):
if individualCall.state == .connected || individualCall.state == .reconnecting {
callManager.setLocalVideoEnabled(enabled: shouldHaveLocalVideoTrack, call: call)
} else if individualCall.isViewLoaded, individualCall.hasLocalVideo, !Platform.isSimulator {
// If we're not yet connected, just enable the camera but don't tell RingRTC
// to start sending video. This allows us to show a "vanity" view while connecting.
individualCall.videoCaptureController.startCapture()
} else {
individualCall.videoCaptureController.stopCapture()
}
case .groupThread(let call as GroupCall), .callLink(let call as GroupCall):
if shouldHaveLocalVideoTrack {
call.videoCaptureController.startCapture()
} else {
call.videoCaptureController.stopCapture()
}
}
}
// MARK: -
func buildAndConnectGroupCall(for groupId: GroupIdentifier, isVideoMuted: Bool) -> (SignalCall, GroupThreadCall)? {
return _buildAndConnectGroupCall(isOutgoingVideoMuted: isVideoMuted) { () -> (SignalCall, GroupThreadCall)? in
let videoCaptureController = VideoCaptureController()
let sfuUrl = DebugFlags.callingUseTestSFU.get() ? TSConstants.sfuTestURL : TSConstants.sfuURL
let ringRtcCall = callManager.createGroupCall(
groupId: groupId.serialize().asData,
sfuUrl: sfuUrl,
hkdfExtraInfo: Data(),
audioLevelsIntervalMillis: nil,
videoCaptureController: videoCaptureController
)
guard let ringRtcCall else {
return nil
}
let groupThreadCall = GroupThreadCall(
delegate: self,
ringRtcCall: ringRtcCall,
groupId: groupId,
videoCaptureController: videoCaptureController
)
guard let groupThreadCall else {
return nil
}
return (SignalCall(groupThreadCall: groupThreadCall), groupThreadCall)
}
}
/// Rather than always fetching the current `CallLinkState`,
/// there may be times when we already have a reasonably
/// up-to-date copy of the state and do not wish to have to,
/// say, block UI waiting on a re-fetch. If in doubt, use
/// `.fetch`. Because that is "so fetch."
enum CallLinkStateRetrievalStrategy {
case reuse(SignalServiceKit.CallLinkState)
case fetch
}
func buildAndConnectCallLinkCall(
callLink: CallLink,
callLinkStateRetrievalStrategy: CallLinkStateRetrievalStrategy
) async throws -> (SignalCall, CallLinkCall)? {
let state: SignalServiceKit.CallLinkState
switch callLinkStateRetrievalStrategy {
case .reuse(let callLinkState):
state = callLinkState
case .fetch:
state = try await callLinkStateUpdater.readCallLink(rootKey: callLink.rootKey).get()
}
let localIdentifiers = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction!
let authCredential = try await authCredentialManager.fetchCallLinkAuthCredential(localIdentifiers: localIdentifiers)
let (adminPasskey, isDeleted) = try databaseStorage.read { tx -> (Data?, Bool) in
let callLinkRecord = try callLinkStore.fetch(roomId: callLink.rootKey.deriveRoomId(), tx: tx)
return (callLinkRecord?.adminPasskey, callLinkRecord?.isDeleted == true)
}
if isDeleted {
throw OWSGenericError("Can't join a call link that you've deleted.")
}
return _buildAndConnectGroupCall(isOutgoingVideoMuted: false) { () -> (SignalCall, CallLinkCall)? in
let videoCaptureController = VideoCaptureController()
let sfuUrl = DebugFlags.callingUseTestSFU.get() ? TSConstants.sfuTestURL : TSConstants.sfuURL
let secretParams = CallLinkSecretParams.deriveFromRootKey(callLink.rootKey.bytes)
let authCredentialPresentation = authCredential.present(callLinkParams: secretParams)
let ringRtcCall = callManager.createCallLinkCall(
sfuUrl: sfuUrl,
authCredentialPresentation: authCredentialPresentation.serialize(),
linkRootKey: callLink.rootKey,
adminPasskey: adminPasskey,
hkdfExtraInfo: Data(),
audioLevelsIntervalMillis: nil,
videoCaptureController: videoCaptureController
)
guard let ringRtcCall else {
return nil
}
let callLinkCall = CallLinkCall(
callLink: callLink,
adminPasskey: adminPasskey,
callLinkState: state,
ringRtcCall: ringRtcCall,
videoCaptureController: videoCaptureController
)
return (SignalCall(callLinkCall: callLinkCall), callLinkCall)
}
}
private func _buildAndConnectGroupCall<T: GroupCall>(
isOutgoingVideoMuted: Bool,
createCall: () -> (SignalCall, T)?
) -> (SignalCall, T)? {
guard callServiceState.currentCall == nil else {
return nil
}
guard let (call, groupCall) = createCall() else {
owsFailDebug("Failed to create call")
return nil
}
// By default, group calls should start out with speakerphone enabled.
self.audioService.requestSpeakerphone(isEnabled: true)
groupCall.ringRtcCall.isOutgoingAudioMuted = false
groupCall.ringRtcCall.isOutgoingVideoMuted = isOutgoingVideoMuted
callServiceState.setCurrentCall(call)
// Connect (but don't join) to subscribe to live updates.
guard connectGroupCallIfNeeded(groupCall) else {
callServiceState.terminateCall(call)
return nil
}
return (call, groupCall)
}
func joinGroupCallIfNecessary(_ call: SignalCall, groupCall: GroupCall) {
guard call === self.callServiceState.currentCall else {
owsFailDebug("Can't join a group call if it's not the current call")
return
}
// If we're disconnected, it means we hit an error with the first
// connection, so connect now. (Ex: You try to join a call that's full, and
// then you try to join again.)
guard connectGroupCallIfNeeded(groupCall) else {
owsFailDebug("Can't join a group call if we can't connect()")
return
}
// If we're not yet joined, join now. In general, it's unexpected that
// this method would be called when you're already joined, but it is
// safe to do so.
let ringRtcCall = groupCall.ringRtcCall
if ringRtcCall.localDeviceState.joinState == .notJoined {
ringRtcCall.join()
// Group calls can get disconnected, but we don't count that as ending the call.
// So this call may have already been reported.
if groupCall.commonState.systemState == .notReported {
callUIAdapter.startOutgoingCall(call: call)
}
}
}
private func connectGroupCallIfNeeded(_ groupCall: GroupCall) -> Bool {
if groupCall.hasInvokedConnectMethod {
return true
}
// If we haven't invoked the method, we shouldn't be connected. (Note: The
// converse is NOT true, and that's why we need `hasInvokedConnectMethod`.)
owsAssertDebug(groupCall.ringRtcCall.localDeviceState.connectionState == .notConnected)
let result = groupCall.ringRtcCall.connect()
if result {
groupCall.hasInvokedConnectMethod = true
}
return result
}
/// Leaves the group call & schedules it for termination.
///
/// If the call has already "ended" (RingRTC term), perhaps because we
/// encountered an error, it will terminate the group call immediately.
///
/// We wait for the call to end before terminating to ensure that observers
/// have an opportunity to handle the "call ended" event.
private func leaveAndTerminateGroupCall(_ call: SignalCall, groupCall: GroupCall) {
if groupCall.hasInvokedConnectMethod {
groupCall.ringRtcCall.disconnect()
groupCall.shouldTerminateOnEndEvent = true
} else {
callServiceState.terminateCall(call)
}
}
func initiateCall(to callTarget: CallTarget, isVideo: Bool) {
switch callTarget {
case .individual(let contactThread):
Task { await self.initiateIndividualCall(thread: contactThread, isVideo: isVideo) }
case .groupThread(let groupId):
GroupCallViewController.presentLobby(forGroupId: groupId, videoMuted: !isVideo)
case .callLink(let callLink):
GroupCallViewController.presentLobby(for: callLink)
}
}
private func initiateIndividualCall(thread: TSContactThread, isVideo: Bool) async {
let untrustedThreshold = Date(timeIntervalSinceNow: -OWSIdentityManagerImpl.Constants.defaultUntrustedInterval)
guard let frontmostViewController = UIApplication.shared.frontmostViewController else {
owsFail("Can't start a call if there's no view controller")
}
let prepareResult = await CallStarter.prepareToStartCall(from: frontmostViewController, shouldAskForCameraPermission: isVideo)
guard let prepareResult else {
return
}
guard await SafetyNumberConfirmationSheet.presentRepeatedlyAsNecessary(
for: { [thread.contactAddress] },
from: frontmostViewController,
confirmationText: CallStrings.confirmAndCallButtonTitle,
untrustedThreshold: untrustedThreshold
) else {
return
}
self.callUIAdapter.startAndShowOutgoingCall(thread: thread, prepareResult: prepareResult, hasLocalVideo: isVideo)
}
func buildOutgoingIndividualCallIfPossible(thread: TSContactThread, localDeviceId: DeviceId, hasVideo: Bool) -> (SignalCall, IndividualCall)? {
guard callServiceState.currentCall == nil else { return nil }
let individualCall = IndividualCall.outgoingIndividualCall(
thread: thread,
offerMediaType: hasVideo ? .video : .audio,
localDeviceId: localDeviceId
)
let call = SignalCall(individualCall: individualCall)
return (call, individualCall)
}
// MARK: - Notifications
private func didEnterBackground() {
self.updateIsVideoEnabled()
}
private func didBecomeActive() {
self.updateIsVideoEnabled()
}
private func registrationChanged() {
if let localAci = DependenciesBridge.shared.tsAccountManager.localIdentifiersWithMaybeSneakyTransaction?.aci {
callManager.setSelfUuid(localAci.rawUUID)
}
}
/// The object is the rotation angle necessary to match the new orientation.
static var phoneOrientationDidChange = Notification.Name("CallService.phoneOrientationDidChange")
private func phoneOrientationDidChange() {
guard callServiceState.currentCall != nil else {
return
}
sendPhoneOrientationNotification()
}
private func shouldReorientUI(for call: SignalCall) -> Bool {
owsAssertDebug(!UIDevice.current.isIPad, "iPad has full UIKit rotation support")
switch call.mode {
case .individual(let individualCall):
// If we're in an audio-only 1:1 call, the user isn't going to be looking at the screen.
// Don't distract them with rotating icons.
return individualCall.hasLocalVideo || individualCall.isRemoteVideoEnabled
case .groupThread, .callLink:
// If we're in a group call, we don't want to use rotating icons because we
// don't rotate user video at the same time, and that's very obvious for
// grid view or any non-speaker tile in speaker view.
return false
}
}
private func sendPhoneOrientationNotification() {
owsAssertDebug(!UIDevice.current.isIPad, "iPad has full UIKit rotation support")
let rotationAngle: CGFloat
if let call = callServiceState.currentCall, !shouldReorientUI(for: call) {
// We still send the notification in case we *previously* rotated the UI and now we need to revert back.
// Example:
// 1. In a 1:1 call, either the user or their contact (but not both) has video on
// 2. the user has the phone in landscape
// 3. whoever had video turns it off (but the icons are still landscape-oriented)
// 4. the user rotates back to portrait
rotationAngle = 0
} else {
switch UIDevice.current.orientation {
case .landscapeLeft:
rotationAngle = .halfPi
case .landscapeRight:
rotationAngle = -.halfPi
case .portrait, .portraitUpsideDown, .faceDown, .faceUp, .unknown:
fallthrough
@unknown default:
rotationAngle = 0
}
}
NotificationCenter.default.post(name: Self.phoneOrientationDidChange, object: rotationAngle)
}
/// Pretend the phone just changed orientations so that the call UI will autorotate.
func sendInitialPhoneOrientationNotification() {
guard !UIDevice.current.isIPad else {
return
}
sendPhoneOrientationNotification()
}
// MARK: -
private func updateGroupMembersForCurrentCallIfNecessary() {
DispatchQueue.main.async {
let currentCall = self.callServiceState.currentCall
guard let groupThreadCall = currentCall?.unpackGroupCall() else {
return
}
let membershipInfo: [GroupMemberInfo]
do {
membershipInfo = try self.databaseStorage.read { tx in
try self.groupCallManager.groupCallPeekClient.groupMemberInfo(
forGroupId: groupThreadCall.groupId,
tx: tx
)
}
} catch {
owsFailDebug("Failed to fetch membership info: \(error)")
return
}
groupThreadCall.ringRtcCall.updateGroupMembers(members: membershipInfo)
}
}
// MARK: - Data Modes
static nonisolated let callServicePreferencesDidChange = Notification.Name("CallServicePreferencesDidChange")
private static nonisolated let keyValueStore = KeyValueStore(collection: "CallService")
// This used to be called "high bandwidth", but "data" is more accurate.
private static nonisolated let highDataPreferenceKey = "HighBandwidthPreferenceKey"
static nonisolated func setHighDataInterfaces(_ interfaceSet: NetworkInterfaceSet, writeTx: DBWriteTransaction) {
Logger.info("Updating preferred low data interfaces: \(interfaceSet.rawValue)")
keyValueStore.setUInt(interfaceSet.rawValue, key: highDataPreferenceKey, transaction: writeTx)
writeTx.addSyncCompletion {
NotificationCenter.default.postOnMainThread(name: callServicePreferencesDidChange, object: nil)
}
}
static nonisolated func highDataNetworkInterfaces(readTx: DBReadTransaction) -> NetworkInterfaceSet {
guard let highDataPreference = keyValueStore.getUInt(
highDataPreferenceKey,
transaction: readTx) else { return .wifiAndCellular }
return NetworkInterfaceSet(rawValue: highDataPreference)
}
}
extension CallService: IndividualCallObserver {
func individualCallStateDidChange(_ call: IndividualCall, state: CallState) {
updateIsVideoEnabled()
configureDataMode()
}
func individualCallLocalVideoMuteDidChange(_ call: IndividualCall, isVideoMuted: Bool) {
updateIsVideoEnabled()
}
}
extension CallService: GroupCallObserver {
func groupCallLocalDeviceStateChanged(_ call: GroupCall) {
let ringRtcCall = call.ringRtcCall
Logger.info("")
updateIsVideoEnabled()
configureDataMode()
switch call.concreteType {
case .groupThread(let call):
updateGroupMembersForCurrentCallIfNecessary()
if
ringRtcCall.localDeviceState.isJoined,
case .shouldRing = call.groupCallRingState,
call.ringRestrictions.isEmpty,
ringRtcCall.remoteDeviceStates.isEmpty
{
// Don't start ringing until we join the call successfully.
call.groupCallRingState = .ringing
ringRtcCall.ringAll()
audioService.playOutboundRing()
}
if ringRtcCall.localDeviceState.isJoined {
if let eraId = ringRtcCall.peekInfo?.eraId {
groupCallAccessoryMessageDelegate.localDeviceMaybeJoinedGroupCall(
eraId: eraId,
groupId: call.groupId,
groupCallRingState: call.groupCallRingState
)
}
} else {
groupCallAccessoryMessageDelegate.localDeviceMaybeLeftGroupCall(
groupId: call.groupId,
groupCall: ringRtcCall
)
}
case .callLink:
self.adHocCallStateObserver!.checkIfJoined()
}
}
func groupCallPeekChanged(_ call: GroupCall) {
let ringRtcCall = call.ringRtcCall
guard let peekInfo = ringRtcCall.peekInfo else {
Logger.warn("No peek info for call: \(call)")
return
}
switch call.concreteType {
case .groupThread(let call):
let groupId = call.groupId
if
ringRtcCall.localDeviceState.isJoined,
let eraId = peekInfo.eraId
{
groupCallAccessoryMessageDelegate.localDeviceMaybeJoinedGroupCall(
eraId: eraId,
groupId: call.groupId,
groupCallRingState: call.groupCallRingState
)
}
databaseStorage.asyncWrite { tx in
self.groupCallManager.updateGroupCallModelsForPeek(
peekInfo: peekInfo,
groupId: groupId,
triggerEventTimestamp: MessageTimestampGenerator.sharedInstance.generateTimestamp(),
tx: tx
)
}
case .callLink:
self.adHocCallStateObserver!.checkIfActive()
self.adHocCallStateObserver!.checkIfJoined()
}
}
func groupCallEnded(_ groupCall: GroupCall, reason: GroupCallEndReason) {
groupCallAccessoryMessageDelegate.localDeviceGroupCallDidEnd()
let call = callServiceState.currentCall
switch call?.mode {
case nil, .individual:
owsFail("Can't receive callback without an active group call")
case .groupThread(let currentCall as GroupCall), .callLink(let currentCall as GroupCall):
owsPrecondition(currentCall === groupCall)
if currentCall.shouldTerminateOnEndEvent {
callServiceState.terminateCall(call!)
}
}
}
public func groupCallRemoteDeviceStatesChanged(_ call: GroupCall) {
switch call.concreteType {
case .groupThread(let call):
if
case .ringing = call.groupCallRingState,
!call.ringRtcCall.remoteDeviceStates.isEmpty
{
// The first time someone joins after a ring, we need to mark the call accepted.
// (But if we didn't ring, the call will have already been marked accepted.)
callUIAdapter.recipientAcceptedCall(.groupThread(call))
}
case .callLink:
break
}
}
}
extension CallService: GroupThreadCallDelegate {
func groupThreadCallRequestMembershipProof(_ call: GroupThreadCall) {
Logger.info("")
let groupCall = call.ringRtcCall
Task { [groupCallManager] in
let databaseStorage = SSKEnvironment.shared.databaseStorageRef
let groupThread = databaseStorage.read { tx in
return TSGroupThread.fetch(forGroupId: call.groupId, tx: tx)
}
guard let groupModel = groupThread?.groupModel as? TSGroupModelV2 else {