FIRFunctions.m 11 KB

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