Nessuna descrizione

RNFetchBlobNetwork.m 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. // set request timeout
  118. float timeout = [options valueForKey:@"timeout"] == nil ? -1 : [[options valueForKey:@"timeout"] floatValue];
  119. if(timeout > 0)
  120. {
  121. defaultConfigObject.timeoutIntervalForRequest = timeout/1000;
  122. }
  123. defaultConfigObject.HTTPMaximumConnectionsPerHost = 10;
  124. session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:taskQueue];
  125. if(path != nil || [self.options valueForKey:CONFIG_USE_TEMP]!= nil)
  126. {
  127. respFile = YES;
  128. NSString* cacheKey = taskId;
  129. if (key != nil) {
  130. cacheKey = [self md5:key];
  131. if (cacheKey == nil) {
  132. cacheKey = taskId;
  133. }
  134. destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
  135. if ([[NSFileManager defaultManager] fileExistsAtPath:destPath]) {
  136. callback(@[[NSNull null], destPath]);
  137. return;
  138. }
  139. }
  140. if(path != nil)
  141. destPath = path;
  142. else
  143. destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
  144. }
  145. else
  146. {
  147. respData = [[NSMutableData alloc] init];
  148. respFile = NO;
  149. }
  150. NSURLSessionDataTask * task = [session dataTaskWithRequest:req];
  151. [taskTable setObject:task forKey:taskId];
  152. [task resume];
  153. // network status indicator
  154. if([[options objectForKey:CONFIG_INDICATOR] boolValue] == YES)
  155. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  156. }
  157. ////////////////////////////////////////
  158. //
  159. // NSURLSession delegates
  160. //
  161. ////////////////////////////////////////
  162. #pragma mark NSURLSession delegate methods
  163. // set expected content length on response received
  164. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
  165. {
  166. expectedBytes = [response expectedContentLength];
  167. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  168. NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
  169. NSString * respType = @"";
  170. respStatus = statusCode;
  171. if ([response respondsToSelector:@selector(allHeaderFields)])
  172. {
  173. NSDictionary *headers = [httpResponse allHeaderFields];
  174. NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type" fromHeaders:headers] lowercaseString];
  175. if(respCType != nil)
  176. {
  177. NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
  178. if([respCType containsString:@"text/"])
  179. {
  180. respType = @"text";
  181. }
  182. else if([respCType containsString:@"application/json"])
  183. {
  184. respType = @"json";
  185. }
  186. // If extra blob content type is not empty, check if response type matches
  187. else if( extraBlobCTypes != nil) {
  188. for(NSString * substr in extraBlobCTypes)
  189. {
  190. if([respCType containsString:[substr lowercaseString]])
  191. {
  192. respType = @"blob";
  193. respFile = YES;
  194. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:nil];
  195. break;
  196. }
  197. }
  198. }
  199. else
  200. {
  201. respType = @"blob";
  202. // for XMLHttpRequest, switch response data handling strategy automatically
  203. if([options valueForKey:@"auto"] == YES) {
  204. respFile = YES;
  205. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:@""];
  206. }
  207. }
  208. }
  209. else
  210. respType = @"text";
  211. respInfo = @{
  212. @"taskId": taskId,
  213. @"state": @"2",
  214. @"headers": headers,
  215. @"respType" : respType,
  216. @"timeout" : @NO,
  217. @"status": [NSString stringWithFormat:@"%d", statusCode ]
  218. };
  219. [self.bridge.eventDispatcher
  220. sendDeviceEventWithName: EVENT_STATE_CHANGE
  221. body:respInfo
  222. ];
  223. headers = nil;
  224. respInfo = nil;
  225. }
  226. else
  227. NSLog(@"oops");
  228. if(respFile == YES)
  229. {
  230. @try{
  231. NSFileManager * fm = [NSFileManager defaultManager];
  232. NSString * folder = [destPath stringByDeletingLastPathComponent];
  233. if(![fm fileExistsAtPath:folder]) {
  234. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:nil];
  235. }
  236. [fm createFileAtPath:destPath contents:[[NSData alloc] init] attributes:nil];
  237. writeStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:YES];
  238. [writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  239. [writeStream open];
  240. }
  241. @catch(NSException * ex)
  242. {
  243. NSLog(@"write file error");
  244. }
  245. }
  246. completionHandler(NSURLSessionResponseAllow);
  247. }
  248. // download progress handler
  249. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  250. {
  251. NSNumber * received = [NSNumber numberWithLong:[data length]];
  252. receivedBytes += [received longValue];
  253. if(respFile == NO)
  254. {
  255. [respData appendData:data];
  256. }
  257. else
  258. {
  259. [writeStream write:[data bytes] maxLength:[data length]];
  260. }
  261. if([progressTable valueForKey:taskId] == @YES)
  262. {
  263. [self.bridge.eventDispatcher
  264. sendDeviceEventWithName:EVENT_PROGRESS
  265. body:@{
  266. @"taskId": taskId,
  267. @"written": [NSString stringWithFormat:@"%d", receivedBytes],
  268. @"total": [NSString stringWithFormat:@"%d", expectedBytes]
  269. }
  270. ];
  271. }
  272. received = nil;
  273. }
  274. - (void) URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
  275. {
  276. if([session isEqual:session])
  277. session = nil;
  278. }
  279. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  280. {
  281. self.error = error;
  282. NSString * errMsg = [NSNull null];
  283. NSString * respStr = [NSNull null];
  284. NSString * rnfbRespType = @"";
  285. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  286. if(respInfo == nil)
  287. {
  288. respInfo = [NSNull null];
  289. }
  290. if(error != nil)
  291. {
  292. errMsg = [error localizedDescription];
  293. }
  294. // Fix #72 response with status code 200 ~ 299 considered as success
  295. else if(respStatus> 299 || respStatus < 200)
  296. {
  297. errMsg = [NSString stringWithFormat:@"Request failed, status %d", respStatus];
  298. }
  299. else
  300. {
  301. if(respFile == YES)
  302. {
  303. [writeStream close];
  304. rnfbRespType = RESP_TYPE_PATH;
  305. respStr = destPath;
  306. }
  307. // base64 response
  308. else {
  309. // #73 fix unicode data encoding issue :
  310. // when response type is BASE64, we should first try to encode the response data to UTF8 format
  311. // if it turns out not to be `nil` that means the response data contains valid UTF8 string,
  312. // in order to properly encode the UTF8 string, use URL encoding before BASE64 encoding.
  313. NSString * utf8 = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
  314. if(utf8 != nil)
  315. {
  316. rnfbRespType = RESP_TYPE_UTF8;
  317. respStr = utf8;
  318. }
  319. else
  320. {
  321. rnfbRespType = RESP_TYPE_BASE64;
  322. respStr = [respData base64EncodedStringWithOptions:0];
  323. }
  324. }
  325. }
  326. callback(@[ errMsg, rnfbRespType, respStr]);
  327. @synchronized(taskTable, uploadProgressTable, progressTable)
  328. {
  329. if([taskTable objectForKey:taskId] == nil)
  330. NSLog(@"object released by ARC.");
  331. else
  332. [taskTable removeObjectForKey:taskId];
  333. [uploadProgressTable removeObjectForKey:taskId];
  334. [progressTable removeObjectForKey:taskId];
  335. }
  336. respData = nil;
  337. receivedBytes = 0;
  338. [session finishTasksAndInvalidate];
  339. }
  340. // upload progress handler
  341. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesWritten totalBytesExpectedToSend:(int64_t)totalBytesExpectedToWrite
  342. {
  343. if([uploadProgressTable valueForKey:taskId] == @YES) {
  344. [self.bridge.eventDispatcher
  345. sendDeviceEventWithName:EVENT_PROGRESS_UPLOAD
  346. body:@{
  347. @"taskId": taskId,
  348. @"written": [NSString stringWithFormat:@"%d", totalBytesWritten],
  349. @"total": [NSString stringWithFormat:@"%d", bodyLength]
  350. }
  351. ];
  352. }
  353. }
  354. + (void) cancelRequest:(NSString *)taskId
  355. {
  356. NSURLSessionDataTask * task = [taskTable objectForKey:taskId];
  357. if(task != nil && task.state == NSURLSessionTaskStateRunning)
  358. [task cancel];
  359. }
  360. //- (void) application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
  361. //
  362. //}
  363. //- (void) URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
  364. //{
  365. // if(self.dataTaskCompletionHandler != nil)
  366. // {
  367. // dataTaskCompletionHandler(self.respData, nil, error);
  368. // }
  369. // else if(self.fileTaskCompletionHandler != nil)
  370. // {
  371. // fileTaskCompletionHandler(nil, nil, self.error);
  372. // }
  373. //}
  374. - (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable credantial))completionHandler
  375. {
  376. if([options valueForKey:CONFIG_TRUSTY] != nil)
  377. {
  378. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  379. }
  380. else
  381. {
  382. NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
  383. __block NSURLCredential *credential = nil;
  384. if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
  385. {
  386. credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  387. if (credential) {
  388. disposition = NSURLSessionAuthChallengeUseCredential;
  389. } else {
  390. disposition = NSURLSessionAuthChallengePerformDefaultHandling;
  391. }
  392. }
  393. else
  394. {
  395. disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
  396. RCTLogWarn(@"counld not create connection with an unstrusted SSL certification, if you're going to create connection anyway, add `trusty:true` to RNFetchBlob.config");
  397. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  398. }
  399. if (completionHandler) {
  400. completionHandler(disposition, credential);
  401. }
  402. }
  403. }
  404. @end