1// Copyright 2018-present 650 Industries. All rights reserved.
2
3#import "EXScopedNotificationPresentationModule.h"
4#import "EXScopedNotificationsUtils.h"
5
6#import <EXNotifications/EXNotificationSerializer.h>
7
8@interface EXScopedNotificationPresentationModule ()
9
10@property (nonatomic, strong) NSString *experienceId;
11
12@end
13
14@implementation EXScopedNotificationPresentationModule
15
16- (instancetype)initWithExperienceId:(NSString *)experienceId
17{
18  if (self = [super init]) {
19    _experienceId = experienceId;
20  }
21
22  return self;
23}
24
25- (NSArray * _Nonnull)serializeNotifications:(NSArray<UNNotification *> * _Nonnull)notifications
26{
27  NSMutableArray *serializedNotifications = [NSMutableArray new];
28  for (UNNotification *notification in notifications) {
29    if ([EXScopedNotificationsUtils shouldNotification:notification beHandledByExperience:_experienceId]) {
30      [serializedNotifications addObject:[EXNotificationSerializer serializedNotification:notification]];
31    }
32  }
33  return serializedNotifications;
34}
35
36- (void)dismissNotificationWithIdentifier:(NSString *)identifier resolve:(UMPromiseResolveBlock)resolve reject:(UMPromiseRejectBlock)reject
37{
38  __block NSString *experienceId = _experienceId;
39  [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
40    for (UNNotification *notification in notifications) {
41      if ([notification.request.identifier isEqual:identifier]) {
42        if ([EXScopedNotificationsUtils shouldNotification:notification beHandledByExperience:experienceId]) {
43          [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[identifier]];
44        }
45        break;
46      }
47    }
48    resolve(nil);
49  }];
50}
51
52- (void)dismissAllNotificationsWithResolver:(UMPromiseResolveBlock)resolve reject:(UMPromiseRejectBlock)reject
53{
54  __block NSString *experienceId = _experienceId;
55  [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
56    NSMutableArray<NSString *> *toDismiss = [NSMutableArray new];
57    for (UNNotification *notification in notifications) {
58      if ([EXScopedNotificationsUtils shouldNotification:notification beHandledByExperience:experienceId]) {
59        [toDismiss addObject:notification.request.identifier];
60      }
61    }
62    [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:toDismiss];
63    resolve(nil);
64  }];
65}
66
67@end
68