FIRMessagingContextManagerService.m 12 KB

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