-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathBatchBridge.m
529 lines (446 loc) · 16.6 KB
/
BatchBridge.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
//
// BatchBridge.m
// bridge
//
// https://batch.com
// Copyright (c) 2014 Batch SDK. All rights reserved.
//
//
#import "BatchBridge.h"
#import <CoreLocation/CoreLocation.h>
#import <Batch/Batch.h>
#import <Batch/BatchUser.h>
#import <Batch/BatchPush.h>
#import "BatchBridgeShared.h"
#import "BatchInboxBridge.h"
#import "BatchBridgeNotificationCenterDelegate.h"
#import "BatchUserBridge.h"
#import "BatchProfileBridge.h"
#import "BatchBridgeUtils.h"
#define INVALID_PARAMETER @"Invalid parameter."
#define BridgeVersion @"2.0"
static NSString *currentAPIKey = @"";
static BatchBridge *sharedInstance = nil;
static dispatch_once_t onceToken;
@interface BatchBridge ()
{
id<BatchBridgeCallback> _callback;
NSDictionary *_userInfo;
}
@end
@implementation BatchBridge
#pragma mark -
#pragma mark Public methods
- (id)initWithCallback:(id<BatchBridgeCallback>)callback userInfos:(NSDictionary *)info
{
self = [super init];
if (self != nil)
{
_callback = callback;
_userInfo = info;
}
return self;
}
+ (void)initialize
{
// Setup bridge version.
NSString *infos = [NSString stringWithFormat:@"Bridge/%@",BridgeVersion];
setenv("BATCH_BRIDGE_VERSION", [infos cStringUsingEncoding:NSUTF8StringEncoding], 1);
}
+ (BatchBridge*)instanceWithCallback:(id<BatchBridgeCallback>)callback
{
dispatch_once(&onceToken, ^{
sharedInstance = [[BatchBridge alloc] initWithCallback:callback userInfos:@{@"APIKey": currentAPIKey}];
});
return sharedInstance;
}
// Perform an action and callback.
+ (BACSimplePromise<NSString*> *)call:(NSString *)action withParameters:(NSDictionary *)parameters callback:(id<BatchBridgeCallback>)callback
{
BACSimplePromise<NSString*> *result = nil;
@try
{
result = [BatchBridge doAction:action withParameters:parameters callback:callback];
}
@catch (NSException *exception)
{
NSLog(@"Batch bridge raised an exception: %@",exception);
if (callback)
{
[callback call:ON_FAILURE withResult:[exception reason]];
}
result = [BACSimplePromise resolved:@""];
}
return result;
}
#pragma mark -
#pragma mark Private methods
+ (NSString *)boolToBridgeString:(BOOL)value
{
return value ? @"true" : @"false";
}
+ (BACSimplePromise<NSString*> *)doAction:(NSString *)action withParameters:(NSDictionary *)parameters callback:(id<BatchBridgeCallback>)callback
{
// Check action description.
if (action==nil || ![action isKindOfClass:[NSString class]] || action.length==0)
{
[NSException raise:INVALID_PARAMETER format:@"Empty or null action: %@",action];
}
// startWithCallback:
if ([action caseInsensitiveCompare:START] == NSOrderedSame)
{
[BatchBridge startWithCallback:callback];
}
// optIn:
else if ([action caseInsensitiveCompare:OPT_IN] == NSOrderedSame)
{
[BatchSDK optIn];
if ([currentAPIKey length] > 0)
{
[BatchSDK startWithAPIKey:currentAPIKey];
}
}
// optOut:
else if ([action caseInsensitiveCompare:OPT_OUT] == NSOrderedSame)
{
[BatchSDK optOut];
}
// optOutAndWipeData:
else if ([action caseInsensitiveCompare:OPT_OUT_AND_WIPE_DATA] == NSOrderedSame)
{
[BatchSDK optOutAndWipeData];
}
// isOptedOut:
else if ([action caseInsensitiveCompare:IS_OPTED_OUT] == NSOrderedSame)
{
return [self convertPromiseToLegacyBridge:[BACSimplePromise resolved:@{
@"isOptedOut": [NSNumber numberWithBool:BatchSDK.isOptedOut]
}]] ;
}
// enablesFindMyInstallation:
else if ([action caseInsensitiveCompare:SET_FIND_MY_INSTALLATION_ENABLED] == NSOrderedSame)
{
if (!parameters || [parameters count]==0)
{
[NSException raise:INVALID_PARAMETER format:@"Empty or null parameters for action setFindMyInstallationEnabled "];
}
NSNumber *enabled = parameters[@"enabled"];
if (![enabled isKindOfClass:[NSNumber class]])
{
[NSException raise:INVALID_PARAMETER format:@"enabled should be a NSNumber"];
}
BatchSDK.enablesFindMyInstallation = [enabled boolValue];
}
// updateAutomaticDataCollection:
else if ([action caseInsensitiveCompare:UPDATE_AUTOMATIC_DATA_COLLECTION] == NSOrderedSame)
{
if (!parameters || [parameters count]==0) {
[NSException raise:INVALID_PARAMETER format:@"Empty or null parameters for action setFindMyInstallationEnabled "];
}
NSDictionary* dataCollectionConfig = [parameters objectForKey:@"dataCollection"];
BOOL hasDeviceModel = [dataCollectionConfig objectForKey:@"deviceModel"] != nil;
BOOL hasGeoIP = [dataCollectionConfig objectForKey:@"geoIP"] != nil;
if (hasDeviceModel || hasGeoIP) {
[BatchSDK updateAutomaticDataCollection:^(BatchDataCollectionConfig * _Nonnull batchDataCollectionConfig) {
if (hasDeviceModel) {
batchDataCollectionConfig.deviceModelEnabled = [dataCollectionConfig[@"deviceModel"] boolValue];
}
if (hasGeoIP) {
batchDataCollectionConfig.geoIPEnabled = [dataCollectionConfig[@"geoIP"] boolValue];
}
}];
} else {
NSLog(@"BatchBridge - Invalid parameter: Data collection config cannot be empty.");
}
}
// setConfigWithApiKey:andUseIDFA:
else if ([action caseInsensitiveCompare:SET_CONFIG] == NSOrderedSame)
{
if (!parameters || [parameters count]==0)
{
[NSException raise:INVALID_PARAMETER format:@"Empty or null parameters for action %@.", action];
}
NSString *APIKey = [parameters objectForKey:@"APIKey"];
if (!APIKey)
{
[NSException raise:INVALID_PARAMETER format:@"Missing parameter 'APIKey' for action %@.", action];
}
NSDictionary *migrations = [parameters objectForKey:@"migrations"];
if (!migrations) {
NSLog(@"BatchBridge - Internal bridge error: expected migrations configuration.");
}
[BatchBridge setConfigWithApiKey:APIKey andMigrations:migrations];
}
else if ([action caseInsensitiveCompare:PUSH_GET_LAST_KNOWN_TOKEN] == NSOrderedSame)
{
return [BACSimplePromise resolved:[BatchBridge lastKnownPushToken]];
}
else if ([action caseInsensitiveCompare:PUSH_REFRESH_TOKEN] == NSOrderedSame)
{
[BatchPush refreshToken];
}
else if ([action caseInsensitiveCompare:PUSH_REQUEST_AUTHORIZATION] == NSOrderedSame)
{
[BatchPush requestNotificationAuthorization];
}
else if ([action caseInsensitiveCompare:PUSH_REQUEST_PROVISIONAL_AUTH] == NSOrderedSame)
{
[BatchPush requestProvisionalNotificationAuthorization];
}
// Android Push Only
else if ([action caseInsensitiveCompare:SET_GCM_SENDER_ID] == NSOrderedSame)
{
// Do nothing
}
else if ([action caseInsensitiveCompare:SET_IOS_SHOW_FOREGROUND_NOTIFS] == NSOrderedSame)
{
if (!parameters || [parameters count]==0)
{
[NSException raise:INVALID_PARAMETER format:@"Empty or null parameters for action %@.", action];
}
NSNumber *showForeground = [parameters objectForKey:@"showForeground"];
if (!showForeground)
{
[NSException raise:INVALID_PARAMETER format:@"Missing parameter 'showForeground' for action %@.", action];
}
[BatchBridge setiOSShowForegroundNotifications:[showForeground boolValue]];
}
else if ([action caseInsensitiveCompare:SET_IOSNOTIF_TYPES] == NSOrderedSame)
{
if (!parameters || [parameters count]==0)
{
[NSException raise:INVALID_PARAMETER format:@"Empty or null parameters for action %@.", action];
}
NSNumber *notifTypes = [parameters objectForKey:@"notifTypes"];
if (!notifTypes)
{
[NSException raise:INVALID_PARAMETER format:@"Missing parameter 'notifTypes' for action %@.", action];
}
[BatchBridge setNotificationTypes:(BatchNotificationType)[notifTypes integerValue]];
}
// Android Push Only
else if ([action caseInsensitiveCompare:SET_ANDROIDNOTIF_TYPES] == NSOrderedSame)
{
// Do nothing
}
else if ([action caseInsensitiveCompare:DISMISS_NOTIFS] == NSOrderedSame)
{
[BatchBridge dismissNotifications];
}
else if ([action caseInsensitiveCompare:CLEAR_BADGE] == NSOrderedSame)
{
[BatchBridge clearBadge];
}
else if ([action caseInsensitiveCompare:USER_GET_LANGUAGE] == NSOrderedSame)
{
return [BACSimplePromise resolved:[BatchBridge user_getLanguage]];
}
else if ([action caseInsensitiveCompare:USER_GET_REGION] == NSOrderedSame)
{
return [BACSimplePromise resolved:[BatchBridge user_getRegion]];
}
else if ([action caseInsensitiveCompare:USER_GET_IDENTIFIER] == NSOrderedSame)
{
return [BACSimplePromise resolved:[BatchBridge user_getIdentifier]];
}
else if ([action caseInsensitiveCompare:USER_CLEAR_INSTALL_DATA] == NSOrderedSame)
{
[BatchUser clearInstallationData];
}
else if ([action caseInsensitiveCompare:PROFILE_IDENTIFY] == NSOrderedSame)
{
if (!parameters || [parameters count]==0)
{
[NSException raise:INVALID_PARAMETER format:@"Empty or null parameters for action %@.", action];
}
[BatchProfileBridge identify:parameters];
}
else if ([action caseInsensitiveCompare:PROFILE_EDIT] == NSOrderedSame)
{
if (!parameters || [parameters count]==0)
{
[NSException raise:INVALID_PARAMETER format:@"Empty or null parameters for action %@.", action];
}
[BatchProfileBridge editAttributes:parameters];
}
else if ([action caseInsensitiveCompare:PROFILE_TRACK_EVENT] == NSOrderedSame)
{
return [BACSimplePromise resolved:[BatchProfileBridge trackEvent:parameters]];
}
else if ([action caseInsensitiveCompare:PROFILE_TRACK_LOCATION] == NSOrderedSame)
{
[BatchProfileBridge trackLocation:parameters];
}
else if ([action caseInsensitiveCompare:USER_GET_INSTALLATION_ID] == NSOrderedSame)
{
return [BACSimplePromise resolved:[BatchUser installationID]];
}
else if ([action caseInsensitiveCompare:USER_FETCH_ATTRIBUTES] == NSOrderedSame)
{
return [self convertPromiseToLegacyBridge:[BatchUserBridge fetchAttributes]];
}
else if ([action caseInsensitiveCompare:USER_FETCH_TAGS] == NSOrderedSame)
{
return [self convertPromiseToLegacyBridge:[BatchUserBridge fetchTags]];
}
else if ([action caseInsensitiveCompare:MESSAGING_SET_DND_ENABLED] == NSOrderedSame)
{
[BatchBridge setMessagingDoNotDisturbEnabled:parameters];
}
else if ([action caseInsensitiveCompare:MESSAGING_SHOW_PENDING_MSG] == NSOrderedSame)
{
[BatchMessaging showPendingMessage];
}
else if ([action.lowercaseString hasPrefix:INBOX_PREFIX])
{
// The Inbox Bridge will take care of every inbox method
BACSimplePromise *inboxPromise = [[BatchInboxBridge sharedInboxBridge] doAction:action withParameters:parameters];
if (inboxPromise != nil) {
return inboxPromise;
} else {
[NSException raise:INVALID_PARAMETER format:@"Unknown inbox action: %@", action];
}
}
else
{
// Unknown method.
[NSException raise:INVALID_PARAMETER format:@"Unknown action: %@", action];
}
return [BACSimplePromise resolved:@""];
}
#pragma mark -
#pragma mark Helpers
// Converts a "new format" Promise matching newer bridges like Flutter (can be resolved to a Dictionary, or rejected)
// to a "legacy" one that is resolved with a string and shouldn't reject.
// Stepping stone until we add proper support for those in the base bridge
+ (nullable BACSimplePromise<NSString*> *)convertPromiseToLegacyBridge:(nullable BACSimplePromise*)sourcePromise {
if (sourcePromise == nil) {
return nil;
}
// Promise that holds the output, will be resolved by a "sub promise" (as we can't chain simple promises yet)
// that convers NSDictionaries to NSStrings and catches errors.
BACSimplePromise<NSString*> *responsePromise = [BACSimplePromise new];
[sourcePromise then:^(NSObject * _Nullable value) {
// No NSNumber/NSArray support. NSNumber might be fine anyway.
if ([value isKindOfClass:[NSDictionary class]]) {
// dictionaryToJSON: might seria
NSString *jsonResponse = [self dictionaryToJSON:(NSDictionary*)value];
if (jsonResponse != nil) {
[responsePromise resolve:jsonResponse];
} else {
[responsePromise resolve:@"{'error':'Internal native error (-1100)', 'code': -1100}"];
}
} else {
[responsePromise resolve:(id)value];
}
}];
[sourcePromise catch:^(NSError * _Nullable error) {
NSString *jsonError;
NSString *description = [error localizedDescription];
if ([description length] > 0) {
jsonError = [self dictionaryToJSON:@{
@"error": description,
@"code": @(error.code),
}];
}
if (jsonError == nil) {
jsonError = @"{'error':'Internal native error (-1200)', 'code': -1200}";
}
[responsePromise resolve:jsonError];
}];
return responsePromise;
}
+ (NSString*)dictionaryToJSON:(NSDictionary*)dictionary
{
if (dictionary) {
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:nil];
if (data) {
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
}
return nil;
}
#pragma mark -
#pragma mark Batch bindings
+ (void)startWithCallback:(id<BatchBridgeCallback>)callback
{
[BatchSDK startWithAPIKey:currentAPIKey];
[BatchBridgeNotificationCenterDelegate sharedInstance].isBatchReady = true;
}
+ (void)setConfigWithApiKey:(NSString*)APIKey andMigrations:(NSDictionary*)migrations
{
// Set profile migrations configuration
id profileCustomIDMigrationEnabled = [migrations objectForKey:@"profileCustomIdMigrationEnabled"];
id profileCustomDataMigrationEnabled = [migrations objectForKey:@"profileCustomDataMigrationEnabled"];
BatchMigration disabledMigrations = BatchMigrationNone;
if (profileCustomIDMigrationEnabled != nil && [profileCustomIDMigrationEnabled boolValue] == false) {
NSLog(@"[BatchBridge] Disabling profile custom id migration");
disabledMigrations |= BatchMigrationCustomID;
}
if (profileCustomDataMigrationEnabled != nil && [profileCustomDataMigrationEnabled boolValue] == false) {
NSLog(@"[BatchBridge] Disabling profile custom data migration");
disabledMigrations |= BatchMigrationCustomData;
}
[BatchSDK setDisabledMigrations:disabledMigrations];
// Set API Key
currentAPIKey = APIKey;
}
#pragma mark -
#pragma mark Push methods
+ (NSString*)lastKnownPushToken
{
NSString *token = [BatchPush lastKnownPushToken];
if (token)
{
return token;
}
return @"";
}
+ (void)setiOSShowForegroundNotifications:(BOOL)showForegroundNotifications
{
BatchBridgeNotificationCenterDelegate *delegate = [BatchBridgeNotificationCenterDelegate sharedInstance];
delegate.showForegroundNotifications = showForegroundNotifications;
delegate.shouldUseChainedCompletionHandlerResponse = false;
}
+ (void)setNotificationTypes:(BatchNotificationType)type
{
[BatchPush setRemoteNotificationTypes:type];
}
+ (void)clearBadge
{
[BatchPush clearBadge];
}
+ (void)dismissNotifications
{
[BatchPush dismissNotifications];
}
#pragma mark -
#pragma mark User methods
+ (NSString *)user_getLanguage
{
return [BatchUser language];
}
+ (NSString *)user_getRegion
{
return [BatchUser region];
}
+ (NSString *)user_getIdentifier
{
return [BatchUser identifier];
}
#pragma mark -
#pragma mark Messaging methods
+ (void)setMessagingDoNotDisturbEnabled:(NSDictionary*)params
{
if (!params || [params count]==0)
{
[NSException raise:INVALID_PARAMETER format:@"Empty or null parameters for action messaging.setDoNotDisturbEnabled"];
}
NSNumber *enabled = params[@"enabled"];
if (![enabled isKindOfClass:[NSNumber class]])
{
[NSException raise:INVALID_PARAMETER format:@"enabled should be a NSNumber"];
}
BatchMessaging.doNotDisturb = [enabled boolValue];
}
@end