Skip to content

Commit 92455e1

Browse files
committed
Merge branch '0.10.5'
2 parents 54ba23a + ecbf535 commit 92455e1

10 files changed

+195
-84
lines changed

android.js

+9-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,15 @@ function actionViewIntent(path:string, mime:string = 'text/plain') {
2424
return Promise.reject('RNFetchBlob.actionViewIntent only supports Android.')
2525
}
2626

27+
function getContentIntent(mime:string) {
28+
if(Platform.OS === 'android')
29+
return RNFetchBlob.getContentIntent(mime)
30+
else
31+
return Promise.reject('RNFetchBlob.getContentIntent only supports Android.')
32+
}
33+
2734

2835
export default {
29-
actionViewIntent
36+
actionViewIntent,
37+
getContentIntent
3038
}

android/src/main/java/com/RNFetchBlob/RNFetchBlob.java

+36
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
package com.RNFetchBlob;
22

3+
import android.app.Activity;
34
import android.content.Intent;
45
import android.net.Uri;
6+
import android.util.Log;
57

68
import com.RNFetchBlob.Utils.RNFBCookieJar;
9+
import com.facebook.react.bridge.ActivityEventListener;
710
import com.facebook.react.bridge.Callback;
811
import com.facebook.react.bridge.LifecycleEventListener;
912
import com.facebook.react.bridge.Promise;
@@ -15,11 +18,16 @@
1518
import com.facebook.react.bridge.WritableArray;
1619
import com.facebook.react.bridge.WritableMap;
1720

21+
import java.util.HashMap;
1822
import java.util.Map;
23+
import java.util.UUID;
1924
import java.util.concurrent.LinkedBlockingQueue;
2025
import java.util.concurrent.ThreadPoolExecutor;
2126
import java.util.concurrent.TimeUnit;
2227

28+
import static android.app.Activity.RESULT_OK;
29+
import static com.RNFetchBlob.RNFetchBlobConst.GET_CONTENT_INTENT;
30+
2331
public class RNFetchBlob extends ReactContextBaseJavaModule {
2432

2533
static ReactApplicationContext RCTContext;
@@ -28,12 +36,28 @@ public class RNFetchBlob extends ReactContextBaseJavaModule {
2836
static LinkedBlockingQueue<Runnable> fsTaskQueue = new LinkedBlockingQueue<>();
2937
static ThreadPoolExecutor fsThreadPool = new ThreadPoolExecutor(2, 10, 5000, TimeUnit.MILLISECONDS, taskQueue);
3038
static public boolean ActionViewVisible = false;
39+
static HashMap<Integer, Promise> promiseTable = new HashMap<>();
3140

3241
public RNFetchBlob(ReactApplicationContext reactContext) {
3342

3443
super(reactContext);
3544

3645
RCTContext = reactContext;
46+
reactContext.addActivityEventListener(new ActivityEventListener() {
47+
@Override
48+
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
49+
if(requestCode == GET_CONTENT_INTENT && resultCode == RESULT_OK) {
50+
Uri d = data.getData();
51+
promiseTable.get(GET_CONTENT_INTENT).resolve(d.toString());
52+
promiseTable.remove(GET_CONTENT_INTENT);
53+
}
54+
}
55+
56+
@Override
57+
public void onNewIntent(Intent intent) {
58+
59+
}
60+
});
3761
}
3862

3963
@Override
@@ -322,4 +346,16 @@ public void fetchBlobForm(ReadableMap options, String taskId, String method, Str
322346
new RNFetchBlobReq(options, taskId, method, url, headers, null, body, callback).run();
323347
}
324348

349+
@ReactMethod
350+
public void getContentIntent(String mime, Promise promise) {
351+
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
352+
if(mime != null)
353+
i.setType(mime);
354+
else
355+
i.setType("*/*");
356+
promiseTable.put(GET_CONTENT_INTENT, promise);
357+
this.getReactApplicationContext().startActivityForResult(i, GET_CONTENT_INTENT, null);
358+
359+
}
360+
325361
}

