FIRDynamicLinkNetworking.m 15 KB

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