Geen omschrijving

RNFetchBlobNetwork.m 19KB

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