android/src/main/java/com/RNFetchBlob/RNFetchBlobConst.java

+1
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,6 @@ public class RNFetchBlobConst {
1313
public static final String RNFB_RESPONSE_BASE64 = "base64";
1414
public static final String RNFB_RESPONSE_UTF8 = "utf8";
1515
public static final String RNFB_RESPONSE_PATH = "path";
16+
public static final Integer GET_CONTENT_INTENT = 99900;
1617

1718
}

android/src/main/java/com/RNFetchBlob/RNFetchBlobFS.java

+6-3
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,8 @@ public void readStream(String path, String encoding, int bufferSize, int tick, f
234234

235235
InputStream fs;
236236
if(path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
237-
fs = RNFetchBlob.RCTContext.getAssets().open(path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
237+
fs = RNFetchBlob.RCTContext.getAssets()
238+
.open(path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
238239
}
239240
else {
240241
fs = new FileInputStream(new File(path));
@@ -249,8 +250,9 @@ public void readStream(String path, String encoding, int bufferSize, int tick, f
249250
while ((cursor = fs.read(buffer)) != -1) {
250251
encoder.encode(ByteBuffer.wrap(buffer).asCharBuffer());
251252
String chunk = new String(buffer);
252-
if(cursor != bufferSize)
253+
if(cursor != bufferSize) {
253254
chunk = chunk.substring(0, cursor);
255+
}
254256
emitStreamEvent(streamId, "data", chunk);
255257
if(tick > 0)
256258
SystemClock.sleep(tick);
@@ -292,7 +294,8 @@ public void readStream(String path, String encoding, int bufferSize, int tick, f
292294
buffer = null;
293295

294296
} catch (Exception err) {
295-
emitStreamEvent(streamId, "error", "Failed to convert data to "+encoding+" encoded string, this might due to the source data is not able to convert using this encoding.");
297+
emitStreamEvent(streamId, "warn", "Failed to convert data to "+encoding+" encoded string, this might due to the source data is not able to convert using this encoding.");
298+
err.printStackTrace();
296299
}
297300
}
298301

android/src/main/java/com/RNFetchBlob/RNFetchBlobReq.java

+18-8
Original file line numberDiff line numberDiff line change
@@ -629,17 +629,26 @@ public void onReceive(Context context, Intent intent) {
629629
DownloadManager dm = (DownloadManager) appCtx.getSystemService(Context.DOWNLOAD_SERVICE);
630630
dm.query(query);
631631
Cursor c = dm.query(query);
632-
String error = null;
632+
633+
633634
String filePath = null;
634635
// the file exists in media content database
635636
if (c.moveToFirst()) {
637+
// #297 handle failed request
638+
int statusCode = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
639+
if(statusCode == DownloadManager.STATUS_FAILED) {
640+
this.callback.invoke("Download manager failed to download from " + this.url + ". Statu Code = " + statusCode, null, null);
641+
return;
642+
}
636643
String contentUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
637-
Uri uri = Uri.parse(contentUri);
638-
Cursor cursor = appCtx.getContentResolver().query(uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
639-
// use default destination of DownloadManager
640-
if (cursor != null) {
641-
cursor.moveToFirst();
642-
filePath = cursor.getString(0);
644+
if (contentUri != null) {
645+
Uri uri = Uri.parse(contentUri);
646+
Cursor cursor = appCtx.getContentResolver().query(uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
647+
// use default destination of DownloadManager
648+
if (cursor != null) {
649+
cursor.moveToFirst();
650+
filePath = cursor.getString(0);
651+
}
643652
}
644653
}
645654
// When the file is not found in media content database, check if custom path exists
@@ -653,7 +662,8 @@ public void onReceive(Context context, Intent intent) {
653662
this.callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, customDest);
654663

655664
} catch(Exception ex) {
656-
error = ex.getLocalizedMessage();
665+
ex.printStackTrace();
666+
this.callback.invoke(ex.getLocalizedMessage(), null);
657667
}
658668
}
659669
else {

ios/RNFetchBlob/RNFetchBlob.m

+29-13
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,7 @@ - (NSDictionary *)constantsToExport
314314
#pragma mark - fs.stat
315315
RCT_EXPORT_METHOD(stat:(NSString *)target callback:(RCTResponseSenderBlock) callback)
316316
{
317-
317+
318318
[RNFetchBlobFS getPathFromUri:target completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
319319
__block NSMutableArray * result;
320320
if(path != nil)
@@ -323,14 +323,14 @@ - (NSDictionary *)constantsToExport
323323
BOOL exist = nil;
324324
BOOL isDir = nil;
325325
NSError * error = nil;
326-
326+
327327
exist = [fm fileExistsAtPath:path isDirectory:&isDir];
328328
if(exist == NO) {
329329
callback(@[[NSString stringWithFormat:@"failed to stat path `%@` for it is not exist or it is not exist", path]]);
330330
return ;
331331
}
332332
result = [RNFetchBlobFS stat:path error:&error];
333-
333+
334334
if(error == nil)
335335
callback(@[[NSNull null], result]);
336336
else
@@ -389,7 +389,7 @@ - (NSDictionary *)constantsToExport
389389
#pragma mark - fs.cp
390390
RCT_EXPORT_METHOD(cp:(NSString*)src toPath:(NSString *)dest callback:(RCTResponseSenderBlock) callback)
391391
{
392-
392+
393393
// path = [RNFetchBlobFS getPathOfAsset:path];
394394
[RNFetchBlobFS getPathFromUri:src completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
395395
NSError * error = nil;
@@ -401,14 +401,14 @@ - (NSDictionary *)constantsToExport
401401
else
402402
{
403403
BOOL result = [[NSFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:path] toURL:[NSURL fileURLWithPath:dest] error:&error];
404-
404+
405405
if(error == nil)
406406
callback(@[[NSNull null], @YES]);
407407
else
408408
callback(@[[error localizedDescription], @NO]);
409409
}
410410
}];
411-
411+
412412
}
413413

414414

@@ -470,7 +470,7 @@ - (NSDictionary *)constantsToExport
470470
else
471471
bufferSize = 4096;
472472
}
473-
473+
474474
dispatch_async(fsQueue, ^{
475475
[RNFetchBlobFS readStream:path encoding:encoding bufferSize:bufferSize tick:tick streamId:streamId bridgeRef:_bridge];
476476
});
@@ -496,7 +496,7 @@ - (NSDictionary *)constantsToExport
496496
#pragma mark - net.enableProgressReport
497497
RCT_EXPORT_METHOD(enableProgressReport:(NSString *)taskId interval:(nonnull NSNumber*)interval count:(nonnull NSNumber*)count)
498498
{
499-
499+
500500
RNFetchBlobProgress * cfg = [[RNFetchBlobProgress alloc] initWithType:Download interval:interval count:count];
501501
[RNFetchBlobNetwork enableProgressReport:taskId config:cfg];
502502
}
@@ -523,9 +523,10 @@ - (NSDictionary *)constantsToExport
523523
UIViewController *rootCtrl = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
524524
documentController.delegate = self;
525525
if(scheme == nil || [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:scheme]]) {
526-
dispatch_sync(dispatch_get_main_queue(), ^{
527-
[documentController presentOptionsMenuFromRect:rootCtrl.view.bounds inView:rootCtrl.view animated:YES];
528-
});
526+
CGRect rect = CGRectMake(0.0, 0.0, 0.0, 0.0);
527+
dispatch_sync(dispatch_get_main_queue(), ^{
528+
[documentController presentOptionsMenuFromRect:rect inView:rootCtrl.view animated:YES];
529+
});
529530
resolve(@[[NSNull null]]);
530531
} else {
531532
reject(@"RNFetchBlob could not open document", @"scheme is not supported", nil);
@@ -541,7 +542,7 @@ - (NSDictionary *)constantsToExport
541542
// NSURL * url = [[NSURL alloc] initWithString:uri];
542543
documentController = [UIDocumentInteractionController interactionControllerWithURL:url];
543544
documentController.delegate = self;
544-
545+
545546
if(scheme == nil || [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:scheme]]) {
546547
dispatch_sync(dispatch_get_main_queue(), ^{
547548
[documentController presentPreviewAnimated:YES];
@@ -564,7 +565,7 @@ - (NSDictionary *)constantsToExport
564565
} else {
565566
reject(@"RNFetchBlob could not open document", [error description], nil);
566567
}
567-
568+
568569
}
569570

570571

@@ -580,11 +581,24 @@ - (UIViewController *) documentInteractionControllerViewControllerForPreview: (U
580581
}
581582

582583
# pragma mark - getCookies
584+
583585
RCT_EXPORT_METHOD(getCookies:(NSString *)url resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
584586
{
585587
resolve([RNFetchBlobNetwork getCookies:url]);
586588
}
587589

590+
# pragma mark - removeCookie
591+
592+
RCT_EXPORT_METHOD(removeCookies:(NSString *)domain resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
593+
{
594+
NSError * err = nil;
595+
[RNFetchBlobNetwork removeCookies:domain error:&err];
596+
if(err)
597+
reject(@"RNFetchBlob failed to remove cookie", @"RNFetchBlob failed to remove cookie", nil);
598+
else
599+
resolve(@[[NSNull null]]);
600+
}
601+
588602
# pragma mark - check expired network events
589603

590604
RCT_EXPORT_METHOD(emitExpiredEvent:(RCTResponseSenderBlock)callback)
@@ -593,4 +607,6 @@ - (UIViewController *) documentInteractionControllerViewControllerForPreview: (U
593607
}
594608

595609

610+
611+
596612
@end

ios/RNFetchBlobFS.m

+3-6
Original file line numberDiff line numberDiff line change
@@ -758,20 +758,17 @@ + (void) getPathFromUri:(NSString *)uri completionHandler:(void(^)(NSString * pa
758758

759759
+(void) df:(RCTResponseSenderBlock)callback
760760
{
761-
uint64_t totalSpace = 0;
762-
uint64_t totalFreeSpace = 0;
763761
NSError *error = nil;
764762
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
765763
NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
766764

767765
if (dictionary) {
768766
NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
769767
NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
770-
totalSpace = [fileSystemSizeInBytes unsignedLongLongValue];
771-
totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
768+
772769
callback(@[[NSNull null], @{
773-
@"free" : [NSString stringWithFormat:@"%ld", totalFreeSpace],
774-
@"total" : [NSString stringWithFormat:@"%ld", totalSpace]
770+
@"free" : freeFileSystemSizeInBytes,
771+
@"total" : fileSystemSizeInBytes,
775772
}]);
776773
} else {
777774
callback(@[@"failed to get storage usage."]);

ios/RNFetchBlobNetwork.h

+2-1
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,10 @@ typedef void(^DataTaskCompletionHander) (NSData * _Nullable resp, NSURLResponse
4949
- (nullable id) init;
5050
- (void) sendRequest;
5151
- (void) sendRequest:(NSDictionary * _Nullable )options contentLength:(long)contentLength bridge:(RCTBridge * _Nullable)bridgeRef taskId:(NSString * _Nullable)taskId withRequest:(NSURLRequest * _Nullable)req callback:(_Nullable RCTResponseSenderBlock) callback;
52+
+ (void) removeCookies:(NSString *) domain error:(NSError **)error;
5253
+ (void) enableProgressReport:(NSString *) taskId config:(RNFetchBlobProgress *)config;
5354
+ (void) enableUploadProgress:(NSString *) taskId config:(RNFetchBlobProgress *)config;
54-
+ (NSArray *) getCookies:(NSString *) url;
55+
+ (NSDictionary *) getCookies:(NSString *) url;
5556

5657

5758

0 commit comments

Comments
 (0)