Нема описа

RNFetchBlobRequest.m 16KB

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