FIRMessagingTopicOperation.m 8.5 KB

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