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