FIRDLDefaultRetrievalProcessV2.m 9.9 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 fingerprinting.
  121. [_networkingService
  122. retrievePendingDynamicLinkWithIOSVersion:[UIDevice currentDevice].systemVersion
  123. resolutionHeight:resolutionHeight
  124. resolutionWidth:resolutionWidth
  125. locale:FIRDLDeviceLocale()
  126. localeRaw:FIRDLDeviceLocaleRaw()
  127. localeFromWebView:_localeFromWebView
  128. timezone:FIRDLDeviceTimezone()
  129. modelName:FIRDLDeviceModelName()
  130. FDLSDKVersion:_FDLSDKVersion
  131. appInstallationDate:FIRDLAppInstallationDate()
  132. uniqueMatchVisualStyle:FIRDynamicLinkNetworkingUniqueMatchVisualStyleUnknown
  133. retrievalProcessType:
  134. FIRDynamicLinkNetworkingRetrievalProcessTypeImplicitDefault
  135. uniqueMatchLinkToCheck:uniqueMatchLinkToCheck
  136. handler:completionHandler];
  137. #pragma clang pop
  138. }
  139. - (void)handleRetrievalProcessWithResult:(FIRDLRetrievalProcessResult *)result {
  140. if (!result) {
  141. // if we did not get any results, construct one
  142. NSString *message = NSLocalizedString(@"Pending dynamic link not found",
  143. @"Message when dynamic link was not found");
  144. result = [[FIRDLRetrievalProcessResult alloc] initWithDynamicLink:nil
  145. error:nil
  146. message:message
  147. matchSource:nil];
  148. }
  149. [self.delegate retrievalProcess:self completedWithResult:result];
  150. }
  151. - (nullable NSURL *)uniqueMatchLinkToCheck {
  152. _clipboardContentAtMatchProcessStart = nil;
  153. NSString *pasteboardContents = [self retrievePasteboardContents];
  154. NSInteger linkStringMinimumLength =
  155. expectedCopiedLinkStringSuffix.length + /* ? or & */ 1 + /* http:// */ 7;
  156. if ((pasteboardContents.length >= linkStringMinimumLength) &&
  157. [pasteboardContents hasSuffix:expectedCopiedLinkStringSuffix] &&
  158. [NSURL URLWithString:pasteboardContents]) {
  159. // remove custom suffix and preceding '&' or '?' character from string
  160. NSString *linkStringWithoutSuffix = [pasteboardContents
  161. substringToIndex:pasteboardContents.length - expectedCopiedLinkStringSuffix.length - 1];
  162. NSURL *URL = [NSURL URLWithString:linkStringWithoutSuffix];
  163. if (URL) {
  164. // check is link matches short link format
  165. if (FIRDLMatchesShortLinkFormat(URL)) {
  166. _clipboardContentAtMatchProcessStart = pasteboardContents;
  167. return URL;
  168. }
  169. // check is link matches long link format
  170. if (FIRDLCanParseUniversalLinkURL(URL)) {
  171. _clipboardContentAtMatchProcessStart = pasteboardContents;
  172. return URL;
  173. }
  174. }
  175. }
  176. return nil;
  177. }
  178. - (NSString *)retrievePasteboardContents {
  179. if (![self isPasteboardRetrievalEnabled]) {
  180. // Pasteboard check for dynamic link is disabled by user.
  181. return @"";
  182. }
  183. NSString *pasteboardContents = @"";
  184. if (@available(iOS 10.0, *)) {
  185. if ([[UIPasteboard generalPasteboard] hasURLs]) {
  186. pasteboardContents = [UIPasteboard generalPasteboard].string;
  187. }
  188. } else {
  189. pasteboardContents = [UIPasteboard generalPasteboard].string;
  190. }
  191. return pasteboardContents;
  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.generateFingerprint=()=>navigator.language||''";
  220. _jsExecutor = [[FIRDLJavaScriptExecutor alloc] initWithDelegate:self script:jsString];
  221. }
  222. @end
  223. NS_ASSUME_NONNULL_END
  224. #endif // TARGET_OS_IOS