FIRMessagingPubSub.m 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 "Firebase/Messaging/FIRMessagingPubSub.h"
  17. #import <GoogleUtilities/GULUserDefaults.h>
  18. #import <FirebaseMessaging/FIRMessaging.h>
  19. #import "Firebase/Messaging/FIRMessagingClient.h"
  20. #import "Firebase/Messaging/FIRMessagingDefines.h"
  21. #import "Firebase/Messaging/FIRMessagingLogger.h"
  22. #import "Firebase/Messaging/FIRMessagingPendingTopicsList.h"
  23. #import "Firebase/Messaging/FIRMessagingUtilities.h"
  24. #import "Firebase/Messaging/FIRMessaging_Private.h"
  25. #import "Firebase/Messaging/NSDictionary+FIRMessaging.h"
  26. #import "Firebase/Messaging/NSError+FIRMessaging.h"
  27. static NSString *const kPendingSubscriptionsListKey =
  28. @"com.firebase.messaging.pending-subscriptions";
  29. @interface FIRMessagingPubSub () <FIRMessagingPendingTopicsListDelegate>
  30. @property(nonatomic, readwrite, strong) FIRMessagingPendingTopicsList *pendingTopicUpdates;
  31. @property(nonatomic, readwrite, strong) FIRMessagingClient *client;
  32. @end
  33. @implementation FIRMessagingPubSub
  34. - (instancetype)init {
  35. FIRMessagingInvalidateInitializer();
  36. // Need this to disable an Xcode warning.
  37. return [self initWithClient:nil];
  38. }
  39. - (instancetype)initWithClient:(FIRMessagingClient *)client {
  40. self = [super init];
  41. if (self) {
  42. _client = client;
  43. [self restorePendingTopicsList];
  44. }
  45. return self;
  46. }
  47. - (void)subscribeWithToken:(NSString *)token
  48. topic:(NSString *)topic
  49. options:(NSDictionary *)options
  50. handler:(FIRMessagingTopicOperationCompletion)handler {
  51. if (!self.client) {
  52. handler([NSError errorWithFCMErrorCode:kFIRMessagingErrorCodePubSubFIRMessagingNotSetup]);
  53. return;
  54. }
  55. token = [token copy];
  56. topic = [topic copy];
  57. if (![options count]) {
  58. options = @{};
  59. }
  60. if (![[self class] isValidTopicWithPrefix:topic]) {
  61. FIRMessagingLoggerError(kFIRMessagingMessageCodePubSub000,
  62. @"Invalid FIRMessaging Pubsub topic %@", topic);
  63. handler([NSError errorWithFCMErrorCode:kFIRMessagingErrorCodePubSubInvalidTopic]);
  64. return;
  65. }
  66. if (![self verifyPubSubOptions:options]) {
  67. // we do not want to quit even if options have some invalid values.
  68. FIRMessagingLoggerError(kFIRMessagingMessageCodePubSub001,
  69. @"Invalid options passed to FIRMessagingPubSub with non-string keys or "
  70. "values.");
  71. }
  72. // copy the dictionary would trim non-string keys or values if any.
  73. options = [options fcm_trimNonStringValues];
  74. [self.client updateSubscriptionWithToken:token
  75. topic:topic
  76. options:options
  77. shouldDelete:NO
  78. handler:^void(NSError *error) {
  79. handler(error);
  80. }];
  81. }
  82. - (void)unsubscribeWithToken:(NSString *)token
  83. topic:(NSString *)topic
  84. options:(NSDictionary *)options
  85. handler:(FIRMessagingTopicOperationCompletion)handler {
  86. if (!self.client) {
  87. handler([NSError errorWithFCMErrorCode:kFIRMessagingErrorCodePubSubFIRMessagingNotSetup]);
  88. return;
  89. }
  90. token = [token copy];
  91. topic = [topic copy];
  92. if (![options count]) {
  93. options = @{};
  94. }
  95. if (![[self class] isValidTopicWithPrefix:topic]) {
  96. FIRMessagingLoggerError(kFIRMessagingMessageCodePubSub002,
  97. @"Invalid FIRMessaging Pubsub topic %@", topic);
  98. handler([NSError errorWithFCMErrorCode:kFIRMessagingErrorCodePubSubInvalidTopic]);
  99. return;
  100. }
  101. if (![self verifyPubSubOptions:options]) {
  102. // we do not want to quit even if options have some invalid values.
  103. FIRMessagingLoggerError(
  104. kFIRMessagingMessageCodePubSub003,
  105. @"Invalid options passed to FIRMessagingPubSub with non-string keys or values.");
  106. }
  107. // copy the dictionary would trim non-string keys or values if any.
  108. options = [options fcm_trimNonStringValues];
  109. [self.client updateSubscriptionWithToken:token
  110. topic:topic
  111. options:options
  112. shouldDelete:YES
  113. handler:^void(NSError *error) {
  114. handler(error);
  115. }];
  116. }
  117. - (void)subscribeToTopic:(NSString *)topic
  118. handler:(nullable FIRMessagingTopicOperationCompletion)handler {
  119. [self.pendingTopicUpdates addOperationForTopic:topic
  120. withAction:FIRMessagingTopicActionSubscribe
  121. completion:handler];
  122. }
  123. - (void)unsubscribeFromTopic:(NSString *)topic
  124. handler:(nullable FIRMessagingTopicOperationCompletion)handler {
  125. [self.pendingTopicUpdates addOperationForTopic:topic
  126. withAction:FIRMessagingTopicActionUnsubscribe
  127. completion:handler];
  128. }
  129. - (void)scheduleSync:(BOOL)immediately {
  130. NSString *fcmToken = [[FIRMessaging messaging] defaultFcmToken];
  131. if (fcmToken.length) {
  132. [self.pendingTopicUpdates resumeOperationsIfNeeded];
  133. }
  134. }
  135. #pragma mark - FIRMessagingPendingTopicsListDelegate
  136. - (void)pendingTopicsList:(FIRMessagingPendingTopicsList *)list
  137. requestedUpdateForTopic:(NSString *)topic
  138. action:(FIRMessagingTopicAction)action
  139. completion:(FIRMessagingTopicOperationCompletion)completion {
  140. NSString *fcmToken = [[FIRMessaging messaging] defaultFcmToken];
  141. if (action == FIRMessagingTopicActionSubscribe) {
  142. [self subscribeWithToken:fcmToken topic:topic options:nil handler:completion];
  143. } else {
  144. [self unsubscribeWithToken:fcmToken topic:topic options:nil handler:completion];
  145. }
  146. }
  147. - (void)pendingTopicsListDidUpdate:(FIRMessagingPendingTopicsList *)list {
  148. [self archivePendingTopicsList:list];
  149. }
  150. - (BOOL)pendingTopicsListCanRequestTopicUpdates:(FIRMessagingPendingTopicsList *)list {
  151. NSString *fcmToken = [[FIRMessaging messaging] defaultFcmToken];
  152. return (fcmToken.length > 0);
  153. }
  154. #pragma mark - Storing Pending Topics
  155. - (void)archivePendingTopicsList:(FIRMessagingPendingTopicsList *)topicsList {
  156. GULUserDefaults *defaults = [GULUserDefaults standardUserDefaults];
  157. #pragma clang diagnostic push
  158. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  159. NSData *pendingData = [NSKeyedArchiver archivedDataWithRootObject:topicsList];
  160. #pragma clang diagnostic pop
  161. [defaults setObject:pendingData forKey:kPendingSubscriptionsListKey];
  162. [defaults synchronize];
  163. }
  164. - (void)restorePendingTopicsList {
  165. GULUserDefaults *defaults = [GULUserDefaults standardUserDefaults];
  166. NSData *pendingData = [defaults objectForKey:kPendingSubscriptionsListKey];
  167. FIRMessagingPendingTopicsList *subscriptions;
  168. @try {
  169. if (pendingData) {
  170. #pragma clang diagnostic push
  171. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  172. subscriptions = [NSKeyedUnarchiver unarchiveObjectWithData:pendingData];
  173. #pragma clang diagnostic pop
  174. }
  175. } @catch (NSException *exception) {
  176. // Nothing we can do, just continue as if we don't have pending subscriptions
  177. } @finally {
  178. if (subscriptions) {
  179. self.pendingTopicUpdates = subscriptions;
  180. } else {
  181. self.pendingTopicUpdates = [[FIRMessagingPendingTopicsList alloc] init];
  182. }
  183. self.pendingTopicUpdates.delegate = self;
  184. }
  185. }
  186. #pragma mark - Private Helpers
  187. - (BOOL)verifyPubSubOptions:(NSDictionary *)options {
  188. return ![options fcm_hasNonStringKeysOrValues];
  189. }
  190. #pragma mark - Topic Name Helpers
  191. static NSString *const kTopicsPrefix = @"/topics/";
  192. static NSString *const kTopicRegexPattern = @"/topics/([a-zA-Z0-9-_.~%]+)";
  193. + (NSString *)addPrefixToTopic:(NSString *)topic {
  194. if (![self hasTopicsPrefix:topic]) {
  195. return [NSString stringWithFormat:@"%@%@", kTopicsPrefix, topic];
  196. } else {
  197. return [topic copy];
  198. }
  199. }
  200. + (NSString *)removePrefixFromTopic:(NSString *)topic {
  201. if ([self hasTopicsPrefix:topic]) {
  202. return [topic substringFromIndex:kTopicsPrefix.length];
  203. } else {
  204. return [topic copy];
  205. }
  206. }
  207. + (BOOL)hasTopicsPrefix:(NSString *)topic {
  208. return [topic hasPrefix:kTopicsPrefix];
  209. }
  210. /**
  211. * Returns a regular expression for matching a topic sender.
  212. *
  213. * @return The topic matching regular expression
  214. */
  215. + (NSRegularExpression *)topicRegex {
  216. // Since this is a static regex pattern, we only only need to declare it once.
  217. static NSRegularExpression *topicRegex;
  218. static dispatch_once_t onceToken;
  219. dispatch_once(&onceToken, ^{
  220. NSError *error;
  221. topicRegex =
  222. [NSRegularExpression regularExpressionWithPattern:kTopicRegexPattern
  223. options:NSRegularExpressionAnchorsMatchLines
  224. error:&error];
  225. });
  226. return topicRegex;
  227. }
  228. /**
  229. * Gets the class describing occurences of topic names and sender IDs in the sender.
  230. *
  231. * @param expression The topic expression used to generate a pubsub topic
  232. *
  233. * @return Representation of captured subexpressions in topic regular expression
  234. */
  235. + (BOOL)isValidTopicWithPrefix:(NSString *)topic {
  236. NSRange topicRange = NSMakeRange(0, topic.length);
  237. NSRange regexMatchRange = [[self topicRegex] rangeOfFirstMatchInString:topic
  238. options:NSMatchingAnchored
  239. range:topicRange];
  240. return NSEqualRanges(topicRange, regexMatchRange);
  241. }
  242. @end