You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

272 lines
9.6 KiB

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