暫無描述

RNFetchBlobFS.m 27KB

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