FIRFunctions.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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 useEmulatorWithHost:@"localhost" port:5005];
  131. }
  132. - (void)useEmulatorWithHost:(NSString *)host port:(NSInteger)port {
  133. NSAssert(host.length > 0, @"Cannot connect to nil or empty host");
  134. NSString *prefix = [host hasPrefix:@"http"] ? @"" : @"http://";
  135. NSString *origin = [NSString stringWithFormat:@"%@%@:%li", prefix, host, (long)port];
  136. _emulatorOrigin = origin;
  137. }
  138. - (void)useFunctionsEmulatorOrigin:(NSString *)origin {
  139. _emulatorOrigin = origin;
  140. }
  141. - (NSString *)URLWithName:(NSString *)name {
  142. if (!name) {
  143. FUNThrowInvalidArgument(@"FIRFunctions function name cannot be nil.");
  144. }
  145. if (!_projectID) {
  146. FUNThrowInvalidArgument(@"FIRFunctions app projectID cannot be nil.");
  147. }
  148. if (_emulatorOrigin) {
  149. return [NSString stringWithFormat:@"%@/%@/%@/%@", _emulatorOrigin, _projectID, _region, name];
  150. }
  151. if (_customDomain) {
  152. return [NSString stringWithFormat:@"%@/%@", _customDomain, name];
  153. }
  154. return
  155. [NSString stringWithFormat:@"https://%@-%@.cloudfunctions.net/%@", _region, _projectID, name];
  156. }
  157. - (void)callFunction:(NSString *)name
  158. withObject:(nullable id)data
  159. timeout:(NSTimeInterval)timeout
  160. completion:(void (^)(FIRHTTPSCallableResult *_Nullable result,
  161. NSError *_Nullable error))completion {
  162. [_contextProvider getContext:^(FUNContext *_Nullable context, NSError *_Nullable error) {
  163. if (error) {
  164. if (completion) {
  165. completion(nil, error);
  166. }
  167. return;
  168. }
  169. return [self callFunction:name
  170. withObject:data
  171. timeout:timeout
  172. context:context
  173. completion:completion];
  174. }];
  175. }
  176. - (void)callFunction:(NSString *)name
  177. withObject:(nullable id)data
  178. timeout:(NSTimeInterval)timeout
  179. context:(FUNContext *)context
  180. completion:(void (^)(FIRHTTPSCallableResult *_Nullable result,
  181. NSError *_Nullable error))completion {
  182. NSURL *url = [NSURL URLWithString:[self URLWithName:name]];
  183. NSURLRequest *request = [NSURLRequest requestWithURL:url
  184. cachePolicy:NSURLRequestUseProtocolCachePolicy
  185. timeoutInterval:timeout];
  186. GTMSessionFetcher *fetcher = [_fetcherService fetcherWithRequest:request];
  187. NSMutableDictionary *body = [NSMutableDictionary dictionary];
  188. // Encode the data in the body.
  189. if (!data) {
  190. data = [NSNull null];
  191. }
  192. id encoded = [_serializer encode:data];
  193. if (!encoded) {
  194. FUNThrowInvalidArgument(@"FIRFunctions data encoded as nil. This should not happen.");
  195. }
  196. body[@"data"] = encoded;
  197. NSError *error = nil;
  198. NSData *payload = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
  199. if (error) {
  200. if (completion) {
  201. dispatch_async(dispatch_get_main_queue(), ^{
  202. completion(nil, error);
  203. });
  204. }
  205. return;
  206. }
  207. fetcher.bodyData = payload;
  208. // Set the headers.
  209. [fetcher setRequestValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  210. if (context.authToken) {
  211. NSString *value = [NSString stringWithFormat:@"Bearer %@", context.authToken];
  212. [fetcher setRequestValue:value forHTTPHeaderField:@"Authorization"];
  213. }
  214. if (context.FCMToken) {
  215. [fetcher setRequestValue:context.FCMToken forHTTPHeaderField:kFUNFCMTokenHeader];
  216. }
  217. // Override normal security rules if this is a local test.
  218. if (_emulatorOrigin) {
  219. fetcher.allowLocalhostRequest = YES;
  220. fetcher.allowedInsecureSchemes = @[ @"http" ];
  221. }
  222. FUNSerializer *serializer = _serializer;
  223. [fetcher beginFetchWithCompletionHandler:^(NSData *_Nullable data, NSError *_Nullable error) {
  224. // If there was an HTTP error, convert it to our own error domain.
  225. if (error) {
  226. if ([error.domain isEqualToString:kGTMSessionFetcherStatusDomain]) {
  227. error = FUNErrorForResponse(error.code, data, serializer);
  228. }
  229. if ([error.domain isEqualToString:NSURLErrorDomain]) {
  230. if (error.code == NSURLErrorTimedOut) {
  231. error = FUNErrorForCode(FIRFunctionsErrorCodeDeadlineExceeded);
  232. }
  233. }
  234. } else {
  235. // If there wasn't an HTTP error, see if there was an error in the body.
  236. error = FUNErrorForResponse(200, data, serializer);
  237. }
  238. // If there was an error, report it to the user and stop.
  239. if (error) {
  240. if (completion) {
  241. completion(nil, error);
  242. }
  243. return;
  244. }
  245. id responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  246. if (error) {
  247. if (completion) {
  248. completion(nil, error);
  249. }
  250. return;
  251. }
  252. if (![responseJSON isKindOfClass:[NSDictionary class]]) {
  253. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : @"Response was not a dictionary."};
  254. error = [NSError errorWithDomain:FIRFunctionsErrorDomain
  255. code:FIRFunctionsErrorCodeInternal
  256. userInfo:userInfo];
  257. if (completion) {
  258. completion(nil, error);
  259. }
  260. return;
  261. }
  262. id dataJSON = responseJSON[@"data"];
  263. // TODO(klimt): Allow "result" instead of "data" for now, for backwards compatibility.
  264. if (!dataJSON) {
  265. dataJSON = responseJSON[@"result"];
  266. }
  267. if (!dataJSON) {
  268. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : @"Response is missing data field."};
  269. error = [NSError errorWithDomain:FIRFunctionsErrorDomain
  270. code:FIRFunctionsErrorCodeInternal
  271. userInfo:userInfo];
  272. if (completion) {
  273. completion(nil, error);
  274. }
  275. return;
  276. }
  277. id resultData = [serializer decode:dataJSON error:&error];
  278. if (error) {
  279. if (completion) {
  280. completion(nil, error);
  281. }
  282. return;
  283. }
  284. id result = [[FIRHTTPSCallableResult alloc] initWithData:resultData];
  285. if (completion) {
  286. // If there's no result field, this will return nil, which is fine.
  287. completion(result, nil);
  288. }
  289. }];
  290. }
  291. - (FIRHTTPSCallable *)HTTPSCallableWithName:(NSString *)name {
  292. return [[FIRHTTPSCallable alloc] initWithFunctions:self name:name];
  293. }
  294. - (nullable NSString *)emulatorOrigin {
  295. return _emulatorOrigin;
  296. }
  297. @end
  298. NS_ASSUME_NONNULL_END