You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

263 lines
9.1 KiB

6 years ago
  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. NSError *error =
  109. [NSError errorWithFCMErrorCode:kFIRMessagingErrorCodePubSubOperationIsCancelled];
  110. [self finishWithError:error];
  111. return;
  112. }
  113. [self setExecuting:YES];
  114. [self performSubscriptionChange];
  115. }
  116. - (void)finishWithError:(NSError *)error {
  117. // Add a check to prevent this finish from being called more than once.
  118. if (self.isFinished) {
  119. return;
  120. }
  121. self.dataTask = nil;
  122. if (self.completion) {
  123. self.completion(error);
  124. }
  125. [self setExecuting:NO];
  126. [self setFinished:YES];
  127. }
  128. - (void)cancel {
  129. [super cancel];
  130. [self.dataTask cancel];
  131. NSError *error = [NSError errorWithFCMErrorCode:kFIRMessagingErrorCodePubSubOperationIsCancelled];
  132. [self finishWithError:error];
  133. }
  134. - (void)performSubscriptionChange {
  135. NSURL *url = [NSURL URLWithString:FIRMessagingSubscriptionsServer()];
  136. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  137. NSString *appIdentifier = FIRMessagingAppIdentifier();
  138. NSString *deviceAuthID = self.checkinService.deviceAuthID;
  139. NSString *secretToken = self.checkinService.secretToken;
  140. NSString *authString = [NSString stringWithFormat:@"AidLogin %@:%@", deviceAuthID, secretToken];
  141. [request setValue:authString forHTTPHeaderField:@"Authorization"];
  142. [request setValue:appIdentifier forHTTPHeaderField:@"app"];
  143. [request setValue:self.checkinService.versionInfo forHTTPHeaderField:@"info"];
  144. // Topic can contain special characters (like `%`) so encode the value.
  145. NSCharacterSet *characterSet = [NSCharacterSet URLQueryAllowedCharacterSet];
  146. NSString *encodedTopic =
  147. [self.topic stringByAddingPercentEncodingWithAllowedCharacters:characterSet];
  148. if (encodedTopic == nil) {
  149. // The transformation was somehow not possible, so use the original topic.
  150. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTopicOptionTopicEncodingFailed,
  151. @"Unable to encode the topic '%@' during topic subscription change. "
  152. @"Please ensure that the topic name contains only valid characters.",
  153. self.topic);
  154. encodedTopic = self.topic;
  155. }
  156. NSMutableString *content = [NSMutableString stringWithFormat:
  157. @"sender=%@&app=%@&device=%@&"
  158. @"app_ver=%@&X-gcm.topic=%@&X-scope=%@",
  159. self.token,
  160. appIdentifier,
  161. deviceAuthID,
  162. FIRMessagingCurrentAppVersion(),
  163. encodedTopic,
  164. encodedTopic];
  165. if (self.action == FIRMessagingTopicActionUnsubscribe) {
  166. [content appendString:@"&delete=true"];
  167. }
  168. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeTopicOption000, @"Topic subscription request: %@",
  169. content);
  170. request.HTTPBody = [content dataUsingEncoding:NSUTF8StringEncoding];
  171. [request setHTTPMethod:@"POST"];
  172. #if DEBUG_LOG_SUBSCRIPTION_OPERATION_DURATIONS
  173. NSDate *start = [NSDate date];
  174. #endif
  175. FIRMessaging_WEAKIFY(self)
  176. void(^requestHandler)(NSData *, NSURLResponse *, NSError *) =
  177. ^(NSData *data, NSURLResponse *URLResponse, NSError *error) {
  178. FIRMessaging_STRONGIFY(self)
  179. if (error) {
  180. // Our operation could have been cancelled, which would result in our data task's error being
  181. // NSURLErrorCancelled
  182. if (error.code == NSURLErrorCancelled) {
  183. // We would only have been cancelled in the -cancel method, which will call finish for us
  184. // so just return and do nothing.
  185. return;
  186. }
  187. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOption001,
  188. @"Device registration HTTP fetch error. Error Code: %ld",
  189. _FIRMessaging_L(error.code));
  190. [self finishWithError:error];
  191. return;
  192. }
  193. NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  194. if (response.length == 0) {
  195. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOperationEmptyResponse,
  196. @"Invalid registration response - zero length.");
  197. [self finishWithError:[NSError errorWithFCMErrorCode:kFIRMessagingErrorCodeUnknown]];
  198. return;
  199. }
  200. NSArray *parts = [response componentsSeparatedByString:@"="];
  201. _FIRMessagingDevAssert(parts.count, @"Invalid registration response");
  202. if (![parts[0] isEqualToString:@"token"] || parts.count <= 1) {
  203. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOption002,
  204. @"Invalid registration response %@", response);
  205. [self finishWithError:[NSError errorWithFCMErrorCode:kFIRMessagingErrorCodeUnknown]];
  206. return;
  207. }
  208. #if DEBUG_LOG_SUBSCRIPTION_OPERATION_DURATIONS
  209. NSTimeInterval duration = -[start timeIntervalSinceNow];
  210. FIRMessagingLoggerDebug(@"%@ change took %.2fs", self.topic, duration);
  211. #endif
  212. [self finishWithError:nil];
  213. };
  214. NSURLSession *urlSession = [FIRMessagingTopicOperation sharedSession];
  215. self.dataTask = [urlSession dataTaskWithRequest:request completionHandler:requestHandler];
  216. NSString *description;
  217. if (_action == FIRMessagingTopicActionSubscribe) {
  218. description = [NSString stringWithFormat:@"com.google.fcm.topics.subscribe: %@", _topic];
  219. } else {
  220. description = [NSString stringWithFormat:@"com.google.fcm.topics.unsubscribe: %@", _topic];
  221. }
  222. self.dataTask.taskDescription = description;
  223. [self.dataTask resume];
  224. }
  225. @end