FIRIAMActivityLogger.m 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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/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 defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  101. if (@available(iOS 13.0, tvOS 13.0, *)) {
  102. [[NSNotificationCenter defaultCenter] addObserver:self
  103. selector:@selector(appWillBecomeInactive:)
  104. name:UISceneWillDeactivateNotification
  105. object:nil];
  106. }
  107. #endif // defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  108. if (loadFromCache) {
  109. @try {
  110. [self loadFromCachePath:nil];
  111. } @catch (NSException *exception) {
  112. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM310003",
  113. @"Non-fatal exception in loading persisted activity log records: %@.",
  114. exception);
  115. }
  116. }
  117. }
  118. return self;
  119. }
  120. - (void)dealloc {
  121. [[NSNotificationCenter defaultCenter] removeObserver:self];
  122. }
  123. + (NSString *)determineCacheFilePath {
  124. static NSString *logCachePath;
  125. static dispatch_once_t onceToken;
  126. dispatch_once(&onceToken, ^{
  127. NSString *cacheDirPath =
  128. NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
  129. logCachePath = [NSString stringWithFormat:@"%@/firebase-iam-activity-log-cache", cacheDirPath];
  130. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM310001",
  131. @"Persistent file path for activity log data is %@", logCachePath);
  132. });
  133. return logCachePath;
  134. }
  135. - (void)loadFromCachePath:(NSString *)cacheFilePath {
  136. NSString *filePath = cacheFilePath == nil ? [self.class determineCacheFilePath] : cacheFilePath;
  137. id fetchedActivityRecords;
  138. NSData *data = [NSData dataWithContentsOfFile:filePath];
  139. if (data) {
  140. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, *)) {
  141. fetchedActivityRecords = [NSKeyedUnarchiver
  142. unarchivedObjectOfClasses:[NSSet setWithObjects:[FIRIAMActivityRecord class],
  143. [NSMutableArray class], nil]
  144. fromData:data
  145. error:nil];
  146. } else {
  147. // Fallback on earlier versions
  148. #pragma clang diagnostic push
  149. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  150. fetchedActivityRecords = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
  151. #pragma clang diagnostic pop
  152. }
  153. }
  154. if (fetchedActivityRecords) {
  155. @synchronized(self) {
  156. self.activityRecords = (NSMutableArray<FIRIAMActivityRecord *> *)fetchedActivityRecords;
  157. self.isDirty = NO;
  158. }
  159. }
  160. }
  161. - (BOOL)saveIntoCacheWithPath:(NSString *)cacheFilePath {
  162. NSString *filePath = cacheFilePath == nil ? [self.class determineCacheFilePath] : cacheFilePath;
  163. @synchronized(self) {
  164. #pragma clang diagnostic push
  165. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  166. BOOL result = [NSKeyedArchiver archiveRootObject:self.activityRecords toFile:filePath];
  167. #pragma clang diagnostic pop
  168. if (result) {
  169. self.isDirty = NO;
  170. }
  171. return result;
  172. }
  173. }
  174. - (void)appWillBecomeInactive:(NSNotification *)notification {
  175. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM310004",
  176. @"App will become inactive, save"
  177. " activity logs");
  178. if (self.isDirty) {
  179. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{
  180. if ([self saveIntoCacheWithPath:nil]) {
  181. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM310002",
  182. @"Persisting activity log data is was successful");
  183. } else {
  184. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM310005",
  185. @"Persisting activity log data has failed");
  186. }
  187. });
  188. }
  189. }
  190. // Helper function to determine if a given activity type should be recorded under
  191. // non verbose type.
  192. + (BOOL)isMandatoryType:(FIRIAMActivityType)type {
  193. switch (type) {
  194. case FIRIAMActivityTypeFetchMessage:
  195. case FIRIAMActivityTypeRenderMessage:
  196. case FIRIAMActivityTypeDismissMessage:
  197. return YES;
  198. default:
  199. return NO;
  200. }
  201. }
  202. - (void)addLogRecord:(FIRIAMActivityRecord *)newRecord {
  203. if (self.verboseMode || [FIRIAMActivityLogger isMandatoryType:newRecord.activityType]) {
  204. @synchronized(self) {
  205. [self.activityRecords insertObject:newRecord atIndex:0];
  206. if (self.activityRecords.count >= self.maxRecordCountBeforeReduce) {
  207. NSRange removeRange;
  208. removeRange.location = self.newSizeAfterReduce;
  209. removeRange.length = self.maxRecordCountBeforeReduce - self.newSizeAfterReduce;
  210. [self.activityRecords removeObjectsInRange:removeRange];
  211. }
  212. self.isDirty = YES;
  213. }
  214. }
  215. }
  216. - (NSArray<FIRIAMActivityRecord *> *)readRecords {
  217. return [self.activityRecords copy];
  218. }
  219. @end
  220. #endif // TARGET_OS_IOS || TARGET_OS_TV