暂无描述

RNFetchBlobNetwork.m 17KB

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