-
Notifications
You must be signed in to change notification settings - Fork 445
/
RNCallKeep.m
1157 lines (1022 loc) · 41.2 KB
/
RNCallKeep.m
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
//
// RNCallKeep.m
// RNCallKeep
//
// Copyright 2016-2019 The CallKeep Authors (see the AUTHORS file)
// SPDX-License-Identifier: ISC, MIT
//
#import "RNCallKeep.h"
#import <React/RCTBridge.h>
#import <React/RCTConvert.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTUtils.h>
#import <React/RCTLog.h>
#import <AVFoundation/AVAudioSession.h>
#import <CallKit/CallKit.h>
#ifdef DEBUG
static int const OUTGOING_CALL_WAKEUP_DELAY = 10;
#else
static int const OUTGOING_CALL_WAKEUP_DELAY = 5;
#endif
static NSString *const RNCallKeepHandleStartCallNotification = @"RNCallKeepHandleStartCallNotification";
static NSString *const RNCallKeepDidReceiveStartCallAction = @"RNCallKeepDidReceiveStartCallAction";
static NSString *const RNCallKeepPerformAnswerCallAction = @"RNCallKeepPerformAnswerCallAction";
static NSString *const RNCallKeepPerformEndCallAction = @"RNCallKeepPerformEndCallAction";
static NSString *const RNCallKeepDidActivateAudioSession = @"RNCallKeepDidActivateAudioSession";
static NSString *const RNCallKeepDidDeactivateAudioSession = @"RNCallKeepDidDeactivateAudioSession";
static NSString *const RNCallKeepDidDisplayIncomingCall = @"RNCallKeepDidDisplayIncomingCall";
static NSString *const RNCallKeepDidPerformSetMutedCallAction = @"RNCallKeepDidPerformSetMutedCallAction";
static NSString *const RNCallKeepPerformPlayDTMFCallAction = @"RNCallKeepDidPerformDTMFAction";
static NSString *const RNCallKeepDidToggleHoldAction = @"RNCallKeepDidToggleHoldAction";
static NSString *const RNCallKeepProviderReset = @"RNCallKeepProviderReset";
static NSString *const RNCallKeepCheckReachability = @"RNCallKeepCheckReachability";
static NSString *const RNCallKeepDidChangeAudioRoute = @"RNCallKeepDidChangeAudioRoute";
static NSString *const RNCallKeepDidLoadWithEvents = @"RNCallKeepDidLoadWithEvents";
@implementation RNCallKeep
{
NSOperatingSystemVersion _version;
BOOL _isStartCallActionEventListenerAdded;
bool _hasListeners;
bool _isReachable;
NSMutableArray *_delayedEvents;
}
static bool isSetupNatively;
static CXProvider* sharedProvider;
// should initialise in AppDelegate.m
RCT_EXPORT_MODULE()
- (instancetype)init
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][init]");
#endif
if (self = [super init]) {
_isStartCallActionEventListenerAdded = NO;
_isReachable = NO;
if (_delayedEvents == nil) _delayedEvents = [NSMutableArray array];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onAudioRouteChange:)
name:AVAudioSessionRouteChangeNotification
object:nil];
// Init provider directly, in case of an app killed and when we've already stored our settings
[RNCallKeep initCallKitProvider];
self.callKeepProvider = sharedProvider;
[self.callKeepProvider setDelegate:self queue:nil];
}
return self;
}
+ (id)allocWithZone:(NSZone *)zone {
static RNCallKeep *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [super allocWithZone:zone];
});
return sharedInstance;
}
- (void)dealloc
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][dealloc]");
#endif
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (self.callKeepProvider != nil) {
[self.callKeepProvider invalidate];
}
sharedProvider = nil;
_isReachable = NO;
}
// Override method of RCTEventEmitter
- (NSArray<NSString *> *)supportedEvents
{
return @[
RNCallKeepDidReceiveStartCallAction,
RNCallKeepPerformAnswerCallAction,
RNCallKeepPerformEndCallAction,
RNCallKeepDidActivateAudioSession,
RNCallKeepDidDeactivateAudioSession,
RNCallKeepDidDisplayIncomingCall,
RNCallKeepDidPerformSetMutedCallAction,
RNCallKeepPerformPlayDTMFCallAction,
RNCallKeepDidToggleHoldAction,
RNCallKeepProviderReset,
RNCallKeepCheckReachability,
RNCallKeepDidLoadWithEvents,
RNCallKeepDidChangeAudioRoute
];
}
- (void)startObserving
{
NSLog(@"[RNCallKeep][startObserving]");
_hasListeners = YES;
if ([_delayedEvents count] > 0) {
[self sendEventWithName:RNCallKeepDidLoadWithEvents body:_delayedEvents];
}
}
- (void)stopObserving
{
_hasListeners = FALSE;
// Fix for https://github.com/react-native-webrtc/react-native-callkeep/issues/406
// We use Objective-C Key Value Coding(KVC) to sync _RTCEventEmitter_ `_listenerCount`.
@try {
[self setValue:@0 forKey:@"_listenerCount"];
}
@catch ( NSException *e ){
NSLog(@"[RNCallKeep][stopObserving] exception: %@",e);
NSLog(@"[RNCallKeep][stopObserving] RNCallKeep parent class RTCEventEmitter might have a broken state.");
NSLog(@"[RNCallKeep][stopObserving] Please verify that the parent RTCEventEmitter.m has iVar `_listenerCount`.");
}
}
- (void)onAudioRouteChange:(NSNotification *)notification
{
NSDictionary *info = notification.userInfo;
NSInteger reason = [[info valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
NSString *output = [RNCallKeep getAudioOutput];
if (output == nil) {
return;
}
[self sendEventWithName:RNCallKeepDidChangeAudioRoute body:@{
@"output": output,
@"reason": @(reason),
}];
}
- (void)sendEventWithNameWrapper:(NSString *)name body:(id)body {
NSLog(@"[RNCallKeep] sendEventWithNameWrapper: %@, hasListeners : %@", name, _hasListeners ? @"YES": @"NO");
if (_hasListeners) {
[self sendEventWithName:name body:body];
} else {
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
name, @"name",
body, @"data",
nil
];
[_delayedEvents addObject:dictionary];
}
}
+ (NSDictionary *) getSettings {
return [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"RNCallKeepSettings"];
}
+ (void)initCallKitProvider {
if (sharedProvider == nil) {
NSDictionary *settings = [self getSettings];
if (settings != nil) {
sharedProvider = [[CXProvider alloc] initWithConfiguration:[RNCallKeep getProviderConfiguration:settings]];
}
}
}
+ (NSString *) getAudioOutput {
@try{
NSArray<AVAudioSessionPortDescription *>* outputs = [AVAudioSession sharedInstance].currentRoute.outputs;
if(outputs != nil && outputs.count > 0){
return outputs[0].portType;
}
} @catch(NSException* error) {
NSLog(@"getAudioOutput error :%@", [error description]);
}
return nil;
}
+ (void)setup:(NSDictionary *)options {
RNCallKeep *callKeep = [RNCallKeep allocWithZone: nil];
[callKeep setup:options];
isSetupNatively = YES;
}
RCT_EXPORT_METHOD(setup:(NSDictionary *)options)
{
if (isSetupNatively) {
#ifdef DEBUG
NSLog(@"[RNCallKeep][setup] already setup");
RCTLog(@"[RNCallKeep][setup] already setup in native code");
#endif
return;
}
#ifdef DEBUG
NSLog(@"[RNCallKeep][setup] options = %@", options);
#endif
_version = [[[NSProcessInfo alloc] init] operatingSystemVersion];
self.callKeepCallController = [[CXCallController alloc] init];
[self setSettings: options];
[RNCallKeep initCallKitProvider];
self.callKeepProvider = sharedProvider;
[self.callKeepProvider setDelegate:self queue:nil];
}
RCT_EXPORT_METHOD(setSettings:(NSDictionary *)options)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][setSettings] options = %@", options);
#endif
NSDictionary *settings = [[NSMutableDictionary alloc] initWithDictionary:options];
// Store settings in NSUserDefault
[[NSUserDefaults standardUserDefaults] setObject:settings forKey:@"RNCallKeepSettings"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
RCT_EXPORT_METHOD(setReachable)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][setReachable]");
#endif
_isReachable = YES;
}
RCT_REMAP_METHOD(checkIfBusy,
checkIfBusyWithResolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][checkIfBusy]");
#endif
resolve(@(self.callKeepCallController.callObserver.calls.count > 0));
}
RCT_REMAP_METHOD(checkSpeaker,
checkSpeakerResolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][checkSpeaker]");
#endif
NSString *output = [RNCallKeep getAudioOutput];
resolve(@([output isEqualToString:@"Speaker"]));
}
#pragma mark - CXCallController call actions
// Display the incoming call to the user
RCT_EXPORT_METHOD(displayIncomingCall:(NSString *)uuidString
handle:(NSString *)handle
handleType:(NSString *)handleType
hasVideo:(BOOL)hasVideo
localizedCallerName:(NSString * _Nullable)localizedCallerName
supportsHolding:(BOOL)supportsHolding
supportsDTMF:(BOOL)supportsDTMF
supportsGrouping:(BOOL)supportsGrouping
supportsUngrouping:(BOOL)supportsUngrouping)
{
[RNCallKeep reportNewIncomingCall: uuidString
handle: handle
handleType: handleType
hasVideo: hasVideo
localizedCallerName: localizedCallerName
supportsHolding: supportsHolding
supportsDTMF: supportsDTMF
supportsGrouping: supportsGrouping
supportsUngrouping: supportsUngrouping
fromPushKit: NO
payload: nil
withCompletionHandler: nil];
NSDictionary *settings = [RNCallKeep getSettings];
NSNumber *timeout = settings[@"displayCallReachabilityTimeout"];
if (timeout) {
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)([timeout intValue] * NSEC_PER_MSEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
if (!self->_isReachable) {
#ifdef DEBUG
NSLog(@"[RNCallKeep]Displayed a call without a reachable app, ending the call: %@", uuidString);
#endif
[RNCallKeep endCallWithUUID: uuidString reason: 1];
}
});
}
}
RCT_EXPORT_METHOD(getInitialEvents:(RCTPromiseResolveBlock)resolve
reject:(RCTPromiseRejectBlock)reject)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][getInitialEvents]");
#endif
resolve(_delayedEvents);
}
RCT_EXPORT_METHOD(clearInitialEvents)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][clearInitialEvents]");
#endif
_delayedEvents = [NSMutableArray array];
}
RCT_EXPORT_METHOD(startCall:(NSString *)uuidString
handle:(NSString *)handle
contactIdentifier:(NSString * _Nullable)contactIdentifier
handleType:(NSString *)handleType
video:(BOOL)video)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][startCall] uuidString = %@", uuidString);
#endif
int _handleType = [RNCallKeep getHandleType:handleType];
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:uuidString];
CXHandle *callHandle = [[CXHandle alloc] initWithType:_handleType value:handle];
CXStartCallAction *startCallAction = [[CXStartCallAction alloc] initWithCallUUID:uuid handle:callHandle];
[startCallAction setVideo:video];
[startCallAction setContactIdentifier:contactIdentifier];
CXTransaction *transaction = [[CXTransaction alloc] initWithAction:startCallAction];
[self requestTransaction:transaction];
}
RCT_EXPORT_METHOD(answerIncomingCall:(NSString *)uuidString)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][answerIncomingCall] uuidString = %@", uuidString);
#endif
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:uuidString];
CXAnswerCallAction *answerCallAction = [[CXAnswerCallAction alloc] initWithCallUUID:uuid];
CXTransaction *transaction = [[CXTransaction alloc] init];
[transaction addAction:answerCallAction];
[self requestTransaction:transaction];
}
RCT_EXPORT_METHOD(endCall:(NSString *)uuidString)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][endCall] uuidString = %@", uuidString);
#endif
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:uuidString];
CXEndCallAction *endCallAction = [[CXEndCallAction alloc] initWithCallUUID:uuid];
CXTransaction *transaction = [[CXTransaction alloc] initWithAction:endCallAction];
[self requestTransaction:transaction];
}
RCT_EXPORT_METHOD(endAllCalls)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][endAllCalls] calls = %@", self.callKeepCallController.callObserver.calls);
#endif
for (CXCall *call in self.callKeepCallController.callObserver.calls) {
CXEndCallAction *endCallAction = [[CXEndCallAction alloc] initWithCallUUID:call.UUID];
CXTransaction *transaction = [[CXTransaction alloc] initWithAction:endCallAction];
[self requestTransaction:transaction];
}
}
RCT_EXPORT_METHOD(setOnHold:(NSString *)uuidString :(BOOL)shouldHold)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][setOnHold] uuidString = %@, shouldHold = %d", uuidString, shouldHold);
#endif
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:uuidString];
CXSetHeldCallAction *setHeldCallAction = [[CXSetHeldCallAction alloc] initWithCallUUID:uuid onHold:shouldHold];
CXTransaction *transaction = [[CXTransaction alloc] init];
[transaction addAction:setHeldCallAction];
[self requestTransaction:transaction];
}
RCT_EXPORT_METHOD(_startCallActionEventListenerAdded)
{
_isStartCallActionEventListenerAdded = YES;
}
RCT_EXPORT_METHOD(reportConnectingOutgoingCallWithUUID:(NSString *)uuidString)
{
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:uuidString];
[self.callKeepProvider reportOutgoingCallWithUUID:uuid startedConnectingAtDate:[NSDate date]];
}
RCT_EXPORT_METHOD(reportConnectedOutgoingCallWithUUID:(NSString *)uuidString)
{
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:uuidString];
[self.callKeepProvider reportOutgoingCallWithUUID:uuid connectedAtDate:[NSDate date]];
}
RCT_EXPORT_METHOD(reportEndCallWithUUID:(NSString *)uuidString :(int)reason)
{
[RNCallKeep endCallWithUUID: uuidString reason:reason];
}
RCT_EXPORT_METHOD(updateDisplay:(NSString *)uuidString :(NSString *)displayName :(NSString *)uri :(NSDictionary *)options)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][updateDisplay] uuidString = %@ displayName = %@ uri = %@", uuidString, displayName, uri);
#endif
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:uuidString];
CXHandle *callHandle = [[CXHandle alloc] initWithType:CXHandleTypePhoneNumber value:uri];
CXCallUpdate *callUpdate = [[CXCallUpdate alloc] init];
callUpdate.localizedCallerName = displayName;
callUpdate.remoteHandle = callHandle;
if ([options valueForKey:@"hasVideo"] != nil) {
callUpdate.hasVideo = [RCTConvert BOOL:options[@"hasVideo"]];
}
if ([options valueForKey:@"supportsHolding"] != nil) {
callUpdate.supportsHolding = [RCTConvert BOOL:options[@"supportsHolding"]];
}
if ([options valueForKey:@"supportsDTMF"] != nil) {
callUpdate.supportsDTMF = [RCTConvert BOOL:options[@"supportsDTMF"]];
}
if ([options valueForKey:@"supportsGrouping"] != nil) {
callUpdate.supportsGrouping = [RCTConvert BOOL:options[@"supportsGrouping"]];
}
if ([options valueForKey:@"supportsUngrouping"] != nil) {
callUpdate.supportsUngrouping = [RCTConvert BOOL:options[@"supportsUngrouping"]];
}
[self.callKeepProvider reportCallWithUUID:uuid updated:callUpdate];
}
RCT_EXPORT_METHOD(setMutedCall:(NSString *)uuidString :(BOOL)muted)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][setMutedCall] muted = %i", muted);
#endif
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:uuidString];
CXSetMutedCallAction *setMutedAction = [[CXSetMutedCallAction alloc] initWithCallUUID:uuid muted:muted];
CXTransaction *transaction = [[CXTransaction alloc] init];
[transaction addAction:setMutedAction];
[self requestTransaction:transaction];
}
RCT_EXPORT_METHOD(sendDTMF:(NSString *)uuidString dtmf:(NSString *)key)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][sendDTMF] key = %@", key);
#endif
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:uuidString];
CXPlayDTMFCallAction *dtmfAction = [[CXPlayDTMFCallAction alloc] initWithCallUUID:uuid digits:key type:CXPlayDTMFCallActionTypeHardPause];
CXTransaction *transaction = [[CXTransaction alloc] init];
[transaction addAction:dtmfAction];
[self requestTransaction:transaction];
}
RCT_EXPORT_METHOD(isCallActive:(NSString *)uuidString
isCallActiveResolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][isCallActive] uuid = %@", uuidString);
#endif
BOOL isActive = [RNCallKeep isCallActive: uuidString];
if (isActive) {
resolve(@YES);
} else {
resolve(@NO);
}
}
RCT_EXPORT_METHOD(getCalls:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][getCalls]");
#endif
resolve([RNCallKeep getCalls]);
}
RCT_EXPORT_METHOD(setAudioRoute: (NSString *)uuid
inputName:(NSString *)inputName
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][setAudioRoute] - inputName: %@", inputName);
#endif
@try {
NSError* err = nil;
AVAudioSession* myAudioSession = [AVAudioSession sharedInstance];
if ([inputName isEqualToString:@"Speaker"]) {
BOOL isOverrided = [myAudioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&err];
if(!isOverrided){
[NSException raise:@"overrideOutputAudioPort failed" format:@"error: %@", err];
}
resolve(@"Speaker");
return;
}
NSArray *ports = [RNCallKeep getAudioInputs];
for (AVAudioSessionPortDescription *port in ports) {
if ([port.portName isEqualToString:inputName]) {
BOOL isSetted = [myAudioSession setPreferredInput:(AVAudioSessionPortDescription *)port error:&err];
if(!isSetted){
[NSException raise:@"setPreferredInput failed" format:@"error: %@", err];
}
resolve(inputName);
return;
}
}
}
@catch ( NSException *e ){
NSLog(@"[RNCallKeep][setAudioRoute] exception: %@",e);
reject(@"Failure to set audio route", e, nil);
}
}
RCT_EXPORT_METHOD(getAudioRoutes: (RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][getAudioRoutes]");
#endif
@try {
NSArray *inputs = [RNCallKeep getAudioInputs];
NSMutableArray *formatedInputs = [RNCallKeep formatAudioInputs: inputs];
resolve(formatedInputs);
}
@catch ( NSException *e ) {
NSLog(@"[RNCallKeep][getAudioRoutes] exception: %@",e);
reject(@"Failure to get audio routes", e, nil);
}
}
+ (NSMutableArray *) formatAudioInputs: (NSMutableArray *)inputs
{
NSMutableArray *newInputs = [NSMutableArray new];
NSString * selected = [RNCallKeep getSelectedAudioRoute];
NSMutableDictionary *speakerDict = [[NSMutableDictionary alloc]init];
[speakerDict setObject:@"Speaker" forKey:@"name"];
[speakerDict setObject:AVAudioSessionPortBuiltInSpeaker forKey:@"type"];
if(selected && [selected isEqualToString:AVAudioSessionPortBuiltInSpeaker]){
[speakerDict setObject:@YES forKey:@"selected"];
}
[newInputs addObject:speakerDict];
for (AVAudioSessionPortDescription* input in inputs)
{
NSString *str = [NSString stringWithFormat:@"PORTS :\"%@\": UID:%@", input.portName, input.UID ];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setObject:input.portName forKey:@"name"];
NSString * type = [RNCallKeep getAudioInputType: input.portType];
if(type)
{
if([selected isEqualToString:type]){
[dict setObject:@YES forKey:@"selected"];
}
[dict setObject:type forKey:@"type"];
[newInputs addObject:dict];
}
}
return newInputs;
}
+ (NSArray *) getAudioInputs
{
NSError* err = nil;
NSString *str = nil;
AVAudioSession* myAudioSession = [AVAudioSession sharedInstance];
NSString *category = [myAudioSession category];
NSUInteger options = [myAudioSession categoryOptions];
if(![category isEqualToString:AVAudioSessionCategoryPlayAndRecord] && (options != AVAudioSessionCategoryOptionAllowBluetooth) && (options !=AVAudioSessionCategoryOptionAllowBluetoothA2DP))
{
BOOL isCategorySetted = [myAudioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:&err];
if (!isCategorySetted)
{
NSLog(@"setCategory failed");
[NSException raise:@"setCategory failed" format:@"error: %@", err];
}
}
BOOL isCategoryActivated = [myAudioSession setActive:YES error:&err];
if (!isCategoryActivated)
{
NSLog(@"[RNCallKeep][getAudioInputs] setActive failed");
[NSException raise:@"setActive failed" format:@"error: %@", err];
}
NSArray *inputs = [myAudioSession availableInputs];
return inputs;
}
+ (NSString *) getAudioInputType: (NSString *) type
{
if ([type isEqualToString:AVAudioSessionPortBuiltInMic]){
return @"Phone";
}
else if ([type isEqualToString:AVAudioSessionPortHeadsetMic]){
return @"Headset";
}
else if ([type isEqualToString:AVAudioSessionPortHeadphones]){
return @"Headset";
}
else if ([type isEqualToString:AVAudioSessionPortBluetoothHFP]){
return @"Bluetooth";
}
else if ([type isEqualToString:AVAudioSessionPortBluetoothA2DP]){
return @"Bluetooth";
}
else if ([type isEqualToString:AVAudioSessionPortBuiltInSpeaker]){
return @"Speaker";
}
else if ([type isEqualToString:AVAudioSessionPortCarAudio]) {
return @"CarAudio";
}
else{
return nil;
}
}
+ (NSString *) getSelectedAudioRoute
{
AVAudioSession* myAudioSession = [AVAudioSession sharedInstance];
AVAudioSessionRouteDescription *currentRoute = [myAudioSession currentRoute];
NSArray *selectedOutputs = currentRoute.outputs;
AVAudioSessionPortDescription *selectedOutput = selectedOutputs[0];
if(selectedOutput && [selectedOutput.portType isEqualToString:AVAudioSessionPortBuiltInReceiver]) {
return @"Phone";
}
return [RNCallKeep getAudioInputType: selectedOutput.portType];
}
- (void)requestTransaction:(CXTransaction *)transaction
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][requestTransaction] transaction = %@", transaction);
#endif
if (self.callKeepCallController == nil) {
self.callKeepCallController = [[CXCallController alloc] init];
}
[self.callKeepCallController requestTransaction:transaction completion:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(@"[RNCallKeep][requestTransaction] Error requesting transaction (%@): (%@)", transaction.actions, error);
} else {
NSLog(@"[RNCallKeep][requestTransaction] Requested transaction successfully");
// CXStartCallAction
if ([[transaction.actions firstObject] isKindOfClass:[CXStartCallAction class]]) {
CXStartCallAction *startCallAction = [transaction.actions firstObject];
CXCallUpdate *callUpdate = [[CXCallUpdate alloc] init];
callUpdate.remoteHandle = startCallAction.handle;
callUpdate.hasVideo = startCallAction.video;
callUpdate.localizedCallerName = startCallAction.contactIdentifier;
callUpdate.supportsDTMF = YES;
callUpdate.supportsHolding = YES;
callUpdate.supportsGrouping = YES;
callUpdate.supportsUngrouping = YES;
[self.callKeepProvider reportCallWithUUID:startCallAction.callUUID updated:callUpdate];
}
}
}];
}
+ (BOOL)isCallActive:(NSString *)uuidString
{
CXCallObserver *callObserver = [[CXCallObserver alloc] init];
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:uuidString];
for(CXCall *call in callObserver.calls){
NSLog(@"[RNCallKeep] isCallActive %@ %d ?", call.UUID, [call.UUID isEqual:uuid]);
if([call.UUID isEqual:[[NSUUID alloc] initWithUUIDString:uuidString]]){
return call.hasConnected;
}
}
return false;
}
+ (NSMutableArray *) getCalls
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][getCalls]");
#endif
CXCallObserver *callObserver = [[CXCallObserver alloc] init];
NSMutableArray *currentCalls = [NSMutableArray array];
for(CXCall *call in callObserver.calls){
NSString *uuidString = [call.UUID UUIDString];
NSDictionary *requestedCall= @{
@"callUUID": uuidString,
@"outgoing": call.outgoing? @YES : @NO,
@"onHold": call.onHold? @YES : @NO,
@"hasConnected": call.hasConnected ? @YES : @NO,
@"hasEnded": call.hasEnded ? @YES : @NO
};
[currentCalls addObject:requestedCall];
}
return currentCalls;
}
+ (void)endCallWithUUID:(NSString *)uuidString
reason:(int)reason
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][reportEndCallWithUUID] uuidString = %@ reason = %d", uuidString, reason);
#endif
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:uuidString];
switch (reason) {
case 1:
[sharedProvider reportCallWithUUID:uuid endedAtDate:[NSDate date] reason:CXCallEndedReasonFailed];
break;
case 2:
case 6:
[sharedProvider reportCallWithUUID:uuid endedAtDate:[NSDate date] reason:CXCallEndedReasonRemoteEnded];
break;
case 3:
[sharedProvider reportCallWithUUID:uuid endedAtDate:[NSDate date] reason:CXCallEndedReasonUnanswered];
break;
case 4:
[sharedProvider reportCallWithUUID:uuid endedAtDate:[NSDate date] reason:CXCallEndedReasonAnsweredElsewhere];
break;
case 5:
[sharedProvider reportCallWithUUID:uuid endedAtDate:[NSDate date] reason:CXCallEndedReasonDeclinedElsewhere];
break;
default:
break;
}
}
+ (void)reportNewIncomingCall:(NSString *)uuidString
handle:(NSString *)handle
handleType:(NSString *)handleType
hasVideo:(BOOL)hasVideo
localizedCallerName:(NSString * _Nullable)localizedCallerName
supportsHolding:(BOOL)supportsHolding
supportsDTMF:(BOOL)supportsDTMF
supportsGrouping:(BOOL)supportsGrouping
supportsUngrouping:(BOOL)supportsUngrouping
fromPushKit:(BOOL)fromPushKit
payload:(NSDictionary * _Nullable)payload
withCompletionHandler:(void (^_Nullable)(void))completion
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][reportNewIncomingCall] uuidString = %@", uuidString);
#endif
int _handleType = [RNCallKeep getHandleType:handleType];
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:uuidString];
CXCallUpdate *callUpdate = [[CXCallUpdate alloc] init];
callUpdate.remoteHandle = [[CXHandle alloc] initWithType:_handleType value:handle];
callUpdate.supportsHolding = supportsHolding;
callUpdate.supportsDTMF = supportsDTMF;
callUpdate.supportsGrouping = supportsGrouping;
callUpdate.supportsUngrouping = supportsUngrouping;
callUpdate.hasVideo = hasVideo;
callUpdate.localizedCallerName = localizedCallerName;
[RNCallKeep initCallKitProvider];
[sharedProvider reportNewIncomingCallWithUUID:uuid update:callUpdate completion:^(NSError * _Nullable error) {
RNCallKeep *callKeep = [RNCallKeep allocWithZone: nil];
[callKeep sendEventWithNameWrapper:RNCallKeepDidDisplayIncomingCall body:@{
@"error": error && error.localizedDescription ? error.localizedDescription : @"",
@"errorCode": error ? [callKeep getIncomingCallErrorCode:error] : @"",
@"callUUID": uuidString,
@"handle": handle,
@"localizedCallerName": localizedCallerName ? localizedCallerName : @"",
@"hasVideo": hasVideo ? @"1" : @"0",
@"supportsHolding": supportsHolding ? @"1" : @"0",
@"supportsDTMF": supportsDTMF ? @"1" : @"0",
@"supportsGrouping": supportsGrouping ? @"1" : @"0",
@"supportsUngrouping": supportsUngrouping ? @"1" : @"0",
@"fromPushKit": fromPushKit ? @"1" : @"0",
@"payload": payload ? payload : @"",
}];
if (error == nil) {
// Workaround per https://forums.developer.apple.com/message/169511
if ([callKeep lessThanIos10_2]) {
[callKeep configureAudioSession];
}
}
if (completion != nil) {
completion();
}
}];
}
- (NSString *)getIncomingCallErrorCode:(NSError *)error {
if ([error code] == CXErrorCodeIncomingCallErrorUnentitled) {
return @"Unentitled";
} else if ([error code] == CXErrorCodeIncomingCallErrorCallUUIDAlreadyExists) {
return @"CallUUIDAlreadyExists";
} else if ([error code] == CXErrorCodeIncomingCallErrorFilteredByDoNotDisturb) {
return @"FilteredByDoNotDisturb";
} else if ([error code] == CXErrorCodeIncomingCallErrorFilteredByBlockList) {
return @"FilteredByBlockList";
} else {
return @"Unknown";
}
}
- (BOOL)lessThanIos10_2
{
if (_version.majorVersion < 10) {
return YES;
} else if (_version.majorVersion > 10) {
return NO;
} else {
return _version.minorVersion < 2;
}
}
+ (NSSet *) getSupportedHandleTypes:(id) handleType {
if(handleType){
if([handleType isKindOfClass:[NSArray class]]) {
NSSet *types = [NSSet set];
for (NSString* type in handleType) {
types = [types setByAddingObject:[NSNumber numberWithInteger:[RNCallKeep getHandleType:type]]];
}
return types;
} else {
int _handleType = [RNCallKeep getHandleType:handleType];
return [NSSet setWithObjects:[NSNumber numberWithInteger:_handleType], nil];
}
} else {
return [NSSet setWithObjects:[NSNumber numberWithInteger:CXHandleTypePhoneNumber], nil];
}
}
+ (int)getHandleType:(NSString *)handleType
{
if ([handleType isEqualToString:@"generic"]) {
return CXHandleTypeGeneric;
} else if ([handleType isEqualToString:@"number"]) {
return CXHandleTypePhoneNumber;
} else if ([handleType isEqualToString:@"phone"]) {
return CXHandleTypePhoneNumber;
} else if ([handleType isEqualToString:@"email"]) {
return CXHandleTypeEmailAddress;
} else {
return CXHandleTypeGeneric;
}
}
+ (CXProviderConfiguration *)getProviderConfiguration:(NSDictionary*)settings
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][getProviderConfiguration]");
#endif
CXProviderConfiguration *providerConfiguration = [[CXProviderConfiguration alloc] initWithLocalizedName:settings[@"appName"]];
providerConfiguration.supportsVideo = YES;
providerConfiguration.maximumCallGroups = 3;
providerConfiguration.maximumCallsPerCallGroup = 1;
providerConfiguration.supportedHandleTypes = [RNCallKeep getSupportedHandleTypes:settings[@"handleType"]];
if (settings[@"supportsVideo"]) {
providerConfiguration.supportsVideo = [settings[@"supportsVideo"] boolValue];
}
if (settings[@"maximumCallGroups"]) {
providerConfiguration.maximumCallGroups = [settings[@"maximumCallGroups"] integerValue];
}
if (settings[@"maximumCallsPerCallGroup"]) {
providerConfiguration.maximumCallsPerCallGroup = [settings[@"maximumCallsPerCallGroup"] integerValue];
}
if (settings[@"imageName"]) {
providerConfiguration.iconTemplateImageData = UIImagePNGRepresentation([UIImage imageNamed:settings[@"imageName"]]);
}
if (settings[@"ringtoneSound"]) {
providerConfiguration.ringtoneSound = settings[@"ringtoneSound"];
}
if (@available(iOS 11.0, *)) {
if (settings[@"includesCallsInRecents"]) {
providerConfiguration.includesCallsInRecents = [settings[@"includesCallsInRecents"] boolValue];
}
}
return providerConfiguration;
}
- (void)configureAudioSession
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][configureAudioSession] Activating audio session");
#endif
NSUInteger categoryOptions = AVAudioSessionCategoryOptionAllowBluetooth | AVAudioSessionCategoryOptionAllowBluetoothA2DP;
NSString *mode = AVAudioSessionModeDefault;
NSDictionary *settings = [RNCallKeep getSettings];
if (settings && settings[@"audioSession"]) {
if (settings[@"audioSession"][@"categoryOptions"]) {
categoryOptions = [settings[@"audioSession"][@"categoryOptions"] integerValue];
}
if (settings[@"audioSession"][@"mode"]) {
mode = settings[@"audioSession"][@"mode"];
}
}
AVAudioSession* audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:categoryOptions error:nil];
[audioSession setMode:mode error:nil];
double sampleRate = 44100.0;
[audioSession setPreferredSampleRate:sampleRate error:nil];
NSTimeInterval bufferDuration = .005;
[audioSession setPreferredIOBufferDuration:bufferDuration error:nil];
[audioSession setActive:TRUE error:nil];
}
+ (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options NS_AVAILABLE_IOS(9_0)
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][application:openURL]");
#endif
/*
NSString *handle = [url startCallHandle];
if (handle != nil && handle.length > 0 ){
NSDictionary *userInfo = @{
@"handle": handle,
@"video": @NO
};
[[NSNotificationCenter defaultCenter] postNotificationName:RNCallKeepHandleStartCallNotification
object:self
userInfo:userInfo];
return YES;
}
return NO;
*/
return YES;
}
+ (BOOL)application:(UIApplication *)application
continueUserActivity:(NSUserActivity *)userActivity
restorationHandler:(void(^)(NSArray * __nullable restorableObjects))restorationHandler
{
#ifdef DEBUG
NSLog(@"[RNCallKeep][application:continueUserActivity]");
#endif
INInteraction *interaction = userActivity.interaction;
INPerson *contact;
NSString *handle;
BOOL isAudioCall;
BOOL isVideoCall;
// HACK TO AVOID XCODE 10 COMPILE CRASH
// REMOVE ON NEXT MAJOR RELEASE OF RNCALLKIT
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
//XCode 11
// iOS 13 returns an INStartCallIntent userActivity type
if (@available(iOS 13, *)) {
INStartCallIntent *intent = (INStartCallIntent*)interaction.intent;
// callCapability is not available on iOS > 13.2, but it is in 13.1 weirdly...
if ([intent respondsToSelector:@selector(callCapability)]) {
isAudioCall = intent.callCapability == INCallCapabilityAudioCall;
isVideoCall = intent.callCapability == INCallCapabilityVideoCall;
} else {
isAudioCall = [userActivity.activityType isEqualToString:INStartAudioCallIntentIdentifier];
isVideoCall = [userActivity.activityType isEqualToString:INStartVideoCallIntentIdentifier];
}
} else {
#endif
// XCode 10 and below