-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathFIRAppDistribution.m
347 lines (282 loc) · 13.9 KB
/
FIRAppDistribution.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
// Copyright 2020 Google LLC
//
// 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 <Foundation/Foundation.h>
#import <GoogleUtilities/GULAppDelegateSwizzler.h>
#import <GoogleUtilities/GULUserDefaults.h>
#import "FirebaseCore/Extension/FirebaseCoreInternal.h"
#import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
#import "FirebaseAppDistribution/Sources/FIRAppDistributionMachO.h"
#import "FirebaseAppDistribution/Sources/FIRAppDistributionUIService.h"
#import "FirebaseAppDistribution/Sources/FIRFADApiService.h"
#import "FirebaseAppDistribution/Sources/FIRFADLogger.h"
#import "FirebaseAppDistribution/Sources/Private/FIRAppDistribution.h"
#import "FirebaseAppDistribution/Sources/Private/FIRAppDistributionRelease.h"
/// Empty protocol to register with FirebaseCore's component system.
@protocol FIRAppDistributionInstanceProvider <NSObject>
@end
@interface FIRAppDistribution () <FIRLibrary, FIRAppDistributionInstanceProvider>
@property(nonatomic) BOOL isTesterSignedIn;
@property(nullable, nonatomic) FIRAppDistributionUIService *uiService;
@end
NSString *const FIRAppDistributionErrorDomain = @"com.firebase.appdistribution";
NSString *const FIRAppDistributionErrorDetailsKey = @"details";
@implementation FIRAppDistribution
// The App Distribution Tester API endpoint used to retrieve releases
NSString *const kReleasesEndpointURL = @"https://firebaseapptesters.googleapis.com/v1alpha/devices/"
@"-/testerApps/%@/installations/%@/releases";
NSString *const kAppDistroLibraryName = @"fire-fad";
NSString *const kReleasesKey = @"releases";
NSString *const kLatestReleaseKey = @"latest";
NSString *const kCodeHashKey = @"codeHash";
NSString *const kBuildVersionKey = @"buildVersion";
NSString *const kDisplayVersionKey = @"displayVersion";
NSString *const kAuthErrorMessage = @"Unable to authenticate the tester";
NSString *const kAuthCancelledErrorMessage = @"Tester cancelled sign-in";
NSString *const kFIRFADSignInStateKey = @"FIRFADSignInState";
@synthesize isTesterSignedIn = _isTesterSignedIn;
- (BOOL)isTesterSignedIn {
BOOL signInState = [[GULUserDefaults standardUserDefaults] boolForKey:kFIRFADSignInStateKey];
FIRFADInfoLog(@"Tester is %@signed in.", signInState ? @"" : @"not ");
return signInState;
}
#pragma mark - Singleton Support
- (instancetype)initWithApp:(FIRApp *)app appInfo:(NSDictionary *)appInfo {
// FIRFADInfoLog(@"Initializing Firebase App Distribution");
self = [super init];
if (self) {
[GULAppDelegateSwizzler proxyOriginalDelegate];
self.uiService = [FIRAppDistributionUIService sharedInstance];
[GULAppDelegateSwizzler registerAppDelegateInterceptor:[self uiService]];
}
return self;
}
+ (void)load {
[FIRApp registerInternalLibrary:(Class<FIRLibrary>)self withName:kAppDistroLibraryName];
}
+ (NSArray<FIRComponent *> *)componentsToRegister {
FIRComponentCreationBlock creationBlock =
^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
if (!container.app.isDefaultApp) {
FIRFADErrorLog(@"Firebase App Distribution only works with the default app.");
return nil;
}
*isCacheable = YES;
return [[FIRAppDistribution alloc] initWithApp:container.app
appInfo:NSBundle.mainBundle.infoDictionary];
};
FIRComponent *component =
[FIRComponent componentWithProtocol:@protocol(FIRAppDistributionInstanceProvider)
instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
creationBlock:creationBlock];
return @[ component ];
}
+ (instancetype)appDistribution {
// The container will return the same instance since isCacheable is set
FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
// Get the instance from the `FIRApp`'s container. This will create a new instance the
// first time it is called, and since `isCacheable` is set in the component creation
// block, it will return the existing instance on subsequent calls.
id<FIRAppDistributionInstanceProvider> instance =
FIR_COMPONENT(FIRAppDistributionInstanceProvider, defaultApp.container);
// In the component creation block, we return an instance of `FIRAppDistribution`. Cast it and
// return it.
FIRFADDebugLog(@"Instance returned: %@", instance);
return (FIRAppDistribution *)instance;
}
- (void)signInTesterWithCompletion:(void (^)(NSError *_Nullable error))completion {
FIRFADDebugLog(@"Prompting tester for sign in");
if ([self isTesterSignedIn]) {
completion(nil);
return;
}
[[self uiService] initializeUIState];
FIRInstallations *installations = [FIRInstallations installations];
// Get a Firebase Installation ID (FID).
[installations installationIDWithCompletion:^(NSString *__nullable identifier,
NSError *__nullable error) {
if (error) {
NSString *description = error.userInfo[NSLocalizedDescriptionKey]
? error.userInfo[NSLocalizedDescriptionKey]
: @"Failed to retrieve Installation ID.";
completion([self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
message:description]);
[[self uiService] resetUIState];
return;
}
NSString *requestURL = [NSString
stringWithFormat:@"https://appdistribution.firebase.google.com/pub/testerapps/%@/"
@"installations/%@/buildalerts?appName=%@",
[[FIRApp defaultApp] options].googleAppID, identifier, [self getAppName]];
FIRFADDebugLog(@"Registration URL: %@", requestURL);
[[self uiService]
appDistributionRegistrationFlow:[[NSURL alloc] initWithString:requestURL]
withCompletion:^(NSError *_Nullable error) {
FIRFADInfoLog(@"Tester sign in complete.");
if (error) {
completion(error);
return;
}
[self persistTesterSignInStateAndHandleCompletion:completion];
}];
}];
}
- (void)persistTesterSignInStateAndHandleCompletion:(void (^)(NSError *_Nullable error))completion {
[FIRFADApiService
fetchReleasesWithCompletion:^(NSArray *_Nullable releases, NSError *_Nullable error) {
if (error) {
FIRFADErrorLog(@"Tester Sign in persistence. Could not fetch releases with code %ld - %@",
[error code], [error localizedDescription]);
completion([self mapFetchReleasesError:error]);
return;
}
[[GULUserDefaults standardUserDefaults] setBool:YES forKey:kFIRFADSignInStateKey];
completion(nil);
}];
}
- (NSString *)getAppName {
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *name = [mainBundle objectForInfoDictionaryKey:@"CFBundleName"];
if (name)
return
[name stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
URLHostAllowedCharacterSet]];
name = [mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
return [name stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
URLHostAllowedCharacterSet]];
}
- (NSString *)getAppVersion {
return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
}
- (NSString *)getAppBuild {
return [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
}
- (void)signOutTester {
FIRFADDebugLog(@"Tester is signed out.");
[[GULUserDefaults standardUserDefaults] setBool:NO forKey:kFIRFADSignInStateKey];
}
- (NSError *)NSErrorForErrorCodeAndMessage:(FIRAppDistributionError)errorCode
message:(NSString *)message {
NSDictionary *userInfo = @{FIRAppDistributionErrorDetailsKey : message};
return [NSError errorWithDomain:FIRAppDistributionErrorDomain code:errorCode userInfo:userInfo];
}
- (NSError *_Nullable)mapFetchReleasesError:(NSError *)error {
if ([error domain] == kFIRFADApiErrorDomain) {
FIRFADErrorLog(@"Failed to retrieve releases: %ld", (long)[error code]);
switch ([error code]) {
case FIRFADApiErrorTimeout:
return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorNetworkFailure
message:@"Failed to fetch releases due to timeout."];
case FIRFADApiErrorUnauthenticated:
case FIRFADApiErrorUnauthorized:
case FIRFADApiTokenGenerationFailure:
case FIRFADApiInstallationIdentifierError:
case FIRFADApiErrorNotFound:
return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationFailure
message:@"Could not authenticate tester"];
default:
return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
message:@"Failed to fetch releases for unknown reason."];
}
}
FIRFADErrorLog(@"Failed to retrieve releases with unexpected domain %@: %ld", [error domain],
(long)[error code]);
return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
message:@"Failed to fetch releases for unknown reason."];
}
- (void)fetchNewLatestRelease:(void (^)(FIRAppDistributionRelease *_Nullable release,
NSError *_Nullable error))completion {
[FIRFADApiService
fetchReleasesWithCompletion:^(NSArray *_Nullable releases, NSError *_Nullable error) {
if (error) {
if ([error code] == FIRFADApiErrorUnauthenticated) {
FIRFADErrorLog(@"Tester authentication failed when fetching releases. Tester will need "
@"to sign in again.");
[self signOutTester];
} else if ([error code] == FIRFADApiErrorUnauthorized) {
FIRFADErrorLog(@"Tester is not authorized to view releases for this app. Tester will "
@"need to sign in again.");
[self signOutTester];
}
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, [self mapFetchReleasesError:error]);
});
return;
}
for (NSDictionary *releaseDict in releases) {
if ([[releaseDict objectForKey:kLatestReleaseKey] boolValue]) {
FIRFADInfoLog(@"Tester API - found latest release in response.");
NSString *displayVersion = [releaseDict objectForKey:kDisplayVersionKey];
NSString *buildVersion = [releaseDict objectForKey:kBuildVersionKey];
NSString *codeHash = [releaseDict objectForKey:kCodeHashKey];
if (![self isCurrentVersion:displayVersion buildVersion:buildVersion] ||
![self isCodeHashIdentical:codeHash]) {
FIRAppDistributionRelease *release =
[[FIRAppDistributionRelease alloc] initWithDictionary:releaseDict];
dispatch_async(dispatch_get_main_queue(), ^{
FIRFADInfoLog(@"Found new release with version: %@ (%@)", [release displayVersion],
[release buildVersion]);
completion(release, nil);
});
return;
}
}
}
completion(nil, nil);
}];
}
- (void)checkForUpdateWithCompletion:(void (^)(FIRAppDistributionRelease *_Nullable release,
NSError *_Nullable error))completion {
FIRFADInfoLog(@"CheckForUpdateWithCompletion");
if ([self isTesterSignedIn]) {
[self fetchNewLatestRelease:completion];
} else {
FIRFADUIActionCompletion actionCompletion = ^(BOOL continued) {
if (continued) {
[self signInTesterWithCompletion:^(NSError *_Nullable error) {
if (error) {
completion(nil, error);
return;
}
[self fetchNewLatestRelease:completion];
}];
} else {
completion(
nil, [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationCancelled
message:@"Tester cancelled authentication flow."]);
}
};
[[self uiService] showUIAlertWithCompletion:actionCompletion];
}
}
- (BOOL)isCurrentVersion:(NSString *)displayVersion buildVersion:(NSString *)buildVersion {
FIRFADInfoLog(@"Checking if version matches");
FIRFADInfoLog(@"App version: %@ (%@) Latest release version: %@ (%@)", [self getAppVersion],
[self getAppBuild], displayVersion, buildVersion);
return [displayVersion isEqualToString:[self getAppVersion]] &&
[buildVersion isEqualToString:[self getAppBuild]];
}
- (BOOL)isCodeHashIdentical:(NSString *)codeHash {
FIRFADInfoLog(@"Checking if code hash matches");
NSString *executablePath = [[NSBundle mainBundle] executablePath];
FIRAppDistributionMachO *machO = [[FIRAppDistributionMachO alloc] initWithPath:executablePath];
FIRFADInfoLog(@"App code hash: %@ Latest release code hash: %@", [machO codeHash], codeHash);
return codeHash && [codeHash isEqualToString:[machO codeHash]];
}
#pragma mark - Swizzling disabled
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<NSString *, id> *)options {
return [self.uiService application:application openURL:url options:options];
}
@end