Geen omschrijving

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