FIRIAMMsgFetcherUsingRestful.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. #import <FirebaseABTesting/FIRExperimentController.h>
  26. static NSInteger const SuccessHTTPStatusCode = 200;
  27. @interface FIRIAMMsgFetcherUsingRestful ()
  28. @property(readonly) NSURLSession *URLSession;
  29. @property(readonly, copy, nonatomic) NSString *serverHostName;
  30. @property(readonly, copy, nonatomic) NSString *appBundleID;
  31. @property(readonly, copy, nonatomic) NSString *httpProtocol;
  32. @property(readonly, copy, nonatomic) NSString *fbProjectNumber;
  33. @property(readonly, copy, nonatomic) NSString *apiKey;
  34. @property(readonly, copy, nonatomic) NSString *firebaseAppId;
  35. @property(readonly, nonatomic) FIRIAMServerMsgFetchStorage *fetchStorage;
  36. @property(readonly, nonatomic) FIRIAMClientInfoFetcher *clientInfoFetcher;
  37. @property(readonly, nonatomic) FIRIAMFetchResponseParser *responseParser;
  38. @end
  39. @implementation FIRIAMMsgFetcherUsingRestful
  40. - (instancetype)initWithHost:(NSString *)serverHost
  41. HTTPProtocol:(NSString *)HTTPProtocol
  42. project:(NSString *)fbProjectNumber
  43. firebaseApp:(NSString *)fbAppId
  44. APIKey:(NSString *)apiKey
  45. fetchStorage:(FIRIAMServerMsgFetchStorage *)fetchStorage
  46. instanceIDFetcher:(FIRIAMClientInfoFetcher *)clientInfoFetcher
  47. usingURLSession:(nullable NSURLSession *)URLSession
  48. responseParser:(FIRIAMFetchResponseParser *)responseParser {
  49. if (self = [super init]) {
  50. _URLSession = URLSession ? URLSession : [NSURLSession sharedSession];
  51. _serverHostName = [serverHost copy];
  52. _fbProjectNumber = [fbProjectNumber copy];
  53. _firebaseAppId = [fbAppId copy];
  54. _httpProtocol = [HTTPProtocol copy];
  55. _apiKey = [apiKey copy];
  56. _clientInfoFetcher = clientInfoFetcher;
  57. _fetchStorage = fetchStorage;
  58. _appBundleID = [NSBundle mainBundle].bundleIdentifier;
  59. _responseParser = responseParser;
  60. }
  61. return self;
  62. }
  63. - (void)updatePostFetchData:(NSMutableDictionary *)postData
  64. withImpressionList:(NSArray<FIRIAMImpressionRecord *> *)impressionList
  65. instanceIDString:(nonnull NSString *)IIDValue
  66. IIDToken:(nonnull NSString *)IIDToken {
  67. NSMutableArray *impressionListForPost = [[NSMutableArray alloc] init];
  68. for (FIRIAMImpressionRecord *nextImpressionRecord in impressionList) {
  69. NSDictionary *nextImpression = @{
  70. @"campaign_id" : nextImpressionRecord.messageID,
  71. @"impression_timestamp_millis" : @(nextImpressionRecord.impressionTimeInSeconds * 1000)
  72. };
  73. [impressionListForPost addObject:nextImpression];
  74. }
  75. [postData setObject:impressionListForPost forKey:@"already_seen_campaigns"];
  76. if (IIDValue) {
  77. NSDictionary *clientAppInfo = @{
  78. @"gmp_app_id" : self.firebaseAppId,
  79. @"app_instance_id" : IIDValue,
  80. @"app_instance_id_token" : IIDToken
  81. };
  82. [postData setObject:clientAppInfo forKey:@"requesting_client_app"];
  83. }
  84. NSMutableArray *clientSignals = [@{} mutableCopy];
  85. // set client signal fields only when they are present
  86. if ([self.clientInfoFetcher getAppVersion]) {
  87. [clientSignals setValue:[self.clientInfoFetcher getAppVersion] forKey:@"app_version"];
  88. }
  89. if ([self.clientInfoFetcher getOSVersion]) {
  90. [clientSignals setValue:[self.clientInfoFetcher getOSVersion] forKey:@"platform_version"];
  91. }
  92. if ([self.clientInfoFetcher getDeviceLanguageCode]) {
  93. [clientSignals setValue:[self.clientInfoFetcher getDeviceLanguageCode] forKey:@"language_code"];
  94. }
  95. if ([self.clientInfoFetcher getTimezone]) {
  96. [clientSignals setValue:[self.clientInfoFetcher getTimezone] forKey:@"time_zone"];
  97. }
  98. [postData setObject:clientSignals forKey:@"client_signals"];
  99. }
  100. - (void)fetchMessagesWithImpressionList:(NSArray<FIRIAMImpressionRecord *> *)impressonList
  101. withIIDvalue:(NSString *)iidValue
  102. IIDToken:(NSString *)iidToken
  103. completion:(FIRIAMFetchMessageCompletionHandler)completion {
  104. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  105. [request setHTTPMethod:@"POST"];
  106. if (_appBundleID.length) {
  107. // Handle the case in which the API key is being restricted to specific iOS app bundle,
  108. // which can be set on Google Cloud console side for API key credentials.
  109. [request addValue:_appBundleID forHTTPHeaderField:@"X-Ios-Bundle-Identifier"];
  110. }
  111. [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  112. [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
  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. // Validate running experiments with ABT.
  166. NSMutableArray *runningExperiments = [[NSMutableArray alloc] init];
  167. for (FIRIAMMessageDefinition *messageDefinition in messages) {
  168. if (messageDefinition.experimentPayload) {
  169. [runningExperiments addObject:messageDefinition.experimentPayload];
  170. }
  171. }
  172. [[FIRExperimentController sharedInstance]
  173. validateRunningExperimentsForServiceOrigin:@"fiam"
  174. runningExperimentPayloads:[runningExperiments copy]];
  175. [self.fetchStorage
  176. saveResponseDictionary:responseDict
  177. withCompletion:^(BOOL success) {
  178. if (!success)
  179. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM130010",
  180. @"Failed to persist server fetch response");
  181. }];
  182. // always report success regardless of whether we are able to persist into
  183. // storage. they should get fixed in the next fetch cycle if it happens.
  184. completion(messages, nextFetchWaitTimeFromResponse, discardCount, nil);
  185. } else {
  186. NSString *errorDesc =
  187. @"Failed to recognize the fiam messages in the server response";
  188. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM130011", @"%@", errorDesc);
  189. NSError *error =
  190. [NSError errorWithDomain:kFirebaseInAppMessagingErrorDomain
  191. code:0
  192. userInfo:@{NSLocalizedDescriptionKey : errorDesc}];
  193. completion(nil, nil, 0, error);
  194. }
  195. }
  196. } else {
  197. NSString *responseBody = [[NSString alloc] initWithData:data
  198. encoding:NSUTF8StringEncoding];
  199. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM130004",
  200. @"Failed restful api request to fetch in-app messages: seeing http "
  201. @"status code as %ld with body as %@",
  202. (long)httpResponse.statusCode, responseBody);
  203. NSError *error = [NSError errorWithDomain:NSURLErrorDomain
  204. code:httpResponse.statusCode
  205. userInfo:nil];
  206. completion(nil, nil, 0, error);
  207. }
  208. } else {
  209. NSString *errorDesc = @"Got a non http response type from fetch endpoint";
  210. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM130005", @"%@", errorDesc);
  211. NSError *error = [NSError errorWithDomain:kFirebaseInAppMessagingErrorDomain
  212. code:0
  213. userInfo:@{NSLocalizedDescriptionKey : errorDesc}];
  214. completion(nil, nil, 0, error);
  215. }
  216. }
  217. }];
  218. if (postDataTask == nil) {
  219. NSString *errorDesc =
  220. @"Internal error: NSURLSessionDataTask failed to be created due to possibly "
  221. "incorrect parameters";
  222. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM130006", @"%@", errorDesc);
  223. NSError *error = [NSError errorWithDomain:kFirebaseInAppMessagingErrorDomain
  224. code:0
  225. userInfo:@{NSLocalizedDescriptionKey : errorDesc}];
  226. completion(nil, nil, 0, error);
  227. } else {
  228. [postDataTask resume];
  229. }
  230. }
  231. #pragma mark - protocol FIRIAMMessageFetcher
  232. - (void)fetchMessagesWithImpressionList:(NSArray<FIRIAMImpressionRecord *> *)impressonList
  233. withCompletion:(FIRIAMFetchMessageCompletionHandler)completion {
  234. // First step is to fetch the instance id value and token on the fly. We are not caching the data
  235. // since the fetch operation frequency is low enough that we are not concerned about its impact
  236. // on server load and this guarantees that we always have an up-to-date iid values and tokens.
  237. [self.clientInfoFetcher
  238. fetchFirebaseIIDDataWithProjectNumber:self.fbProjectNumber
  239. withCompletion:^(NSString *_Nullable iid, NSString *_Nullable token,
  240. NSError *_Nullable error) {
  241. if (error) {
  242. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM130008",
  243. @"Not able to get iid value and/or token for "
  244. @"talking to server: %@",
  245. error.localizedDescription);
  246. completion(nil, nil, 0, error);
  247. } else {
  248. [self fetchMessagesWithImpressionList:impressonList
  249. withIIDvalue:iid
  250. IIDToken:token
  251. completion:completion];
  252. }
  253. }];
  254. }
  255. @end