RNFIRMessaging.m 30.3 KB
Newer Older
1
#import "RNFIRMessaging.h"
Libin Lu's avatar
init  
Libin Lu committed
2

Libin Lu's avatar
Libin Lu committed
3 4
#import <React/RCTConvert.h>
#import <React/RCTUtils.h>
Libin Lu's avatar
init  
Libin Lu committed
5

Libin Lu's avatar
Libin Lu committed
6 7
@import UserNotifications;

Libin Lu's avatar
init  
Libin Lu committed
8 9 10 11 12 13 14 15 16 17 18
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0

#define UIUserNotificationTypeAlert UIRemoteNotificationTypeAlert
#define UIUserNotificationTypeBadge UIRemoteNotificationTypeBadge
#define UIUserNotificationTypeSound UIRemoteNotificationTypeSound
#define UIUserNotificationTypeNone  UIRemoteNotificationTypeNone
#define UIUserNotificationType      UIRemoteNotificationType

#endif

NSString *const FCMNotificationReceived = @"FCMNotificationReceived";
Libin Lu's avatar
Libin Lu committed
19 20
NSString *const FCMTokenRefreshed = @"FCMTokenRefreshed";
NSString *const FCMDirectChannelConnectionChanged = @"FCMDirectChannelConnectionChanged";
Libin Lu's avatar
init  
Libin Lu committed
21

Libin Lu's avatar
Libin Lu committed
22 23
@implementation RCTConvert (NSCalendarUnit)

Libin Lu's avatar
Libin Lu committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
RCT_ENUM_CONVERTER(NSCalendarUnit,
                   (@{
                      @"year": @(NSCalendarUnitYear),
                      @"month": @(NSCalendarUnitMonth),
                      @"week": @(NSCalendarUnitWeekOfYear),
                      @"day": @(NSCalendarUnitDay),
                      @"hour": @(NSCalendarUnitHour),
                      @"minute": @(NSCalendarUnitMinute)
                      }),
                   0,
                   integerValue)
@end


@implementation RCTConvert (UNNotificationRequest)

+ (UNNotificationRequest *)UNNotificationRequest:(id)json
Libin Lu's avatar
Libin Lu committed
41
{
Libin Lu's avatar
Libin Lu committed
42 43 44 45 46 47
    NSDictionary<NSString *, id> *details = [self NSDictionary:json];
    UNMutableNotificationContent *content = [UNMutableNotificationContent new];
    content.title =[RCTConvert NSString:details[@"title"]];
    content.body =[RCTConvert NSString:details[@"body"]];
    NSString* sound = [RCTConvert NSString:details[@"sound"]];
    if(sound != nil){
48 49 50 51 52
        if ([sound isEqual:@"default"]) {
            content.sound = [UNNotificationSound defaultSound];
        } else {
            content.sound = [UNNotificationSound soundNamed:sound];
        }
Libin Lu's avatar
Libin Lu committed
53
    }
Libin Lu's avatar
Libin Lu committed
54 55 56
    content.categoryIdentifier = [RCTConvert NSString:details[@"click_action"]];
    content.userInfo = details;
    content.badge = [RCTConvert NSNumber:details[@"badge"]];
Libin Lu's avatar
Libin Lu committed
57
    
Libin Lu's avatar
Libin Lu committed
58
    NSDate *fireDate = [RCTConvert NSDate:details[@"fire_date"]];
Libin Lu's avatar
Libin Lu committed
59
    
Libin Lu's avatar
Libin Lu committed
60 61
    if(fireDate == nil){
        return [UNNotificationRequest requestWithIdentifier:[RCTConvert NSString:details[@"id"]] content:content trigger:nil];
Libin Lu's avatar
Libin Lu committed
62
    }
Libin Lu's avatar
Libin Lu committed
63
    
Libin Lu's avatar
Libin Lu committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    NSCalendarUnit interval = [RCTConvert NSCalendarUnit:details[@"repeat_interval"]];
    NSCalendarUnit unitFlags;
    switch (interval) {
        case NSCalendarUnitMinute: {
            unitFlags = NSCalendarUnitSecond;
            break;
        }
        case NSCalendarUnitHour: {
            unitFlags = NSCalendarUnitMinute | NSCalendarUnitSecond;
            break;
        }
        case NSCalendarUnitDay: {
            unitFlags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
            break;
        }
        case NSCalendarUnitWeekOfYear: {
            unitFlags = NSCalendarUnitWeekday | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
            break;
        }
        case NSCalendarUnitMonth:{
            unitFlags = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
85
            break;
Libin Lu's avatar
Libin Lu committed
86 87 88
        }
        case NSCalendarUnitYear:{
            unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
89
            break;
Libin Lu's avatar
Libin Lu committed
90 91 92 93
        }
        default:
            unitFlags = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
            break;
Libin Lu's avatar
Libin Lu committed
94
    }
Libin Lu's avatar
Libin Lu committed
95 96 97
    NSDateComponents *components = [[NSCalendar currentCalendar] components:unitFlags fromDate:fireDate];
    UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:interval != 0];
    return [UNNotificationRequest requestWithIdentifier:[RCTConvert NSString:details[@"id"]] content:content trigger:trigger];
Libin Lu's avatar
Libin Lu committed
98 99 100 101 102 103 104 105
}

