Skip to content
This repository was archived by the owner on Mar 16, 2019. It is now read-only.

Commit 4d15c0f

Browse files
committed
Merge branch '0.10.5' into issue-287-wip
2 parents 8121dbf + 221287d commit 4d15c0f

16 files changed

+253
-166
lines changed

README.md

+6-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44

55
A project committed to making file access and data transfer easier, efficient for React Native developers.
6-
76
> For Firebase Storage solution, please upgrade to latest version for best compatibility.
87
98
## Features
@@ -61,6 +60,12 @@ pod 'react-native-fetch-blob',
6160
:path => '../node_modules/react-native-fetch-blob'
6261
```
6362

63+
After `0.10.3` you can install this package directly from Github
64+
65+
```sh
66+
# replace <branch_name> with any one of the branches
67+
npm install --save github:wkh237/react-native-fetch-blob-package#<branch_name>
68+
```
6469
**Automatically Link Native Modules**
6570

6671
For 0.29.2+ projects, simply link native packages via the following command because rnpm has been merged into react-native, you no longer need it.

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

+4-2
Original file line numberDiff line numberDiff line change
@@ -265,8 +265,9 @@ else if(resolved == null) {
265265
while ((cursor = fs.read(buffer)) != -1) {
266266
encoder.encode(ByteBuffer.wrap(buffer).asCharBuffer());
267267
String chunk = new String(buffer);
268-
if(cursor != bufferSize)
268+
if(cursor != bufferSize) {
269269
chunk = chunk.substring(0, cursor);
270+
}
270271
emitStreamEvent(streamId, "data", chunk);
271272
if(tick > 0)
272273
SystemClock.sleep(tick);
@@ -308,7 +309,8 @@ else if(resolved == null) {
308309
buffer = null;
309310

310311
} catch (Exception err) {
311-
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.");
312+
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.");
313+
err.printStackTrace();
312314
}
313315
}
314316

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

+10-30
Original file line numberDiff line numberDiff line change
@@ -220,8 +220,8 @@ else if (value.equalsIgnoreCase("utf8"))
220220
responseFormat = ResponseFormat.UTF8;
221221
}
222222
else {
223-
builder.header(key, value);
224-
mheaders.put(key, value);
223+
builder.header(key.toLowerCase(), value);
224+
mheaders.put(key.toLowerCase(), value);
225225
}
226226
}
227227
}
@@ -304,9 +304,9 @@ else if(cType.isEmpty()) {
304304
clientBuilder.addNetworkInterceptor(new Interceptor() {
305305
@Override
306306
public Response intercept(Chain chain) throws IOException {
307-
redirects.add(chain.request().url().toString());
308-
return chain.proceed(chain.request());
309-
}
307+
redirects.add(chain.request().url().toString());
308+
return chain.proceed(chain.request());
309+
}
310310
});
311311
// Add request interceptor for upload progress event
312312
clientBuilder.addInterceptor(new Interceptor() {
@@ -500,32 +500,11 @@ private void done(Response resp) {
500500
// It uses customized response body which is able to report download progress
501501
// and write response data to destination path.
502502
resp.body().bytes();
503-
504503
} catch (Exception ignored) {
505504
// ignored.printStackTrace();
506505
}
507506
this.destPath = this.destPath.replace("?append=true", "");
508-
509-
try {
510-
long expectedLength = resp.body().contentLength();
511-
// when response contains Content-Length, check if the stream length is correct
512-
if(expectedLength > 0) {
513-
long actualLength = new File(this.destPath).length();
514-
if(actualLength != expectedLength) {
515-
callback.invoke("RNFetchBlob failed to write data to storage : expected " + expectedLength + " bytes but got " + actualLength + " bytes", null);
516-
}
517-
else {
518-
callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, this.destPath);
519-
}
520-
}
521-
else {
522-
callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, this.destPath);
523-
}
524-
}
525-
catch (Exception err) {
526-
callback.invoke(err.getMessage());
527-
err.printStackTrace();
528-
}
507+
callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, this.destPath);
529508
break;
530509
default:
531510
try {
@@ -536,7 +515,7 @@ private void done(Response resp) {
536515
break;
537516
}
538517
// if(!resp.isSuccessful())
539-
resp.body().close();
518+
resp.body().close();
540519
releaseTaskResource();
541520
}
542521

@@ -578,7 +557,7 @@ private WritableMap getResponseInfo(Response resp, boolean isBlobResp) {
578557
}
579558
WritableArray redirectList = Arguments.createArray();
580559
for(String r : redirects) {
581-
redirectList.pushString(r);
560+
redirectList.pushString(r);
582561
}
583562
info.putArray("redirects", redirectList);
584563
info.putMap("headers", headers);
@@ -629,7 +608,8 @@ private String getHeaderIgnoreCases(Headers headers, String field) {
629608
private String getHeaderIgnoreCases(HashMap<String,String> headers, String field) {
630609
String val = headers.get(field);
631610
if(val != null) return val;
632-
return headers.get(field.toLowerCase()) == null ? "" : headers.get(field.toLowerCase());
611+
String lowerCasedValue = headers.get(field.toLowerCase());
612+
return lowerCasedValue == null ? "" : lowerCasedValue;
633613
}
634614

635615
private void emitStateEvent(WritableMap args) {

index.js

+4-3
Original file line numberDiff line numberDiff line change
@@ -220,9 +220,10 @@ function fetch(...args:any):Promise {
220220

221221
// # 241 normalize null or undefined headers, in case nil or null string
222222
// pass to native context
223-
_.each(headers, (h,i) => {
224-
headers[i] = h || ''
225-
});
223+
headers = _.reduce(headers, (result, value, key) => {
224+
result[key] = value || ''
225+
return result
226+
}, {});
226227

227228
// fetch from file system
228229
if(URIUtil.isFileURI(url)) {

ios/RNFetchBlob/RNFetchBlob.m

+55-8
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,25 @@ - (NSDictionary *)constantsToExport
8080
callback:(RCTResponseSenderBlock)callback)
8181
{
8282

83-
[RNFetchBlobReqBuilder buildMultipartRequest:options taskId:taskId method:method url:url headers:headers form:form onComplete:^(__weak NSURLRequest *req, long bodyLength) {
83+
[RNFetchBlobReqBuilder buildMultipartRequest:options
84+
taskId:taskId
85+
method:method
86+
url:url
87+
headers:headers
88+
form:form
89+
onComplete:^(__weak NSURLRequest *req, long bodyLength)
90+
{
91+
// something went wrong when building the request body
92+
if(req == nil)
93+
{
94+
callback(@[@"RNFetchBlob.fetchBlobForm failed to create request body"]);
95+
}
8496
// send HTTP request
85-
RNFetchBlobNetwork * utils = [[RNFetchBlobNetwork alloc] init];
86-
[utils sendRequest:options contentLength:bodyLength bridge:self.bridge taskId:taskId withRequest:req callback:callback];
97+
else
98+
{
99+
RNFetchBlobNetwork * utils = [[RNFetchBlobNetwork alloc] init];
100+
[utils sendRequest:options contentLength:bodyLength bridge:self.bridge taskId:taskId withRequest:req callback:callback];
101+
}
87102
}];
88103

89104
}
@@ -97,10 +112,25 @@ - (NSDictionary *)constantsToExport
97112
headers:(NSDictionary *)headers
98113
body:(NSString *)body callback:(RCTResponseSenderBlock)callback)
99114
{
100-
[RNFetchBlobReqBuilder buildOctetRequest:options taskId:taskId method:method url:url headers:headers body:body onComplete:^(NSURLRequest *req, long bodyLength) {
115+
[RNFetchBlobReqBuilder buildOctetRequest:options
116+
taskId:taskId
117+
method:method
118+
url:url
119+
headers:headers
120+
body:body
121+
onComplete:^(NSURLRequest *req, long bodyLength)
122+
{
123+
// something went wrong when building the request body
124+
if(req == nil)
125+
{
126+
callback(@[@"RNFetchBlob.fetchBlob failed to create request body"]);
127+
}
101128
// send HTTP request
102-
__block RNFetchBlobNetwork * utils = [[RNFetchBlobNetwork alloc] init];
103-
[utils sendRequest:options contentLength:bodyLength bridge:self.bridge taskId:taskId withRequest:req callback:callback];
129+
else
130+
{
131+
__block RNFetchBlobNetwork * utils = [[RNFetchBlobNetwork alloc] init];
132+
[utils sendRequest:options contentLength:bodyLength bridge:self.bridge taskId:taskId withRequest:req callback:callback];
133+
}
104134
}];
105135
}
106136

@@ -394,10 +424,27 @@ - (NSDictionary *)constantsToExport
394424
}
395425

396426
#pragma mark - fs.readFile
397-
RCT_EXPORT_METHOD(readFile:(NSString *)path encoding:(NSString *)encoding resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
427+
RCT_EXPORT_METHOD(readFile:(NSString *)path
428+
encoding:(NSString *)encoding
429+
resolver:(RCTPromiseResolveBlock)resolve
430+
rejecter:(RCTPromiseRejectBlock)reject)
398431
{
399432

400-
[RNFetchBlobFS readFile:path encoding:encoding resolver:resolve rejecter:reject onComplete:nil];
433+
[RNFetchBlobFS readFile:path encoding:encoding onComplete:^(id content, NSString * err) {
434+
if(err != nil)
435+
{
436+
reject(@"RNFetchBlob failed to read file", err, nil);
437+
return;
438+
}
439+
if(encoding == @"ascii")
440+
{
441+
resolve((NSMutableArray *)content);
442+
}
443+
else
444+
{
445+
resolve((NSString *)content);
446+
}
447+
}];
401448
}
402449

403450
#pragma mark - fs.readStream

ios/RNFetchBlobFS.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@
6161
+ (void) exists:(NSString *) path callback:(RCTResponseSenderBlock)callback;
6262
+ (void) writeFileArray:(NSString *)path data:(NSArray *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject;
6363
+ (void) writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject;
64-
+ (void) readFile:(NSString *)path encoding:(NSString *)encoding resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject onComplete:(void (^)(NSData * content))onComplete;
64+
+ (void) readFile:(NSString *)path encoding:(NSString *)encoding onComplete:(void (^)(NSData * content, NSString * errMsg))onComplete;
6565
+ (void) readAssetFile:(NSData *)assetUrl completionBlock:(void(^)(NSData * content))completionBlock failBlock:(void(^)(NSError * err))failBlock;
6666
+ (void) slice:(NSString *)path
6767
dest:(NSString *)dest

0 commit comments

Comments
 (0)