FIRAppDistribution.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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/Sources/Private/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. dependencies:@[]
  82. creationBlock:creationBlock];
  83. return @[ component ];
  84. }
  85. + (instancetype)appDistribution {
  86. // The container will return the same instance since isCacheable is set
  87. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  88. // Get the instance from the `FIRApp`'s container. This will create a new instance the
  89. // first time it is called, and since `isCacheable` is set in the component creation
  90. // block, it will return the existing instance on subsequent calls.
  91. id<FIRAppDistributionInstanceProvider> instance =
  92. FIR_COMPONENT(FIRAppDistributionInstanceProvider, defaultApp.container);
  93. // In the component creation block, we return an instance of `FIRAppDistribution`. Cast it and
  94. // return it.
  95. FIRFADDebugLog(@"Instance returned: %@", instance);
  96. return (FIRAppDistribution *)instance;
  97. }
  98. - (void)signInTesterWithCompletion:(void (^)(NSError *_Nullable error))completion {
  99. FIRFADDebugLog(@"Prompting tester for sign in");
  100. if ([self isTesterSignedIn]) {
  101. completion(nil);
  102. return;
  103. }
  104. [[self uiService] initializeUIState];
  105. FIRInstallations *installations = [FIRInstallations installations];
  106. // Get a Firebase Installation ID (FID).
  107. [installations installationIDWithCompletion:^(NSString *__nullable identifier,
  108. NSError *__nullable error) {
  109. if (error) {
  110. NSString *description = error.userInfo[NSLocalizedDescriptionKey]
  111. ? error.userInfo[NSLocalizedDescriptionKey]
  112. : @"Failed to retrieve Installation ID.";
  113. completion([self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
  114. message:description]);
  115. [[self uiService] resetUIState];
  116. return;
  117. }
  118. NSString *requestURL = [NSString
  119. stringWithFormat:@"https://appdistribution.firebase.dev/nba/pub/apps/%@/"
  120. @"installations/%@/buildalerts?appName=%@",
  121. [[FIRApp defaultApp] options].googleAppID, identifier, [self getAppName]];
  122. FIRFADDebugLog(@"Registration URL: %@", requestURL);
  123. [[self uiService]
  124. appDistributionRegistrationFlow:[[NSURL alloc] initWithString:requestURL]
  125. withCompletion:^(NSError *_Nullable error) {
  126. FIRFADInfoLog(@"Tester sign in complete.");
  127. if (error) {
  128. completion(error);
  129. return;
  130. }
  131. [self persistTesterSignInStateAndHandleCompletion:completion];
  132. }];
  133. }];
  134. }
  135. - (void)persistTesterSignInStateAndHandleCompletion:(void (^)(NSError *_Nullable error))completion {
  136. [FIRFADApiService
  137. fetchReleasesWithCompletion:^(NSArray *_Nullable releases, NSError *_Nullable error) {
  138. if (error) {
  139. FIRFADErrorLog(@"Tester Sign in persistence. Could not fetch releases with code %ld - %@",
  140. [error code], [error localizedDescription]);
  141. completion([self mapFetchReleasesError:error]);
  142. return;
  143. }
  144. [[GULUserDefaults standardUserDefaults] setBool:YES forKey:kFIRFADSignInStateKey];
  145. completion(nil);
  146. }];
  147. }
  148. - (NSString *)getAppName {
  149. NSBundle *mainBundle = [NSBundle mainBundle];
  150. NSString *name = [mainBundle objectForInfoDictionaryKey:@"CFBundleName"];
  151. if (name)
  152. return
  153. [name stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
  154. URLHostAllowedCharacterSet]];
  155. name = [mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
  156. return [name stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
  157. URLHostAllowedCharacterSet]];
  158. }
  159. - (NSString *)getAppVersion {
  160. return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
  161. }
  162. - (NSString *)getAppBuild {
  163. return [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
  164. }
  165. - (void)signOutTester {
  166. FIRFADDebugLog(@"Tester is signed out.");
  167. [[GULUserDefaults standardUserDefaults] setBool:NO forKey:kFIRFADSignInStateKey];
  168. }
  169. - (NSError *)NSErrorForErrorCodeAndMessage:(FIRAppDistributionError)errorCode
  170. message:(NSString *)message {
  171. NSDictionary *userInfo = @{FIRAppDistributionErrorDetailsKey : message};
  172. return [NSError errorWithDomain:FIRAppDistributionErrorDomain code:errorCode userInfo:userInfo];
  173. }
  174. - (NSError *_Nullable)mapFetchReleasesError:(NSError *)error {
  175. if ([error domain] == kFIRFADApiErrorDomain) {
  176. FIRFADErrorLog(@"Failed to retrieve releases: %ld", (long)[error code]);
  177. switch ([error code]) {
  178. case FIRFADApiErrorTimeout:
  179. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorNetworkFailure
  180. message:@"Failed to fetch releases due to timeout."];
  181. case FIRFADApiErrorUnauthenticated:
  182. case FIRFADApiErrorUnauthorized:
  183. case FIRFADApiTokenGenerationFailure:
  184. case FIRFADApiInstallationIdentifierError:
  185. case FIRFADApiErrorNotFound:
  186. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationFailure
  187. message:@"Could not authenticate tester"];
  188. default:
  189. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
  190. message:@"Failed to fetch releases for unknown reason."];
  191. }
  192. }
  193. FIRFADErrorLog(@"Failed to retrieve releases with unexpected domain %@: %ld", [error domain],
  194. (long)[error code]);
  195. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
  196. message:@"Failed to fetch releases for unknown reason."];
  197. }
  198. - (void)fetchNewLatestRelease:(void (^)(FIRAppDistributionRelease *_Nullable release,
  199. NSError *_Nullable error))completion {
  200. [FIRFADApiService
  201. fetchReleasesWithCompletion:^(NSArray *_Nullable releases, NSError *_Nullable error) {
  202. if (error) {
  203. if ([error code] == FIRFADApiErrorUnauthenticated) {
  204. FIRFADErrorLog(@"Tester authentication failed when fetching releases. Tester will need "
  205. @"to sign in again.");
  206. [self signOutTester];
  207. } else if ([error code] == FIRFADApiErrorUnauthorized) {
  208. FIRFADErrorLog(@"Tester is not authorized to view releases for this app. Tester will "
  209. @"need to sign in again.");
  210. [self signOutTester];
  211. }
  212. dispatch_async(dispatch_get_main_queue(), ^{
  213. completion(nil, [self mapFetchReleasesError:error]);
  214. });
  215. return;
  216. }
  217. for (NSDictionary *releaseDict in releases) {
  218. if ([[releaseDict objectForKey:kLatestReleaseKey] boolValue]) {
  219. FIRFADInfoLog(@"Tester API - found latest release in response.");
  220. NSString *displayVersion = [releaseDict objectForKey:kDisplayVersionKey];
  221. NSString *buildVersion = [releaseDict objectForKey:kBuildVersionKey];
  222. NSString *codeHash = [releaseDict objectForKey:kCodeHashKey];
  223. if (![self isCurrentVersion:displayVersion buildVersion:buildVersion] ||
  224. ![self isCodeHashIdentical:codeHash]) {
  225. FIRAppDistributionRelease *release =
  226. [[FIRAppDistributionRelease alloc] initWithDictionary:releaseDict];
  227. dispatch_async(dispatch_get_main_queue(), ^{
  228. FIRFADInfoLog(@"Found new release with version: %@ (%@)", [release displayVersion],
  229. [release buildVersion]);
  230. completion(release, nil);
  231. });
  232. return;
  233. }
  234. }
  235. }
  236. completion(nil, nil);
  237. }];
  238. }
  239. - (void)checkForUpdateWithCompletion:(void (^)(FIRAppDistributionRelease *_Nullable release,
  240. NSError *_Nullable error))completion {
  241. FIRFADInfoLog(@"CheckForUpdateWithCompletion");
  242. if ([self isTesterSignedIn]) {
  243. [self fetchNewLatestRelease:completion];
  244. } else {
  245. FIRFADUIActionCompletion actionCompletion = ^(BOOL continued) {
  246. if (continued) {
  247. [self signInTesterWithCompletion:^(NSError *_Nullable error) {
  248. if (error) {
  249. completion(nil, error);
  250. return;
  251. }
  252. [self fetchNewLatestRelease:completion];
  253. }];
  254. } else {
  255. completion(
  256. nil, [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationCancelled
  257. message:@"Tester cancelled authentication flow."]);
  258. }
  259. };
  260. [[self uiService] showUIAlertWithCompletion:actionCompletion];
  261. }
  262. }
  263. - (BOOL)isCurrentVersion:(NSString *)displayVersion buildVersion:(NSString *)buildVersion {
  264. FIRFADInfoLog(@"Checking if version matches");
  265. FIRFADInfoLog(@"App version: %@ (%@) Latest release version: %@ (%@)", [self getAppVersion],
  266. [self getAppBuild], displayVersion, buildVersion);
  267. return [displayVersion isEqualToString:[self getAppVersion]] &&
  268. [buildVersion isEqualToString:[self getAppBuild]];
  269. }
  270. - (BOOL)isCodeHashIdentical:(NSString *)codeHash {
  271. FIRFADInfoLog(@"Checking if code hash matches");
  272. NSString *executablePath = [[NSBundle mainBundle] executablePath];
  273. FIRAppDistributionMachO *machO = [[FIRAppDistributionMachO alloc] initWithPath:executablePath];
  274. FIRFADInfoLog(@"App code hash: %@ Latest release code hash: %@", [machO codeHash], codeHash);
  275. return codeHash && [codeHash isEqualToString:[machO codeHash]];
  276. }
  277. @end