FIRAppDistribution.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. // Copyright 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import <Foundation/Foundation.h>
  15. #import <GoogleUtilities/GULAppDelegateSwizzler.h>
  16. #import <GoogleUtilities/GULUserDefaults.h>
  17. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  18. #import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
  19. #import "FirebaseAppDistribution/Sources/FIRAppDistributionMachO.h"
  20. #import "FirebaseAppDistribution/Sources/FIRAppDistributionUIService.h"
  21. #import "FirebaseAppDistribution/Sources/FIRFADApiService.h"
  22. #import "FirebaseAppDistribution/Sources/FIRFADLogger.h"
  23. #import "FirebaseAppDistribution/Sources/Private/FIRAppDistribution.h"
  24. #import "FirebaseAppDistribution/Sources/Private/FIRAppDistributionRelease.h"
  25. /// Empty protocol to register with FirebaseCore's component system.
  26. @protocol FIRAppDistributionInstanceProvider <NSObject>
  27. @end
  28. @interface FIRAppDistribution () <FIRLibrary, FIRAppDistributionInstanceProvider>
  29. @property(nonatomic) BOOL isTesterSignedIn;
  30. @property(nullable, nonatomic) FIRAppDistributionUIService *uiService;
  31. @end
  32. NSString *const FIRAppDistributionErrorDomain = @"com.firebase.appdistribution";
  33. NSString *const FIRAppDistributionErrorDetailsKey = @"details";
  34. @implementation FIRAppDistribution
  35. // The App Distribution Tester API endpoint used to retrieve releases
  36. NSString *const kReleasesEndpointURL = @"https://firebaseapptesters.googleapis.com/v1alpha/devices/"
  37. @"-/testerApps/%@/installations/%@/releases";
  38. NSString *const kAppDistroLibraryName = @"fire-fad";
  39. NSString *const kReleasesKey = @"releases";
  40. NSString *const kLatestReleaseKey = @"latest";
  41. NSString *const kCodeHashKey = @"codeHash";
  42. NSString *const kBuildVersionKey = @"buildVersion";
  43. NSString *const kDisplayVersionKey = @"displayVersion";
  44. NSString *const kAuthErrorMessage = @"Unable to authenticate the tester";
  45. NSString *const kAuthCancelledErrorMessage = @"Tester cancelled sign-in";
  46. NSString *const kFIRFADSignInStateKey = @"FIRFADSignInState";
  47. @synthesize isTesterSignedIn = _isTesterSignedIn;
  48. - (BOOL)isTesterSignedIn {
  49. BOOL signInState = [[GULUserDefaults standardUserDefaults] boolForKey:kFIRFADSignInStateKey];
  50. FIRFADInfoLog(@"Tester is %@signed in.", signInState ? @"" : @"not ");
  51. return signInState;
  52. }
  53. #pragma mark - Singleton Support
  54. - (instancetype)initWithApp:(FIRApp *)app appInfo:(NSDictionary *)appInfo {
  55. // FIRFADInfoLog(@"Initializing Firebase App Distribution");
  56. self = [super init];
  57. if (self) {
  58. [GULAppDelegateSwizzler proxyOriginalDelegate];
  59. self.uiService = [FIRAppDistributionUIService sharedInstance];
  60. [GULAppDelegateSwizzler registerAppDelegateInterceptor:[self uiService]];
  61. }
  62. return self;
  63. }
  64. + (void)load {
  65. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self withName:kAppDistroLibraryName];
  66. }
  67. + (NSArray<FIRComponent *> *)componentsToRegister {
  68. FIRComponentCreationBlock creationBlock =
  69. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  70. if (!container.app.isDefaultApp) {
  71. FIRFADErrorLog(@"Firebase App Distribution only works with the default app.");
  72. return nil;
  73. }
  74. *isCacheable = YES;
  75. return [[FIRAppDistribution alloc] initWithApp:container.app
  76. appInfo:NSBundle.mainBundle.infoDictionary];
  77. };
  78. FIRComponent *component =
  79. [FIRComponent componentWithProtocol:@protocol(FIRAppDistributionInstanceProvider)
  80. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  81. creationBlock:creationBlock];
  82. return @[ component ];
  83. }
  84. + (instancetype)appDistribution {
  85. // The container will return the same instance since isCacheable is set
  86. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  87. // Get the instance from the `FIRApp`'s container. This will create a new instance the
  88. // first time it is called, and since `isCacheable` is set in the component creation
  89. // block, it will return the existing instance on subsequent calls.
  90. id<FIRAppDistributionInstanceProvider> instance =
  91. FIR_COMPONENT(FIRAppDistributionInstanceProvider, defaultApp.container);
  92. // In the component creation block, we return an instance of `FIRAppDistribution`. Cast it and
  93. // return it.
  94. FIRFADDebugLog(@"Instance returned: %@", instance);
  95. return (FIRAppDistribution *)instance;
  96. }
  97. - (void)signInTesterWithCompletion:(void (^)(NSError *_Nullable error))completion {
  98. FIRFADDebugLog(@"Prompting tester for sign in");
  99. if ([self isTesterSignedIn]) {
  100. completion(nil);
  101. return;
  102. }
  103. [[self uiService] initializeUIState];
  104. FIRInstallations *installations = [FIRInstallations installations];
  105. // Get a Firebase Installation ID (FID).
  106. [installations installationIDWithCompletion:^(NSString *__nullable identifier,
  107. NSError *__nullable error) {
  108. if (error) {
  109. NSString *description = error.userInfo[NSLocalizedDescriptionKey]
  110. ? error.userInfo[NSLocalizedDescriptionKey]
  111. : @"Failed to retrieve Installation ID.";
  112. completion([self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
  113. message:description]);
  114. [[self uiService] resetUIState];
  115. return;
  116. }
  117. NSString *requestURL = [NSString
  118. stringWithFormat:@"https://appdistribution.firebase.google.com/pub/testerapps/%@/"
  119. @"installations/%@/buildalerts?appName=%@",
  120. [[FIRApp defaultApp] options].googleAppID, identifier, [self getAppName]];
  121. FIRFADDebugLog(@"Registration URL: %@", requestURL);
  122. [[self uiService]
  123. appDistributionRegistrationFlow:[[NSURL alloc] initWithString:requestURL]
  124. withCompletion:^(NSError *_Nullable error) {
  125. FIRFADInfoLog(@"Tester sign in complete.");
  126. if (error) {
  127. completion(error);
  128. return;
  129. }
  130. [self persistTesterSignInStateAndHandleCompletion:completion];
  131. }];
  132. }];
  133. }
  134. - (void)persistTesterSignInStateAndHandleCompletion:(void (^)(NSError *_Nullable error))completion {
  135. [FIRFADApiService
  136. fetchReleasesWithCompletion:^(NSArray *_Nullable releases, NSError *_Nullable error) {
  137. if (error) {
  138. FIRFADErrorLog(@"Tester Sign in persistence. Could not fetch releases with code %ld - %@",
  139. [error code], [error localizedDescription]);
  140. completion([self mapFetchReleasesError:error]);
  141. return;
  142. }
  143. [[GULUserDefaults standardUserDefaults] setBool:YES forKey:kFIRFADSignInStateKey];
  144. completion(nil);
  145. }];
  146. }
  147. - (NSString *)getAppName {
  148. NSBundle *mainBundle = [NSBundle mainBundle];
  149. NSString *name = [mainBundle objectForInfoDictionaryKey:@"CFBundleName"];
  150. if (name)
  151. return
  152. [name stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
  153. URLHostAllowedCharacterSet]];
  154. name = [mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
  155. return [name stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
  156. URLHostAllowedCharacterSet]];
  157. }
  158. - (NSString *)getAppVersion {
  159. return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
  160. }
  161. - (NSString *)getAppBuild {
  162. return [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
  163. }
  164. - (void)signOutTester {
  165. FIRFADDebugLog(@"Tester is signed out.");
  166. [[GULUserDefaults standardUserDefaults] setBool:NO forKey:kFIRFADSignInStateKey];
  167. }
  168. - (NSError *)NSErrorForErrorCodeAndMessage:(FIRAppDistributionError)errorCode
  169. message:(NSString *)message {
  170. NSDictionary *userInfo = @{FIRAppDistributionErrorDetailsKey : message};
  171. return [NSError errorWithDomain:FIRAppDistributionErrorDomain code:errorCode userInfo:userInfo];
  172. }
  173. - (NSError *_Nullable)mapFetchReleasesError:(NSError *)error {
  174. if ([error domain] == kFIRFADApiErrorDomain) {
  175. FIRFADErrorLog(@"Failed to retrieve releases: %ld", (long)[error code]);
  176. switch ([error code]) {
  177. case FIRFADApiErrorTimeout:
  178. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorNetworkFailure
  179. message:@"Failed to fetch releases due to timeout."];
  180. case FIRFADApiErrorUnauthenticated:
  181. case FIRFADApiErrorUnauthorized:
  182. case FIRFADApiTokenGenerationFailure:
  183. case FIRFADApiInstallationIdentifierError:
  184. case FIRFADApiErrorNotFound:
  185. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationFailure
  186. message:@"Could not authenticate tester"];
  187. default:
  188. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
  189. message:@"Failed to fetch releases for unknown reason."];
  190. }
  191. }
  192. FIRFADErrorLog(@"Failed to retrieve releases with unexpected domain %@: %ld", [error domain],
  193. (long)[error code]);
  194. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
  195. message:@"Failed to fetch releases for unknown reason."];
  196. }
  197. - (void)fetchNewLatestRelease:(void (^)(FIRAppDistributionRelease *_Nullable release,
  198. NSError *_Nullable error))completion {
  199. [FIRFADApiService
  200. fetchReleasesWithCompletion:^(NSArray *_Nullable releases, NSError *_Nullable error) {
  201. if (error) {
  202. if ([error code] == FIRFADApiErrorUnauthenticated) {
  203. FIRFADErrorLog(@"Tester authentication failed when fetching releases. Tester will need "
  204. @"to sign in again.");
  205. [self signOutTester];
  206. } else if ([error code] == FIRFADApiErrorUnauthorized) {
  207. FIRFADErrorLog(@"Tester is not authorized to view releases for this app. Tester will "
  208. @"need to sign in again.");
  209. [self signOutTester];
  210. }
  211. dispatch_async(dispatch_get_main_queue(), ^{
  212. completion(nil, [self mapFetchReleasesError:error]);
  213. });
  214. return;
  215. }
  216. for (NSDictionary *releaseDict in releases) {
  217. if ([[releaseDict objectForKey:kLatestReleaseKey] boolValue]) {
  218. FIRFADInfoLog(@"Tester API - found latest release in response.");
  219. NSString *displayVersion = [releaseDict objectForKey:kDisplayVersionKey];
  220. NSString *buildVersion = [releaseDict objectForKey:kBuildVersionKey];
  221. NSString *codeHash = [releaseDict objectForKey:kCodeHashKey];
  222. if (![self isCurrentVersion:displayVersion buildVersion:buildVersion] ||
  223. ![self isCodeHashIdentical:codeHash]) {
  224. FIRAppDistributionRelease *release =
  225. [[FIRAppDistributionRelease alloc] initWithDictionary:releaseDict];
  226. dispatch_async(dispatch_get_main_queue(), ^{
  227. FIRFADInfoLog(@"Found new release with version: %@ (%@)", [release displayVersion],
  228. [release buildVersion]);
  229. completion(release, nil);
  230. });
  231. return;
  232. }
  233. }
  234. }
  235. completion(nil, nil);
  236. }];
  237. }
  238. - (void)checkForUpdateWithCompletion:(void (^)(FIRAppDistributionRelease *_Nullable release,
  239. NSError *_Nullable error))completion {
  240. FIRFADInfoLog(@"CheckForUpdateWithCompletion");
  241. if ([self isTesterSignedIn]) {
  242. [self fetchNewLatestRelease:completion];
  243. } else {
  244. FIRFADUIActionCompletion actionCompletion = ^(BOOL continued) {
  245. if (continued) {
  246. [self signInTesterWithCompletion:^(NSError *_Nullable error) {
  247. if (error) {
  248. completion(nil, error);
  249. return;
  250. }
  251. [self fetchNewLatestRelease:completion];
  252. }];
  253. } else {
  254. completion(
  255. nil, [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationCancelled
  256. message:@"Tester cancelled authentication flow."]);
  257. }
  258. };
  259. [[self uiService] showUIAlertWithCompletion:actionCompletion];
  260. }
  261. }
  262. - (BOOL)isCurrentVersion:(NSString *)displayVersion buildVersion:(NSString *)buildVersion {
  263. FIRFADInfoLog(@"Checking if version matches");
  264. FIRFADInfoLog(@"App version: %@ (%@) Latest release version: %@ (%@)", [self getAppVersion],
  265. [self getAppBuild], displayVersion, buildVersion);
  266. return [displayVersion isEqualToString:[self getAppVersion]] &&
  267. [buildVersion isEqualToString:[self getAppBuild]];
  268. }
  269. - (BOOL)isCodeHashIdentical:(NSString *)codeHash {
  270. FIRFADInfoLog(@"Checking if code hash matches");
  271. NSString *executablePath = [[NSBundle mainBundle] executablePath];
  272. FIRAppDistributionMachO *machO = [[FIRAppDistributionMachO alloc] initWithPath:executablePath];
  273. FIRFADInfoLog(@"App code hash: %@ Latest release code hash: %@", [machO codeHash], codeHash);
  274. return codeHash && [codeHash isEqualToString:[machO codeHash]];
  275. }
  276. #pragma mark - Swizzling disabled
  277. - (BOOL)application:(UIApplication *)application
  278. openURL:(NSURL *)url
  279. options:(NSDictionary<NSString *, id> *)options {
  280. return [self.uiService application:application openURL:url options:options];
  281. }
  282. @end