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

Commit 3373932

Browse files
committed
Code refactor
1 parent bb126fd commit 3373932

File tree

10 files changed

+105
-60
lines changed

10 files changed

+105
-60
lines changed

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

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,7 @@
2727
import java.net.MalformedURLException;
2828
import java.net.SocketTimeoutException;
2929
import java.net.URL;
30-
import java.net.URLEncoder;
3130
import java.nio.ByteBuffer;
32-
import java.nio.CharBuffer;
3331
import java.nio.charset.CharacterCodingException;
3432
import java.nio.charset.Charset;
3533
import java.nio.charset.CharsetEncoder;

src/ios/RNFetchBlobConst.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ extern NSString *const MSG_EVENT;
1616
extern NSString *const MSG_EVENT_LOG;
1717
extern NSString *const MSG_EVENT_WARN;
1818
extern NSString *const MSG_EVENT_ERROR;
19+
20+
extern NSString *const EVENT_PROGRESS;
21+
extern NSString *const EVENT_PROGRESS_UPLOAD;
1922
extern NSString *const EVENT_STATE_CHANGE;
2023

2124
extern NSString *const FILE_PREFIX;

src/ios/RNFetchBlobConst.m

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@
2323
extern NSString *const CONFIG_EXTRA_BLOB_CTYPE = @"binaryContentTypes";
2424

2525
extern NSString *const EVENT_STATE_CHANGE = @"RNFetchBlobState";
26+
extern NSString *const EVENT_PROGRESS = @"RNFetchBlobProgress";
27+
extern NSString *const EVENT_PROGRESS_UPLOAD = @"RNFetchBlobProgress-upload";
28+
2629
extern NSString *const MSG_EVENT = @"RNFetchBlobMessage";
2730
extern NSString *const MSG_EVENT_LOG = @"log";
2831
extern NSString *const MSG_EVENT_WARN = @"warn";

src/ios/RNFetchBlobFS.m

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ +(NSString *) getPathOfAsset:(NSString *)assetURI
6363
return assetURI;
6464
}
6565

66+
#pragma mark - system directories
67+
6668
+ (NSString *) getCacheDir {
6769
return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
6870
}
@@ -98,6 +100,8 @@ + (NSString *) getTempPath:(NSString*)taskId withExtension:(NSString *)ext {
98100
return tempPath;
99101
}
100102

103+
#pragma mark - read asset stream
104+
101105
- (void) startAssetReadStream:(NSString *)assetUrl
102106
{
103107
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
@@ -185,6 +189,8 @@ - (void) startAssetReadStream:(NSString *)assetUrl
185189
}
186190
}
187191

192+
# pragma write file from file
193+
188194
+ (NSNumber *) writeFileFromFile:(NSString *)src toFile:(NSString *)dest append:(BOOL)append
189195
{
190196
NSInputStream * is = [[NSInputStream alloc] initWithFileAtPath:src];
@@ -205,6 +211,8 @@ + (NSNumber *) writeFileFromFile:(NSString *)src toFile:(NSString *)dest append:
205211
return [NSNumber numberWithLong:written];
206212
}
207213

214+
# pragma mark - write file
215+
208216
+ (void) writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject
209217
{
210218
@try {
@@ -226,14 +234,6 @@ + (void) writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString
226234
NSData * content = nil;
227235
if([encoding containsString:@"base64"]) {
228236
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-
}
237237
}
238238
else if([encoding isEqualToString:@"uri"]) {
239239
NSNumber* size = [[self class] writeFileFromFile:data toFile:path append:append];
@@ -261,6 +261,8 @@ + (void) writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString
261261
}
262262
}
263263

264+
# pragma mark - write file (array)
265+
264266
+ (void) writeFileArray:(NSString *)path data:(NSArray *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
265267
@try {
266268
NSFileManager * fm = [NSFileManager defaultManager];
@@ -303,6 +305,8 @@ + (void) writeFileArray:(NSString *)path data:(NSArray *)data append:(BOOL)appen
303305
}
304306
}
305307

