FIRAppDistribution.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 "FIRAppDistribution+Private.h"
  20. #import "FIRAppDistributionAppDelegateInterceptor.h"
  21. #import "FIRAppDistributionMachO+Private.h"
  22. #import "FIRAppDistributionRelease+Private.h"
  23. #import "FIRFADApiService+Private.h"
  24. #import "FIRFADLogger+Private.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) FIRAppDistributionAppDelegateInterceptor *appDelegateInterceptor;
  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.appDelegateInterceptor = [FIRAppDistributionAppDelegateInterceptor sharedInstance];
  58. [GULAppDelegateSwizzler registerAppDelegateInterceptor:self.appDelegateInterceptor];
  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. // TODO: Remove this and log error
  74. @throw([NSException exceptionWithName:@"NotImplementedException"
  75. reason:@"This code path is not implemented yet"
  76. userInfo:nil]);
  77. return nil;
  78. }
  79. *isCacheable = YES;
  80. return [[FIRAppDistribution alloc] initWithApp:container.app
  81. appInfo:NSBundle.mainBundle.infoDictionary];
  82. };
  83. FIRComponent *component =
  84. [FIRComponent componentWithProtocol:@protocol(FIRAppDistributionInstanceProvider)
  85. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  86. dependencies:@[]
  87. creationBlock:creationBlock];
  88. return @[ component ];
  89. }
  90. + (instancetype)appDistribution {
  91. // The container will return the same instance since isCacheable is set
  92. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  93. // Get the instance from the `FIRApp`'s container. This will create a new instance the
  94. // first time it is called, and since `isCacheable` is set in the component creation
  95. // block, it will return the existing instance on subsequent calls.
  96. id<FIRAppDistributionInstanceProvider> instance =
  97. FIR_COMPONENT(FIRAppDistributionInstanceProvider, defaultApp.container);
  98. // In the component creation block, we return an instance of `FIRAppDistribution`. Cast it and
  99. // return it.
  100. FIRFADDebugLog(@"Instance returned: %@", instance);
  101. return (FIRAppDistribution *)instance;
  102. }
  103. - (void)signInTesterWithCompletion:(void (^)(NSError *_Nullable error))completion {
  104. FIRFADDebugLog(@"Prompting tester for sign in");
  105. if ([self isTesterSignedIn]) {
  106. completion(nil);
  107. return;
  108. }
  109. [self.appDelegateInterceptor initializeUIState];
  110. FIRInstallations *installations = [FIRInstallations installations];
  111. // Get a Firebase Installation ID (FID).
  112. [installations installationIDWithCompletion:^(NSString *__nullable identifier,
  113. NSError *__nullable error) {
  114. if (error) {
  115. NSString *description = error.userInfo[NSLocalizedDescriptionKey]
  116. ? error.userInfo[NSLocalizedDescriptionKey]
  117. : @"Failed to retrieve Installation ID.";
  118. completion([self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
  119. message:description]);
  120. return;
  121. }
  122. NSString *requestURL = [NSString
  123. stringWithFormat:@"https://partnerdash.google.com/apps/appdistribution/pub/apps/%@/"
  124. @"installations/%@/buildalerts?appName=%@",
  125. [[FIRApp defaultApp] options].googleAppID, identifier, [self getAppName]];
  126. FIRFADDebugLog(@"Registration URL: %@", requestURL);
  127. [self.appDelegateInterceptor
  128. appDistributionRegistrationFlow:[[NSURL alloc] initWithString:requestURL]
  129. withCompletion:^(NSError *_Nullable error) {
  130. FIRFADInfoLog(@"Tester sign in complete.");
  131. if (!error) {
  132. [self persistTesterSignInState];
  133. }
  134. completion(error);
  135. }];
  136. }];
  137. }
  138. - (void)persistTesterSignInState {
  139. [FIRFADApiService
  140. fetchReleasesWithCompletion:^(NSArray *_Nullable releases, NSError *_Nullable error) {
  141. if (error) {
  142. FIRFADErrorLog(@"Could not fetch releases with code %ld - %@", [error code],
  143. [error localizedDescription]);
  144. return;
  145. }
  146. [[GULUserDefaults standardUserDefaults] setBool:YES forKey:kFIRFADSignInStateKey];
  147. }];
  148. }
  149. - (NSString *)getAppName {
  150. NSBundle *mainBundle = [NSBundle mainBundle];
  151. NSString *name = [mainBundle objectForInfoDictionaryKey:@"CFBundleName"];
  152. if (name)
  153. return
  154. [name stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
  155. URLHostAllowedCharacterSet]];
  156. name = [mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
  157. return [name stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
  158. URLHostAllowedCharacterSet]];
  159. }
  160. - (void)signOutTester {
  161. FIRFADDebugLog(@"Tester is signed out.");
  162. [[GULUserDefaults standardUserDefaults] setBool:NO forKey:kFIRFADSignInStateKey];
  163. }
  164. - (NSError *)NSErrorForErrorCodeAndMessage:(FIRAppDistributionError)errorCode
  165. message:(NSString *)message {
  166. NSDictionary *userInfo = @{FIRAppDistributionErrorDetailsKey : message};
  167. return [NSError errorWithDomain:FIRAppDistributionErrorDomain code:errorCode userInfo:userInfo];
  168. }
  169. - (NSError *_Nullable)handleFetchReleasesError:(NSError *)error {
  170. if ([error domain] == kFIRFADApiErrorDomain) {
  171. FIRFADErrorLog(@"Failed to retrieve releases: %ld", (long)[error code]);
  172. switch ([error code]) {
  173. case FIRFADApiErrorTimeout:
  174. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorNetworkFailure
  175. message:@"Failed to fetch releases due to timeout."];
  176. case FIRFADApiErrorUnauthenticated:
  177. case FIRFADApiErrorUnauthorized:
  178. case FIRFADApiTokenGenerationFailure:
  179. case FIRFADApiInstallationIdentifierError:
  180. case FIRFADApiErrorNotFound:
  181. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorAuthenticationFailure
  182. message:@"Could not authenticate tester"];
  183. default:
  184. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
  185. message:@"Failed to fetch releases for unknown reason."];
  186. }
  187. }
  188. FIRFADErrorLog(@"Failed to retrieve releases with unexpected domain %@: %ld", [error domain],
  189. (long)[error code]);
  190. return [self NSErrorForErrorCodeAndMessage:FIRAppDistributionErrorUnknown
  191. message:@"Failed to fetch releases for unknown reason."];
  192. }
  193. - (void)fetchNewLatestRelease:(FIRAppDistributionUpdateCheckCompletion)completion {
  194. [FIRFADApiService
  195. fetchReleasesWithCompletion:^(NSArray *_Nullable releases, NSError *_Nullable error) {
  196. if (error) {
  197. completion(nil, [self handleFetchReleasesError:error]);
  198. return;
  199. }
  200. for (NSDictionary *releaseDict in releases) {
  201. if ([[releaseDict objectForKey:kLatestReleaseKey] boolValue]) {
  202. FIRFADInfoLog(
  203. @"Tester API - found latest release in response. Checking if code hash match");
  204. NSString *codeHash = [releaseDict objectForKey:kCodeHashKey];
  205. NSString *executablePath = [[NSBundle mainBundle] executablePath];
  206. FIRAppDistributionMachO *machO =
  207. [[FIRAppDistributionMachO alloc] initWithPath:executablePath];
  208. FIRFADInfoLog(@"Code hash for the app on device - %@", machO.codeHash);
  209. FIRFADInfoLog(@"Code hash for the release from the service response - %@", codeHash);
  210. if (codeHash && ![codeHash isEqualToString:machO.codeHash]) {
  211. FIRAppDistributionRelease *release =
  212. [[FIRAppDistributionRelease alloc] initWithDictionary:releaseDict];
  213. dispatch_async(dispatch_get_main_queue(), ^{
  214. FIRFADInfoLog(@"Found new release with version: %@", [release displayVersion]);
  215. completion(release, nil);
  216. });
  217. return;
  218. }
  219. }
  220. }
  221. }];
  222. }
  223. - (void)checkForUpdateWithCompletion:(FIRAppDistributionUpdateCheckCompletion)completion {
  224. FIRFADInfoLog(@"CheckForUpdateWithCompletion");
  225. if ([self isTesterSignedIn]) {
  226. [self fetchNewLatestRelease:completion];
  227. } else {
  228. UIAlertController *alert = [UIAlertController
  229. alertControllerWithTitle:@"Enable in-app alerts"
  230. message:@"Sign in with your Firebase App Distribution Google account to "
  231. @"turn on in-app alerts for new test releases."
  232. preferredStyle:UIAlertControllerStyleAlert];
  233. UIAlertAction *yesButton =
  234. [UIAlertAction actionWithTitle:@"Turn on"
  235. style:UIAlertActionStyleDefault
  236. handler:^(UIAlertAction *action) {
  237. [self signInTesterWithCompletion:^(NSError *_Nullable error) {
  238. if (error) {
  239. completion(nil, error);
  240. return;
  241. }
  242. [self fetchNewLatestRelease:completion];
  243. }];
  244. }];
  245. UIAlertAction *noButton = [UIAlertAction actionWithTitle:@"Not now"
  246. style:UIAlertActionStyleDefault
  247. handler:^(UIAlertAction *action) {
  248. // precaution to ensure window gets destroyed
  249. [self.appDelegateInterceptor resetUIState];
  250. completion(nil, nil);
  251. }];
  252. [alert addAction:noButton];
  253. [alert addAction:yesButton];
  254. // Create an empty window + viewController to host the Safari UI.
  255. [self.appDelegateInterceptor showUIAlert:alert];
  256. }
  257. }
  258. @end