Explorar el Código

Fix Android implementation #140

Ben Hsieh hace 7 años
padre
commit
dc5c959138

+ 10
- 10
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobBody.java Ver fichero

@@ -372,16 +372,16 @@ public class RNFetchBlobBody extends RequestBody{
372 372
      */
373 373
     private void emitUploadProgress(int written) {
374 374
         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
+        }
385 385
     }
386 386
 
387 387
 }

+ 12
- 14
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobProgressConfig.java Ver fichero

@@ -5,26 +5,12 @@ package com.RNFetchBlob;
5 5
  */
6 6
 public class RNFetchBlobProgressConfig {
7 7
 
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
-
21 8
     public enum ReportType {
22 9
         Upload,
23 10
         Download
24 11
     };
25 12
 
26 13
     long lastTick = 0;
27
-    float progress = 0;
28 14
     int tick = 0;
29 15
     int count = -1;
30 16
     public int interval = -1;
@@ -38,4 +24,16 @@ public class RNFetchBlobProgressConfig {
38 24
         this.count = count;
39 25
     }
40 26
 
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
+
41 39
 }

+ 1
- 2
src/android/src/main/java/com/RNFetchBlob/Response/RNFetchBlobDefaultResp.java Ver fichero

@@ -63,8 +63,7 @@ public class RNFetchBlobDefaultResp extends ResponseBody {
63 63
             long read =  mOriginalSource.read(sink, byteCount);
64 64
             bytesRead += read > 0 ? read : 0;
65 65
             RNFetchBlobProgressConfig reportConfig = RNFetchBlobReq.getReportProgress(mTaskId);
66
-            if(reportConfig != null && reportConfig.shouldReport()) {
67
-                reportConfig.tick(bytesRead/contentLength());
66
+            if(reportConfig != null && reportConfig.shouldReport(bytesRead/contentLength())) {
68 67
                 WritableMap args = Arguments.createMap();
69 68
                 args.putString("taskId", mTaskId);
70 69
                 args.putString("written", String.valueOf(bytesRead));

+ 20
- 17
src/android/src/main/java/com/RNFetchBlob/Response/RNFetchBlobFileResp.java Ver fichero

@@ -71,24 +71,27 @@ public class RNFetchBlobFileResp extends ResponseBody {
71 71
     private class ProgressReportingSource implements Source {
72 72
         @Override
73 73
         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;
80 94
             }
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;
92 95
         }
93 96
 
94 97
         @Override

+ 3
- 2
src/ios/RNFetchBlob/RNFetchBlob.m Ver fichero

@@ -414,13 +414,14 @@ RCT_EXPORT_METHOD(cancelRequest:(NSString *)taskId callback:(RCTResponseSenderBl
414 414
 }
415 415
 
416 416
 #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
+    
418 419
     RNFetchBlobProgress * cfg = [[RNFetchBlobProgress alloc] initWithType:Download interval:interval count:count];
419 420
     [RNFetchBlobNetwork enableProgressReport:taskId config:cfg];
420 421
 })
421 422
 
422 423
 #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{
424 425
     RNFetchBlobProgress * cfg = [[RNFetchBlobProgress alloc] initWithType:Upload interval:interval count:count];
425 426
     [RNFetchBlobNetwork enableUploadProgress:taskId config:cfg];
426 427
 })

+ 2
- 2
src/ios/RNFetchBlobNetwork.h Ver fichero

