FDLUtilities.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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/Utilities/FDLUtilities.h"
  19. #import <UIKit/UIDevice.h>
  20. #include <sys/sysctl.h>
  21. NS_ASSUME_NONNULL_BEGIN
  22. NSString *const kFIRDLParameterDeepLinkIdentifier = @"deep_link_id";
  23. NSString *const kFIRDLParameterLink = @"link";
  24. NSString *const kFIRDLParameterMinimumAppVersion = @"imv";
  25. NSString *const kFIRDLParameterSource = @"utm_source";
  26. NSString *const kFIRDLParameterMedium = @"utm_medium";
  27. NSString *const kFIRDLParameterCampaign = @"utm_campaign";
  28. NSString *const kFIRDLParameterMatchType = @"match_type";
  29. NSString *const kFIRDLParameterInviteId = @"invitation_id";
  30. NSString *const kFIRDLParameterWeakMatchEndpoint = @"invitation_weakMatchEndpoint";
  31. NSString *const kFIRDLParameterMatchMessage = @"match_message";
  32. NSString *const kFIRDLParameterRequestIPVersion = @"request_ip_version";
  33. static NSSet *FIRDLCustomDomains = nil;
  34. NSURL *FIRDLCookieRetrievalURL(NSString *urlScheme, NSString *bundleID) {
  35. static NSString *const kFDLBundleIDQueryParameterName = @"fdl_ios_bundle_id";
  36. static NSString *const kFDLURLSchemeQueryParameterName = @"fdl_ios_url_scheme";
  37. NSURLComponents *components = [[NSURLComponents alloc] init];
  38. components.scheme = @"https";
  39. components.host = @"goo.gl";
  40. components.path = @"/app/_/deeplink";
  41. NSMutableArray *queryItems = [NSMutableArray array];
  42. [queryItems addObject:[NSURLQueryItem queryItemWithName:kFDLBundleIDQueryParameterName
  43. value:bundleID]];
  44. [queryItems addObject:[NSURLQueryItem queryItemWithName:kFDLURLSchemeQueryParameterName
  45. value:urlScheme]];
  46. [components setQueryItems:queryItems];
  47. return [components URL];
  48. }
  49. NSString *FIRDLURLQueryStringFromDictionary(NSDictionary<NSString *, NSString *> *dictionary) {
  50. NSMutableString *parameters = [NSMutableString string];
  51. NSCharacterSet *queryCharacterSet = [NSCharacterSet alphanumericCharacterSet];
  52. NSString *parameterFormatString = @"%@%@=%@";
  53. __block NSUInteger index = 0;
  54. [dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *_Nonnull key, NSString *_Nonnull value,
  55. BOOL *_Nonnull stop) {
  56. NSString *delimiter = index++ == 0 ? @"?" : @"&";
  57. NSString *encodedValue =
  58. [value stringByAddingPercentEncodingWithAllowedCharacters:queryCharacterSet];
  59. NSString *parameter =
  60. [NSString stringWithFormat:parameterFormatString, delimiter, key, encodedValue];
  61. [parameters appendString:parameter];
  62. }];
  63. return parameters;
  64. }
  65. NSDictionary *FIRDLDictionaryFromQuery(NSString *queryString) {
  66. NSArray<NSString *> *keyValuePairs = [queryString componentsSeparatedByString:@"&"];
  67. NSMutableDictionary *queryDictionary =
  68. [NSMutableDictionary dictionaryWithCapacity:keyValuePairs.count];
  69. for (NSString *pair in keyValuePairs) {
  70. NSArray *keyValuePair = [pair componentsSeparatedByString:@"="];
  71. if (keyValuePair.count == 2) {
  72. NSString *key = keyValuePair[0];
  73. NSString *value = [keyValuePair[1] stringByRemovingPercentEncoding];
  74. [queryDictionary setObject:value forKey:key];
  75. }
  76. }
  77. return [queryDictionary copy];
  78. }
  79. NSURL *FIRDLDeepLinkURLWithInviteID(NSString *_Nullable inviteID,
  80. NSString *_Nullable deepLinkString,
  81. NSString *_Nullable utmSource,
  82. NSString *_Nullable utmMedium,
  83. NSString *_Nullable utmCampaign,
  84. BOOL isWeakLink,
  85. NSString *_Nullable weakMatchEndpoint,
  86. NSString *_Nullable minAppVersion,
  87. NSString *URLScheme,
  88. NSString *_Nullable matchMessage) {
  89. // We are unable to use NSURLComponents as NSURLQueryItem is avilable beginning in iOS 8 and
  90. // appending our query string with NSURLComponents improperly formats the query by adding
  91. // a second '?' in the query.
  92. NSMutableDictionary *queryDictionary = [NSMutableDictionary dictionary];
  93. if (inviteID != nil) {
  94. queryDictionary[kFIRDLParameterInviteId] = inviteID;
  95. }
  96. if (deepLinkString != nil) {
  97. queryDictionary[kFIRDLParameterDeepLinkIdentifier] = deepLinkString;
  98. }
  99. if (utmSource != nil) {
  100. queryDictionary[kFIRDLParameterSource] = utmSource;
  101. }
  102. if (utmMedium != nil) {
  103. queryDictionary[kFIRDLParameterMedium] = utmMedium;
  104. }
  105. if (utmCampaign != nil) {
  106. queryDictionary[kFIRDLParameterCampaign] = utmCampaign;
  107. }
  108. if (isWeakLink) {
  109. queryDictionary[kFIRDLParameterMatchType] = @"weak";
  110. } else {
  111. queryDictionary[kFIRDLParameterMatchType] = @"unique";
  112. }
  113. if (weakMatchEndpoint != nil) {
  114. queryDictionary[kFIRDLParameterWeakMatchEndpoint] = weakMatchEndpoint;
  115. }
  116. if (minAppVersion != nil) {
  117. queryDictionary[kFIRDLParameterMinimumAppVersion] = minAppVersion;
  118. }
  119. if (matchMessage != nil) {
  120. queryDictionary[kFIRDLParameterMatchMessage] = matchMessage;
  121. }
  122. NSString *scheme = [URLScheme lowercaseString];
  123. NSString *queryString = FIRDLURLQueryStringFromDictionary(queryDictionary);
  124. NSString *urlString = [NSString stringWithFormat:@"%@://google/link/%@", scheme, queryString];
  125. return [NSURL URLWithString:urlString];
  126. }
  127. BOOL FIRDLOSVersionSupported(NSString *_Nullable systemVersion, NSString *minSupportedVersion) {
  128. systemVersion = systemVersion ?: [UIDevice currentDevice].systemVersion;
  129. return [systemVersion compare:minSupportedVersion options:NSNumericSearch] != NSOrderedAscending;
  130. }
  131. NSDate *_Nullable FIRDLAppInstallationDate() {
  132. NSURL *documentsDirectoryURL =
  133. [[[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory
  134. inDomains:NSUserDomainMask] firstObject];
  135. if (!documentsDirectoryURL) {
  136. return nil;
  137. }
  138. NSDictionary<NSString *, id> *attributes =
  139. [[NSFileManager defaultManager] attributesOfItemAtPath:documentsDirectoryURL.path error:NULL];
  140. if (attributes[NSFileCreationDate] &&
  141. [attributes[NSFileCreationDate] isKindOfClass:[NSDate class]]) {
  142. return attributes[NSFileCreationDate];
  143. }
  144. return nil;
  145. }
  146. NSString *FIRDLDeviceModelName() {
  147. // this method will return string like iPad3,3
  148. // for Simulator this will be x86_64
  149. static NSString *machineString = @"";
  150. static dispatch_once_t onceToken;
  151. dispatch_once(&onceToken, ^{
  152. size_t size;
  153. // compute string size
  154. if (sysctlbyname("hw.machine", NULL, &size, NULL, 0) == 0) {
  155. // get device name
  156. char *machine = calloc(1, size);
  157. if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == 0) {
  158. machineString = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
  159. }
  160. free(machine);
  161. }
  162. });
  163. return machineString;
  164. }
  165. NSString *FIRDLDeviceLocale() {
  166. // expected return value from this method looks like: @"en-US"
  167. return [[[NSLocale currentLocale] localeIdentifier] stringByReplacingOccurrencesOfString:@"_"
  168. withString:@"-"];
  169. }
  170. NSString *FIRDLDeviceLocaleRaw() {
  171. return [[NSLocale currentLocale] localeIdentifier];
  172. }
  173. NSString *FIRDLDeviceTimezone() {
  174. NSString *timeZoneName = [[NSTimeZone localTimeZone] name];
  175. return timeZoneName;
  176. }
  177. BOOL FIRDLIsURLForAllowedCustomDomain(NSURL *_Nullable URL) {
  178. BOOL customDomainMatchFound = false;
  179. for (NSURL *allowedCustomDomain in FIRDLCustomDomains) {
  180. // All custom domain host names should match at a minimum.
  181. if ([allowedCustomDomain.host isEqualToString:URL.host]) {
  182. NSString *urlStr = URL.absoluteString;
  183. NSString *domainURIPrefixStr = allowedCustomDomain.absoluteString;
  184. // Next, do a string compare to check if entire domainURIPrefix matches as well.
  185. if (([URL.absoluteString rangeOfString:allowedCustomDomain.absoluteString
  186. options:NSCaseInsensitiveSearch | NSAnchoredSearch]
  187. .location) == 0) {
  188. // The (short) URL needs to be longer than the domainURIPrefix, it's first character after
  189. // the domainURIPrefix needs to be '/' and should be followed by at-least one more
  190. // character.
  191. if (urlStr.length > domainURIPrefixStr.length + 1 &&
  192. ([urlStr characterAtIndex:domainURIPrefixStr.length] == '/')) {
  193. // Check if there are any more '/' after the first '/'trailing the
  194. // domainURIPrefix. This does not apply to unique match links copied from the clipboard.
  195. // The clipboard links will have '?link=' after the domainURIPrefix.
  196. NSString *urlWithoutDomainURIPrefix =
  197. [urlStr substringFromIndex:domainURIPrefixStr.length + 1];
  198. if ([urlWithoutDomainURIPrefix rangeOfString:@"/"].location == NSNotFound ||
  199. [urlWithoutDomainURIPrefix rangeOfString:@"?link="].location != NSNotFound) {
  200. customDomainMatchFound = true;
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. }
  207. return customDomainMatchFound;
  208. }
  209. BOOL FIRDLCanParseUniversalLinkURL(NSURL *_Nullable URL) {
  210. // Handle universal links with format |https://goo.gl/app/<appcode>?<parameters>|.
  211. // Also support page.link format.
  212. BOOL isDDLWithAppcodeInPath = ([URL.host isEqual:@"goo.gl"] || [URL.host isEqual:@"page.link"]) &&
  213. [URL.path hasPrefix:@"/app"];
  214. // Handle universal links with format |https://<appcode>.app.goo.gl?<parameters>| and page.link.
  215. BOOL isDDLWithSubdomain =
  216. [URL.host hasSuffix:@".app.goo.gl"] || [URL.host hasSuffix:@".page.link"];
  217. // Handle universal links for custom domains.
  218. BOOL isDDLWithCustomDomain = FIRDLIsURLForAllowedCustomDomain(URL);
  219. return isDDLWithAppcodeInPath || isDDLWithSubdomain || isDDLWithCustomDomain;
  220. }
  221. BOOL FIRDLMatchesShortLinkFormat(NSURL *URL) {
  222. // Short Durable Link URLs always have a path.
  223. BOOL hasPath = URL.path.length > 0;
  224. BOOL matchesRegularExpression =
  225. ([URL.path rangeOfString:@"/[^/]+" options:NSRegularExpressionSearch].location != NSNotFound);
  226. // Must be able to parse (also checks if the URL conforms to *.app.goo.gl/* or goo.gl/app/*)
  227. BOOL canParse = FIRDLCanParseUniversalLinkURL(URL) | FIRDLIsURLForAllowedCustomDomain(URL);
  228. ;
  229. // Path cannot be prefixed with /link/dismiss
  230. BOOL isDismiss = [[URL.path lowercaseString] hasPrefix:@"/link/dismiss"];
  231. return hasPath && matchesRegularExpression && !isDismiss && canParse;
  232. }
  233. NSString *FIRDLMatchTypeStringFromServerString(NSString *_Nullable serverMatchTypeString) {
  234. static NSDictionary *matchMap;
  235. static dispatch_once_t onceToken;
  236. dispatch_once(&onceToken, ^{
  237. matchMap = @{
  238. @"WEAK" : @"weak",
  239. @"DEFAULT" : @"default",
  240. @"UNIQUE" : @"unique",
  241. };
  242. });
  243. return matchMap[serverMatchTypeString] ?: @"none";
  244. }
  245. void FIRDLAddToAllowListForCustomDomainsArray(NSArray *_Nonnull customDomains) {
  246. // Duplicates will be weeded out when converting to a set.
  247. NSMutableArray *validCustomDomains =
  248. [[NSMutableArray alloc] initWithCapacity:customDomains.count];
  249. for (NSString *customDomainEntry in customDomains) {
  250. // We remove trailing slashes in the path if present.
  251. NSString *domainEntry =
  252. [customDomainEntry hasSuffix:@"/"]
  253. ? [customDomainEntry substringToIndex:[customDomainEntry length] - 1]
  254. : customDomainEntry;
  255. NSURL *customDomainURL = [NSURL URLWithString:domainEntry];
  256. // We require a valid scheme for each custom domain enumerated in the info.plist file.
  257. if (customDomainURL && customDomainURL.scheme) {
  258. [validCustomDomains addObject:customDomainURL];
  259. }
  260. }
  261. // Duplicates will be weeded out when converting to a set.
  262. FIRDLCustomDomains = [NSSet setWithArray:validCustomDomains];
  263. }
  264. NS_ASSUME_NONNULL_END
  265. #endif // TARGET_OS_IOS