Nav apraksta

RNFetchBlobRequest.m 16KB

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