Brak opisu

RNFetchBlobNetwork.m 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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:(__weak NSDictionary * _Nullable )options
  96. contentLength:(long) contentLength
  97. bridge:(RCTBridge * _Nullable)bridgeRef
  98. taskId:(NSString * _Nullable)taskId
  99. withRequest:(__weak 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. __block 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]/1000;
  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 setObject:task 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. NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
  174. // If extra blob content type is not empty, check if response type matches
  175. if( extraBlobCTypes != nil) {
  176. for(NSString * substr in extraBlobCTypes)
  177. {
  178. if([[respType lowercaseString] containsString:[substr lowercaseString]])
  179. {
  180. respType = @"blob";
  181. respFile = YES;
  182. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:nil];
  183. break;
  184. }
  185. }
  186. }
  187. else if([respType containsString:@"text/"])
  188. {
  189. respType = @"text";
  190. }
  191. else if([respType containsString:@"application/json"])
  192. {
  193. respType = @"json";
  194. }
  195. else
  196. {
  197. respType = @"blob";
  198. // for XMLHttpRequest, switch response data handling strategy automatically
  199. if([options valueForKey:@"auto"] == YES) {
  200. respFile = YES;
  201. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:@""];
  202. }
  203. }
  204. }
  205. else
  206. respType = @"";
  207. respInfo = @{
  208. @"taskId": taskId,
  209. @"state": @"2",
  210. @"headers": headers,
  211. @"respType" : respType,
  212. @"timeout" : @NO,
  213. @"status": [NSString stringWithFormat:@"%d", statusCode ]
  214. };
  215. [self.bridge.eventDispatcher
  216. sendDeviceEventWithName: EVENT_STATE_CHANGE
  217. body:respInfo
  218. ];
  219. headers = nil;
  220. respInfo = nil;
  221. }
  222. if(respFile == YES)
  223. {
  224. @try{
  225. NSFileManager * fm = [NSFileManager defaultManager];
  226. NSString * folder = [destPath stringByDeletingLastPathComponent];
  227. if(![fm fileExistsAtPath:folder]) {
  228. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:nil];
  229. }
  230. [fm createFileAtPath:destPath contents:[[NSData alloc] init] attributes:nil];
  231. writeStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:YES];
  232. [writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  233. [writeStream open];
  234. }
  235. @catch(NSException * ex)
  236. {
  237. NSLog(@"write file error");
  238. }
  239. }
  240. completionHandler(NSURLSessionResponseAllow);
  241. }
  242. // download progress handler
  243. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  244. {
  245. NSNumber * received = [NSNumber numberWithLong:[data length]];
  246. receivedBytes += [received longValue];
  247. if(respFile == NO)
  248. {
  249. [respData appendData:data];
  250. }
  251. else
  252. {
  253. [writeStream write:[data bytes] maxLength:[data length]];
  254. }
  255. if([progressTable valueForKey:taskId] == @YES)
  256. {
  257. [self.bridge.eventDispatcher
  258. sendDeviceEventWithName:@"RNFetchBlobProgress"
  259. body:@{
  260. @"taskId": taskId,
  261. @"written": [NSString stringWithFormat:@"%d", receivedBytes],
  262. @"total": [NSString stringWithFormat:@"%d", expectedBytes]
  263. }
  264. ];
  265. }
  266. received = nil;
  267. }
  268. - (void) URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
  269. {
  270. if([session isEqual:session])
  271. session = nil;
  272. }
  273. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  274. {
  275. self.error = error;
  276. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  277. NSString * respType = [respInfo valueForKey:@"respType"];
  278. if(error != nil) {
  279. NSLog([error localizedDescription]);
  280. }
  281. if(respFile == YES)
  282. {
  283. [writeStream close];
  284. callback(@[error == nil ? [NSNull null] : [error localizedDescription],
  285. respInfo == nil ? [NSNull null] : respInfo,
  286. destPath
  287. ]);
  288. }
  289. // base64 response
  290. else {
  291. NSString * utf8 = [[[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  292. NSString * base64 = @"";
  293. if(utf8 != nil)
  294. base64 = [[utf8 dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
  295. else
  296. base64 = [respData base64EncodedStringWithOptions:0];
  297. callback(@[error == nil ? [NSNull null] : [error localizedDescription],
  298. respInfo == nil ? [NSNull null] : respInfo,
  299. base64
  300. ]);
  301. }
  302. [taskTable removeObjectForKey:taskId];
  303. [uploadProgressTable removeObjectForKey:taskId];
  304. [progressTable removeObjectForKey:taskId];
  305. respData = nil;
  306. receivedBytes = 0;
  307. [session finishTasksAndInvalidate];
  308. }
  309. // upload progress handler
  310. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesWritten totalBytesExpectedToSend:(int64_t)totalBytesExpectedToWrite
  311. {
  312. if([uploadProgressTable valueForKey:taskId] == @YES) {
  313. [self.bridge.eventDispatcher
  314. sendDeviceEventWithName:@"RNFetchBlobProgress-upload"
  315. body:@{
  316. @"taskId": taskId,
  317. @"written": [NSString stringWithFormat:@"%d", totalBytesWritten],
  318. @"total": [NSString stringWithFormat:@"%d", bodyLength]
  319. }
  320. ];
  321. }
  322. }
  323. + (void) cancelRequest:(NSString *)taskId
  324. {
  325. NSURLSessionDataTask * task = [taskTable objectForKey:taskId];
  326. if(task != nil && task.state == NSURLSessionTaskStateRunning)
  327. [task cancel];
  328. }
  329. //- (void) application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
  330. //
  331. //}
  332. //- (void) URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
  333. //{
  334. // if(self.dataTaskCompletionHandler != nil)
  335. // {
  336. // dataTaskCompletionHandler(self.respData, nil, error);
  337. // }
  338. // else if(self.fileTaskCompletionHandler != nil)
  339. // {
  340. // fileTaskCompletionHandler(nil, nil, self.error);
  341. // }
  342. //}
  343. - (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable credantial))completionHandler
  344. {
  345. if([options valueForKey:CONFIG_TRUSTY] != nil)
  346. {
  347. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  348. }
  349. else
  350. {
  351. NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
  352. __block NSURLCredential *credential = nil;
  353. if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
  354. {
  355. credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  356. if (credential) {
  357. disposition = NSURLSessionAuthChallengeUseCredential;
  358. } else {
  359. disposition = NSURLSessionAuthChallengePerformDefaultHandling;
  360. }
  361. }
  362. else
  363. {
  364. disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
  365. RCTLogWarn(@"counld not create connection with an unstrusted SSL certification, if you're going to create connection anyway, add `trusty:true` to RNFetchBlob.config");
  366. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  367. }
  368. if (completionHandler) {
  369. completionHandler(disposition, credential);
  370. }
  371. }
  372. }
  373. @end