308+
# pragma mark - read file
309+
306310
+ (void) readFile:(NSString *)path encoding:(NSString *)encoding
307311
resolver:(RCTPromiseResolveBlock)resolve
308312
rejecter:(RCTPromiseRejectBlock)reject
@@ -370,6 +374,8 @@ + (void) readFile:(NSString *)path encoding:(NSString *)encoding
370374
}
371375
}
372376

377+
# pragma mark - mkdir
378+
373379
+ (BOOL) mkdir:(NSString *) path {
374380
BOOL isDir;
375381
NSError * err = nil;
@@ -380,6 +386,8 @@ + (BOOL) mkdir:(NSString *) path {
380386
return err == nil;
381387
}
382388

389+
# pragma mark - stat
390+
383391
+ (NSDictionary *) stat:(NSString *) path error:(NSError **) error {
384392
NSMutableDictionary *stat = [[NSMutableDictionary alloc] init];
385393
BOOL isDir = NO;
@@ -401,6 +409,8 @@ + (NSDictionary *) stat:(NSString *) path error:(NSError **) error {
401409
};
402410
}
403411

412+
# pragma mark - exists
413+
404414
+ (BOOL) exists:(NSString *) path {
405415
return [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:NULL];
406416
}
@@ -422,6 +432,8 @@ - (id)initWithBridgeRef:(RCTBridge *)bridgeRef {
422432
return self;
423433
}
424434

435+
# pragma mark - open file stream
436+
425437
// Create file stream for write data
426438
- (NSString *)openWithPath:(NSString *)destPath encode:(nullable NSString *)encode appendData:(BOOL)append {
427439
self.outStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:append];
@@ -434,6 +446,8 @@ - (NSString *)openWithPath:(NSString *)destPath encode:(nullable NSString *)enco
434446
return uuid;
435447
}
436448

