FIRMessagingTopicOperation.m 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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/FIRMessagingTopicOperation.h"
  17. #import "FirebaseMessaging/Sources/FIRMessagingDefines.h"
  18. #import "FirebaseMessaging/Sources/FIRMessagingLogger.h"
  19. #import "FirebaseMessaging/Sources/FIRMessagingUtilities.h"
  20. #import "FirebaseMessaging/Sources/NSError+FIRMessaging.h"
  21. #import "FirebaseMessaging/Sources/Token/FIRMessagingTokenManager.h"
  22. static NSString *const kFIRMessagingSubscribeServerHost =
  23. @"https://iid.googleapis.com/iid/register";
  24. NSString *FIRMessagingSubscriptionsServer(void) {
  25. static NSString *serverHost = nil;
  26. static dispatch_once_t onceToken;
  27. dispatch_once(&onceToken, ^{
  28. NSDictionary *environment = [[NSProcessInfo processInfo] environment];
  29. NSString *customServerHost = environment[@"FCM_SERVER_ENDPOINT"];
  30. if (customServerHost.length) {
  31. serverHost = customServerHost;
  32. } else {
  33. serverHost = kFIRMessagingSubscribeServerHost;
  34. }
  35. });
  36. return serverHost;
  37. }
  38. @interface FIRMessagingTopicOperation () {
  39. BOOL _isFinished;
  40. BOOL _isExecuting;
  41. }
  42. @property(nonatomic, readwrite, copy) NSString *topic;
  43. @property(nonatomic, readwrite, assign) FIRMessagingTopicAction action;
  44. @property(nonatomic, readwrite, strong) FIRMessagingTokenManager *tokenManager;
  45. @property(nonatomic, readwrite, copy) NSDictionary *options;
  46. @property(nonatomic, readwrite, copy) FIRMessagingTopicOperationCompletion completion;
  47. @property(atomic, strong) NSURLSessionDataTask *dataTask;
  48. @end
  49. @implementation FIRMessagingTopicOperation
  50. + (NSURLSession *)sharedSession {
  51. static NSURLSession *subscriptionOperationSharedSession;
  52. static dispatch_once_t onceToken;
  53. dispatch_once(&onceToken, ^{
  54. NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
  55. config.timeoutIntervalForResource = 60.0f; // 1 minute
  56. subscriptionOperationSharedSession = [NSURLSession sessionWithConfiguration:config];
  57. subscriptionOperationSharedSession.sessionDescription = @"com.google.fcm.topics.session";
  58. });
  59. return subscriptionOperationSharedSession;
  60. }
  61. - (instancetype)initWithTopic:(NSString *)topic
  62. action:(FIRMessagingTopicAction)action
  63. tokenManager:(FIRMessagingTokenManager *)tokenManager
  64. options:(NSDictionary *)options
  65. completion:(FIRMessagingTopicOperationCompletion)completion {
  66. if (self = [super init]) {
  67. _topic = topic;
  68. _action = action;
  69. _tokenManager = tokenManager;
  70. _options = options;
  71. _completion = completion;
  72. _isExecuting = NO;
  73. _isFinished = NO;
  74. }
  75. return self;
  76. }
  77. - (void)dealloc {
  78. _topic = nil;
  79. _completion = nil;
  80. }
  81. - (BOOL)isAsynchronous {
  82. return YES;
  83. }
  84. - (BOOL)isExecuting {
  85. return _isExecuting;
  86. }
  87. - (void)setExecuting:(BOOL)executing {
  88. [self willChangeValueForKey:@"isExecuting"];
  89. _isExecuting = executing;
  90. [self didChangeValueForKey:@"isExecuting"];
  91. }
  92. - (BOOL)isFinished {
  93. return _isFinished;
  94. }
  95. - (void)setFinished:(BOOL)finished {
  96. [self willChangeValueForKey:@"isFinished"];
  97. _isFinished = finished;
  98. [self didChangeValueForKey:@"isFinished"];
  99. }
  100. - (void)start {
  101. if (self.isCancelled) {
  102. NSError *error = [NSError
  103. messagingErrorWithCode:kFIRMessagingErrorCodePubSubOperationIsCancelled
  104. failureReason:
  105. @"Failed to start the pubsub service as the topic operation is cancelled."];
  106. [self finishWithError:error];
  107. return;
  108. }
  109. [self setExecuting:YES];
  110. [self performSubscriptionChange];
  111. }
  112. - (void)finishWithError:(NSError *)error {
  113. // Add a check to prevent this finish from being called more than once.
  114. if (self.isFinished) {
  115. return;
  116. }
  117. self.dataTask = nil;
  118. if (self.completion) {
  119. self.completion(error);
  120. }
  121. [self setExecuting:NO];
  122. [self setFinished:YES];
  123. }
  124. - (void)cancel {
  125. [super cancel];
  126. [self.dataTask cancel];
  127. NSError *error = [NSError messagingErrorWithCode:kFIRMessagingErrorCodePubSubOperationIsCancelled
  128. failureReason:@"The topic operation is cancelled."];
  129. [self finishWithError:error];
  130. }
  131. - (void)performSubscriptionChange {
  132. NSURL *url = [NSURL URLWithString:FIRMessagingSubscriptionsServer()];
  133. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  134. NSString *appIdentifier = FIRMessagingAppIdentifier();
  135. NSString *authString = [NSString
  136. stringWithFormat:@"AidLogin %@:%@", _tokenManager.deviceAuthID, _tokenManager.secretToken];
  137. [request setValue:authString forHTTPHeaderField:@"Authorization"];
  138. [request setValue:appIdentifier forHTTPHeaderField:@"app"];
  139. [request setValue:_tokenManager.versionInfo forHTTPHeaderField:@"info"];
  140. // Topic can contain special characters (like `%`) so encode the value.
  141. NSCharacterSet *characterSet = [NSCharacterSet URLQueryAllowedCharacterSet];
  142. NSString *encodedTopic =
  143. [self.topic stringByAddingPercentEncodingWithAllowedCharacters:characterSet];
  144. if (encodedTopic == nil) {
  145. // The transformation was somehow not possible, so use the original topic.
  146. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTopicOptionTopicEncodingFailed,
  147. @"Unable to encode the topic '%@' during topic subscription change. "
  148. @"Please ensure that the topic name contains only valid characters.",
  149. self.topic);
  150. encodedTopic = self.topic;
  151. }
  152. NSMutableString *content = [NSMutableString
  153. stringWithFormat:@"sender=%@&app=%@&device=%@&"
  154. @"app_ver=%@&X-gcm.topic=%@&X-scope=%@",
  155. _tokenManager.defaultFCMToken, appIdentifier, _tokenManager.deviceAuthID,
  156. FIRMessagingCurrentAppVersion(), encodedTopic, encodedTopic];
  157. if (self.action == FIRMessagingTopicActionUnsubscribe) {
  158. [content appendString:@"&delete=true"];
  159. }
  160. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeTopicOption000, @"Topic subscription request: %@",
  161. content);
  162. request.HTTPBody = [content dataUsingEncoding:NSUTF8StringEncoding];
  163. [request setHTTPMethod:@"POST"];
  164. FIRMessaging_WEAKIFY(self) void (^requestHandler)(NSData *, NSURLResponse *, NSError *) =
  165. ^(NSData *data, NSURLResponse *URLResponse, NSError *error) {
  166. FIRMessaging_STRONGIFY(self) if (error) {
  167. // Our operation could have been cancelled, which would result in our data task's error
  168. // being NSURLErrorCancelled
  169. if (error.code == NSURLErrorCancelled) {
  170. // We would only have been cancelled in the -cancel method, which will call finish for
  171. // us so just return and do nothing.
  172. return;
  173. }
  174. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOption001,
  175. @"Device registration HTTP fetch error. Error Code: %ld",
  176. (long)error.code);
  177. [self finishWithError:error];
  178. return;
  179. }
  180. NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  181. if (response.length == 0) {
  182. NSString *failureReason = @"Invalid registration response - zero length.";
  183. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOperationEmptyResponse, @"%@",
  184. failureReason);
  185. [self finishWithError:[NSError messagingErrorWithCode:kFIRMessagingErrorCodeUnknown
  186. failureReason:failureReason]];
  187. return;
  188. }
  189. NSArray *parts = [response componentsSeparatedByString:@"="];
  190. if (![parts[0] isEqualToString:@"token"] || parts.count <= 1) {
  191. NSString *failureReason = [NSString
  192. stringWithFormat:@"Invalid registration response :'%@'. It is missing 'token' field.",
  193. response];
  194. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOption002, @"%@", failureReason);
  195. [self finishWithError:[NSError messagingErrorWithCode:kFIRMessagingErrorCodeUnknown
  196. failureReason:failureReason]];
  197. return;
  198. }
  199. [self finishWithError:nil];
  200. };
  201. NSURLSession *urlSession = [FIRMessagingTopicOperation sharedSession];
  202. self.dataTask = [urlSession dataTaskWithRequest:request completionHandler:requestHandler];
  203. NSString *description;
  204. if (_action == FIRMessagingTopicActionSubscribe) {
  205. description = [NSString stringWithFormat:@"com.google.fcm.topics.subscribe: %@", _topic];
  206. } else {
  207. description = [NSString stringWithFormat:@"com.google.fcm.topics.unsubscribe: %@", _topic];
  208. }
  209. self.dataTask.taskDescription = description;
  210. [self.dataTask resume];
  211. }
  212. @end