No Description

RNFetchBlobFS.m 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. // RNFetchBlobFS.m
  2. // RNFetchBlob
  3. //
  4. // Created by Ben Hsieh on 2016/6/6.
  5. // Copyright © 2016年 suzuri04x2. All rights reserved.
  6. //
  7. #import <Foundation/Foundation.h>
  8. #import "RNFetchBlob.h"
  9. #import "RNFetchBlobFS.h"
  10. #import "RNFetchBlobConst.h"
  11. #import "IOS7Polyfill.h"
  12. @import AssetsLibrary;
  13. #if __has_include(<React/RCTAssert.h>)
  14. #import <React/RCTBridge.h>
  15. #import <React/RCTEventDispatcher.h>
  16. #else
  17. #import "RCTBridge.h"
  18. #import "RCTEventDispatcher.h"
  19. #endif
  20. NSMutableDictionary *fileStreams = nil;
  21. ////////////////////////////////////////
  22. //
  23. // File system access methods
  24. //
  25. ////////////////////////////////////////
  26. @interface RNFetchBlobFS() {
  27. UIDocumentInteractionController * docCtrl;
  28. }
  29. @end
  30. @implementation RNFetchBlobFS
  31. @synthesize outStream;
  32. @synthesize inStream;
  33. @synthesize encoding;
  34. @synthesize callback;
  35. @synthesize taskId;
  36. @synthesize path;
  37. @synthesize appendData;
  38. @synthesize bufferSize;
  39. - (id)init {
  40. self = [super init];
  41. return self;
  42. }
  43. - (id)initWithCallback:(RCTResponseSenderBlock)callback {
  44. self = [super init];
  45. self.callback = callback;
  46. return self;
  47. }
  48. - (id)initWithBridgeRef:(RCTBridge *)bridgeRef {
  49. self = [super init];
  50. self.bridge = bridgeRef;
  51. return self;
  52. }
  53. // static member getter
  54. + (NSArray *) getFileStreams {
  55. if(fileStreams == nil)
  56. fileStreams = [[NSMutableDictionary alloc] init];
  57. return fileStreams;
  58. }
  59. +(void) setFileStream:(RNFetchBlobFS *) instance withId:(NSString *) uuid {
  60. if(fileStreams == nil)
  61. fileStreams = [[NSMutableDictionary alloc] init];
  62. [fileStreams setValue:instance forKey:uuid];
  63. }
  64. +(NSString *) getPathOfAsset:(NSString *)assetURI
  65. {
  66. // get file path of an app asset
  67. if([assetURI hasPrefix:ASSET_PREFIX])
  68. {
  69. assetURI = [assetURI stringByReplacingOccurrencesOfString:ASSET_PREFIX withString:@""];
  70. assetURI = [[NSBundle mainBundle] pathForResource: [assetURI stringByDeletingPathExtension]
  71. ofType: [assetURI pathExtension]];
  72. }
  73. return assetURI;
  74. }
  75. #pragma mark - system directories
  76. + (NSString *) getMainBundleDir {
  77. return [[NSBundle mainBundle] bundlePath];
  78. }
  79. + (NSString *) getCacheDir {
  80. return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  81. }
  82. + (NSString *) getDocumentDir {
  83. return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  84. }
  85. + (NSString *) getMusicDir {
  86. return [NSSearchPathForDirectoriesInDomains(NSMusicDirectory, NSUserDomainMask, YES) firstObject];
  87. }
  88. + (NSString *) getMovieDir {
  89. return [NSSearchPathForDirectoriesInDomains(NSMoviesDirectory, NSUserDomainMask, YES) firstObject];
  90. }
  91. + (NSString *) getPictureDir {
  92. return [NSSearchPathForDirectoriesInDomains(NSPicturesDirectory, NSUserDomainMask, YES) firstObject];
  93. }
  94. + (NSString *) getTempPath {
  95. return NSTemporaryDirectory();
  96. }
  97. + (NSString *) getTempPath:(NSString*)taskId withExtension:(NSString *)ext {
  98. NSString * documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  99. NSString * filename = [NSString stringWithFormat:@"/RNFetchBlob_tmp/RNFetchBlobTmp_%@", taskId];
  100. if(ext != nil)
  101. filename = [filename stringByAppendingString: [NSString stringWithFormat:@".%@", ext]];
  102. NSString * tempPath = [documentDir stringByAppendingString: filename];
  103. return tempPath;
  104. }
  105. + (NSString *) getPathForAppGroup:(NSString *)groupName {
  106. NSFileManager* fileManager = [NSFileManager defaultManager];
  107. NSURL* containerURL = [fileManager containerURLForSecurityApplicationGroupIdentifier:groupName];
  108. if(containerURL) {
  109. return [containerURL path];
  110. } else {
  111. return nil;
  112. }
  113. }
  114. #pragma margk - readStream
  115. + (void) readStream:(NSString *)uri
  116. encoding:(NSString * )encoding
  117. bufferSize:(int)bufferSize
  118. tick:(int)tick
  119. streamId:(NSString *)streamId
  120. bridgeRef:(RCTBridge *)bridgeRef
  121. {
  122. [[self class] getPathFromUri:uri completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  123. __block RCTEventDispatcher * event = bridgeRef.eventDispatcher;
  124. __block int read = 0;
  125. __block int backoff = tick *1000;
  126. __block int chunkSize = bufferSize;
  127. // allocate buffer in heap instead of stack
  128. uint8_t * buffer;
  129. @try
  130. {
  131. buffer = (uint8_t *) malloc(bufferSize);
  132. if(path != nil)
  133. {
  134. if([[NSFileManager defaultManager] fileExistsAtPath:path] == NO)
  135. {
  136. NSString * message = [NSString stringWithFormat:@"File does not exist at path %@", path];
  137. NSDictionary * payload = @{ @"event": FS_EVENT_ERROR, @"detail": message };
  138. [event sendDeviceEventWithName:streamId body:payload];
  139. free(buffer);
  140. return ;
  141. }
  142. NSInputStream * stream = [[NSInputStream alloc] initWithFileAtPath:path];
  143. [stream open];
  144. while((read = [stream read:buffer maxLength:bufferSize]) > 0)
  145. {
  146. [[self class] emitDataChunks:[NSData dataWithBytes:buffer length:read] encoding:encoding streamId:streamId event:event];
  147. if(tick > 0)
  148. {
  149. usleep(backoff);
  150. }
  151. }
  152. [stream close];
  153. }
  154. else if (asset != nil)
  155. {
  156. int cursor = 0;
  157. NSError * err;
  158. while((read = [asset getBytes:buffer fromOffset:cursor length:bufferSize error:&err]) > 0)
  159. {
  160. cursor += read;
  161. [[self class] emitDataChunks:[NSData dataWithBytes:buffer length:read] encoding:encoding streamId:streamId event:event];
  162. if(tick > 0)
  163. {
  164. usleep(backoff);
  165. }
  166. }
  167. }
  168. else
  169. {
  170. NSDictionary * payload = @{ @"event": FS_EVENT_ERROR, @"detail": @"RNFetchBlob.readStream unable to resolve URI" };
  171. [event sendDeviceEventWithName:streamId body:payload];
  172. }
  173. // release buffer
  174. if(buffer != nil)
  175. free(buffer);
  176. }
  177. @catch (NSError * err)
  178. {
  179. NSDictionary * payload = @{ @"event": FS_EVENT_ERROR, @"detail": [NSString stringWithFormat:@"RNFetchBlob.readStream error %@", [err description]] };
  180. [event sendDeviceEventWithName:streamId body:payload];
  181. }
  182. @finally
  183. {
  184. NSDictionary * payload = @{ @"event": FS_EVENT_END, @"detail": @"" };
  185. [event sendDeviceEventWithName:streamId body:payload];
  186. }
  187. }];
  188. }
  189. // send read stream chunks via native event emitter
  190. + (void) emitDataChunks:(NSData *)data encoding:(NSString *) encoding streamId:(NSString *)streamId event:(RCTEventDispatcher *)event
  191. {
  192. @try
  193. {
  194. NSString * encodedChunk = @"";
  195. if([[encoding lowercaseString] isEqualToString:@"utf8"])
  196. {
  197. NSDictionary * payload = @{
  198. @"event": FS_EVENT_DATA,
  199. @"detail" : [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]
  200. };
  201. [event sendDeviceEventWithName:streamId body:payload];
  202. }
  203. else if ([[encoding lowercaseString] isEqualToString:@"base64"])
  204. {
  205. NSDictionary * payload = @{ @"event": FS_EVENT_DATA, @"detail" : [data base64EncodedStringWithOptions:0] };
  206. [event sendDeviceEventWithName:streamId body:payload];
  207. }
  208. else if([[encoding lowercaseString] isEqualToString:@"ascii"])
  209. {
  210. // RCTBridge only emits string data, so we have to create JSON byte array string
  211. NSMutableArray * asciiArray = [NSMutableArray array];
  212. unsigned char *bytePtr;
  213. if (data.length > 0)
  214. {
  215. bytePtr = (unsigned char *)[data bytes];
  216. NSInteger byteLen = data.length/sizeof(uint8_t);
  217. for (int i = 0; i < byteLen; i++)
  218. {
  219. [asciiArray addObject:[NSNumber numberWithChar:bytePtr[i]]];
  220. }
  221. }
  222. NSDictionary * payload = @{ @"event": FS_EVENT_DATA, @"detail" : asciiArray };
  223. [event sendDeviceEventWithName:streamId body:payload];
  224. }
  225. }
  226. @catch (NSException * ex)
  227. {
  228. NSString * message = [NSString stringWithFormat:@"Failed to convert data to '%@' encoded string, this might due to the source data is not able to convert using this encoding. source = %@", encoding, [ex description]];
  229. [event
  230. sendDeviceEventWithName:streamId
  231. body:@{
  232. @"event" : MSG_EVENT_ERROR,
  233. @"detail" : message
  234. }];
  235. [event
  236. sendDeviceEventWithName:MSG_EVENT
  237. body:@{
  238. @"event" : MSG_EVENT_WARN,
  239. @"detail" : message
  240. }];
  241. }
  242. }
  243. # pragma write file from file
  244. + (NSNumber *) writeFileFromFile:(NSString *)src toFile:(NSString *)dest append:(BOOL)append callback:(void(^)(NSString * errMsg, NSNumber *size))callback
  245. {
  246. [[self class] getPathFromUri:src completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  247. if(path != nil)
  248. {
  249. __block NSInputStream * is = [[NSInputStream alloc] initWithFileAtPath:path];
  250. __block NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:append];
  251. [is open];
  252. [os open];
  253. uint8_t buffer[10240];
  254. __block long written = 0;
  255. int read = [is read:buffer maxLength:10240];
  256. written += read;
  257. while(read > 0) {
  258. [os write:buffer maxLength:read];
  259. read = [is read:buffer maxLength:10240];
  260. written += read;
  261. }
  262. [os close];
  263. [is close];
  264. __block NSNumber * size = [NSNumber numberWithLong:written];
  265. callback(nil, size);
  266. }
  267. else if(asset != nil)
  268. {
  269. __block NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:append];
  270. int read = 0;
  271. int cursor = 0;
  272. __block long written = 0;
  273. uint8_t buffer[10240];
  274. [os open];
  275. while((read = [asset getBytes:buffer fromOffset:cursor length:10240 error:nil]) > 0)
  276. {
  277. cursor += read;
  278. [os write:buffer maxLength:read];
  279. }
  280. __block NSNumber * size = [NSNumber numberWithLong:written];
  281. [os close];
  282. callback(nil, size);
  283. }
  284. else
  285. callback(@"failed to resolve path", nil);
  286. }];
  287. return 0;
  288. }
  289. # pragma mark - write file
  290. + (void) writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject
  291. {
  292. @try {
  293. NSFileManager * fm = [NSFileManager defaultManager];
  294. NSError * err = nil;
  295. // check if the folder exists, if it does not exist create folders recursively
  296. // after the folders created, write data into the file
  297. NSString * folder = [path stringByDeletingLastPathComponent];
  298. encoding = [encoding lowercaseString];
  299. if(![fm fileExistsAtPath:folder]) {
  300. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:&err];
  301. if(err != nil) {
  302. return reject(@"ENOTDIR", [NSString stringWithFormat:@"Failed to create parent directory of '%@'; error: %@", path, [err description]], nil);
  303. }
  304. if(![fm createFileAtPath:path contents:nil attributes:nil]) {
  305. return reject(@"ENOENT", [NSString stringWithFormat:@"File '%@' does not exist and could not be created", path], nil);
  306. }
  307. }
  308. NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
  309. NSData * content = nil;
  310. if([encoding RNFBContainsString:@"base64"]) {
  311. content = [[NSData alloc] initWithBase64EncodedString:data options:0];
  312. }
  313. else if([encoding isEqualToString:@"uri"]) {
  314. NSNumber* size = [[self class] writeFileFromFile:data toFile:path append:append callback:^(NSString *errMsg, NSNumber *size) {
  315. if(errMsg != nil)
  316. reject(@"RNFetchBlob writeFile Error", errMsg, nil);
  317. else
  318. resolve(size);
  319. }];
  320. return;
  321. }
  322. else {
  323. content = [data dataUsingEncoding:NSUTF8StringEncoding];
  324. }
  325. if(append == YES) {
  326. [fileHandle seekToEndOfFile];
  327. [fileHandle writeData:content];
  328. [fileHandle closeFile];
  329. }
  330. else {
  331. [content writeToFile:path atomically:YES];
  332. }
  333. fm = nil;
  334. resolve([NSNumber numberWithInteger:[content length]]);
  335. }
  336. @catch (NSException * e)
  337. {
  338. reject(@"RNFetchBlob writeFile Error", @"Error", [e description]);
  339. }
  340. }
  341. # pragma mark - write file (array)
  342. + (void) writeFileArray:(NSString *)path data:(NSArray *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
  343. @try {
  344. NSFileManager * fm = [NSFileManager defaultManager];
  345. NSError * err = nil;
  346. // check if the folder exists, if not exists, create folders recursively
  347. // after the folders created, write data into the file
  348. NSString * folder = [path stringByDeletingLastPathComponent];
  349. if(![fm fileExistsAtPath:folder]) {
  350. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:&err];
  351. }
  352. NSMutableData * fileContent = [NSMutableData alloc];
  353. // prevent stack overflow, alloc on heap
  354. char * bytes = (char*) malloc([data count]);
  355. for(int i = 0; i < data.count; i++) {
  356. bytes[i] = [[data objectAtIndex:i] charValue];
  357. }
  358. [fileContent appendBytes:bytes length:data.count];
  359. if(![fm fileExistsAtPath:path]) {
  360. [fm createFileAtPath:path contents:fileContent attributes:NULL];
  361. }
  362. // if file exists, write file
  363. else {
  364. if(append == YES) {
  365. NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
  366. [fileHandle seekToEndOfFile];
  367. [fileHandle writeData:fileContent];
  368. [fileHandle closeFile];
  369. }
  370. else {
  371. [fileContent writeToFile:path atomically:YES];
  372. }
  373. }
  374. free(bytes);
  375. fm = nil;
  376. resolve([NSNumber numberWithInteger: data.count]);
  377. }
  378. @catch (NSException * e)
  379. {
  380. reject(@"RNFetchBlob writeFile Error", @"Error", [e description]);
  381. }
  382. }
  383. # pragma mark - read file
  384. + (void) readFile:(NSString *)path
  385. encoding:(NSString *)encoding
  386. onComplete:(void (^)(id content, NSString * errMsg))onComplete
  387. {
  388. [[self class] getPathFromUri:path completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  389. __block NSData * fileContent;
  390. NSError * err;
  391. __block Byte * buffer;
  392. if(asset != nil)
  393. {
  394. buffer = malloc(asset.size);
  395. [asset getBytes:buffer fromOffset:0 length:asset.size error:&err];
  396. if(err != nil)
  397. {
  398. onComplete(nil, [err description]);
  399. free(buffer);
  400. return;
  401. }
  402. fileContent = [NSData dataWithBytes:buffer length:asset.size];
  403. free(buffer);
  404. }
  405. else
  406. {
  407. if(![[NSFileManager defaultManager] fileExistsAtPath:path]) {
  408. onComplete(nil, @"file does not exist");
  409. return;
  410. }
  411. fileContent = [NSData dataWithContentsOfFile:path];
  412. }
  413. if(encoding != nil)
  414. {
  415. if([[encoding lowercaseString] isEqualToString:@"utf8"])
  416. {
  417. NSString * utf8 = [[NSString alloc] initWithData:fileContent encoding:NSUTF8StringEncoding];
  418. if(utf8 == nil)
  419. onComplete([[NSString alloc] initWithData:fileContent encoding:NSISOLatin1StringEncoding], nil);
  420. else
  421. onComplete(utf8, nil);
  422. }
  423. else if ([[encoding lowercaseString] isEqualToString:@"base64"]) {
  424. onComplete([fileContent base64EncodedStringWithOptions:0], nil);
  425. }
  426. else if ([[encoding lowercaseString] isEqualToString:@"ascii"]) {
  427. NSMutableArray * resultArray = [NSMutableArray array];
  428. char * bytes = [fileContent bytes];
  429. for(int i=0;i<[fileContent length];i++) {
  430. [resultArray addObject:[NSNumber numberWithChar:bytes[i]]];
  431. }
  432. onComplete(resultArray, nil);
  433. }
  434. }
  435. else
  436. {
  437. onComplete(fileContent, nil);
  438. }
  439. }];
  440. }
  441. # pragma mark - hash
  442. RCT_EXPORT_METHOD(hash:(NSString *)filepath
  443. algorithm:(NSString *)algorithm
  444. resolver:(RCTPromiseResolveBlock)resolve
  445. rejecter:(RCTPromiseRejectBlock)reject)
  446. {
  447. BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filepath];
  448. if (!fileExists) {
  449. return reject(@"ENOENT", [NSString stringWithFormat:@"ENOENT: no such file or directory, open '%@'", filepath], nil);
  450. }
  451. NSError *error = nil;
  452. NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filepath error:&error];
  453. if (error) {
  454. return [self reject:reject withError:error];
  455. }
  456. if ([attributes objectForKey:NSFileType] == NSFileTypeDirectory) {
  457. return reject(@"EISDIR", @"EISDIR: illegal operation on a directory, read", nil);
  458. }
  459. NSData *content = [[NSFileManager defaultManager] contentsAtPath:filepath];
  460. NSArray *keys = [NSArray arrayWithObjects:@"md5", @"sha1", @"sha224", @"sha256", @"sha384", @"sha512", nil];
  461. NSArray *digestLengths = [NSArray arrayWithObjects:
  462. @CC_MD5_DIGEST_LENGTH,
  463. @CC_SHA1_DIGEST_LENGTH,
  464. @CC_SHA224_DIGEST_LENGTH,
  465. @CC_SHA256_DIGEST_LENGTH,
  466. @CC_SHA384_DIGEST_LENGTH,
  467. @CC_SHA512_DIGEST_LENGTH,
  468. nil];
  469. NSDictionary *keysToDigestLengths = [NSDictionary dictionaryWithObjects:digestLengths forKeys:keys];
  470. int digestLength = [[keysToDigestLengths objectForKey:algorithm] intValue];
  471. if (!digestLength) {
  472. return reject(@"Error", [NSString stringWithFormat:@"Invalid hash algorithm '%@'", algorithm], nil);
  473. }
  474. unsigned char buffer[digestLength];
  475. if ([algorithm isEqualToString:@"md5"]) {
  476. CC_MD5(content.bytes, (CC_LONG)content.length, buffer);
  477. } else if ([algorithm isEqualToString:@"sha1"]) {
  478. CC_SHA1(content.bytes, (CC_LONG)content.length, buffer);
  479. } else if ([algorithm isEqualToString:@"sha224"]) {
  480. CC_SHA224(content.bytes, (CC_LONG)content.length, buffer);
  481. } else if ([algorithm isEqualToString:@"sha256"]) {
  482. CC_SHA256(content.bytes, (CC_LONG)content.length, buffer);
  483. } else if ([algorithm isEqualToString:@"sha384"]) {
  484. CC_SHA384(content.bytes, (CC_LONG)content.length, buffer);
  485. } else if ([algorithm isEqualToString:@"sha512"]) {
  486. CC_SHA512(content.bytes, (CC_LONG)content.length, buffer);
  487. } else {
  488. return reject(@"Error", [NSString stringWithFormat:@"Invalid hash algorithm '%@'", algorithm], nil);
  489. }
  490. NSMutableString *output = [NSMutableString stringWithCapacity:digestLength * 2];
  491. for(int i = 0; i < digestLength; i++)
  492. [output appendFormat:@"%02x",buffer[i]];
  493. resolve(output);
  494. }
  495. # pragma mark - mkdir
  496. + (BOOL) mkdir:(NSString *) path {
  497. BOOL isDir;
  498. NSError * err = nil;
  499. // if temp folder does not exist create it
  500. if(![[NSFileManager defaultManager] fileExistsAtPath: path isDirectory:&isDir]) {
  501. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&err];
  502. }
  503. return err == nil;
  504. }
  505. # pragma mark - stat
  506. + (NSDictionary *) stat:(NSString *) path error:(NSError **) error {
  507. BOOL isDir = NO;
  508. NSFileManager * fm = [NSFileManager defaultManager];
  509. if([fm fileExistsAtPath:path isDirectory:&isDir] == NO) {
  510. return nil;
  511. }
  512. NSDictionary * info = [fm attributesOfItemAtPath:path error:&error];
  513. NSString * size = [NSString stringWithFormat:@"%d", [info fileSize]];
  514. NSString * filename = [path lastPathComponent];
  515. NSDate * lastModified;
  516. [[NSURL fileURLWithPath:path] getResourceValue:&lastModified forKey:NSURLContentModificationDateKey error:&error];
  517. return @{
  518. @"size" : size,
  519. @"filename" : filename,
  520. @"path" : path,
  521. @"lastModified" : [NSNumber numberWithLong:(time_t) [lastModified timeIntervalSince1970]*1000],
  522. @"type" : isDir ? @"directory" : @"file"
  523. };
  524. }
  525. # pragma mark - exists
  526. + (void) exists:(NSString *) path callback:(RCTResponseSenderBlock)callback
  527. {
  528. [[self class] getPathFromUri:path completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  529. if(path != nil)
  530. {
  531. BOOL isDir = NO;
  532. BOOL exists = NO;
  533. exists = [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory: &isDir];
  534. callback(@[@(exists), @(isDir)]);
  535. }
  536. else if(asset != nil)
  537. {
  538. callback(@[@YES, @NO]);
  539. }
  540. else
  541. {
  542. callback(@[@NO, @NO]);
  543. }
  544. }];
  545. }
  546. # pragma mark - open file stream
  547. // Create file stream for write data
  548. - (NSString *)openWithPath:(NSString *)destPath encode:(nullable NSString *)encode appendData:(BOOL)append {
  549. self.outStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:append];
  550. self.encoding = encode;
  551. [self.outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  552. [self.outStream open];
  553. NSString *uuid = [[NSUUID UUID] UUIDString];
  554. self.streamId = uuid;
  555. [RNFetchBlobFS setFileStream:self withId:uuid];
  556. return uuid;
  557. }
  558. # pragma mark - file stream write chunk
  559. // Write file chunk into an opened stream
  560. - (void)writeEncodeChunk:(NSString *) chunk {
  561. NSData * decodedData = nil;
  562. if([[self.encoding lowercaseString] isEqualToString:@"base64"]) {
  563. decodedData = [[NSData alloc] initWithBase64EncodedString:chunk options: NSDataBase64DecodingIgnoreUnknownCharacters];
  564. }
  565. else if([[self.encoding lowercaseString] isEqualToString:@"utf8"]) {
  566. decodedData = [chunk dataUsingEncoding:NSUTF8StringEncoding];
  567. }
  568. else if([[self.encoding lowercaseString] isEqualToString:@"ascii"]) {
  569. decodedData = [chunk dataUsingEncoding:NSASCIIStringEncoding];
  570. }
  571. NSUInteger left = [decodedData length];
  572. NSUInteger nwr = 0;
  573. do {
  574. nwr = [self.outStream write:[decodedData bytes] maxLength:left];
  575. if (-1 == nwr) break;
  576. left -= nwr;
  577. } while (left > 0);
  578. if (left) {
  579. NSLog(@"stream error: %@", [self.outStream streamError]);
  580. }
  581. }
  582. // Write file chunk into an opened stream
  583. - (void)write:(NSData *) chunk {
  584. NSUInteger left = [chunk length];
  585. NSUInteger nwr = 0;
  586. do {
  587. nwr = [self.outStream write:[chunk bytes] maxLength:left];
  588. if (-1 == nwr) break;
  589. left -= nwr;
  590. } while (left > 0);
  591. if (left) {
  592. NSLog(@"stream error: %@", [self.outStream streamError]);
  593. }
  594. }
  595. // close file write stream
  596. - (void)closeOutStream {
  597. if(self.outStream != nil) {
  598. [self.outStream close];
  599. self.outStream = nil;
  600. }
  601. }
  602. // Slice a file into another file, generally for support Blob implementation.
  603. + (void)slice:(NSString *)path
  604. dest:(NSString *)dest
  605. start:(nonnull NSNumber *)start
  606. end:(nonnull NSNumber *)end
  607. encode:(NSString *)encode
  608. resolver:(RCTPromiseResolveBlock)resolve
  609. rejecter:(RCTPromiseRejectBlock)reject
  610. {
  611. [[self class] getPathFromUri:path completionHandler:^(NSString *path, ALAssetRepresentation *asset)
  612. {
  613. if(path != nil)
  614. {
  615. long expected = [end longValue] - [start longValue];
  616. long read = 0;
  617. NSFileHandle * handle = [NSFileHandle fileHandleForReadingAtPath:path];
  618. NSFileManager * fm = [NSFileManager defaultManager];
  619. NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:NO];
  620. [os open];
  621. // abort because the source file does not exist
  622. if([fm fileExistsAtPath:path] == NO)
  623. {
  624. reject(@"RNFetchBlob slice Error : the file does not exist", path, nil);
  625. return;
  626. }
  627. long size = [fm attributesOfItemAtPath:path error:nil].fileSize;
  628. long max = MIN(size, [end longValue]);
  629. if(![fm fileExistsAtPath:dest]) {
  630. [fm createFileAtPath:dest contents:@"" attributes:nil];
  631. }
  632. [handle seekToFileOffset:[start longValue]];
  633. while(read < expected)
  634. {
  635. NSData * chunk;
  636. long chunkSize = 0;
  637. if([start longValue] + read + 10240 > max)
  638. {
  639. NSLog(@"read chunk %lu", max - read - [start longValue]);
  640. chunkSize = max - read - [start longValue];
  641. chunk = [handle readDataOfLength:chunkSize];
  642. }
  643. else
  644. {
  645. NSLog(@"read chunk %lu", 10240);
  646. chunkSize = 10240;
  647. chunk = [handle readDataOfLength:10240];
  648. }
  649. if([chunk length] <= 0)
  650. break;
  651. long remain = expected - read;
  652. [os write:[chunk bytes] maxLength:chunkSize];
  653. read += [chunk length];
  654. }
  655. [handle closeFile];
  656. [os close];
  657. resolve(dest);
  658. }
  659. else if (asset != nil)
  660. {
  661. long expected = [end longValue] - [start longValue];
  662. long read = 0;
  663. long chunkRead = 0;
  664. NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:NO];
  665. [os open];
  666. long size = asset.size;
  667. long max = MIN(size, [end longValue]);
  668. while(read < expected)
  669. {
  670. uint8_t * chunk[10240];
  671. long chunkSize = 0;
  672. if([start longValue] + read + 10240 > max)
  673. {
  674. NSLog(@"read chunk %lu", max - read - [start longValue]);
  675. chunkSize = max - read - [start longValue];
  676. chunkRead = [asset getBytes:chunk fromOffset:[start longValue] + read length:chunkSize error:nil];
  677. }
  678. else
  679. {
  680. NSLog(@"read chunk %lu", 10240);
  681. chunkSize = 10240;
  682. chunkRead = [asset getBytes:chunk fromOffset:[start longValue] + read length:chunkSize error:nil];
  683. }
  684. if( chunkRead <= 0)
  685. break;
  686. long remain = expected - read;
  687. [os write:chunk maxLength:chunkSize];
  688. read += chunkRead;
  689. }
  690. [os close];
  691. resolve(dest);
  692. }
  693. else
  694. {
  695. reject(@"RNFetchBlob slice Error", [NSString stringWithFormat: @"could not resolve URI %@", path ], nil);
  696. }
  697. }];
  698. }
  699. // close file read stream
  700. - (void)closeInStream
  701. {
  702. if(self.inStream != nil) {
  703. [self.inStream close];
  704. [self.inStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  705. [[RNFetchBlobFS getFileStreams] setValue:nil forKey:self.streamId];
  706. self.streamId = nil;
  707. }
  708. }
  709. # pragma mark - get absolute path of resource
  710. + (void) getPathFromUri:(NSString *)uri completionHandler:(void(^)(NSString * path, ALAssetRepresentation *asset)) onComplete
  711. {
  712. if([uri hasPrefix:AL_PREFIX])
  713. {
  714. NSURL *asseturl = [NSURL URLWithString:uri];
  715. __block ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
  716. [assetslibrary assetForURL:asseturl
  717. resultBlock:^(ALAsset *asset) {
  718. __block ALAssetRepresentation * present = [asset defaultRepresentation];
  719. onComplete(nil, present);
  720. }
  721. failureBlock:^(NSError *error) {
  722. onComplete(nil, nil);
  723. }];
  724. }
  725. else
  726. {
  727. onComplete([[self class] getPathOfAsset:uri], nil);
  728. }
  729. }
  730. #pragma mark - get disk space
  731. +(void) df:(RCTResponseSenderBlock)callback
  732. {
  733. NSError *error = nil;
  734. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  735. NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
  736. if (dictionary) {
  737. NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
  738. NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
  739. callback(@[[NSNull null], @{
  740. @"free" : freeFileSystemSizeInBytes,
  741. @"total" : fileSystemSizeInBytes,
  742. }]);
  743. } else {
  744. callback(@[@"failed to get storage usage."]);
  745. }
  746. }
  747. + (void) writeAssetToPath:(ALAssetRepresentation * )rep dest:(NSString *)dest
  748. {
  749. int read = 0;
  750. int cursor = 0;
  751. Byte * buffer = (Byte *)malloc(10240);
  752. NSOutputStream * ostream = [[NSOutputStream alloc] initToFileAtPath:dest append:NO];
  753. [ostream open];
  754. while((read = [rep getBytes:buffer fromOffset:cursor length:10240 error:nil]) > 0)
  755. {
  756. cursor+=10240;
  757. [ostream write:buffer maxLength:read];
  758. }
  759. [ostream close];
  760. free(buffer);
  761. return;
  762. }
  763. @end