FIRInstallationsAPIService.m 12 KB

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