FIRDynamicLinkNetworking.m 15 KB

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