FIRMessagingTopicOperation.m 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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 "FIRMessagingTopicOperation.h"
  17. #import <FirebaseInstanceID/FIRInstanceID_Private.h>
  18. #import "FIRMessagingDefines.h"
  19. #import "FIRMessagingLogger.h"
  20. #import "FIRMessagingUtilities.h"
  21. #import "NSError+FIRMessaging.h"
  22. #define DEBUG_LOG_SUBSCRIPTION_OPERATION_DURATIONS 0
  23. static NSString *const kFIRMessagingSubscribeServerHost =
  24. @"https://iid.googleapis.com/iid/register";
  25. NSString *FIRMessagingSubscriptionsServer() {
  26. static NSString *serverHost = nil;
  27. static dispatch_once_t onceToken;
  28. dispatch_once(&onceToken, ^{
  29. NSDictionary *environment = [[NSProcessInfo processInfo] environment];
  30. NSString *customServerHost = environment[@"FCM_SERVER_ENDPOINT"];
  31. if (customServerHost.length) {
  32. serverHost = customServerHost;
  33. } else {
  34. serverHost = kFIRMessagingSubscribeServerHost;
  35. }
  36. });
  37. return serverHost;
  38. }
  39. @interface FIRMessagingTopicOperation () {
  40. BOOL _isFinished;
  41. BOOL _isExecuting;
  42. }
  43. @property(nonatomic, readwrite, copy) NSString *topic;
  44. @property(nonatomic, readwrite, assign) FIRMessagingTopicAction action;
  45. @property(nonatomic, readwrite, copy) NSString *token;
  46. @property(nonatomic, readwrite, copy) NSDictionary *options;
  47. @property(nonatomic, readwrite, copy) FIRMessagingTopicOperationCompletion completion;
  48. @property(atomic, strong) NSURLSessionDataTask *dataTask;
  49. @end
  50. @implementation FIRMessagingTopicOperation
  51. + (NSURLSession *)sharedSession {
  52. static NSURLSession *subscriptionOperationSharedSession;
  53. static dispatch_once_t onceToken;
  54. dispatch_once(&onceToken, ^{
  55. NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
  56. config.timeoutIntervalForResource = 60.0f; // 1 minute
  57. subscriptionOperationSharedSession = [NSURLSession sessionWithConfiguration:config];
  58. subscriptionOperationSharedSession.sessionDescription = @"com.google.fcm.topics.session";
  59. });
  60. return subscriptionOperationSharedSession;
  61. }
  62. - (instancetype)initWithTopic:(NSString *)topic
  63. action:(FIRMessagingTopicAction)action
  64. token:(NSString *)token
  65. options:(NSDictionary *)options
  66. completion:(FIRMessagingTopicOperationCompletion)completion {
  67. if (self = [super init]) {
  68. _topic = topic;
  69. _action = action;
  70. _token = token;
  71. _options = options;
  72. _completion = completion;
  73. _isExecuting = NO;
  74. _isFinished = NO;
  75. }
  76. return self;
  77. }
  78. - (void)dealloc {
  79. _topic = nil;
  80. _token = nil;
  81. _completion = nil;
  82. }
  83. - (BOOL)isAsynchronous {
  84. return YES;
  85. }
  86. - (BOOL)isExecuting {
  87. return _isExecuting;
  88. }
  89. - (void)setExecuting:(BOOL)executing {
  90. [self willChangeValueForKey:@"isExecuting"];
  91. _isExecuting = executing;
  92. [self didChangeValueForKey:@"isExecuting"];
  93. }
  94. - (BOOL)isFinished {
  95. return _isFinished;
  96. }
  97. - (void)setFinished:(BOOL)finished {
  98. [self willChangeValueForKey:@"isFinished"];
  99. _isFinished = finished;
  100. [self didChangeValueForKey:@"isFinished"];
  101. }
  102. - (void)start {
  103. if (self.isCancelled) {
  104. NSError *error =
  105. [NSError errorWithFCMErrorCode:kFIRMessagingErrorCodePubSubOperationIsCancelled];
  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 errorWithFCMErrorCode:kFIRMessagingErrorCodePubSubOperationIsCancelled];
  128. [self finishWithError:error];
  129. }
  130. - (void)performSubscriptionChange {
  131. NSURL *url = [NSURL URLWithString:FIRMessagingSubscriptionsServer()];
  132. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  133. NSString *appIdentifier = FIRMessagingAppIdentifier();
  134. NSString *deviceAuthID = [FIRInstanceID instanceID].deviceAuthID;
  135. NSString *secretToken = [FIRInstanceID instanceID].secretToken;
  136. NSString *authString = [NSString stringWithFormat:@"AidLogin %@:%@", deviceAuthID, secretToken];
  137. [request setValue:authString forHTTPHeaderField:@"Authorization"];
  138. [request setValue:appIdentifier forHTTPHeaderField:@"app"];
  139. [request setValue:[FIRInstanceID instanceID].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 stringWithFormat:
  153. @"sender=%@&app=%@&device=%@&"
  154. @"app_ver=%@&X-gcm.topic=%@&X-scope=%@",
  155. self.token,
  156. appIdentifier,
  157. deviceAuthID,
  158. FIRMessagingCurrentAppVersion(),
  159. encodedTopic,
  160. encodedTopic];
  161. if (self.action == FIRMessagingTopicActionUnsubscribe) {
  162. [content appendString:@"&delete=true"];
  163. }
  164. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeTopicOption000, @"Topic subscription request: %@",
  165. content);
  166. request.HTTPBody = [content dataUsingEncoding:NSUTF8StringEncoding];
  167. [request setHTTPMethod:@"POST"];
  168. #if DEBUG_LOG_SUBSCRIPTION_OPERATION_DURATIONS
  169. NSDate *start = [NSDate date];
  170. #endif
  171. FIRMessaging_WEAKIFY(self)
  172. void(^requestHandler)(NSData *, NSURLResponse *, NSError *) =
  173. ^(NSData *data, NSURLResponse *URLResponse, NSError *error) {
  174. FIRMessaging_STRONGIFY(self)
  175. if (error) {
  176. // Our operation could have been cancelled, which would result in our data task's error being
  177. // NSURLErrorCancelled
  178. if (error.code == NSURLErrorCancelled) {
  179. // We would only have been cancelled in the -cancel method, which will call finish for us
  180. // so just return and do nothing.
  181. return;
  182. }
  183. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOption001,
  184. @"Device registration HTTP fetch error. Error Code: %ld",
  185. _FIRMessaging_L(error.code));
  186. [self finishWithError:error];
  187. return;
  188. }
  189. NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  190. if (response.length == 0) {
  191. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOperationEmptyResponse,
  192. @"Invalid registration response - zero length.");
  193. [self finishWithError:[NSError errorWithFCMErrorCode:kFIRMessagingErrorCodeUnknown]];
  194. return;
  195. }
  196. NSArray *parts = [response componentsSeparatedByString:@"="];
  197. _FIRMessagingDevAssert(parts.count, @"Invalid registration response");
  198. if (![parts[0] isEqualToString:@"token"] || parts.count <= 1) {
  199. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOption002,
  200. @"Invalid registration response %@", response);
  201. [self finishWithError:[NSError errorWithFCMErrorCode:kFIRMessagingErrorCodeUnknown]];
  202. return;
  203. }
  204. #if DEBUG_LOG_SUBSCRIPTION_OPERATION_DURATIONS
  205. NSTimeInterval duration = -[start timeIntervalSinceNow];
  206. FIRMessagingLoggerDebug(@"%@ change took %.2fs", self.topic, duration);
  207. #endif
  208. [self finishWithError:nil];
  209. };
  210. NSURLSession *urlSession = [FIRMessagingTopicOperation sharedSession];
  211. self.dataTask = [urlSession dataTaskWithRequest:request completionHandler:requestHandler];
  212. NSString *description;
  213. if (_action == FIRMessagingTopicActionSubscribe) {
  214. description = [NSString stringWithFormat:@"com.google.fcm.topics.subscribe: %@", _topic];
  215. } else {
  216. description = [NSString stringWithFormat:@"com.google.fcm.topics.unsubscribe: %@", _topic];
  217. }
  218. self.dataTask.taskDescription = description;
  219. [self.dataTask resume];
  220. }
  221. @end