暂无描述

RNFetchBlobNetwork.m 13KB

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