FIRAppDistribution.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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 "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  16. #import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
  17. #import "GoogleUtilities/AppDelegateSwizzler/Private/GULAppDelegateSwizzler.h"
  18. #import "GoogleUtilities/UserDefaults/Private/GULUserDefaults.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 kAuthErrorMessage = @"Unable to authenticate the tester";
  43. NSString *const kAuthCancelledErrorMessage = @"Tester cancelled sign-in";
  44. NSString *const kFIRFADSignInStateKey = @"FIRFADSignInState";
  45. @synthesize isTesterSignedIn = _isTesterSignedIn;
  46. - (BOOL)isTesterSignedIn {
  47. BOOL signInState = [[GULUserDefaults standardUserDefaults] boolForKey:kFIRFADSignInStateKey];
  48. FIRFADInfoLog(@"Tester is %@signed in.", signInState ? @"" : @"not ");
  49. return signInState;
  50. }
  51. #pragma mark - Singleton Support
  52. - (instancetype)initWithApp:(FIRApp *)app appInfo:(NSDictionary *)appInfo {
  53. // FIRFADInfoLog(@"Initializing Firebase App Distribution");
  54. self = [super init];
  55. if (self) {
  56. [GULAppDelegateSwizzler proxyOriginalDelegate];
  57. self.uiService = [FIRAppDistributionUIService sharedInstance];
  58. [GULAppDelegateSwizzler registerAppDelegateInterceptor:[self uiService]];
  59. }
  60. return self;
  61. }
  62. + (void)load {
  63. NSString *version =
  64. [NSString stringWithUTF8String:(const char *const)STR_EXPAND(FIRAppDistribution_VERSION)];
  65. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self
  66. withName:kAppDistroLibraryName
  67. withVersion:version];
  68. }
  69. + (NSArray<FIRComponent *> *)componentsToRegister {
  70. FIRComponentCreationBlock creationBlock =
  71. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  72. if (!container.app.isDefaultApp) {
  73. FIRFADErrorLog(@"Firebase App Distribution only works with the default app.");
  74. return nil;
  75. }
  76. *isCacheable = YES;
  77. return [[FIRAppDistribution alloc] initWithApp:container.app
  78. appInfo:NSBundle.mainBundle.infoDictionary];
  79. };
  80. FIRComponent *component =
  81. [FIRComponent componentWithProtocol:@protocol(FIRAppDistributionInstanceProvider)
  82. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  83. dependencies:@[]
  84. creationBlock:creationBlock];
  85. return @[ component ];
  86. }
  87. + (instancetype)appDistribution {
  88. // The container will return the same instance since isCacheable is set
  89. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  90. // Get the instance from the `FIRApp`'s container. This will create a new instance the
  91. // first time it is called, and since `isCacheable` is set in the component creation
  92. // block, it will return the existing instance on subsequent calls.
  93. id<FIRAppDistributionInstanceProvider> instance =
  94. FIR_COMPONENT(FIRAppDistributionInstanceProvider, defaultApp.container);
  95. // In the component creation block, we return an instance of `FIRAppDistribution`. Cast it and
  96. // return it.
  97. FIRFADDebugLog(@"Instance returned: %@", instance);
  98. return (FIRAppDistribution *)instance;
  99. }
  100. - (void)signInTesterWithCompletion:(void (^)(NSError *_Nullable error))completion {
  101. FIRFADDebugLog(@"Prompting tester for sign in");
  102. if ([self isTesterSignedIn]) {
  103. completion(nil);
  104. return;
  105. }
  106. [[self uiService] initializeUIState];
  107. FIRInstallations *installations = [FIRInstallations installations];
  108. // Get a Firebase Installation ID (FID).
  109. [installations installationIDWithCompletion:^(NSString *__nullable identifier,
  110. NSError *__nullable error) {
  111. if (error) {
  112. NSString *description = error.userInfo[NSLocalizedDescriptionKey]
  113. ? error.userInfo[NSLocalizedDescriptionKey]
  114. : @"Failed to retrieve Installation ID.";
  115. completion([self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
  116. message:description]);
  117. [[self uiService] resetUIState];
  118. return;
  119. }
  120. NSString *requestURL = [NSString
  121. stringWithFormat:@"https://appdistribution.firebase.dev/nba/pub/apps/%@/"
  122. @"installations/%@/buildalerts?appName=%@",
  123. [[FIRApp defaultApp] options].googleAppID, identifier, [self getAppName]];
  124. FIRFADDebugLog(@"Registration URL: %@", requestURL);
  125. [[self uiService]
  126. appDistributionRegistrationFlow:[[NSURL alloc] initWithString:requestURL]
  127. withCompletion:^(NSError *_Nullable error) {
  128. FIRFADInfoLog(@"Tester sign in complete.");
  129. if (error) {
  130. completion(error);
  131. return;
  132. }
  133. [self persistTesterSignInStateAndHandleCompletion:completion];
  134. }];
  135. }];
  136. }
  137. - (void)persistTesterSignInStateAndHandleCompletion:(void (^)(NSError *_Nullable error))completion {
  138. [FIRFADApiService
  139. fetchReleasesWithCompletion:^(NSArray *_Nullable releases, NSError *_Nullable error) {
  140. if (error) {
  141. FIRFADErrorLog(@"Tester Sign in persistence. Could not fetch releases with code %ld - %@",
  142. [error code], [error localizedDescription]);
  143. completion([self mapFetchReleasesError:error]);
  144. return;
  145. }
  146. [[GULUserDefaults standardUserDefaults] setBool:YES forKey:kFIRFADSignInStateKey];
  147. completion(nil);
  148. }];
  149. }
  150. - (NSString *)getAppName {
  151. NSBundle *mainBundle = [NSBundle mainBundle];
  152. NSString *name = [mainBundle objectForInfoDictionaryKey:@"CFBundleName"];
  153. if (name)
  154. return
  155. [name stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
  156. URLHostAllowedCharacterSet]];
  157. name = [mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
  158. return [name stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
  159. URLHostAllowedCharacterSet]];
  160. }
  161. - (void)signOutTester {
  162. FIRFADDebugLog(@"Tester is signed out.");
  163. [[GULUserDefaults standardUserDefaults] setBool:NO forKey:kFIRFADSignInStateKey];
  164. }
  165. - (NSError *)NSErrorForErrorCodeAndMessage:(FIRAppDistributionError)errorCode
  166. message:(NSString *)message {
  167. NSDictionary *userInfo = @{FIRAppDistributionErrorDetailsKey : message};
  168. return [NSError errorWithDomain:FIRAppDistributionErrorDomain code:errorCode userInfo:userInfo];
  169. }
  170. - (NSError *_Nullable)mapFetchReleasesError:(NSError *)error {
  171. if ([error domain] == kFIRFADApiErrorDomain) {
  172. FIRFADErrorLog(@"Failed to retrieve releases: %ld", (long)[error code]);
  173. switch ([error code]) {
  174. case FIRFADApiErrorTimeout:
  175. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorNetworkFailure
  176. message:@"Failed to fetch releases due to timeout."];
  177. case FIRFADApiErrorUnauthenticated:
  178. case FIRFADApiErrorUnauthorized:
  179. case FIRFADApiTokenGenerationFailure:
  180. case FIRFADApiInstallationIdentifierError:
  181. case FIRFADApiErrorNotFound:
  182. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationFailure
  183. message:@"Could not authenticate tester"];
  184. default:
  185. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
  186. message:@"Failed to fetch releases for unknown reason."];
  187. }
  188. }
  189. FIRFADErrorLog(@"Failed to retrieve releases with unexpected domain %@: %ld", [error domain],
  190. (long)[error code]);
  191. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
  192. message:@"Failed to fetch releases for unknown reason."];
  193. }
  194. - (void)fetchNewLatestRelease:(FIRAppDistributionUpdateCheckCompletion)completion {
  195. [FIRFADApiService
  196. fetchReleasesWithCompletion:^(NSArray *_Nullable releases, NSError *_Nullable error) {
  197. if (error) {
  198. dispatch_async(dispatch_get_main_queue(), ^{
  199. completion(nil, [self mapFetchReleasesError:error]);
  200. });
  201. return;
  202. }
  203. for (NSDictionary *releaseDict in releases) {
  204. if ([[releaseDict objectForKey:kLatestReleaseKey] boolValue]) {
  205. FIRFADInfoLog(
  206. @"Tester API - found latest release in response. Checking if code hash match");
  207. NSString *codeHash = [releaseDict objectForKey:kCodeHashKey];
  208. NSString *executablePath = [[NSBundle mainBundle] executablePath];
  209. FIRAppDistributionMachO *machO =
  210. [[FIRAppDistributionMachO alloc] initWithPath:executablePath];
  211. FIRFADInfoLog(@"Code hash for the app on device - %@", machO.codeHash);
  212. FIRFADInfoLog(@"Code hash for the release from the service response - %@", codeHash);
  213. if (codeHash && ![codeHash isEqualToString:machO.codeHash]) {
  214. FIRAppDistributionRelease *release =
  215. [[FIRAppDistributionRelease alloc] initWithDictionary:releaseDict];
  216. dispatch_async(dispatch_get_main_queue(), ^{
  217. FIRFADInfoLog(@"Found new release with version: %@", [release displayVersion]);
  218. completion(release, nil);
  219. });
  220. return;
  221. }
  222. }
  223. }
  224. completion(nil, nil);
  225. }];
  226. }
  227. - (void)checkForUpdateWithCompletion:(FIRAppDistributionUpdateCheckCompletion)completion {
  228. FIRFADInfoLog(@"CheckForUpdateWithCompletion");
  229. if ([self isTesterSignedIn]) {
  230. [self fetchNewLatestRelease:completion];
  231. } else {
  232. FIRFADUIActionCompletion actionCompletion = ^(BOOL continued) {
  233. if (continued) {
  234. [self signInTesterWithCompletion:^(NSError *_Nullable error) {
  235. if (error) {
  236. completion(nil, error);
  237. return;
  238. }
  239. [self fetchNewLatestRelease:completion];
  240. }];
  241. } else {
  242. completion(
  243. nil, [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationCancelled
  244. message:@"Tester cancelled authentication flow."]);
  245. }
  246. };
  247. [[self uiService] showUIAlertWithCompletion:actionCompletion];
  248. }
  249. }
  250. @end