FIRFunctions.m 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. // Copyright 2017 Google
  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 "FIRFunctions.h"
  15. #import "FIRFunctions+Internal.h"
  16. #import <FirebaseAuthInterop/FIRAuthInterop.h>
  17. #import <FirebaseCore/FIRComponent.h>
  18. #import <FirebaseCore/FIRComponentContainer.h>
  19. #import <FirebaseCore/FIRComponentRegistrant.h>
  20. #import <FirebaseCore/FIRDependency.h>
  21. #import "FIRError.h"
  22. #import "FIRHTTPSCallable+Internal.h"
  23. #import "FIRHTTPSCallable.h"
  24. #import "FUNContext.h"
  25. #import "FUNError.h"
  26. #import "FUNSerializer.h"
  27. #import "FUNUsageValidation.h"
  28. #import "FIRApp.h"
  29. #import "FIRAppInternal.h"
  30. #import "FIROptions.h"
  31. #import "GTMSessionFetcherService.h"
  32. NS_ASSUME_NONNULL_BEGIN
  33. NSString *const kFUNInstanceIDTokenHeader = @"Firebase-Instance-ID-Token";
  34. NSString *const kFUNDefaultRegion = @"us-central1";
  35. /// Empty protocol to register Functions as a component with Core.
  36. @protocol FIRFunctionsInstanceProvider
  37. @end
  38. @interface FIRFunctions () <FIRComponentRegistrant, FIRFunctionsInstanceProvider> {
  39. // The network client to use for http requests.
  40. GTMSessionFetcherService *_fetcherService;
  41. // The projectID to use for all function references.
  42. NSString *_projectID;
  43. // The region to use for all function references.
  44. NSString *_region;
  45. // A serializer to encode/decode data and return values.
  46. FUNSerializer *_serializer;
  47. // A factory for getting the metadata to include with function calls.
  48. FUNContextProvider *_contextProvider;
  49. // For testing only. If this is set, functions will be called against it instead of Firebase.
  50. NSString *_emulatorOrigin;
  51. }
  52. // Re-declare this initializer here in order to attribute it as the designated initializer.
  53. - (instancetype)initWithProjectID:(NSString *)projectID
  54. region:(NSString *)region
  55. auth:(nullable id<FIRAuthInterop>)auth NS_DESIGNATED_INITIALIZER;
  56. @end
  57. @implementation FIRFunctions
  58. + (void)load {
  59. [FIRComponentContainer registerAsComponentRegistrant:self];
  60. }
  61. + (NSArray<FIRComponent *> *)componentsToRegister {
  62. FIRComponentCreationBlock creationBlock =
  63. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  64. *isCacheable = YES;
  65. return [self functionsForApp:container.app];
  66. };
  67. FIRDependency *auth =
  68. [FIRDependency dependencyWithProtocol:@protocol(FIRAuthInterop) isRequired:NO];
  69. FIRComponent *internalProvider =
  70. [FIRComponent componentWithProtocol:@protocol(FIRFunctionsInstanceProvider)
  71. instantiationTiming:FIRInstantiationTimingLazy
  72. dependencies:@[ auth ]
  73. creationBlock:creationBlock];
  74. return @[ internalProvider ];
  75. }
  76. + (instancetype)functions {
  77. return [[self alloc] initWithApp:[FIRApp defaultApp] region:kFUNDefaultRegion];
  78. }
  79. + (instancetype)functionsForApp:(FIRApp *)app {
  80. return [[self alloc] initWithApp:app region:kFUNDefaultRegion];
  81. }
  82. + (instancetype)functionsForRegion:(NSString *)region {
  83. return [[self alloc] initWithApp:[FIRApp defaultApp] region:region];
  84. }
  85. + (instancetype)functionsForApp:(FIRApp *)app region:(NSString *)region {
  86. return [[self alloc] initWithApp:app region:region];
  87. }
  88. - (instancetype)initWithApp:(FIRApp *)app region:(NSString *)region {
  89. return [self initWithProjectID:app.options.projectID
  90. region:region
  91. auth:FIR_COMPONENT(FIRAuthInterop, app.container)];
  92. }
  93. - (instancetype)initWithProjectID:(NSString *)projectID
  94. region:(NSString *)region
  95. auth:(nullable id<FIRAuthInterop>)auth {
  96. self = [super init];
  97. if (self) {
  98. if (!region) {
  99. FUNThrowInvalidArgument(@"FIRFunctions region cannot be nil.");
  100. }
  101. _fetcherService = [[GTMSessionFetcherService alloc] init];
  102. _projectID = [projectID copy];
  103. _region = [region copy];
  104. _serializer = [[FUNSerializer alloc] init];
  105. _contextProvider = [[FUNContextProvider alloc] initWithAuth:auth];
  106. _emulatorOrigin = nil;
  107. }
  108. return self;
  109. }
  110. - (void)useLocalhost {
  111. [self useFunctionsEmulatorOrigin:@"http://localhost:5005"];
  112. }
  113. - (void)useFunctionsEmulatorOrigin:(NSString *)origin {
  114. _emulatorOrigin = origin;
  115. }
  116. - (NSString *)URLWithName:(NSString *)name {
  117. if (!name) {
  118. FUNThrowInvalidArgument(@"FIRFunctions function name cannot be nil.");
  119. }
  120. if (!_projectID) {
  121. FUNThrowInvalidArgument(@"FIRFunctions app projectID cannot be nil.");
  122. }
  123. if (_emulatorOrigin) {
  124. return [NSString stringWithFormat:@"%@/%@/%@/%@", _emulatorOrigin, _projectID, _region, name];
  125. }
  126. return
  127. [NSString stringWithFormat:@"https://%@-%@.cloudfunctions.net/%@", _region, _projectID, name];
  128. }
  129. - (void)callFunction:(NSString *)name
  130. withObject:(nullable id)data
  131. completion:(void (^)(FIRHTTPSCallableResult *_Nullable result,
  132. NSError *_Nullable error))completion {
  133. [_contextProvider getContext:^(FUNContext *_Nullable context, NSError *_Nullable error) {
  134. if (error) {
  135. if (completion) {
  136. completion(nil, error);
  137. }
  138. return;
  139. }
  140. return [self callFunction:name withObject:data context:context completion:completion];
  141. }];
  142. }
  143. - (void)callFunction:(NSString *)name
  144. withObject:(nullable id)data
  145. context:(FUNContext *)context
  146. completion:(void (^)(FIRHTTPSCallableResult *_Nullable result,
  147. NSError *_Nullable error))completion {
  148. GTMSessionFetcher *fetcher = [_fetcherService fetcherWithURLString:[self URLWithName:name]];
  149. NSMutableDictionary *body = [NSMutableDictionary dictionary];
  150. // Encode the data in the body.
  151. if (!data) {
  152. data = [NSNull null];
  153. }
  154. id encoded = [_serializer encode:data];
  155. if (!encoded) {
  156. FUNThrowInvalidArgument(@"FIRFunctions data encoded as nil. This should not happen.");
  157. }
  158. body[@"data"] = encoded;
  159. NSError *error = nil;
  160. NSData *payload = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
  161. if (error) {
  162. if (completion) {
  163. dispatch_async(dispatch_get_main_queue(), ^{
  164. completion(nil, error);
  165. });
  166. }
  167. return;
  168. }
  169. fetcher.bodyData = payload;
  170. // Set the headers.
  171. [fetcher setRequestValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  172. if (context.authToken) {
  173. NSString *value = [NSString stringWithFormat:@"Bearer %@", context.authToken];
  174. [fetcher setRequestValue:value forHTTPHeaderField:@"Authorization"];
  175. }
  176. if (context.instanceIDToken) {
  177. [fetcher setRequestValue:context.instanceIDToken forHTTPHeaderField:kFUNInstanceIDTokenHeader];
  178. }
  179. // Override normal security rules if this is a local test.
  180. if (_emulatorOrigin) {
  181. fetcher.allowLocalhostRequest = YES;
  182. fetcher.allowedInsecureSchemes = @[ @"http" ];
  183. }
  184. FUNSerializer *serializer = _serializer;
  185. [fetcher beginFetchWithCompletionHandler:^(NSData *_Nullable data, NSError *_Nullable error) {
  186. // If there was an HTTP error, convert it to our own error domain.
  187. if (error) {
  188. if ([error.domain isEqualToString:kGTMSessionFetcherStatusDomain]) {
  189. error = FUNErrorForResponse(error.code, data, serializer);
  190. }
  191. } else {
  192. // If there wasn't an HTTP error, see if there was an error in the body.
  193. error = FUNErrorForResponse(200, data, serializer);
  194. }
  195. // If there was an error, report it to the user and stop.
  196. if (error) {
  197. if (completion) {
  198. completion(nil, error);
  199. }
  200. return;
  201. }
  202. id responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  203. if (error) {
  204. if (completion) {
  205. completion(nil, error);
  206. }
  207. return;
  208. }
  209. if (![responseJSON isKindOfClass:[NSDictionary class]]) {
  210. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : @"Response was not a dictionary."};
  211. error = [NSError errorWithDomain:FIRFunctionsErrorDomain
  212. code:FIRFunctionsErrorCodeInternal
  213. userInfo:userInfo];
  214. if (completion) {
  215. completion(nil, error);
  216. }
  217. return;
  218. }
  219. id dataJSON = responseJSON[@"data"];
  220. // TODO(klimt): Allow "result" instead of "data" for now, for backwards compatibility.
  221. if (!dataJSON) {
  222. dataJSON = responseJSON[@"result"];
  223. }
  224. if (!dataJSON) {
  225. NSDictionary *userInfo =
  226. @{NSLocalizedDescriptionKey : @"Response did not include data field."};
  227. error = [NSError errorWithDomain:FIRFunctionsErrorDomain
  228. code:FIRFunctionsErrorCodeInternal
  229. userInfo:userInfo];
  230. if (completion) {
  231. completion(nil, error);
  232. }
  233. return;
  234. }
  235. id resultData = [serializer decode:dataJSON error:&error];
  236. if (error) {
  237. if (completion) {
  238. completion(nil, error);
  239. }
  240. return;
  241. }
  242. id result = [[FIRHTTPSCallableResult alloc] initWithData:resultData];
  243. if (completion) {
  244. // If there's no result field, this will return nil, which is fine.
  245. completion(result, nil);
  246. }
  247. }];
  248. }
  249. - (FIRHTTPSCallable *)HTTPSCallableWithName:(NSString *)name {
  250. return [[FIRHTTPSCallable alloc] initWithFunctions:self name:name];
  251. }
  252. @end
  253. NS_ASSUME_NONNULL_END