-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathBridge.java
692 lines (618 loc) · 31 KB
/
Bridge.java
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
package com.batch.cordova.android.interop;
import static com.batch.cordova.android.interop.BridgeUtils.convertSerializedEventDataToEventAttributes;
import static com.batch.cordova.android.interop.BridgeUtils.convertModernPromiseToLegacy;
import static com.batch.cordova.android.interop.BridgeUtils.getOptionalTypedParameter;
import static com.batch.cordova.android.interop.BridgeUtils.getTypedParameter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.util.Log;
import androidx.annotation.NonNull;
import com.batch.android.Batch;
import com.batch.android.BatchAttributesFetchListener;
import com.batch.android.BatchEmailSubscriptionState;
import com.batch.android.BatchSMSSubscriptionState;
import com.batch.android.BatchEventAttributes;
import com.batch.android.BatchMessage;
import com.batch.android.BatchMigration;
import com.batch.android.BatchPushRegistration;
import com.batch.android.BatchTagCollectionsFetchListener;
import com.batch.android.BatchUserAttribute;
import com.batch.android.BatchProfileAttributeEditor;
import com.batch.android.LoggerDelegate;
import com.batch.android.PushNotificationType;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Bridge that allows code to use Batch's APIs via an action+parameters request, to easily bridge it to some kind of JSON RPC
*/
public class Bridge {
private static final String INVALID_PARAMETER = "Invalid parameter";
private static final String BRIDGE_VERSION_ENVIRONMENT_VAR = "batch.bridge.version";
private static final String BRIDGE_VERSION = "Bridge/2.0";
private static final InboxBridge inboxBridge = new InboxBridge();
private static final String TAG = "BatchBridge";
public static final String BATCH_SHARED_PREFS_FILE ="batch";
public static final String BATCH_API_KEY_SHARED_PREFS_KEY ="batch_api_key";
static {
System.setProperty(BRIDGE_VERSION_ENVIRONMENT_VAR, BRIDGE_VERSION);
}
@SuppressWarnings("unused")
public static SimplePromise<String> call(String action, Map<String, Object> parameters, Callback callback, Activity activity) {
SimplePromise<String> result = null;
try {
result = doAction(action, parameters, activity);
} catch (Exception e) {
Log.e(TAG, "Batch bridge raised an exception", e);
if (callback != null) {
final Map<String, Object> failResult = new HashMap<>();
failResult.put("action", action);
failResult.put("error", errorToMap(e));
callback.callback(Result.BRIDGE_FAILURE.getName(), failResult);
}
}
if (result == null) {
result = SimplePromise.resolved("");
}
return result;
}
private static SimplePromise<String> doAction(String actionName, Map<String, Object> parameters, Activity activity) throws BridgeException, BatchBridgeNotImplementedException {
if (actionName == null || actionName.isEmpty()) {
throw new BridgeException(INVALID_PARAMETER + " : Empty or null action");
}
Action action;
try {
action = Action.fromName(actionName);
} catch (IllegalArgumentException actionParsingException) {
throw new BridgeException(INVALID_PARAMETER + " : Unknown action '" + actionName + "'", actionParsingException);
}
switch (action) {
case SET_CONFIG:
setConfig(activity, parameters);
break;
case START:
start(activity);
break;
case STOP:
stop(activity);
break;
case DESTROY:
destroy(activity);
break;
case ON_NEW_INTENT:
onNewIntent(activity, getTypedParameter(parameters, "intent", Intent.class));
break;
case OPT_IN:
optIn(activity);
break;
case OPT_OUT:
optOut(activity, false);
break;
case OPT_OUT_AND_WIPE_DATA:
optOut(activity, true);
break;
case IS_OPTED_OUT:
return convertModernPromiseToLegacy(isOptedOut(activity));
case SET_FIND_INSTALLATION_ENABLED:
Batch.setFindMyInstallationEnabled(getTypedParameter(parameters, "enabled", Boolean.class));
break;
case UPDATE_AUTOMATIC_DATA_COLLECTION:
updateAutomaticDataCollection(parameters);
break;
case MESSAGING_SET_DO_NOT_DISTURB_ENABLED:
Batch.Messaging.setDoNotDisturbEnabled(getTypedParameter(parameters, "enabled", Boolean.class));
break;
case MESSAGING_SHOW_PENDING_MESSAGE:
showPendingMessage(activity);
break;
case PUSH_GET_LAST_KNOWN_TOKEN:
return SimplePromise.resolved(getLastKnownPushToken());
case PUSH_DISMISS_NOTIFICATIONS:
dismissNotifications();
break;
case PUSH_CLEAR_BADGE:
// iOS only, do nothing
return null;
case PUSH_SET_IOSNOTIF_TYPES:
// iOS only, do nothing
return null;
case PUSH_SET_ANDROIDNOTIF_TYPES:
setNotificationTypes(getTypedParameter(parameters, "notifTypes", Integer.class));
break;
case PUSH_SET_IOSSHOW_FOREGROUND:
// iOS only, do nothing
return null;
case PUSH_IOS_REFRESH_TOKEN:
// iOS only, do nothing
return null;
case PUSH_REQUEST_AUTHORIZATION:
requestAuthorization(activity);
break;
case PUSH_IOS_REQUEST_PROVISIONAL_AUTH:
// iOS only, do nothing
return null;
case PROFILE_IDENTIFY:
identify(parameters);
break;
case PROFILE_EDIT:
editProfileAttributes(parameters);
break;
case PROFILE_TRACK_EVENT:
return convertModernPromiseToLegacy(trackEvent(parameters));
case PROFILE_TRACK_LOCATION:
trackLocation(parameters);
break;
case USER_GET_INSTALLATION_ID:
return SimplePromise.resolved(Batch.User.getInstallationID());
case USER_GET_LANGUAGE:
return SimplePromise.resolved(Batch.User.getLanguage(activity));
case USER_GET_REGION:
return SimplePromise.resolved(Batch.User.getRegion(activity));
case USER_GET_IDENTIFIER:
return SimplePromise.resolved(Batch.User.getIdentifier(activity));
case USER_FETCH_ATTRIBUTES:
return convertModernPromiseToLegacy(userFetchAttributes(activity));
case USER_FETCH_TAGS:
return convertModernPromiseToLegacy(userFetchTags(activity));
case USER_CLEAR_INSTALL_DATA:
Batch.User.clearInstallationData();
break;
case INBOX_CREATE_INSTALLATION_FETCHER:
case INBOX_CREATE_USER_FETCHER:
case INBOX_RELEASE_FETCHER:
case INBOX_FETCH_NEW_NOTIFICATIONS:
case INBOX_FETCH_NEXT_PAGE:
case INBOX_GET_FETCHED_NOTIFICATIONS:
case INBOX_MARK_AS_READ:
case INBOX_MARK_ALL_AS_READ:
case INBOX_MARK_AS_DELETED:
case INBOX_DISPLAY_LANDING_MESSAGE:
return inboxBridge.compatDoAction(action, parameters, activity);
default:
throw new BridgeException(INVALID_PARAMETER + " : Action '" + actionName + "' is known, but not implemented");
}
return null;
}
private static Map<String, Object> errorToMap(Exception exception) {
final Map<String, Object> errorMap = new HashMap<>();
if (exception != null) {
errorMap.put("cause", exception.getMessage());
errorMap.put("kind", exception.toString());
}
return errorMap;
}
// region Core Module
private static void setConfig(Context context, Map<String, Object> parameters) throws BridgeException {
// Set BatchCordovaPlugin class as LoggerDelegate
LoggerDelegate loggerDelegate = null;
try {
loggerDelegate = getTypedParameter(parameters, "logger", LoggerDelegate.class);
} catch (BridgeException e) {
// The parameter is optional, disregard the exception
// TODO : Maybe improve this if the parameter is here but deserialization failed
}
if (loggerDelegate != null) {
Batch.setLoggerDelegate(loggerDelegate);
}
// Set profile migrations configuration
try {
Map<String, Object> migrationsConfig = getTypedParameter(parameters, "migrations", Map.class);
Boolean profileCustomIdMigrationEnabled = getOptionalTypedParameter(migrationsConfig, "profileCustomIdMigrationEnabled", Boolean.class, true);
Boolean profileCustomDataMigrationEnabled = getOptionalTypedParameter(migrationsConfig, "profileCustomDataMigrationEnabled", Boolean.class, true);
EnumSet<BatchMigration> migrations = EnumSet.noneOf(BatchMigration.class);
if (Boolean.FALSE.equals(profileCustomIdMigrationEnabled)) {
Log.d(TAG, "Disabling profile custom id migration.");
migrations.add(BatchMigration.CUSTOM_ID);
}
if (Boolean.FALSE.equals(profileCustomDataMigrationEnabled)) {
Log.d(TAG, "Disabling profile custom data migration.");
migrations.add(BatchMigration.CUSTOM_DATA);
}
Batch.disableMigration(migrations);
} catch (BridgeException e) {
Log.d(TAG, "Internal bridge error, expected migrations configuration.");
}
// Start SDK
String apiKey = getTypedParameter(parameters, "APIKey", String.class);
SharedPreferences preferences = context.getSharedPreferences(BATCH_SHARED_PREFS_FILE, Context.MODE_PRIVATE);
preferences.edit().putString(BATCH_API_KEY_SHARED_PREFS_KEY, apiKey).apply();
Batch.start(apiKey);
}
private static void start(Activity activity) {
Batch.onStart(activity);
}
private static void stop(Activity activity) {
Batch.onStop(activity);
}
private static void destroy(Activity activity) {
Batch.onDestroy(activity);
}
private static void onNewIntent(Activity activity, Intent intent) {
Batch.onNewIntent(activity, intent);
}
private static void optIn(Activity activity) {
Batch.optIn(activity);
Batch.onStart(activity);
}
private static void optOut(Activity activity, boolean wipeData) {
if (wipeData) {
Batch.optOutAndWipeData(activity);
} else {
Batch.optOut(activity);
}
}
private static SimplePromise<Object> isOptedOut(Activity activity) {
return SimplePromise.resolved(Collections.singletonMap("isOptedOut", Batch.isOptedOut(activity)));
}
private static String getLastKnownPushToken() {
BatchPushRegistration registration = Batch.Push.getRegistration();
return registration != null ? registration.getToken() : "";
}
@SuppressWarnings("unchecked")
private static void updateAutomaticDataCollection(Map<String, Object> parameters) throws BridgeException {
Map<String, Object> dataCollectionConfig = getTypedParameter(parameters, "dataCollection", Map.class);
Boolean deviceBrand = getOptionalTypedParameter(dataCollectionConfig, "deviceBrand", Boolean.class, null);
Boolean deviceModel = getOptionalTypedParameter(dataCollectionConfig, "deviceModel", Boolean.class, null);
Boolean geoIP = getOptionalTypedParameter(dataCollectionConfig, "geoIP", Boolean.class, null);
Batch.updateAutomaticDataCollection(batchDataCollectionConfig -> {
if (deviceBrand != null) {
batchDataCollectionConfig.setDeviceBrandEnabled(deviceBrand);
}
if (deviceModel != null) {
batchDataCollectionConfig.setDeviceModelEnabled(deviceModel);
}
if (geoIP != null) {
batchDataCollectionConfig.setGeoIPEnabled(geoIP);
}
});
}
// endregion
// region Push Module
private static void dismissNotifications() {
Batch.Push.dismissNotifications();
}
private static void setNotificationTypes(Integer types) {
// Setup notification types.
EnumSet<PushNotificationType> pushTypes = PushNotificationType.fromValue(types.intValue());
Batch.Push.setNotificationsType(pushTypes);
}
private static void requestAuthorization(Activity activity) {
// Ask for android 13 notification permission
Batch.Push.requestNotificationPermission(activity);
}
// endregion
//region Messaging Module
private static void showPendingMessage(Activity activity) {
BatchMessage msg = Batch.Messaging.popPendingMessage();
if (msg != null) {
Batch.Messaging.show(activity, msg);
}
}
//endregion
// region Profile Module
private static void identify(Map<String, Object> parameters) {
String identifier = getOptionalTypedParameter(parameters, "custom_user_id", String.class, null);
Batch.Profile.identify(identifier);
}
@SuppressWarnings({"unchecked", "ConstantConditions"})
private static void editProfileAttributes(Map<String, Object> parameters) throws BridgeException {
try {
//noinspection unchecked
List<Map<String, Object>> operations = getTypedParameter(parameters, "operations", List.class);
if (operations == null) {
return;
}
BatchProfileAttributeEditor editor = Batch.Profile.editor();
for (Map<String, Object> operationDescription : operations) {
String operationName = getTypedParameter(operationDescription, "operation", String.class);
switch (operationName) {
case "SET_LANGUAGE" -> {
Object value = operationDescription.get("value");
if (value != null && !(value instanceof String)) {
Log.e(TAG, "Invalid SET_LANGUAGE value: it can only be a string or null");
// Invalid value, continue. NULL is allowed though
continue;
}
editor.setLanguage((String) value);
}
case "SET_REGION" -> {
Object value = operationDescription.get("value");
if (value != null && !(value instanceof String)) {
Log.e(TAG, "Invalid SET_REGION value: it can only be a string or null");
// Invalid value, continue. NULL is allowed though
continue;
}
editor.setRegion((String) value);
}
case "SET_EMAIL_ADDRESS" -> {
Object value = operationDescription.get("value");
if (value != null && !(value instanceof String)) {
Log.e(TAG, "Invalid SET_EMAIL value: it can only be a string or null");
// Invalid value, continue. NULL is allowed though
continue;
}
editor.setEmailAddress((String) value);
}
case "SET_EMAIL_MARKETING_SUB" -> {
Object value = operationDescription.get("value");
if (value == null || !(value instanceof String)) {
Log.e(TAG, "Invalid SET_EMAIL_MARKETING_SUB value: it can only be a string");
// Invalid value, continue.
continue;
}
if ("subscribed".equals(value)) {
editor.setEmailMarketingSubscription(BatchEmailSubscriptionState.SUBSCRIBED);
} else if ("unsubscribed".equals(value)) {
editor.setEmailMarketingSubscription(BatchEmailSubscriptionState.UNSUBSCRIBED);
} else {
Log.e(TAG, "Invalid SET_EMAIL_MARKETING_SUBSCRIPTION value: it can only be `subscribed` or `unsubscribed`.");
}
}
case "SET_PHONE_NUMBER" -> {
Object value = operationDescription.get("value");
if (value != null && !(value instanceof String)) {
Log.e(TAG, "Invalid SET_PHONE_NUMBER value: it can only be a string or null");
// Invalid value, continue. NULL is allowed though
continue;
}
editor.setPhoneNumber((String) value);
}
case "SET_SMS_MARKETING_SUB" -> {
Object value = operationDescription.get("value");
if (value == null || !(value instanceof String)) {
Log.e(TAG, "Invalid SET_SMS_MARKETING_SUB value: it can only be a string");
// Invalid value, continue.
continue;
}
if ("subscribed".equals(value)) {
editor.setSMSMarketingSubscription(BatchSMSSubscriptionState.SUBSCRIBED);
} else if ("unsubscribed".equals(value)) {
editor.setSMSMarketingSubscription(BatchSMSSubscriptionState.UNSUBSCRIBED);
} else {
Log.e(TAG, "Invalid SET_SMS_MARKETING_SUB value: it can only be `subscribed` or `unsubscribed`.");
}
}
case "SET_ATTRIBUTE" -> {
String key = getTypedParameter(operationDescription, "key", String.class);
String type = getTypedParameter(operationDescription, "type", String.class);
switch (type) {
case "string" ->
editor.setAttribute(key, getTypedParameter(operationDescription, "value", String.class));
case "url" -> {
try {
editor.setAttribute(key, new URI(getTypedParameter(operationDescription, "value", String.class)));
} catch (URISyntaxException e) {
Log.e(TAG, "Invalid SET_ATTRIBUTE url value: couldn't parse value", e);
}
}
case "date" ->
editor.setAttribute(key, new Date(getTypedParameter(operationDescription, "value", Number.class).longValue()));
case "integer" -> {
Object rawValue = operationDescription.get("value");
if (rawValue instanceof Number) {
editor.setAttribute(key, ((Number) rawValue).longValue());
} else if (rawValue instanceof String) {
try {
editor.setAttribute(key, Long.parseLong((String) rawValue));
} catch (NumberFormatException e) {
Log.e(TAG, "Invalid SET_ATTRIBUTE integer value: couldn't parse value", e);
}
}
}
case "float" -> {
Object rawValue = operationDescription.get("value");
if (rawValue instanceof Number) {
editor.setAttribute(key, ((Number) rawValue).doubleValue());
} else if (rawValue instanceof String) {
try {
editor.setAttribute(key, Double.parseDouble((String) rawValue));
} catch (NumberFormatException e) {
Log.e(TAG, "Invalid SET_ATTRIBUTE float value: couldn't parse value", e);
}
}
}
case "boolean" -> {
Object rawValue = operationDescription.get("value");
if (rawValue instanceof Boolean) {
editor.setAttribute(key, (Boolean) rawValue);
} else if (rawValue instanceof String) {
try {
editor.setAttribute(key, Boolean.parseBoolean((String) rawValue));
} catch (NumberFormatException e) {
Log.e(TAG, "Invalid SET_ATTRIBUTE boolean value: couldn't parse value", e);
}
}
}
case "array" -> {
List<String> value = getTypedParameter(operationDescription, "value", ArrayList.class);
if (value != null) {
editor.setAttribute(key, new ArrayList<String>(value));
}
}
}
}
case "REMOVE_ATTRIBUTE" ->
editor.removeAttribute(getTypedParameter(operationDescription, "key", String.class));
case "ADD_TO_ARRAY" -> {
String key = getTypedParameter(operationDescription, "key", String.class);
String value = getOptionalTypedParameter(operationDescription, "value", String.class, null);
List<String> arrayValue = getOptionalTypedParameter(operationDescription, "value", ArrayList.class, null);
if (value != null) {
editor.addToArray(key, value);
} else if (arrayValue != null){
editor.addToArray(key, new ArrayList<>(arrayValue));
}
}
case "REMOVE_FROM_ARRAY" -> {
String key = getTypedParameter(operationDescription, "key", String.class);
String value = getOptionalTypedParameter(operationDescription, "value", String.class, null);
List<String> arrayValue = getOptionalTypedParameter(operationDescription, "value", ArrayList.class, null);
if (value != null) {
editor.removeFromArray(key, value);
} else if (arrayValue != null){
editor.removeFromArray(key, new ArrayList<>(arrayValue));
}
}
}
}
editor.save();
} catch (ClassCastException e) {
throw new BridgeException("Error while reading operations ", e);
}
}
private static SimplePromise<Object> trackEvent(Map<String, Object> parameters) {
return new SimplePromise<>(promise -> {
String name = null;
try {
name = getTypedParameter(parameters, "name", String.class);
} catch (BridgeException e) {
promise.reject(new BridgeException("Missing event name parameter.", e));
return;
}
Map<String, Object> data = null;
try {
data = getTypedParameter(parameters, "event_data", Map.class);
} catch (BridgeException e) {
// Event data are optionals, disregard the exception
}
if (data != null) {
try {
BatchEventAttributes batchEventAttributes = convertSerializedEventDataToEventAttributes(data);
List<String> errors = batchEventAttributes.validateEventAttributes();
if (errors.isEmpty()) {
Batch.Profile.trackEvent(name, batchEventAttributes);
promise.resolve(null);
} else {
Log.w(TAG, "Invalid event attributes: " + errors);
promise.reject(new BridgeException("Invalid event attributes: " + errors));
}
} catch (BridgeException e) {
promise.reject(e);
}
} else {
Batch.Profile.trackEvent(name, null);
}
});
}
private static void trackLocation(Map<String, Object> parameters) throws BridgeException {
double latitude = getTypedParameter(parameters, "latitude", Number.class).doubleValue();
double longitude = getTypedParameter(parameters, "longitude", Number.class).doubleValue();
Integer precision = null;
try {
precision = getTypedParameter(parameters, "precision", Integer.class);
} catch (BridgeException e) {
// The parameter is optional, disregard the exception
}
Number date = null;
try {
date = getTypedParameter(parameters, "date", Number.class);
} catch (BridgeException e) {
// The parameter is optional, disregard the exception
}
Location location = new Location("com.batch.android.cordova.bridge");
location.setLatitude(latitude);
location.setLongitude(longitude);
if (precision != null) {
location.setAccuracy(precision.floatValue());
}
if (date != null) {
location.setTime(date.longValue());
}
Batch.Profile.trackLocation(location);
}
//endregion
//region User Module
private static SimplePromise<Object> userFetchAttributes(Activity activity) {
return new SimplePromise<>(promise -> {
Batch.User.fetchAttributes(activity, new BatchAttributesFetchListener() {
@Override
public void onSuccess(@NonNull Map<String, BatchUserAttribute> map) {
Map<String, Map<String, Object>> bridgeAttributes = new HashMap<>();
for (Map.Entry<String, BatchUserAttribute> attributeEntry : map.entrySet()) {
Map<String, Object> typedBrdigeAttribute = new HashMap<>();
BatchUserAttribute attribute = attributeEntry.getValue();
String type;
Object value = attribute.value;
switch (attribute.type) {
case BOOL:
type = "b";
break;
case DATE: {
type = "d";
Date dateValue = attribute.getDateValue();
if (dateValue == null) {
promise.reject(new BridgeException("Fetch attribute: Could not parse date for key: " + attributeEntry.getKey()));
return;
}
value = dateValue.getTime();
break;
}
case STRING:
type = "s";
break;
case LONGLONG:
type = "i";
break;
case DOUBLE:
type = "f";
break;
case URL:
type = "u";
URI uriValue = attribute.getUriValue();
if (uriValue == null) {
promise.reject(new BridgeException("Fetch attribute: Could not parse URL for key: " + attributeEntry.getKey()));
return;
}
value = uriValue.toString();
break;
default:
promise.reject(new BridgeException("Fetch attribute: Unknown attribute type " + attribute.type + " for key: " + attributeEntry.getKey()));
return;
}
typedBrdigeAttribute.put("type", type);
typedBrdigeAttribute.put("value", value);
bridgeAttributes.put(attributeEntry.getKey(), typedBrdigeAttribute);
}
final Map<String, Map<String, Map<String, Object>>> resultMap = new HashMap<>();
resultMap.put("attributes", bridgeAttributes);
promise.resolve(resultMap);
}
@Override
public void onError() {
promise.reject(new BridgeException("Native fetchAttributes returned an error"));
}
});
});
}
private static SimplePromise<Object> userFetchTags(Activity activity) {
return new SimplePromise<>(promise -> {
Batch.User.fetchTagCollections(activity, new BatchTagCollectionsFetchListener() {
@Override
public void onSuccess(@NonNull Map<String, Set<String>> map) {
Map<String, List<String>> bridgeTagCollections = new HashMap<>();
for (Map.Entry<String, Set<String>> tagCollection : map.entrySet()) {
bridgeTagCollections.put(tagCollection.getKey(), new ArrayList<>(tagCollection.getValue()));
}
final Map<String, Map<String, List<String>>> resultMap = new HashMap<>();
resultMap.put("tagCollections", bridgeTagCollections);
promise.resolve(resultMap);
}
@Override
public void onError() {
promise.reject(new BridgeException("Native fetchTagCollections returned an error"));
}
});
});
}
//endregion
}