Nav apraksta

RNFetchBlobFS.m 32KB

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