Brak opisu

RNFetchBlobRequest.m 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  132. }
  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) {
  154. if (partBuffer) {
  155. [self.bridge.eventDispatcher
  156. sendDeviceEventWithName:EVENT_SERVER_PUSH
  157. body:@{
  158. @"taskId": taskId,
  159. @"chunk": [partBuffer base64EncodedStringWithOptions:0],
  160. }
  161. ];
  162. }
  163. partBuffer = [[NSMutableData alloc] init];
  164. completionHandler(NSURLSessionResponseAllow);
  165. return;
  166. } else {
  167. self.isServerPush = [[respCType lowercaseString] RNFBContainsString:@"multipart/x-mixed-replace;"];
  168. }
  169. if(respCType)
  170. {
  171. NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
  172. if ([respCType RNFBContainsString:@"text/"]) {
  173. respType = @"text";
  174. } else if ([respCType RNFBContainsString:@"application/json"]) {
  175. respType = @"json";
  176. } else if(extraBlobCTypes) { // If extra blob content type is not empty, check if response type matches
  177. for (NSString * substr in extraBlobCTypes) {
  178. if ([respCType RNFBContainsString:[substr lowercaseString]]) {
  179. respType = @"blob";
  180. respFile = YES;
  181. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:nil];
  182. break;
  183. }
  184. }
  185. } else {
  186. respType = @"blob";
  187. // for XMLHttpRequest, switch response data handling strategy automatically
  188. if ([options valueForKey:@"auto"]) {
  189. respFile = YES;
  190. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:@""];
  191. }
  192. }
  193. } else {
  194. respType = @"text";
  195. }
  196. #pragma mark - handling cookies
  197. // # 153 get cookies
  198. if (response.URL) {
  199. NSHTTPCookieStorage * cookieStore = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  200. NSArray<NSHTTPCookie *> * cookies = [NSHTTPCookie cookiesWithResponseHeaderFields: headers forURL:response.URL];
  201. if (cookies.count) {
  202. [cookieStore setCookies:cookies forURL:response.URL mainDocumentURL:nil];
  203. }
  204. }
  205. [self.bridge.eventDispatcher
  206. sendDeviceEventWithName: EVENT_STATE_CHANGE
  207. body:@{
  208. @"taskId": taskId,
  209. @"state": @"2",
  210. @"headers": headers,
  211. @"redirects": redirects,
  212. @"respType" : respType,
  213. @"timeout" : @NO,
  214. @"status": [NSNumber numberWithInteger:statusCode]
  215. }
  216. ];
  217. } else {
  218. NSLog(@"oops");
  219. }
  220. if (respFile)
  221. {
  222. @try{
  223. NSFileManager * fm = [NSFileManager defaultManager];
  224. NSString * folder = [destPath stringByDeletingLastPathComponent];
  225. if (![fm fileExistsAtPath:folder]) {
  226. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:nil];
  227. }
  228. // if not set overwrite in options, defaults to TRUE
  229. BOOL overwrite = [options valueForKey:@"overwrite"] == nil ? YES : [[options valueForKey:@"overwrite"] boolValue];
  230. BOOL appendToExistingFile = [destPath RNFBContainsString:@"?append=true"];
  231. appendToExistingFile = !overwrite;
  232. // For solving #141 append response data if the file already exists
  233. // base on PR#139 @kejinliang
  234. if (appendToExistingFile) {
  235. destPath = [destPath stringByReplacingOccurrencesOfString:@"?append=true" withString:@""];
  236. }
  237. if (![fm fileExistsAtPath:destPath]) {
  238. [fm createFileAtPath:destPath contents:[[NSData alloc] init] attributes:nil];
  239. }
  240. writeStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:appendToExistingFile];
  241. [writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  242. [writeStream open];
  243. }
  244. @catch(NSException * ex)
  245. {
  246. NSLog(@"write file error");
  247. }
  248. }
  249. completionHandler(NSURLSessionResponseAllow);
  250. }
  251. // download progress handler
  252. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  253. {
  254. // For #143 handling multipart/x-mixed-replace response
  255. if (self.isServerPush)
  256. {
  257. [partBuffer appendData:data];
  258. return ;
  259. }
  260. NSNumber * received = [NSNumber numberWithLong:[data length]];
  261. receivedBytes += [received longValue];
  262. NSString * chunkString = @"";
  263. if (isIncrement) {
  264. chunkString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  265. }
  266. if (respFile) {
  267. [writeStream write:[data bytes] maxLength:[data length]];
  268. } else {
  269. [respData appendData:data];
  270. }
  271. if (expectedBytes == 0) {
  272. return;
  273. }
  274. NSNumber * now =[NSNumber numberWithFloat:((float)receivedBytes/(float)expectedBytes)];
  275. if ([self.progressConfig shouldReport:now]) {
  276. [self.bridge.eventDispatcher
  277. sendDeviceEventWithName:EVENT_PROGRESS
  278. body:@{
  279. @"taskId": taskId,
  280. @"written": [NSString stringWithFormat:@"%ld", (long) receivedBytes],
  281. @"total": [NSString stringWithFormat:@"%ld", (long) expectedBytes],
  282. @"chunk": chunkString
  283. }
  284. ];
  285. }
  286. }
  287. - (void) URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
  288. {
  289. if ([session isEqual:session]) {
  290. session = nil;
  291. }
  292. }
  293. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  294. {
  295. self.error = error;
  296. NSString * errMsg;
  297. NSString * respStr;
  298. NSString * rnfbRespType;
  299. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  300. if (error) {
  301. errMsg = [error localizedDescription];
  302. }
  303. if (respFile) {
  304. [writeStream close];
  305. rnfbRespType = RESP_TYPE_PATH;
  306. respStr = destPath;
  307. } else { // base64 response
  308. // #73 fix unicode data encoding issue :
  309. // when response type is BASE64, we should first try to encode the response data to UTF8 format
  310. // if it turns out not to be `nil` that means the response data contains valid UTF8 string,
  311. // in order to properly encode the UTF8 string, use URL encoding before BASE64 encoding.
  312. NSString * utf8 = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
  313. if (responseFormat == BASE64) {
  314. rnfbRespType = RESP_TYPE_BASE64;
  315. respStr = [respData base64EncodedStringWithOptions:0];
  316. } else if (responseFormat == UTF8) {
  317. rnfbRespType = RESP_TYPE_UTF8;
  318. respStr = utf8;
  319. } else {
  320. if (utf8) {
  321. rnfbRespType = RESP_TYPE_UTF8;
  322. respStr = utf8;
  323. } else {
  324. rnfbRespType = RESP_TYPE_BASE64;
  325. respStr = [respData base64EncodedStringWithOptions:0];
  326. }
  327. }
  328. }
  329. callback(@[
  330. errMsg ?: [NSNull null],
  331. rnfbRespType ?: @"",
  332. respStr ?: [NSNull null]
  333. ]);
  334. respData = nil;
  335. receivedBytes = 0;
  336. [session finishTasksAndInvalidate];
  337. }
  338. // upload progress handler
  339. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesWritten totalBytesExpectedToSend:(int64_t)totalBytesExpectedToWrite
  340. {
  341. if (totalBytesExpectedToWrite == 0) {
  342. return;
  343. }
  344. NSNumber * now = [NSNumber numberWithFloat:((float)totalBytesWritten/(float)totalBytesExpectedToWrite)];
  345. if ([self.uploadProgressConfig shouldReport:now]) {
  346. [self.bridge.eventDispatcher
  347. sendDeviceEventWithName:EVENT_PROGRESS_UPLOAD
  348. body:@{
  349. @"taskId": taskId,
  350. @"written": [NSString stringWithFormat:@"%ld", (long) totalBytesWritten],
  351. @"total": [NSString stringWithFormat:@"%ld", (long) totalBytesExpectedToWrite]
  352. }
  353. ];
  354. }
  355. }
  356. - (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable credantial))completionHandler
  357. {
  358. if ([[options valueForKey:CONFIG_TRUSTY] boolValue]) {
  359. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  360. } else {
  361. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  362. }
  363. }
  364. - (void) URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
  365. {
  366. NSLog(@"sess done in background");
  367. }
  368. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler
  369. {
  370. if (followRedirect) {
  371. if (request.URL) {
  372. [redirects addObject:[request.URL absoluteString]];
  373. }
  374. completionHandler(request);
  375. } else {
  376. completionHandler(nil);
  377. }
  378. }
  379. @end