No Description

RNFetchBlobFS.m 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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. #pragma margk - readStream
  106. + (void) readStream:(NSString *)uri
  107. encoding:(NSString * )encoding
  108. bufferSize:(int)bufferSize
  109. tick:(int)tick
  110. streamId:(NSString *)streamId
  111. bridgeRef:(RCTBridge *)bridgeRef
  112. {
  113. [[self class] getPathFromUri:uri completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  114. __block RCTEventDispatcher * event = bridgeRef.eventDispatcher;
  115. __block int read = 0;
  116. __block int backoff = tick *1000;
  117. __block int chunkSize = bufferSize;
  118. // allocate buffer in heap instead of stack
  119. uint8_t * buffer;
  120. @try
  121. {
  122. buffer = (uint8_t *) malloc(bufferSize);
  123. if(path != nil)
  124. {
  125. if([[NSFileManager defaultManager] fileExistsAtPath:path] == NO)
  126. {
  127. NSString * message = [NSString stringWithFormat:@"File not exists at path %@", path];
  128. NSDictionary * payload = @{ @"event": FS_EVENT_ERROR, @"detail": message };
  129. [event sendDeviceEventWithName:streamId body:payload];
  130. free(buffer);
  131. return ;
  132. }
  133. NSInputStream * stream = [[NSInputStream alloc] initWithFileAtPath:path];
  134. [stream open];
  135. while((read = [stream read:buffer maxLength:bufferSize]) > 0)
  136. {
  137. [[self class] emitDataChunks:[NSData dataWithBytes:buffer length:read] encoding:encoding streamId:streamId event:event];
  138. if(tick > 0)
  139. {
  140. usleep(backoff);
  141. }
  142. }
  143. [stream close];
  144. }
  145. else if (asset != nil)
  146. {
  147. int cursor = 0;
  148. NSError * err;
  149. while((read = [asset getBytes:buffer fromOffset:cursor length:bufferSize error:&err]) > 0)
  150. {
  151. cursor += read;
  152. [[self class] emitDataChunks:[NSData dataWithBytes:buffer length:read] encoding:encoding streamId:streamId event:event];
  153. if(tick > 0)
  154. {
  155. usleep(backoff);
  156. }
  157. }
  158. }
  159. else
  160. {
  161. NSDictionary * payload = @{ @"event": FS_EVENT_ERROR, @"detail": @"RNFetchBlob.readStream unable to resolve URI" };
  162. [event sendDeviceEventWithName:streamId body:payload];
  163. }
  164. // release buffer
  165. if(buffer != nil)
  166. free(buffer);
  167. }
  168. @catch (NSError * err)
  169. {
  170. NSDictionary * payload = @{ @"event": FS_EVENT_ERROR, @"detail": [NSString stringWithFormat:@"RNFetchBlob.readStream error %@", [err description]] };
  171. [event sendDeviceEventWithName:streamId body:payload];
  172. }
  173. @finally
  174. {
  175. NSDictionary * payload = @{ @"event": FS_EVENT_END, @"detail": @"" };
  176. [event sendDeviceEventWithName:streamId body:payload];
  177. }
  178. }];
  179. }
  180. // send read stream chunks via native event emitter
  181. + (void) emitDataChunks:(NSData *)data encoding:(NSString *) encoding streamId:(NSString *)streamId event:(RCTEventDispatcher *)event
  182. {
  183. @try
  184. {
  185. NSString * encodedChunk = @"";
  186. if([[encoding lowercaseString] isEqualToString:@"utf8"])
  187. {
  188. NSDictionary * payload = @{
  189. @"event": FS_EVENT_DATA,
  190. @"detail" : [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]
  191. };
  192. [event sendDeviceEventWithName:streamId body:payload];
  193. }
  194. else if ([[encoding lowercaseString] isEqualToString:@"base64"])
  195. {
  196. NSDictionary * payload = @{ @"event": FS_EVENT_DATA, @"detail" : [data base64EncodedStringWithOptions:0] };
  197. [event sendDeviceEventWithName:streamId body:payload];
  198. }
  199. else if([[encoding lowercaseString] isEqualToString:@"ascii"])
  200. {
  201. // RCTBridge only emits string data, so we have to create JSON byte array string
  202. NSMutableArray * asciiArray = [NSMutableArray array];
  203. unsigned char *bytePtr;
  204. if (data.length > 0)
  205. {
  206. bytePtr = (unsigned char *)[data bytes];
  207. NSInteger byteLen = data.length/sizeof(uint8_t);
  208. for (int i = 0; i < byteLen; i++)
  209. {
  210. [asciiArray addObject:[NSNumber numberWithChar:bytePtr[i]]];
  211. }
  212. }
  213. NSDictionary * payload = @{ @"event": FS_EVENT_DATA, @"detail" : asciiArray };
  214. [event sendDeviceEventWithName:streamId body:payload];
  215. }
  216. }
  217. @catch (NSException * ex)
  218. {
  219. 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]];
  220. [event
  221. sendDeviceEventWithName:streamId
  222. body:@{
  223. @"event" : MSG_EVENT_ERROR,
  224. @"detail" : message
  225. }];
  226. [event
  227. sendDeviceEventWithName:MSG_EVENT
  228. body:@{
  229. @"event" : MSG_EVENT_WARN,
  230. @"detail" : message
  231. }];
  232. }
  233. }
  234. # pragma write file from file
  235. + (NSNumber *) writeFileFromFile:(NSString *)src toFile:(NSString *)dest append:(BOOL)append callback:(void(^)(NSString * errMsg, NSNumber *size))callback
  236. {
  237. [[self class] getPathFromUri:src completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  238. if(path != nil)
  239. {
  240. __block NSInputStream * is = [[NSInputStream alloc] initWithFileAtPath:path];
  241. __block NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:append];
  242. [is open];
  243. [os open];
  244. uint8_t buffer[10240];
  245. __block long written = 0;
  246. int read = [is read:buffer maxLength:10240];
  247. written += read;
  248. while(read > 0) {
  249. [os write:buffer maxLength:read];
  250. read = [is read:buffer maxLength:10240];
  251. written += read;
  252. }
  253. [os close];
  254. [is close];
  255. __block NSNumber * size = [NSNumber numberWithLong:written];
  256. callback(nil, size);
  257. }
  258. else if(asset != nil)
  259. {
  260. __block NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:append];
  261. int read = 0;
  262. int cursor = 0;
  263. __block long written = 0;
  264. uint8_t buffer[10240];
  265. [os open];
  266. while((read = [asset getBytes:buffer fromOffset:cursor length:10240 error:nil]) > 0)
  267. {
  268. cursor += read;
  269. [os write:buffer maxLength:read];
  270. }
  271. __block NSNumber * size = [NSNumber numberWithLong:written];
  272. [os close];
  273. callback(nil, size);
  274. }
  275. else
  276. callback(@"failed to resolve path", nil);
  277. }];
  278. return 0;
  279. }
  280. # pragma mark - write file
  281. + (void) writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject
  282. {
  283. @try {
  284. NSFileManager * fm = [NSFileManager defaultManager];
  285. NSError * err = nil;
  286. // check if the folder exists, if not exists, create folders recursively
  287. // after the folders created, write data into the file
  288. NSString * folder = [path stringByDeletingLastPathComponent];
  289. encoding = [encoding lowercaseString];
  290. if(![fm fileExistsAtPath:folder]) {
  291. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:&err];
  292. [fm createFileAtPath:path contents:nil attributes:nil];
  293. }
  294. if(err != nil) {
  295. reject(@"RNFetchBlob writeFile Error", @"could not create file at path", nil);
  296. return;
  297. }
  298. NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
  299. NSData * content = nil;
  300. if([encoding RNFBContainsString:@"base64"]) {
  301. content = [[NSData alloc] initWithBase64EncodedString:data options:0];
  302. }
  303. else if([encoding isEqualToString:@"uri"]) {
  304. NSNumber* size = [[self class] writeFileFromFile:data toFile:path append:append callback:^(NSString *errMsg, NSNumber *size) {
  305. if(errMsg != nil)
  306. reject(@"RNFetchBlob writeFile Error", errMsg, nil);
  307. else
  308. resolve(size);
  309. }];
  310. return;
  311. }
  312. else {
  313. content = [data dataUsingEncoding:NSUTF8StringEncoding];
  314. }
  315. if(append == YES) {
  316. [fileHandle seekToEndOfFile];
  317. [fileHandle writeData:content];
  318. [fileHandle closeFile];
  319. }
  320. else {
  321. [content writeToFile:path atomically:YES];
  322. }
  323. fm = nil;
  324. resolve([NSNumber numberWithInteger:[content length]]);
  325. }
  326. @catch (NSException * e)
  327. {
  328. reject(@"RNFetchBlob writeFile Error", @"Error", [e description]);
  329. }
  330. }
  331. # pragma mark - write file (array)
  332. + (void) writeFileArray:(NSString *)path data:(NSArray *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
  333. @try {
  334. NSFileManager * fm = [NSFileManager defaultManager];
  335. NSError * err = nil;
  336. // check if the folder exists, if not exists, create folders recursively
  337. // after the folders created, write data into the file
  338. NSString * folder = [path stringByDeletingLastPathComponent];
  339. if(![fm fileExistsAtPath:folder]) {
  340. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:&err];
  341. }
  342. NSMutableData * fileContent = [NSMutableData alloc];
  343. // prevent stack overflow, alloc on heap
  344. char * bytes = (char*) malloc([data count]);
  345. for(int i = 0; i < data.count; i++) {
  346. bytes[i] = [[data objectAtIndex:i] charValue];
  347. }
  348. [fileContent appendBytes:bytes length:data.count];
  349. if(![fm fileExistsAtPath:path]) {
  350. [fm createFileAtPath:path contents:fileContent attributes:NULL];
  351. }
  352. // if file exists, write file
  353. else {
  354. if(append == YES) {
  355. NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
  356. [fileHandle seekToEndOfFile];
  357. [fileHandle writeData:fileContent];
  358. [fileHandle closeFile];
  359. }
  360. else {
  361. [fileContent writeToFile:path atomically:YES];
  362. }
  363. }
  364. free(bytes);
  365. fm = nil;
  366. resolve([NSNumber numberWithInteger: data.count]);
  367. }
  368. @catch (NSException * e)
  369. {
  370. reject(@"RNFetchBlob writeFile Error", @"Error", [e description]);
  371. }
  372. }
  373. # pragma mark - read file
  374. + (void) readFile:(NSString *)path encoding:(NSString *)encoding
  375. resolver:(RCTPromiseResolveBlock)resolve
  376. rejecter:(RCTPromiseRejectBlock)reject
  377. onComplete:(void (^)(NSData * content))onComplete
  378. {
  379. @try
  380. {
  381. [[self class] getPathFromUri:path completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  382. __block NSData * fileContent;
  383. NSError * err;
  384. __block Byte * buffer;
  385. if(asset != nil)
  386. {
  387. buffer = malloc(asset.size);
  388. [asset getBytes:buffer fromOffset:0 length:asset.size error:&err];
  389. if(err != nil)
  390. {
  391. reject(@"RNFetchBlobFS readFile error", @"failed to read asset", [err localizedDescription]);
  392. return;
  393. }
  394. fileContent = [NSData dataWithBytes:buffer length:asset.size];
  395. free(buffer);
  396. }
  397. else
  398. {
  399. if(![[NSFileManager defaultManager] fileExistsAtPath:path]) {
  400. reject(@"RNFetchBlobFS readFile error", @"file not exists", nil);
  401. return;
  402. }
  403. fileContent = [NSData dataWithContentsOfFile:path];
  404. }
  405. if(onComplete != nil)
  406. onComplete(fileContent);
  407. if([[encoding lowercaseString] isEqualToString:@"utf8"]) {
  408. if(resolve != nil) {
  409. NSString * utf8 = [[NSString alloc] initWithData:fileContent encoding:NSUTF8StringEncoding];
  410. if(utf8 == nil)
  411. resolve([[NSString alloc] initWithData:fileContent encoding:NSISOLatin1StringEncoding]);
  412. else
  413. resolve(utf8);
  414. }
  415. }
  416. else if ([[encoding lowercaseString] isEqualToString:@"base64"]) {
  417. if(resolve != nil)
  418. resolve([fileContent base64EncodedStringWithOptions:0]);
  419. }
  420. else if ([[encoding lowercaseString] isEqualToString:@"ascii"]) {
  421. NSMutableArray * resultArray = [NSMutableArray array];
  422. char * bytes = [fileContent bytes];
  423. for(int i=0;i<[fileContent length];i++) {
  424. [resultArray addObject:[NSNumber numberWithChar:bytes[i]]];
  425. }
  426. if(resolve != nil)
  427. resolve(resultArray);
  428. }
  429. }];
  430. }
  431. @catch(NSException * e)
  432. {
  433. if(reject != nil)
  434. reject(@"RNFetchBlobFS readFile error", @"error", [e description]);
  435. }
  436. }
  437. # pragma mark - mkdir
  438. + (BOOL) mkdir:(NSString *) path {
  439. BOOL isDir;
  440. NSError * err = nil;
  441. // if temp folder not exists, create one
  442. if(![[NSFileManager defaultManager] fileExistsAtPath: path isDirectory:&isDir]) {
  443. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&err];
  444. }
  445. return err == nil;
  446. }
  447. # pragma mark - stat
  448. + (NSDictionary *) stat:(NSString *) path error:(NSError **) error {
  449. BOOL isDir = NO;
  450. NSFileManager * fm = [NSFileManager defaultManager];
  451. if([fm fileExistsAtPath:path isDirectory:&isDir] == NO) {
  452. return nil;
  453. }
  454. NSDictionary * info = [fm attributesOfItemAtPath:path error:&error];
  455. NSString * size = [NSString stringWithFormat:@"%d", [info fileSize]];
  456. NSString * filename = [path lastPathComponent];
  457. NSDate * lastModified;
  458. [[NSURL fileURLWithPath:path] getResourceValue:&lastModified forKey:NSURLContentModificationDateKey error:&error];
  459. return @{
  460. @"size" : size,
  461. @"filename" : filename,
  462. @"path" : path,
  463. @"lastModified" : [NSString stringWithFormat:@"%@", [NSNumber numberWithLong:(time_t) [lastModified timeIntervalSince1970]*1000]],
  464. @"type" : isDir ? @"directory" : @"file"
  465. };
  466. }
  467. # pragma mark - exists
  468. + (void) exists:(NSString *) path callback:(RCTResponseSenderBlock)callback
  469. {
  470. [[self class] getPathFromUri:path completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  471. if(path != nil)
  472. {
  473. BOOL isDir = NO;
  474. BOOL exists = NO;
  475. exists = [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory: &isDir];
  476. callback(@[@(exists), @(isDir)]);
  477. }
  478. else if(asset != nil)
  479. {
  480. callback(@[@YES, @NO]);
  481. }
  482. else
  483. {
  484. callback(@[@NO, @NO]);
  485. }
  486. }];
  487. }
  488. # pragma mark - open file stream
  489. // Create file stream for write data
  490. - (NSString *)openWithPath:(NSString *)destPath encode:(nullable NSString *)encode appendData:(BOOL)append {
  491. self.outStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:append];
  492. self.encoding = encode;
  493. [self.outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  494. [self.outStream open];
  495. NSString *uuid = [[NSUUID UUID] UUIDString];
  496. self.streamId = uuid;
  497. [RNFetchBlobFS setFileStream:self withId:uuid];
  498. return uuid;
  499. }
  500. # pragma mark - file stream write chunk
  501. // Write file chunk into an opened stream
  502. - (void)writeEncodeChunk:(NSString *) chunk {
  503. NSMutableData * decodedData = [NSData alloc];
  504. if([[self.encoding lowercaseString] isEqualToString:@"base64"]) {
  505. decodedData = [[NSData alloc] initWithBase64EncodedData:chunk options:0];
  506. }
  507. if([[self.encoding lowercaseString] isEqualToString:@"utf8"]) {
  508. decodedData = [chunk dataUsingEncoding:NSUTF8StringEncoding];
  509. }
  510. else if([[self.encoding lowercaseString] isEqualToString:@"ascii"]) {
  511. decodedData = [chunk dataUsingEncoding:NSASCIIStringEncoding];
  512. }
  513. NSUInteger left = [decodedData length];
  514. NSUInteger nwr = 0;
  515. do {
  516. nwr = [self.outStream write:[decodedData bytes] maxLength:left];
  517. if (-1 == nwr) break;
  518. left -= nwr;
  519. } while (left > 0);
  520. if (left) {
  521. NSLog(@"stream error: %@", [self.outStream streamError]);
  522. }
  523. }
  524. // Write file chunk into an opened stream
  525. - (void)write:(NSData *) chunk {
  526. NSUInteger left = [chunk length];
  527. NSUInteger nwr = 0;
  528. do {
  529. nwr = [self.outStream write:[chunk bytes] maxLength:left];
  530. if (-1 == nwr) break;
  531. left -= nwr;
  532. } while (left > 0);
  533. if (left) {
  534. NSLog(@"stream error: %@", [self.outStream streamError]);
  535. }
  536. }
  537. // close file write stream
  538. - (void)closeOutStream {
  539. if(self.outStream != nil) {
  540. [self.outStream close];
  541. self.outStream = nil;
  542. }
  543. }
  544. // Slice a file into another file, generally for support Blob implementation.
  545. + (void)slice:(NSString *)path
  546. dest:(NSString *)dest
  547. start:(nonnull NSNumber *)start
  548. end:(nonnull NSNumber *)end
  549. encode:(NSString *)encode
  550. resolver:(RCTPromiseResolveBlock)resolve
  551. rejecter:(RCTPromiseRejectBlock)reject
  552. {
  553. [[self class] getPathFromUri:path completionHandler:^(NSString *path, ALAssetRepresentation *asset)
  554. {
  555. if(path != nil)
  556. {
  557. long expected = [end longValue] - [start longValue];
  558. long read = 0;
  559. NSFileHandle * handle = [NSFileHandle fileHandleForReadingAtPath:path];
  560. NSFileManager * fm = [NSFileManager defaultManager];
  561. NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:NO];
  562. [os open];
  563. // abort for the source file not exists
  564. if([fm fileExistsAtPath:path] == NO)
  565. {
  566. reject(@"RNFetchBlob slice failed : the file does not exists", path, nil);
  567. return;
  568. }
  569. long size = [fm attributesOfItemAtPath:path error:nil].fileSize;
  570. long max = MIN(size, [end longValue]);
  571. if(![fm fileExistsAtPath:dest]) {
  572. [fm createFileAtPath:dest contents:@"" attributes:nil];
  573. }
  574. [handle seekToFileOffset:[start longValue]];
  575. while(read < expected)
  576. {
  577. NSData * chunk;
  578. long chunkSize = 0;
  579. if([start longValue] + read + 10240 > max)
  580. {
  581. NSLog(@"read chunk %lu", max - read - [start longValue]);
  582. chunkSize = max - read - [start longValue];
  583. chunk = [handle readDataOfLength:chunkSize];
  584. }
  585. else
  586. {
  587. NSLog(@"read chunk %lu", 10240);
  588. chunkSize = 10240;
  589. chunk = [handle readDataOfLength:10240];
  590. }
  591. if([chunk length] <= 0)
  592. break;
  593. long remain = expected - read;
  594. [os write:[chunk bytes] maxLength:chunkSize];
  595. read += [chunk length];
  596. }
  597. [handle closeFile];
  598. [os close];
  599. resolve(dest);
  600. }
  601. else if (asset != nil)
  602. {
  603. long expected = [end longValue] - [start longValue];
  604. long read = 0;
  605. long chunkRead = 0;
  606. NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:NO];
  607. [os open];
  608. long size = asset.size;
  609. long max = MIN(size, [end longValue]);
  610. while(read < expected)
  611. {
  612. uint8_t * chunk[10240];
  613. long chunkSize = 0;
  614. if([start longValue] + read + 10240 > max)
  615. {
  616. NSLog(@"read chunk %lu", max - read - [start longValue]);
  617. chunkSize = max - read - [start longValue];
  618. chunkRead = [asset getBytes:chunk fromOffset:[start longValue] + read length:chunkSize error:nil];
  619. }
  620. else
  621. {
  622. NSLog(@"read chunk %lu", 10240);
  623. chunkSize = 10240;
  624. chunkRead = [asset getBytes:chunk fromOffset:[start longValue] + read length:chunkSize error:nil];
  625. }
  626. if( chunkRead <= 0)
  627. break;
  628. long remain = expected - read;
  629. [os write:chunk maxLength:chunkSize];
  630. read += chunkRead;
  631. }
  632. [os close];
  633. resolve(dest);
  634. }
  635. else
  636. {
  637. reject(@"slice error", [NSString stringWithFormat: @"could not resolve URI %@", path ], nil);
  638. }
  639. }];
  640. }
  641. // close file read stream
  642. - (void)closeInStream
  643. {
  644. if(self.inStream != nil) {
  645. [self.inStream close];
  646. [self.inStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  647. [[RNFetchBlobFS getFileStreams] setValue:nil forKey:self.streamId];
  648. self.streamId = nil;
  649. }
  650. }
  651. # pragma mark - get absolute path of resource
  652. + (void) getPathFromUri:(NSString *)uri completionHandler:(void(^)(NSString * path, ALAssetRepresentation *asset)) onComplete
  653. {
  654. if([uri hasPrefix:AL_PREFIX])
  655. {
  656. NSURL *asseturl = [NSURL URLWithString:uri];
  657. __block ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
  658. [assetslibrary assetForURL:asseturl
  659. resultBlock:^(ALAsset *asset) {
  660. __block ALAssetRepresentation * present = [asset defaultRepresentation];
  661. onComplete(nil, present);
  662. }
  663. failureBlock:^(NSError *error) {
  664. onComplete(nil, nil);
  665. }];
  666. }
  667. else
  668. {
  669. onComplete([[self class] getPathOfAsset:uri], nil);
  670. }
  671. }
  672. #pragma mark - get disk space
  673. +(void) df:(RCTResponseSenderBlock)callback
  674. {
  675. uint64_t totalSpace = 0;
  676. uint64_t totalFreeSpace = 0;
  677. NSError *error = nil;
  678. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  679. NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
  680. if (dictionary) {
  681. NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
  682. NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
  683. totalSpace = [fileSystemSizeInBytes unsignedLongLongValue];
  684. totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
  685. callback(@[[NSNull null], @{
  686. @"free" : [NSString stringWithFormat:@"%d", totalFreeSpace],
  687. @"total" : [NSString stringWithFormat:@"%d", totalSpace]
  688. }]);
  689. } else {
  690. callback(@[@"failed to get storage usage."]);
  691. }
  692. }
  693. + (void) writeAssetToPath:(ALAssetRepresentation * )rep dest:(NSString *)dest
  694. {
  695. int read = 0;
  696. int cursor = 0;
  697. Byte * buffer = (Byte *)malloc(10240);
  698. NSOutputStream * ostream = [[NSOutputStream alloc] initToFileAtPath:dest append:NO];
  699. [ostream open];
  700. while((read = [rep getBytes:buffer fromOffset:cursor length:10240 error:nil]) > 0)
  701. {
  702. cursor+=10240;
  703. [ostream write:buffer maxLength:read];
  704. }
  705. [ostream close];
  706. free(buffer);
  707. return;
  708. }
  709. @end