Ben Hsieh 8 lat temu
rodzic
commit
3373932cd5

+ 0
- 2
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobReq.java Wyświetl plik

@@ -27,9 +27,7 @@ import java.io.InputStream;
27 27
 import java.net.MalformedURLException;
28 28
 import java.net.SocketTimeoutException;
29 29
 import java.net.URL;
30
-import java.net.URLEncoder;
31 30
 import java.nio.ByteBuffer;
32
-import java.nio.CharBuffer;
33 31
 import java.nio.charset.CharacterCodingException;
34 32
 import java.nio.charset.Charset;
35 33
 import java.nio.charset.CharsetEncoder;

+ 3
- 0
src/ios/RNFetchBlobConst.h Wyświetl plik

@@ -16,6 +16,9 @@ extern NSString *const MSG_EVENT;
16 16
 extern NSString *const MSG_EVENT_LOG;
17 17
 extern NSString *const MSG_EVENT_WARN;
18 18
 extern NSString *const MSG_EVENT_ERROR;
19
+
20
+extern NSString *const EVENT_PROGRESS;
21
+extern NSString *const EVENT_PROGRESS_UPLOAD;
19 22
 extern NSString *const EVENT_STATE_CHANGE;
20 23
 
21 24
 extern NSString *const FILE_PREFIX;

+ 3
- 0
src/ios/RNFetchBlobConst.m Wyświetl plik

@@ -23,6 +23,9 @@ extern NSString *const CONFIG_KEY = @"key";
23 23
 extern NSString *const CONFIG_EXTRA_BLOB_CTYPE = @"binaryContentTypes";
24 24
 
25 25
 extern NSString *const EVENT_STATE_CHANGE = @"RNFetchBlobState";
26
+extern NSString *const EVENT_PROGRESS = @"RNFetchBlobProgress";
27
+extern NSString *const EVENT_PROGRESS_UPLOAD = @"RNFetchBlobProgress-upload";
28
+
26 29
 extern NSString *const MSG_EVENT = @"RNFetchBlobMessage";
27 30
 extern NSString *const MSG_EVENT_LOG = @"log";
28 31
 extern NSString *const MSG_EVENT_WARN = @"warn";

+ 24
- 8
src/ios/RNFetchBlobFS.m Wyświetl plik

@@ -63,6 +63,8 @@ NSMutableDictionary *fileStreams = nil;
63 63
     return assetURI;
64 64
 }
65 65
 
66
+#pragma mark - system directories
67
+
66 68
 + (NSString *) getCacheDir {
67 69
     return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
68 70
 }
@@ -98,6 +100,8 @@ NSMutableDictionary *fileStreams = nil;
98 100
     return tempPath;
99 101
 }
100 102
 
103
+#pragma mark - read asset stream
104
+
101 105
 - (void) startAssetReadStream:(NSString *)assetUrl
102 106
 {
103 107
     ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
@@ -185,6 +189,8 @@ NSMutableDictionary *fileStreams = nil;
185 189
     }
186 190
 }
187 191
 
192
+# pragma write file from file
193
+
188 194
 + (NSNumber *) writeFileFromFile:(NSString *)src toFile:(NSString *)dest append:(BOOL)append
189 195
 {
190 196
     NSInputStream * is = [[NSInputStream alloc] initWithFileAtPath:src];
@@ -205,6 +211,8 @@ NSMutableDictionary *fileStreams = nil;
205 211
     return [NSNumber numberWithLong:written];
206 212
 }
207 213
 
214
+# pragma mark - write file
215
+
208 216
 + (void) writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject
209 217
 {
210 218
     @try {
@@ -226,14 +234,6 @@ NSMutableDictionary *fileStreams = nil;
226 234
         NSData * content = nil;
227 235
         if([encoding containsString:@"base64"]) {
228 236
             content = [[NSData alloc] initWithBase64EncodedString:data options:0];
229
-            if([encoding containsString:@"urlencode"])
230
-            {
231
-                NSString * decode = [[[NSString alloc] initWithData:content encoding:NSUTF8StringEncoding] stringByRemovingPercentEncoding];
232
-                if(decode != nil)
233
-                {
234
-                    content = [decode dataUsingEncoding:NSUTF8StringEncoding];
235
-                }
236
-            }
237 237
         }
238 238
         else if([encoding isEqualToString:@"uri"]) {
239 239
             NSNumber* size = [[self class] writeFileFromFile:data toFile:path append:append];
@@ -261,6 +261,8 @@ NSMutableDictionary *fileStreams = nil;
261 261
     }
262 262
 }
263 263
 
264
+# pragma mark - write file (array)
265
+
264 266
 + (void) writeFileArray:(NSString *)path data:(NSArray *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
265 267
     @try {
266 268
         NSFileManager * fm = [NSFileManager defaultManager];
@@ -303,6 +305,8 @@ NSMutableDictionary *fileStreams = nil;
303 305
     }
304 306
 }
305 307
 
308
+# pragma mark - read file
309
+
306 310
 + (void) readFile:(NSString *)path encoding:(NSString *)encoding
307 311
          resolver:(RCTPromiseResolveBlock)resolve
308 312
          rejecter:(RCTPromiseRejectBlock)reject
@@ -370,6 +374,8 @@ NSMutableDictionary *fileStreams = nil;
370 374
     }
