Нема описа

RNFetchBlobNetwork.m 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. NSLog(@"timeout = %f",timeout);
  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"
  175. fromHeaders:headers]
  176. 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. if(respFile == NO)
  256. {
  257. [respData appendData:data];
  258. }
  259. else
  260. {
  261. [writeStream write:[data bytes] maxLength:[data length]];
  262. }
  263. if([progressTable valueForKey:taskId] == @YES)
  264. {
  265. [self.bridge.eventDispatcher
  266. sendDeviceEventWithName:@"RNFetchBlobProgress"
  267. body:@{
  268. @"taskId": taskId,
  269. @"written": [NSString stringWithFormat:@"%d", receivedBytes],
  270. @"total": [NSString stringWithFormat:@"%d", expectedBytes]
  271. }
  272. ];
  273. }
  274. received = nil;
  275. }
  276. - (void) URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
  277. {
  278. if([session isEqual:session])
  279. session = nil;
  280. }
  281. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  282. {
  283. self.error = error;
  284. NSString * errMsg = [NSNull null];
  285. NSString * respStr = [NSNull null];
  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. 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 * urlEncoded = [[[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding]
  314. stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  315. NSString * base64 = @"";
  316. if(urlEncoded != nil)
  317. base64 = [[urlEncoded dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
  318. else
  319. base64 = [respData base64EncodedStringWithOptions:0];
  320. respStr = base64;
  321. }
  322. }
  323. callback(@[ errMsg, respInfo, respStr ]);
  324. @synchronized(taskTable, uploadProgressTable, progressTable)
  325. {
  326. if([taskTable objectForKey:taskId] == nil)
  327. NSLog(@"object released.");
  328. else
  329. [taskTable removeObjectForKey:taskId];
  330. [uploadProgressTable removeObjectForKey:taskId];
  331. [progressTable removeObjectForKey:taskId];
  332. }
  333. respData = nil;
  334. receivedBytes = 0;
  335. [session finishTasksAndInvalidate];
  336. }
  337. // upload progress handler
  338. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesWritten totalBytesExpectedToSend:(int64_t)totalBytesExpectedToWrite
  339. {
  340. if([uploadProgressTable valueForKey:taskId] == @YES) {
  341. [self.bridge.eventDispatcher
  342. sendDeviceEventWithName:@"RNFetchBlobProgress-upload"
  343. body:@{
  344. @"taskId": taskId,
  345. @"written": [NSString stringWithFormat:@"%d", totalBytesWritten],
  346. @"total": [NSString stringWithFormat:@"%d", bodyLength]
  347. }
  348. ];
  349. }
  350. }
  351. + (void) cancelRequest:(NSString *)taskId
  352. {
  353. NSURLSessionDataTask * task = [taskTable objectForKey:taskId];
  354. if(task != nil && task.state == NSURLSessionTaskStateRunning)
  355. [task cancel];
  356. }
  357. //- (void) application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
  358. //
  359. //}
  360. //- (void) URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
  361. //{
  362. // if(self.dataTaskCompletionHandler != nil)
  363. // {
  364. // dataTaskCompletionHandler(self.respData, nil, error);
  365. // }
  366. // else if(self.fileTaskCompletionHandler != nil)
  367. // {
  368. // fileTaskCompletionHandler(nil, nil, self.error);
  369. // }
  370. //}
  371. - (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable credantial))completionHandler
  372. {
  373. if([options valueForKey:CONFIG_TRUSTY] != nil)
  374. {
  375. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  376. }
  377. else
  378. {
  379. NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
  380. __block NSURLCredential *credential = nil;
  381. if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
  382. {
  383. credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  384. if (credential) {
  385. disposition = NSURLSessionAuthChallengeUseCredential;
  386. } else {
  387. disposition = NSURLSessionAuthChallengePerformDefaultHandling;
  388. }
  389. }
  390. else
  391. {
  392. disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
  393. RCTLogWarn(@"counld not create connection with an unstrusted SSL certification, if you're going to create connection anyway, add `trusty:true` to RNFetchBlob.config");
  394. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  395. }
  396. if (completionHandler) {
  397. completionHandler(disposition, credential);
  398. }
  399. }
  400. }
  401. @end