FIRIAMMsgFetcherUsingRestful.m 13 KB

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