FIRAppDistribution.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 "FIRAppDistribution+Private.h"
  15. #import "FIRAppDistributionMachO+Private.h"
  16. #import "FIRAppDistributionRelease+Private.h"
  17. #import <FirebaseCore/FIRAppInternal.h>
  18. #import <FirebaseCore/FIRComponent.h>
  19. #import <FirebaseCore/FIRComponentContainer.h>
  20. #import <FirebaseCore/FIROptions.h>
  21. #import <GoogleUtilities/GULAppDelegateSwizzler.h>
  22. #import "FIRAppDistributionAppDelegateInterceptor.h"
  23. /// Empty protocol to register with FirebaseCore's component system.
  24. @protocol FIRAppDistributionInstanceProvider <NSObject>
  25. @end
  26. @interface FIRAppDistribution () <FIRLibrary, FIRAppDistributionInstanceProvider>
  27. @property(nonatomic) BOOL isTesterSignedIn;
  28. @end
  29. @implementation FIRAppDistribution
  30. // The OAuth scope needed to authorize the App Distribution Tester API
  31. NSString *const kOIDScopeTesterAPI = @"https://www.googleapis.com/auth/cloud-platform";
  32. // The App Distribution Tester API endpoint used to retrieve releases
  33. NSString *const kReleasesEndpointURL =
  34. @"https://firebaseapptesters.googleapis.com/v1alpha/devices/-/testerApps/%@/releases";
  35. NSString *const kTesterAPIClientID =
  36. @"319754533822-osu3v3hcci24umq6diathdm0dipds1fb.apps.googleusercontent.com";
  37. NSString *const kIssuerURL = @"https://accounts.google.com";
  38. NSString *const kAppDistroLibraryName = @"fire-fad";
  39. #pragma mark - Singleton Support
  40. - (instancetype)initWithApp:(FIRApp *)app appInfo:(NSDictionary *)appInfo {
  41. self = [super init];
  42. if (self) {
  43. self.safariHostingViewController = [[UIViewController alloc] init];
  44. [GULAppDelegateSwizzler proxyOriginalDelegate];
  45. FIRAppDistributionAppDelegatorInterceptor *interceptor =
  46. [FIRAppDistributionAppDelegatorInterceptor sharedInstance];
  47. [GULAppDelegateSwizzler registerAppDelegateInterceptor:interceptor];
  48. }
  49. // TODO: Lookup keychain to load auth state on init
  50. self.isTesterSignedIn = self.authState ? YES : NO;
  51. return self;
  52. }
  53. + (void)load {
  54. NSString *version =
  55. [NSString stringWithUTF8String:(const char *const)STR_EXPAND(FIRAppDistribution_VERSION)];
  56. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self
  57. withName:kAppDistroLibraryName
  58. withVersion:version];
  59. }
  60. + (NSArray<FIRComponent *> *)componentsToRegister {
  61. FIRComponentCreationBlock creationBlock =
  62. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  63. if (!container.app.isDefaultApp) {
  64. // TODO: Implement error handling
  65. @throw([NSException exceptionWithName:@"NotImplementedException"
  66. reason:@"This code path is not implemented yet"
  67. userInfo:nil]);
  68. return nil;
  69. }
  70. *isCacheable = YES;
  71. return [[FIRAppDistribution alloc] initWithApp:container.app
  72. appInfo:NSBundle.mainBundle.infoDictionary];
  73. };
  74. FIRComponent *component =
  75. [FIRComponent componentWithProtocol:@protocol(FIRAppDistributionInstanceProvider)
  76. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  77. dependencies:@[]
  78. creationBlock:creationBlock];
  79. return @[ component ];
  80. }
  81. + (instancetype)appDistribution {
  82. // The container will return the same instance since isCacheable is set
  83. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  84. // Get the instance from the `FIRApp`'s container. This will create a new instance the
  85. // first time it is called, and since `isCacheable` is set in the component creation
  86. // block, it will return the existing instance on subsequent calls.
  87. id<FIRAppDistributionInstanceProvider> instance =
  88. FIR_COMPONENT(FIRAppDistributionInstanceProvider, defaultApp.container);
  89. // In the component creation block, we return an instance of `FIRAppDistribution`. Cast it and
  90. // return it.
  91. return (FIRAppDistribution *)instance;
  92. }
  93. - (void)signInTesterWithCompletion:(void (^)(NSError *_Nullable error))completion {
  94. NSURL *issuer = [NSURL URLWithString:kIssuerURL];
  95. [OIDAuthorizationService
  96. discoverServiceConfigurationForIssuer:issuer
  97. completion:^(OIDServiceConfiguration *_Nullable configuration,
  98. NSError *_Nullable error) {
  99. [self handleOauthDiscoveryCompletion:configuration
  100. error:error
  101. appDistributionSignInCompletion:completion];
  102. }];
  103. }
  104. - (void)signOutTester {
  105. self.authState = nil;
  106. self.isTesterSignedIn = false;
  107. }
  108. - (void)fetchReleases:(FIRAppDistributionUpdateCheckCompletion)completion {
  109. NSURLSession *URLSession = [NSURLSession sharedSession];
  110. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  111. NSString *URLString =
  112. [NSString stringWithFormat:kReleasesEndpointURL, [[FIRApp defaultApp] options].googleAppID];
  113. [request setURL:[NSURL URLWithString:URLString]];
  114. [request setHTTPMethod:@"GET"];
  115. [request setValue:[NSString
  116. stringWithFormat:@"Bearer %@", self.authState.lastTokenResponse.accessToken]
  117. forHTTPHeaderField:@"Authorization"];
  118. NSURLSessionDataTask *listReleasesDataTask = [URLSession
  119. dataTaskWithRequest:request
  120. completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  121. if (error) {
  122. // TODO: Reformat error into error code
  123. completion(nil, error);
  124. return;
  125. }
  126. NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
  127. if (HTTPResponse.statusCode == 200) {
  128. [self handleReleasesAPIResponseWithData:data completion:completion];
  129. } else {
  130. // TODO: Handle non-200 http response
  131. @throw([NSException exceptionWithName:@"NotImplementedException"
  132. reason:@"This code path is not implemented yet"
  133. userInfo:nil]);
  134. }
  135. }];
  136. [listReleasesDataTask resume];
  137. }
  138. - (void)handleOauthDiscoveryCompletion:(OIDServiceConfiguration *_Nullable)configuration
  139. error:(NSError *_Nullable)error
  140. appDistributionSignInCompletion:(void (^)(NSError *_Nullable error))completion {
  141. if (!configuration) {
  142. // TODO: Handle when we cannot get configuration
  143. @throw([NSException exceptionWithName:@"NotImplementedException"
  144. reason:@"This code path is not implemented yet"
  145. userInfo:nil]);
  146. return;
  147. }
  148. NSString *redirectURL = [@"dev.firebase.appdistribution."
  149. stringByAppendingString:[[[NSBundle mainBundle] bundleIdentifier]
  150. stringByAppendingString:@":/launch"]];
  151. OIDAuthorizationRequest *request = [[OIDAuthorizationRequest alloc]
  152. initWithConfiguration:configuration
  153. clientId:kTesterAPIClientID
  154. scopes:@[ OIDScopeOpenID, OIDScopeProfile, kOIDScopeTesterAPI ]
  155. redirectURL:[NSURL URLWithString:redirectURL]
  156. responseType:OIDResponseTypeCode
  157. additionalParameters:nil];
  158. [self createUIWindowForLogin];
  159. // performs authentication request
  160. [FIRAppDistributionAppDelegatorInterceptor sharedInstance].currentAuthorizationFlow =
  161. [OIDAuthState authStateByPresentingAuthorizationRequest:request
  162. presentingViewController:self.safariHostingViewController
  163. callback:^(OIDAuthState *_Nullable authState,
  164. NSError *_Nullable error) {
  165. self.authState = authState;
  166. self.isTesterSignedIn =
  167. self.authState ? YES : NO;
  168. completion(error);
  169. }];
  170. }
  171. - (UIWindow *)createUIWindowForLogin {
  172. // Create an empty window + viewController to host the Safari UI.
  173. UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  174. window.rootViewController = self.safariHostingViewController;
  175. // Place it at the highest level within the stack.
  176. window.windowLevel = +CGFLOAT_MAX;
  177. // Run it.
  178. [window makeKeyAndVisible];
  179. return window;
  180. }
  181. - (void)handleReleasesAPIResponseWithData:data
  182. completion:(FIRAppDistributionUpdateCheckCompletion)completion {
  183. NSError *error = nil;
  184. NSDictionary *object = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  185. NSArray *releaseList = [object objectForKey:@"releases"];
  186. for (NSDictionary *releaseDict in releaseList) {
  187. if (![[releaseDict objectForKey:@"latest"] boolValue]) continue;
  188. NSString *codeHash = [releaseDict objectForKey:@"codeHash"];
  189. FIRAppDistributionMachO *machO =
  190. [[FIRAppDistributionMachO alloc] initWithPath:[[NSBundle mainBundle] executablePath]];
  191. if (![codeHash isEqualToString:machO.codeHash]) {
  192. FIRAppDistributionRelease *release =
  193. [[FIRAppDistributionRelease alloc] initWithDictionary:releaseDict];
  194. dispatch_async(dispatch_get_main_queue(), ^{
  195. completion(release, nil);
  196. });
  197. }
  198. }
  199. }
  200. - (void)checkForUpdateWithCompletion:(FIRAppDistributionUpdateCheckCompletion)completion {
  201. if (self.isTesterSignedIn) {
  202. [self fetchReleases:completion];
  203. } else {
  204. UIAlertController *alert = [UIAlertController
  205. alertControllerWithTitle:@"Enable in-app alerts"
  206. message:@"Sign in with your Firebase App Distribution Google account to "
  207. @"turn on in-app alerts for new test releases."
  208. preferredStyle:UIAlertControllerStyleAlert];
  209. UIAlertAction *yesButton =
  210. [UIAlertAction actionWithTitle:@"Turn on"
  211. style:UIAlertActionStyleDefault
  212. handler:^(UIAlertAction *action) {
  213. [self signInTesterWithCompletion:^(NSError *_Nullable error) {
  214. self.window.hidden = YES;
  215. self.window = nil;
  216. if (error) {
  217. completion(nil, error);
  218. return;
  219. }
  220. [self fetchReleases:completion];
  221. }];
  222. }];
  223. UIAlertAction *noButton = [UIAlertAction actionWithTitle:@"Not now"
  224. style:UIAlertActionStyleDefault
  225. handler:^(UIAlertAction *action) {
  226. // precaution to ensure window gets destroyed
  227. self.window.hidden = YES;
  228. self.window = nil;
  229. completion(nil, nil);
  230. }];
  231. [alert addAction:noButton];
  232. [alert addAction:yesButton];
  233. // Create an empty window + viewController to host the Safari UI.
  234. self.window = [self createUIWindowForLogin];
  235. [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
  236. }
  237. }
  238. @end