Bez popisu

RNFetchBlobNetwork.m 15KB

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