371 375
 }
372 376
 
377
+# pragma mark - mkdir
378
+
373 379
 + (BOOL) mkdir:(NSString *) path {
374 380
     BOOL isDir;
375 381
     NSError * err = nil;
@@ -380,6 +386,8 @@ NSMutableDictionary *fileStreams = nil;
380 386
     return err == nil;
381 387
 }
382 388
 
389
+# pragma mark - stat
390
+
383 391
 + (NSDictionary *) stat:(NSString *) path error:(NSError **) error {
384 392
     NSMutableDictionary *stat = [[NSMutableDictionary alloc] init];
385 393
     BOOL isDir = NO;
@@ -401,6 +409,8 @@ NSMutableDictionary *fileStreams = nil;
401 409
              };
402 410
 }
403 411
 
412
+# pragma mark - exists
413
+
404 414
 + (BOOL) exists:(NSString *) path {
405 415
     return [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:NULL];
406 416
 }
@@ -422,6 +432,8 @@ NSMutableDictionary *fileStreams = nil;
422 432
     return self;
423 433
 }
424 434
 
435
+# pragma mark - open file stream
436
+
425 437
 // Create file stream for write data
426 438
 - (NSString *)openWithPath:(NSString *)destPath encode:(nullable NSString *)encode appendData:(BOOL)append {
427 439
     self.outStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:append];
@@ -434,6 +446,8 @@ NSMutableDictionary *fileStreams = nil;
434 446
     return uuid;
435 447
 }
436 448
 
449
+# pragma mark - file stream write chunk
450
+
437 451
 // Write file chunk into an opened stream
438 452
 - (void)writeEncodeChunk:(NSString *) chunk {
439 453
     NSMutableData * decodedData = [NSData alloc];
@@ -679,6 +693,8 @@ NSMutableDictionary *fileStreams = nil;
679 693
     
680 694
 }
681 695
 
696
+# pragma mark - get absolute path of resource
697
+
682 698
 + (void) getPathFromUri:(NSString *)uri completionHandler:(void(^)(NSString * path, ALAssetRepresentation *asset)) onComplete
