Browse Source

Add fs API URI support #114

Ben Hsieh 8 years ago
parent
commit
e5d7012545

+ 18
- 11
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobFS.java View File

5
 import android.content.CursorLoader;
5
 import android.content.CursorLoader;
6
 import android.content.res.AssetFileDescriptor;
6
 import android.content.res.AssetFileDescriptor;
7
 import android.database.Cursor;
7
 import android.database.Cursor;
8
+import android.graphics.Path;
8
 import android.media.MediaScannerConnection;
9
 import android.media.MediaScannerConnection;
9
 import android.net.Uri;
10
 import android.net.Uri;
10
 import android.os.AsyncTask;
11
 import android.os.AsyncTask;
74
      * @param path Destination file path.
75
      * @param path Destination file path.
75
      * @param encoding Encoding of the string.
76
      * @param encoding Encoding of the string.
76
      * @param data Array passed from JS context.
77
      * @param data Array passed from JS context.
77
-     * @param promise
78
+     * @param promise RCT Promise
78
      */
79
      */
79
     static public void writeFile(String path, String encoding, String data, final boolean append, final Promise promise) {
80
     static public void writeFile(String path, String encoding, String data, final boolean append, final Promise promise) {
80
         try {
81
         try {
86
             FileOutputStream fout = new FileOutputStream(f, append);
87
             FileOutputStream fout = new FileOutputStream(f, append);
87
             // write data from a file
88
             // write data from a file
88
             if(encoding.equalsIgnoreCase(RNFetchBlobConst.DATA_ENCODE_URI)) {
89
             if(encoding.equalsIgnoreCase(RNFetchBlobConst.DATA_ENCODE_URI)) {
90
+                data = normalizePath(data);
89
                 File src = new File(data);
91
                 File src = new File(data);
90
                 if(!src.exists()) {
92
                 if(!src.exists()) {
91
                     promise.reject("RNfetchBlob writeFileError", "source file : " + data + "not exists");
93
                     promise.reject("RNfetchBlob writeFileError", "source file : " + data + "not exists");
118
      * Write array of bytes into file
120
      * Write array of bytes into file
119
      * @param path Destination file path.
121
      * @param path Destination file path.
120
      * @param data Array passed from JS context.
122
      * @param data Array passed from JS context.
121
-     * @param promise
123
+     * @param promise RCT Promise
122
      */
124
      */
123
     static public void writeFile(String path, ReadableArray data, final boolean append, final Promise promise) {
125
     static public void writeFile(String path, ReadableArray data, final boolean append, final Promise promise) {
124
 
126
 
432
      * @param callback  JS context callback
434
      * @param callback  JS context callback
433
      */
435
      */
434
     static void cp(String path, String dest, Callback callback) {
436
     static void cp(String path, String dest, Callback callback) {
437
+
435
         path = normalizePath(path);
438
         path = normalizePath(path);
436
         InputStream in = null;
439
         InputStream in = null;
437
         OutputStream out = null;
440
         OutputStream out = null;
442
                 callback.invoke("cp error: source file at path`" + path + "` not exists");
445
                 callback.invoke("cp error: source file at path`" + path + "` not exists");
443
                 return;
446
                 return;
444
             }
447
             }
445
-
446
             if(!new File(dest).exists())
448
             if(!new File(dest).exists())
447
                 new File(dest).createNewFile();
449
                 new File(dest).createNewFile();
448
 
450
 
456
             }
458
             }
457
 
459
 
458
         } catch (Exception err) {
460
         } catch (Exception err) {
459
-            if(err != null)
460
-                callback.invoke(err.getLocalizedMessage());
461
+            callback.invoke(err.getLocalizedMessage());
461
         } finally {
462
         } finally {
462
             try {
463
             try {
463
-                in.close();
464
-                out.close();
464
+                if (in != null) {
465
+                    in.close();
466
+                }
467
+                if (out != null) {
468
+                    out.close();
469
+                }
465
                 callback.invoke();
470
                 callback.invoke();
466
-            } catch (IOException e) {
471
+            } catch (Exception e) {
467
                 callback.invoke(e.getLocalizedMessage());
472
                 callback.invoke(e.getLocalizedMessage());
468
             }
473
             }
469
         }
474
         }
491
      * @param callback  JS context callback
496
      * @param callback  JS context callback
492
      */
497
      */
493
     static void exists(String path, Callback callback) {
498
     static void exists(String path, Callback callback) {
494
-        path = normalizePath(path);
499
+
495
         if(isAsset(path)) {
500
         if(isAsset(path)) {
496
             try {
501
             try {
497
                 String filename = path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
502
                 String filename = path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
502
             }
507
             }
503
         }
508
         }
504
         else {
509
         else {
510
+            path = normalizePath(path);
505
             boolean exist = new File(path).exists();
511
             boolean exist = new File(path).exists();
506
             boolean isDir = new File(path).isDirectory();
512
             boolean isDir = new File(path).isDirectory();
507
             callback.invoke(exist, isDir);
513
             callback.invoke(exist, isDir);
508
         }
514
         }
509
-
510
     }
515
     }
511
 
516
 
512
     /**
517
     /**
535
      * @param dest  Destination of created file
540
      * @param dest  Destination of created file
536
      * @param start Start byte offset in source file
541
      * @param start Start byte offset in source file
537
      * @param end   End byte offset
542
      * @param end   End byte offset
538
-     * @param encode
543
+     * @param encode NOT IMPLEMENTED
539
      */
544
      */
540
     public static void slice(String src, String dest, int start, int end, String encode, Promise promise) {
545
     public static void slice(String src, String dest, int start, int end, String encode, Promise promise) {
541
         try {
546
         try {
547
+            src = normalizePath(src);
542
             File source = new File(src);
548
             File source = new File(src);
543
             if(!source.exists()) {
549
             if(!source.exists()) {
544
                 promise.reject("RNFetchBlob.slice error", "source file : " + src + " not exists");
550
                 promise.reject("RNFetchBlob.slice error", "source file : " + src + " not exists");
604
      */
610
      */
605
     static void stat(String path, Callback callback) {
611
     static void stat(String path, Callback callback) {
606
         try {
612
         try {
613
+            path = normalizePath(path);
607
             WritableMap result = statFile(path);
614
             WritableMap result = statFile(path);
608
             if(result == null)
615
             if(result == null)
609
                 callback.invoke("stat error: failed to list path `" + path + "` for it is not exist or it is not a folder", null);
616
                 callback.invoke("stat error: failed to list path `" + path + "` for it is not exist or it is not a folder", null);

+ 61
- 28
src/ios/RNFetchBlob/RNFetchBlob.m View File

86
     }];
86
     }];
87
 }
87
 }
88
 
88
 
89
+#pragma mark - fs.createFile
89
 RCT_EXPORT_METHOD(createFile:(NSString *)path data:(NSString *)data encoding:(NSString *)encoding callback:(RCTResponseSenderBlock)callback) {
90
 RCT_EXPORT_METHOD(createFile:(NSString *)path data:(NSString *)data encoding:(NSString *)encoding callback:(RCTResponseSenderBlock)callback) {
90
 
91
 
91
     NSFileManager * fm = [NSFileManager defaultManager];
92
     NSFileManager * fm = [NSFileManager defaultManager];
112
         callback(@[[NSString stringWithFormat:@"failed to create new file at path %@ please ensure the folder exists"]]);
113
         callback(@[[NSString stringWithFormat:@"failed to create new file at path %@ please ensure the folder exists"]]);
113
 
114
 
114
 }
115
 }
115
-
116
+#pragma mark - fs.createFileASCII
116
 // method for create file with ASCII content
117
 // method for create file with ASCII content
117
 RCT_EXPORT_METHOD(createFileASCII:(NSString *)path data:(NSArray *)dataArray callback:(RCTResponseSenderBlock)callback) {
118
 RCT_EXPORT_METHOD(createFileASCII:(NSString *)path data:(NSArray *)dataArray callback:(RCTResponseSenderBlock)callback) {
118
 
119
 
134
 
135
 
135
 }
136
 }
136
 
137
 
137
-
138
+#pragma mark - fs.exists
138
 RCT_EXPORT_METHOD(exists:(NSString *)path callback:(RCTResponseSenderBlock)callback) {
139
 RCT_EXPORT_METHOD(exists:(NSString *)path callback:(RCTResponseSenderBlock)callback) {
139
-    BOOL isDir = NO;
140
-    BOOL exists = NO;
141
-    exists = [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory: &isDir];
142
-    callback(@[@(exists), @(isDir)]);
143
-
140
+    [RNFetchBlobFS exists:path callback:callback];
144
 }
141
 }
145
 
142
 
143
+#pragma mark - fs.writeFile
146
 RCT_EXPORT_METHOD(writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
144
 RCT_EXPORT_METHOD(writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
147
-    
148
     [RNFetchBlobFS writeFile:path encoding:[NSString stringWithString:encoding] data:data append:append resolver:resolve rejecter:reject];
145
     [RNFetchBlobFS writeFile:path encoding:[NSString stringWithString:encoding] data:data append:append resolver:resolve rejecter:reject];
149
 })
146
 })
150
 
147
 
148
+#pragma mark - fs.writeArray
151
 RCT_EXPORT_METHOD(writeFileArray:(NSString *)path data:(NSArray *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
149
 RCT_EXPORT_METHOD(writeFileArray:(NSString *)path data:(NSArray *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
152
     [RNFetchBlobFS writeFileArray:path data:data append:append resolver:resolve rejecter:reject];
150
     [RNFetchBlobFS writeFileArray:path data:data append:append resolver:resolve rejecter:reject];
153
 })
151
 })
154
 
152
 
153
+#pragma mark - fs.writeStream
155
 RCT_EXPORT_METHOD(writeStream:(NSString *)path withEncoding:(NSString *)encoding appendData:(BOOL)append callback:(RCTResponseSenderBlock)callback) {
154
 RCT_EXPORT_METHOD(writeStream:(NSString *)path withEncoding:(NSString *)encoding appendData:(BOOL)append callback:(RCTResponseSenderBlock)callback) {
156
     RNFetchBlobFS * fileStream = [[RNFetchBlobFS alloc] initWithBridgeRef:self.bridge];
155
     RNFetchBlobFS * fileStream = [[RNFetchBlobFS alloc] initWithBridgeRef:self.bridge];
157
     NSFileManager * fm = [NSFileManager defaultManager];
156
     NSFileManager * fm = [NSFileManager defaultManager];
165
     callback(@[[NSNull null], streamId]);
164
     callback(@[[NSNull null], streamId]);
166
 }
165
 }
167
 
166
 
167
+#pragma mark - fs.writeArrayChunk
168
 RCT_EXPORT_METHOD(writeArrayChunk:(NSString *)streamId withArray:(NSArray *)dataArray callback:(RCTResponseSenderBlock) callback) {
168
 RCT_EXPORT_METHOD(writeArrayChunk:(NSString *)streamId withArray:(NSArray *)dataArray callback:(RCTResponseSenderBlock) callback) {
169
     RNFetchBlobFS *fs = [[RNFetchBlobFS getFileStreams] valueForKey:streamId];
169
     RNFetchBlobFS *fs = [[RNFetchBlobFS getFileStreams] valueForKey:streamId];
170
     char * bytes = (char *) malloc([dataArray count]);
170
     char * bytes = (char *) malloc([dataArray count]);
178
     callback(@[[NSNull null]]);
178
     callback(@[[NSNull null]]);
179
 }
179
 }
180
 
180
 
181
+#pragma mark - fs.writeChunk
181
 RCT_EXPORT_METHOD(writeChunk:(NSString *)streamId withData:(NSString *)data callback:(RCTResponseSenderBlock) callback) {
182
 RCT_EXPORT_METHOD(writeChunk:(NSString *)streamId withData:(NSString *)data callback:(RCTResponseSenderBlock) callback) {
182
     RNFetchBlobFS *fs = [[RNFetchBlobFS getFileStreams] valueForKey:streamId];
183
     RNFetchBlobFS *fs = [[RNFetchBlobFS getFileStreams] valueForKey:streamId];
183
     [fs writeEncodeChunk:data];
184
     [fs writeEncodeChunk:data];
184
     callback(@[[NSNull null]]);
185
     callback(@[[NSNull null]]);
185
 }
186
 }
186
 
187
 
188
+#pragma mark - fs.closeStream
187
 RCT_EXPORT_METHOD(closeStream:(NSString *)streamId callback:(RCTResponseSenderBlock) callback) {
189
 RCT_EXPORT_METHOD(closeStream:(NSString *)streamId callback:(RCTResponseSenderBlock) callback) {
188
     RNFetchBlobFS *fs = [[RNFetchBlobFS getFileStreams] valueForKey:streamId];
190
     RNFetchBlobFS *fs = [[RNFetchBlobFS getFileStreams] valueForKey:streamId];
189
     [fs closeOutStream];
191
     [fs closeOutStream];
200
         callback(@[[NSString stringWithFormat:@"failed to unlink file or path at %@", path]]);
202
         callback(@[[NSString stringWithFormat:@"failed to unlink file or path at %@", path]]);
201
 }
203
 }
202
 
204
 
205
+#pragma mark - fs.removeSession
203
 RCT_EXPORT_METHOD(removeSession:(NSArray *)paths callback:(RCTResponseSenderBlock) callback) {
206
 RCT_EXPORT_METHOD(removeSession:(NSArray *)paths callback:(RCTResponseSenderBlock) callback) {
204
     NSError * error = nil;
207
     NSError * error = nil;
205
     NSString * tmpPath = nil;
208
     NSString * tmpPath = nil;
215
 
218
 
216
 }
219
 }
217
 
220
 
221
+#pragma mark - fs.ls
218
 RCT_EXPORT_METHOD(ls:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
222
 RCT_EXPORT_METHOD(ls:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
219
     NSFileManager* fm = [NSFileManager defaultManager];
223
     NSFileManager* fm = [NSFileManager defaultManager];
220
     BOOL exist = nil;
224
     BOOL exist = nil;
234
 
238
 
235
 }
239
 }
236
 
240
 
237
-RCT_EXPORT_METHOD(stat:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
238
-    NSFileManager* fm = [NSFileManager defaultManager];
239
-    BOOL exist = nil;
240
-    BOOL isDir = nil;
241
-    NSError * error = nil;
242
-
243
-    path = [RNFetchBlobFS getPathOfAsset:path];
244
-
245
-    exist = [fm fileExistsAtPath:path isDirectory:&isDir];
246
-    if(exist == NO) {
247
-        callback(@[[NSString stringWithFormat:@"failed to list path `%@` for it is not exist or it is not exist", path]]);
248
-        return ;
249
-    }
250
-    NSData * res = [RNFetchBlobFS stat:path error:&error];
251
-
252
-    if(error == nil)
253
-        callback(@[[NSNull null], res]);
254
-    else
255
-        callback(@[[error localizedDescription], [NSNull null]]);
241
+#pragma mark - fs.stat
242
+RCT_EXPORT_METHOD(stat:(NSString *)target callback:(RCTResponseSenderBlock) callback) {
243
+    
244
+    [RNFetchBlobFS getPathFromUri:target completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
245
+        __block NSMutableArray * result;
246
+        if(path != nil)
247
+        {
248
+            NSFileManager* fm = [NSFileManager defaultManager];
249
+            BOOL exist = nil;
250
+            BOOL isDir = nil;
251
+            NSError * error = nil;
252
+            
253
+            exist = [fm fileExistsAtPath:path isDirectory:&isDir];
254
+            if(exist == NO) {
255
+                callback(@[[NSString stringWithFormat:@"failed to stat path `%@` for it is not exist or it is not exist", path]]);
256
+                return ;
257
+            }
258
+            result = [RNFetchBlobFS stat:path error:&error];
259
+            
260
+            if(error == nil)
261
+                callback(@[[NSNull null], result]);
262
+            else
263
+                callback(@[[error localizedDescription], [NSNull null]]);
256
 
264
 
265
+        }
266
+        else if(asset != nil)
267
+        {
268
+            __block NSNumber * size = [NSNumber numberWithLong:[asset size]];
269
+            result = [asset metadata];
270
+            [result setValue:size forKey:@"size"];
271
+            callback(@[[NSNull null], result]);
272
+        }
273
+        else
274
+        {
275
+            callback(@[@"failed to stat path, could not resolve URI", [NSNull null]]);
276
+        }
277
+    }];
257
 }
278
 }
258
 
279
 
280
+#pragma mark - fs.lstat
259
 RCT_EXPORT_METHOD(lstat:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
281
 RCT_EXPORT_METHOD(lstat:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
260
     NSFileManager* fm = [NSFileManager defaultManager];
282
     NSFileManager* fm = [NSFileManager defaultManager];
261
     BOOL exist = nil;
283
     BOOL exist = nil;
289
 
311
 
290
 }
312
 }
291
 
313
 
314
+#pragma mark - fs.cp
292
 RCT_EXPORT_METHOD(cp:(NSString*)src toPath:(NSString *)dest callback:(RCTResponseSenderBlock) callback) {
315
 RCT_EXPORT_METHOD(cp:(NSString*)src toPath:(NSString *)dest callback:(RCTResponseSenderBlock) callback) {
293
     
316
     
294
 //    path = [RNFetchBlobFS getPathOfAsset:path];
317
 //    path = [RNFetchBlobFS getPathOfAsset:path];
312
     
335
     
313
 }
336
 }
314
 
337
 
338
+
339
+#pragma mark - fs.mv
315
 RCT_EXPORT_METHOD(mv:(NSString *)path toPath:(NSString *)dest callback:(RCTResponseSenderBlock) callback) {
340
 RCT_EXPORT_METHOD(mv:(NSString *)path toPath:(NSString *)dest callback:(RCTResponseSenderBlock) callback) {
316
     NSError * error = nil;
341
     NSError * error = nil;
317
     BOOL result = [[NSFileManager defaultManager] moveItemAtURL:[NSURL fileURLWithPath:path] toURL:[NSURL fileURLWithPath:dest] error:&error];
342
     BOOL result = [[NSFileManager defaultManager] moveItemAtURL:[NSURL fileURLWithPath:path] toURL:[NSURL fileURLWithPath:dest] error:&error];
323
 
348
 
324
 }
349
 }
325
 
350
 
351
+#pragma mark - fs.mkdir
326
 RCT_EXPORT_METHOD(mkdir:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
352
 RCT_EXPORT_METHOD(mkdir:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
327
-    if([RNFetchBlobFS exists:path]) {
353
+    if([[NSFileManager defaultManager] fileExistsAtPath:path]) {
328
         callback(@[@"mkdir failed, folder already exists"]);
354
         callback(@[@"mkdir failed, folder already exists"]);
329
         return;
355
         return;
330
     }
356
     }
333
     callback(@[[NSNull null]]);
359
     callback(@[[NSNull null]]);
334
 }
360
 }
335
 
361
 
362
+#pragma mark - fs.readFile
336
 RCT_EXPORT_METHOD(readFile:(NSString *)path encoding:(NSString *)encoding resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
363
 RCT_EXPORT_METHOD(readFile:(NSString *)path encoding:(NSString *)encoding resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
337
 
364
 
338
     [RNFetchBlobFS readFile:path encoding:encoding resolver:resolve rejecter:reject onComplete:nil];
365
     [RNFetchBlobFS readFile:path encoding:encoding resolver:resolve rejecter:reject onComplete:nil];
339
 })
366
 })
340
 
367
 
368
+#pragma mark - fs.readStream
341
 RCT_EXPORT_METHOD(readStream:(NSString *)path withEncoding:(NSString *)encoding bufferSize:(int)bufferSize) {
369
 RCT_EXPORT_METHOD(readStream:(NSString *)path withEncoding:(NSString *)encoding bufferSize:(int)bufferSize) {
342
 
370
 
343
     RNFetchBlobFS *fileStream = [[RNFetchBlobFS alloc] initWithBridgeRef:self.bridge];
371
     RNFetchBlobFS *fileStream = [[RNFetchBlobFS alloc] initWithBridgeRef:self.bridge];
351
     [fileStream readWithPath:path useEncoding:encoding bufferSize:bufferSize];
379
     [fileStream readWithPath:path useEncoding:encoding bufferSize:bufferSize];
352
 }
380
 }
353
 
381
 
382
+#pragma mark - fs.getEnvionmentDirs
354
 RCT_EXPORT_METHOD(getEnvironmentDirs:(RCTResponseSenderBlock) callback) {
383
 RCT_EXPORT_METHOD(getEnvironmentDirs:(RCTResponseSenderBlock) callback) {
355
 
384
 
356
     callback(@[
385
     callback(@[
359
                ]);
388
                ]);
360
 }
389
 }
361
 
390
 
391
+#pragma mark - net.cancelRequest
362
 RCT_EXPORT_METHOD(cancelRequest:(NSString *)taskId callback:(RCTResponseSenderBlock)callback) {
392
 RCT_EXPORT_METHOD(cancelRequest:(NSString *)taskId callback:(RCTResponseSenderBlock)callback) {
363
     [RNFetchBlobNetwork cancelRequest:taskId];
393
     [RNFetchBlobNetwork cancelRequest:taskId];
364
     callback(@[[NSNull null], taskId]);
394
     callback(@[[NSNull null], taskId]);
365
 
395
 
366
 }
396
 }
367
 
397
 
398
+#pragma mark - net.enableProgressReport
368
 RCT_EXPORT_METHOD(enableProgressReport:(NSString *)taskId {
399
 RCT_EXPORT_METHOD(enableProgressReport:(NSString *)taskId {
369
     [RNFetchBlobNetwork enableProgressReport:taskId];
400
     [RNFetchBlobNetwork enableProgressReport:taskId];
370
 })
401
 })
371
 
402
 
403
+#pragma mark - net.enableUploadProgressReport
372
 RCT_EXPORT_METHOD(enableUploadProgressReport:(NSString *)taskId {
404
 RCT_EXPORT_METHOD(enableUploadProgressReport:(NSString *)taskId {
373
     [RNFetchBlobNetwork enableUploadProgress:taskId];
405
     [RNFetchBlobNetwork enableUploadProgress:taskId];
374
 })
406
 })
375
 
407
 
408
+#pragma mark - fs.slice
376
 RCT_EXPORT_METHOD(slice:(NSString *)src dest:(NSString *)dest start:(nonnull NSNumber *)start end:(nonnull NSNumber *)end resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject
409
 RCT_EXPORT_METHOD(slice:(NSString *)src dest:(NSString *)dest start:(nonnull NSNumber *)start end:(nonnull NSNumber *)end resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject
377
 {
410
 {
378
     [RNFetchBlobFS slice:src dest:dest start:start end:end encode:@"" resolver:resolve rejecter:reject];
411
     [RNFetchBlobFS slice:src dest:dest start:start end:end encode:@"" resolver:resolve rejecter:reject];

+ 1
- 1
src/ios/RNFetchBlobFS.h View File

50
 + (RNFetchBlobFS *) getFileStreams;
50
 + (RNFetchBlobFS *) getFileStreams;
51
 + (BOOL) mkdir:(NSString *) path;
51
 + (BOOL) mkdir:(NSString *) path;
52
 + (NSDictionary *) stat:(NSString *) path error:(NSError **) error;
52
 + (NSDictionary *) stat:(NSString *) path error:(NSError **) error;
53
-+ (BOOL) exists:(NSString *) path;
53
++ (void) exists:(NSString *) path callback:(RCTResponseSenderBlock)callback;
54
 + (void) writeFileArray:(NSString *)path data:(NSArray *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject;
54
 + (void) writeFileArray:(NSString *)path data:(NSArray *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject;
55
 + (void) writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject;
55
 + (void) writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject;
56
 + (void) readFile:(NSString *)path encoding:(NSString *)encoding resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject onComplete:(void (^)(NSData * content))onComplete;
56
 + (void) readFile:(NSString *)path encoding:(NSString *)encoding resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject onComplete:(void (^)(NSData * content))onComplete;

+ 158
- 63
src/ios/RNFetchBlobFS.m View File

191
 
191
 
192
 # pragma write file from file
192
 # pragma write file from file
193
 
193
 
194
-+ (NSNumber *) writeFileFromFile:(NSString *)src toFile:(NSString *)dest append:(BOOL)append
194
++ (NSNumber *) writeFileFromFile:(NSString *)src toFile:(NSString *)dest append:(BOOL)append callback:(void(^)(NSString * errMsg, NSNumber *size))callback
195
 {
195
 {
196
+    [[self class] getPathFromUri:src completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
197
+        if(path != nil)
198
+        {
199
+            __block NSInputStream * is = [[NSInputStream alloc] initWithFileAtPath:path];
200
+            __block NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:append];
201
+            [is open];
202
+            [os open];
203
+            uint8_t buffer[10240];
204
+            __block long written = 0;
205
+            int read = [is read:buffer maxLength:10240];
206
+            written += read;
207
+            while(read > 0) {
208
+                [os write:buffer maxLength:read];
209
+                read = [is read:buffer maxLength:10240];
210
+                written += read;
211
+            }
212
+            [os close];
213
+            [is close];
214
+            __block NSNumber * size = [NSNumber numberWithLong:written];
215
+            callback(nil, size);
216
+        }
217
+        else if(asset != nil)
218
+        {
219
+            
220
+            __block NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:append];
221
+            int read = 0;
222
+            int cursor = 0;
223
+            __block long written = 0;
224
+            uint8_t buffer[10240];
225
+            [os open];
226
+            while((read = [asset getBytes:buffer fromOffset:cursor length:10240 error:nil]) > 0)
227
+            {
228
+                [os write:buffer maxLength:read];
229
+            }
230
+            __block NSNumber * size = [NSNumber numberWithLong:written];
231
+            [os close];
232
+            callback(nil, size);
233
+        }
234
+        else
235
+            callback(@"failed to resolve path", nil);
236
+    }];
196
     
237
     
197
-    NSInputStream * is = [[NSInputStream alloc] initWithFileAtPath:src];
198
-    NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:append];
199
-    [is open];
200
-    [os open];
201
-    uint8_t buffer[10240];
202
-    long written = 0;
203
-    int read = [is read:buffer maxLength:10240];
204
-    written += read;
205
-    while(read > 0) {
206
-        [os write:buffer maxLength:read];
207
-        read = [is read:buffer maxLength:10240];
208
-        written += read;
209
-    }
210
-    [os close];
211
-    [is close];
212
-    return [NSNumber numberWithLong:written];
238
+    return 0;
213
 }
239
 }
214
 
240
 
215
 # pragma mark - write file
241
 # pragma mark - write file
228
             [fm createFileAtPath:path contents:nil attributes:nil];
254
             [fm createFileAtPath:path contents:nil attributes:nil];
229
         }
255
         }
230
         if(err != nil) {
256
         if(err != nil) {
231
-            reject(@"RNFetchBlob writeFile Error", @"could not create file at path", path);
257
+            reject(@"RNFetchBlob writeFile Error", @"could not create file at path", nil);
232
             return;
258
             return;
233
         }
259
         }
234
         NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
260
         NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
237
             content = [[NSData alloc] initWithBase64EncodedString:data options:0];
263
             content = [[NSData alloc] initWithBase64EncodedString:data options:0];
238
         }
264
         }
239
         else if([encoding isEqualToString:@"uri"]) {
265
         else if([encoding isEqualToString:@"uri"]) {
240
-            NSNumber* size = [[self class] writeFileFromFile:data toFile:path append:append];
241
-            resolve(size);
266
+            NSNumber* size = [[self class] writeFileFromFile:data toFile:path append:append callback:^(NSString *errMsg, NSNumber *size) {
267
+                if(errMsg != nil)
268
+                    reject(@"RNFetchBlob writeFile Error", errMsg, nil);
269
+                else
270
+                    resolve(size);
271
+            }];
242
             return;
272
             return;
243
         }
273
         }
244
         else {
274
         else {
390
 # pragma mark - stat
420
 # pragma mark - stat
391
 
421
 
392
 + (NSDictionary *) stat:(NSString *) path error:(NSError **) error {
422
 + (NSDictionary *) stat:(NSString *) path error:(NSError **) error {
423
+
393
     
424
     
394
     BOOL isDir = NO;
425
     BOOL isDir = NO;
395
     NSFileManager * fm = [NSFileManager defaultManager];
426
     NSFileManager * fm = [NSFileManager defaultManager];
413
 
444
 
414
 # pragma mark - exists
445
 # pragma mark - exists
415
 
446
 
416
-+ (BOOL) exists:(NSString *) path {
417
-    return [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:NULL];
447
++ (void) exists:(NSString *) path callback:(RCTResponseSenderBlock)callback
448
+{
449
+    [[self class] getPathFromUri:path completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
450
+        if(path != nil)
451
+        {
452
+            BOOL isDir = NO;
453
+            BOOL exists = NO;
454
+            exists = [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory: &isDir];
455
+            callback(@[@(exists), @(isDir)]);
456
+        }
457
+        else if(asset != nil)
458
+        {
459
+            callback(@[@YES, @NO]);
460
+        }
461
+        else
462
+        {
463
+            callback(@[@NO, @NO]);
464
+        }
465
+    }];
418
 }
466
 }
419
 
467
 
420
 - (id)init {
468
 - (id)init {
535
      resolver:(RCTPromiseResolveBlock)resolve
583
      resolver:(RCTPromiseResolveBlock)resolve
536
      rejecter:(RCTPromiseRejectBlock)reject
584
      rejecter:(RCTPromiseRejectBlock)reject
537
 {
585
 {
538
-    long expected = [end longValue] - [start longValue];
539
-    long read = 0;
540
-    NSFileHandle * handle = [NSFileHandle fileHandleForReadingAtPath:path];
541
-    NSFileManager * fm = [NSFileManager defaultManager];
542
-    NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:NO];
543
-    [os open];
544
-    // abort for the source file not exists
545
-    if([fm fileExistsAtPath:path] == NO)
586
+    [[self class] getPathFromUri:path completionHandler:^(NSString *path, ALAssetRepresentation *asset)
546
     {
587
     {
547
-        reject(@"RNFetchBlob slice failed : the file does not exists", path, nil);
548
-        return;
549
-    }
550
-    long size = [fm attributesOfItemAtPath:path error:nil].fileSize;
551
-    long max = MIN(size, [end longValue]);
552
-    
553
-    if(![fm fileExistsAtPath:dest]) {
554
-        [fm createFileAtPath:dest contents:@"" attributes:nil];
555
-    }
556
-    [handle seekToFileOffset:[start longValue]];
557
-    while(read < expected)
558
-    {
559
-        
560
-        NSData * chunk;
561
-        long chunkSize = 0;
562
-        if([start longValue] + read + 10240 > max)
588
+        if(path != nil)
589
+        {
590
+            long expected = [end longValue] - [start longValue];
591
+            long read = 0;
592
+            NSFileHandle * handle = [NSFileHandle fileHandleForReadingAtPath:path];
593
+            NSFileManager * fm = [NSFileManager defaultManager];
594
+            NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:NO];
595
+            [os open];
596
+            // abort for the source file not exists
597
+            if([fm fileExistsAtPath:path] == NO)
598
+            {
599
+                reject(@"RNFetchBlob slice failed : the file does not exists", path, nil);
600
+                return;
601
+            }
602
+            long size = [fm attributesOfItemAtPath:path error:nil].fileSize;
603
+            long max = MIN(size, [end longValue]);
604
+            
605
+            if(![fm fileExistsAtPath:dest]) {
606
+                [fm createFileAtPath:dest contents:@"" attributes:nil];
607
+            }
608
+            [handle seekToFileOffset:[start longValue]];
609
+            while(read < expected)
610
+            {
611
+                
612
+                NSData * chunk;
613
+                long chunkSize = 0;
614
+                if([start longValue] + read + 10240 > max)
615
+                {
616
+                    NSLog(@"read chunk %lu", max - read - [start longValue]);
617
+                    chunkSize = max - read - [start longValue];
618
+                    chunk = [handle readDataOfLength:chunkSize];
619
+                }
620
+                else
621
+                {
622
+                    NSLog(@"read chunk %lu", 10240);
623
+                    chunkSize = 10240;
624
+                    chunk = [handle readDataOfLength:10240];
625
+                }
626
+                if([chunk length] <= 0)
627
+                    break;
628
+                long remain = expected - read;
629
+                
630
+                [os write:[chunk bytes] maxLength:chunkSize];
631
+                read += [chunk length];
632
+            }
633
+            [handle closeFile];
634
+            [os close];
635
+            resolve(dest);
636
+        }
637
+        else if (asset != nil)
563
         {
638
         {
564
-            NSLog(@"read chunk %lu", max - read - [start longValue]);
565
-            chunkSize = max - read - [start longValue];
566
-            chunk = [handle readDataOfLength:chunkSize];
639
+            long expected = [end longValue] - [start longValue];
640
+            long read = 0;
641
+            long chunkRead = 0;
642
+            NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:NO];
643
+            [os open];
644
+            long size = asset.size;
645
+            long max = MIN(size, [end longValue]);
646
+            
647
+            while(read < expected)
648
+            {
649
+                
650
+                uint8_t * chunk[10240];
651
+                long chunkSize = 0;
652
+                if([start longValue] + read + 10240 > max)
653
+                {
654
+                    NSLog(@"read chunk %lu", max - read - [start longValue]);
655
+                    chunkSize = max - read - [start longValue];
656
+                    chunkRead = [asset getBytes:chunk fromOffset:[start longValue] + read length:chunkSize error:nil];
657
+                }
658
+                else
659
+                {
660
+                    NSLog(@"read chunk %lu", 10240);
661
+                    chunkSize = 10240;
662
+                    chunkRead = [asset getBytes:chunk fromOffset:[start longValue] + read length:chunkSize error:nil];
663
+                }
664
+                if( chunkRead <= 0)
665
+                    break;
666
+                long remain = expected - read;
667
+                
668
+                [os write:chunk maxLength:chunkSize];
669
+                read += chunkRead;
670
+            }
671
+            [os close];
672
+            resolve(dest);
567
         }
673
         }
568
         else
674
         else
569
         {
675
         {
570
-            NSLog(@"read chunk %lu", 10240);
571
-            chunkSize = 10240;
572
-            chunk = [handle readDataOfLength:10240];
676
+            reject(@"slice error",  [NSString stringWithFormat: @"could not resolve URI %@", path ], nil);
573
         }
677
         }
574
-        if([chunk length] <= 0)
575
-            break;
576
-        long remain = expected - read;
577
-    
578
-        [os write:[chunk bytes] maxLength:chunkSize];
579
-        read += [chunk length];
580
-    }
581
-    [handle closeFile];
582
-    [os close];
583
-    resolve(dest);
584
-    
678
+        
679
+    }];
585
 }
680
 }
586
 
681
 
587
 // close file read stream
682
 // close file read stream