FIRMessagingPubSub.m 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. [self.pendingTopicUpdates addOperationForTopic:topic
  128. withAction:FIRMessagingTopicActionSubscribe
  129. completion:nil];
  130. }
  131. - (void)unsubscribeFromTopic:(NSString *)topic {
  132. [self.pendingTopicUpdates addOperationForTopic:topic
  133. withAction:FIRMessagingTopicActionUnsubscribe
  134. completion:nil];
  135. }
  136. - (void)scheduleSync:(BOOL)immediately {
  137. NSString *fcmToken = [[FIRMessaging messaging] defaultFcmToken];
  138. if (fcmToken.length) {
  139. [self.pendingTopicUpdates resumeOperationsIfNeeded];
  140. }
  141. }
  142. #pragma mark - FIRMessagingPendingTopicsListDelegate
  143. - (void)pendingTopicsList:(FIRMessagingPendingTopicsList *)list
  144. requestedUpdateForTopic:(NSString *)topic
  145. action:(FIRMessagingTopicAction)action
  146. completion:(FIRMessagingTopicOperationCompletion)completion {
  147. NSString *fcmToken = [[FIRMessaging messaging] defaultFcmToken];
  148. if (action == FIRMessagingTopicActionSubscribe) {
  149. [self subscribeWithToken:fcmToken topic:topic options:nil handler:completion];
  150. } else {
  151. [self unsubscribeWithToken:fcmToken topic:topic options:nil handler:completion];
  152. }
  153. }
  154. - (void)pendingTopicsListDidUpdate:(FIRMessagingPendingTopicsList *)list {
  155. [self archivePendingTopicsList:list];
  156. }
  157. - (BOOL)pendingTopicsListCanRequestTopicUpdates:(FIRMessagingPendingTopicsList *)list {
  158. NSString *fcmToken = [[FIRMessaging messaging] defaultFcmToken];
  159. return (fcmToken.length > 0);
  160. }
  161. #pragma mark - Storing Pending Topics
  162. - (void)archivePendingTopicsList:(FIRMessagingPendingTopicsList *)topicsList {
  163. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  164. NSData *pendingData = [NSKeyedArchiver archivedDataWithRootObject:topicsList];
  165. [defaults setObject:pendingData forKey:kPendingSubscriptionsListKey];
  166. [defaults synchronize];
  167. }
  168. - (void)restorePendingTopicsList {
  169. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  170. NSData *pendingData = [defaults objectForKey:kPendingSubscriptionsListKey];
  171. FIRMessagingPendingTopicsList *subscriptions;
  172. @try {
  173. if (pendingData) {
  174. subscriptions = [NSKeyedUnarchiver unarchiveObjectWithData:pendingData];
  175. }
  176. } @catch (NSException *exception) {
  177. // Nothing we can do, just continue as if we don't have pending subscriptions
  178. } @finally {
  179. if (subscriptions) {
  180. self.pendingTopicUpdates = subscriptions;
  181. } else {
  182. self.pendingTopicUpdates = [[FIRMessagingPendingTopicsList alloc] init];
  183. }
  184. self.pendingTopicUpdates.delegate = self;
  185. }
  186. }
  187. #pragma mark - Private Helpers
  188. - (BOOL)verifyPubSubOptions:(NSDictionary *)options {
  189. return ![options fcm_hasNonStringKeysOrValues];
  190. }
  191. #pragma mark - Topic Name Helpers
  192. static NSString *const kTopicsPrefix = @"/topics/";
  193. static NSString *const kTopicRegexPattern = @"/topics/([a-zA-Z0-9-_.~%]+)";
  194. + (NSString *)addPrefixToTopic:(NSString *)topic {
  195. if (![self hasTopicsPrefix:topic]) {
  196. return [NSString stringWithFormat:@"%@%@", kTopicsPrefix, topic];
  197. } else {
  198. return [topic copy];
  199. }
  200. }
  201. + (BOOL)hasTopicsPrefix:(NSString *)topic {
  202. return [topic hasPrefix:kTopicsPrefix];
  203. }
  204. /**
  205. * Returns a regular expression for matching a topic sender.
  206. *
  207. * @return The topic matching regular expression
  208. */
  209. + (NSRegularExpression *)topicRegex {
  210. // Since this is a static regex pattern, we only only need to declare it once.
  211. static NSRegularExpression *topicRegex;
  212. static dispatch_once_t onceToken;
  213. dispatch_once(&onceToken, ^{
  214. NSError *error;
  215. topicRegex =
  216. [NSRegularExpression regularExpressionWithPattern:kTopicRegexPattern
  217. options:NSRegularExpressionAnchorsMatchLines
  218. error:&error];
  219. });
  220. return topicRegex;
  221. }
  222. /**
  223. * Gets the class describing occurences of topic names and sender IDs in the sender.
  224. *
  225. * @param expression The topic expression used to generate a pubsub topic
  226. *
  227. * @return Representation of captured subexpressions in topic regular expression
  228. */
  229. + (BOOL)isValidTopicWithPrefix:(NSString *)topic {
  230. NSRange topicRange = NSMakeRange(0, topic.length);
  231. NSRange regexMatchRange = [[self topicRegex] rangeOfFirstMatchInString:topic
  232. options:NSMatchingAnchored
  233. range:topicRange];
  234. return NSEqualRanges(topicRange, regexMatchRange);
  235. }
  236. @end