No Description

RNFetchBlobNetwork.m 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. //
  2. // RNFetchBlobNetwork.m
  3. // RNFetchBlob
  4. //
  5. // Created by wkh237 on 2016/6/6.
  6. // Copyright © 2016 wkh237. All rights reserved.
  7. //
  8. #import <Foundation/Foundation.h>
  9. #import "RNFetchBlob.h"
  10. #import "RNFetchBlobFS.h"
  11. #import "RNFetchBlobNetwork.h"
  12. #import "RNFetchBlobConst.h"
  13. #import "RNFetchBlobReqBuilder.h"
  14. #import "IOS7Polyfill.h"
  15. #import <CommonCrypto/CommonDigest.h>
  16. #import "RNFetchBlobProgress.h"
  17. #if __has_include(<React/RCTAssert.h>)
  18. #import <React/RCTRootView.h>
  19. #import <React/RCTLog.h>
  20. #import <React/RCTEventDispatcher.h>
  21. #import <React/RCTBridge.h>
  22. #else
  23. #import "RCTRootView.h"
  24. #import "RCTLog.h"
  25. #import "RCTEventDispatcher.h"
  26. #import "RCTBridge.h"
  27. #endif
  28. ////////////////////////////////////////
  29. //
  30. // HTTP request handler
  31. //
  32. ////////////////////////////////////////
  33. NSMapTable * taskTable;
  34. NSMapTable * expirationTable;
  35. NSMutableDictionary * progressTable;
  36. NSMutableDictionary * uploadProgressTable;
  37. __attribute__((constructor))
  38. static void initialize_tables() {
  39. if(expirationTable == nil)
  40. {
  41. expirationTable = [[NSMapTable alloc] init];
  42. }
  43. if(taskTable == nil)
  44. {
  45. taskTable = [[NSMapTable alloc] init];
  46. }
  47. if(progressTable == nil)
  48. {
  49. progressTable = [[NSMutableDictionary alloc] init];
  50. }
  51. if(uploadProgressTable == nil)
  52. {
  53. uploadProgressTable = [[NSMutableDictionary alloc] init];
  54. }
  55. }
  56. typedef NS_ENUM(NSUInteger, ResponseFormat) {
  57. UTF8,
  58. BASE64,
  59. AUTO
  60. };
  61. @interface RNFetchBlobNetwork ()
  62. {
  63. BOOL respFile;
  64. BOOL isNewPart;
  65. BOOL isIncrement;
  66. NSMutableData * partBuffer;
  67. NSString * destPath;
  68. NSOutputStream * writeStream;
  69. long bodyLength;
  70. NSInteger respStatus;
  71. NSMutableArray * redirects;
  72. ResponseFormat responseFormat;
  73. BOOL followRedirect;
  74. BOOL backgroundTask;
  75. }
  76. @end
  77. @implementation RNFetchBlobNetwork
  78. NSOperationQueue *taskQueue;
  79. @synthesize taskId;
  80. @synthesize expectedBytes;
  81. @synthesize receivedBytes;
  82. @synthesize respData;
  83. @synthesize callback;
  84. @synthesize bridge;
  85. @synthesize options;
  86. @synthesize error;
  87. // constructor
  88. - (id)init {
  89. self = [super init];
  90. @synchronized ([RNFetchBlobNetwork class]) {
  91. if (taskQueue == nil) {
  92. taskQueue = [[NSOperationQueue alloc] init];
  93. taskQueue.maxConcurrentOperationCount = 10;
  94. }
  95. }
  96. return self;
  97. }
  98. + (void) enableProgressReport:(NSString *) taskId config:(RNFetchBlobProgress *)config
  99. {
  100. @synchronized ([RNFetchBlobNetwork class]) {
  101. if(progressTable == nil)
  102. {
  103. progressTable = [[NSMutableDictionary alloc] init];
  104. }
  105. if (config) [progressTable setValue:config forKey:taskId];
  106. }
  107. }
  108. + (void) enableUploadProgress:(NSString *) taskId config:(RNFetchBlobProgress *)config
  109. {
  110. @synchronized ([RNFetchBlobNetwork class]) {
  111. if(uploadProgressTable == nil)
  112. {
  113. uploadProgressTable = [[NSMutableDictionary alloc] init];
  114. }
  115. if (config) [uploadProgressTable setValue:config forKey:taskId];
  116. }
  117. }
  118. // removing case from headers
  119. + (NSMutableDictionary *) normalizeHeaders:(NSDictionary *)headers
  120. {
  121. NSMutableDictionary * mheaders = [[NSMutableDictionary alloc]init];
  122. for(NSString * key in headers) {
  123. [mheaders setValue:[headers valueForKey:key] forKey:[key lowercaseString]];
  124. }
  125. return mheaders;
  126. }
  127. - (NSString *)md5:(NSString *)input {
  128. const char* str = [input UTF8String];
  129. unsigned char result[CC_MD5_DIGEST_LENGTH];
  130. CC_MD5(str, (CC_LONG)strlen(str), result);
  131. NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
  132. for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
  133. [ret appendFormat:@"%02x",result[i]];
  134. }
  135. return ret;
  136. }
  137. // send HTTP request
  138. - (void) sendRequest:(__weak NSDictionary * _Nullable )options
  139. contentLength:(long) contentLength
  140. bridge:(RCTBridge * _Nullable)bridgeRef
  141. taskId:(NSString * _Nullable)taskId
  142. withRequest:(__weak NSURLRequest * _Nullable)req
  143. callback:(_Nullable RCTResponseSenderBlock) callback
  144. {
  145. self.taskId = taskId;
  146. self.respData = [[NSMutableData alloc] initWithLength:0];
  147. self.callback = callback;
  148. self.bridge = bridgeRef;
  149. self.expectedBytes = 0;
  150. self.receivedBytes = 0;
  151. self.options = options;
  152. backgroundTask = [options valueForKey:@"IOSBackgroundTask"] == nil ? NO : [[options valueForKey:@"IOSBackgroundTask"] boolValue];
  153. followRedirect = [options valueForKey:@"followRedirect"] == nil ? YES : [[options valueForKey:@"followRedirect"] boolValue];
  154. isIncrement = [options valueForKey:@"increment"] == nil ? NO : [[options valueForKey:@"increment"] boolValue];
  155. redirects = [[NSMutableArray alloc] init];
  156. if(req.URL != nil)
  157. [redirects addObject:req.URL.absoluteString];
  158. // set response format
  159. NSString * rnfbResp = [req.allHTTPHeaderFields valueForKey:@"RNFB-Response"];
  160. if([[rnfbResp lowercaseString] isEqualToString:@"base64"])
  161. responseFormat = BASE64;
  162. else if([[rnfbResp lowercaseString] isEqualToString:@"utf8"])
  163. responseFormat = UTF8;
  164. else
  165. responseFormat = AUTO;
  166. NSString * path = [self.options valueForKey:CONFIG_FILE_PATH];
  167. NSString * key = [self.options valueForKey:CONFIG_KEY];
  168. NSURLSession * session;
  169. bodyLength = contentLength;
  170. // the session trust any SSL certification
  171. NSURLSessionConfiguration *defaultConfigObject;
  172. defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
  173. if(backgroundTask)
  174. {
  175. defaultConfigObject = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:taskId];
  176. }
  177. // set request timeout
  178. float timeout = [options valueForKey:@"timeout"] == nil ? -1 : [[options valueForKey:@"timeout"] floatValue];
  179. if(timeout > 0)
  180. {
  181. defaultConfigObject.timeoutIntervalForRequest = timeout/1000;
  182. }
  183. defaultConfigObject.HTTPMaximumConnectionsPerHost = 10;
  184. session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:taskQueue];
  185. if(path != nil || [self.options valueForKey:CONFIG_USE_TEMP]!= nil)
  186. {
  187. respFile = YES;
  188. NSString* cacheKey = taskId;
  189. if (key != nil) {
  190. cacheKey = [self md5:key];
  191. if (cacheKey == nil) {
  192. cacheKey = taskId;
  193. }
  194. destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
  195. if ([[NSFileManager defaultManager] fileExistsAtPath:destPath]) {
  196. callback(@[[NSNull null], RESP_TYPE_PATH, destPath]);
  197. return;
  198. }
  199. }
  200. if(path != nil)
  201. destPath = path;
  202. else
  203. destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
  204. }
  205. else
  206. {
  207. respData = [[NSMutableData alloc] init];
  208. respFile = NO;
  209. }
  210. NSURLSessionDataTask * task = [session dataTaskWithRequest:req];
  211. @synchronized ([RNFetchBlobNetwork class]){
  212. [taskTable setObject:task forKey:taskId];
  213. }
  214. [task resume];
  215. // network status indicator
  216. if([[options objectForKey:CONFIG_INDICATOR] boolValue] == YES)
  217. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  218. }
  219. // #115 Invoke fetch.expire event on those expired requests so that the expired event can be handled
  220. + (void) emitExpiredTasks
  221. {
  222. @synchronized ([RNFetchBlobNetwork class]){
  223. NSEnumerator * emu = [expirationTable keyEnumerator];
  224. NSString * key;
  225. while((key = [emu nextObject]))
  226. {
  227. RCTBridge * bridge = [RNFetchBlob getRCTBridge];
  228. id args = @{ @"taskId": key };
  229. [bridge.eventDispatcher sendDeviceEventWithName:EVENT_EXPIRE body:args];
  230. }
  231. // clear expired task entries
  232. [expirationTable removeAllObjects];
  233. expirationTable = [[NSMapTable alloc] init];
  234. }
  235. }
  236. ////////////////////////////////////////
  237. //
  238. // NSURLSession delegates
  239. //
  240. ////////////////////////////////////////
  241. #pragma mark NSURLSession delegate methods
  242. #pragma mark - Received Response
  243. // set expected content length on response received
  244. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
  245. {
  246. expectedBytes = [response expectedContentLength];
  247. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  248. NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
  249. NSString * respType = @"";
  250. respStatus = statusCode;
  251. if ([response respondsToSelector:@selector(allHeaderFields)])
  252. {
  253. NSDictionary *headers = [httpResponse allHeaderFields];
  254. NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type" fromHeaders:headers] lowercaseString];
  255. if(self.isServerPush == NO)
  256. {
  257. self.isServerPush = [[respCType lowercaseString] RNFBContainsString:@"multipart/x-mixed-replace;"];
  258. }
  259. if(self.isServerPush)
  260. {
  261. if(partBuffer != nil)
  262. {
  263. [self.bridge.eventDispatcher
  264. sendDeviceEventWithName:EVENT_SERVER_PUSH
  265. body:@{
  266. @"taskId": taskId,
  267. @"chunk": [partBuffer base64EncodedStringWithOptions:0],
  268. }
  269. ];
  270. }
  271. partBuffer = [[NSMutableData alloc] init];
  272. completionHandler(NSURLSessionResponseAllow);
  273. return;
  274. }
  275. if(respCType != nil)
  276. {
  277. NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
  278. if([respCType RNFBContainsString:@"text/"])
  279. {
  280. respType = @"text";
  281. }
  282. else if([respCType RNFBContainsString:@"application/json"])
  283. {
  284. respType = @"json";
  285. }
  286. // If extra blob content type is not empty, check if response type matches
  287. else if( extraBlobCTypes != nil) {
  288. for(NSString * substr in extraBlobCTypes)
  289. {
  290. if([respCType RNFBContainsString:[substr lowercaseString]])
  291. {
  292. respType = @"blob";
  293. respFile = YES;
  294. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:nil];
  295. break;
  296. }
  297. }
  298. }
  299. else
  300. {
  301. respType = @"blob";
  302. // for XMLHttpRequest, switch response data handling strategy automatically
  303. if([options valueForKey:@"auto"]) {
  304. respFile = YES;
  305. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:@""];
  306. }
  307. }
  308. } else {
  309. respType = @"text";
  310. }
  311. #pragma mark - handling cookies
  312. // # 153 get cookies
  313. if(response.URL != nil)
  314. {
  315. NSHTTPCookieStorage * cookieStore = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  316. NSArray<NSHTTPCookie *> * cookies = [NSHTTPCookie cookiesWithResponseHeaderFields: headers forURL:response.URL];
  317. if(cookies != nil && [cookies count] > 0) {
  318. [cookieStore setCookies:cookies forURL:response.URL mainDocumentURL:nil];
  319. }
  320. }
  321. [self.bridge.eventDispatcher
  322. sendDeviceEventWithName: EVENT_STATE_CHANGE
  323. body:@{
  324. @"taskId": taskId,
  325. @"state": @"2",
  326. @"headers": headers,
  327. @"redirects": redirects,
  328. @"respType" : respType,
  329. @"timeout" : @NO,
  330. @"status": [NSNumber numberWithInteger:statusCode]
  331. }
  332. ];
  333. }
  334. else
  335. NSLog(@"oops");
  336. if(respFile == YES)
  337. {
  338. @try{
  339. NSFileManager * fm = [NSFileManager defaultManager];
  340. NSString * folder = [destPath stringByDeletingLastPathComponent];
  341. if(![fm fileExistsAtPath:folder])
  342. {
  343. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:nil];
  344. }
  345. BOOL overwrite = [options valueForKey:@"overwrite"] == nil ? YES : [[options valueForKey:@"overwrite"] boolValue];
  346. BOOL appendToExistingFile = [destPath RNFBContainsString:@"?append=true"];
  347. appendToExistingFile = !overwrite;
  348. // For solving #141 append response data if the file already exists
  349. // base on PR#139 @kejinliang
  350. if(appendToExistingFile)
  351. {
  352. destPath = [destPath stringByReplacingOccurrencesOfString:@"?append=true" withString:@""];
  353. }
  354. if (![fm fileExistsAtPath:destPath])
  355. {
  356. [fm createFileAtPath:destPath contents:[[NSData alloc] init] attributes:nil];
  357. }
  358. writeStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:appendToExistingFile];
  359. [writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  360. [writeStream open];
  361. }
  362. @catch(NSException * ex)
  363. {
  364. NSLog(@"write file error");
  365. }
  366. }
  367. completionHandler(NSURLSessionResponseAllow);
  368. }
  369. // download progress handler
  370. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  371. {
  372. // For #143 handling multipart/x-mixed-replace response
  373. if(self.isServerPush)
  374. {
  375. [partBuffer appendData:data];
  376. return ;
  377. }
  378. NSNumber * received = [NSNumber numberWithLong:[data length]];
  379. receivedBytes += [received longValue];
  380. NSString * chunkString = @"";
  381. if(isIncrement == YES)
  382. {
  383. chunkString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  384. }
  385. if(respFile == NO)
  386. {
  387. [respData appendData:data];
  388. }
  389. else
  390. {
  391. [writeStream write:[data bytes] maxLength:[data length]];
  392. }
  393. if(expectedBytes == 0)
  394. return;
  395. RNFetchBlobProgress * pconfig;
  396. @synchronized ([RNFetchBlobNetwork class]){
  397. pconfig = [progressTable valueForKey:taskId];
  398. }
  399. NSNumber * now =[NSNumber numberWithFloat:((float)receivedBytes/(float)expectedBytes)];
  400. if(pconfig != nil && [pconfig shouldReport:now])
  401. {
  402. [self.bridge.eventDispatcher
  403. sendDeviceEventWithName:EVENT_PROGRESS
  404. body:@{
  405. @"taskId": taskId,
  406. @"written": [NSString stringWithFormat:@"%ld", (long) receivedBytes],
  407. @"total": [NSString stringWithFormat:@"%ld", (long) expectedBytes],
  408. @"chunk": chunkString
  409. }
  410. ];
  411. }
  412. }
  413. - (void) URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
  414. {
  415. if([session isEqual:session])
  416. session = nil;
  417. }
  418. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  419. {
  420. self.error = error;
  421. NSString * errMsg;
  422. NSString * respStr;
  423. NSString * rnfbRespType;
  424. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  425. if(error != nil)
  426. {
  427. errMsg = [error localizedDescription];
  428. }
  429. if(respFile == YES)
  430. {
  431. [writeStream close];
  432. rnfbRespType = RESP_TYPE_PATH;
  433. respStr = destPath;
  434. }
  435. // base64 response
  436. else {
  437. // #73 fix unicode data encoding issue :
  438. // when response type is BASE64, we should first try to encode the response data to UTF8 format
  439. // if it turns out not to be `nil` that means the response data contains valid UTF8 string,
  440. // in order to properly encode the UTF8 string, use URL encoding before BASE64 encoding.
  441. NSString * utf8 = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
  442. if(responseFormat == BASE64)
  443. {
  444. rnfbRespType = RESP_TYPE_BASE64;
  445. respStr = [respData base64EncodedStringWithOptions:0];
  446. }
  447. else if (responseFormat == UTF8)
  448. {
  449. rnfbRespType = RESP_TYPE_UTF8;
  450. respStr = utf8;
  451. }
  452. else
  453. {
  454. if(utf8 != nil)
  455. {
  456. rnfbRespType = RESP_TYPE_UTF8;
  457. respStr = utf8;
  458. }
  459. else
  460. {
  461. rnfbRespType = RESP_TYPE_BASE64;
  462. respStr = [respData base64EncodedStringWithOptions:0];
  463. }
  464. }
  465. }
  466. callback(@[
  467. errMsg ?: [NSNull null],
  468. rnfbRespType ?: @"",
  469. respStr ?: [NSNull null]
  470. ]);
  471. @synchronized ([RNFetchBlobNetwork class])
  472. {
  473. if([taskTable objectForKey:taskId] == nil)
  474. NSLog(@"object released by ARC.");
  475. else
  476. [taskTable removeObjectForKey:taskId];
  477. [uploadProgressTable removeObjectForKey:taskId];
  478. [progressTable removeObjectForKey:taskId];
  479. }
  480. respData = nil;
  481. receivedBytes = 0;
  482. [session finishTasksAndInvalidate];
  483. }
  484. // upload progress handler
  485. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesWritten totalBytesExpectedToSend:(int64_t)totalBytesExpectedToWrite
  486. {
  487. if(totalBytesExpectedToWrite == 0)
  488. return;
  489. RNFetchBlobProgress * pconfig;
  490. @synchronized ([RNFetchBlobNetwork class]) {
  491. pconfig = [uploadProgressTable valueForKey:taskId];
  492. }
  493. NSNumber * now = [NSNumber numberWithFloat:((float)totalBytesWritten/(float)totalBytesExpectedToWrite)];
  494. if(pconfig != nil && [pconfig shouldReport:now]) {
  495. [self.bridge.eventDispatcher
  496. sendDeviceEventWithName:EVENT_PROGRESS_UPLOAD
  497. body:@{
  498. @"taskId": taskId,
  499. @"written": [NSString stringWithFormat:@"%ld", (long) totalBytesWritten],
  500. @"total": [NSString stringWithFormat:@"%ld", (long) totalBytesExpectedToWrite]
  501. }
  502. ];
  503. }
  504. }
  505. + (void) cancelRequest:(NSString *)taskId
  506. {
  507. NSURLSessionDataTask * task;
  508. @synchronized ([RNFetchBlobNetwork class]) {
  509. task = [taskTable objectForKey:taskId];
  510. }
  511. if(task != nil && task.state == NSURLSessionTaskStateRunning)
  512. [task cancel];
  513. }
  514. - (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable credantial))completionHandler
  515. {
  516. BOOL trusty = [[options valueForKey:CONFIG_TRUSTY] boolValue];
  517. if(!trusty)
  518. {
  519. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  520. }
  521. else
  522. {
  523. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  524. }
  525. }
  526. - (void) URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
  527. {
  528. NSLog(@"sess done in background");
  529. }
  530. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler
  531. {
  532. if(followRedirect)
  533. {
  534. if(request.URL != nil)
  535. [redirects addObject:[request.URL absoluteString]];
  536. completionHandler(request);
  537. }
  538. else
  539. {
  540. completionHandler(nil);
  541. }
  542. }
  543. @end