説明なし

RNFetchBlobNetwork.m 17KB

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