FIRInstallationsAPIService.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /*
  2. * Copyright 2019 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 "FIRInstallationsAPIService.h"
  17. #import <FirebaseInstallations/FIRInstallationsVersion.h>
  18. #if __has_include(<FBLPromises/FBLPromises.h>)
  19. #import <FBLPromises/FBLPromises.h>
  20. #else
  21. #import "FBLPromises.h"
  22. #endif
  23. #import "FIRInstallationsErrorUtil.h"
  24. #import "FIRInstallationsItem+RegisterInstallationAPI.h"
  25. #import "FIRInstallationsLogger.h"
  26. NSString *const kFIRInstallationsAPIBaseURL = @"https://firebaseinstallations.googleapis.com";
  27. NSString *const kFIRInstallationsAPIKey = @"X-Goog-Api-Key";
  28. NS_ASSUME_NONNULL_BEGIN
  29. @interface FIRInstallationsURLSessionResponse : NSObject
  30. @property(nonatomic) NSHTTPURLResponse *HTTPResponse;
  31. @property(nonatomic) NSData *data;
  32. - (instancetype)initWithResponse:(NSHTTPURLResponse *)response data:(nullable NSData *)data;
  33. @end
  34. @implementation FIRInstallationsURLSessionResponse
  35. - (instancetype)initWithResponse:(NSHTTPURLResponse *)response data:(nullable NSData *)data {
  36. self = [super init];
  37. if (self) {
  38. _HTTPResponse = response;
  39. _data = data ?: [NSData data];
  40. }
  41. return self;
  42. }
  43. @end
  44. @interface FIRInstallationsAPIService ()
  45. @property(nonatomic, readonly) NSURLSession *URLSession;
  46. @end
  47. NS_ASSUME_NONNULL_END
  48. @implementation FIRInstallationsAPIService
  49. - (instancetype)initWithAPIKey:(NSString *)APIKey projectID:(NSString *)projectID {
  50. NSURLSession *URLSession = [NSURLSession
  51. sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  52. return [self initWithURLSession:URLSession APIKey:APIKey projectID:projectID];
  53. }
  54. /// The initializer for tests.
  55. - (instancetype)initWithURLSession:(NSURLSession *)URLSession
  56. APIKey:(NSString *)APIKey
  57. projectID:(NSString *)projectID {
  58. self = [super init];
  59. if (self) {
  60. _URLSession = URLSession;
  61. _APIKey = [APIKey copy];
  62. _projectID = [projectID copy];
  63. }
  64. return self;
  65. }
  66. #pragma mark - Public
  67. - (FBLPromise<FIRInstallationsItem *> *)registerInstallation:(FIRInstallationsItem *)installation {
  68. NSURLRequest *request = [self registerRequestWithInstallation:installation];
  69. return [self sendURLRequest:request].then(
  70. ^id _Nullable(FIRInstallationsURLSessionResponse *response) {
  71. return [self registeredInstallationWithInstallation:installation serverResponse:response];
  72. });
  73. }
  74. - (FBLPromise<FIRInstallationsItem *> *)refreshAuthTokenForInstallation:
  75. (FIRInstallationsItem *)installation {
  76. NSURLRequest *request = [self authTokenRequestWithInstallation:installation];
  77. return [self sendURLRequest:request]
  78. .then(^FBLPromise<FIRInstallationsStoredAuthToken *> *(
  79. FIRInstallationsURLSessionResponse *response) {
  80. return [self authTokenWithServerResponse:response];
  81. })
  82. .then(^FIRInstallationsItem *(FIRInstallationsStoredAuthToken *authToken) {
  83. FIRInstallationsItem *updatedInstallation = [installation copy];
  84. updatedInstallation.authToken = authToken;
  85. return updatedInstallation;
  86. });
  87. }
  88. - (FBLPromise<FIRInstallationsItem *> *)deleteInstallation:(FIRInstallationsItem *)installation {
  89. NSURLRequest *request = [self deleteInstallationRequestWithInstallation:installation];
  90. return [[self sendURLRequest:request]
  91. then:^id _Nullable(FIRInstallationsURLSessionResponse *_Nullable value) {
  92. // Return the original installation on success.
  93. return installation;
  94. }];
  95. }
  96. #pragma mark - Register Installation
  97. - (NSURLRequest *)registerRequestWithInstallation:(FIRInstallationsItem *)installation {
  98. NSString *URLString = [NSString stringWithFormat:@"%@/v1/projects/%@/installations/",
  99. kFIRInstallationsAPIBaseURL, self.projectID];
  100. NSURL *URL = [NSURL URLWithString:URLString];
  101. NSDictionary *bodyDict = @{
  102. @"fid" : installation.firebaseInstallationID,
  103. @"authVersion" : @"FIS_v2",
  104. @"appId" : installation.appID,
  105. @"sdkVersion" : [self SDKVersion]
  106. };
  107. return [self requestWithURL:URL HTTPMethod:@"POST" bodyDict:bodyDict refreshToken:nil];
  108. }
  109. - (FBLPromise<FIRInstallationsItem *> *)
  110. registeredInstallationWithInstallation:(FIRInstallationsItem *)installation
  111. serverResponse:(FIRInstallationsURLSessionResponse *)response {
  112. return [FBLPromise do:^id {
  113. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeParsingAPIResponse,
  114. @"Parsing server response for %@.", response.HTTPResponse.URL);
  115. NSError *error;
  116. FIRInstallationsItem *registeredInstallation =
  117. [installation registeredInstallationWithJSONData:response.data
  118. date:[NSDate date]
  119. error:&error];
  120. if (registeredInstallation == nil) {
  121. FIRLogDebug(kFIRLoggerInstallations,
  122. kFIRInstallationsMessageCodeAPIResponseParsingInstallationFailed,
  123. @"Failed to parse FIRInstallationsItem: %@.", error);
  124. return error;
  125. }
  126. FIRLogDebug(kFIRLoggerInstallations,
  127. kFIRInstallationsMessageCodeAPIResponseParsingInstallationSucceed,
  128. @"FIRInstallationsItem parsed successfully.");
  129. return registeredInstallation;
  130. }];
  131. }
  132. #pragma mark - Auth token
  133. - (NSURLRequest *)authTokenRequestWithInstallation:(FIRInstallationsItem *)installation {
  134. NSString *URLString =
  135. [NSString stringWithFormat:@"%@/v1/projects/%@/installations/%@/authTokens:generate",
  136. kFIRInstallationsAPIBaseURL, self.projectID,
  137. installation.firebaseInstallationID];
  138. NSURL *URL = [NSURL URLWithString:URLString];
  139. NSDictionary *bodyDict = @{@"installation" : @{@"sdkVersion" : [self SDKVersion]}};
  140. return [self requestWithURL:URL
  141. HTTPMethod:@"POST"
  142. bodyDict:bodyDict
  143. refreshToken:installation.refreshToken];
  144. }
  145. - (FBLPromise<FIRInstallationsStoredAuthToken *> *)authTokenWithServerResponse:
  146. (FIRInstallationsURLSessionResponse *)response {
  147. return [FBLPromise do:^id {
  148. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeParsingAPIResponse,
  149. @"Parsing server response for %@.", response.HTTPResponse.URL);
  150. NSError *error;
  151. FIRInstallationsStoredAuthToken *token =
  152. [FIRInstallationsItem authTokenWithGenerateTokenAPIJSONData:response.data
  153. date:[NSDate date]
  154. error:&error];
  155. if (token == nil) {
  156. FIRLogDebug(kFIRLoggerInstallations,
  157. kFIRInstallationsMessageCodeAPIResponseParsingAuthTokenFailed,
  158. @"Failed to parse FIRInstallationsStoredAuthToken: %@.", error);
  159. return error;
  160. }
  161. FIRLogDebug(kFIRLoggerInstallations,
  162. kFIRInstallationsMessageCodeAPIResponseParsingAuthTokenSucceed,
  163. @"FIRInstallationsStoredAuthToken parsed successfully.");
  164. return token;
  165. }];
  166. }
  167. #pragma mark - Delete Installation
  168. - (NSURLRequest *)deleteInstallationRequestWithInstallation:(FIRInstallationsItem *)installation {
  169. NSString *URLString = [NSString stringWithFormat:@"%@/v1/projects/%@/installations/%@/",
  170. kFIRInstallationsAPIBaseURL, self.projectID,
  171. installation.firebaseInstallationID];
  172. NSURL *URL = [NSURL URLWithString:URLString];
  173. return [self requestWithURL:URL
  174. HTTPMethod:@"DELETE"
  175. bodyDict:@{}
  176. refreshToken:installation.refreshToken];
  177. }
  178. #pragma mark - URL Request
  179. - (NSURLRequest *)requestWithURL:(NSURL *)requestURL
  180. HTTPMethod:(NSString *)HTTPMethod
  181. bodyDict:(NSDictionary *)bodyDict
  182. refreshToken:(nullable NSString *)refreshToken {
  183. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];
  184. request.HTTPMethod = HTTPMethod;
  185. [request addValue:self.APIKey forHTTPHeaderField:kFIRInstallationsAPIKey];
  186. [self setJSONHTTPBody:bodyDict forRequest:request];
  187. if (refreshToken) {
  188. NSString *authHeader = [NSString stringWithFormat:@"FIS_v2 %@", refreshToken];
  189. [request setValue:authHeader forHTTPHeaderField:@"Authorization"];
  190. }
  191. return [request copy];
  192. }
  193. - (FBLPromise<FIRInstallationsURLSessionResponse *> *)URLRequestPromise:(NSURLRequest *)request {
  194. return [[FBLPromise async:^(FBLPromiseFulfillBlock fulfill, FBLPromiseRejectBlock reject) {
  195. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeSendAPIRequest,
  196. @"Sending request: %@, body:%@, headers: %@.", request,
  197. [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding],
  198. request.allHTTPHeaderFields);
  199. [[self.URLSession
  200. dataTaskWithRequest:request
  201. completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response,
  202. NSError *_Nullable error) {
  203. if (error) {
  204. FIRLogDebug(kFIRLoggerInstallations,
  205. kFIRInstallationsMessageCodeAPIRequestNetworkError,
  206. @"Request failed: %@, error: %@.", request, error);
  207. reject(error);
  208. } else {
  209. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeAPIRequestResponse,
  210. @"Request response received: %@, error: %@, body: %@.", request, error,
  211. [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
  212. fulfill([[FIRInstallationsURLSessionResponse alloc]
  213. initWithResponse:(NSHTTPURLResponse *)response
  214. data:data]);
  215. }
  216. }] resume];
  217. }] then:^id _Nullable(FIRInstallationsURLSessionResponse *response) {
  218. return [self validateHTTPResponseStatusCode:response];
  219. }];
  220. }
  221. - (FBLPromise<FIRInstallationsURLSessionResponse *> *)validateHTTPResponseStatusCode:
  222. (FIRInstallationsURLSessionResponse *)response {
  223. NSInteger statusCode = response.HTTPResponse.statusCode;
  224. return [FBLPromise do:^id _Nullable {
  225. if (statusCode < 200 || statusCode >= 300) {
  226. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeUnexpectedAPIRequestResponse,
  227. @"Unexpected API response: %@, body: %@.", response.HTTPResponse,
  228. [[NSString alloc] initWithData:response.data encoding:NSUTF8StringEncoding]);
  229. return [FIRInstallationsErrorUtil APIErrorWithHTTPResponse:response.HTTPResponse
  230. data:response.data];
  231. }
  232. return response;
  233. }];
  234. }
  235. - (FBLPromise<FIRInstallationsURLSessionResponse *> *)sendURLRequest:(NSURLRequest *)request {
  236. return [FBLPromise attempts:1
  237. delay:1
  238. condition:^BOOL(NSInteger remainingAttempts, NSError *_Nonnull error) {
  239. return [FIRInstallationsErrorUtil isAPIError:error withHTTPCode:500];
  240. }
  241. retry:^id _Nullable {
  242. return [self URLRequestPromise:request];
  243. }];
  244. }
  245. - (NSString *)SDKVersion {
  246. return [NSString stringWithFormat:@"i:%s", FIRInstallationsVersionStr];
  247. }
  248. #pragma mark - JSON
  249. - (void)setJSONHTTPBody:(NSDictionary<NSString *, id> *)body
  250. forRequest:(NSMutableURLRequest *)request {
  251. [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  252. NSError *error;
  253. NSData *JSONData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
  254. if (JSONData == nil) {
  255. // TODO: Log or return an error.
  256. }
  257. request.HTTPBody = JSONData;
  258. }
  259. @end