FIRMessagingContextManagerService.m 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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 <UserNotifications/UserNotifications.h>
  17. #import "FirebaseMessaging/Sources/FIRMessagingContextManagerService.h"
  18. #import "FirebaseMessaging/Sources/FIRMessagingDefines.h"
  19. #import "FirebaseMessaging/Sources/FIRMessagingLogger.h"
  20. #import "FirebaseMessaging/Sources/FIRMessagingUtilities.h"
  21. #import <GoogleUtilities/GULAppDelegateSwizzler.h>
  22. #define kFIRMessagingContextManagerPrefix @"gcm."
  23. #define kFIRMessagingContextManagerPrefixKey @"google.c.cm."
  24. #define kFIRMessagingContextManagerNotificationKeyPrefix @"gcm.notification."
  25. static NSString *const kLogTag = @"FIRMessagingAnalytics";
  26. static NSString *const kLocalTimeFormatString = @"yyyy-MM-dd HH:mm:ss";
  27. static NSString *const kContextManagerPrefixKey = kFIRMessagingContextManagerPrefixKey;
  28. // Local timed messages (format yyyy-mm-dd HH:mm:ss)
  29. NSString *const kFIRMessagingContextManagerLocalTimeStart =
  30. kFIRMessagingContextManagerPrefixKey @"lt_start";
  31. NSString *const kFIRMessagingContextManagerLocalTimeEnd =
  32. kFIRMessagingContextManagerPrefixKey @"lt_end";
  33. // Local Notification Params
  34. NSString *const kFIRMessagingContextManagerBodyKey =
  35. kFIRMessagingContextManagerNotificationKeyPrefix @"body";
  36. NSString *const kFIRMessagingContextManagerTitleKey =
  37. kFIRMessagingContextManagerNotificationKeyPrefix @"title";
  38. NSString *const kFIRMessagingContextManagerBadgeKey =
  39. kFIRMessagingContextManagerNotificationKeyPrefix @"badge";
  40. NSString *const kFIRMessagingContextManagerCategoryKey =
  41. kFIRMessagingContextManagerNotificationKeyPrefix @"click_action";
  42. NSString *const kFIRMessagingContextManagerSoundKey =
  43. kFIRMessagingContextManagerNotificationKeyPrefix @"sound";
  44. NSString *const kFIRMessagingContextManagerContentAvailableKey =
  45. kFIRMessagingContextManagerNotificationKeyPrefix @"content-available";
  46. static NSString *const kFIRMessagingID = kFIRMessagingContextManagerPrefix @"message_id";
  47. static NSString *const kFIRMessagingAPNSPayloadKey = @"aps";
  48. typedef NS_ENUM(NSUInteger, FIRMessagingContextManagerMessageType) {
  49. FIRMessagingContextManagerMessageTypeNone,
  50. FIRMessagingContextManagerMessageTypeLocalTime,
  51. };
  52. @implementation FIRMessagingContextManagerService
  53. + (BOOL)isContextManagerMessage:(NSDictionary *)message {
  54. // For now we only support local time in ContextManager.
  55. if (![message[kFIRMessagingContextManagerLocalTimeStart] length]) {
  56. FIRMessagingLoggerDebug(
  57. kFIRMessagingMessageCodeContextManagerService000,
  58. @"Received message missing local start time, not a contextual message.");
  59. return NO;
  60. }
  61. return YES;
  62. }
  63. + (BOOL)handleContextManagerMessage:(NSDictionary *)message {
  64. NSString *startTimeString = message[kFIRMessagingContextManagerLocalTimeStart];
  65. if (startTimeString.length) {
  66. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeContextManagerService001,
  67. @"%@ Received context manager message with local time %@", kLogTag,
  68. startTimeString);
  69. return [self handleContextManagerLocalTimeMessage:message];
  70. }
  71. return NO;
  72. }
  73. + (BOOL)handleContextManagerLocalTimeMessage:(NSDictionary *)message {
  74. NSString *startTimeString = message[kFIRMessagingContextManagerLocalTimeStart];
  75. if (!startTimeString) {
  76. FIRMessagingLoggerError(kFIRMessagingMessageCodeContextManagerService002,
  77. @"Invalid local start date format %@. Message dropped",
  78. startTimeString);
  79. return NO;
  80. }
  81. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  82. dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  83. [dateFormatter setDateFormat:kLocalTimeFormatString];
  84. NSDate *startDate = [dateFormatter dateFromString:startTimeString];
  85. NSDate *currentDate = [NSDate date];
  86. if ([currentDate compare:startDate] == NSOrderedAscending) {
  87. [self scheduleLocalNotificationForMessage:message atDate:startDate];
  88. } else {
  89. // check end time has not passed
  90. NSString *endTimeString = message[kFIRMessagingContextManagerLocalTimeEnd];
  91. if (!endTimeString) {
  92. FIRMessagingLoggerInfo(
  93. kFIRMessagingMessageCodeContextManagerService003,
  94. @"No end date specified for message, start date elapsed. Message dropped.");
  95. return YES;
  96. }
  97. NSDate *endDate = [dateFormatter dateFromString:endTimeString];
  98. if (!endTimeString) {
  99. FIRMessagingLoggerError(kFIRMessagingMessageCodeContextManagerService004,
  100. @"Invalid local end date format %@. Message dropped", endTimeString);
  101. return NO;
  102. }
  103. if ([endDate compare:currentDate] == NSOrderedAscending) {
  104. // end date has already passed drop the message
  105. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeContextManagerService005,
  106. @"End date %@ has already passed. Message dropped.", endTimeString);
  107. return YES;
  108. }
  109. // schedule message right now (buffer 10s)
  110. [self scheduleLocalNotificationForMessage:message
  111. atDate:[currentDate dateByAddingTimeInterval:10]];
  112. }
  113. return YES;
  114. }
  115. + (void)scheduleiOS10LocalNotificationForMessage:(NSDictionary *)message
  116. atDate:(NSDate *)date
  117. API_AVAILABLE(macosx(10.14), ios(10.0), watchos(3.0), tvos(10.0)) {
  118. NSCalendar *calendar = [NSCalendar currentCalendar];
  119. NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |
  120. NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
  121. NSDateComponents *dateComponents = [calendar components:(NSCalendarUnit)unit fromDate:date];
  122. UNCalendarNotificationTrigger *trigger =
  123. [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateComponents repeats:NO];
  124. UNMutableNotificationContent *content = [self contentFromContextualMessage:message];
  125. NSString *identifier = message[kFIRMessagingID];
  126. if (!identifier) {
  127. identifier = [NSUUID UUID].UUIDString;
  128. }
  129. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
  130. content:content
  131. trigger:trigger];
  132. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  133. [center
  134. addNotificationRequest:request
  135. withCompletionHandler:^(NSError *_Nullable error) {
  136. if (error) {
  137. FIRMessagingLoggerError(kFIRMessagingMessageCodeContextManagerServiceFailedLocalSchedule,
  138. @"Failed scheduling local timezone notification: %@.", error);
  139. }
  140. }];
  141. }
  142. + (UNMutableNotificationContent *)contentFromContextualMessage:(NSDictionary *)message
  143. API_AVAILABLE(macosx(10.14), ios(10.0), watchos(3.0), tvos(10.0)) {
  144. UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
  145. NSDictionary *apsDictionary = message;
  146. // Badge is universal
  147. if (apsDictionary[kFIRMessagingContextManagerBadgeKey]) {
  148. content.badge = apsDictionary[kFIRMessagingContextManagerBadgeKey];
  149. }
  150. #if !TARGET_OS_TV
  151. // The following fields are not available on tvOS
  152. if ([apsDictionary[kFIRMessagingContextManagerBodyKey] length]) {
  153. content.body = apsDictionary[kFIRMessagingContextManagerBodyKey];
  154. }
  155. if ([apsDictionary[kFIRMessagingContextManagerTitleKey] length]) {
  156. content.title = apsDictionary[kFIRMessagingContextManagerTitleKey];
  157. }
  158. if (apsDictionary[kFIRMessagingContextManagerSoundKey]) {
  159. #if !TARGET_OS_WATCH
  160. // UNNotificationSound soundNamded: is not available in watchOS
  161. content.sound =
  162. [UNNotificationSound soundNamed:apsDictionary[kFIRMessagingContextManagerSoundKey]];
  163. #else // !TARGET_OS_WATCH
  164. content.sound = [UNNotificationSound defaultSound];
  165. #endif // !TARGET_OS_WATCH
  166. }
  167. if (apsDictionary[kFIRMessagingContextManagerCategoryKey]) {
  168. content.categoryIdentifier = apsDictionary[kFIRMessagingContextManagerCategoryKey];
  169. }
  170. NSDictionary *userInfo = [self parseDataFromMessage:message];
  171. if (userInfo.count) {
  172. content.userInfo = userInfo;
  173. }
  174. #endif // !TARGET_OS_TV
  175. return content;
  176. }
  177. + (void)scheduleLocalNotificationForMessage:(NSDictionary *)message atDate:(NSDate *)date {
  178. if (@available(macOS 10.14, *)) {
  179. [self scheduleiOS10LocalNotificationForMessage:message atDate:date];
  180. return;
  181. }
  182. }
  183. + (NSDictionary *)parseDataFromMessage:(NSDictionary *)message {
  184. NSMutableDictionary *data = [NSMutableDictionary dictionary];
  185. for (NSObject<NSCopying> *key in message) {
  186. if ([key isKindOfClass:[NSString class]]) {
  187. NSString *keyString = (NSString *)key;
  188. if ([keyString isEqualToString:kFIRMessagingContextManagerContentAvailableKey]) {
  189. continue;
  190. } else if ([keyString hasPrefix:kContextManagerPrefixKey]) {
  191. continue;
  192. } else if ([keyString isEqualToString:kFIRMessagingAPNSPayloadKey]) {
  193. // Local timezone message is scheduled with FCM payload. APNS payload with
  194. // content_available should be ignored and not passed to the scheduled
  195. // messages.
  196. continue;
  197. }
  198. }
  199. data[[key copy]] = message[key];
  200. }
  201. return [data copy];
  202. }
  203. @end