Proyectos de Subversion Iphone Microlearning

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
/*
2
 * Copyright 2017 Google
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
 
17
#import <TargetConditionals.h>
18
#if TARGET_OS_IOS || TARGET_OS_TV
19
 
20
#import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
21
 
22
#import "FirebaseInAppMessaging/Sources/FIRCore+InAppMessaging.h"
23
#import "FirebaseInAppMessaging/Sources/Private/Data/FIRIAMFetchResponseParser.h"
24
#import "FirebaseInAppMessaging/Sources/Private/DisplayTrigger/FIRIAMDisplayTriggerDefinition.h"
25
#import "FirebaseInAppMessaging/Sources/Private/Flows/FIRIAMDisplayCheckOnAnalyticEventsFlow.h"
26
#import "FirebaseInAppMessaging/Sources/Private/Flows/FIRIAMMessageClientCache.h"
27
#import "FirebaseInAppMessaging/Sources/Private/Flows/FIRIAMServerMsgFetchStorage.h"
28
 
29
@interface FIRIAMMessageClientCache ()
30
 
31
// messages not for client-side testing
32
@property(nonatomic) NSMutableArray<FIRIAMMessageDefinition *> *regularMessages;
33
// messages for client-side testing
34
@property(nonatomic) NSMutableArray<FIRIAMMessageDefinition *> *testMessages;
35
@property(nonatomic, weak) id<FIRIAMCacheDataObserver> observer;
36
@property(nonatomic) NSMutableSet<NSString *> *firebaseAnalyticEventsToWatch;
37
@property(nonatomic) id<FIRIAMBookKeeper> bookKeeper;
38
@property(readonly, nonatomic) FIRIAMFetchResponseParser *responseParser;
39
 
40
@end
41
 
42
// Methods doing read and write operations on messages field is synchronized to avoid
43
// race conditions like change the array while iterating through it
44
@implementation FIRIAMMessageClientCache
45
- (instancetype)initWithBookkeeper:(id<FIRIAMBookKeeper>)bookKeeper
46
               usingResponseParser:(FIRIAMFetchResponseParser *)responseParser {
47
  if (self = [super init]) {
48
    _bookKeeper = bookKeeper;
49
    _responseParser = responseParser;
50
  }
51
  return self;
52
}
53
 
54
- (void)setDataObserver:(id<FIRIAMCacheDataObserver>)observer {
55
  self.observer = observer;
56
}
57
 
58
// reset messages data
59
- (void)setMessageData:(NSArray<FIRIAMMessageDefinition *> *)messages {
60
  @synchronized(self) {
61
    NSSet<NSString *> *impressionSet =
62
        [NSSet setWithArray:[self.bookKeeper getMessageIDsFromImpressions]];
63
 
64
    NSMutableArray<FIRIAMMessageDefinition *> *regularMessages = [[NSMutableArray alloc] init];
65
    self.testMessages = [[NSMutableArray alloc] init];
66
 
67
    // split between test vs non-test messages
68
    for (FIRIAMMessageDefinition *next in messages) {
69
      if (next.isTestMessage) {
70
        [self.testMessages addObject:next];
71
      } else {
72
        [regularMessages addObject:next];
73
      }
74
    }
75
 
76
    // while resetting the whole message set, we do prefiltering based on the impressions
77
    // data to get rid of messages we don't care so that the future searches are more efficient
78
    NSPredicate *notImpressedPredicate =
79
        [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
80
          FIRIAMMessageDefinition *message = (FIRIAMMessageDefinition *)evaluatedObject;
81
          return ![impressionSet containsObject:message.renderData.messageID];
82
        }];
83
 
84
    self.regularMessages =
85
        [[regularMessages filteredArrayUsingPredicate:notImpressedPredicate] mutableCopy];
86
    [self setupAnalyticsEventListening];
87
  }
88
 
89
  FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM160001",
90
              @"There are %lu test messages and %lu regular messages and "
91
               "%lu Firebase Analytics events to watch after "
92
               "resetting the message cache",
93
              (unsigned long)self.testMessages.count, (unsigned long)self.regularMessages.count,
94
              (unsigned long)self.firebaseAnalyticEventsToWatch.count);
95
  [self.observer dataChanged];
96
}
97
 
98
// triggered after self.messages are updated so that we can correctly enable/disable listening
99
// on analytics event based on current fiam message set
100
- (void)setupAnalyticsEventListening {
101
  self.firebaseAnalyticEventsToWatch = [[NSMutableSet alloc] init];
102
  for (FIRIAMMessageDefinition *nextMessage in self.regularMessages) {
103
    // if it's event based triggering, add it to the watch set
104
    for (FIRIAMDisplayTriggerDefinition *nextTrigger in nextMessage.renderTriggers) {
105
      if (nextTrigger.triggerType == FIRIAMRenderTriggerOnFirebaseAnalyticsEvent) {
106
        [self.firebaseAnalyticEventsToWatch addObject:nextTrigger.firebaseEventName];
107
      }
108
    }
109
  }
110
 
111
  if (self.analycisEventDislayCheckFlow) {
112
    if ([self.firebaseAnalyticEventsToWatch count] > 0) {
113
      FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM160010",
114
                  @"There are analytics event trigger based messages, enable listening");
115
      [self.analycisEventDislayCheckFlow start];
116
    } else {
117
      FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM160011",
118
                  @"No analytics event trigger based messages, disable listening");
119
      [self.analycisEventDislayCheckFlow stop];
120
    }
121
  }
122
}
123
 
124
- (NSArray<FIRIAMMessageDefinition *> *)allRegularMessages {
125
  return [self.regularMessages copy];
126
}
127
 
128
- (BOOL)hasTestMessage {
129
  return self.testMessages.count > 0;
130
}
131
 
132
- (nullable FIRIAMMessageDefinition *)nextOnAppLaunchDisplayMsg {
133
  return [self nextMessageForTrigger:FIRIAMRenderTriggerOnAppLaunch];
134
}
135
 
136
- (nullable FIRIAMMessageDefinition *)nextOnAppOpenDisplayMsg {
137
  @synchronized(self) {
138
    // always first check test message which always have higher prirority
139
    if (self.testMessages.count > 0) {
140
      FIRIAMMessageDefinition *testMessage = self.testMessages[0];
141
      // always remove test message right away when being fetched for display
142
      [self.testMessages removeObjectAtIndex:0];
143
      FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM160007",
144
                  @"Returning a test message for app foreground display");
145
      return testMessage;
146
    }
147
  }
148
 
149
  // otherwise check for a message from a published campaign
150
  return [self nextMessageForTrigger:FIRIAMRenderTriggerOnAppForeground];
151
}
152
 
153
- (nullable FIRIAMMessageDefinition *)nextMessageForTrigger:(FIRIAMRenderTrigger)trigger {
154
  // search from the start to end in the list (which implies the display priority) for the
155
  // first match (some messages in the cache may not be eligible for the current display
156
  // message fetch
157
  NSSet<NSString *> *impressionSet =
158
      [NSSet setWithArray:[self.bookKeeper getMessageIDsFromImpressions]];
159
 
160
  @synchronized(self) {
161
    for (FIRIAMMessageDefinition *next in self.regularMessages) {
162
      // message being active and message not impressed yet
163
      if ([next messageHasStarted] && ![next messageHasExpired] &&
164
          ![impressionSet containsObject:next.renderData.messageID] &&
165
          [next messageRenderedOnTrigger:trigger]) {
166
        return next;
167
      }
168
    }
169
  }
170
  return nil;
171
}
172
 
173
- (nullable FIRIAMMessageDefinition *)nextOnFirebaseAnalyticEventDisplayMsg:(NSString *)eventName {
174
  FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM160005",
175
              @"Inside nextOnFirebaseAnalyticEventDisplay for checking contextual trigger match");
176
  if (![self.firebaseAnalyticEventsToWatch containsObject:eventName]) {
177
    return nil;
178
  }
179
 
180
  FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM160006",
181
              @"There could be a potential message match for analytics event %@", eventName);
182
  NSSet<NSString *> *impressionSet =
183
      [NSSet setWithArray:[self.bookKeeper getMessageIDsFromImpressions]];
184
  @synchronized(self) {
185
    for (FIRIAMMessageDefinition *next in self.regularMessages) {
186
      // message being active and message not impressed yet and the contextual trigger condition
187
      // match
188
      if ([next messageHasStarted] && ![next messageHasExpired] &&
189
          ![impressionSet containsObject:next.renderData.messageID] &&
190
          [next messageRenderedOnAnalyticsEvent:eventName]) {
191
        return next;
192
      }
193
    }
194
  }
195
  return nil;
196
}
197
 
198
- (void)removeMessageWithId:(NSString *)messageID {
199
  FIRIAMMessageDefinition *msgToRemove = nil;
200
  @synchronized(self) {
201
    for (FIRIAMMessageDefinition *next in self.regularMessages) {
202
      if ([next.renderData.messageID isEqualToString:messageID]) {
203
        msgToRemove = next;
204
        break;
205
      }
206
    }
207
 
208
    if (msgToRemove) {
209
      [self.regularMessages removeObject:msgToRemove];
210
      [self setupAnalyticsEventListening];
211
    }
212
  }
213
 
214
  // triggers the observer outside synchronization block
215
  if (msgToRemove) {
216
    [self.observer dataChanged];
217
  }
218
}
219
 
220
- (void)loadMessageDataFromServerFetchStorage:(FIRIAMServerMsgFetchStorage *)fetchStorage
221
                               withCompletion:(void (^)(BOOL success))completion {
222
  [fetchStorage readResponseDictionary:^(NSDictionary *_Nonnull response, BOOL success) {
223
    if (success) {
224
      NSInteger discardCount;
225
      NSNumber *fetchWaitTime;
226
      NSArray<FIRIAMMessageDefinition *> *messagesFromStorage =
227
          [self.responseParser parseAPIResponseDictionary:response
228
                                        discardedMsgCount:&discardCount
229
                                   fetchWaitTimeInSeconds:&fetchWaitTime];
230
      [self setMessageData:messagesFromStorage];
231
      completion(YES);
232
    } else {
233
      completion(NO);
234
    }
235
  }];
236
}
237
@end
238
 
239
#endif  // TARGET_OS_IOS || TARGET_OS_TV