@end

@implementation RCTConvert (UILocalNotification)

+ (UILocalNotification *)UILocalNotification:(id)json
{
Libin Lu's avatar
Libin Lu committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119
    NSDictionary<NSString *, id> *details = [self NSDictionary:json];
    UILocalNotification *notification = [UILocalNotification new];
    notification.fireDate = [RCTConvert NSDate:details[@"fire_date"]] ?: [NSDate date];
    if([notification respondsToSelector:@selector(setAlertTitle:)]){
        [notification setAlertTitle:[RCTConvert NSString:details[@"title"]]];
    }
    notification.alertBody = [RCTConvert NSString:details[@"body"]];
    notification.alertAction = [RCTConvert NSString:details[@"alert_action"]];
    notification.soundName = [RCTConvert NSString:details[@"sound"]] ?: UILocalNotificationDefaultSoundName;
    notification.userInfo = details;
    notification.category = [RCTConvert NSString:details[@"click_action"]];
    notification.repeatInterval = [RCTConvert NSCalendarUnit:details[@"repeat_interval"]];
    notification.applicationIconBadgeNumber = [RCTConvert NSInteger:details[@"badge"]];
    return notification;
Libin Lu's avatar
Libin Lu committed
120
}
Libin Lu's avatar
Libin Lu committed
121 122 123 124 125 126 127 128

RCT_ENUM_CONVERTER(UIBackgroundFetchResult, (@{
                                               @"UIBackgroundFetchResultNewData": @(UIBackgroundFetchResultNewData),
                                               @"UIBackgroundFetchResultNoData": @(UIBackgroundFetchResultNoData),
                                               @"UIBackgroundFetchResultFailed": @(UIBackgroundFetchResultFailed),
                                               }), UIBackgroundFetchResultNoData, integerValue)

RCT_ENUM_CONVERTER(UNNotificationPresentationOptions, (@{
Libin Lu's avatar
Libin Lu committed
129 130
                                                         @"UNNotificationPresentationOptionAll": @(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound),
                                                         @"UNNotificationPresentationOptionNone": @(UNNotificationPresentationOptionNone)}), UIBackgroundFetchResultNoData, integerValue)
Libin Lu's avatar
Libin Lu committed
131 132 133

@end

134 135 136 137 138 139 140 141 142
@implementation RCTConvert (UNNotificationAction)

typedef NS_ENUM(NSUInteger, UNNotificationActionType) {
    UNNotificationActionTypeDefault,
    UNNotificationActionTypeTextInput
};

+ (UNNotificationAction *) UNNotificationAction:(id)json {
    NSDictionary<NSString *, id> *details = [self NSDictionary:json];
143
    
144 145 146 147
    NSString *identifier = [RCTConvert NSString: details[@"id"]];
    NSString *title = [RCTConvert NSString: details[@"title"]];
    UNNotificationActionOptions options = [RCTConvert UNNotificationActionOptions: details[@"options"]];
    UNNotificationActionType type = [RCTConvert UNNotificationActionType:details[@"type"]];
Libin Lu's avatar
Libin Lu committed
148
    
149 150 151
    if (type == UNNotificationActionTypeTextInput) {
        NSString *textInputButtonTitle = [RCTConvert NSString: details[@"textInputButtonTitle"]];
        NSString *textInputPlaceholder = [RCTConvert NSString: details[@"textInputPlaceholder"]];
Libin Lu's avatar
Libin Lu committed
152
        
153 154
        return [UNTextInputNotificationAction actionWithIdentifier:identifier title:title options:options textInputButtonTitle:textInputButtonTitle textInputPlaceholder:textInputPlaceholder];
    }
155
    
156 157 158
    return [UNNotificationAction actionWithIdentifier:identifier
                                                title:title
                                              options:options];
159
    
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
}

RCT_ENUM_CONVERTER(UNNotificationActionType, (@{
                                                @"UNNotificationActionTypeDefault": @(UNNotificationActionTypeDefault),
                                                @"UNNotificationActionTypeTextInput": @(UNNotificationActionTypeTextInput),
                                                }), UNNotificationActionTypeDefault, integerValue)


RCT_MULTI_ENUM_CONVERTER(UNNotificationActionOptions, (@{
                                                         @"UNNotificationActionOptionAuthenticationRequired": @(UNNotificationActionOptionAuthenticationRequired),
                                                         @"UNNotificationActionOptionDestructive": @(UNNotificationActionOptionDestructive),
                                                         @"UNNotificationActionOptionForeground": @(UNNotificationActionOptionForeground),
                                                         @"UNNotificationActionOptionNone": @(UNNotificationActionOptionNone),
                                                         }), UNNotificationActionOptionNone, integerValue)


@end

@implementation RCTConvert (UNNotificationCategory)


