Browse Source

Code refactor

Ben Hsieh 8 years ago
parent
commit
3373932cd5

+ 0
- 2
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobReq.java View File

27
 import java.net.MalformedURLException;
27
 import java.net.MalformedURLException;
28
 import java.net.SocketTimeoutException;
28
 import java.net.SocketTimeoutException;
29
 import java.net.URL;
29
 import java.net.URL;
30
-import java.net.URLEncoder;
31
 import java.nio.ByteBuffer;
30
 import java.nio.ByteBuffer;
32
-import java.nio.CharBuffer;
33
 import java.nio.charset.CharacterCodingException;
31
 import java.nio.charset.CharacterCodingException;
34
 import java.nio.charset.Charset;
32
 import java.nio.charset.Charset;
35
 import java.nio.charset.CharsetEncoder;
33
 import java.nio.charset.CharsetEncoder;

+ 3
- 0
src/ios/RNFetchBlobConst.h View File

16
 extern NSString *const MSG_EVENT_LOG;
16
 extern NSString *const MSG_EVENT_LOG;
17
 extern NSString *const MSG_EVENT_WARN;
17
 extern NSString *const MSG_EVENT_WARN;
18
 extern NSString *const MSG_EVENT_ERROR;
18
 extern NSString *const MSG_EVENT_ERROR;
19
+
20
+extern NSString *const EVENT_PROGRESS;
21
+extern NSString *const EVENT_PROGRESS_UPLOAD;
19
 extern NSString *const EVENT_STATE_CHANGE;
22
 extern NSString *const EVENT_STATE_CHANGE;
20
 
23
 
21
 extern NSString *const FILE_PREFIX;
24
 extern NSString *const FILE_PREFIX;

+ 3
- 0
src/ios/RNFetchBlobConst.m View File

23
 extern NSString *const CONFIG_EXTRA_BLOB_CTYPE = @"binaryContentTypes";
23
 extern NSString *const CONFIG_EXTRA_BLOB_CTYPE = @"binaryContentTypes";
24
 
24
 
25
 extern NSString *const EVENT_STATE_CHANGE = @"RNFetchBlobState";
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
 extern NSString *const MSG_EVENT = @"RNFetchBlobMessage";
29
 extern NSString *const MSG_EVENT = @"RNFetchBlobMessage";
27
 extern NSString *const MSG_EVENT_LOG = @"log";
30
 extern NSString *const MSG_EVENT_LOG = @"log";
28
 extern NSString *const MSG_EVENT_WARN = @"warn";
31
 extern NSString *const MSG_EVENT_WARN = @"warn";

+ 24
- 8
src/ios/RNFetchBlobFS.m View File

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

+ 6
- 9
src/ios/RNFetchBlobNetwork.m View File

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

+ 22
- 5
src/polyfill/Fetch.js View File

110
     return readJSON(this.rnfbResp, this.rnfbRespInfo)
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
   blob() {
113
   blob() {
119
     log.verbose('to blob', this.rnfbResp, this.rnfbRespInfo)
114
     log.verbose('to blob', this.rnfbResp, this.rnfbRespInfo)
120
     return readBlob(this.rnfbResp, this.rnfbRespInfo)
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
  * Get response data as string.
142
  * Get response data as string.
126
  * @param  {FetchBlobResponse} resp Response data object from RNFB fetch call.
143
  * @param  {FetchBlobResponse} resp Response data object from RNFB fetch call.

+ 2
- 1
src/polyfill/XMLHttpRequest.js View File

10
 
10
 
11
 const log = new Log('XMLHttpRequest')
11
 const log = new Log('XMLHttpRequest')
12
 
12
 
13
-log.level(2)
13
+log.disable()
14
+// log.level(2)
14
 
15
 
15
 const UNSENT = 0
16
 const UNSENT = 0
16
 const OPENED = 1
17
 const OPENED = 1

+ 36
- 26
test/test-0.8.0.js View File

27
 
27
 
28
 describe('fs URI encoding support', (report, done) => {
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
 describe('request timeout working properly', (report, done) => {
68
 describe('request timeout working properly', (report, done) => {

test/test-0.8.2.js → test/test-0.9.0.js View File

22
 const fs = RNFetchBlob.fs
22
 const fs = RNFetchBlob.fs
23
 const { Assert, Comparer, Info, prop } = RNTest
23
 const { Assert, Comparer, Info, prop } = RNTest
24
 const describe = RNTest.config({
24
 const describe = RNTest.config({
25
-  group : '0.8.2',
25
+  group : '0.9.0',
26
   run : true,
26
   run : true,
27
   expand : true,
27
   expand : true,
28
   timeout : 20000,
28
   timeout : 20000,
63
 })
63
 })
64
 
64
 
65
 describe = RNTest.config({
65
 describe = RNTest.config({
66
-  group : '0.8.2',
66
+  group : '0.9.0',
67
   run : true,
67
   run : true,
68
   expand : true,
68
   expand : true,
69
   timeout : 24000
69
   timeout : 24000
88
 })
88
 })
89
 
89
 
90
 describe = RNTest.config({
90
 describe = RNTest.config({
91
-  group : '0.8.2',
91
+  group : '0.9.0',
92
   run : true,
92
   run : true,
93
   expand : true,
93
   expand : true,
94
   timeout : 65000
94
   timeout : 65000
105
     done()
105
     done()
106
   })
106
   })
107
 
107
 
108
-
109
 })
108
 })

+ 6
- 5
test/test-init.js View File

18
 // test environment variables
18
 // test environment variables
19
 
19
 
20
 prop('FILENAME', `${Platform.OS}-0.8.0-${Date.now()}.png`)
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
 prop('DROPBOX_TOKEN', 'fsXcpmKPrHgAAAAAAAAAoXZhcXYWdgLpQMan6Tb_bzJ237DXhgQSev12hA-gUXt4')
23
 prop('DROPBOX_TOKEN', 'fsXcpmKPrHgAAAAAAAAAoXZhcXYWdgLpQMan6Tb_bzJ237DXhgQSev12hA-gUXt4')
24
 prop('styles', {
24
 prop('styles', {
25
   image : {
25
   image : {
26
     width: Dimensions.get('window').width*0.9,
26
     width: Dimensions.get('window').width*0.9,
27
     height : Dimensions.get('window').width*0.9,
27
     height : Dimensions.get('window').width*0.9,
28
-    margin : 16
28
+    margin : 16,
29
+    flex : 1
29
   }
30
   }
30
 })
31
 })
31
 
32
 
65
 // require('./test-0.6.2')
66
 // require('./test-0.6.2')
66
 // require('./test-0.6.3')
67
 // require('./test-0.6.3')
67
 // require('./test-0.7.0')
68
 // require('./test-0.7.0')
68
-// require('./test-0.8.0')
69
+require('./test-0.8.0')
69
 // require('./test-0.8.2')
70
 // require('./test-0.8.2')
70
-require('./test-fetch')
71
+// require('./test-fetch')
71
 // require('./test-fs')
72
 // require('./test-fs')
72
 // require('./test-xmlhttp')
73
 // require('./test-xmlhttp')
73
 // require('./test-blob')
74
 // require('./test-blob')