FIRDLDefaultRetrievalProcessV2.m 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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/FIRDLDefaultRetrievalProcessV2.h"
  19. #import <UIKit/UIKit.h>
  20. #import "FirebaseDynamicLinks/Sources/FIRDLJavaScriptExecutor.h"
  21. #import "FirebaseDynamicLinks/Sources/FIRDLRetrievalProcessResult+Private.h"
  22. #import "FirebaseDynamicLinks/Sources/FIRDynamicLink+Private.h"
  23. #import "FirebaseDynamicLinks/Sources/FIRDynamicLinkNetworking.h"
  24. #import "FirebaseDynamicLinks/Sources/Utilities/FDLUtilities.h"
  25. // Reason for this string to ensure that only FDL links, copied to clipboard by AppPreview Page
  26. // JavaScript code, are recognized and used in copy-unique-match process. If user copied FDL to
  27. // clipboard by himself, that link must not be used in copy-unique-match process.
  28. // This constant must be kept in sync with constant in the server version at
  29. // durabledeeplink/click/ios/click_page.js
  30. static NSString *expectedCopiedLinkStringSuffix = @"_icp=1";
  31. NS_ASSUME_NONNULL_BEGIN
  32. @interface FIRDLDefaultRetrievalProcessV2 () <FIRDLJavaScriptExecutorDelegate>
  33. @end
  34. @implementation FIRDLDefaultRetrievalProcessV2 {
  35. FIRDynamicLinkNetworking *_networkingService;
  36. NSString *_URLScheme;
  37. NSString *_APIKey;
  38. NSString *_FDLSDKVersion;
  39. NSString *_clipboardContentAtMatchProcessStart;
  40. FIRDLJavaScriptExecutor *_jsExecutor;
  41. NSString *_localeFromWebView;
  42. }
  43. @synthesize delegate = _delegate;
  44. #pragma mark - Initialization
  45. - (instancetype)initWithNetworkingService:(FIRDynamicLinkNetworking *)networkingService
  46. URLScheme:(NSString *)URLScheme
  47. APIKey:(NSString *)APIKey
  48. FDLSDKVersion:(NSString *)FDLSDKVersion
  49. delegate:(id<FIRDLRetrievalProcessDelegate>)delegate {
  50. NSParameterAssert(networkingService);
  51. NSParameterAssert(URLScheme);
  52. NSParameterAssert(APIKey);
  53. if (self = [super init]) {
  54. _networkingService = networkingService;
  55. _URLScheme = [URLScheme copy];
  56. _APIKey = [APIKey copy];
  57. _FDLSDKVersion = [FDLSDKVersion copy];
  58. _delegate = delegate;
  59. }
  60. return self;
  61. }
  62. #pragma mark - FIRDLRetrievalProcessProtocol
  63. - (void)retrievePendingDynamicLink {
  64. if (_localeFromWebView) {
  65. [self retrievePendingDynamicLinkInternal];
  66. } else {
  67. [self fetchLocaleFromWebView];
  68. }
  69. }
  70. #pragma mark - FIRDLJavaScriptExecutorDelegate
  71. - (void)javaScriptExecutor:(FIRDLJavaScriptExecutor *)executor
  72. completedExecutionWithResult:(NSString *)result {
  73. _localeFromWebView = result ?: @"";
  74. _jsExecutor = nil;
  75. [self retrievePendingDynamicLinkInternal];
  76. }
  77. - (void)javaScriptExecutor:(FIRDLJavaScriptExecutor *)executor failedWithError:(NSError *)error {
  78. _localeFromWebView = @"";
  79. _jsExecutor = nil;
  80. [self retrievePendingDynamicLinkInternal];
  81. }
  82. #pragma mark - Internal methods
  83. - (void)retrievePendingDynamicLinkInternal {
  84. CGRect mainScreenBounds = [UIScreen mainScreen].bounds;
  85. NSInteger resolutionWidth = mainScreenBounds.size.width;
  86. NSInteger resolutionHeight = mainScreenBounds.size.height;
  87. if ([[[UIDevice currentDevice] model] isEqualToString:@"iPad"] &&
  88. UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  89. // iPhone App running in compatibility mode on iPad
  90. // screen resolution reported by UIDevice/UIScreen will be wrong
  91. resolutionWidth = 0;
  92. resolutionHeight = 0;
  93. }
  94. NSURL *uniqueMatchLinkToCheck = [self uniqueMatchLinkToCheck];
  95. __weak __typeof__(self) weakSelf = self;
  96. FIRPostInstallAttributionCompletionHandler completionHandler =
  97. ^(NSDictionary *_Nullable dynamicLinkParameters, NSString *_Nullable matchMessage,
  98. NSError *_Nullable error) {
  99. __typeof__(self) strongSelf = weakSelf;
  100. if (!strongSelf) {
  101. return;
  102. }
  103. FIRDynamicLink *dynamicLink;
  104. if (dynamicLinkParameters.count) {
  105. dynamicLink = [[FIRDynamicLink alloc] initWithParametersDictionary:dynamicLinkParameters];
  106. }
  107. FIRDLRetrievalProcessResult *result =
  108. [[FIRDLRetrievalProcessResult alloc] initWithDynamicLink:dynamicLink
  109. error:error
  110. message:matchMessage
  111. matchSource:nil];
  112. [strongSelf handleRetrievalProcessWithResult:result];
  113. if (!error) {
  114. [strongSelf clearUsedUniqueMatchLinkToCheckFromClipboard];
  115. }
  116. };
  117. // Disable deprecated warning for internal methods.
  118. #pragma clang diagnostic push
  119. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  120. // If there is not a unique match, we will send an additional request for device heuristics based
  121. // matching.
  122. [_networkingService
  123. retrievePendingDynamicLinkWithIOSVersion:[UIDevice currentDevice].systemVersion
  124. resolutionHeight:resolutionHeight
  125. resolutionWidth:resolutionWidth
  126. locale:FIRDLDeviceLocale()
  127. localeRaw:FIRDLDeviceLocaleRaw()
  128. localeFromWebView:_localeFromWebView
  129. timezone:FIRDLDeviceTimezone()
  130. modelName:FIRDLDeviceModelName()
  131. FDLSDKVersion:_FDLSDKVersion
  132. appInstallationDate:FIRDLAppInstallationDate()
  133. uniqueMatchVisualStyle:FIRDynamicLinkNetworkingUniqueMatchVisualStyleUnknown
  134. retrievalProcessType:
  135. FIRDynamicLinkNetworkingRetrievalProcessTypeImplicitDefault
  136. uniqueMatchLinkToCheck:uniqueMatchLinkToCheck
  137. handler:completionHandler];
  138. #pragma clang pop
  139. }
  140. - (void)handleRetrievalProcessWithResult:(FIRDLRetrievalProcessResult *)result {
  141. if (!result) {
  142. // if we did not get any results, construct one
  143. NSString *message = NSLocalizedString(@"Pending dynamic link not found",
  144. @"Message when dynamic link was not found");
  145. result = [[FIRDLRetrievalProcessResult alloc] initWithDynamicLink:nil
  146. error:nil
  147. message:message
  148. matchSource:nil];
  149. }
  150. [self.delegate retrievalProcess:self completedWithResult:result];
  151. }
  152. - (nullable NSURL *)uniqueMatchLinkToCheck {
  153. _clipboardContentAtMatchProcessStart = nil;
  154. NSString *pasteboardContents = [self retrievePasteboardContents];
  155. if (!pasteboardContents) {
  156. return nil;
  157. }
  158. NSInteger linkStringMinimumLength =
  159. expectedCopiedLinkStringSuffix.length + /* ? or & */ 1 + /* http:// */ 7;
  160. if ((pasteboardContents.length >= linkStringMinimumLength) &&
  161. [pasteboardContents hasSuffix:expectedCopiedLinkStringSuffix] &&
  162. [NSURL URLWithString:pasteboardContents]) {
  163. // remove custom suffix and preceding '&' or '?' character from string
  164. NSString *linkStringWithoutSuffix = [pasteboardContents
  165. substringToIndex:pasteboardContents.length - expectedCopiedLinkStringSuffix.length - 1];
  166. NSURL *URL = [NSURL URLWithString:linkStringWithoutSuffix];
  167. if (URL) {
  168. // check is link matches short link format
  169. if (FIRDLMatchesShortLinkFormat(URL)) {
  170. _clipboardContentAtMatchProcessStart = pasteboardContents;
  171. return URL;
  172. }
  173. // check is link matches long link format
  174. if (FIRDLCanParseUniversalLinkURL(URL)) {
  175. _clipboardContentAtMatchProcessStart = pasteboardContents;
  176. return URL;
  177. }
  178. }
  179. }
  180. return nil;
  181. }
  182. - (nullable NSString *)retrievePasteboardContents {
  183. if (![self isPasteboardRetrievalEnabled]) {
  184. // Pasteboard check for dynamic link is disabled by user.
  185. return nil;
  186. }
  187. if ([[UIPasteboard generalPasteboard] hasURLs]) {
  188. return [UIPasteboard generalPasteboard].string;
  189. } else {
  190. return nil;
  191. }
  192. }
  193. /**
  194. Property to enable or disable dynamic link retrieval from Pasteboard.
  195. This property is added because of iOS 14 feature where pop up is displayed while accessing
  196. Pasteboard. So if developers don't want their users to see the Pasteboard popup, they can set
  197. "FirebaseDeepLinkPasteboardRetrievalEnabled" to false in their plist.
  198. */
  199. - (BOOL)isPasteboardRetrievalEnabled {
  200. id retrievalEnabledValue =
  201. [[NSBundle mainBundle] infoDictionary][@"FirebaseDeepLinkPasteboardRetrievalEnabled"];
  202. if ([retrievalEnabledValue respondsToSelector:@selector(boolValue)]) {
  203. return [retrievalEnabledValue boolValue];
  204. }
  205. return YES;
  206. }
  207. - (void)clearUsedUniqueMatchLinkToCheckFromClipboard {
  208. // See discussion in b/65304652
  209. // We will clear clipboard after we used the unique match link from the clipboard
  210. if (_clipboardContentAtMatchProcessStart.length > 0 &&
  211. [_clipboardContentAtMatchProcessStart isEqualToString:_clipboardContentAtMatchProcessStart]) {
  212. [UIPasteboard generalPasteboard].string = @"";
  213. }
  214. }
  215. - (void)fetchLocaleFromWebView {
  216. if (_jsExecutor) {
  217. return;
  218. }
  219. NSString *jsString = @"window.generateDeviceHeuristics=()=>navigator.language||''";
  220. _jsExecutor = [[FIRDLJavaScriptExecutor alloc] initWithDelegate:self script:jsString];
  221. }
  222. @end
  223. NS_ASSUME_NONNULL_END
  224. #endif // TARGET_OS_IOS