+ (UNNotificationCategory *) UNNotificationCategory:(id)json {
    NSDictionary<NSString *, id> *details = [self NSDictionary:json];
183
    
184
    NSString *identifier = [RCTConvert NSString: details[@"id"]];
185
    
186 187 188 189
    NSMutableArray *actions = [[NSMutableArray alloc] init];
    for (NSDictionary *actionDict in details[@"actions"]) {
        [actions addObject:[RCTConvert UNNotificationAction:actionDict]];
    }
Libin Lu's avatar
Libin Lu committed
190
    
191 192 193
    NSArray<NSString *> *intentIdentifiers = [RCTConvert NSStringArray:details[@"intentIdentifiers"]];
    NSString *hiddenPreviewsBodyPlaceholder = [RCTConvert NSString:details[@"hiddenPreviewsBodyPlaceholder"]];
    UNNotificationCategoryOptions options = [RCTConvert UNNotificationCategoryOptions: details[@"options"]];
Libin Lu's avatar
Libin Lu committed
194
    
195
    if (hiddenPreviewsBodyPlaceholder) {
196
#if defined(__IPHONE_11_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_11_0
Libin Lu's avatar
Libin Lu committed
197
        return [UNNotificationCategory categoryWithIdentifier:identifier actions:actions intentIdentifiers:intentIdentifiers hiddenPreviewsBodyPlaceholder:hiddenPreviewsBodyPlaceholder options:options];
198
#endif
199
    }
Libin Lu's avatar
Libin Lu committed
200
    
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    return [UNNotificationCategory categoryWithIdentifier:identifier actions:actions intentIdentifiers:intentIdentifiers options:options];
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"

RCT_MULTI_ENUM_CONVERTER(UNNotificationCategoryOptions, (@{
                                                           @"UNNotificationCategoryOptionNone": @(UNNotificationCategoryOptionNone),
                                                           @"UNNotificationCategoryOptionCustomDismissAction": @(UNNotificationCategoryOptionCustomDismissAction),
                                                           @"UNNotificationCategoryOptionAllowInCarPlay": @(UNNotificationCategoryOptionAllowInCarPlay),
                                                           @"UNNotificationCategoryOptionHiddenPreviewsShowTitle": @(UNNotificationCategoryOptionHiddenPreviewsShowTitle),
                                                           @"UNNotificationCategoryOptionHiddenPreviewsShowSubtitle": @(UNNotificationCategoryOptionHiddenPreviewsShowSubtitle),
                                                           }), UNNotificationCategoryOptionNone, integerValue)

#pragma clang diagnostic pop


@end

220 221 222 223
@interface RCTEventEmitter ()
- (void) addListener:(NSString *)eventName;
@end

Libin Lu's avatar
Libin Lu committed
224
@interface RNFIRMessaging ()
Libin Lu's avatar
Libin Lu committed
225
@property (nonatomic, strong) NSMutableDictionary *notificationCallbacks;
Libin Lu's avatar
Libin Lu committed
226
@end
Libin Lu's avatar
init  
Libin Lu committed
227

228
@implementation RNFIRMessaging
Libin Lu's avatar
init  
Libin Lu committed
229

230 231
static bool jsHandlerRegistered;
static NSMutableArray* pendingNotifications;
Libin Lu's avatar
Libin Lu committed
232
static NSString* refreshToken;
233

Libin Lu's avatar
Libin Lu committed
234
RCT_EXPORT_MODULE();
Libin Lu's avatar
init  
Libin Lu committed
235

Libin Lu's avatar
Libin Lu committed
236
- (NSArray<NSString *> *)supportedEvents {
Libin Lu's avatar
Libin Lu committed
237
    return @[FCMNotificationReceived, FCMTokenRefreshed, FCMDirectChannelConnectionChanged];
Libin Lu's avatar
Libin Lu committed
238 239
}

240
+ (BOOL)requiresMainQueueSetup {
241
    return YES;
242 243
}

Libin Lu's avatar
Libin Lu committed
244
+ (void)didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull RCTRemoteNotificationCallback)completionHandler {
Libin Lu's avatar
Libin Lu committed
245 246 247
    NSMutableDictionary* data = [[NSMutableDictionary alloc] initWithDictionary: userInfo];
    [data setValue:@"remote_notification" forKey:@"_notificationType"];
    [data setValue:@(RCTSharedApplication().applicationState == UIApplicationStateInactive) forKey:@"opened_from_tray"];
248
    [self sendNotificationEventWhenAvailable:@{@"data": data, @"completionHandler": completionHandler}];
Libin Lu's avatar
Libin Lu committed
249 250 251
}

+ (void)didReceiveLocalNotification:(UILocalNotification *)notification {
Libin Lu's avatar
Libin Lu committed
252 253
    NSMutableDictionary* data = [[NSMutableDictionary alloc] initWithDictionary: notification.userInfo];
    [data setValue:@"local_notification" forKey:@"_notificationType"];
254
    [data setValue:@(RCTSharedApplication().applicationState == UIApplicationStateInactive) forKey:@"opened_from_tray"];
255
    [self sendNotificationEventWhenAvailable:@{@"data": data}];
Libin Lu's avatar
Libin Lu committed
256 257
}

