暫無描述

RNFetchBlob.m 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. //
  2. // RNFetchBlob.m
  3. //
  4. // Created by wkh237 on 2016/4/28.
  5. //
  6. #import "RNFetchBlob.h"
  7. #import "RCTConvert.h"
  8. #import "RCTLog.h"
  9. #import "RCTBridge.h"
  10. #import "RCTEventDispatcher.h"
  11. #import "RNFetchBlobFS.h"
  12. #import "RNFetchBlobNetwork.h"
  13. #import "RNFetchBlobConst.h"
  14. #import "RNFetchBlobReqBuilder.h"
  15. ////////////////////////////////////////
  16. //
  17. // Exported native methods
  18. //
  19. ////////////////////////////////////////
  20. #pragma mark RNFetchBlob exported methods
  21. @implementation RNFetchBlob
  22. @synthesize filePathPrefix;
  23. @synthesize bridge = _bridge;
  24. - (dispatch_queue_t) methodQueue {
  25. return dispatch_queue_create("RNFetchBlob.queue", DISPATCH_QUEUE_SERIAL);
  26. }
  27. RCT_EXPORT_MODULE();
  28. - (id) init {
  29. self = [super init];
  30. self.filePathPrefix = FILE_PREFIX;
  31. BOOL isDir;
  32. // if temp folder not exists, create one
  33. if(![[NSFileManager defaultManager] fileExistsAtPath: [RNFetchBlobFS getTempPath] isDirectory:&isDir]) {
  34. [[NSFileManager defaultManager] createDirectoryAtPath:[RNFetchBlobFS getTempPath] withIntermediateDirectories:YES attributes:nil error:NULL];
  35. }
  36. return self;
  37. }
  38. - (NSDictionary *)constantsToExport
  39. {
  40. return @{
  41. @"DocumentDir": [RNFetchBlobFS getDocumentDir],
  42. @"CacheDir" : [RNFetchBlobFS getCacheDir]
  43. };
  44. }
  45. // Fetch blob data request
  46. RCT_EXPORT_METHOD(fetchBlobForm:(NSDictionary *)options
  47. taskId:(NSString *)taskId
  48. method:(NSString *)method
  49. url:(NSString *)url
  50. headers:(NSDictionary *)headers
  51. form:(NSArray *)form
  52. callback:(RCTResponseSenderBlock)callback)
  53. {
  54. [RNFetchBlobReqBuilder buildMultipartRequest:options taskId:taskId method:method url:url headers:headers form:form onComplete:^(__weak NSURLRequest *req, long bodyLength) {
  55. // send HTTP request
  56. RNFetchBlobNetwork * utils = [[RNFetchBlobNetwork alloc] init];
  57. [utils sendRequest:options contentLength:bodyLength bridge:self.bridge taskId:taskId withRequest:req callback:callback];
  58. }];
  59. }
  60. // Fetch blob data request
  61. RCT_EXPORT_METHOD(fetchBlob:(NSDictionary *)options
  62. taskId:(NSString *)taskId
  63. method:(NSString *)method
  64. url:(NSString *)url
  65. headers:(NSDictionary *)headers
  66. body:(NSString *)body callback:(RCTResponseSenderBlock)callback)
  67. {
  68. [RNFetchBlobReqBuilder buildOctetRequest:options taskId:taskId method:method url:url headers:headers body:body onComplete:^(NSURLRequest *req, long bodyLength) {
  69. // send HTTP request
  70. __block RNFetchBlobNetwork * utils = [[RNFetchBlobNetwork alloc] init];
  71. [utils sendRequest:options contentLength:bodyLength bridge:self.bridge taskId:taskId withRequest:req callback:callback];
  72. }];
  73. }
  74. #pragma mark - fs.createFile
  75. RCT_EXPORT_METHOD(createFile:(NSString *)path data:(NSString *)data encoding:(NSString *)encoding callback:(RCTResponseSenderBlock)callback) {
  76. NSFileManager * fm = [NSFileManager defaultManager];
  77. NSData * fileContent = nil;
  78. if([[encoding lowercaseString] isEqualToString:@"utf8"]) {
  79. fileContent = [[NSData alloc] initWithData:[data dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
  80. }
  81. else if([[encoding lowercaseString] isEqualToString:@"base64"]) {
  82. fileContent = [[NSData alloc] initWithBase64EncodedData:data options:0];
  83. }
  84. else if([[encoding lowercaseString] isEqualToString:@"uri"]) {
  85. NSString * orgPath = [data stringByReplacingOccurrencesOfString:FILE_PREFIX withString:@""];
  86. fileContent = [[NSData alloc] initWithContentsOfFile:orgPath];
  87. }
  88. else {
  89. fileContent = [[NSData alloc] initWithData:[data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
  90. }
  91. BOOL success = [fm createFileAtPath:path contents:fileContent attributes:NULL];
  92. if(success == YES)
  93. callback(@[[NSNull null]]);
  94. else
  95. callback(@[[NSString stringWithFormat:@"failed to create new file at path %@ please ensure the folder exists"]]);
  96. }
  97. #pragma mark - fs.createFileASCII
  98. // method for create file with ASCII content
  99. RCT_EXPORT_METHOD(createFileASCII:(NSString *)path data:(NSArray *)dataArray callback:(RCTResponseSenderBlock)callback) {
  100. NSFileManager * fm = [NSFileManager defaultManager];
  101. NSMutableData * fileContent = [NSMutableData alloc];
  102. // prevent stack overflow, alloc on heap
  103. char * bytes = (char*) malloc([dataArray count]);
  104. for(int i = 0; i < dataArray.count; i++) {
  105. bytes[i] = [[dataArray objectAtIndex:i] charValue];
  106. }
  107. [fileContent appendBytes:bytes length:dataArray.count];
  108. BOOL success = [fm createFileAtPath:path contents:fileContent attributes:NULL];
  109. free(bytes);
  110. if(success == YES)
  111. callback(@[[NSNull null]]);
  112. else
  113. callback(@[[NSString stringWithFormat:@"failed to create new file at path %@ please ensure the folder exists"]]);
  114. }
  115. #pragma mark - fs.exists
  116. RCT_EXPORT_METHOD(exists:(NSString *)path callback:(RCTResponseSenderBlock)callback) {
  117. [RNFetchBlobFS exists:path callback:callback];
  118. }
  119. #pragma mark - fs.writeFile
  120. RCT_EXPORT_METHOD(writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
  121. [RNFetchBlobFS writeFile:path encoding:[NSString stringWithString:encoding] data:data append:append resolver:resolve rejecter:reject];
  122. })
  123. #pragma mark - fs.writeArray
  124. RCT_EXPORT_METHOD(writeFileArray:(NSString *)path data:(NSArray *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
  125. [RNFetchBlobFS writeFileArray:path data:data append:append resolver:resolve rejecter:reject];
  126. })
  127. #pragma mark - fs.writeStream
  128. RCT_EXPORT_METHOD(writeStream:(NSString *)path withEncoding:(NSString *)encoding appendData:(BOOL)append callback:(RCTResponseSenderBlock)callback) {
  129. RNFetchBlobFS * fileStream = [[RNFetchBlobFS alloc] initWithBridgeRef:self.bridge];
  130. NSFileManager * fm = [NSFileManager defaultManager];
  131. BOOL isDir = nil;
  132. BOOL exist = [fm fileExistsAtPath:path isDirectory:&isDir];
  133. if( exist == NO || isDir == YES) {
  134. callback(@[[NSString stringWithFormat:@"target path `%@` may not exists or it's a folder", path]]);
  135. return;
  136. }
  137. NSString * streamId = [fileStream openWithPath:path encode:encoding appendData:append];
  138. callback(@[[NSNull null], streamId]);
  139. }
  140. #pragma mark - fs.writeArrayChunk
  141. RCT_EXPORT_METHOD(writeArrayChunk:(NSString *)streamId withArray:(NSArray *)dataArray callback:(RCTResponseSenderBlock) callback) {
  142. RNFetchBlobFS *fs = [[RNFetchBlobFS getFileStreams] valueForKey:streamId];
  143. char * bytes = (char *) malloc([dataArray count]);
  144. for(int i = 0; i < dataArray.count; i++) {
  145. bytes[i] = [[dataArray objectAtIndex:i] charValue];
  146. }
  147. NSMutableData * data = [NSMutableData alloc];
  148. [data appendBytes:bytes length:dataArray.count];
  149. [fs write:data];
  150. free(bytes);
  151. callback(@[[NSNull null]]);
  152. }
  153. #pragma mark - fs.writeChunk
  154. RCT_EXPORT_METHOD(writeChunk:(NSString *)streamId withData:(NSString *)data callback:(RCTResponseSenderBlock) callback) {
  155. RNFetchBlobFS *fs = [[RNFetchBlobFS getFileStreams] valueForKey:streamId];
  156. [fs writeEncodeChunk:data];
  157. callback(@[[NSNull null]]);
  158. }
  159. #pragma mark - fs.closeStream
  160. RCT_EXPORT_METHOD(closeStream:(NSString *)streamId callback:(RCTResponseSenderBlock) callback) {
  161. RNFetchBlobFS *fs = [[RNFetchBlobFS getFileStreams] valueForKey:streamId];
  162. [fs closeOutStream];
  163. callback(@[[NSNull null], @YES]);
  164. }
  165. #pragma mark - unlink
  166. RCT_EXPORT_METHOD(unlink:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
  167. NSError * error = nil;
  168. NSString * tmpPath = nil;
  169. [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
  170. if(error == nil)
  171. callback(@[[NSNull null]]);
  172. else
  173. callback(@[[NSString stringWithFormat:@"failed to unlink file or path at %@", path]]);
  174. }
  175. #pragma mark - fs.removeSession
  176. RCT_EXPORT_METHOD(removeSession:(NSArray *)paths callback:(RCTResponseSenderBlock) callback) {
  177. NSError * error = nil;
  178. NSString * tmpPath = nil;
  179. for(NSString * path in paths) {
  180. [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
  181. if(error != nil) {
  182. callback(@[[NSString stringWithFormat:@"failed to remove session path at %@", path]]);
  183. return;
  184. }
  185. }
  186. callback(@[[NSNull null]]);
  187. }
  188. #pragma mark - fs.ls
  189. RCT_EXPORT_METHOD(ls:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
  190. NSFileManager* fm = [NSFileManager defaultManager];
  191. BOOL exist = nil;
  192. BOOL isDir = nil;
  193. exist = [fm fileExistsAtPath:path isDirectory:&isDir];
  194. if(exist == NO || isDir == NO) {
  195. callback(@[[NSString stringWithFormat:@"failed to list path `%@` for it is not exist or it is not a folder", path]]);
  196. return ;
  197. }
  198. NSError * error = nil;
  199. NSArray * result = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
  200. if(error == nil)
  201. callback(@[[NSNull null], result == nil ? [NSNull null] :result ]);
  202. else
  203. callback(@[[error localizedDescription], [NSNull null]]);
  204. }
  205. #pragma mark - fs.stat
  206. RCT_EXPORT_METHOD(stat:(NSString *)target callback:(RCTResponseSenderBlock) callback) {
  207. [RNFetchBlobFS getPathFromUri:target completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  208. __block NSMutableArray * result;
  209. if(path != nil)
  210. {
  211. NSFileManager* fm = [NSFileManager defaultManager];
  212. BOOL exist = nil;
  213. BOOL isDir = nil;
  214. NSError * error = nil;
  215. exist = [fm fileExistsAtPath:path isDirectory:&isDir];
  216. if(exist == NO) {
  217. callback(@[[NSString stringWithFormat:@"failed to stat path `%@` for it is not exist or it is not exist", path]]);
  218. return ;
  219. }
  220. result = [RNFetchBlobFS stat:path error:&error];
  221. if(error == nil)
  222. callback(@[[NSNull null], result]);
  223. else
  224. callback(@[[error localizedDescription], [NSNull null]]);
  225. }
  226. else if(asset != nil)
  227. {
  228. __block NSNumber * size = [NSNumber numberWithLong:[asset size]];
  229. result = [asset metadata];
  230. [result setValue:size forKey:@"size"];
  231. callback(@[[NSNull null], result]);
  232. }
  233. else
  234. {
  235. callback(@[@"failed to stat path, could not resolve URI", [NSNull null]]);
  236. }
  237. }];
  238. }
  239. #pragma mark - fs.lstat
  240. RCT_EXPORT_METHOD(lstat:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
  241. NSFileManager* fm = [NSFileManager defaultManager];
  242. BOOL exist = nil;
  243. BOOL isDir = nil;
  244. path = [RNFetchBlobFS getPathOfAsset:path];
  245. exist = [fm fileExistsAtPath:path isDirectory:&isDir];
  246. if(exist == NO) {
  247. callback(@[[NSString stringWithFormat:@"failed to list path `%@` for it is not exist or it is not exist", path]]);
  248. return ;
  249. }
  250. NSError * error = nil;
  251. NSArray * files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
  252. NSMutableArray * res = [[NSMutableArray alloc] init];
  253. if(isDir == YES) {
  254. for(NSString * p in files) {
  255. NSString * filePath = [NSString stringWithFormat:@"%@/%@", path, p];
  256. [res addObject:[RNFetchBlobFS stat:filePath error:&error]];
  257. }
  258. }
  259. else {
  260. [res addObject:[RNFetchBlobFS stat:path error:&error]];
  261. }
  262. if(error == nil)
  263. callback(@[[NSNull null], res == nil ? [NSNull null] :res ]);
  264. else
  265. callback(@[[error localizedDescription], [NSNull null]]);
  266. }
  267. #pragma mark - fs.cp
  268. RCT_EXPORT_METHOD(cp:(NSString*)src toPath:(NSString *)dest callback:(RCTResponseSenderBlock) callback) {
  269. // path = [RNFetchBlobFS getPathOfAsset:path];
  270. [RNFetchBlobFS getPathFromUri:src completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  271. NSError * error = nil;
  272. if(path == nil)
  273. {
  274. [RNFetchBlobFS writeAssetToPath:asset dest:dest];
  275. callback(@[[NSNull null], @YES]);
  276. }
  277. else
  278. {
  279. BOOL result = [[NSFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:path] toURL:[NSURL fileURLWithPath:dest] error:&error];
  280. if(error == nil)
  281. callback(@[[NSNull null], @YES]);
  282. else
  283. callback(@[[error localizedDescription], @NO]);
  284. }
  285. }];
  286. }
  287. #pragma mark - fs.mv
  288. RCT_EXPORT_METHOD(mv:(NSString *)path toPath:(NSString *)dest callback:(RCTResponseSenderBlock) callback) {
  289. NSError * error = nil;
  290. BOOL result = [[NSFileManager defaultManager] moveItemAtURL:[NSURL fileURLWithPath:path] toURL:[NSURL fileURLWithPath:dest] error:&error];
  291. if(error == nil)
  292. callback(@[[NSNull null], @YES]);
  293. else
  294. callback(@[[error localizedDescription], @NO]);
  295. }
  296. #pragma mark - fs.mkdir
  297. RCT_EXPORT_METHOD(mkdir:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
  298. if([[NSFileManager defaultManager] fileExistsAtPath:path]) {
  299. callback(@[@"mkdir failed, folder already exists"]);
  300. return;
  301. }
  302. else
  303. [RNFetchBlobFS mkdir:path];
  304. callback(@[[NSNull null]]);
  305. }
  306. #pragma mark - fs.readFile
  307. RCT_EXPORT_METHOD(readFile:(NSString *)path encoding:(NSString *)encoding resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
  308. [RNFetchBlobFS readFile:path encoding:encoding resolver:resolve rejecter:reject onComplete:nil];
  309. })
  310. #pragma mark - fs.readStream
  311. RCT_EXPORT_METHOD(readStream:(NSString *)path withEncoding:(NSString *)encoding bufferSize:(int)bufferSize) {
  312. RNFetchBlobFS *fileStream = [[RNFetchBlobFS alloc] initWithBridgeRef:self.bridge];
  313. if(bufferSize == nil) {
  314. if([[encoding lowercaseString] isEqualToString:@"base64"])
  315. bufferSize = 4095;
  316. else
  317. bufferSize = 4096;
  318. }
  319. // read asset stream
  320. [fileStream readWithPath:path useEncoding:encoding bufferSize:bufferSize];
  321. }
  322. #pragma mark - fs.getEnvionmentDirs
  323. RCT_EXPORT_METHOD(getEnvironmentDirs:(RCTResponseSenderBlock) callback) {
  324. callback(@[
  325. [RNFetchBlobFS getDocumentDir],
  326. [RNFetchBlobFS getCacheDir],
  327. ]);
  328. }
  329. #pragma mark - net.cancelRequest
  330. RCT_EXPORT_METHOD(cancelRequest:(NSString *)taskId callback:(RCTResponseSenderBlock)callback) {
  331. [RNFetchBlobNetwork cancelRequest:taskId];
  332. callback(@[[NSNull null], taskId]);
  333. }
  334. #pragma mark - net.enableProgressReport
  335. RCT_EXPORT_METHOD(enableProgressReport:(NSString *)taskId {
  336. [RNFetchBlobNetwork enableProgressReport:taskId];
  337. })
  338. #pragma mark - net.enableUploadProgressReport
  339. RCT_EXPORT_METHOD(enableUploadProgressReport:(NSString *)taskId {
  340. [RNFetchBlobNetwork enableUploadProgress:taskId];
  341. })
  342. #pragma mark - fs.slice
  343. RCT_EXPORT_METHOD(slice:(NSString *)src dest:(NSString *)dest start:(nonnull NSNumber *)start end:(nonnull NSNumber *)end resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject
  344. {
  345. [RNFetchBlobFS slice:src dest:dest start:start end:end encode:@"" resolver:resolve rejecter:reject];
  346. })
  347. #pragma mark RNFetchBlob private methods
  348. @end