Ei kuvausta

RNFetchBlobNetwork.m 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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. dispatch_async(dispatch_get_main_queue(), ^{
  214. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  215. });
  216. }
  217. __block UIApplication * app = [UIApplication sharedApplication];
  218. }
  219. // #115 Invoke fetch.expire event on those expired requests so that the expired event can be handled
  220. + (void) emitExpiredTasks
  221. {
  222. NSEnumerator * emu = [expirationTable keyEnumerator];
  223. NSString * key;
  224. while((key = [emu nextObject]))
  225. {
  226. RCTBridge * bridge = [RNFetchBlob getRCTBridge];
  227. NSData * args = @{ @"taskId": key };
  228. [bridge.eventDispatcher sendDeviceEventWithName:EVENT_EXPIRE body:args];
  229. }
  230. // clear expired task entries
  231. [expirationTable removeAllObjects];
  232. expirationTable = [[NSMapTable alloc] init];
  233. }
  234. ////////////////////////////////////////
  235. //
  236. // NSURLSession delegates
  237. //
  238. ////////////////////////////////////////
  239. #pragma mark NSURLSession delegate methods
  240. #pragma mark - Received Response
  241. // set expected content length on response received
  242. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
  243. {
  244. expectedBytes = [response expectedContentLength];
  245. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  246. NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
  247. NSString * respType = @"";
  248. respStatus = statusCode;
  249. if ([response respondsToSelector:@selector(allHeaderFields)])
  250. {
  251. NSDictionary *headers = [httpResponse allHeaderFields];
  252. NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type" fromHeaders:headers] lowercaseString];
  253. if(self.isServerPush == NO)
  254. {
  255. self.isServerPush = [[respCType lowercaseString] RNFBContainsString:@"multipart/x-mixed-replace;"];
  256. }
  257. if(self.isServerPush)
  258. {
  259. if(partBuffer != nil)
  260. {
  261. [self.bridge.eventDispatcher
  262. sendDeviceEventWithName:EVENT_SERVER_PUSH
  263. body:@{
  264. @"taskId": taskId,
  265. @"chunk": [partBuffer base64EncodedStringWithOptions:0],
  266. }
  267. ];
  268. }
  269. partBuffer = [[NSMutableData alloc] init];
  270. completionHandler(NSURLSessionResponseAllow);
  271. return;
  272. }
  273. if(respCType != nil)
  274. {
  275. NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
  276. if([respCType RNFBContainsString:@"text/"])
  277. {
  278. respType = @"text";
  279. }
  280. else if([respCType RNFBContainsString:@"application/json"])
  281. {
  282. respType = @"json";
  283. }
  284. // If extra blob content type is not empty, check if response type matches
  285. else if( extraBlobCTypes != nil) {
  286. for(NSString * substr in extraBlobCTypes)
  287. {
  288. if([respCType RNFBContainsString:[substr lowercaseString]])
  289. {
  290. respType = @"blob";
  291. respFile = YES;
  292. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:nil];
  293. break;
  294. }
  295. }
  296. }
  297. else
  298. {
  299. respType = @"blob";
  300. // for XMLHttpRequest, switch response data handling strategy automatically
  301. if([options valueForKey:@"auto"] == YES) {
  302. respFile = YES;
  303. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:@""];
  304. }
  305. }
  306. }
  307. else
  308. respType = @"text";
  309. respInfo = @{
  310. @"taskId": taskId,
  311. @"state": @"2",
  312. @"headers": headers,
  313. @"redirects": redirects,
  314. @"respType" : respType,
  315. @"timeout" : @NO,
  316. @"status": [NSNumber numberWithInteger:statusCode]
  317. };
  318. #pragma mark - handling cookies
  319. // # 153 get cookies
  320. if(response.URL != nil)
  321. {
  322. NSHTTPCookieStorage * cookieStore = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  323. NSArray<NSHTTPCookie *> * cookies = [NSHTTPCookie cookiesWithResponseHeaderFields: headers forURL:response.URL];
  324. if(cookies != nil && [cookies count] > 0) {
  325. [cookieStore setCookies:cookies forURL:response.URL mainDocumentURL:nil];
  326. }
  327. }
  328. [self.bridge.eventDispatcher
  329. sendDeviceEventWithName: EVENT_STATE_CHANGE
  330. body:respInfo
  331. ];
  332. headers = nil;
  333. respInfo = nil;
  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. RNFetchBlobProgress * pconfig = [progressTable valueForKey:taskId];
  395. if(expectedBytes == 0)
  396. return;
  397. NSNumber * now =[NSNumber numberWithFloat:((float)receivedBytes/(float)expectedBytes)];
  398. if(pconfig != nil && [pconfig shouldReport:now])
  399. {
  400. [self.bridge.eventDispatcher
  401. sendDeviceEventWithName:EVENT_PROGRESS
  402. body:@{
  403. @"taskId": taskId,
  404. @"written": [NSString stringWithFormat:@"%d", receivedBytes],
  405. @"total": [NSString stringWithFormat:@"%d", expectedBytes],
  406. @"chunk": chunkString
  407. }
  408. ];
  409. }
  410. received = nil;
  411. }
  412. - (void) URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
  413. {
  414. if([session isEqual:session])
  415. session = nil;
  416. }
  417. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  418. {
  419. self.error = error;
  420. NSString * errMsg = [NSNull null];
  421. NSString * respStr = [NSNull null];
  422. NSString * rnfbRespType = @"";
  423. dispatch_async(dispatch_get_main_queue(), ^{
  424. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  425. });
  426. if(respInfo == nil)
  427. {
  428. respInfo = [NSNull null];
  429. }
  430. if(error != nil)
  431. {
  432. errMsg = [error localizedDescription];
  433. }
  434. if(respFile == YES)
  435. {
  436. [writeStream close];
  437. rnfbRespType = RESP_TYPE_PATH;
  438. respStr = destPath;
  439. }
  440. // base64 response
  441. else {
  442. // #73 fix unicode data encoding issue :
  443. // when response type is BASE64, we should first try to encode the response data to UTF8 format
  444. // if it turns out not to be `nil` that means the response data contains valid UTF8 string,
  445. // in order to properly encode the UTF8 string, use URL encoding before BASE64 encoding.
  446. NSString * utf8 = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
  447. if(responseFormat == BASE64)
  448. {
  449. rnfbRespType = RESP_TYPE_BASE64;
  450. respStr = [respData base64EncodedStringWithOptions:0];
  451. }
  452. else if (responseFormat == UTF8)
  453. {
  454. rnfbRespType = RESP_TYPE_UTF8;
  455. respStr = utf8;
  456. }
  457. else
  458. {
  459. if(utf8 != nil)
  460. {
  461. rnfbRespType = RESP_TYPE_UTF8;
  462. respStr = utf8;
  463. }
  464. else
  465. {
  466. rnfbRespType = RESP_TYPE_BASE64;
  467. respStr = [respData base64EncodedStringWithOptions:0];
  468. }
  469. }
  470. }
  471. callback(@[ errMsg, rnfbRespType, respStr]);
  472. @synchronized(taskTable, uploadProgressTable, progressTable)
  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. RNFetchBlobProgress * pconfig = [uploadProgressTable valueForKey:taskId];
  489. if(totalBytesExpectedToWrite == 0)
  490. return;
  491. NSNumber * now = [NSNumber numberWithFloat:((float)totalBytesWritten/(float)totalBytesExpectedToWrite)];
  492. if(pconfig != nil && [pconfig shouldReport:now]) {
  493. [self.bridge.eventDispatcher
  494. sendDeviceEventWithName:EVENT_PROGRESS_UPLOAD
  495. body:@{
  496. @"taskId": taskId,
  497. @"written": [NSString stringWithFormat:@"%d", totalBytesWritten],
  498. @"total": [NSString stringWithFormat:@"%d", totalBytesExpectedToWrite]
  499. }
  500. ];
  501. }
  502. }
  503. + (void) cancelRequest:(NSString *)taskId
  504. {
  505. NSURLSessionDataTask * task = [taskTable objectForKey:taskId];
  506. if(task != nil && task.state == NSURLSessionTaskStateRunning)
  507. [task cancel];
  508. }
  509. - (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable credantial))completionHandler
  510. {
  511. BOOL trusty = [options valueForKey:CONFIG_TRUSTY];
  512. if(!trusty)
  513. {
  514. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  515. }
  516. else
  517. {
  518. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  519. }
  520. }
  521. - (void) URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
  522. {
  523. NSLog(@"sess done in background");
  524. }
  525. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler
  526. {
  527. if(followRedirect)
  528. {
  529. if(request.URL != nil)
  530. [redirects addObject:[request.URL absoluteString]];
  531. completionHandler(request);
  532. }
  533. else
  534. {
  535. completionHandler(nil);
  536. }
  537. }
  538. @end