Sin descripción

RNFetchBlobRequest.m 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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"] boolValue];
  71. // when followRedirect not set in options, defaults to TRUE
  72. followRedirect = [options valueForKey:@"followRedirect"] == nil ? YES : [[options valueForKey:@"followRedirect"] boolValue];
  73. isIncrement = [[options valueForKey:@"increment"] boolValue];
  74. redirects = [[NSMutableArray alloc] init];
  75. if (req.URL) {
  76. [redirects addObject:req.URL.absoluteString];
  77. }
  78. // set response format
  79. NSString * rnfbResp = [req.allHTTPHeaderFields valueForKey:@"RNFB-Response"];
  80. if ([[rnfbResp lowercaseString] isEqualToString:@"base64"]) {
  81. responseFormat = BASE64;
  82. } else if ([[rnfbResp lowercaseString] isEqualToString:@"utf8"]) {
  83. responseFormat = UTF8;
  84. } else {
  85. responseFormat = AUTO;
  86. }
  87. NSString * path = [self.options valueForKey:CONFIG_FILE_PATH];
  88. NSString * key = [self.options valueForKey:CONFIG_KEY];
  89. NSURLSession * session;
  90. bodyLength = contentLength;
  91. // the session trust any SSL certification
  92. NSURLSessionConfiguration *defaultConfigObject;
  93. defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
  94. if (backgroundTask) {
  95. defaultConfigObject = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:taskId];
  96. }
  97. // request timeout, -1 if not set in options
  98. float timeout = [options valueForKey:@"timeout"] == nil ? -1 : [[options valueForKey:@"timeout"] floatValue];
  99. if (timeout > 0) {
  100. defaultConfigObject.timeoutIntervalForRequest = timeout/1000;
  101. }
  102. defaultConfigObject.HTTPMaximumConnectionsPerHost = 10;
  103. session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:operationQueue];
  104. if (path || [self.options valueForKey:CONFIG_USE_TEMP]) {
  105. respFile = YES;
  106. NSString* cacheKey = taskId;
  107. if (key) {
  108. cacheKey = [self md5:key];
  109. if (!cacheKey) {
  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) {
  119. destPath = path;
  120. } else {
  121. destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
  122. }
  123. } else {
  124. respData = [[NSMutableData alloc] init];
  125. respFile = NO;
  126. }
  127. self.task = [session dataTaskWithRequest:req];
  128. [self.task resume];
  129. // network status indicator
  130. if ([[options objectForKey:CONFIG_INDICATOR] boolValue]) {
  131. dispatch_async(dispatch_get_main_queue(), ^{
  132. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  133. });
  134. }
  135. }
  136. ////////////////////////////////////////
  137. //
  138. // NSURLSession delegates
  139. //
  140. ////////////////////////////////////////
  141. #pragma mark NSURLSession delegate methods
  142. #pragma mark - Received Response
  143. // set expected content length on response received
  144. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
  145. {
  146. expectedBytes = [response expectedContentLength];
  147. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  148. NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
  149. NSString * respType = @"";
  150. respStatus = statusCode;
  151. if ([response respondsToSelector:@selector(allHeaderFields)])
  152. {
  153. NSDictionary *headers = [httpResponse allHeaderFields];
  154. NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type" fromHeaders:headers] lowercaseString];
  155. if (self.isServerPush) {
  156. if (partBuffer) {
  157. [self.bridge.eventDispatcher
  158. sendDeviceEventWithName:EVENT_SERVER_PUSH
  159. body:@{
  160. @"taskId": taskId,
  161. @"chunk": [partBuffer base64EncodedStringWithOptions:0],
  162. }
  163. ];
  164. }
  165. partBuffer = [[NSMutableData alloc] init];
  166. completionHandler(NSURLSessionResponseAllow);
  167. return;
  168. } else {
  169. self.isServerPush = [[respCType lowercaseString] RNFBContainsString:@"multipart/x-mixed-replace;"];
  170. }
  171. if(respCType)
  172. {
  173. NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
  174. if ([respCType RNFBContainsString:@"text/"]) {
  175. respType = @"text";
  176. } else if ([respCType RNFBContainsString:@"application/json"]) {
  177. respType = @"json";
  178. } else if(extraBlobCTypes) { // If extra blob content type is not empty, check if response type matches
  179. for (NSString * substr in extraBlobCTypes) {
  180. if ([respCType RNFBContainsString:[substr lowercaseString]]) {
  181. respType = @"blob";
  182. respFile = YES;
  183. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:nil];
  184. break;
  185. }
  186. }
  187. } else {
  188. respType = @"blob";
  189. // for XMLHttpRequest, switch response data handling strategy automatically
  190. if ([options valueForKey:@"auto"]) {
  191. respFile = YES;
  192. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:@""];
  193. }
  194. }
  195. } else {
  196. respType = @"text";
  197. }
  198. #pragma mark - handling cookies
  199. // # 153 get cookies
  200. if (response.URL) {
  201. NSHTTPCookieStorage * cookieStore = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  202. NSArray<NSHTTPCookie *> * cookies = [NSHTTPCookie cookiesWithResponseHeaderFields: headers forURL:response.URL];
  203. if (cookies.count) {
  204. [cookieStore setCookies:cookies forURL:response.URL mainDocumentURL:nil];
  205. }
  206. }
  207. [self.bridge.eventDispatcher
  208. sendDeviceEventWithName: EVENT_STATE_CHANGE
  209. body:@{
  210. @"taskId": taskId,
  211. @"state": @"2",
  212. @"headers": headers,
  213. @"redirects": redirects,
  214. @"respType" : respType,
  215. @"timeout" : @NO,
  216. @"status": [NSNumber numberWithInteger:statusCode]
  217. }
  218. ];
  219. } else {
  220. NSLog(@"oops");
  221. }
  222. if (respFile)
  223. {
  224. @try{
  225. NSFileManager * fm = [NSFileManager defaultManager];
  226. NSString * folder = [destPath stringByDeletingLastPathComponent];
  227. if (![fm fileExistsAtPath:folder]) {
  228. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:nil];
  229. }
  230. // if not set overwrite in options, defaults to TRUE
  231. BOOL overwrite = [options valueForKey:@"overwrite"] == nil ? YES : [[options valueForKey:@"overwrite"] boolValue];
  232. BOOL appendToExistingFile = [destPath RNFBContainsString:@"?append=true"];
  233. appendToExistingFile = !overwrite;
  234. // For solving #141 append response data if the file already exists
  235. // base on PR#139 @kejinliang
  236. if (appendToExistingFile) {
  237. destPath = [destPath stringByReplacingOccurrencesOfString:@"?append=true" withString:@""];
  238. }
  239. if (![fm fileExistsAtPath:destPath]) {
  240. [fm createFileAtPath:destPath contents:[[NSData alloc] init] attributes:nil];
  241. }
  242. writeStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:appendToExistingFile];
  243. [writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  244. [writeStream open];
  245. }
  246. @catch(NSException * ex)
  247. {
  248. NSLog(@"write file error");
  249. }
  250. }
  251. completionHandler(NSURLSessionResponseAllow);
  252. }
  253. // download progress handler
  254. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  255. {
  256. // For #143 handling multipart/x-mixed-replace response
  257. if (self.isServerPush)
  258. {
  259. [partBuffer appendData:data];
  260. return ;
  261. }
  262. NSNumber * received = [NSNumber numberWithLong:[data length]];
  263. receivedBytes += [received longValue];
  264. NSString * chunkString = @"";
  265. if (isIncrement) {
  266. chunkString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  267. }
  268. if (respFile) {
  269. [writeStream write:[data bytes] maxLength:[data length]];
  270. } else {
  271. [respData appendData:data];
  272. }
  273. if (expectedBytes == 0) {
  274. return;
  275. }
  276. NSNumber * now =[NSNumber numberWithFloat:((float)receivedBytes/(float)expectedBytes)];
  277. if ([self.progressConfig shouldReport:now]) {
  278. [self.bridge.eventDispatcher
  279. sendDeviceEventWithName:EVENT_PROGRESS
  280. body:@{
  281. @"taskId": taskId,
  282. @"written": [NSString stringWithFormat:@"%ld", (long) receivedBytes],
  283. @"total": [NSString stringWithFormat:@"%ld", (long) expectedBytes],
  284. @"chunk": chunkString
  285. }
  286. ];
  287. }
  288. }
  289. - (void) URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
  290. {
  291. if ([session isEqual:session]) {
  292. session = nil;
  293. }
  294. }
  295. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  296. {
  297. self.error = error;
  298. NSString * errMsg;
  299. NSString * respStr;
  300. NSString * rnfbRespType;
  301. dispatch_async(dispatch_get_main_queue(), ^{
  302. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  303. });
  304. if (error) {
  305. if (error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled) {
  306. errMsg = @"task cancelled";
  307. } else {
  308. errMsg = [error localizedDescription];
  309. }
  310. }
  311. if (respFile) {
  312. [writeStream close];
  313. rnfbRespType = RESP_TYPE_PATH;
  314. respStr = destPath;
  315. } else { // base64 response
  316. // #73 fix unicode data encoding issue :
  317. // when response type is BASE64, we should first try to encode the response data to UTF8 format
  318. // if it turns out not to be `nil` that means the response data contains valid UTF8 string,
  319. // in order to properly encode the UTF8 string, use URL encoding before BASE64 encoding.
  320. NSString * utf8 = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
  321. if (responseFormat == BASE64) {
  322. rnfbRespType = RESP_TYPE_BASE64;
  323. respStr = [respData base64EncodedStringWithOptions:0];
  324. } else if (responseFormat == UTF8) {
  325. rnfbRespType = RESP_TYPE_UTF8;
  326. respStr = utf8;
  327. } else {
  328. if (utf8) {
  329. rnfbRespType = RESP_TYPE_UTF8;
  330. respStr = utf8;
  331. } else {
  332. rnfbRespType = RESP_TYPE_BASE64;
  333. respStr = [respData base64EncodedStringWithOptions:0];
  334. }
  335. }
  336. }
  337. callback(@[
  338. errMsg ?: [NSNull null],
  339. rnfbRespType ?: @"",
  340. respStr ?: [NSNull null]
  341. ]);
  342. respData = nil;
  343. receivedBytes = 0;
  344. [session finishTasksAndInvalidate];
  345. }
  346. // upload progress handler
  347. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesWritten totalBytesExpectedToSend:(int64_t)totalBytesExpectedToWrite
  348. {
  349. if (totalBytesExpectedToWrite == 0) {
  350. return;
  351. }
  352. NSNumber * now = [NSNumber numberWithFloat:((float)totalBytesWritten/(float)totalBytesExpectedToWrite)];
  353. if ([self.uploadProgressConfig shouldReport:now]) {
  354. [self.bridge.eventDispatcher
  355. sendDeviceEventWithName:EVENT_PROGRESS_UPLOAD
  356. body:@{
  357. @"taskId": taskId,
  358. @"written": [NSString stringWithFormat:@"%ld", (long) totalBytesWritten],
  359. @"total": [NSString stringWithFormat:@"%ld", (long) totalBytesExpectedToWrite]
  360. }
  361. ];
  362. }
  363. }
  364. - (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable credantial))completionHandler
  365. {
  366. if ([[options valueForKey:CONFIG_TRUSTY] boolValue]) {
  367. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  368. } else {
  369. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  370. }
  371. }
  372. - (void) URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
  373. {
  374. NSLog(@"sess done in background");
  375. }
  376. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler
  377. {
  378. if (followRedirect) {
  379. if (request.URL) {
  380. [redirects addObject:[request.URL absoluteString]];
  381. }
  382. completionHandler(request);
  383. } else {
  384. completionHandler(nil);
  385. }
  386. }
  387. @end