FIRMessagingTopicOperation.m 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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 "Firebase/InstanceID/Private/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. #pragma clang diagnostic push
  137. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  138. NSString *deviceAuthID = [FIRInstanceID instanceID].deviceAuthID;
  139. NSString *secretToken = [FIRInstanceID instanceID].secretToken;
  140. NSString *authString = [NSString stringWithFormat:@"AidLogin %@:%@", deviceAuthID, secretToken];
  141. [request setValue:authString forHTTPHeaderField:@"Authorization"];
  142. [request setValue:appIdentifier forHTTPHeaderField:@"app"];
  143. [request setValue:[FIRInstanceID instanceID].versionInfo forHTTPHeaderField:@"info"];
  144. #pragma clang diagnostic pop
  145. // Topic can contain special characters (like `%`) so encode the value.
  146. NSCharacterSet *characterSet = [NSCharacterSet URLQueryAllowedCharacterSet];
  147. NSString *encodedTopic =
  148. [self.topic stringByAddingPercentEncodingWithAllowedCharacters:characterSet];
  149. if (encodedTopic == nil) {
  150. // The transformation was somehow not possible, so use the original topic.
  151. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTopicOptionTopicEncodingFailed,
  152. @"Unable to encode the topic '%@' during topic subscription change. "
  153. @"Please ensure that the topic name contains only valid characters.",
  154. self.topic);
  155. encodedTopic = self.topic;
  156. }
  157. NSMutableString *content = [NSMutableString
  158. stringWithFormat:@"sender=%@&app=%@&device=%@&"
  159. @"app_ver=%@&X-gcm.topic=%@&X-scope=%@",
  160. self.token, appIdentifier, deviceAuthID, FIRMessagingCurrentAppVersion(),
  161. encodedTopic, encodedTopic];
  162. if (self.action == FIRMessagingTopicActionUnsubscribe) {
  163. [content appendString:@"&delete=true"];
  164. }
  165. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeTopicOption000, @"Topic subscription request: %@",
  166. content);
  167. request.HTTPBody = [content dataUsingEncoding:NSUTF8StringEncoding];
  168. [request setHTTPMethod:@"POST"];
  169. FIRMessaging_WEAKIFY(self) void (^requestHandler)(NSData *, NSURLResponse *, NSError *) =
  170. ^(NSData *data, NSURLResponse *URLResponse, NSError *error) {
  171. FIRMessaging_STRONGIFY(self) if (error) {
  172. // Our operation could have been cancelled, which would result in our data task's error
  173. // being NSURLErrorCancelled
  174. if (error.code == NSURLErrorCancelled) {
  175. // We would only have been cancelled in the -cancel method, which will call finish for
  176. // us so just return and do nothing.
  177. return;
  178. }
  179. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOption001,
  180. @"Device registration HTTP fetch error. Error Code: %ld",
  181. (long)error.code);
  182. [self finishWithError:error];
  183. return;
  184. }
  185. NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  186. if (response.length == 0) {
  187. NSString *failureReason = @"Invalid registration response - zero length.";
  188. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOperationEmptyResponse, @"%@",
  189. failureReason);
  190. [self finishWithError:[NSError messagingErrorWithCode:kFIRMessagingErrorCodeUnknown
  191. failureReason:failureReason]];
  192. return;
  193. }
  194. NSArray *parts = [response componentsSeparatedByString:@"="];
  195. if (![parts[0] isEqualToString:@"token"] || parts.count <= 1) {
  196. NSString *failureReason = [NSString
  197. stringWithFormat:@"Invalid registration response :'%@'. It is missing 'token' field.",
  198. response];
  199. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOption002, @"%@", failureReason);
  200. [self finishWithError:[NSError messagingErrorWithCode:kFIRMessagingErrorCodeUnknown
  201. failureReason:failureReason]];
  202. return;
  203. }
  204. [self finishWithError:nil];
  205. };
  206. NSURLSession *urlSession = [FIRMessagingTopicOperation sharedSession];
  207. self.dataTask = [urlSession dataTaskWithRequest:request completionHandler:requestHandler];
  208. NSString *description;
  209. if (_action == FIRMessagingTopicActionSubscribe) {
  210. description = [NSString stringWithFormat:@"com.google.fcm.topics.subscribe: %@", _topic];
  211. } else {
  212. description = [NSString stringWithFormat:@"com.google.fcm.topics.unsubscribe: %@", _topic];
  213. }
  214. self.dataTask.taskDescription = description;
  215. [self.dataTask resume];
  216. }
  217. @end