FIRMessagingPubSub.m 9.8 KB

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