FIRFunctions.m 10.0 KB

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