Libin Lu's avatar
Libin Lu committed
258
+ (void)didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(nonnull RCTNotificationResponseCallback)completionHandler
Libin Lu's avatar
Libin Lu committed
259
{
Libin Lu's avatar
Libin Lu committed
260 261 262 263 264 265
    NSMutableDictionary* data = [[NSMutableDictionary alloc] initWithDictionary: response.notification.request.content.userInfo];
    [data setValue:@"notification_response" forKey:@"_notificationType"];
    [data setValue:@YES forKey:@"opened_from_tray"];
    if (response.actionIdentifier) {
        [data setValue:response.actionIdentifier forKey:@"_actionIdentifier"];
    }
Libin Lu's avatar
Libin Lu committed
266
    
267 268 269
    if ([response isKindOfClass:UNTextInputNotificationResponse.class]) {
        [data setValue:[(UNTextInputNotificationResponse *)response userText] forKey:@"_userText"];
    }
270
    
271
    NSDictionary *userInfo = @{@"data": data, @"completionHandler": completionHandler};
272
    [self sendNotificationEventWhenAvailable:userInfo];
Libin Lu's avatar
Libin Lu committed
273
    
Libin Lu's avatar
Libin Lu committed
274 275
}

Libin Lu's avatar
Libin Lu committed
276
+ (void)willPresentNotification:(UNNotification *)notification withCompletionHandler:(nonnull RCTWillPresentNotificationCallback)completionHandler
Libin Lu's avatar
Libin Lu committed
277
{
Libin Lu's avatar
Libin Lu committed
278 279
    NSMutableDictionary* data = [[NSMutableDictionary alloc] initWithDictionary: notification.request.content.userInfo];
    [data setValue:@"will_present_notification" forKey:@"_notificationType"];
280 281 282 283 284
    [self sendNotificationEventWhenAvailable:@{@"data": data, @"completionHandler": completionHandler}];
}

+ (void)sendNotificationEventWhenAvailable:(NSDictionary*)data
{
Libin Lu's avatar
Libin Lu committed
285 286 287 288 289 290 291 292
    if(!jsHandlerRegistered){
        // JS hasn't registered callback yet. hold on that
        if(!pendingNotifications){
            pendingNotifications = [NSMutableArray array];
        }
        [pendingNotifications addObject:data];
    } else {
        [[NSNotificationCenter defaultCenter] postNotificationName:FCMNotificationReceived object:self userInfo:data];
293
    }
Libin Lu's avatar
Libin Lu committed
294 295
}

Libin Lu's avatar
init  
Libin Lu committed
296 297
- (void)dealloc
{
Libin Lu's avatar
Libin Lu committed
298
    [[NSNotificationCenter defaultCenter] removeObserver:self];
Libin Lu's avatar
init  
Libin Lu committed
299 300
}

Libin Lu's avatar
Libin Lu committed
301
- (instancetype)init {
Libin Lu's avatar
Libin Lu committed
302
    self = [super init];
Libin Lu's avatar
Libin Lu committed
303
    
Libin Lu's avatar
Libin Lu committed
304
    [[NSNotificationCenter defaultCenter] addObserver:self
Libin Lu's avatar
Libin Lu committed
305 306 307 308
                                             selector:@selector(handleNotificationReceived:)
                                                 name:FCMNotificationReceived
                                               object:nil];
    
Libin Lu's avatar
Libin Lu committed
309 310 311
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(sendDataMessageFailure:)
     name:FIRMessagingSendErrorNotification object:nil];
Libin Lu's avatar
Libin Lu committed
312
    
Libin Lu's avatar
Libin Lu committed
313 314 315
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(sendDataMessageSuccess:)
     name:FIRMessagingSendSuccessNotification object:nil];
Libin Lu's avatar
Libin Lu committed
316
    
Libin Lu's avatar
Libin Lu committed
317 318 319
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(connectionStateChanged:)
     name:FIRMessagingConnectionStateChangedNotification object:nil];
Libin Lu's avatar
Libin Lu committed
320
    
Libin Lu's avatar
Libin Lu committed
321 322 323 324
    // For iOS 10 data message (sent via FCM)
    dispatch_async(dispatch_get_main_queue(), ^{
        [[FIRMessaging messaging] setDelegate:self];
    });
Libin Lu's avatar
Libin Lu committed
325 326 327 328 329 330 331 332 333 334
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(!jsHandlerRegistered){
            [self sendPendingNotifications];
        }
        if(refreshToken != nil){
            [self sendEventWithName:FCMTokenRefreshed body:refreshToken];
        }
    });
    
Libin Lu's avatar
Libin Lu committed
335
    return self;
Libin Lu's avatar
init  
Libin Lu committed
336 337
}

338
-(void) addListener:(NSString *)eventName {
Libin Lu's avatar
Libin Lu committed
339 340 341 342 343 344 345 346
    [super addListener:eventName];
    
    if([eventName isEqualToString:FCMNotificationReceived]) {
        [self sendPendingNotifications];
    } else if([eventName isEqualToString:FCMTokenRefreshed] && refreshToken != nil) {
        [self sendEventWithName:FCMTokenRefreshed body:refreshToken];
        refreshToken = nil;
    }
347 348
}

349
-(void) sendPendingNotifications {
Libin Lu's avatar
Libin Lu committed
350 351 352 353 354 355 356 357 358 359 360
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        jsHandlerRegistered = true;
        
        for (NSDictionary* data in pendingNotifications) {
            [[NSNotificationCenter defaultCenter] postNotificationName:FCMNotificationReceived object:self userInfo:data];
        }
        
        [pendingNotifications removeAllObjects];
        
    });
361 362
}

