FIRIAMActivityLogger.m 8.8 KB

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