FDLUtilities.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. // At least one custom domain host name 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 (([urlStr rangeOfString:domainURIPrefixStr
  186. options:NSCaseInsensitiveSearch | NSAnchoredSearch]
  187. .location) == 0) {
  188. NSString *urlWithoutDomainURIPrefix = [urlStr substringFromIndex:domainURIPrefixStr.length];
  189. // For a valid custom domain DL Suffix:
  190. // 1. At least one path exists OR
  191. // 2. Should have a link query param with an http/https link
  192. BOOL matchesRegularExpression =
  193. ([urlWithoutDomainURIPrefix
  194. rangeOfString:@"((\\/[A-Za-z0-9]+)|((\\?|\\/\\?)link=https?.*))"
  195. options:NSRegularExpressionSearch]
  196. .location != NSNotFound);
  197. if (matchesRegularExpression) {
  198. customDomainMatchFound = true;
  199. break;
  200. }
  201. }
  202. }
  203. }
  204. return customDomainMatchFound;
  205. }
  206. /* We are validating following domains in proper format.
  207. *.page.link
  208. *.app.goo.gl
  209. *.page.link/i/
  210. *.app.goo.gl/i/
  211. */
  212. BOOL FIRDLIsAValidDLWithFDLDomain(NSURL *_Nullable URL) {
  213. BOOL matchesRegularExpression = false;
  214. NSString *urlStr = URL.absoluteString;
  215. if ([URL.host containsString:@".page.link"] || [URL.host containsString:@".app.goo.gl"]) {
  216. // Matches the *.page.link and *.app.goo.gl domains.
  217. matchesRegularExpression =
  218. ([urlStr rangeOfString:@"^https?://[a-zA-Z0-9]+((\\.app\\.goo\\.gl)|(\\.page\\.link))((\\/"
  219. @"?\\?.*link=https?.*)|(\\/[a-zA-Z0-9-_]+)((\\/?\\?.*=.*)?$|$))"
  220. options:NSRegularExpressionSearch]
  221. .location != NSNotFound);
  222. if (!matchesRegularExpression) {
  223. // Matches the *.page.link/i/ and *.app.goo.gl/i/ domains.
  224. // Checks whether the URL is of the format :
  225. // http(s)://$DOMAIN(.page.link or .app.goo.gl)/i/$ANYTHING
  226. matchesRegularExpression =
  227. ([urlStr rangeOfString:
  228. @"^https?:\\/\\/[a-zA-Z0-9]+((\\.app\\.goo\\.gl)|(\\.page\\.link))\\/i\\/.*$"
  229. options:NSRegularExpressionSearch]
  230. .location != NSNotFound);
  231. }
  232. }
  233. return matchesRegularExpression;
  234. }
  235. /*
  236. DL can be parsed if it :
  237. 1. Has http(s)://goo.gl/app* or http(s)://page.link/app* format
  238. 2. OR http(s)://$DomainPrefix.page.link or http(s)://$DomainPrefix.app.goo.gl domain with specific
  239. format
  240. 3. OR the domain is a listed custom domain
  241. */
  242. BOOL FIRDLCanParseUniversalLinkURL(NSURL *_Nullable URL) {
  243. // Handle universal links with format |https://goo.gl/app/<appcode>?<parameters>|.
  244. // Also support page.link format.
  245. BOOL isDDLWithAppcodeInPath = ([URL.host isEqual:@"goo.gl"] || [URL.host isEqual:@"page.link"]) &&
  246. [URL.path hasPrefix:@"/app"];
  247. return isDDLWithAppcodeInPath || FIRDLIsAValidDLWithFDLDomain(URL) ||
  248. FIRDLIsURLForAllowedCustomDomain(URL);
  249. }
  250. BOOL FIRDLMatchesShortLinkFormat(NSURL *URL) {
  251. // Short Durable Link URLs always have a path or it should be a custom domain.
  252. BOOL hasPathOrCustomDomain = URL.path.length > 0 || FIRDLIsURLForAllowedCustomDomain(URL);
  253. // Must be able to parse (also checks if the URL conforms to *.app.goo.gl/* or goo.gl/app/* or
  254. // *.page.link or custom domain with valid suffix)
  255. BOOL canParse = FIRDLCanParseUniversalLinkURL(URL);
  256. // Path cannot be prefixed with /link/dismiss
  257. BOOL isDismiss = [[URL.path lowercaseString] hasPrefix:@"/link/dismiss"];
  258. // Checks short link format by having only one path after domain prefix.
  259. BOOL matchesRegularExpression =
  260. ([URL.path rangeOfString:@"/[^/]+" options:NSRegularExpressionSearch].location != NSNotFound);
  261. return hasPathOrCustomDomain && !isDismiss && canParse && matchesRegularExpression;
  262. }
  263. NSString *FIRDLMatchTypeStringFromServerString(NSString *_Nullable serverMatchTypeString) {
  264. static NSDictionary *matchMap;
  265. static dispatch_once_t onceToken;
  266. dispatch_once(&onceToken, ^{
  267. matchMap = @{
  268. @"WEAK" : @"weak",
  269. @"DEFAULT" : @"default",
  270. @"UNIQUE" : @"unique",
  271. };
  272. });
  273. return matchMap[serverMatchTypeString] ?: @"none";
  274. }
  275. void FIRDLAddToAllowListForCustomDomainsArray(NSArray *_Nonnull customDomains) {
  276. // Duplicates will be weeded out when converting to a set.
  277. NSMutableArray *validCustomDomains =
  278. [[NSMutableArray alloc] initWithCapacity:customDomains.count];
  279. for (NSString *customDomainEntry in customDomains) {
  280. // We remove trailing slashes in the path if present.
  281. NSString *domainEntry =
  282. [customDomainEntry hasSuffix:@"/"]
  283. ? [customDomainEntry substringToIndex:[customDomainEntry length] - 1]
  284. : customDomainEntry;
  285. NSURL *customDomainURL = [NSURL URLWithString:domainEntry];
  286. // We require a valid scheme for each custom domain enumerated in the info.plist file.
  287. if (customDomainURL && customDomainURL.scheme) {
  288. [validCustomDomains addObject:customDomainURL];
  289. }
  290. }
  291. // Duplicates will be weeded out when converting to a set.
  292. FIRDLCustomDomains = [NSSet setWithArray:validCustomDomains];
  293. }
  294. NS_ASSUME_NONNULL_END
  295. #endif // TARGET_OS_IOS