FIRMessagingContextManagerService.m 12 KB

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