Libin Lu's avatar
Libin Lu committed
363
RCT_EXPORT_METHOD(enableDirectChannel)
Libin Lu's avatar
init  
Libin Lu committed
364
{
Libin Lu's avatar
Libin Lu committed
365
    [[FIRMessaging messaging] setShouldEstablishDirectChannel:@YES];
Libin Lu's avatar
init  
Libin Lu committed
366 367
}

Libin Lu's avatar
Libin Lu committed
368
RCT_EXPORT_METHOD(isDirectChannelEstablished:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
init  
Libin Lu committed
369
{
Libin Lu's avatar
Libin Lu committed
370
    resolve([[FIRMessaging messaging] isDirectChannelEstablished] ? @YES: @NO);
Libin Lu's avatar
init  
Libin Lu committed
371 372
}

Libin Lu's avatar
Libin Lu committed
373
RCT_EXPORT_METHOD(getInitialNotification:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
Libin Lu committed
374
{
Libin Lu's avatar
Libin Lu committed
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
    NSDictionary* initialNotif;
    NSDictionary *localUserInfo = [[self.bridge.launchOptions[UIApplicationLaunchOptionsLocalNotificationKey] userInfo] mutableCopy];
    
    NSDictionary *remoteUserInfo = [self.bridge.launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] mutableCopy];
    if(localUserInfo){
        initialNotif = localUserInfo;
    } else if (remoteUserInfo) {
        initialNotif = remoteUserInfo;
    }
    if (initialNotif) {
        [initialNotif setValue:@YES forKey:@"opened_from_tray"];
        resolve(initialNotif);
    } else {
        resolve(nil);
    }
Libin Lu's avatar
Libin Lu committed
390 391
}

392 393


Libin Lu's avatar
Libin Lu committed
394
RCT_EXPORT_METHOD(getAPNSToken:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
init  
Libin Lu committed
395
{
396 397 398 399 400 401 402
    NSData * deviceToken = [FIRMessaging messaging].APNSToken;
    const char *data = [deviceToken bytes];
    NSMutableString *token = [NSMutableString string];
    for (NSUInteger i = 0; i < [deviceToken length]; i++) {
        [token appendFormat:@"%02.2hhX", data[i]];
    }
    resolve([token copy]);
Libin Lu's avatar
init  
Libin Lu committed
403 404
}

Libin Lu's avatar
Libin Lu committed
405
RCT_EXPORT_METHOD(getFCMToken:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
init  
Libin Lu committed
406
{
Libin Lu's avatar
Libin Lu committed
407
    resolve([FIRMessaging messaging].FCMToken);
Libin Lu's avatar
Libin Lu committed
408 409
}

Libin Lu's avatar
Libin Lu committed
410 411 412 413 414
RCT_EXPORT_METHOD(getEntityFCMToken:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
    FIROptions *options = FIROptions.defaultOptions;
    NSString *entity = options.GCMSenderID;
    NSData * deviceToken = [FIRMessaging messaging].APNSToken;
Libin Lu's avatar
Libin Lu committed
415
    
416 417
    if (deviceToken == nil) {
        resolve(nil);
418
        return;
419
    }
Libin Lu's avatar
Libin Lu committed
420
    
Libin Lu's avatar
Libin Lu committed
421
    [[FIRInstanceID instanceID]tokenWithAuthorizedEntity:entity scope:kFIRInstanceIDScopeFirebaseMessaging options:@{@"apns_token": deviceToken} handler:^(NSString * _Nullable token, NSError * _Nullable error) {
Libin Lu's avatar
Libin Lu committed
422
        
Libin Lu's avatar
Libin Lu committed
423 424 425 426 427 428 429 430 431 432 433 434
        if (error != nil) {
            reject([NSString stringWithFormat:@"%ld",error.code],error.localizedDescription,nil);
        } else {
            resolve(token);
        }
    }];
}

RCT_EXPORT_METHOD(deleteEntityFCMToken:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
    FIROptions *options = FIROptions.defaultOptions;;
    NSString *entity = options.GCMSenderID;
Libin Lu's avatar
Libin Lu committed
435
    
Libin Lu's avatar
Libin Lu committed
436
    [[FIRInstanceID instanceID]deleteTokenWithAuthorizedEntity:entity scope:kFIRInstanceIDScopeFirebaseMessaging handler:^(NSError * _Nullable error) {
Libin Lu's avatar
Libin Lu committed
437
        
Libin Lu's avatar
Libin Lu committed
438 439 440 441 442 443 444 445
        if (error != nil) {
            reject([NSString stringWithFormat:@"%ld",error.code],error.localizedDescription,nil);
        } else {
            resolve(nil);
        }
    }];
}

446 447
RCT_EXPORT_METHOD(deleteInstanceId:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
Libin Lu's avatar
Libin Lu committed
448 449 450 451 452 453 454 455
    [[FIRInstanceID instanceID]deleteIDWithHandler:^(NSError * _Nullable error) {
        
        if (error != nil) {
            reject([NSString stringWithFormat:@"%ld",error.code],error.localizedDescription,nil);
        } else {
            resolve(nil);
        }
    }];
456 457
}

Libin Lu's avatar
Libin Lu committed
458 459 460
- (void)messaging:(nonnull FIRMessaging *)messaging didReceiveRegistrationToken:(nonnull NSString *)fcmToken {
  refreshToken = fcmToken;
  [self sendEventWithName:FCMTokenRefreshed body:fcmToken];
Libin Lu's avatar
init  
Libin Lu committed
461 462
}

463 464 465 466 467
- (void)messaging:(nonnull FIRMessaging *)messaging didRefreshRegistrationToken:(nonnull NSString *)fcmToken {
  refreshToken = fcmToken;
  [self sendEventWithName:FCMTokenRefreshed body:fcmToken];
}

Libin Lu's avatar
Libin Lu committed
468
RCT_EXPORT_METHOD(requestPermissions:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
init  
Libin Lu committed
469
{
Libin Lu's avatar
Libin Lu committed
470
    if (RCTRunningInAppExtension()) {
Libin Lu's avatar
Libin Lu committed
471
        resolve(nil);
Libin Lu's avatar
Libin Lu committed
472
        return;
Libin Lu's avatar
Libin Lu committed
473
    }
Libin Lu's avatar
Libin Lu committed
474 475 476 477 478 479 480 481 482 483
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
        UIUserNotificationType allNotificationTypes =
        (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
        UIApplication *app = RCTSharedApplication();
        if ([app respondsToSelector:@selector(registerUserNotificationSettings:)]) {
            //iOS 8 or later
            UIUserNotificationSettings *notificationSettings =
            [UIUserNotificationSettings settingsForTypes:(NSUInteger)allNotificationTypes categories:nil];
            [app registerUserNotificationSettings:notificationSettings];
        }
Libin Lu's avatar
Libin Lu committed
484
        resolve(nil);
Libin Lu's avatar
Libin Lu committed
485 486
    } else {
        // iOS 10 or later
Libin Lu's avatar
Libin Lu committed
487
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
Libin Lu's avatar
Libin Lu committed
488 489 490 491 492 493 494 495 496 497
        UNAuthorizationOptions authOptions =
        UNAuthorizationOptionAlert
        | UNAuthorizationOptionSound
        | UNAuthorizationOptionBadge;
        [[UNUserNotificationCenter currentNotificationCenter]
         requestAuthorizationWithOptions:authOptions
         completionHandler:^(BOOL granted, NSError * _Nullable error) {
             if(granted){
                 resolve(nil);
             } else{
498
                 reject(@"notification_error", @"Failed to grant permission", error);
Libin Lu's avatar
Libin Lu committed
499 500 501
             }
         }
         ];
Libin Lu's avatar
Libin Lu committed
502
#endif
Libin Lu's avatar
Libin Lu committed
503
    }
Libin Lu's avatar
Libin Lu committed
504
    
505 506 507
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    });
Libin Lu's avatar
Libin Lu committed
508 509
}

510 511
RCT_EXPORT_METHOD(subscribeToTopic: (NSString*) topic)
{
Libin Lu's avatar
Libin Lu committed
512
    [[FIRMessaging messaging] subscribeToTopic:topic];
513 514 515 516
}

RCT_EXPORT_METHOD(unsubscribeFromTopic: (NSString*) topic)
{
Libin Lu's avatar
Libin Lu committed
517
    [[FIRMessaging messaging] unsubscribeFromTopic:topic];
518 519
}

Libin Lu's avatar
Libin Lu committed
520 521 522 523
- (void)messaging:(FIRMessaging *)messaging didReceiveMessage:(FIRMessagingRemoteMessage *)remoteMessage {
    [self sendEventWithName:FCMNotificationReceived body:[remoteMessage appData]];
}

Libin Lu's avatar
Libin Lu committed
524
RCT_EXPORT_METHOD(presentLocalNotification:(id)data resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
Libin Lu committed
525
{
Libin Lu's avatar
Libin Lu committed
526 527 528 529 530 531 532 533 534 535 536 537
    if([UNUserNotificationCenter currentNotificationCenter] != nil){
        UNNotificationRequest* request = [RCTConvert UNNotificationRequest:data];
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            if (!error) {
                resolve(nil);
            }else{
                reject(@"notification_error", @"Failed to present local notificaton", error);
            }
        }];
    }else{
        UILocalNotification* notif = [RCTConvert UILocalNotification:data];
        [RCTSharedApplication() presentLocalNotificationNow:notif];
Libin Lu's avatar
Libin Lu committed
538
        resolve(nil);
Libin Lu's avatar
Libin Lu committed
539
    }
Libin Lu's avatar
Libin Lu committed
540 541
}

Libin Lu's avatar
Libin Lu committed
542
RCT_EXPORT_METHOD(scheduleLocalNotification:(id)data resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
Libin Lu committed
543
{
Libin Lu's avatar
Libin Lu committed
544 545 546 547 548 549 550 551 552 553 554 555
    if([UNUserNotificationCenter currentNotificationCenter] != nil){
        UNNotificationRequest* request = [RCTConvert UNNotificationRequest:data];
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            if (!error) {
                resolve(nil);
            }else{
                reject(@"notification_error", @"Failed to present local notificaton", error);
            }
        }];
    }else{
        UILocalNotification* notif = [RCTConvert UILocalNotification:data];
        [RCTSharedApplication() scheduleLocalNotification:notif];
Libin Lu's avatar
Libin Lu committed
556
        resolve(nil);
Libin Lu's avatar
Libin Lu committed
557
    }
Libin Lu's avatar
Libin Lu committed
558 559
}

