FIRIAMActivityLogger.m 7.9 KB

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