Нет описания

RNFetchBlobNetwork.m 14KB

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