Libin Lu's avatar
Libin Lu committed
560
RCT_EXPORT_METHOD(removeDeliveredNotification:(NSString*) notificationId)
Libin Lu's avatar
Libin Lu committed
561
{
Libin Lu's avatar
Libin Lu committed
562 563 564
    if([UNUserNotificationCenter currentNotificationCenter] != nil){
        [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[notificationId]];
    }
Libin Lu's avatar
Libin Lu committed
565 566 567 568
}

RCT_EXPORT_METHOD(removeAllDeliveredNotifications)
{
Libin Lu's avatar
Libin Lu committed
569 570 571
    if([UNUserNotificationCenter currentNotificationCenter] != nil){
        [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
    } else {
572 573 574
        dispatch_async(dispatch_get_main_queue(), ^{
            [RCTSharedApplication() setApplicationIconBadgeNumber: 0];
        });
Libin Lu's avatar
Libin Lu committed
575
    }
Libin Lu's avatar
Libin Lu committed
576 577
}

Libin Lu's avatar
Libin Lu committed
578 579
RCT_EXPORT_METHOD(cancelAllLocalNotifications)
{
Libin Lu's avatar
Libin Lu committed
580 581 582 583 584
    if([UNUserNotificationCenter currentNotificationCenter] != nil){
        [[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests];
    } else {
        [RCTSharedApplication() cancelAllLocalNotifications];
    }
Libin Lu's avatar
Libin Lu committed
585 586 587 588
}

RCT_EXPORT_METHOD(cancelLocalNotification:(NSString*) notificationId)
{
Libin Lu's avatar
Libin Lu committed
589 590 591 592 593 594 595 596 597
    if([UNUserNotificationCenter currentNotificationCenter] != nil){
        [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[notificationId]];
    }else {
        for (UILocalNotification *notification in [UIApplication sharedApplication].scheduledLocalNotifications) {
            NSDictionary<NSString *, id> *notificationInfo = notification.userInfo;
            if([notificationId isEqualToString:[notificationInfo valueForKey:@"id"]]){
                [[UIApplication sharedApplication] cancelLocalNotification:notification];
            }
        }
Libin Lu's avatar
Libin Lu committed
598 599 600
    }
}

Libin Lu's avatar
Libin Lu committed
601
RCT_EXPORT_METHOD(getScheduledLocalNotifications:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
Libin Lu committed
602
{
Libin Lu's avatar
Libin Lu committed
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
    if([UNUserNotificationCenter currentNotificationCenter] != nil){
        [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
            NSMutableArray* list = [[NSMutableArray alloc] init];
            for(UNNotificationRequest * notif in requests){
                UNNotificationContent *content = notif.content;
                [list addObject:content.userInfo];
            }
            resolve(list);
        }];
    }else{
        NSMutableArray* list = [[NSMutableArray alloc] init];
        for(UILocalNotification * notif in [RCTSharedApplication() scheduledLocalNotifications]){
            [list addObject:notif.userInfo];
        }
        resolve(list);
Libin Lu's avatar
Libin Lu committed
618 619 620
    }
}

621 622 623 624
RCT_EXPORT_METHOD(setNotificationCategories:(NSArray *)categories)
{
    if([UNUserNotificationCenter currentNotificationCenter] != nil) {
        NSMutableSet *categoriesSet = [[NSMutableSet alloc] init];
Libin Lu's avatar
Libin Lu committed
625
        
626 627 628 629
        for(NSDictionary *categoryDict in categories) {
            UNNotificationCategory *category = [RCTConvert UNNotificationCategory:categoryDict];
            [categoriesSet addObject:category];
        }
Libin Lu's avatar
Libin Lu committed
630
        
631 632 633 634
        [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:categoriesSet];
    }
}

Libin Lu's avatar
Libin Lu committed
635
RCT_EXPORT_METHOD(setBadgeNumber: (NSInteger) number)
Libin Lu's avatar
Libin Lu committed
636
{
637 638 639
    dispatch_async(dispatch_get_main_queue(), ^{
        [RCTSharedApplication() setApplicationIconBadgeNumber:number];
    });
Libin Lu's avatar
Libin Lu committed
640 641
}

Libin Lu's avatar
Libin Lu committed
642
RCT_EXPORT_METHOD(getBadgeNumber: (RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
Libin Lu committed
643
{
Libin Lu's avatar
Libin Lu committed
644
    resolve(@([RCTSharedApplication() applicationIconBadgeNumber]));
Libin Lu's avatar
Libin Lu committed
645 646
}

647 648
RCT_EXPORT_METHOD(send:(NSString*)senderId withPayload:(NSDictionary *)message)
{
Libin Lu's avatar
Libin Lu committed
649 650 651 652 653
    NSMutableDictionary * mMessage = [message mutableCopy];
    NSMutableDictionary * upstreamMessage = [[NSMutableDictionary alloc] init];
    for (NSString* key in mMessage) {
        upstreamMessage[key] = [NSString stringWithFormat:@"%@", [mMessage valueForKey:key]];
    }
Libin Lu's avatar
Libin Lu committed
654
    
Libin Lu's avatar
Libin Lu committed
655
    NSDictionary *imMessage = [NSDictionary dictionaryWithDictionary:upstreamMessage];
Libin Lu's avatar
Libin Lu committed
656
    
Libin Lu's avatar
Libin Lu committed
657 658
    int64_t ttl = 3600;
    NSString * receiver = [NSString stringWithFormat:@"%@@gcm.googleapis.com", senderId];
Libin Lu's avatar
Libin Lu committed
659
    
Libin Lu's avatar
Libin Lu committed
660 661
    NSUUID *uuid = [NSUUID UUID];
    NSString * messageID = [uuid UUIDString];
Libin Lu's avatar
Libin Lu committed
662
    
Libin Lu's avatar
Libin Lu committed
663
    [[FIRMessaging messaging]sendMessage:imMessage to:receiver withMessageID:messageID timeToLive:ttl];
664 665
}

Libin Lu's avatar
Libin Lu committed
666
RCT_EXPORT_METHOD(finishRemoteNotification: (NSString *)completionHandlerId fetchResult:(UIBackgroundFetchResult)result){
Libin Lu's avatar
Libin Lu committed
667 668 669 670 671 672 673
    RCTRemoteNotificationCallback completionHandler = self.notificationCallbacks[completionHandlerId];
    if (!completionHandler) {
        RCTLogError(@"There is no completion handler with completionHandlerId: %@", completionHandlerId);
        return;
    }
    completionHandler(result);
    [self.notificationCallbacks removeObjectForKey:completionHandlerId];
Libin Lu's avatar
Libin Lu committed
674 675 676
}

RCT_EXPORT_METHOD(finishWillPresentNotification: (NSString *)completionHandlerId fetchResult:(UNNotificationPresentationOptions)result){
Libin Lu's avatar
Libin Lu committed
677 678 679 680 681 682 683
    RCTWillPresentNotificationCallback completionHandler = self.notificationCallbacks[completionHandlerId];
    if (!completionHandler) {
        RCTLogError(@"There is no completion handler with completionHandlerId: %@", completionHandlerId);
        return;
    }
    completionHandler(result);
    [self.notificationCallbacks removeObjectForKey:completionHandlerId];
Libin Lu's avatar
Libin Lu committed
684 685 686
}

RCT_EXPORT_METHOD(finishNotificationResponse: (NSString *)completionHandlerId){
Libin Lu's avatar
Libin Lu committed
687 688 689 690 691 692 693
    RCTNotificationResponseCallback completionHandler = self.notificationCallbacks[completionHandlerId];
    if (!completionHandler) {
        RCTLogError(@"There is no completion handler with completionHandlerId: %@", completionHandlerId);
        return;
    }
    completionHandler();
    [self.notificationCallbacks removeObjectForKey:completionHandlerId];
Libin Lu's avatar
Libin Lu committed
694 695
}

Libin Lu's avatar
Libin Lu committed
696
- (void)handleNotificationReceived:(NSNotification *)notification
Libin Lu's avatar
init  
Libin Lu committed
697
{
Libin Lu's avatar
Libin Lu committed
698 699 700 701 702 703 704 705 706 707
    id completionHandler = notification.userInfo[@"completionHandler"];
    NSMutableDictionary* data = notification.userInfo[@"data"];
    if(completionHandler != nil){
        NSString *completionHandlerId = [[NSUUID UUID] UUIDString];
        if (!self.notificationCallbacks) {
            // Lazy initialization
            self.notificationCallbacks = [NSMutableDictionary dictionary];
        }
        self.notificationCallbacks[completionHandlerId] = completionHandler;
        data[@"_completionHandlerId"] = completionHandlerId;
Libin Lu's avatar
Libin Lu committed
708
    }
Libin Lu's avatar
Libin Lu committed
709
    [self sendEventWithName:FCMNotificationReceived body:data];
Libin Lu's avatar
init  
Libin Lu committed
710 711
}

Libin Lu's avatar
Libin Lu committed
712
- (void)sendDataMessageFailure:(NSNotification *)notification
713
{
Libin Lu's avatar
Libin Lu committed
714
    NSString *messageID = (NSString *)notification.userInfo[@"messageID"];
Libin Lu's avatar
Libin Lu committed
715
    
Libin Lu's avatar
Libin Lu committed
716
    NSLog(@"sendDataMessageFailure: %@", messageID);
717 718
}

Libin Lu's avatar
Libin Lu committed
719
- (void)sendDataMessageSuccess:(NSNotification *)notification
720
{
Libin Lu's avatar
Libin Lu committed
721
    NSString *messageID = (NSString *)notification.userInfo[@"messageID"];
Libin Lu's avatar
Libin Lu committed
722
    
Libin Lu's avatar
Libin Lu committed
723
    NSLog(@"sendDataMessageSuccess: %@", messageID);
724 725
}

Libin Lu's avatar
Libin Lu committed
726 727
- (void)connectionStateChanged:(NSNotification *)notification
{
Libin Lu's avatar
Libin Lu committed
728 729
    [self sendEventWithName:FCMDirectChannelConnectionChanged body:[FIRMessaging messaging].isDirectChannelEstablished ? @YES: @NO];
    NSLog(@"connectionStateChanged: %@", [FIRMessaging messaging].isDirectChannelEstablished ? @"connected": @"disconnected");
Libin Lu's avatar
Libin Lu committed
730 731
}

Libin Lu's avatar
init  
Libin Lu committed
732
@end