FIRFunctions.m 11 KB

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