449+
# pragma mark - file stream write chunk
450+
437451
// Write file chunk into an opened stream
438452
- (void)writeEncodeChunk:(NSString *) chunk {
439453
NSMutableData * decodedData = [NSData alloc];
@@ -679,6 +693,8 @@ - (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
679693

680694
}
681695

696+
# pragma mark - get absolute path of resource
697+
682698
+ (void) getPathFromUri:(NSString *)uri completionHandler:(void(^)(NSString * path, ALAssetRepresentation *asset)) onComplete
683699
{
684700
if([uri hasPrefix:AL_PREFIX])

src/ios/RNFetchBlobNetwork.m

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -134,9 +134,8 @@ - (void) sendRequest:(__weak NSDictionary * _Nullable )options
134134
bodyLength = contentLength;
135135

136136
// the session trust any SSL certification
137-
138-
139137
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
138+
// set request timeout
140139
float timeout = [options valueForKey:@"timeout"] == nil ? -1 : [[options valueForKey:@"timeout"] floatValue];
141140
if(timeout > 0)
142141
{
@@ -202,9 +201,7 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
202201
if ([response respondsToSelector:@selector(allHeaderFields)])
203202
{
204203
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];
208205
if(respCType != nil)
209206
{
210207
NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
@@ -299,12 +296,12 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
299296
if([progressTable valueForKey:taskId] == @YES)
300297
{
301298
[self.bridge.eventDispatcher
302-
sendDeviceEventWithName:@"RNFetchBlobProgress"
299+
sendDeviceEventWithName:EVENT_PROGRESS
303300
body:@{
304301
@"taskId": taskId,
305302
@"written": [NSString stringWithFormat:@"%d", receivedBytes],
306303
@"total": [NSString stringWithFormat:@"%d", expectedBytes]
307-
}
304+
}
308305
];
309306
}
310307
received = nil;
@@ -376,7 +373,7 @@ - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCom
376373
@synchronized(taskTable, uploadProgressTable, progressTable)
377374
{
378375
if([taskTable objectForKey:taskId] == nil)
379-
NSLog(@"object released.");
376+
NSLog(@"object released by ARC.");
380377
else
381378
[taskTable removeObjectForKey:taskId];
382379
[uploadProgressTable removeObjectForKey:taskId];
@@ -394,7 +391,7 @@ - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSen
394391
{
395392
if([uploadProgressTable valueForKey:taskId] == @YES) {
396393
[self.bridge.eventDispatcher
397-
sendDeviceEventWithName:@"RNFetchBlobProgress-upload"
394+
sendDeviceEventWithName:EVENT_PROGRESS_UPLOAD
398395
body:@{
399396
@"taskId": taskId,
400397
@"written": [NSString stringWithFormat:@"%d", totalBytesWritten],

src/polyfill/Fetch.js

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -110,17 +110,34 @@ class RNFetchBlobFetchRepsonse {
110110
return readJSON(this.rnfbResp, this.rnfbRespInfo)
111111
}
112112

113-
formData() {
114-
log.verbose('to formData', this.rnfbResp, this.rnfbRespInfo)
115-
return readFormData(this.rnfbResp, this.rnfbRespInfo)
116-
}
117-
118113
blob() {
119114
log.verbose('to blob', this.rnfbResp, this.rnfbRespInfo)
120115
return readBlob(this.rnfbResp, this.rnfbRespInfo)
121116
}
122117
}
123118

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+
124141
/**
125142
* Get response data as string.
126143
* @param {FetchBlobResponse} resp Response data object from RNFB fetch call.

src/polyfill/XMLHttpRequest.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ import ProgressEvent from './ProgressEvent.js'
1010

1111
const log = new Log('XMLHttpRequest')
1212

13-
log.level(2)
13+
log.disable()
14+
// log.level(2)
1415

1516
const UNSENT = 0
1617
const OPENED = 1

test/test-0.8.0.js

Lines changed: 36 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -27,32 +27,42 @@ let prefix = ((Platform.OS === 'android') ? 'file://' : '')
2727

2828
describe('fs URI encoding support', (report, done) => {
2929

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+
5666
})
5767

5868
describe('request timeout working properly', (report, done) => {

test/test-0.8.2.js renamed to test/test-0.9.0.js

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ window.fetch = new RNFetchBlob.polyfill.Fetch({
2222
const fs = RNFetchBlob.fs
2323
const { Assert, Comparer, Info, prop } = RNTest
2424
const describe = RNTest.config({
25-
group : '0.8.2',
25+
group : '0.9.0',
2626
run : true,
2727
expand : true,
2828
timeout : 20000,
@@ -63,7 +63,7 @@ describe('#73 unicode response content test', (report, done) => {
6363
})
6464

6565
describe = RNTest.config({
66-
group : '0.8.2',
66+
group : '0.9.0',
6767
run : true,
6868
expand : true,
6969
timeout : 24000
@@ -88,7 +88,7 @@ describe('request should not retry after timed out', (report, done) => {
8888
})
8989

9090
describe = RNTest.config({
91-
group : '0.8.2',
91+
group : '0.9.0',
9292
run : true,
9393
expand : true,
9494
timeout : 65000
@@ -105,5 +105,4 @@ describe('long live download or upload task won\'t timeout', (report, done) => {
105105
done()
106106
})
107107

108-
109108
})

test/test-init.js

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,15 @@ const { Assert, Comparer, Info, prop } = RNTest
1818
// test environment variables
1919

2020
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')
2323
prop('DROPBOX_TOKEN', 'fsXcpmKPrHgAAAAAAAAAoXZhcXYWdgLpQMan6Tb_bzJ237DXhgQSev12hA-gUXt4')
2424
prop('styles', {
2525
image : {
2626
width: Dimensions.get('window').width*0.9,
2727
height : Dimensions.get('window').width*0.9,
28-
margin : 16
28+
margin : 16,
29+
flex : 1
2930
}
3031
})
3132

@@ -65,9 +66,9 @@ describe('GET image from server', (report, done) => {
6566
// require('./test-0.6.2')
6667
// require('./test-0.6.3')
6768
// require('./test-0.7.0')
68-
// require('./test-0.8.0')
69+
require('./test-0.8.0')
6970
// require('./test-0.8.2')
70-
require('./test-fetch')
71+
// require('./test-fetch')
7172
// require('./test-fs')
7273
// require('./test-xmlhttp')
7374
// require('./test-blob')

0 commit comments

Comments
 (0)