-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathTwilioVoiceReactNativeModule.java
More file actions
536 lines (433 loc) · 16.3 KB
/
TwilioVoiceReactNativeModule.java
File metadata and controls
536 lines (433 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
package com.twiliovoicereactnative;
import androidx.annotation.NonNull;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.ReadableType;
import com.facebook.react.module.annotations.ReactModule;
import com.twilio.voice.AudioCodec;
import com.twilio.voice.IceOptions;
import com.twilio.voice.IceServer;
import com.twilio.voice.IceTransportPolicy;
import com.twilio.voice.OpusCodec;
import com.twilio.voice.PcmuCodec;
import com.twilio.voice.PreflightOptions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@ReactModule(name = TwilioVoiceReactNativeModule.NAME)
public class TwilioVoiceReactNativeModule extends ReactContextBaseJavaModule {
private record PromiseAdapter(Promise promise) implements ModuleProxy.UniversalPromise {
public void resolve(Object value) {
promise.resolve(
ReactNativeArgumentsSerializer.serializePromiseResolution(value)
);
}
public void rejectWithCode(int code, String message) {
promise.resolve(
ReactNativeArgumentsSerializer.serializePromiseErrorWithCode(code, message)
);
}
public void rejectWithName(String name, String message) {
promise.resolve(
ReactNativeArgumentsSerializer.serializePromiseErrorWithName(name, message)
);
}
}
public static final String NAME = "TwilioVoiceReactNative";
private static final SDKLog logger = new SDKLog(TwilioVoiceReactNativeModule.class);
private final ModuleProxy moduleProxy;
public TwilioVoiceReactNativeModule(ReactApplicationContext reactContext) {
super(reactContext);
logger.log("instantiation of TwilioVoiceReactNativeModule");
this.moduleProxy = new ModuleProxy(reactContext);
}
/**
* Invoked by React Native, necessary when passing this NativeModule to the constructor of a
* NativeEventEmitter on the JS layer.
* <p>
* Invoked when a listener is added to the NativeEventEmitter.
*
* @param eventName The string representation of the event.
*/
@ReactMethod
public void addListener(String eventName) {
logger.debug(String.format("Calling addListener: %s", eventName));
}
/**
* Invoked by React Native, necessary when passing this NativeModule to the constructor of a
* NativeEventEmitter on the JS layer.
* <p>
* Invoked when listeners are removed from the NativeEventEmitter.
*
* @param count The number of event listeners removed.
*/
@ReactMethod
public void removeListeners(Integer count) {
logger.debug("Calling removeListeners: " + count);
}
@Override
@NonNull
public String getName() {
return NAME;
}
@ReactMethod
public void testing_promiseReject(Promise promise) {
promise.reject("is this a code", "is this a message", new Error());
}
/**
* Call API
*/
@ReactMethod
public void call_disconnect(String uuid, Promise promise) {
this.moduleProxy.call.disconnect(uuid, new PromiseAdapter(promise));
}
@ReactMethod
public void call_getState(String uuid, Promise promise) {
this.moduleProxy.call.getState(uuid, new PromiseAdapter(promise));
}
@ReactMethod
public void call_getStats(String uuid, Promise promise) {
this.moduleProxy.call.getStats(uuid, new PromiseAdapter(promise));
}
@ReactMethod
public void call_hold(String uuid, boolean hold, Promise promise) {
this.moduleProxy.call.hold(uuid, hold, new PromiseAdapter(promise));
}
@ReactMethod
public void call_isMuted(String uuid, Promise promise) {
this.moduleProxy.call.isMuted(uuid, new PromiseAdapter(promise));
}
@ReactMethod
public void call_isOnHold(String uuid, Promise promise) {
this.moduleProxy.call.isOnHold(uuid, new PromiseAdapter(promise));
}
@ReactMethod
public void call_mute(String uuid, boolean mute, Promise promise) {
this.moduleProxy.call.mute(uuid, mute, new PromiseAdapter(promise));
}
@ReactMethod
public void call_postFeedback(String uuid, String score, String issue, Promise promise) {
this.moduleProxy.call.postFeedback(uuid, score, issue, new PromiseAdapter(promise));
}
@ReactMethod
public void call_sendDigits(String uuid, String digits, Promise promise) {
this.moduleProxy.call.sendDigits(uuid, digits, new PromiseAdapter(promise));
}
@ReactMethod
public void call_sendMessage(
String uuid,
String content,
String contentType,
String messageType,
Promise promise
) {
this.moduleProxy.call.sendMessage(
uuid,
content,
contentType,
messageType,
new PromiseAdapter(promise)
);
}
/**
* CallInvite API
*/
@ReactMethod
public void callInvite_accept(String uuid, ReadableMap options, Promise promise) {
this.moduleProxy.callInvite.accept(uuid, new PromiseAdapter(promise));
}
@ReactMethod
public void callInvite_reject(String uuid, Promise promise) {
this.moduleProxy.callInvite.reject(uuid, new PromiseAdapter(promise));
}
@ReactMethod
public void callInvite_sendMessage(
String uuid,
String content,
String contentType,
String messageType,
Promise promise
) {
this.moduleProxy.callInvite.sendMessage(
uuid,
content,
contentType,
messageType,
new PromiseAdapter(promise)
);
}
/**
* PreflightTest API
*/
@ReactMethod
public void preflightTest_getCallSid(String uuidStr, Promise promise) {
this.moduleProxy.preflightTest.getCallSid(uuidStr, new PromiseAdapter(promise));
}
@ReactMethod
public void preflightTest_getEndTime(String uuidStr, Promise promise) {
this.moduleProxy.preflightTest.getEndTime(uuidStr, new PromiseAdapter(promise));
}
@ReactMethod
public void preflightTest_getLatestSample(String uuidStr, Promise promise) {
this.moduleProxy.preflightTest.getLatestSample(uuidStr, new PromiseAdapter(promise));
}
@ReactMethod
public void preflightTest_getReport(String uuidStr, Promise promise) {
this.moduleProxy.preflightTest.getReport(uuidStr, new PromiseAdapter(promise));
}
@ReactMethod
public void preflightTest_getStartTime(String uuidStr, Promise promise) {
this.moduleProxy.preflightTest.getStartTime(uuidStr, new PromiseAdapter(promise));
}
@ReactMethod
public void preflightTest_getState(String uuidStr, Promise promise) {
this.moduleProxy.preflightTest.getState(uuidStr, new PromiseAdapter(promise));
}
@ReactMethod
public void preflightTest_stop(String uuidStr, Promise promise) {
this.moduleProxy.preflightTest.stop(uuidStr, new PromiseAdapter(promise));
}
/**
* Voice API
*/
@ReactMethod
public void voice_connect_android(
String accessToken,
ReadableMap twimlParams,
String notificationDisplayName,
ReadableArray jsIceServers,
String jsIceTransportPolicy,
Promise promise
) {
logger.debug(".voice_connect_android");
final ModuleProxy.UniversalPromise uPromise = new PromiseAdapter(promise);
HashMap<String, String> parsedTwimlParams = new HashMap<>();
ReadableMapKeySetIterator iterator = twimlParams.keySetIterator();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableType readableType = twimlParams.getType(key);
switch (readableType) {
case Boolean:
parsedTwimlParams.put(key, String.valueOf(twimlParams.getBoolean(key)));
break;
case Number:
parsedTwimlParams.put(key, String.valueOf(twimlParams.getDouble(key)));
break;
case String:
parsedTwimlParams.put(key, twimlParams.getString(key));
break;
default:
logger.warning("Could not convert with key: " + key + ".");
break;
}
}
final Set<IceServer> iceServers = new HashSet<>();
final ReadableArray parsedJsIceServers = Optional
.ofNullable(jsIceServers)
.orElse(Arguments.createArray());
for (int i = 0; i < parsedJsIceServers.size(); i++) {
final ReadableMap jsIceServer = Optional
.ofNullable(parsedJsIceServers.getMap(i))
.orElse(Arguments.createMap());
final String serverUrl =
jsIceServer.hasKey(CommonConstants.IceServerKeyServerUrl)
? jsIceServer.getString(CommonConstants.IceServerKeyServerUrl)
: null;
final String username = jsIceServer.hasKey(CommonConstants.IceServerKeyUsername)
? jsIceServer.getString(CommonConstants.IceServerKeyUsername)
: null;
final String password = jsIceServer.hasKey(CommonConstants.IceServerKeyPassword)
? jsIceServer.getString(CommonConstants.IceServerKeyPassword)
: null;
if (serverUrl == null) {
uPromise.rejectWithName(
CommonConstants.ErrorCodeInvalidArgumentError,
"Server URL must be a non-null string."
);
return;
}
if (username != null && password != null) {
iceServers.add(new IceServer(serverUrl, username, password));
} else {
iceServers.add(new IceServer(serverUrl));
}
}
final String parsedJsIceTransportPolicy = Optional
.ofNullable(jsIceTransportPolicy)
.orElse("");
final IceTransportPolicy iceTransportPolicy = switch (parsedJsIceTransportPolicy) {
case CommonConstants.IceTransportPolicyValueAll -> IceTransportPolicy.ALL;
case CommonConstants.IceTransportPolicyValueRelay -> IceTransportPolicy.RELAY;
default -> null;
};
IceOptions iceOptions = null;
if (!iceServers.isEmpty() || iceTransportPolicy != null) {
final IceOptions.Builder iceOptionsBuilder = new IceOptions.Builder();
if (!iceServers.isEmpty()) {
iceOptionsBuilder.iceServers(iceServers);
}
if (iceTransportPolicy != null) {
iceOptionsBuilder.iceTransportPolicy(iceTransportPolicy);
}
iceOptions = iceOptionsBuilder.build();
}
this.moduleProxy.voice.connect(
accessToken,
parsedTwimlParams,
notificationDisplayName,
iceOptions,
uPromise
);
}
@ReactMethod
public void voice_getAudioDevices(Promise promise) {
this.moduleProxy.voice.getAudioDevices(new PromiseAdapter(promise));
}
@ReactMethod
public void voice_getCalls(Promise promise) {
this.moduleProxy.voice.getCalls(new PromiseAdapter(promise));
}
@ReactMethod
public void voice_getCallInvites(Promise promise) {
this.moduleProxy.voice.getCallInvites(new PromiseAdapter(promise));
}
@ReactMethod
public void voice_getDeviceToken(Promise promise) {
this.moduleProxy.voice.getDeviceToken(new PromiseAdapter(promise));
}
@ReactMethod
public void voice_getVersion(Promise promise) {
this.moduleProxy.voice.getVersion(new PromiseAdapter(promise));
}
@ReactMethod
public void voice_handleEvent(ReadableMap messageData, Promise promise) {
// parse data to string map
final HashMap<String, String> parsedMessageData = new HashMap<>();
ReadableMapKeySetIterator iterator = messageData.keySetIterator();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
parsedMessageData.put(key, messageData.getString(key));
}
this.moduleProxy.voice.handleEvent(parsedMessageData, new PromiseAdapter(promise));
}
@ReactMethod
public void voice_register(String token, Promise promise) {
this.moduleProxy.voice.register(token, new PromiseAdapter(promise));
}
@ReactMethod
public void voice_runPreflight(String accessToken, ReadableMap options, Promise promise) {
logger.debug(".voice_runPreflight");
final ModuleProxy.UniversalPromise uPromise = new PromiseAdapter(promise);
final PreflightOptions.Builder preflightOptionsBuilder = new PreflightOptions.Builder(accessToken);
// parse audio codec logic
final List<AudioCodec> preferredAudioCodecs = new ArrayList<>();
final ReadableArray jsPreferredAudioCodecs = Optional
.ofNullable(options.getArray(CommonConstants.CallOptionsKeyPreferredAudioCodecs))
.orElse(Arguments.createArray());
for (int i = 0; i < jsPreferredAudioCodecs.size(); i++) {
final ReadableMap jsAudioCodec = jsPreferredAudioCodecs.getMap(i);
if (jsAudioCodec == null) {
continue;
}
final String jsAudioCodecType = Optional
.ofNullable(jsAudioCodec.getString(CommonConstants.AudioCodecKeyType))
.orElse("");
if (jsAudioCodecType.equals(CommonConstants.AudioCodecTypeValuePCMU)) {
preferredAudioCodecs.add(new PcmuCodec());
continue;
}
if (jsAudioCodecType.equals(CommonConstants.AudioCodecTypeValueOpus)) {
if (!jsAudioCodec.hasKey(CommonConstants.AudioCodecOpusKeyMaxAverageBitrate)) {
preferredAudioCodecs.add(new OpusCodec());
continue;
}
final ReadableType maxAvgBitrateType = jsAudioCodec
.getDynamic(CommonConstants.AudioCodecOpusKeyMaxAverageBitrate)
.getType();
int maxAvgBitrate = 0;
if (ReadableType.Number.equals(maxAvgBitrateType)) {
maxAvgBitrate = Math.max(
maxAvgBitrate,
jsAudioCodec.getInt(CommonConstants.AudioCodecOpusKeyMaxAverageBitrate)
);
}
preferredAudioCodecs.add(new OpusCodec(maxAvgBitrate));
}
}
if (!preferredAudioCodecs.isEmpty()) {
preflightOptionsBuilder.preferAudioCodecs(preferredAudioCodecs);
}
// Ice servers logic.
final Set<IceServer> iceServers = new HashSet<>();
final ReadableArray jsIceServers = Optional
.ofNullable(options.getArray(CommonConstants.CallOptionsKeyIceServers))
.orElse(Arguments.createArray());
for (int i = 0; i < jsIceServers.size(); i++) {
final ReadableMap jsIceServer = Optional
.ofNullable(jsIceServers.getMap(i))
.orElse(Arguments.createMap());
final String serverUrl = jsIceServer.getString(CommonConstants.IceServerKeyServerUrl);
final String username = Optional
.ofNullable(jsIceServer.getString(CommonConstants.IceServerKeyUsername))
.orElse("");
final String password = Optional
.ofNullable(jsIceServer.getString(CommonConstants.IceServerKeyPassword))
.orElse("");
if (serverUrl == null) {
uPromise.rejectWithName(
CommonConstants.ErrorCodeInvalidArgumentError,
"Server URL must be a non-null string."
);
return;
}
iceServers.add(new IceServer(serverUrl, username, password));
}
// Ice transport policy logic.
final String jsIceTransportPolicy = Optional
.ofNullable(options.getString(CommonConstants.CallOptionsKeyIceTransportPolicy))
.orElse("");
final IceTransportPolicy iceTransportPolicy = switch (jsIceTransportPolicy) {
case CommonConstants.IceTransportPolicyValueAll -> IceTransportPolicy.ALL;
case CommonConstants.IceTransportPolicyValueRelay -> IceTransportPolicy.RELAY;
default -> null;
};
// Finally, build the options.
final IceOptions.Builder iceOptionsBuilder = new IceOptions.Builder();
if (iceTransportPolicy != null) {
iceOptionsBuilder.iceTransportPolicy(iceTransportPolicy);
}
if (!iceServers.isEmpty()) {
iceOptionsBuilder.iceServers(iceServers);
}
if (!iceServers.isEmpty() || iceTransportPolicy != null) {
preflightOptionsBuilder.iceOptions(iceOptionsBuilder.build());
}
final PreflightOptions preflightOptions = preflightOptionsBuilder.build();
this.moduleProxy.voice.runPreflight(preflightOptions, new PromiseAdapter(promise));
}
@ReactMethod
public void voice_selectAudioDevice(String uuid, Promise promise) {
this.moduleProxy.voice.selectAudioDevice(uuid, new PromiseAdapter(promise));
}
@ReactMethod
public void voice_setExpoVersion(String expoVersion, Promise promise) {
this.moduleProxy.voice.setExpoVersion(expoVersion, new PromiseAdapter(promise));
}
@ReactMethod
public void voice_setIncomingCallContactHandleTemplate(String template, Promise promise) {
this.moduleProxy.voice.setIncomingCallContactHandleTemplate(template, new PromiseAdapter(promise));
}
@ReactMethod
public void voice_unregister(String token, Promise promise) {
this.moduleProxy.voice.unregister(token, new PromiseAdapter(promise));
}
}