FIRIAMActivityLogger.m 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. #import <TargetConditionals.h>
  17. #if TARGET_OS_IOS || TARGET_OS_TV
  18. #import <UIKit/UIKit.h>
  19. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  20. #import "FirebaseInAppMessaging/Sources/FIRCore+InAppMessaging.h"
  21. #import "FirebaseInAppMessaging/Sources/Private/Flows/FIRIAMActivityLogger.h"
  22. @implementation FIRIAMActivityRecord
  23. static NSString *const kActiveTypeArchiveKey = @"type";
  24. static NSString *const kIsSuccessArchiveKey = @"is_success";
  25. static NSString *const kTimeStampArchiveKey = @"timestamp";
  26. static NSString *const kDetailArchiveKey = @"detail";
  27. - (id)initWithCoder:(NSCoder *)decoder {
  28. self = [super init];
  29. if (self != nil) {
  30. _activityType = [decoder decodeIntegerForKey:kActiveTypeArchiveKey];
  31. _timestamp = [decoder decodeObjectForKey:kTimeStampArchiveKey];
  32. _success = [decoder decodeBoolForKey:kIsSuccessArchiveKey];
  33. _detail = [decoder decodeObjectForKey:kDetailArchiveKey];
  34. }
  35. return self;
  36. }
  37. - (void)encodeWithCoder:(NSCoder *)encoder {
  38. [encoder encodeInteger:self.activityType forKey:kActiveTypeArchiveKey];
  39. [encoder encodeObject:self.timestamp forKey:kTimeStampArchiveKey];
  40. [encoder encodeBool:self.success forKey:kIsSuccessArchiveKey];
  41. [encoder encodeObject:self.detail forKey:kDetailArchiveKey];
  42. }
  43. - (instancetype)initWithActivityType:(FIRIAMActivityType)type
  44. isSuccessful:(BOOL)isSuccessful
  45. withDetail:(NSString *)detail
  46. timestamp:(nullable NSDate *)timestamp {
  47. if (self = [super init]) {
  48. _activityType = type;
  49. _success = isSuccessful;
  50. _detail = detail;
  51. _timestamp = timestamp ? timestamp : [[NSDate alloc] init];
  52. }
  53. return self;
  54. }
  55. - (NSString *)displayStringForActivityType {
  56. switch (self.activityType) {
  57. case FIRIAMActivityTypeFetchMessage:
  58. return @"Message Fetching";
  59. case FIRIAMActivityTypeRenderMessage:
  60. return @"Message Rendering";
  61. case FIRIAMActivityTypeDismissMessage:
  62. return @"Message Dismiss";
  63. case FIRIAMActivityTypeCheckForOnOpenMessage:
  64. return @"OnOpen Msg Check";
  65. case FIRIAMActivityTypeCheckForAnalyticsEventMessage:
  66. return @"Analytic Msg Check";
  67. case FIRIAMActivityTypeCheckForFetch:
  68. return @"Fetch Check";
  69. }
  70. }
  71. @end
  72. @interface FIRIAMActivityLogger ()
  73. @property(nonatomic) BOOL isDirty;
  74. // always insert at the head of this array so that they are always in anti-chronological order
  75. @property(nonatomic, nonnull) NSMutableArray<FIRIAMActivityRecord *> *activityRecords;
  76. // When we see the number of log records goes beyond maxRecordCountBeforeReduce, we would trigger
  77. // a reduction action which would bring the array length to be the size as defined by
  78. // newSizeAfterReduce
  79. @property(nonatomic, readonly) NSInteger maxRecordCountBeforeReduce;
  80. @property(nonatomic, readonly) NSInteger newSizeAfterReduce;
  81. @end
  82. @implementation FIRIAMActivityLogger
  83. - (instancetype)initWithMaxCountBeforeReduce:(NSInteger)maxBeforeReduce
  84. withSizeAfterReduce:(NSInteger)sizeAfterReduce
  85. verboseMode:(BOOL)verboseMode
  86. loadFromCache:(BOOL)loadFromCache {
  87. if (self = [super init]) {
  88. _maxRecordCountBeforeReduce = maxBeforeReduce;
  89. _newSizeAfterReduce = sizeAfterReduce;
  90. _activityRecords = [[NSMutableArray alloc] init];
  91. _verboseMode = verboseMode;
  92. _isDirty = NO;
  93. [[NSNotificationCenter defaultCenter] addObserver:self
  94. selector:@selector(appWillBecomeInactive:)
  95. name:UIApplicationWillResignActiveNotification
  96. object:nil];
  97. #if defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  98. if (@available(iOS 13.0, tvOS 13.0, *)) {
  99. [[NSNotificationCenter defaultCenter] addObserver:self
  100. selector:@selector(appWillBecomeInactive:)
  101. name:UISceneWillDeactivateNotification
  102. object:nil];
  103. }
  104. #endif // defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  105. if (loadFromCache) {
  106. @try {
  107. [self loadFromCachePath:nil];
  108. } @catch (NSException *exception) {
  109. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM310003",
  110. @"Non-fatal exception in loading persisted activity log records: %@.",
  111. exception);
  112. }
  113. }
  114. }
  115. return self;
  116. }
  117. - (void)dealloc {
  118. [[NSNotificationCenter defaultCenter] removeObserver:self];
  119. }
  120. + (NSString *)determineCacheFilePath {
  121. static NSString *logCachePath;
  122. static dispatch_once_t onceToken;
  123. dispatch_once(&onceToken, ^{
  124. NSString *cacheDirPath =
  125. NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
  126. logCachePath = [NSString stringWithFormat:@"%@/firebase-iam-activity-log-cache", cacheDirPath];
  127. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM310001",
  128. @"Persistent file path for activity log data is %@", logCachePath);
  129. });
  130. return logCachePath;
  131. }
  132. - (void)loadFromCachePath:(NSString *)cacheFilePath {
  133. NSString *filePath = cacheFilePath == nil ? [self.class determineCacheFilePath] : cacheFilePath;
  134. #pragma clang diagnostic push
  135. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  136. id fetchedActivityRecords = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
  137. #pragma clang diagnostic pop
  138. if (fetchedActivityRecords) {
  139. @synchronized(self) {
  140. self.activityRecords = (NSMutableArray<FIRIAMActivityRecord *> *)fetchedActivityRecords;
  141. self.isDirty = NO;
  142. }
  143. }
  144. }
  145. - (BOOL)saveIntoCacheWithPath:(NSString *)cacheFilePath {
  146. NSString *filePath = cacheFilePath == nil ? [self.class determineCacheFilePath] : cacheFilePath;
  147. @synchronized(self) {
  148. #pragma clang diagnostic push
  149. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  150. BOOL result = [NSKeyedArchiver archiveRootObject:self.activityRecords toFile:filePath];
  151. #pragma clang diagnostic pop
  152. if (result) {
  153. self.isDirty = NO;
  154. }
  155. return result;
  156. }
  157. }
  158. - (void)appWillBecomeInactive:(NSNotification *)notification {
  159. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM310004",
  160. @"App will become inactive, save"
  161. " activity logs");
  162. if (self.isDirty) {
  163. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{
  164. if ([self saveIntoCacheWithPath:nil]) {
  165. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM310002",
  166. @"Persisting activity log data is was successful");
  167. } else {
  168. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM310005",
  169. @"Persisting activity log data has failed");
  170. }
  171. });
  172. }
  173. }
  174. // Helper function to determine if a given activity type should be recorded under
  175. // non verbose type.
  176. + (BOOL)isMandatoryType:(FIRIAMActivityType)type {
  177. switch (type) {
  178. case FIRIAMActivityTypeFetchMessage:
  179. case FIRIAMActivityTypeRenderMessage:
  180. case FIRIAMActivityTypeDismissMessage:
  181. return YES;
  182. default:
  183. return NO;
  184. }
  185. }
  186. - (void)addLogRecord:(FIRIAMActivityRecord *)newRecord {
  187. if (self.verboseMode || [FIRIAMActivityLogger isMandatoryType:newRecord.activityType]) {
  188. @synchronized(self) {
  189. [self.activityRecords insertObject:newRecord atIndex:0];
  190. if (self.activityRecords.count >= self.maxRecordCountBeforeReduce) {
  191. NSRange removeRange;
  192. removeRange.location = self.newSizeAfterReduce;
  193. removeRange.length = self.maxRecordCountBeforeReduce - self.newSizeAfterReduce;
  194. [self.activityRecords removeObjectsInRange:removeRange];
  195. }
  196. self.isDirty = YES;
  197. }
  198. }
  199. }
  200. - (NSArray<FIRIAMActivityRecord *> *)readRecords {
  201. return [self.activityRecords copy];
  202. }
  203. @end
  204. #endif // TARGET_OS_IOS || TARGET_OS_TV