Ingen beskrivning

RNFetchBlobFS.m 32KB

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