@robono/calling-react-native 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -1
- package/INCOMING-CALLS.md +68 -0
- package/README.md +8 -2
- package/RobonoCallingRuntime.podspec +1 -1
- package/SBOM.spdx.json +654 -366
- package/android/build.gradle +1 -0
- package/android/consumer-rules.pro +9 -0
- package/android/src/main/AndroidManifest.xml +9 -0
- package/android/src/main/java/com/robono/calling/CallingPackage.java +1 -1
- package/android/src/main/java/com/robono/calling/CallingRuntime.java +2 -2
- package/android/src/main/java/com/robono/calling/SystemCallActionReceiver.java +5 -0
- package/android/src/main/java/com/robono/calling/SystemCallActivity.java +25 -0
- package/android/src/main/java/com/robono/calling/SystemCallConnectionService.java +17 -0
- package/android/src/main/java/com/robono/calling/SystemCallMessagingService.java +19 -0
- package/android/src/main/java/com/robono/calling/SystemCallService.java +28 -0
- package/android/src/main/java/com/robono/calling/SystemCalling.java +95 -0
- package/app.plugin.cjs +11 -0
- package/dist/messenger.d.ts +1 -0
- package/dist/messenger.js +2 -0
- package/dist/native.d.ts +6 -0
- package/dist/native.js +35 -3
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.js +2 -2
- package/dist/system-calling.d.ts +29 -0
- package/dist/system-calling.js +184 -0
- package/dist/versions.d.ts +1 -1
- package/dist/versions.js +1 -1
- package/ios/RobonoCallingRuntime.m +2 -1
- package/ios/RobonoSystemCalling.h +7 -0
- package/ios/RobonoSystemCalling.m +176 -0
- package/package.json +6 -1
- package/plugin/incoming-calls.cjs +14 -0
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { NativeEventEmitter, NativeModules, Platform } from 'react-native';
|
|
2
|
+
/** The OS presents an invitation; only a fresh authenticated server response can
|
|
3
|
+
* authorize its media. One coordinator per signed-in Messenger, shared by calls. */
|
|
4
|
+
export function createNativeSystemCalling(options) {
|
|
5
|
+
const native = NativeModules.RobonoSystemCalling;
|
|
6
|
+
let account, closed = false, onChange = () => { }, queue = Promise.resolve(), token = '';
|
|
7
|
+
let enabled = false;
|
|
8
|
+
const controllers = new Set(), known = new Map();
|
|
9
|
+
const pending = new Set();
|
|
10
|
+
const nativeIds = new Set();
|
|
11
|
+
const contacts = {};
|
|
12
|
+
let appearance;
|
|
13
|
+
const report = (e) => options.onError(e instanceof Error ? e : Error(String(e)));
|
|
14
|
+
const callOf = (c) => c.client.state.call;
|
|
15
|
+
const closeId = (id) => { nativeIds.delete(id); native?.end(id); };
|
|
16
|
+
const synchronize = (c) => {
|
|
17
|
+
if (!enabled || !account || closed)
|
|
18
|
+
return;
|
|
19
|
+
const call = callOf(c), state = c.getSnapshot(), last = known.get(c);
|
|
20
|
+
const terminal = ['idle', 'error'].includes(state.phase);
|
|
21
|
+
if (last && (!call || call.id !== last || call.state === 'ended' || !call.controlled || terminal)) {
|
|
22
|
+
closeId(last);
|
|
23
|
+
known.delete(c);
|
|
24
|
+
}
|
|
25
|
+
if (!call || call.state === 'ended' || !call.controlled || terminal)
|
|
26
|
+
return;
|
|
27
|
+
const incoming = 'memberState' in call ? call.memberState === 'invited' : call.role === 'callee' && call.state === 'ringing';
|
|
28
|
+
if (incoming) {
|
|
29
|
+
known.set(c, call.id);
|
|
30
|
+
nativeIds.add(call.id);
|
|
31
|
+
const name = state.contact?.name;
|
|
32
|
+
if (name) {
|
|
33
|
+
contacts[call.connectionId] = name;
|
|
34
|
+
native.cacheContacts(account, contacts);
|
|
35
|
+
}
|
|
36
|
+
native.receive({ event: state.group ? 'calling.group_incoming' : 'calling.incoming', event_id: 'native_' + call.id, call_id: call.id, connection_id: call.connectionId,
|
|
37
|
+
kind: call.kind ?? 'voice', sequence: '1', ring_expires_at: new Date('ringExpiresAt' in call && call.ringExpiresAt ? call.ringExpiresAt : Date.now() + (call.ringRemainingMs ?? 0)).toISOString(), accountScope: account });
|
|
38
|
+
}
|
|
39
|
+
if (nativeIds.has(call.id) && state.phase === 'connected')
|
|
40
|
+
native.connected(call.id);
|
|
41
|
+
};
|
|
42
|
+
const process = async () => {
|
|
43
|
+
if (!native || !account || closed)
|
|
44
|
+
return;
|
|
45
|
+
const scope = account, state = await native.state();
|
|
46
|
+
if (scope !== account || closed || state.accountScope !== scope)
|
|
47
|
+
return;
|
|
48
|
+
if ((state.voipToken ?? '') !== token) {
|
|
49
|
+
token = state.voipToken ?? '';
|
|
50
|
+
onChange();
|
|
51
|
+
}
|
|
52
|
+
for (const row of state.calls ?? [])
|
|
53
|
+
if (row.data?.accountScope === scope)
|
|
54
|
+
nativeIds.add(row.id);
|
|
55
|
+
const events = await native.drain();
|
|
56
|
+
for (const event of events) {
|
|
57
|
+
if (closed || scope !== account || event.accountScope !== scope || !event.call_id)
|
|
58
|
+
continue;
|
|
59
|
+
const id = event.call_id;
|
|
60
|
+
if (event.type === 'token')
|
|
61
|
+
continue;
|
|
62
|
+
try {
|
|
63
|
+
await options.start();
|
|
64
|
+
if (closed || scope !== account) {
|
|
65
|
+
closeId(id);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const group = String(event.event).startsWith('calling.group_');
|
|
69
|
+
const c = [...controllers].find(c => !!c.getSnapshot().group === group);
|
|
70
|
+
if (!c) {
|
|
71
|
+
closeId(id);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
const active = callOf(c);
|
|
75
|
+
// Never let a stale notification operate on a different active call.
|
|
76
|
+
if (active && active.state !== 'ended' && active.id !== id) {
|
|
77
|
+
closeId(id);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (event.type === 'dismissed') {
|
|
81
|
+
await c.refresh();
|
|
82
|
+
const current = callOf(c);
|
|
83
|
+
if (!current || current.id !== id || current.state === 'ended' || !current.controlled)
|
|
84
|
+
closeId(id);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (event.type === 'mute') {
|
|
88
|
+
if (active?.id === id)
|
|
89
|
+
c.mute(!!event.muted);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (event.type === 'answer' || !active || active.id !== id) {
|
|
93
|
+
if (!await c.openIncoming(id)) {
|
|
94
|
+
closeId(id);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const current = callOf(c);
|
|
99
|
+
if (!current || current.id !== id || !current.controlled || current.state === 'ended') {
|
|
100
|
+
closeId(id);
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (event.type === 'end') {
|
|
104
|
+
await c.hangUp({ playEndTone: false });
|
|
105
|
+
closeId(id);
|
|
106
|
+
}
|
|
107
|
+
if (event.type === 'answer' && c.getSnapshot().phase === 'incoming' && !pending.has(id)) {
|
|
108
|
+
pending.add(id);
|
|
109
|
+
// Keep draining Decline/End while permissions and media connect. Those
|
|
110
|
+
// events must be able to cancel an answer already in progress.
|
|
111
|
+
void c.answer().catch(e => { closeId(id); report(e); }).finally(() => pending.delete(id));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
catch (e) {
|
|
115
|
+
closeId(id);
|
|
116
|
+
report(e);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
const wake = () => { queue = queue.then(process).catch(report); };
|
|
121
|
+
const sub = native ? new NativeEventEmitter(native).addListener('RobonoSystemCallingEvent', wake) : undefined;
|
|
122
|
+
const registration = async () => {
|
|
123
|
+
if (!native || !enabled || !account || closed)
|
|
124
|
+
return { systemCalling: false };
|
|
125
|
+
const scope = account, state = await native.state();
|
|
126
|
+
if (scope !== account || closed || state.accountScope !== scope)
|
|
127
|
+
return { systemCalling: false };
|
|
128
|
+
const voipToken = typeof state.voipToken === 'string' ? state.voipToken : undefined;
|
|
129
|
+
return { systemCalling: Platform.OS === 'android' || !!voipToken, ...(voipToken ? { voipToken } : {}) };
|
|
130
|
+
};
|
|
131
|
+
const notifications = {
|
|
132
|
+
async configure(scope, changed) {
|
|
133
|
+
if (closed)
|
|
134
|
+
throw Error('Calling has ended.');
|
|
135
|
+
if (!native)
|
|
136
|
+
throw Error('Rebuild the app to enable incoming calls on the lock screen.');
|
|
137
|
+
if (!/^[a-f\d]{64}$/.test(scope))
|
|
138
|
+
throw Error('Invalid calling account.');
|
|
139
|
+
if (account && account !== scope) {
|
|
140
|
+
nativeIds.clear();
|
|
141
|
+
known.clear();
|
|
142
|
+
for (const key of Object.keys(contacts))
|
|
143
|
+
delete contacts[key];
|
|
144
|
+
}
|
|
145
|
+
account = scope;
|
|
146
|
+
onChange = changed;
|
|
147
|
+
const state = await native.configure(scope);
|
|
148
|
+
if (account !== scope || closed)
|
|
149
|
+
return { systemCalling: false };
|
|
150
|
+
enabled = state.enabled === true;
|
|
151
|
+
native.cacheContacts(scope, contacts);
|
|
152
|
+
if (appearance)
|
|
153
|
+
native.cacheAppearance?.(scope, appearance);
|
|
154
|
+
controllers.forEach(synchronize);
|
|
155
|
+
wake();
|
|
156
|
+
return registration();
|
|
157
|
+
}, registration,
|
|
158
|
+
async disconnect() { const previous = account; account = undefined; enabled = false; onChange = () => { }; nativeIds.clear(); known.clear(); for (const key of Object.keys(contacts))
|
|
159
|
+
delete contacts[key]; if (previous)
|
|
160
|
+
await native?.clear(previous); },
|
|
161
|
+
};
|
|
162
|
+
return {
|
|
163
|
+
notifications,
|
|
164
|
+
updateAppearance(value) { appearance = value; if (account)
|
|
165
|
+
native?.cacheAppearance?.(account, value); },
|
|
166
|
+
attach(controller) { controllers.add(controller); const unsub = controller.subscribe(() => synchronize(controller)); synchronize(controller); return () => { unsub(); controllers.delete(controller); const id = known.get(controller); if (id)
|
|
167
|
+
closeId(id); known.delete(controller); }; },
|
|
168
|
+
audio(getController) {
|
|
169
|
+
const id = () => { const c = getController(); return c ? callOf(c)?.id : undefined; };
|
|
170
|
+
return {
|
|
171
|
+
active: () => { const value = id(); return enabled && !!value && nativeIds.has(value); },
|
|
172
|
+
async prepare() { const value = id(); if (!value || !nativeIds.has(value))
|
|
173
|
+
return; await native.prepare(value); },
|
|
174
|
+
speaker(selected) { native?.speaker(selected); },
|
|
175
|
+
};
|
|
176
|
+
},
|
|
177
|
+
async receive(data) { if (enabled)
|
|
178
|
+
native.receive(data); },
|
|
179
|
+
cacheContacts(names) { Object.assign(contacts, names); if (account)
|
|
180
|
+
native?.cacheContacts(account, contacts); },
|
|
181
|
+
async dispose() { if (closed)
|
|
182
|
+
return; closed = true; sub?.remove(); await notifications.disconnect(); controllers.clear(); },
|
|
183
|
+
};
|
|
184
|
+
}
|
package/dist/versions.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const mobileVersion = "0.
|
|
1
|
+
export declare const mobileVersion = "0.6.0";
|
|
2
2
|
export declare const engineVersion = "0.4.0";
|
package/dist/versions.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
#import <AVFAudio/AVFAudio.h>
|
|
4
4
|
#import <UIKit/UIKit.h>
|
|
5
5
|
#import <ReplayKit/ReplayKit.h>
|
|
6
|
+
#import "RobonoSystemCalling.h"
|
|
6
7
|
|
|
7
8
|
@interface RobonoCallingRuntime : RCTEventEmitter <RCTBridgeModule>
|
|
8
9
|
@property(nonatomic, strong) RPSystemBroadcastPickerView *screenPicker;
|
|
@@ -72,7 +73,7 @@ RCT_REMAP_METHOD(activateAudio, activateAudio:(NSString *)token resolver:(RCTPro
|
|
|
72
73
|
}
|
|
73
74
|
RCT_REMAP_METHOD(begin, begin:(NSString *)token title:(NSString *)title text:(NSString *)text channel:(NSString *)channel endLabel:(NSString *)endLabel resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
|
|
74
75
|
if (self.owner && ![self.owner isEqualToString:token]) { reject(@"audio_busy", @"Another call owns audio.", nil); return; }
|
|
75
|
-
if (UIApplication.sharedApplication.applicationState != UIApplicationStateActive) { reject(@"open_app_to_start_call", @"Open the app to start a call.", nil); return; }
|
|
76
|
+
if (UIApplication.sharedApplication.applicationState != UIApplicationStateActive && ![RobonoSystemCalling canCapture]) { reject(@"open_app_to_start_call", @"Open the app to start a call.", nil); return; }
|
|
76
77
|
NSArray *modes = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIBackgroundModes"];
|
|
77
78
|
if (![modes containsObject:@"audio"]) { reject(@"background_audio_not_configured", @"Enable the audio background mode for ongoing calls.", nil); return; }
|
|
78
79
|
self.owner = token;
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
#import "RobonoSystemCalling.h"
|
|
2
|
+
#import <React/RCTBridgeModule.h>
|
|
3
|
+
#import <React/RCTEventEmitter.h>
|
|
4
|
+
#import <CallKit/CallKit.h>
|
|
5
|
+
#import <PushKit/PushKit.h>
|
|
6
|
+
#import <AVFAudio/AVFAudio.h>
|
|
7
|
+
#import <UIKit/UIKit.h>
|
|
8
|
+
#import <objc/message.h>
|
|
9
|
+
|
|
10
|
+
static NSString *const Changed = @"RobonoSystemCallingChanged";
|
|
11
|
+
static NSString *const AccountKey = @"robono.sdk.calls.account.v1";
|
|
12
|
+
static NSString *const NamesKey = @"robono.sdk.calls.names.v1";
|
|
13
|
+
// WebRTC remains an optional peer for customers using only the screen components.
|
|
14
|
+
static id RTCSession(void) {
|
|
15
|
+
Class c=NSClassFromString(@"RTCAudioSession");
|
|
16
|
+
return c?((id(*)(id,SEL))objc_msgSend)(c,NSSelectorFromString(@"sharedInstance")):nil;
|
|
17
|
+
}
|
|
18
|
+
static void RTCBool(NSString *selector,BOOL value){id s=RTCSession();if([s respondsToSelector:NSSelectorFromString(selector)])((void(*)(id,SEL,BOOL))objc_msgSend)(s,NSSelectorFromString(selector),value);}
|
|
19
|
+
static void RTCAudio(NSString *selector,AVAudioSession *audio){id s=RTCSession();if([s respondsToSelector:NSSelectorFromString(selector)])((void(*)(id,SEL,id))objc_msgSend)(s,NSSelectorFromString(selector),audio);}
|
|
20
|
+
@interface RobonoSystemCalling () <PKPushRegistryDelegate,CXProviderDelegate,NSURLSessionTaskDelegate>
|
|
21
|
+
@property CXProvider *provider;
|
|
22
|
+
@property CXCallController *controller;
|
|
23
|
+
@property PKPushRegistry *registry;
|
|
24
|
+
@property NSMutableDictionary<NSString *,NSMutableDictionary *> *calls;
|
|
25
|
+
@property NSMutableDictionary<NSString *,CXAnswerCallAction *> *answers;
|
|
26
|
+
@property NSMutableDictionary<NSString *,NSDate *> *ended;
|
|
27
|
+
@property NSMutableArray *events;
|
|
28
|
+
@property NSString *token;
|
|
29
|
+
@property BOOL audioActive;
|
|
30
|
+
@property BOOL started;
|
|
31
|
+
@end
|
|
32
|
+
@implementation RobonoSystemCalling
|
|
33
|
+
+ (void)load {
|
|
34
|
+
// Called before React is created, including a cold start caused by a VoIP push.
|
|
35
|
+
[NSNotificationCenter.defaultCenter addObserverForName:@"RobonoSystemCallRemoteNotification" object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note){[self receiveRemoteNotification:note.userInfo];}];
|
|
36
|
+
[NSNotificationCenter.defaultCenter addObserverForName:UIApplicationDidFinishLaunchingNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note){[[self shared] start];}];
|
|
37
|
+
}
|
|
38
|
+
+ (instancetype)shared {static RobonoSystemCalling *value;static dispatch_once_t once;dispatch_once(&once,^{value=[self new];value.calls=[NSMutableDictionary new];value.answers=[NSMutableDictionary new];value.ended=[NSMutableDictionary new];value.events=[NSMutableArray new];});return value;}
|
|
39
|
+
- (NSString *)account {return [NSUserDefaults.standardUserDefaults stringForKey:AccountKey];}
|
|
40
|
+
- (BOOL)enabled {return [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"RobonoSystemCallingEnabled"] boolValue];}
|
|
41
|
+
- (void)start {
|
|
42
|
+
if(self.started||!self.enabled)return;self.started=YES;
|
|
43
|
+
NSString *name=[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]?:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"]?:@"Calls";
|
|
44
|
+
CXProviderConfiguration *config=[[CXProviderConfiguration alloc] initWithLocalizedName:name];
|
|
45
|
+
config.supportsVideo=YES;config.maximumCallGroups=1;config.maximumCallsPerCallGroup=1;config.supportedHandleTypes=[NSSet setWithObject:@(CXHandleTypeGeneric)];config.includesCallsInRecents=NO;
|
|
46
|
+
self.provider=[[CXProvider alloc] initWithConfiguration:config];[self.provider setDelegate:self queue:dispatch_get_main_queue()];self.controller=[CXCallController new];
|
|
47
|
+
if(self.account.length)[self registerPush];
|
|
48
|
+
}
|
|
49
|
+
- (void)registerPush {if(!self.registry){self.registry=[[PKPushRegistry alloc] initWithQueue:dispatch_get_main_queue()];self.registry.delegate=self;}self.registry.desiredPushTypes=[NSSet setWithObject:PKPushTypeVoIP];}
|
|
50
|
+
- (void)changed {[NSNotificationCenter.defaultCenter postNotificationName:Changed object:nil];}
|
|
51
|
+
- (void)event:(NSString *)kind data:(NSDictionary *)data {
|
|
52
|
+
NSMutableDictionary *event=[data mutableCopy]?:[NSMutableDictionary new];event[@"type"]=kind;event[@"eventId"]=NSUUID.UUID.UUIDString;
|
|
53
|
+
if(self.account)event[@"accountScope"]=self.account;[self.events addObject:event];while(self.events.count>64)[self.events removeObjectAtIndex:0];[self changed];
|
|
54
|
+
}
|
|
55
|
+
- (void)configure:(NSString *)account {
|
|
56
|
+
[self start];if(![self.account isEqualToString:account]){
|
|
57
|
+
for(NSString *callId in self.calls.allKeys)[self end:callId reason:CXCallEndedReasonFailed];
|
|
58
|
+
[self.events removeAllObjects];[NSUserDefaults.standardUserDefaults removeObjectForKey:NamesKey];
|
|
59
|
+
}
|
|
60
|
+
if(account.length&&self.enabled){[NSUserDefaults.standardUserDefaults setObject:account forKey:AccountKey];[self registerPush];}
|
|
61
|
+
else {[NSUserDefaults.standardUserDefaults removeObjectForKey:AccountKey];self.registry.desiredPushTypes=[NSSet new];self.token=nil;}
|
|
62
|
+
}
|
|
63
|
+
- (NSDictionary *)state {return @{@"enabled":@(self.enabled),@"accountScope":self.account?:NSNull.null,@"voipToken":self.token?:NSNull.null,@"calls":self.calls.allValues};}
|
|
64
|
+
- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(PKPushType)type {
|
|
65
|
+
if(![type isEqualToString:PKPushTypeVoIP])return;NSMutableString *token=[NSMutableString new];const unsigned char *bytes=credentials.token.bytes;for(NSUInteger i=0;i<credentials.token.length;i++)[token appendFormat:@"%02x",bytes[i]];self.token=token;[self event:@"token" data:nil];
|
|
66
|
+
}
|
|
67
|
+
- (void)pushRegistry:(PKPushRegistry *)registry didInvalidatePushTokenForType:(PKPushType)type {self.token=nil;[self event:@"token" data:nil];}
|
|
68
|
+
- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type withCompletionHandler:(void (^)(void))completion {
|
|
69
|
+
NSDictionary *data=payload.dictionaryPayload[@"body"];if(![data isKindOfClass:NSDictionary.class])data=@{};
|
|
70
|
+
[self incoming:data mustReport:YES completion:completion];
|
|
71
|
+
}
|
|
72
|
+
- (void)incoming:(NSDictionary *)data mustReport:(BOOL)mustReport completion:(void (^)(void))completion {
|
|
73
|
+
NSString *raw=[data[@"call_id"] isKindOfClass:NSString.class]?data[@"call_id"]:@"";
|
|
74
|
+
NSUUID *uuid=[[NSUUID alloc] initWithUUIDString:raw];NSString *callId=uuid.UUIDString.lowercaseString;
|
|
75
|
+
NSString *event=data[@"event"],*scope=data[@"accountScope"];
|
|
76
|
+
NSDate *expiry=nil;if([data[@"ring_expires_at"] isKindOfClass:NSString.class]){NSISO8601DateFormatter *f=[NSISO8601DateFormatter new];f.formatOptions=NSISO8601DateFormatWithInternetDateTime|NSISO8601DateFormatWithFractionalSeconds;expiry=[f dateFromString:data[@"ring_expires_at"]];if(!expiry){f.formatOptions=NSISO8601DateFormatWithInternetDateTime;expiry=[f dateFromString:data[@"ring_expires_at"]];}}
|
|
77
|
+
BOOL valid=uuid&&self.account.length&&[scope isEqual:self.account]&&[data[@"connection_id"] isKindOfClass:NSString.class]&&([data[@"kind"] isEqual:@"voice"]||[data[@"kind"] isEqual:@"video"])&&([event isEqual:@"calling.incoming"]||[event isEqual:@"calling.group_incoming"])&&expiry.timeIntervalSinceNow>0&&expiry.timeIntervalSinceNow<=120&& !self.ended[callId];
|
|
78
|
+
if(callId&&self.calls[callId]){if(valid&&[data[@"decline_grant"] isKindOfClass:NSString.class]){NSMutableDictionary *merged=[self.calls[callId][@"data"] mutableCopy];merged[@"decline_grant"]=data[@"decline_grant"];self.calls[callId][@"data"]=merged;}if(mustReport){CXCallUpdate *duplicate=[CXCallUpdate new];duplicate.hasVideo=[data[@"kind"] isEqual:@"video"];[self.provider reportNewIncomingCallWithUUID:uuid update:duplicate completion:^(NSError *error){completion();}];}else completion();return;}
|
|
79
|
+
if(!valid&&!mustReport){completion();return;}
|
|
80
|
+
// Apple requires a CallKit report for every delivered VoIP invitation, even
|
|
81
|
+
// when it became stale in transit. End invalid/stale invitations immediately.
|
|
82
|
+
if(!uuid)uuid=NSUUID.UUID;if(!callId)callId=uuid.UUIDString.lowercaseString;
|
|
83
|
+
if(self.calls.count)valid=NO;
|
|
84
|
+
NSString *name=valid?[NSUserDefaults.standardUserDefaults dictionaryForKey:NamesKey][data[@"conversation_id"]?:data[@"connection_id"]]:nil;
|
|
85
|
+
CXCallUpdate *update=[CXCallUpdate new];update.remoteHandle=[[CXHandle alloc] initWithType:CXHandleTypeGeneric value:name.length?name:@"Incoming call"];
|
|
86
|
+
update.localizedCallerName=name.length?name:@"Incoming call";update.hasVideo=[data[@"kind"] isEqual:@"video"];update.supportsHolding=NO;update.supportsGrouping=NO;update.supportsUngrouping=NO;update.supportsDTMF=NO;
|
|
87
|
+
if(valid){self.calls[callId]=[@{@"id":callId,@"data":data,@"state":@"ringing",@"authorized":@NO,@"incoming":@YES} mutableCopy];}
|
|
88
|
+
[self.provider reportNewIncomingCallWithUUID:uuid update:update completion:^(NSError *error){dispatch_async(dispatch_get_main_queue(),^{
|
|
89
|
+
if(error||!valid){[self.calls removeObjectForKey:callId];if(!error)[self.provider reportCallWithUUID:uuid endedAtDate:NSDate.date reason:CXCallEndedReasonFailed];}
|
|
90
|
+
else {[self event:@"incoming" data:data];dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(MAX(0,expiry.timeIntervalSinceNow)*NSEC_PER_SEC)),dispatch_get_main_queue(),^{if([self.calls[callId][@"state"] isEqual:@"ringing"])[self end:callId reason:CXCallEndedReasonUnanswered];});}
|
|
91
|
+
completion();
|
|
92
|
+
});}];
|
|
93
|
+
}
|
|
94
|
+
- (void)end:(NSString *)callId reason:(CXCallEndedReason)reason {
|
|
95
|
+
if(!callId.length)return;self.ended[callId]=NSDate.date;
|
|
96
|
+
if(self.ended.count>128){NSString *old=[self.ended keysSortedByValueUsingSelector:@selector(compare:)].firstObject;[self.ended removeObjectForKey:old];}
|
|
97
|
+
if(!self.calls[callId])return;[self.answers[callId] fail];[self.answers removeObjectForKey:callId];[self.calls removeObjectForKey:callId];
|
|
98
|
+
[self.provider reportCallWithUUID:[[NSUUID alloc] initWithUUIDString:callId] endedAtDate:NSDate.date reason:reason];[self changed];
|
|
99
|
+
if(!self.calls.count&&!self.audioActive)RTCBool(@"setUseManualAudio:",NO);
|
|
100
|
+
}
|
|
101
|
+
+ (void)receiveRemoteNotification:(NSDictionary *)payload {
|
|
102
|
+
NSDictionary *data=[payload[@"body"] isKindOfClass:NSDictionary.class]?payload[@"body"]:payload;
|
|
103
|
+
if(![data isKindOfClass:NSDictionary.class])return;
|
|
104
|
+
dispatch_async(dispatch_get_main_queue(),^{RobonoSystemCalling *c=self.shared;NSString *event=data[@"event"];if([data[@"accountScope"] isEqual:c.account]&&([event isEqual:@"calling.dismissed"]||[event isEqual:@"calling.group_dismissed"])){
|
|
105
|
+
NSString *callId=[data[@"call_id"] isKindOfClass:NSString.class]?[data[@"call_id"] lowercaseString]:nil;if(![[NSUUID alloc] initWithUUIDString:callId])return;if(![data[@"reason"] isEqual:@"answered"]||![c.calls[callId][@"authorized"] boolValue])[c end:callId reason:CXCallEndedReasonRemoteEnded];[c event:@"dismissed" data:data];
|
|
106
|
+
}});
|
|
107
|
+
}
|
|
108
|
+
+ (BOOL)canCapture {for(NSDictionary *call in RobonoSystemCalling.shared.calls.allValues)if([call[@"authorized"] boolValue]&& ![call[@"state"] isEqual:@"ringing"])return YES;return NO;}
|
|
109
|
+
+ (BOOL)ownsAudio {return RobonoSystemCalling.shared.audioActive;}
|
|
110
|
+
- (void)decline:(NSDictionary *)data {
|
|
111
|
+
NSString *grant=data[@"decline_grant"];if(![grant isKindOfClass:NSString.class]||grant.length>2048)return;
|
|
112
|
+
__block UIBackgroundTaskIdentifier task=UIBackgroundTaskInvalid;
|
|
113
|
+
void(^finish)(void)=^{if(task!=UIBackgroundTaskInvalid){[UIApplication.sharedApplication endBackgroundTask:task];task=UIBackgroundTaskInvalid;}};
|
|
114
|
+
task=[UIApplication.sharedApplication beginBackgroundTaskWithName:@"Decline incoming call" expirationHandler:finish];
|
|
115
|
+
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.robono.com/v1/calling"]];request.HTTPMethod=@"POST";request.timeoutInterval=5;[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
|
|
116
|
+
request.HTTPBody=[NSJSONSerialization dataWithJSONObject:@{@"operation":@"decline-invitation",@"grant":grant} options:0 error:nil];
|
|
117
|
+
NSURLSession *session=[NSURLSession sessionWithConfiguration:NSURLSessionConfiguration.ephemeralSessionConfiguration delegate:self delegateQueue:nil];
|
|
118
|
+
[[session dataTaskWithRequest:request completionHandler:^(NSData *body,NSURLResponse *response,NSError *error){[session finishTasksAndInvalidate];dispatch_async(dispatch_get_main_queue(),finish);}] resume];
|
|
119
|
+
}
|
|
120
|
+
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler {completionHandler(nil);}
|
|
121
|
+
- (void)providerDidReset:(CXProvider *)provider {for(NSString *callId in self.calls.allKeys){[self event:@"end" data:self.calls[callId][@"data"]];[self end:callId reason:CXCallEndedReasonFailed];}}
|
|
122
|
+
- (void)provider:(CXProvider *)provider performAnswerCallAction:(CXAnswerCallAction *)action {
|
|
123
|
+
NSString *callId=action.callUUID.UUIDString.lowercaseString;NSMutableDictionary *call=self.calls[callId];if(!call){[action fail];return;}
|
|
124
|
+
self.answers[callId]=action;call[@"state"]=@"answering";[self event:@"answer" data:call[@"data"]];
|
|
125
|
+
if([call[@"authorized"] boolValue]){[action fulfill];[self.answers removeObjectForKey:callId];}
|
|
126
|
+
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,25*NSEC_PER_SEC),dispatch_get_main_queue(),^{if([self.calls[callId][@"state"] isEqual:@"answering"]){[self event:@"end" data:self.calls[callId][@"data"]];[self end:callId reason:CXCallEndedReasonFailed];}});
|
|
127
|
+
}
|
|
128
|
+
- (void)provider:(CXProvider *)provider performEndCallAction:(CXEndCallAction *)action {NSString *callId=action.callUUID.UUIDString.lowercaseString;[self decline:self.calls[callId][@"data"]];[self event:@"end" data:self.calls[callId][@"data"]];[self end:callId reason:CXCallEndedReasonRemoteEnded];[action fulfill];}
|
|
129
|
+
- (void)provider:(CXProvider *)provider performSetMutedCallAction:(CXSetMutedCallAction *)action {
|
|
130
|
+
NSMutableDictionary *data=[self.calls[action.callUUID.UUIDString.lowercaseString][@"data"] mutableCopy];if(!data){[action fail];return;}data[@"muted"]=@(action.muted);[self event:@"mute" data:data];[action fulfill];
|
|
131
|
+
}
|
|
132
|
+
- (void)provider:(CXProvider *)provider timedOutPerformingAction:(CXAction *)action {if([action isKindOfClass:CXCallAction.class]){NSString *callId=((CXCallAction *)action).callUUID.UUIDString.lowercaseString;[self event:@"end" data:self.calls[callId][@"data"]];[self end:callId reason:CXCallEndedReasonFailed];}}
|
|
133
|
+
- (void)provider:(CXProvider *)provider didActivateAudioSession:(AVAudioSession *)session {self.audioActive=YES;RTCBool(@"setUseManualAudio:",YES);RTCAudio(@"audioSessionDidActivate:",session);RTCBool(@"setIsAudioEnabled:",YES);[self changed];}
|
|
134
|
+
- (void)provider:(CXProvider *)provider didDeactivateAudioSession:(AVAudioSession *)session {self.audioActive=NO;RTCAudio(@"audioSessionDidDeactivate:",session);RTCBool(@"setIsAudioEnabled:",NO);if(!self.calls.count)RTCBool(@"setUseManualAudio:",NO);[self changed];}
|
|
135
|
+
@end
|
|
136
|
+
|
|
137
|
+
@interface RobonoSystemCallingModule:RCTEventEmitter<RCTBridgeModule>
|
|
138
|
+
@end
|
|
139
|
+
@implementation RobonoSystemCallingModule
|
|
140
|
+
RCT_EXPORT_MODULE(RobonoSystemCalling);
|
|
141
|
+
+ (BOOL)requiresMainQueueSetup{return YES;}
|
|
142
|
+
- (dispatch_queue_t)methodQueue{return dispatch_get_main_queue();}
|
|
143
|
+
- (NSArray *)supportedEvents{return @[@"RobonoSystemCallingEvent"];}
|
|
144
|
+
- (void)startObserving{[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(changed:) name:Changed object:nil];}
|
|
145
|
+
- (void)stopObserving{[NSNotificationCenter.defaultCenter removeObserver:self];}
|
|
146
|
+
- (void)changed:(NSNotification *)note{[self sendEventWithName:@"RobonoSystemCallingEvent" body:@{}];}
|
|
147
|
+
RCT_EXPORT_METHOD(configure:(NSString *)account resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
|
|
148
|
+
if(account&&(![account isKindOfClass:NSString.class]||account.length!=64)){reject(@"invalid_account",@"A verified notification account is required.",nil);return;}
|
|
149
|
+
[RobonoSystemCalling.shared configure:account];resolve([RobonoSystemCalling.shared state]);
|
|
150
|
+
}
|
|
151
|
+
RCT_EXPORT_METHOD(state:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){resolve([RobonoSystemCalling.shared state]);}
|
|
152
|
+
RCT_EXPORT_METHOD(clear:(NSString *)account resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){if([account isEqual:RobonoSystemCalling.shared.account])[RobonoSystemCalling.shared configure:nil];resolve(nil);}
|
|
153
|
+
RCT_EXPORT_METHOD(drain:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){NSArray *events=[RobonoSystemCalling.shared.events copy];[RobonoSystemCalling.shared.events removeAllObjects];resolve(events);}
|
|
154
|
+
RCT_EXPORT_METHOD(cacheContacts:(NSString *)account names:(NSDictionary *)names){if([account isEqual:RobonoSystemCalling.shared.account])[NSUserDefaults.standardUserDefaults setObject:names forKey:NamesKey];}
|
|
155
|
+
RCT_EXPORT_METHOD(receive:(NSDictionary *)data){if([data[@"event"] hasSuffix:@"dismissed"])[RobonoSystemCalling receiveRemoteNotification:data];else[RobonoSystemCalling.shared incoming:data mustReport:NO completion:^{}];}
|
|
156
|
+
RCT_EXPORT_METHOD(end:(NSString *)callId){[RobonoSystemCalling.shared end:callId.lowercaseString reason:CXCallEndedReasonRemoteEnded];}
|
|
157
|
+
RCT_EXPORT_METHOD(connected:(NSString *)callId){NSMutableDictionary *call=RobonoSystemCalling.shared.calls[callId.lowercaseString];if(call)call[@"state"]=@"connected";}
|
|
158
|
+
RCT_EXPORT_METHOD(canCapture:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){resolve(@([RobonoSystemCalling canCapture]));}
|
|
159
|
+
RCT_EXPORT_METHOD(speaker:(BOOL)speaker){if([RobonoSystemCalling canCapture])[AVAudioSession.sharedInstance overrideOutputAudioPort:speaker?AVAudioSessionPortOverrideSpeaker:AVAudioSessionPortOverrideNone error:nil];}
|
|
160
|
+
RCT_EXPORT_METHOD(prepare:(NSString *)callId resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
|
|
161
|
+
RobonoSystemCalling *c=RobonoSystemCalling.shared;NSMutableDictionary *call=c.calls[callId.lowercaseString];
|
|
162
|
+
if(!call){reject(@"call_cancelled",@"The incoming call has ended.",nil);return;}
|
|
163
|
+
void(^prepare)(BOOL)=^(BOOL granted){dispatch_async(dispatch_get_main_queue(),^{
|
|
164
|
+
if(!granted||c.calls[callId.lowercaseString]!=call){reject(granted?@"call_cancelled":@"microphone_permission_denied",@"Open the app and allow microphone access to answer calls.",nil);return;}
|
|
165
|
+
NSError *error=nil;RTCBool(@"setUseManualAudio:",YES);
|
|
166
|
+
[AVAudioSession.sharedInstance setCategory:AVAudioSessionCategoryPlayAndRecord mode:AVAudioSessionModeVoiceChat options:AVAudioSessionCategoryOptionAllowBluetooth error:&error];
|
|
167
|
+
if(error){reject(@"call_audio_unavailable",@"Call audio is unavailable.",error);return;}
|
|
168
|
+
call[@"authorized"]=@YES;call[@"state"]=@"answering";
|
|
169
|
+
CXAnswerCallAction *answer=c.answers[callId.lowercaseString];
|
|
170
|
+
if(answer){[answer fulfill];[c.answers removeObjectForKey:callId.lowercaseString];resolve(nil);}
|
|
171
|
+
else {CXAnswerCallAction *action=[[CXAnswerCallAction alloc] initWithCallUUID:[[NSUUID alloc] initWithUUIDString:callId]];[c.controller requestTransaction:[[CXTransaction alloc] initWithAction:action] completion:^(NSError *e){dispatch_async(dispatch_get_main_queue(),^{if(e){reject(@"call_cancelled",@"The call cannot be answered.",e);return;}[c.answers[callId.lowercaseString] fulfill];[c.answers removeObjectForKey:callId.lowercaseString];resolve(nil);});}];}
|
|
172
|
+
});};
|
|
173
|
+
AVAudioSessionRecordPermission p=AVAudioSession.sharedInstance.recordPermission;
|
|
174
|
+
if(p==AVAudioSessionRecordPermissionUndetermined&&UIApplication.sharedApplication.applicationState==UIApplicationStateActive)[AVAudioSession.sharedInstance requestRecordPermission:prepare];else prepare(p==AVAudioSessionRecordPermissionGranted);
|
|
175
|
+
}
|
|
176
|
+
@end
|
package/package.json
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@robono/calling-react-native",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Optional branded calling screens, sounds and native audio adapters for Robono calling.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"main": "./dist/index.js",
|
|
8
8
|
"types": "./dist/index.d.ts",
|
|
9
9
|
"exports": {
|
|
10
|
+
"./system-calling": {
|
|
11
|
+
"types": "./dist/system-calling.d.ts",
|
|
12
|
+
"default": "./dist/system-calling.js"
|
|
13
|
+
},
|
|
10
14
|
".": {
|
|
11
15
|
"types": "./dist/index.d.ts",
|
|
12
16
|
"default": "./dist/index.js"
|
|
@@ -61,6 +65,7 @@
|
|
|
61
65
|
"react-native.config.js",
|
|
62
66
|
"app.plugin.cjs",
|
|
63
67
|
"README.md",
|
|
68
|
+
"INCOMING-CALLS.md",
|
|
64
69
|
"CHANGELOG.md",
|
|
65
70
|
"LICENSE",
|
|
66
71
|
"SBOM.spdx.json",
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
const {withAppDelegate}=require('expo/config-plugins');
|
|
2
|
+
const marker='// @robono/system-call-cancellation';
|
|
3
|
+
function installRemoteNotificationHook(source){
|
|
4
|
+
if(source.includes(marker))return source;
|
|
5
|
+
const existing=/(?:public\s+)?(?:override\s+)?func\s+application\s*\(\s*_\s+\w+\s*:\s*UIApplication\s*,\s*didReceiveRemoteNotification\s+(\w+)\s*:\s*\[AnyHashable\s*:\s*Any\]\s*,\s*fetchCompletionHandler\s+\w+\s*:\s*@escaping\s*\(UIBackgroundFetchResult\)\s*->\s*Void\s*\)\s*\{/;
|
|
6
|
+
const hook=name=>`\n ${marker}\n NotificationCenter.default.post(name: NSNotification.Name("RobonoSystemCallRemoteNotification"), object: nil, userInfo: ${name})\n`;
|
|
7
|
+
if(existing.test(source))return source.replace(existing,(match,name)=>match+hook(name));
|
|
8
|
+
if(source.includes('didReceiveRemoteNotification'))throw Error('The app has a custom Apple notification handler. Forward its userInfo to the RobonoSystemCallRemoteNotification notification; see the incoming-calls guide.');
|
|
9
|
+
const declaration=/class\s+AppDelegate\s*:\s*ExpoAppDelegate\s*\{/;
|
|
10
|
+
if(!declaration.test(source))throw Error('Automatic incoming calls require an Expo AppDelegate. See the incoming-calls guide for an existing native host.');
|
|
11
|
+
return source.replace(declaration,match=>match+`\n public override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {${hook('userInfo')} super.application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)\n }\n`);
|
|
12
|
+
}
|
|
13
|
+
function withIncomingCalls(config){return withAppDelegate(config,c=>{if(c.modResults.language!=='swift')throw Error('Automatic incoming calls require a Swift Expo AppDelegate. See the incoming-calls guide for the native forwarding hook.');c.modResults.contents=installRemoteNotificationHook(c.modResults.contents);return c;});}
|
|
14
|
+
module.exports={withIncomingCalls,installRemoteNotificationHook};
|