暂无描述

RNFetchBlobNetwork.m 19KB

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