FIRMessagingTopicOperation.m 9.1 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 "FIRMessagingCheckinService.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, strong) FIRMessagingCheckinService *checkinService;
  48. @property(nonatomic, readwrite, copy) FIRMessagingTopicOperationCompletion completion;
  49. @property(atomic, strong) NSURLSessionDataTask *dataTask;
  50. @end
  51. @implementation FIRMessagingTopicOperation
  52. + (NSURLSession *)sharedSession {
  53. static NSURLSession *subscriptionOperationSharedSession;
  54. static dispatch_once_t onceToken;
  55. dispatch_once(&onceToken, ^{
  56. NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
  57. config.timeoutIntervalForResource = 60.0f; // 1 minute
  58. subscriptionOperationSharedSession = [NSURLSession sessionWithConfiguration:config];
  59. subscriptionOperationSharedSession.sessionDescription = @"com.google.fcm.topics.session";
  60. });
  61. return subscriptionOperationSharedSession;
  62. }
  63. - (instancetype)initWithTopic:(NSString *)topic
  64. action:(FIRMessagingTopicAction)action
  65. token:(NSString *)token
  66. options:(NSDictionary *)options
  67. checkinService:(FIRMessagingCheckinService *)checkinService
  68. completion:(FIRMessagingTopicOperationCompletion)completion {
  69. if (self = [super init]) {
  70. _topic = topic;
  71. _action = action;
  72. _token = token;
  73. _options = options;
  74. _checkinService = checkinService;
  75. _completion = completion;
  76. _isExecuting = NO;
  77. _isFinished = NO;
  78. }
  79. return self;
  80. }
  81. - (void)dealloc {
  82. _topic = nil;
  83. _token = nil;
  84. _checkinService = nil;
  85. _completion = nil;
  86. }
  87. - (BOOL)isAsynchronous {
  88. return YES;
  89. }
  90. - (BOOL)isExecuting {
  91. return _isExecuting;
  92. }
  93. - (void)setExecuting:(BOOL)executing {
  94. [self willChangeValueForKey:@"isExecuting"];
  95. _isExecuting = executing;
  96. [self didChangeValueForKey:@"isExecuting"];
  97. }
  98. - (BOOL)isFinished {
  99. return _isFinished;
  100. }
  101. - (void)setFinished:(BOOL)finished {
  102. [self willChangeValueForKey:@"isFinished"];
  103. _isFinished = finished;
  104. [self didChangeValueForKey:@"isFinished"];
  105. }
  106. - (void)start {
  107. if (self.isCancelled) {
  108. [self finishWithResult:FIRMessagingTopicOperationResultCancelled error:nil];
  109. return;
  110. }
  111. [self setExecuting:YES];
  112. [self performSubscriptionChange];
  113. }
  114. - (void)finishWithResult:(FIRMessagingTopicOperationResult)result error:(NSError *)error {
  115. // Add a check to prevent this finish from being called more than once.
  116. if (self.isFinished) {
  117. return;
  118. }
  119. self.dataTask = nil;
  120. if (self.completion) {
  121. self.completion(result, error);
  122. }
  123. [self setExecuting:NO];
  124. [self setFinished:YES];
  125. }
  126. - (void)cancel {
  127. [super cancel];
  128. [self.dataTask cancel];
  129. [self finishWithResult:FIRMessagingTopicOperationResultCancelled error:nil];
  130. }
  131. - (void)performSubscriptionChange {
  132. NSURL *url = [NSURL URLWithString:FIRMessagingSubscriptionsServer()];
  133. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  134. NSString *appIdentifier = FIRMessagingAppIdentifier();
  135. NSString *deviceAuthID = self.checkinService.deviceAuthID;
  136. NSString *secretToken = self.checkinService.secretToken;
  137. NSString *authString = [NSString stringWithFormat:@"AidLogin %@:%@", deviceAuthID, secretToken];
  138. [request setValue:authString forHTTPHeaderField:@"Authorization"];
  139. [request setValue:appIdentifier forHTTPHeaderField:@"app"];
  140. [request setValue:self.checkinService.versionInfo forHTTPHeaderField:@"info"];
  141. // Topic can contain special characters (like `%`) so encode the value.
  142. NSCharacterSet *characterSet = [NSCharacterSet URLQueryAllowedCharacterSet];
  143. NSString *encodedTopic =
  144. [self.topic stringByAddingPercentEncodingWithAllowedCharacters:characterSet];
  145. if (encodedTopic == nil) {
  146. // The transformation was somehow not possible, so use the original topic.
  147. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTopicOptionTopicEncodingFailed,
  148. @"Unable to encode the topic '%@' during topic subscription change. "
  149. @"Please ensure that the topic name contains only valid characters.",
  150. self.topic);
  151. encodedTopic = self.topic;
  152. }
  153. NSMutableString *content = [NSMutableString stringWithFormat:
  154. @"sender=%@&app=%@&device=%@&"
  155. @"app_ver=%@&X-gcm.topic=%@&X-scope=%@",
  156. self.token,
  157. appIdentifier,
  158. deviceAuthID,
  159. FIRMessagingCurrentAppVersion(),
  160. encodedTopic,
  161. 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. #if DEBUG_LOG_SUBSCRIPTION_OPERATION_DURATIONS
  170. NSDate *start = [NSDate date];
  171. #endif
  172. FIRMessaging_WEAKIFY(self)
  173. void(^requestHandler)(NSData *, NSURLResponse *, NSError *) =
  174. ^(NSData *data, NSURLResponse *URLResponse, NSError *error) {
  175. FIRMessaging_STRONGIFY(self)
  176. if (error) {
  177. // Our operation could have been cancelled, which would result in our data task's error being
  178. // NSURLErrorCancelled
  179. if (error.code == NSURLErrorCancelled) {
  180. // We would only have been cancelled in the -cancel method, which will call finish for us
  181. // so just return and do nothing.
  182. return;
  183. }
  184. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOption001,
  185. @"Device registration HTTP fetch error. Error Code: %ld",
  186. _FIRMessaging_L(error.code));
  187. [self finishWithResult:FIRMessagingTopicOperationResultError error:error];
  188. return;
  189. }
  190. NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  191. if (response.length == 0) {
  192. [self finishWithResult:FIRMessagingTopicOperationResultError
  193. error:[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 request, response");
  201. [self finishWithResult:FIRMessagingTopicOperationResultError
  202. error:[NSError errorWithFCMErrorCode:kFIRMessagingErrorCodeUnknown]];
  203. return;
  204. }
  205. #if DEBUG_LOG_SUBSCRIPTION_OPERATION_DURATIONS
  206. NSTimeInterval duration = -[start timeIntervalSinceNow];
  207. FIRMessagingLoggerDebug(@"%@ change took %.2fs", self.topic, duration);
  208. #endif
  209. [self finishWithResult:FIRMessagingTopicOperationResultSucceeded error:nil];
  210. };
  211. NSURLSession *urlSession = [FIRMessagingTopicOperation sharedSession];
  212. self.dataTask = [urlSession dataTaskWithRequest:request completionHandler:requestHandler];
  213. NSString *description;
  214. if (_action == FIRMessagingTopicActionSubscribe) {
  215. description = [NSString stringWithFormat:@"com.google.fcm.topics.subscribe: %@", _topic];
  216. } else {
  217. description = [NSString stringWithFormat:@"com.google.fcm.topics.unsubscribe: %@", _topic];
  218. }
  219. self.dataTask.taskDescription = description;
  220. [self.dataTask resume];
  221. }
  222. @end