FIRIAMMsgFetcherUsingRestful.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 <FirebaseCore/FIRAppInternal.h>
  17. #import <FirebaseCore/FIRLogger.h>
  18. #import "FIRCore+InAppMessaging.h"
  19. #import "FIRIAMFetchFlow.h"
  20. #import "FIRIAMFetchResponseParser.h"
  21. #import "FIRIAMMessageContentDataWithImageURL.h"
  22. #import "FIRIAMMessageDefinition.h"
  23. #import "FIRIAMMsgFetcherUsingRestful.h"
  24. #import "FIRIAMSDKSettings.h"
  25. static NSInteger const SuccessHTTPStatusCode = 200;
  26. @interface FIRIAMMsgFetcherUsingRestful ()
  27. @property(readonly) NSURLSession *URLSession;
  28. @property(readonly, copy, nonatomic) NSString *serverHostName;
  29. @property(readonly, copy, nonatomic) NSString *appBundleID;
  30. @property(readonly, copy, nonatomic) NSString *httpProtocol;
  31. @property(readonly, copy, nonatomic) NSString *fbProjectNumber;
  32. @property(readonly, copy, nonatomic) NSString *apiKey;
  33. @property(readonly, copy, nonatomic) NSString *firebaseAppId;
  34. @property(readonly, nonatomic) FIRIAMServerMsgFetchStorage *fetchStorage;
  35. @property(readonly, nonatomic) FIRIAMClientInfoFetcher *clientInfoFetcher;
  36. @property(readonly, nonatomic) FIRIAMFetchResponseParser *responseParser;
  37. @end
  38. @implementation FIRIAMMsgFetcherUsingRestful
  39. - (instancetype)initWithHost:(NSString *)serverHost
  40. HTTPProtocol:(NSString *)HTTPProtocol
  41. project:(NSString *)fbProjectNumber
  42. firebaseApp:(NSString *)fbAppId
  43. APIKey:(NSString *)apiKey
  44. fetchStorage:(FIRIAMServerMsgFetchStorage *)fetchStorage
  45. instanceIDFetcher:(FIRIAMClientInfoFetcher *)clientInfoFetcher
  46. usingURLSession:(nullable NSURLSession *)URLSession
  47. responseParser:(FIRIAMFetchResponseParser *)responseParser {
  48. if (self = [super init]) {
  49. _URLSession = URLSession ? URLSession : [NSURLSession sharedSession];
  50. _serverHostName = [serverHost copy];
  51. _fbProjectNumber = [fbProjectNumber copy];
  52. _firebaseAppId = [fbAppId copy];
  53. _httpProtocol = [HTTPProtocol copy];
  54. _apiKey = [apiKey copy];
  55. _clientInfoFetcher = clientInfoFetcher;
  56. _fetchStorage = fetchStorage;
  57. _appBundleID = [NSBundle mainBundle].bundleIdentifier;
  58. _responseParser = responseParser;
  59. }
  60. return self;
  61. }
  62. - (void)updatePostFetchData:(NSMutableDictionary *)postData
  63. withImpressionList:(NSArray<FIRIAMImpressionRecord *> *)impressionList
  64. instanceIDString:(nonnull NSString *)IIDValue
  65. IIDToken:(nonnull NSString *)IIDToken {
  66. NSMutableArray *impressionListForPost = [[NSMutableArray alloc] init];
  67. for (FIRIAMImpressionRecord *nextImpressionRecord in impressionList) {
  68. NSDictionary *nextImpression = @{
  69. @"campaign_id" : nextImpressionRecord.messageID,
  70. @"impression_timestamp_millis" : @(nextImpressionRecord.impressionTimeInSeconds * 1000)
  71. };
  72. [impressionListForPost addObject:nextImpression];
  73. }
  74. [postData setObject:impressionListForPost forKey:@"already_seen_campaigns"];
  75. if (IIDValue) {
  76. NSDictionary *clientAppInfo = @{
  77. @"gmp_app_id" : self.firebaseAppId,
  78. @"app_instance_id" : IIDValue,
  79. @"app_instance_id_token" : IIDToken
  80. };
  81. [postData setObject:clientAppInfo forKey:@"requesting_client_app"];
  82. }
  83. NSMutableArray *clientSignals = [@{} mutableCopy];
  84. // set client signal fields only when they are present
  85. if ([self.clientInfoFetcher getAppVersion]) {
  86. [clientSignals setValue:[self.clientInfoFetcher getAppVersion] forKey:@"app_version"];
  87. }
  88. if ([self.clientInfoFetcher getOSVersion]) {
  89. [clientSignals setValue:[self.clientInfoFetcher getOSVersion] forKey:@"platform_version"];
  90. }
  91. if ([self.clientInfoFetcher getDeviceLanguageCode]) {
  92. [clientSignals setValue:[self.clientInfoFetcher getDeviceLanguageCode] forKey:@"language_code"];
  93. }
  94. if ([self.clientInfoFetcher getTimezone]) {
  95. [clientSignals setValue:[self.clientInfoFetcher getTimezone] forKey:@"time_zone"];
  96. }
  97. [postData setObject:clientSignals forKey:@"client_signals"];
  98. }
  99. - (void)fetchMessagesWithImpressionList:(NSArray<FIRIAMImpressionRecord *> *)impressonList
  100. withIIDvalue:(NSString *)iidValue
  101. IIDToken:(NSString *)iidToken
  102. completion:(FIRIAMFetchMessageCompletionHandler)completion {
  103. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  104. [request setHTTPMethod:@"POST"];
  105. if (_appBundleID.length) {
  106. // Handle the case in which the API key is being restricted to specific iOS app bundle,
  107. // which can be set on Google Cloud console side for API key credentials.
  108. [request addValue:_appBundleID forHTTPHeaderField:@"X-Ios-Bundle-Identifier"];
  109. }
  110. [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  111. [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
  112. [request addValue:iidToken forHTTPHeaderField:@"x-goog-firebase-installations-auth"];
  113. NSMutableDictionary *postFetchDict = [[NSMutableDictionary alloc] init];
  114. [self updatePostFetchData:postFetchDict
  115. withImpressionList:impressonList
  116. instanceIDString:iidValue
  117. IIDToken:iidToken];
  118. NSData *postFetchData = [NSJSONSerialization dataWithJSONObject:postFetchDict
  119. options:0
  120. error:nil];
  121. NSString *requestURLString = [NSString
  122. stringWithFormat:@"%@://%@/v1/sdkServing/projects/%@/eligibleCampaigns:fetch?key=%@",
  123. self.httpProtocol, self.serverHostName, self.fbProjectNumber, self.apiKey];
  124. [request setURL:[NSURL URLWithString:requestURLString]];
  125. [request setHTTPBody:postFetchData];
  126. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM130001",
  127. @"Making a restful API request for pulling messages with fetch POST body as %@ "
  128. "and request headers as %@",
  129. postFetchDict, request.allHTTPHeaderFields);
  130. NSURLSessionDataTask *postDataTask = [self.URLSession
  131. dataTaskWithRequest:request
  132. completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  133. if (error) {
  134. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM130002",
  135. @"Internal error: encountered error in pulling messages from server"
  136. ":%@",
  137. error);
  138. completion(nil, nil, 0, error);
  139. } else {
  140. if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
  141. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  142. if (httpResponse.statusCode == SuccessHTTPStatusCode) {
  143. // got response data successfully
  144. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM130007",
  145. @"Fetch API response headers are %@", [httpResponse allHeaderFields]);
  146. NSError *errorJson = nil;
  147. NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data
  148. options:kNilOptions
  149. error:&errorJson];
  150. if (errorJson) {
  151. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM130003",
  152. @"Failed to parse the response body as JSON string %@", errorJson);
  153. completion(nil, nil, 0, errorJson);
  154. } else {
  155. NSInteger discardCount;
  156. NSNumber *nextFetchWaitTimeFromResponse;
  157. NSArray<FIRIAMMessageDefinition *> *messages = [self.responseParser
  158. parseAPIResponseDictionary:responseDict
  159. discardedMsgCount:&discardCount
  160. fetchWaitTimeInSeconds:&nextFetchWaitTimeFromResponse];
  161. if (messages) {
  162. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM130012",
  163. @"API request for fetching messages and parsing the response was "
  164. "successful.");
  165. [self.fetchStorage
  166. saveResponseDictionary:responseDict
  167. withCompletion:^(BOOL success) {
  168. if (!success)
  169. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM130010",
  170. @"Failed to persist server fetch response");
  171. }];
  172. // always report success regardless of whether we are able to persist into
  173. // storage. they should get fixed in the next fetch cycle if it happens.
  174. completion(messages, nextFetchWaitTimeFromResponse, discardCount, nil);
  175. } else {
  176. NSString *errorDesc =
  177. @"Failed to recognize the fiam messages in the server response";
  178. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM130011", @"%@", errorDesc);
  179. NSError *error =
  180. [NSError errorWithDomain:kFirebaseInAppMessagingErrorDomain
  181. code:0
  182. userInfo:@{NSLocalizedDescriptionKey : errorDesc}];
  183. completion(nil, nil, 0, error);
  184. }
  185. }
  186. } else {
  187. NSString *responseBody = [[NSString alloc] initWithData:data
  188. encoding:NSUTF8StringEncoding];
  189. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM130004",
  190. @"Failed restful api request to fetch in-app messages: seeing http "
  191. @"status code as %ld with body as %@",
  192. (long)httpResponse.statusCode, responseBody);
  193. NSError *error = [NSError errorWithDomain:NSURLErrorDomain
  194. code:httpResponse.statusCode
  195. userInfo:nil];
  196. completion(nil, nil, 0, error);
  197. }
  198. } else {
  199. NSString *errorDesc = @"Got a non http response type from fetch endpoint";
  200. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM130005", @"%@", errorDesc);
  201. NSError *error = [NSError errorWithDomain:kFirebaseInAppMessagingErrorDomain
  202. code:0
  203. userInfo:@{NSLocalizedDescriptionKey : errorDesc}];
  204. completion(nil, nil, 0, error);
  205. }
  206. }
  207. }];
  208. if (postDataTask == nil) {
  209. NSString *errorDesc =
  210. @"Internal error: NSURLSessionDataTask failed to be created due to possibly "
  211. "incorrect parameters";
  212. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM130006", @"%@", errorDesc);
  213. NSError *error = [NSError errorWithDomain:kFirebaseInAppMessagingErrorDomain
  214. code:0
  215. userInfo:@{NSLocalizedDescriptionKey : errorDesc}];
  216. completion(nil, nil, 0, error);
  217. } else {
  218. [postDataTask resume];
  219. }
  220. }
  221. #pragma mark - protocol FIRIAMMessageFetcher
  222. - (void)fetchMessagesWithImpressionList:(NSArray<FIRIAMImpressionRecord *> *)impressonList
  223. withCompletion:(FIRIAMFetchMessageCompletionHandler)completion {
  224. // First step is to fetch the instance id value and token on the fly. We are not caching the data
  225. // since the fetch operation frequency is low enough that we are not concerned about its impact
  226. // on server load and this guarantees that we always have an up-to-date iid values and tokens.
  227. [self.clientInfoFetcher
  228. fetchFirebaseInstallationDataWithProjectNumber:self.fbProjectNumber
  229. withCompletion:^(NSString *_Nullable FID,
  230. NSString *_Nullable FISToken,
  231. NSError *_Nullable error) {
  232. if (error) {
  233. FIRLogWarning(
  234. kFIRLoggerInAppMessaging, @"I-IAM130008",
  235. @"Not able to get iid value and/or token for "
  236. @"talking to server: %@",
  237. error.localizedDescription);
  238. completion(nil, nil, 0, error);
  239. } else {
  240. [self fetchMessagesWithImpressionList:impressonList
  241. withIIDvalue:FID
  242. IIDToken:FISToken
  243. completion:completion];
  244. }
  245. }];
  246. }
  247. @end