Ingen beskrivning

RNFetchBlobNetwork.m 19KB

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