-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathFIRDLDefaultRetrievalProcessV2.m
353 lines (315 loc) · 14.1 KB
/
FIRDLDefaultRetrievalProcessV2.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*
* Copyright 2018 Google
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "FirebaseDynamicLinks/Sources/FIRDLDefaultRetrievalProcessV2.h"
#import <UIKit/UIKit.h>
#import "FirebaseDynamicLinks/Sources/FIRDLJavaScriptExecutor.h"
#import "FirebaseDynamicLinks/Sources/FIRDLRetrievalProcessResult+Private.h"
#import "FirebaseDynamicLinks/Sources/FIRDynamicLink+Private.h"
#import "FirebaseDynamicLinks/Sources/FIRDynamicLinkNetworking.h"
#import "FirebaseDynamicLinks/Sources/Utilities/FDLUtilities.h"
// The maximum number of successful fingerprint api calls.
const static NSUInteger kMaximumNumberOfSuccessfulFingerprintAPICalls = 2;
// Reason for this string to ensure that only FDL links, copied to clipboard by AppPreview Page
// JavaScript code, are recognized and used in copy-unique-match process. If user copied FDL to
// clipboard by himself, that link must not be used in copy-unique-match process.
// This constant must be kept in sync with constant in the server version at
// durabledeeplink/click/ios/click_page.js
static NSString *expectedCopiedLinkStringSuffix = @"_icp=1";
NS_ASSUME_NONNULL_BEGIN
@interface FIRDLDefaultRetrievalProcessV2 () <FIRDLJavaScriptExecutorDelegate>
@property(atomic, strong) NSMutableArray *requestResults;
@end
@implementation FIRDLDefaultRetrievalProcessV2 {
FIRDynamicLinkNetworking *_networkingService;
NSString *_clientID;
NSString *_URLScheme;
NSString *_APIKey;
NSString *_FDLSDKVersion;
NSString *_clipboardContentAtMatchProcessStart;
FIRDLJavaScriptExecutor *_jsExecutor;
NSString *_localeFromWebView;
}
@synthesize delegate = _delegate;
#pragma mark - Initialization
- (instancetype)initWithNetworkingService:(FIRDynamicLinkNetworking *)networkingService
clientID:(NSString *)clientID
URLScheme:(NSString *)URLScheme
APIKey:(NSString *)APIKey
FDLSDKVersion:(NSString *)FDLSDKVersion
delegate:(id<FIRDLRetrievalProcessDelegate>)delegate {
NSParameterAssert(networkingService);
NSParameterAssert(clientID);
NSParameterAssert(URLScheme);
NSParameterAssert(APIKey);
if (self = [super init]) {
_networkingService = networkingService;
_clientID = [clientID copy];
_URLScheme = [URLScheme copy];
_APIKey = [APIKey copy];
_FDLSDKVersion = [FDLSDKVersion copy];
self.requestResults =
[[NSMutableArray alloc] initWithCapacity:kMaximumNumberOfSuccessfulFingerprintAPICalls];
_delegate = delegate;
}
return self;
}
#pragma mark - FIRDLRetrievalProcessProtocol
- (void)retrievePendingDynamicLink {
if (_localeFromWebView) {
[self retrievePendingDynamicLinkInternal];
} else {
[self fetchLocaleFromWebView];
}
}
- (BOOL)isCompleted {
return self.requestResults.count >= kMaximumNumberOfSuccessfulFingerprintAPICalls;
}
#pragma mark - FIRDLJavaScriptExecutorDelegate
- (void)javaScriptExecutor:(FIRDLJavaScriptExecutor *)executor
completedExecutionWithResult:(NSString *)result {
_localeFromWebView = result ?: @"";
_jsExecutor = nil;
[self retrievePendingDynamicLinkInternal];
}
- (void)javaScriptExecutor:(FIRDLJavaScriptExecutor *)executor failedWithError:(NSError *)error {
_localeFromWebView = @"";
_jsExecutor = nil;
[self retrievePendingDynamicLinkInternal];
}
#pragma mark - Internal methods
- (void)retrievePendingDynamicLinkInternal {
CGRect mainScreenBounds = [UIScreen mainScreen].bounds;
NSInteger resolutionWidth = mainScreenBounds.size.width;
NSInteger resolutionHeight = mainScreenBounds.size.height;
if ([[[UIDevice currentDevice] model] isEqualToString:@"iPad"] &&
UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
// iPhone App running in compatibility mode on iPad
// screen resolution reported by UIDevice/UIScreen will be wrong
resolutionWidth = 0;
resolutionHeight = 0;
}
NSURL *uniqueMatchLinkToCheck = [self uniqueMatchLinkToCheck];
__weak __typeof__(self) weakSelf = self;
FIRPostInstallAttributionCompletionHandler completionHandler =
^(NSDictionary *_Nullable dynamicLinkParameters, NSString *_Nullable matchMessage,
NSError *_Nullable error) {
__typeof__(self) strongSelf = weakSelf;
if (!strongSelf) {
return;
}
if (strongSelf.completed) {
// we may abort process and return previously found dynamic link before all requests
// completed
return;
}
FIRDynamicLink *dynamicLink;
if (dynamicLinkParameters.count) {
dynamicLink = [[FIRDynamicLink alloc] initWithParametersDictionary:dynamicLinkParameters];
}
FIRDLRetrievalProcessResult *result =
[[FIRDLRetrievalProcessResult alloc] initWithDynamicLink:dynamicLink
error:error
message:matchMessage
matchSource:nil];
[strongSelf.requestResults addObject:result];
[strongSelf handleRequestResultsUpdated];
if (!error) {
[strongSelf clearUsedUniqueMatchLinkToCheckFromClipboard];
}
};
// Disable deprecated warning for internal methods.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// If not unique match, we send request twice, since there are two server calls:
// one for IPv4, another for IPV6.
[_networkingService
retrievePendingDynamicLinkWithIOSVersion:[UIDevice currentDevice].systemVersion
resolutionHeight:resolutionHeight
resolutionWidth:resolutionWidth
locale:FIRDLDeviceLocale()
localeRaw:FIRDLDeviceLocaleRaw()
localeFromWebView:_localeFromWebView
timezone:FIRDLDeviceTimezone()
modelName:FIRDLDeviceModelName()
FDLSDKVersion:_FDLSDKVersion
appInstallationDate:FIRDLAppInstallationDate()
uniqueMatchVisualStyle:FIRDynamicLinkNetworkingUniqueMatchVisualStyleUnknown
retrievalProcessType:
FIRDynamicLinkNetworkingRetrievalProcessTypeImplicitDefault
uniqueMatchLinkToCheck:uniqueMatchLinkToCheck
handler:completionHandler];
#pragma clang pop
}
- (NSArray<FIRDLRetrievalProcessResult *> *)foundResultsWithDynamicLinks {
NSPredicate *predicate =
[NSPredicate predicateWithBlock:^BOOL(id _Nullable evaluatedObject,
NSDictionary<NSString *, id> *_Nullable bindings) {
if ([evaluatedObject isKindOfClass:[FIRDLRetrievalProcessResult class]]) {
FIRDLRetrievalProcessResult *result = (FIRDLRetrievalProcessResult *)evaluatedObject;
return result.dynamicLink.url != nil;
}
return NO;
}];
return [self.requestResults filteredArrayUsingPredicate:predicate];
}
- (NSArray<FIRDLRetrievalProcessResult *> *)resultsWithErrors {
NSPredicate *predicate =
[NSPredicate predicateWithBlock:^BOOL(id _Nullable evaluatedObject,
NSDictionary<NSString *, id> *_Nullable bindings) {
if ([evaluatedObject isKindOfClass:[FIRDLRetrievalProcessResult class]]) {
FIRDLRetrievalProcessResult *result = (FIRDLRetrievalProcessResult *)evaluatedObject;
return result.error != nil;
}
return NO;
}];
return [self.requestResults filteredArrayUsingPredicate:predicate];
}
- (NSArray<FIRDLRetrievalProcessResult *> *)results {
NSPredicate *predicate =
[NSPredicate predicateWithBlock:^BOOL(id _Nullable evaluatedObject,
NSDictionary<NSString *, id> *_Nullable bindings) {
return [evaluatedObject isKindOfClass:[FIRDLRetrievalProcessResult class]];
}];
return [self.requestResults filteredArrayUsingPredicate:predicate];
}
- (nullable FIRDLRetrievalProcessResult *)resultWithUniqueMatchedDynamicLink {
// return result with unique-matched dynamic link if found
NSArray<FIRDLRetrievalProcessResult *> *foundResultsWithDynamicLinks =
[self foundResultsWithDynamicLinks];
for (FIRDLRetrievalProcessResult *result in foundResultsWithDynamicLinks) {
if (result.dynamicLink.matchType == FIRDLMatchTypeUnique) {
return result;
}
}
return nil;
}
- (void)handleRequestResultsUpdated {
FIRDLRetrievalProcessResult *resultWithUniqueMatchedDynamicLink =
[self resultWithUniqueMatchedDynamicLink];
if (resultWithUniqueMatchedDynamicLink) {
[self markCompleted];
[self.delegate retrievalProcess:self completedWithResult:resultWithUniqueMatchedDynamicLink];
} else if (self.completed) {
NSArray<FIRDLRetrievalProcessResult *> *foundResultsWithDynamicLinks =
[self foundResultsWithDynamicLinks];
NSArray<FIRDLRetrievalProcessResult *> *resultsThatEncounteredErrors = [self resultsWithErrors];
if (foundResultsWithDynamicLinks.count) {
// return any result if no unique-matched URL is available
// TODO: Merge match message from all results
[self.delegate retrievalProcess:self
completedWithResult:foundResultsWithDynamicLinks.firstObject];
} else if (resultsThatEncounteredErrors.count > 0) {
// TODO: Merge match message and errors from all results
[self.delegate retrievalProcess:self
completedWithResult:resultsThatEncounteredErrors.firstObject];
} else {
// dynamic link not found
// TODO: Merge match message from all results
FIRDLRetrievalProcessResult *result = [[self results] firstObject];
if (!result) {
// if we did not get any results, construct one
NSString *message = NSLocalizedString(@"Pending dynamic link not found",
@"Message when dynamic link was not found");
result = [[FIRDLRetrievalProcessResult alloc] initWithDynamicLink:nil
error:nil
message:message
matchSource:nil];
}
[self.delegate retrievalProcess:self completedWithResult:result];
}
}
}
- (void)markCompleted {
while (!self.completed) {
[self.requestResults addObject:[NSNull null]];
}
}
- (nullable NSURL *)uniqueMatchLinkToCheck {
_clipboardContentAtMatchProcessStart = nil;
NSString *pasteboardContents = [self retrievePasteboardContents];
NSInteger linkStringMinimumLength =
expectedCopiedLinkStringSuffix.length + /* ? or & */ 1 + /* http:// */ 7;
if ((pasteboardContents.length >= linkStringMinimumLength) &&
[pasteboardContents hasSuffix:expectedCopiedLinkStringSuffix] &&
[NSURL URLWithString:pasteboardContents]) {
// remove custom suffix and preceding '&' or '?' character from string
NSString *linkStringWithoutSuffix = [pasteboardContents
substringToIndex:pasteboardContents.length - expectedCopiedLinkStringSuffix.length - 1];
NSURL *URL = [NSURL URLWithString:linkStringWithoutSuffix];
if (URL) {
// check is link matches short link format
if (FIRDLMatchesShortLinkFormat(URL)) {
_clipboardContentAtMatchProcessStart = pasteboardContents;
return URL;
}
// check is link matches long link format
if (FIRDLCanParseUniversalLinkURL(URL)) {
_clipboardContentAtMatchProcessStart = pasteboardContents;
return URL;
}
}
}
return nil;
}
- (NSString *)retrievePasteboardContents {
if (![self isPasteboardRetrievalEnabled]) {
// Pasteboard check for dynamic link is disabled by user.
return @"";
}
NSString *pasteboardContents = @"";
if (@available(iOS 10.0, *)) {
if ([[UIPasteboard generalPasteboard] hasURLs]) {
pasteboardContents = [UIPasteboard generalPasteboard].string;
}
} else {
pasteboardContents = [UIPasteboard generalPasteboard].string;
}
return pasteboardContents;
}
/**
Property to enable or disable dynamic link retrieval from Pasteboard.
This property is added because of iOS 14 feature where pop up is displayed while accessing
Pasteboard. So if developers don't want their users to see the Pasteboard popup, they can set
"FirebaseDeepLinkPasteboardRetrievalEnabled" to false in their plist.
*/
- (BOOL)isPasteboardRetrievalEnabled {
id retrievalEnabledValue =
[[NSBundle mainBundle] infoDictionary][@"FirebaseDeepLinkPasteboardRetrievalEnabled"];
if ([retrievalEnabledValue respondsToSelector:@selector(boolValue)]) {
return [retrievalEnabledValue boolValue];
}
return YES;
}
- (void)clearUsedUniqueMatchLinkToCheckFromClipboard {
// See discussion in b/65304652
// We will clear clipboard after we used the unique match link from the clipboard
if (_clipboardContentAtMatchProcessStart.length > 0 &&
[_clipboardContentAtMatchProcessStart isEqualToString:_clipboardContentAtMatchProcessStart]) {
[UIPasteboard generalPasteboard].string = @"";
}
}
- (void)fetchLocaleFromWebView {
if (_jsExecutor) {
return;
}
NSString *jsString = @"window.generateFingerprint=function(){try{var "
@"languageCode=navigator.languages?navigator.languages[0]:navigator."
@"language;return languageCode;}catch(b){return"
"}};";
_jsExecutor = [[FIRDLJavaScriptExecutor alloc] initWithDelegate:self script:jsString];
}
@end
NS_ASSUME_NONNULL_END