FIRMessagingTopicOperation.m 9.1 KB

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