683 699
 {
684 700
     if([uri hasPrefix:AL_PREFIX])

+ 6
- 9
src/ios/RNFetchBlobNetwork.m Wyświetl plik

@@ -134,9 +134,8 @@ NSOperationQueue *taskQueue;
134 134
     bodyLength = contentLength;
135 135
 
136 136
     // the session trust any SSL certification
137
-
138
-    
139 137
     NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
138
+    // set request timeout
140 139
     float timeout = [options valueForKey:@"timeout"] == nil ? -1 : [[options valueForKey:@"timeout"] floatValue];
141 140
     if(timeout > 0)
142 141
     {
@@ -202,9 +201,7 @@ NSOperationQueue *taskQueue;
202 201
     if ([response respondsToSelector:@selector(allHeaderFields)])
203 202
     {
204 203
         NSDictionary *headers = [httpResponse allHeaderFields];
205
-        NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type"
206
-                                                               fromHeaders:headers]
207
-                               lowercaseString];
204
+        NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type" fromHeaders:headers] lowercaseString];
208 205
         if(respCType != nil)
209 206
         {
210 207
             NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
@@ -299,12 +296,12 @@ NSOperationQueue *taskQueue;
299 296
     if([progressTable valueForKey:taskId] == @YES)
300 297
     {
301 298
         [self.bridge.eventDispatcher
302
-         sendDeviceEventWithName:@"RNFetchBlobProgress"
299
+         sendDeviceEventWithName:EVENT_PROGRESS 
303 300
          body:@{
304 301
                 @"taskId": taskId,
305 302
                 @"written": [NSString stringWithFormat:@"%d", receivedBytes],
306 303
                 @"total": [NSString stringWithFormat:@"%d", expectedBytes]
307
-                }
304
+            }
308 305
          ];
309 306
     }
310 307
     received = nil;
@@ -376,7 +373,7 @@ NSOperationQueue *taskQueue;
376 373
     @synchronized(taskTable, uploadProgressTable, progressTable)
377 374
     {
378 375
         if([taskTable objectForKey:taskId] == nil)
379
-            NSLog(@"object released.");
376
+            NSLog(@"object released by ARC.");
380 377
         else
381 378
             [taskTable removeObjectForKey:taskId];
382 379
         [uploadProgressTable removeObjectForKey:taskId];
@@ -394,7 +391,7 @@ NSOperationQueue *taskQueue;
394 391
 {
395 392
     if([uploadProgressTable valueForKey:taskId] == @YES) {
396 393
         [self.bridge.eventDispatcher
397
-         sendDeviceEventWithName:@"RNFetchBlobProgress-upload"
394
+         sendDeviceEventWithName:EVENT_PROGRESS_UPLOAD
398 395
          body:@{
399 396
                 @"taskId": taskId,
400 397
                 @"written": [NSString stringWithFormat:@"%d", totalBytesWritten],

+ 22
- 5
src/polyfill/Fetch.js Wyświetl plik

@@ -110,17 +110,34 @@ class RNFetchBlobFetchRepsonse {
110 110
     return readJSON(this.rnfbResp, this.rnfbRespInfo)
111 111
   }
112 112
 
113
-  formData() {
114
-    log.verbose('to formData', this.rnfbResp, this.rnfbRespInfo)
115
-    return readFormData(this.rnfbResp, this.rnfbRespInfo)
116
-  }
117
-
118 113
   blob() {
119 114
     log.verbose('to blob', this.rnfbResp, this.rnfbRespInfo)
120 115
     return readBlob(this.rnfbResp, this.rnfbRespInfo)
121 116
   }
122 117
 }
123 118
 
119
+/**
120
+ * Get response data as array.
121
+ * @param  {FetchBlobResponse} resp Response data object from RNFB fetch call.
122
+ * @param  {RNFetchBlobResponseInfo} info Response informations.
123
+ * @return {Promise<Array>}
124
+ */
125
+function readArrayBuffer(resp, info):Promise<Array> {
126
+  switch (info.rnfbEncode) {
127
+    case 'path':
128
+      return resp.readFile('ascii')
129
+      break
130
+    default:
131
+      let buffer = []
132
+      let str = resp.text()
133
+      for (let i in str) {
134
+        buffer[i] = str.charCodeAt(i);
135
+      }
136
+      return Promise.resolve(buffer)
137
+      break
138
+  }
139
+}
140
+
124 141
 /**
125 142
  * Get response data as string.
126 143
  * @param  {FetchBlobResponse} resp Response data object from RNFB fetch call.

+ 2
- 1
src/polyfill/XMLHttpRequest.js Wyświetl plik

@@ -10,7 +10,8 @@ import ProgressEvent from './ProgressEvent.js'
10 10
 
11 11
 const log = new Log('XMLHttpRequest')
12 12
 
13
-log.level(2)
13
+log.disable()
14
+// log.level(2)
14 15
 
15 16
 const UNSENT = 0
16 17
 const OPENED = 1

+ 36
- 26
test/test-0.8.0.js Wyświetl plik

@@ -27,32 +27,42 @@ let prefix = ((Platform.OS === 'android') ? 'file://' : '')
27 27
 
28 28
 describe('fs URI encoding support', (report, done) => {
29 29
 
30
-  let testData1 = `test date write file from file ${Date.now()}`
31
-  let testData2 = `test date write file from file ${Date.now()*Math.random()}`
32
-  let file1 = dirs.DocumentDir + '/testFiletFile1' + Date.now()
33
-  let file2 = dirs.DocumentDir + '/testFiletFile2' + Date.now()
34
-  let init = [fs.createFile(file1, testData1, 'utf8'),
35
-              fs.createFile(file2, testData2, 'utf8')]
36
-  Promise.all(init)
37
-    .then(() => fs.appendFile(file1, file2, 'uri'))
38
-    .then(() => fs.readFile(file1, 'utf8'))
39
-    .then((data) => {
40
-      report(
41
-        <Assert key="append content from URI should be correct"
42
-          expect={testData1 + testData2}
43
-          actual={data}
44
-        />)
45
-      return fs.writeFile(file1, file2, 'uri')
46
-    })
47
-    .then(() => fs.readFile(file1, 'utf8'))
48
-    .then((data) => {
49
-      report(
50
-        <Assert key="write content from URI should be correct"
51
-          expect={testData2}
52
-          actual={data}
53
-        />)
54
-      done()
55
-    })
30
+  let testFiles = []
31
+  let sizes = []
32
+
33
+  RNFetchBlob.config({
34
+    fileCache : true
35
+  })
36
+  .fetch('GET', `${TEST_SERVER_URL}/public/github.png`)
37
+  .then((res) => {
38
+    testFiles.push(res.path())
39
+    sizes.push(Math.floor(res.info().headers['Content-Length']))
40
+    return RNFetchBlob.config({fileCache : true}).fetch('GET', `${TEST_SERVER_URL}/public/github2.jpg`)
41
+  })
42
+  .then((res) => {
43
+    testFiles.push(res.path())
44
+    sizes.push(Math.floor(res.info().headers['Content-Length']))
45
+    return fs.appendFile(testFiles[0], testFiles[1], 'uri')
46
+  })
47
+  .then(() => fs.stat(testFiles[0]))
48
+  .then((stat) => {
49
+    report(
50
+      <Assert key="append content from URI should be correct"
51
+        expect={sizes[0] + sizes[1]}
52
+        actual={Math.floor(stat.size)}
53
+      />)
54
+    return fs.writeFile(testFiles[0], testFiles[1], 'uri')
55
+  })
56
+  .then(() => fs.stat(testFiles[0]))
57
+  .then((stat) => {
58
+    report(
59
+      <Assert key="replace content from URI should be correct"
60
+        expect={sizes[1]}
61
+        actual={Math.floor(stat.size)}
62
+      />)
63
+    done()
64
+  })
65
+
56 66
 })
57 67
 
58 68
 describe('request timeout working properly', (report, done) => {

test/test-0.8.2.js → test/test-0.9.0.js Wyświetl plik

@@ -22,7 +22,7 @@ window.fetch = new RNFetchBlob.polyfill.Fetch({
22 22
 const fs = RNFetchBlob.fs
23 23
 const { Assert, Comparer, Info, prop } = RNTest
24 24
 const describe = RNTest.config({
25
-  group : '0.8.2',
25
+  group : '0.9.0',
26 26
   run : true,
27 27
   expand : true,
28 28
   timeout : 20000,
@@ -63,7 +63,7 @@ describe('#73 unicode response content test', (report, done) => {
63 63
 })
64 64
 
65 65
 describe = RNTest.config({
66
-  group : '0.8.2',
66
+  group : '0.9.0',
67 67
   run : true,
68 68
   expand : true,
69 69
   timeout : 24000
@@ -88,7 +88,7 @@ describe('request should not retry after timed out', (report, done) => {
88 88
 })
89 89
 
90 90
 describe = RNTest.config({
91
-  group : '0.8.2',
91
+  group : '0.9.0',
92 92
   run : true,
93 93
   expand : true,
94 94
   timeout : 65000
@@ -105,5 +105,4 @@ describe('long live download or upload task won\'t timeout', (report, done) => {
105 105
     done()
106 106
   })
107 107
 
108
-
109 108
 })

+ 6
- 5
test/test-init.js Wyświetl plik

@@ -18,14 +18,15 @@ const { Assert, Comparer, Info, prop } = RNTest
18 18
 // test environment variables
19 19
 
20 20
 prop('FILENAME', `${Platform.OS}-0.8.0-${Date.now()}.png`)
21
-prop('TEST_SERVER_URL', 'http://192.168.16.70:8123')
22
-prop('TEST_SERVER_URL_SSL', 'https://192.168.16.70:8124')
21
+prop('TEST_SERVER_URL', 'http://192.168.0.11:8123')
22
+prop('TEST_SERVER_URL_SSL', 'https://192.168.0.11:8124')
23 23
 prop('DROPBOX_TOKEN', 'fsXcpmKPrHgAAAAAAAAAoXZhcXYWdgLpQMan6Tb_bzJ237DXhgQSev12hA-gUXt4')
24 24
 prop('styles', {
25 25
   image : {
26 26
     width: Dimensions.get('window').width*0.9,
27 27
     height : Dimensions.get('window').width*0.9,
28
-    margin : 16
28
+    margin : 16,
29
+    flex : 1
29 30
   }
30 31
 })
31 32
 
@@ -65,9 +66,9 @@ describe('GET image from server', (report, done) => {
65 66
 // require('./test-0.6.2')
66 67
 // require('./test-0.6.3')
67 68
 // require('./test-0.7.0')
68
-// require('./test-0.8.0')
69
+require('./test-0.8.0')
69 70
 // require('./test-0.8.2')
70
-require('./test-fetch')
71
+// require('./test-fetch')
71 72
 // require('./test-fs')
72 73
 // require('./test-xmlhttp')
73 74
 // require('./test-blob')