Keine Beschreibung

RNFetchBlobNetwork.m 12KB

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