FIRAppDistribution.m 13 KB

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