Nav apraksta

RNFetchBlobFS.m 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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 not exists 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 not exists, 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. [fm createFileAtPath:path contents:nil attributes:nil];
  302. }
  303. if(err != nil) {
  304. reject(@"RNFetchBlob writeFile Error", @"could not create file at path", nil);
  305. return;
  306. }
  307. NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
  308. NSData * content = nil;
  309. if([encoding RNFBContainsString:@"base64"]) {
  310. content = [[NSData alloc] initWithBase64EncodedString:data options:0];
  311. }
  312. else if([encoding isEqualToString:@"uri"]) {
  313. NSNumber* size = [[self class] writeFileFromFile:data toFile:path append:append callback:^(NSString *errMsg, NSNumber *size) {
  314. if(errMsg != nil)
  315. reject(@"RNFetchBlob writeFile Error", errMsg, nil);
  316. else
  317. resolve(size);
  318. }];
  319. return;
  320. }
  321. else {
  322. content = [data dataUsingEncoding:NSUTF8StringEncoding];
  323. }
  324. if(append == YES) {
  325. [fileHandle seekToEndOfFile];
  326. [fileHandle writeData:content];
  327. [fileHandle closeFile];
  328. }
  329. else {
  330. [content writeToFile:path atomically:YES];
  331. }
  332. fm = nil;
  333. resolve([NSNumber numberWithInteger:[content length]]);
  334. }
  335. @catch (NSException * e)
  336. {
  337. reject(@"RNFetchBlob writeFile Error", @"Error", [e description]);
  338. }
  339. }
  340. # pragma mark - write file (array)
  341. + (void) writeFileArray:(NSString *)path data:(NSArray *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
  342. @try {
  343. NSFileManager * fm = [NSFileManager defaultManager];
  344. NSError * err = nil;
  345. // check if the folder exists, if not exists, create folders recursively
  346. // after the folders created, write data into the file
  347. NSString * folder = [path stringByDeletingLastPathComponent];
  348. if(![fm fileExistsAtPath:folder]) {
  349. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:&err];
  350. }
  351. NSMutableData * fileContent = [NSMutableData alloc];
  352. // prevent stack overflow, alloc on heap
  353. char * bytes = (char*) malloc([data count]);
  354. for(int i = 0; i < data.count; i++) {
  355. bytes[i] = [[data objectAtIndex:i] charValue];
  356. }
  357. [fileContent appendBytes:bytes length:data.count];
  358. if(![fm fileExistsAtPath:path]) {
  359. [fm createFileAtPath:path contents:fileContent attributes:NULL];
  360. }
  361. // if file exists, write file
  362. else {
  363. if(append == YES) {
  364. NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
  365. [fileHandle seekToEndOfFile];
  366. [fileHandle writeData:fileContent];
  367. [fileHandle closeFile];
  368. }
  369. else {
  370. [fileContent writeToFile:path atomically:YES];
  371. }
  372. }
  373. free(bytes);
  374. fm = nil;
  375. resolve([NSNumber numberWithInteger: data.count]);
  376. }
  377. @catch (NSException * e)
  378. {
  379. reject(@"RNFetchBlob writeFile Error", @"Error", [e description]);
  380. }
  381. }
  382. # pragma mark - read file
  383. + (void) readFile:(NSString *)path
  384. encoding:(NSString *)encoding
  385. onComplete:(void (^)(id content, NSString * errMsg))onComplete
  386. {
  387. [[self class] getPathFromUri:path completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  388. __block NSData * fileContent;
  389. NSError * err;
  390. __block Byte * buffer;
  391. if(asset != nil)
  392. {
  393. buffer = malloc(asset.size);
  394. [asset getBytes:buffer fromOffset:0 length:asset.size error:&err];
  395. if(err != nil)
  396. {
  397. onComplete(nil, [err description]);
  398. free(buffer);
  399. return;
  400. }
  401. fileContent = [NSData dataWithBytes:buffer length:asset.size];
  402. free(buffer);
  403. }
  404. else
  405. {
  406. if(![[NSFileManager defaultManager] fileExistsAtPath:path]) {
  407. onComplete(nil, @"file not exists");
  408. return;
  409. }
  410. fileContent = [NSData dataWithContentsOfFile:path];
  411. }
  412. if(encoding != nil)
  413. {
  414. if([[encoding lowercaseString] isEqualToString:@"utf8"])
  415. {
  416. NSString * utf8 = [[NSString alloc] initWithData:fileContent encoding:NSUTF8StringEncoding];
  417. if(utf8 == nil)
  418. onComplete([[NSString alloc] initWithData:fileContent encoding:NSISOLatin1StringEncoding], nil);
  419. else
  420. onComplete(utf8, nil);
  421. }
  422. else if ([[encoding lowercaseString] isEqualToString:@"base64"]) {
  423. onComplete([fileContent base64EncodedStringWithOptions:0], nil);
  424. }
  425. else if ([[encoding lowercaseString] isEqualToString:@"ascii"]) {
  426. NSMutableArray * resultArray = [NSMutableArray array];
  427. char * bytes = [fileContent bytes];
  428. for(int i=0;i<[fileContent length];i++) {
  429. [resultArray addObject:[NSNumber numberWithChar:bytes[i]]];
  430. }
  431. onComplete(resultArray, nil);
  432. }
  433. }
  434. else
  435. {
  436. onComplete(fileContent, nil);
  437. }
  438. }];
  439. }
  440. # pragma mark - mkdir
  441. + (BOOL) mkdir:(NSString *) path {
  442. BOOL isDir;
  443. NSError * err = nil;
  444. // if temp folder not exists, create one
  445. if(![[NSFileManager defaultManager] fileExistsAtPath: path isDirectory:&isDir]) {
  446. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&err];
  447. }
  448. return err == nil;
  449. }
  450. # pragma mark - stat
  451. + (NSDictionary *) stat:(NSString *) path error:(NSError **) error {
  452. BOOL isDir = NO;
  453. NSFileManager * fm = [NSFileManager defaultManager];
  454. if([fm fileExistsAtPath:path isDirectory:&isDir] == NO) {
  455. return nil;
  456. }
  457. NSDictionary * info = [fm attributesOfItemAtPath:path error:&error];
  458. NSString * size = [NSString stringWithFormat:@"%d", [info fileSize]];
  459. NSString * filename = [path lastPathComponent];
  460. NSDate * lastModified;
  461. [[NSURL fileURLWithPath:path] getResourceValue:&lastModified forKey:NSURLContentModificationDateKey error:&error];
  462. return @{
  463. @"size" : size,
  464. @"filename" : filename,
  465. @"path" : path,
  466. @"lastModified" : [NSNumber numberWithLong:(time_t) [lastModified timeIntervalSince1970]*1000],
  467. @"type" : isDir ? @"directory" : @"file"
  468. };
  469. }
  470. # pragma mark - exists
  471. + (void) exists:(NSString *) path callback:(RCTResponseSenderBlock)callback
  472. {
  473. [[self class] getPathFromUri:path completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  474. if(path != nil)
  475. {
  476. BOOL isDir = NO;
  477. BOOL exists = NO;
  478. exists = [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory: &isDir];
  479. callback(@[@(exists), @(isDir)]);
  480. }
  481. else if(asset != nil)
  482. {
  483. callback(@[@YES, @NO]);
  484. }
  485. else
  486. {
  487. callback(@[@NO, @NO]);
  488. }
  489. }];
  490. }
  491. # pragma mark - open file stream
  492. // Create file stream for write data
  493. - (NSString *)openWithPath:(NSString *)destPath encode:(nullable NSString *)encode appendData:(BOOL)append {
  494. self.outStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:append];
  495. self.encoding = encode;
  496. [self.outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  497. [self.outStream open];
  498. NSString *uuid = [[NSUUID UUID] UUIDString];
  499. self.streamId = uuid;
  500. [RNFetchBlobFS setFileStream:self withId:uuid];
  501. return uuid;
  502. }
  503. # pragma mark - file stream write chunk
  504. // Write file chunk into an opened stream
  505. - (void)writeEncodeChunk:(NSString *) chunk {
  506. NSMutableData * decodedData = [NSData alloc];
  507. if([[self.encoding lowercaseString] isEqualToString:@"base64"]) {
  508. decodedData = [[NSData alloc] initWithBase64EncodedData:chunk options:0];
  509. }
  510. if([[self.encoding lowercaseString] isEqualToString:@"utf8"]) {
  511. decodedData = [chunk dataUsingEncoding:NSUTF8StringEncoding];
  512. }
  513. else if([[self.encoding lowercaseString] isEqualToString:@"ascii"]) {
  514. decodedData = [chunk dataUsingEncoding:NSASCIIStringEncoding];
  515. }
  516. NSUInteger left = [decodedData length];
  517. NSUInteger nwr = 0;
  518. do {
  519. nwr = [self.outStream write:[decodedData bytes] maxLength:left];
  520. if (-1 == nwr) break;
  521. left -= nwr;
  522. } while (left > 0);
  523. if (left) {
  524. NSLog(@"stream error: %@", [self.outStream streamError]);
  525. }
  526. }
  527. // Write file chunk into an opened stream
  528. - (void)write:(NSData *) chunk {
  529. NSUInteger left = [chunk length];
  530. NSUInteger nwr = 0;
  531. do {
  532. nwr = [self.outStream write:[chunk bytes] maxLength:left];
  533. if (-1 == nwr) break;
  534. left -= nwr;
  535. } while (left > 0);
  536. if (left) {
  537. NSLog(@"stream error: %@", [self.outStream streamError]);
  538. }
  539. }
  540. // close file write stream
  541. - (void)closeOutStream {
  542. if(self.outStream != nil) {
  543. [self.outStream close];
  544. self.outStream = nil;
  545. }
  546. }
  547. // Slice a file into another file, generally for support Blob implementation.
  548. + (void)slice:(NSString *)path
  549. dest:(NSString *)dest
  550. start:(nonnull NSNumber *)start
  551. end:(nonnull NSNumber *)end
  552. encode:(NSString *)encode
  553. resolver:(RCTPromiseResolveBlock)resolve
  554. rejecter:(RCTPromiseRejectBlock)reject
  555. {
  556. [[self class] getPathFromUri:path completionHandler:^(NSString *path, ALAssetRepresentation *asset)
  557. {
  558. if(path != nil)
  559. {
  560. long expected = [end longValue] - [start longValue];
  561. long read = 0;
  562. NSFileHandle * handle = [NSFileHandle fileHandleForReadingAtPath:path];
  563. NSFileManager * fm = [NSFileManager defaultManager];
  564. NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:NO];
  565. [os open];
  566. // abort for the source file not exists
  567. if([fm fileExistsAtPath:path] == NO)
  568. {
  569. reject(@"RNFetchBlob slice failed : the file does not exists", path, nil);
  570. return;
  571. }
  572. long size = [fm attributesOfItemAtPath:path error:nil].fileSize;
  573. long max = MIN(size, [end longValue]);
  574. if(![fm fileExistsAtPath:dest]) {
  575. [fm createFileAtPath:dest contents:@"" attributes:nil];
  576. }
  577. [handle seekToFileOffset:[start longValue]];
  578. while(read < expected)
  579. {
  580. NSData * chunk;
  581. long chunkSize = 0;
  582. if([start longValue] + read + 10240 > max)
  583. {
  584. NSLog(@"read chunk %lu", max - read - [start longValue]);
  585. chunkSize = max - read - [start longValue];
  586. chunk = [handle readDataOfLength:chunkSize];
  587. }
  588. else
  589. {
  590. NSLog(@"read chunk %lu", 10240);
  591. chunkSize = 10240;
  592. chunk = [handle readDataOfLength:10240];
  593. }
  594. if([chunk length] <= 0)
  595. break;
  596. long remain = expected - read;
  597. [os write:[chunk bytes] maxLength:chunkSize];
  598. read += [chunk length];
  599. }
  600. [handle closeFile];
  601. [os close];
  602. resolve(dest);
  603. }
  604. else if (asset != nil)
  605. {
  606. long expected = [end longValue] - [start longValue];
  607. long read = 0;
  608. long chunkRead = 0;
  609. NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:NO];
  610. [os open];
  611. long size = asset.size;
  612. long max = MIN(size, [end longValue]);
  613. while(read < expected)
  614. {
  615. uint8_t * chunk[10240];
  616. long chunkSize = 0;
  617. if([start longValue] + read + 10240 > max)
  618. {
  619. NSLog(@"read chunk %lu", max - read - [start longValue]);
  620. chunkSize = max - read - [start longValue];
  621. chunkRead = [asset getBytes:chunk fromOffset:[start longValue] + read length:chunkSize error:nil];
  622. }
  623. else
  624. {
  625. NSLog(@"read chunk %lu", 10240);
  626. chunkSize = 10240;
  627. chunkRead = [asset getBytes:chunk fromOffset:[start longValue] + read length:chunkSize error:nil];
  628. }
  629. if( chunkRead <= 0)
  630. break;
  631. long remain = expected - read;
  632. [os write:chunk maxLength:chunkSize];
  633. read += chunkRead;
  634. }
  635. [os close];
  636. resolve(dest);
  637. }
  638. else
  639. {
  640. reject(@"slice error", [NSString stringWithFormat: @"could not resolve URI %@", path ], nil);
  641. }
  642. }];
  643. }
  644. // close file read stream
  645. - (void)closeInStream
  646. {
  647. if(self.inStream != nil) {
  648. [self.inStream close];
  649. [self.inStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  650. [[RNFetchBlobFS getFileStreams] setValue:nil forKey:self.streamId];
  651. self.streamId = nil;
  652. }
  653. }
  654. # pragma mark - get absolute path of resource
  655. + (void) getPathFromUri:(NSString *)uri completionHandler:(void(^)(NSString * path, ALAssetRepresentation *asset)) onComplete
  656. {
  657. if([uri hasPrefix:AL_PREFIX])
  658. {
  659. NSURL *asseturl = [NSURL URLWithString:uri];
  660. __block ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
  661. [assetslibrary assetForURL:asseturl
  662. resultBlock:^(ALAsset *asset) {
  663. __block ALAssetRepresentation * present = [asset defaultRepresentation];
  664. onComplete(nil, present);
  665. }
  666. failureBlock:^(NSError *error) {
  667. onComplete(nil, nil);
  668. }];
  669. }
  670. else
  671. {
  672. onComplete([[self class] getPathOfAsset:uri], nil);
  673. }
  674. }
  675. #pragma mark - get disk space
  676. +(void) df:(RCTResponseSenderBlock)callback
  677. {
  678. NSError *error = nil;
  679. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  680. NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
  681. if (dictionary) {
  682. NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
  683. NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
  684. callback(@[[NSNull null], @{
  685. @"free" : freeFileSystemSizeInBytes,
  686. @"total" : fileSystemSizeInBytes,
  687. }]);
  688. } else {
  689. callback(@[@"failed to get storage usage."]);
  690. }
  691. }
  692. + (void) writeAssetToPath:(ALAssetRepresentation * )rep dest:(NSString *)dest
  693. {
  694. int read = 0;
  695. int cursor = 0;
  696. Byte * buffer = (Byte *)malloc(10240);
  697. NSOutputStream * ostream = [[NSOutputStream alloc] initToFileAtPath:dest append:NO];
  698. [ostream open];
  699. while((read = [rep getBytes:buffer fromOffset:cursor length:10240 error:nil]) > 0)
  700. {
  701. cursor+=10240;
  702. [ostream write:buffer maxLength:read];
  703. }
  704. [ostream close];
  705. free(buffer);
  706. return;
  707. }
  708. @end