FIRFunctions.m 12 KB

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