FIRDynamicLinkNetworking.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. /*
  2. * Copyright 2018 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 <TargetConditionals.h>
  17. #if TARGET_OS_IOS
  18. #import "FirebaseDynamicLinks/Sources/FIRDynamicLinkNetworking+Private.h"
  19. #import "FirebaseDynamicLinks/Sources/GINInvocation/GINArgument.h"
  20. #import "FirebaseDynamicLinks/Sources/GINInvocation/GINInvocation.h"
  21. #import "FirebaseDynamicLinks/Sources/Utilities/FDLUtilities.h"
  22. NS_ASSUME_NONNULL_BEGIN
  23. NSString *const kApiaryRestBaseUrl = @"https://appinvite-pa.googleapis.com/v1";
  24. static NSString *const kiOSReopenRestBaseUrl = @"https://firebasedynamiclinks.googleapis.com/v1";
  25. // Endpoint for default retrieval process V2. (Endpoint version is V1)
  26. static NSString *const kIosPostInstallAttributionRestBaseUrl =
  27. @"https://firebasedynamiclinks.googleapis.com/v1";
  28. static NSString *const kReasonString = @"reason";
  29. static NSString *const kiOSInviteReason = @"ios_invite";
  30. NSString *const kFDLResolvedLinkDeepLinkURLKey = @"deepLink";
  31. NSString *const kFDLResolvedLinkMinAppVersionKey = @"iosMinAppVersion";
  32. static NSString *const kFDLAnalyticsDataSourceKey = @"utmSource";
  33. static NSString *const kFDLAnalyticsDataMediumKey = @"utmMedium";
  34. static NSString *const kFDLAnalyticsDataCampaignKey = @"utmCampaign";
  35. static NSString *const kHeaderIosBundleIdentifier = @"X-Ios-Bundle-Identifier";
  36. static NSString *const kGenericErrorDomain = @"com.firebase.dynamicLinks";
  37. typedef NSDictionary *_Nullable (^FIRDLNetworkingParserBlock)(
  38. NSString *requestURLString,
  39. NSData *data,
  40. NSString *_Nullable *_Nonnull matchMessagePtr,
  41. NSError *_Nullable *_Nullable errorPtr);
  42. NSString *FIRURLParameterString(NSString *key, NSString *value) {
  43. if (key.length > 0) {
  44. return [NSString stringWithFormat:@"?%@=%@", key, value];
  45. }
  46. return @"";
  47. }
  48. NSString *_Nullable FIRDynamicLinkAPIKeyParameter(NSString *apiKey) {
  49. return apiKey ? FIRURLParameterString(@"key", apiKey) : nil;
  50. }
  51. void FIRMakeHTTPRequest(NSURLRequest *request, FIRNetworkRequestCompletionHandler completion) {
  52. NSURLSessionConfiguration *sessionConfig =
  53. [NSURLSessionConfiguration defaultSessionConfiguration];
  54. NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
  55. NSURLSessionDataTask *dataTask =
  56. [session dataTaskWithRequest:request
  57. completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response,
  58. NSError *_Nullable error) {
  59. completion(data, response, error);
  60. }];
  61. [dataTask resume];
  62. }
  63. NSData *_Nullable FIRDataWithDictionary(NSDictionary *dictionary, NSError **_Nullable error) {
  64. return [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:error];
  65. }
  66. @implementation FIRDynamicLinkNetworking {
  67. NSString *_APIKey;
  68. NSString *_URLScheme;
  69. }
  70. - (instancetype)initWithAPIKey:(NSString *)APIKey URLScheme:(NSString *)URLScheme {
  71. NSParameterAssert(APIKey);
  72. NSParameterAssert(URLScheme);
  73. if (self = [super init]) {
  74. _APIKey = [APIKey copy];
  75. _URLScheme = [URLScheme copy];
  76. }
  77. return self;
  78. }
  79. + (nullable NSError *)extractErrorForShortLink:(NSURL *)url
  80. data:(NSData *)data
  81. response:(NSURLResponse *)response
  82. error:(nullable NSError *)error {
  83. if (error) {
  84. return error;
  85. }
  86. NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
  87. NSError *customError = nil;
  88. if (![response isKindOfClass:[NSHTTPURLResponse class]]) {
  89. customError =
  90. [NSError errorWithDomain:kGenericErrorDomain
  91. code:0
  92. userInfo:@{@"message" : @"Response should be of type NSHTTPURLResponse."}];
  93. } else if ((statusCode < 200 || statusCode >= 300) && data) {
  94. NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  95. if ([result isKindOfClass:[NSDictionary class]] && [result objectForKey:@"error"]) {
  96. id err = [result objectForKey:@"error"];
  97. customError = [NSError errorWithDomain:kGenericErrorDomain code:statusCode userInfo:err];
  98. } else {
  99. customError = [NSError
  100. errorWithDomain:kGenericErrorDomain
  101. code:0
  102. userInfo:@{
  103. @"message" :
  104. [NSString stringWithFormat:@"Failed to resolve link: %@", url.absoluteString]
  105. }];
  106. }
  107. }
  108. return customError;
  109. }
  110. #pragma mark - Public interface
  111. - (void)resolveShortLink:(NSURL *)url
  112. FDLSDKVersion:(NSString *)FDLSDKVersion
  113. completion:(FIRDynamicLinkResolverHandler)handler {
  114. NSParameterAssert(handler);
  115. if (!url) {
  116. handler(nil, nil);
  117. return;
  118. }
  119. NSDictionary *requestBody = @{
  120. @"requestedLink" : url.absoluteString,
  121. @"bundle_id" : [NSBundle mainBundle].bundleIdentifier,
  122. @"sdk_version" : FDLSDKVersion
  123. };
  124. FIRNetworkRequestCompletionHandler resolveLinkCallback =
  125. ^(NSData *data, NSURLResponse *response, NSError *error) {
  126. NSURL *resolvedURL = nil;
  127. NSError *extractedError = [FIRDynamicLinkNetworking extractErrorForShortLink:url
  128. data:data
  129. response:response
  130. error:error];
  131. if (!extractedError && data) {
  132. NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  133. if ([result isKindOfClass:[NSDictionary class]]) {
  134. id invitationIDObject = [result objectForKey:@"invitationId"];
  135. NSString *invitationIDString;
  136. if ([invitationIDObject isKindOfClass:[NSDictionary class]]) {
  137. NSDictionary *invitationIDDictionary = invitationIDObject;
  138. invitationIDString = invitationIDDictionary[@"id"];
  139. } else if ([invitationIDObject isKindOfClass:[NSString class]]) {
  140. invitationIDString = invitationIDObject;
  141. }
  142. NSString *deepLinkString = result[kFDLResolvedLinkDeepLinkURLKey];
  143. NSString *minAppVersion = result[kFDLResolvedLinkMinAppVersionKey];
  144. NSString *utmSource = result[kFDLAnalyticsDataSourceKey];
  145. NSString *utmMedium = result[kFDLAnalyticsDataMediumKey];
  146. NSString *utmCampaign = result[kFDLAnalyticsDataCampaignKey];
  147. resolvedURL = FIRDLDeepLinkURLWithInviteID(invitationIDString, deepLinkString,
  148. utmSource, utmMedium, utmCampaign, NO, nil,
  149. minAppVersion, self->_URLScheme, nil);
  150. }
  151. }
  152. handler(resolvedURL, extractedError);
  153. };
  154. NSString *requestURLString =
  155. [NSString stringWithFormat:@"%@/reopenAttribution%@", kiOSReopenRestBaseUrl,
  156. FIRDynamicLinkAPIKeyParameter(_APIKey)];
  157. [self executeOnePlatformRequest:requestBody
  158. forURL:requestURLString
  159. completionHandler:resolveLinkCallback];
  160. }
  161. - (void)retrievePendingDynamicLinkWithIOSVersion:(NSString *)IOSVersion
  162. resolutionHeight:(NSInteger)resolutionHeight
  163. resolutionWidth:(NSInteger)resolutionWidth
  164. locale:(NSString *)locale
  165. localeRaw:(NSString *)localeRaw
  166. localeFromWebView:(NSString *)localeFromWebView
  167. timezone:(NSString *)timezone
  168. modelName:(NSString *)modelName
  169. FDLSDKVersion:(NSString *)FDLSDKVersion
  170. appInstallationDate:(NSDate *_Nullable)appInstallationDate
  171. uniqueMatchVisualStyle:
  172. (FIRDynamicLinkNetworkingUniqueMatchVisualStyle)uniqueMatchVisualStyle
  173. retrievalProcessType:
  174. (FIRDynamicLinkNetworkingRetrievalProcessType)retrievalProcessType
  175. uniqueMatchLinkToCheck:(NSURL *)uniqueMatchLinkToCheck
  176. handler:
  177. (FIRPostInstallAttributionCompletionHandler)handler {
  178. NSParameterAssert(handler);
  179. NSMutableDictionary *requestBody = [@{
  180. @"bundleId" : [NSBundle mainBundle].bundleIdentifier,
  181. @"device" : @{
  182. @"screenResolutionHeight" : @(resolutionHeight),
  183. @"screenResolutionWidth" : @(resolutionWidth),
  184. @"languageCode" : locale,
  185. @"languageCodeRaw" : localeRaw,
  186. @"languageCodeFromWebview" : localeFromWebView,
  187. @"timezone" : timezone,
  188. @"deviceModelName" : modelName,
  189. },
  190. @"iosVersion" : IOSVersion,
  191. @"sdkVersion" : FDLSDKVersion,
  192. @"visualStyle" : @(uniqueMatchVisualStyle),
  193. @"retrievalMethod" : @(retrievalProcessType),
  194. } mutableCopy];
  195. if (appInstallationDate) {
  196. requestBody[@"appInstallationTime"] = @((NSInteger)[appInstallationDate timeIntervalSince1970]);
  197. }
  198. if (uniqueMatchLinkToCheck) {
  199. requestBody[@"uniqueMatchLinkToCheck"] = uniqueMatchLinkToCheck.absoluteString;
  200. }
  201. FIRDLNetworkingParserBlock responseParserBlock = ^NSDictionary *_Nullable(
  202. NSString *requestURLString, NSData *data, NSString **matchMessagePtr, NSError **errorPtr) {
  203. NSError *serializationError;
  204. NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data
  205. options:0
  206. error:&serializationError];
  207. if (serializationError) {
  208. *errorPtr = serializationError;
  209. return nil;
  210. }
  211. NSString *matchMessage = result[@"matchMessage"];
  212. if (matchMessage.length) {
  213. *matchMessagePtr = matchMessage;
  214. }
  215. // Create the dynamic link parameters
  216. NSMutableDictionary *dynamicLinkParameters = [[NSMutableDictionary alloc] init];
  217. dynamicLinkParameters[kFIRDLParameterInviteId] = result[@"invitationId"];
  218. dynamicLinkParameters[kFIRDLParameterDeepLinkIdentifier] = result[@"deepLink"];
  219. if (result[@"deepLink"]) {
  220. dynamicLinkParameters[kFIRDLParameterMatchType] =
  221. FIRDLMatchTypeStringFromServerString(result[@"attributionConfidence"]);
  222. }
  223. dynamicLinkParameters[kFIRDLParameterSource] = result[@"utmSource"];
  224. dynamicLinkParameters[kFIRDLParameterMedium] = result[@"utmMedium"];
  225. dynamicLinkParameters[kFIRDLParameterCampaign] = result[@"utmCampaign"];
  226. dynamicLinkParameters[kFIRDLParameterMinimumAppVersion] = result[@"appMinimumVersion"];
  227. dynamicLinkParameters[kFIRDLParameterRequestIPVersion] = result[@"requestIpVersion"];
  228. dynamicLinkParameters[kFIRDLParameterMatchMessage] = matchMessage;
  229. return [dynamicLinkParameters copy];
  230. };
  231. [self sendRequestWithBaseURLString:kIosPostInstallAttributionRestBaseUrl
  232. requestBody:requestBody
  233. endpointPath:@"installAttribution"
  234. parserBlock:responseParserBlock
  235. completion:handler];
  236. }
  237. - (void)convertInvitation:(NSString *)invitationID
  238. handler:(nullable FIRDynamicLinkNetworkingErrorHandler)handler {
  239. if (!invitationID) {
  240. return;
  241. }
  242. NSDictionary *requestBody = @{
  243. @"invitationId" : @{@"id" : invitationID},
  244. @"containerClientId" : @{
  245. @"type" : @"IOS",
  246. }
  247. };
  248. FIRNetworkRequestCompletionHandler convertInvitationCallback =
  249. ^(NSData *data, NSURLResponse *response, NSError *error) {
  250. if (handler) {
  251. dispatch_async(dispatch_get_main_queue(), ^{
  252. handler(error);
  253. });
  254. }
  255. };
  256. NSString *requestURL = [NSString stringWithFormat:@"%@/convertInvitation%@", kApiaryRestBaseUrl,
  257. FIRDynamicLinkAPIKeyParameter(_APIKey)];
  258. [self executeOnePlatformRequest:requestBody
  259. forURL:requestURL
  260. completionHandler:convertInvitationCallback];
  261. }
  262. #pragma mark - Internal methods
  263. - (void)sendRequestWithBaseURLString:(NSString *)baseURL
  264. requestBody:(NSDictionary *)requestBody
  265. endpointPath:(NSString *)endpointPath
  266. parserBlock:(FIRDLNetworkingParserBlock)parserBlock
  267. completion:(FIRPostInstallAttributionCompletionHandler)handler {
  268. NSParameterAssert(handler);
  269. NSString *requestURLString = [NSString
  270. stringWithFormat:@"%@/%@%@", baseURL, endpointPath, FIRDynamicLinkAPIKeyParameter(_APIKey)];
  271. FIRNetworkRequestCompletionHandler completeInvitationByDeviceCallback =
  272. ^(NSData *data, NSURLResponse *response, NSError *error) {
  273. if (error || !data) {
  274. dispatch_async(dispatch_get_main_queue(), ^{
  275. handler(nil, nil, error);
  276. });
  277. return;
  278. }
  279. NSString *matchMessage = nil;
  280. NSError *parsingError = nil;
  281. NSDictionary *parsedDynamicLinkParameters =
  282. parserBlock(requestURLString, data, &matchMessage, &parsingError);
  283. dispatch_async(dispatch_get_main_queue(), ^{
  284. handler(parsedDynamicLinkParameters, matchMessage, parsingError);
  285. });
  286. };
  287. [self executeOnePlatformRequest:requestBody
  288. forURL:requestURLString
  289. completionHandler:completeInvitationByDeviceCallback];
  290. }
  291. - (void)executeOnePlatformRequest:(NSDictionary *)requestBody
  292. forURL:(NSString *)requestURLString
  293. completionHandler:(FIRNetworkRequestCompletionHandler)handler {
  294. NSURL *requestURL = [NSURL URLWithString:requestURLString];
  295. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];
  296. // TODO: Verify that HTTPBody and HTTPMethod are iOS 8+ and find an alternative.
  297. request.HTTPBody = FIRDataWithDictionary(requestBody, nil);
  298. request.HTTPMethod = @"POST";
  299. [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
  300. // Set the iOS bundleID as a request header.
  301. NSString *bundleID = [[NSBundle mainBundle] bundleIdentifier];
  302. if (bundleID) {
  303. [request setValue:bundleID forHTTPHeaderField:kHeaderIosBundleIdentifier];
  304. }
  305. FIRMakeHTTPRequest(request, handler);
  306. }
  307. @end
  308. NS_ASSUME_NONNULL_END
  309. #endif // TARGET_OS_IOS