FIRMessagingPubSub.m 11 KB

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