@@ -37,8 +37,8 @@ typedef void(^DataTaskCompletionHander) (NSData * _Nullable resp, NSURLResponse
37 37
 
38 38
 + (NSMutableDictionary  * _Nullable ) normalizeHeaders:(NSDictionary * _Nullable)headers;
39 39
 + (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;
42 42
 - (void) sendRequest:(NSDictionary  * _Nullable )options contentLength:(long)contentLength bridge:(RCTBridge * _Nullable)bridgeRef taskId:(NSString * _Nullable)taskId withRequest:(NSURLRequest * _Nullable)req callback:(_Nullable RCTResponseSenderBlock) callback;
43 43
 
44 44
 

+ 11
- 13
src/ios/RNFetchBlobNetwork.m Ver fichero

@@ -85,14 +85,14 @@ NSOperationQueue *taskQueue;
85 85
     return self;
86 86
 }
87 87
 
88
-+ (void) enableProgressReport:(NSString *) taskId
88
++ (void) enableProgressReport:(NSString *) taskId config:(RNFetchBlobProgress *)config
89 89
 {
90
-    [progressTable setValue:@YES forKey:taskId];
90
+    [progressTable setValue:config forKey:taskId];
91 91
 }
92 92
 
93
-+ (void) enableUploadProgress:(NSString *) taskId
93
++ (void) enableUploadProgress:(NSString *) taskId config:(RNFetchBlobProgress *)config
94 94
 {
95
-    [uploadProgressTable setValue:@YES forKey:taskId];
95
+    [uploadProgressTable setValue:config forKey:taskId];
96 96
 }
97 97
 
98 98
 // removing case from headers
@@ -221,11 +221,6 @@ NSOperationQueue *taskQueue;
221 221
     if ([response respondsToSelector:@selector(allHeaderFields)])
222 222
     {
223 223
         NSDictionary *headers = [httpResponse allHeaderFields];
224
-        if(expectedBytes < 0)
225
-        {
226
-            expectedBytes = [[headers valueForKey:@"Content-Length"] intValue];
227
-            
228
-        }
229 224
         NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type" fromHeaders:headers] lowercaseString];
230 225
         if(respCType != nil)
231 226
         {
@@ -329,8 +324,9 @@ NSOperationQueue *taskQueue;
329 324
     {
330 325
         [writeStream write:[data bytes] maxLength:[data length]];
331 326
     }
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])
334 330
     {
335 331
         [self.bridge.eventDispatcher
336 332
          sendDeviceEventWithName:EVENT_PROGRESS
@@ -433,13 +429,15 @@ NSOperationQueue *taskQueue;
433 429
 // upload progress handler
434 430
 - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesWritten totalBytesExpectedToSend:(int64_t)totalBytesExpectedToWrite
435 431
 {
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]) {
437 435
         [self.bridge.eventDispatcher
438 436
          sendDeviceEventWithName:EVENT_PROGRESS_UPLOAD
439 437
          body:@{
440 438
                 @"taskId": taskId,
441 439
                 @"written": [NSString stringWithFormat:@"%d", totalBytesWritten],
442
-                @"total": [NSString stringWithFormat:@"%d", bodyLength]
440
+                @"total": [NSString stringWithFormat:@"%d", totalBytesExpectedToWrite]
443 441
                 }
444 442
          ];
445 443
     }

+ 1
- 2
src/ios/RNFetchBlobProgress.h Ver fichero

@@ -31,8 +31,7 @@ typedef NS_ENUM(NSUInteger, ProgressType) {
31 31
 @property (nonatomic) BOOL enable;
32 32
 
33 33
 -(id)initWithType:(ProgressType)type interval:(NSNumber*)interval count:(NSNumber *)count;
34
--(BOOL)shouldReport;
35
--(void)tick;
34
+-(BOOL)shouldReport:(NSNumber *) nextProgress;
36 35
 
37 36
 
38 37
 @end

+ 17
- 16
src/ios/RNFetchBlobProgress.m Ver fichero

@@ -12,7 +12,7 @@
12 12
 {
13 13
     float progress;
14 14
     int tick;
15
-    long lastTick;
15
+    double lastTick;
16 16
 }
17 17
 @end
18 18
 
@@ -22,33 +22,34 @@
22 22
 {
23 23
     self = [super init];
24 24
     self.count = count;
25
-    self.interval = interval;
25
+    self.interval = [NSNumber numberWithFloat:[interval floatValue] /1000];
26 26
     self.type = type;
27 27
     self.enable = YES;
28
+    lastTick = 0;
29
+    tick = 1;
28 30
     return self;
29 31
 }
30 32
 
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
42 34
 {
43 35
     BOOL result = YES;
44
-    if(self.count > 0)
36
+    float countF = [self.count floatValue];
37
+    if(countF > 0 && [nextProgress floatValue] > 0)
45 38
     {
46
-        result = floorf(progress*100/[count floatValue]) > tick;
39
+        result = (int)(floorf([nextProgress floatValue]*countF)) >= tick;
47 40
     }
41
+    
48 42
     NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
49 43
     // NSTimeInterval is defined as double
50 44
     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;
52 53
     
53 54
 }
54 55
 

+ 8
- 1
src/polyfill/XMLHttpRequest.js Ver fichero

@@ -33,7 +33,7 @@ export default class XMLHttpRequest extends XMLHttpRequestEventTarget{
33 33
   _response : any = '';
34 34
   _responseText : any = null;
35 35
   _responseHeaders : any = {};
36
-  _responseType : '' | 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' = '';
36
+  _responseType : '' | 'arraybuffer' | 'blob'  | 'json' | 'text' = '';
37 37
   // TODO : not suppoted ATM
38 38
   _responseURL : null = '';
39 39
   _responseXML : null = '';
@@ -331,6 +331,13 @@ export default class XMLHttpRequest extends XMLHttpRequestEventTarget{
331 331
             responseDataReady()
332 332
           })
333 333
         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
334 341
         default :
335 342
           this._responseText = resp.text()
336 343
           this._response = this.responseText