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

Commit dc5c959

Browse files
committed
Fix Android implementation #140
1 parent 3788204 commit dc5c959

File tree

10 files changed

+85
-79
lines changed

10 files changed

+85
-79
lines changed

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

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -372,16 +372,16 @@ public FormField(ReadableMap rawData) {
372372
*/
373373
private void emitUploadProgress(int written) {
374374
RNFetchBlobProgressConfig config = RNFetchBlobReq.getReportUploadProgress(mTaskId);
375-
if(!config.enable)
376-
return;
377-
WritableMap args = Arguments.createMap();
378-
args.putString("taskId", mTaskId);
379-
args.putString("written", String.valueOf(written));
380-
args.putString("total", String.valueOf(contentLength));
381-
382-
// emit event to js context
383-
RNFetchBlob.RCTContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
384-
.emit(RNFetchBlobConst.EVENT_UPLOAD_PROGRESS, args);
375+
if(config.enable && config.shouldReport((float)written/contentLength)) {
376+
WritableMap args = Arguments.createMap();
377+
args.putString("taskId", mTaskId);
378+
args.putString("written", String.valueOf(written));
379+
args.putString("total", String.valueOf(contentLength));
380+
381+
// emit event to js context
382+
RNFetchBlob.RCTContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
383+
.emit(RNFetchBlobConst.EVENT_UPLOAD_PROGRESS, args);
384+
}
385385
}
386386

387387
}

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

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,26 +5,12 @@
55
*/
66
public class RNFetchBlobProgressConfig {
77

8-
public boolean shouldReport() {
9-
boolean checkCount = true;
10-
if(count > 0)
11-
checkCount = Math.floor(progress*100/count)> tick;
12-
return (lastTick - System.currentTimeMillis() > interval) && enable && checkCount;
13-
}
14-
15-
public void tick(float progress) {
16-
this.progress = progress;
17-
this.tick ++;
18-
this.lastTick = System.currentTimeMillis();
19-
}
20-
218
public enum ReportType {
229
Upload,
2310
Download
2411
};
2512

2613
long lastTick = 0;
27-
float progress = 0;
2814
int tick = 0;
2915
int count = -1;
3016
public int interval = -1;
@@ -38,4 +24,16 @@ public enum ReportType {
3824
this.count = count;
3925
}
4026

27+
public boolean shouldReport(float progress) {
28+
boolean checkCount = true;
29+
if(count > 0 && progress > 0)
30+
checkCount = Math.floor(progress*count)> tick;
31+
boolean result = (System.currentTimeMillis() - lastTick> interval) && enable && checkCount;
32+
if(result) {
33+
tick++;
34+
lastTick = System.currentTimeMillis();
35+
}
36+
return result;
37+
}
38+
4139
}

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

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,7 @@ public long read(Buffer sink, long byteCount) throws IOException {
6363
long read = mOriginalSource.read(sink, byteCount);
6464
bytesRead += read > 0 ? read : 0;
6565
RNFetchBlobProgressConfig reportConfig = RNFetchBlobReq.getReportProgress(mTaskId);
66-
if(reportConfig != null && reportConfig.shouldReport()) {
67-
reportConfig.tick(bytesRead/contentLength());
66+
if(reportConfig != null && reportConfig.shouldReport(bytesRead/contentLength())) {
6867
WritableMap args = Arguments.createMap();
6968
args.putString("taskId", mTaskId);
7069
args.putString("written", String.valueOf(bytesRead));

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

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -71,24 +71,27 @@ public BufferedSource source() {
7171
private class ProgressReportingSource implements Source {
7272
@Override
7373
public long read(Buffer sink, long byteCount) throws IOException {
74-
byte [] bytes = new byte[(int) byteCount];
75-
long read = originalBody.byteStream().read(bytes, 0, (int) byteCount);
76-
bytesDownloaded += read > 0 ? read : 0;
77-
Log.i("bytes downloaded", String.valueOf(byteCount) +"/"+ String.valueOf(read) + "=" + String.valueOf(bytesDownloaded));
78-
if(read > 0 ) {
79-
ofStream.write(bytes, 0, (int) read);
74+
try {
75+
byte[] bytes = new byte[(int) byteCount];
76+
long read = originalBody.byteStream().read(bytes, 0, (int) byteCount);
77+
bytesDownloaded += read > 0 ? read : 0;
78+
Log.i("bytes downloaded", String.valueOf(byteCount) + "/" + String.valueOf(read) + "=" + String.valueOf(bytesDownloaded));
79+
if (read > 0) {
80+
ofStream.write(bytes, 0, (int) read);
81+
}
82+
RNFetchBlobProgressConfig reportConfig = RNFetchBlobReq.getReportProgress(mTaskId);
83+
if (reportConfig != null && reportConfig.shouldReport(bytesDownloaded / contentLength())) {
84+
WritableMap args = Arguments.createMap();
85+
args.putString("taskId", mTaskId);
86+
args.putString("written", String.valueOf(bytesDownloaded));
87+
args.putString("total", String.valueOf(contentLength()));
88+
rctContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
89+
.emit(RNFetchBlobConst.EVENT_PROGRESS, args);
90+
}
91+
return read;
92+
} catch(Exception ex) {
93+
return -1;
8094
}
81-
RNFetchBlobProgressConfig reportConfig = RNFetchBlobReq.getReportProgress(mTaskId);
82-
if(reportConfig != null && reportConfig.shouldReport()) {
83-
reportConfig.tick(bytesDownloaded/contentLength());
84-
WritableMap args = Arguments.createMap();
85-
args.putString("taskId", mTaskId);
86-
args.putString("written", String.valueOf(bytesDownloaded));
87-
args.putString("total", String.valueOf(contentLength()));
88-
rctContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
89-
.emit(RNFetchBlobConst.EVENT_PROGRESS, args);
90-
}
91-
return read;
9295
}
9396

9497
@Override

src/ios/RNFetchBlob/RNFetchBlob.m

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -414,13 +414,14 @@ - (NSDictionary *)constantsToExport
414414
}
415415

416416
#pragma mark - net.enableProgressReport
417-
RCT_EXPORT_METHOD(enableProgressReport:(NSString *)taskId interval:(NSNumber*)interval count:(NSNumber*)count {
417+
RCT_EXPORT_METHOD(enableProgressReport:(NSString *)taskId interval:(nonnull NSNumber*)interval count:(nonnull NSNumber*)count {
418+
418419
RNFetchBlobProgress * cfg = [[RNFetchBlobProgress alloc] initWithType:Download interval:interval count:count];
419420
[RNFetchBlobNetwork enableProgressReport:taskId config:cfg];
420421
})
421422

422423
#pragma mark - net.enableUploadProgressReport
423-
RCT_EXPORT_METHOD(enableUploadProgressReport:(NSString *)taskId interval:(NSNumber*)interval count:(NSNumber*)count{
424+
RCT_EXPORT_METHOD(enableUploadProgressReport:(NSString *)taskId interval:(nonnull NSNumber*)interval count:(nonnull NSNumber*)count{
424425
RNFetchBlobProgress * cfg = [[RNFetchBlobProgress alloc] initWithType:Upload interval:interval count:count];
425426
[RNFetchBlobNetwork enableUploadProgress:taskId config:cfg];
426427
})

src/ios/RNFetchBlobNetwork.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,8 @@ typedef void(^DataTaskCompletionHander) (NSData * _Nullable resp, NSURLResponse
3737

3838
+ (NSMutableDictionary * _Nullable ) normalizeHeaders:(NSDictionary * _Nullable)headers;
3939
+ (void) cancelRequest:(NSString *)taskId;
40-
+ (void) enableProgressReport:(NSString *) taskId config:(RNFetchBlobProgress*)config;
41-
+ (void) enableUploadProgress:(NSString *) taskId config:(RNFetchBlobProgress*)config;
40+
+ (void) enableProgressReport:(NSString *) taskId config:(RNFetchBlobProgress *)config;
41+
+ (void) enableUploadProgress:(NSString *) taskId config:(RNFetchBlobProgress *)config;
4242
- (void) sendRequest:(NSDictionary * _Nullable )options contentLength:(long)contentLength bridge:(RCTBridge * _Nullable)bridgeRef taskId:(NSString * _Nullable)taskId withRequest:(NSURLRequest * _Nullable)req callback:(_Nullable RCTResponseSenderBlock) callback;
4343

4444

src/ios/RNFetchBlobNetwork.m

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -85,14 +85,14 @@ - (id)init {
8585
return self;
8686
}
8787

88-
+ (void) enableProgressReport:(NSString *) taskId
88+
+ (void) enableProgressReport:(NSString *) taskId config:(RNFetchBlobProgress *)config
8989
{
90-
[progressTable setValue:@YES forKey:taskId];
90+
[progressTable setValue:config forKey:taskId];
9191
}
9292

93-
+ (void) enableUploadProgress:(NSString *) taskId
93+
+ (void) enableUploadProgress:(NSString *) taskId config:(RNFetchBlobProgress *)config
9494
{
95-
[uploadProgressTable setValue:@YES forKey:taskId];
95+
[uploadProgressTable setValue:config forKey:taskId];
9696
}
9797

9898
// removing case from headers
@@ -221,11 +221,6 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
221221
if ([response respondsToSelector:@selector(allHeaderFields)])
222222
{
223223
NSDictionary *headers = [httpResponse allHeaderFields];
224-
if(expectedBytes < 0)
225-
{
226-
expectedBytes = [[headers valueForKey:@"Content-Length"] intValue];
227-
228-
}
229224
NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type" fromHeaders:headers] lowercaseString];
230225
if(respCType != nil)
231226
{
@@ -329,8 +324,9 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
329324
{
330325
[writeStream write:[data bytes] maxLength:[data length]];
331326
}
332-
333-
if([progressTable valueForKey:taskId] == @YES)
327+
RNFetchBlobProgress * pconfig = [progressTable valueForKey:taskId];
328+
NSNumber * now =[NSNumber numberWithFloat:((float)receivedBytes/(float)expectedBytes)];
329+
if(pconfig != nil && [pconfig shouldReport:now])
334330
{
335331
[self.bridge.eventDispatcher
336332
sendDeviceEventWithName:EVENT_PROGRESS
@@ -433,13 +429,15 @@ - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCom
433429
// upload progress handler
434430
- (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesWritten totalBytesExpectedToSend:(int64_t)totalBytesExpectedToWrite
435431
{
436-
if([uploadProgressTable valueForKey:taskId] == @YES) {
432+
RNFetchBlobProgress * pconfig = [uploadProgressTable valueForKey:taskId];
433+
NSNumber * now = [NSNumber numberWithFloat:((float)totalBytesWritten/(float)totalBytesExpectedToWrite)];
434+
if(pconfig != nil && [pconfig shouldReport:now]) {
437435
[self.bridge.eventDispatcher
438436
sendDeviceEventWithName:EVENT_PROGRESS_UPLOAD
439437
body:@{
440438
@"taskId": taskId,
441439
@"written": [NSString stringWithFormat:@"%d", totalBytesWritten],
442-
@"total": [NSString stringWithFormat:@"%d", bodyLength]
440+
@"total": [NSString stringWithFormat:@"%d", totalBytesExpectedToWrite]
443441
}
444442
];
445443
}

src/ios/RNFetchBlobProgress.h

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@ typedef NS_ENUM(NSUInteger, ProgressType) {
3131
@property (nonatomic) BOOL enable;
3232

3333
-(id)initWithType:(ProgressType)type interval:(NSNumber*)interval count:(NSNumber *)count;
34-
-(BOOL)shouldReport;
35-
-(void)tick;
34+
-(BOOL)shouldReport:(NSNumber *) nextProgress;
3635

3736

3837
@end

src/ios/RNFetchBlobProgress.m

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ @interface RNFetchBlobProgress ()
1212
{
1313
float progress;
1414
int tick;
15-
long lastTick;
15+
double lastTick;
1616
}
1717
@end
1818

@@ -22,33 +22,34 @@ -(id)initWithType:(ProgressType)type interval:(NSNumber *)interval count:(NSNumb
2222
{
2323
self = [super init];
2424
self.count = count;
25-
self.interval = interval;
25+
self.interval = [NSNumber numberWithFloat:[interval floatValue] /1000];
2626
self.type = type;
2727
self.enable = YES;
28+
lastTick = 0;
29+
tick = 1;
2830
return self;
2931
}
3032

31-
-(void)tick:(NSNumber *) nextProgress
32-
{
33-
progress = [nextProgress floatValue];
34-
tick++;
35-
NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
36-
// NSTimeInterval is defined as double
37-
NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp];
38-
lastTick = [timeStampObj longValue];
39-
}
40-
41-
-(BOOL)shouldReport
33+
-(BOOL)shouldReport:(NSNumber *)nextProgress
4234
{
4335
BOOL result = YES;
44-
if(self.count > 0)
36+
float countF = [self.count floatValue];
37+
if(countF > 0 && [nextProgress floatValue] > 0)
4538
{
46-
result = floorf(progress*100/[count floatValue]) > tick;
39+
result = (int)(floorf([nextProgress floatValue]*countF)) >= tick;
4740
}
41+
4842
NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
4943
// NSTimeInterval is defined as double
5044
NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp];
51-
return lastTick - [timeStampObj longValue] > [self.interval longValue] && self.enable && result;
45+
float delta = [timeStampObj doubleValue] - lastTick;
46+
BOOL shouldReport = delta > [self.interval doubleValue] && self.enable && result;
47+
if(shouldReport)
48+
{
49+
tick++;
50+
lastTick = [timeStampObj doubleValue];
51+
}
52+
return shouldReport;
5253

5354
}
5455

src/polyfill/XMLHttpRequest.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ export default class XMLHttpRequest extends XMLHttpRequestEventTarget{
3333
_response : any = '';
3434
_responseText : any = null;
3535
_responseHeaders : any = {};
36-
_responseType : '' | 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' = '';
36+
_responseType : '' | 'arraybuffer' | 'blob' | 'json' | 'text' = '';
3737
// TODO : not suppoted ATM
3838
_responseURL : null = '';
3939
_responseXML : null = '';
@@ -331,6 +331,13 @@ export default class XMLHttpRequest extends XMLHttpRequestEventTarget{
331331
responseDataReady()
332332
})
333333
break;
334+
case 'arraybuffer':
335+
// TODO : to array buffer
336+
break
337+
case 'json':
338+
this._response = resp.json()
339+
this._responseText = resp.text()
340+
break
334341
default :
335342
this._responseText = resp.text()
336343
this._response = this.responseText

0 commit comments

Comments
 (0)