Selaa lähdekoodia

Add key cache implementation (android/ios)

Juan B. Rodriguez 8 vuotta sitten
vanhempi
commit
7704239d48

+ 0
- 1
src/android/src/main/java/com/RNFetchBlob/RNFetchBlob.java Näytä tiedosto

@@ -171,4 +171,3 @@ public class RNFetchBlob extends ReactContextBaseJavaModule {
171 171
     }
172 172
 
173 173
 }
174
-

+ 32
- 1
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobBody.java Näytä tiedosto

@@ -20,6 +20,7 @@ import java.util.HashMap;
20 20
 
21 21
 import okhttp3.MediaType;
22 22
 import okhttp3.RequestBody;
23
+import okhttp3.FormBody;
23 24
 import okio.Buffer;
24 25
 import okio.BufferedSink;
25 26
 import okio.ForwardingSink;
@@ -71,11 +72,14 @@ public class RNFetchBlobBody extends RequestBody{
71 72
             case SingleFile:
72 73
                 writeOctetData(sink);
73 74
                 break;
75
+			case Encoded:
76
+				writeEncodedData(sink);
77
+				break;
74 78
         }
75 79
         buffer.flush();
76 80
     }
77 81
 
78
-    private void writeFormData(BufferedSink sink) throws IOException {
82
+	private void writeFormData(BufferedSink sink) throws IOException {
79 83
         String boundary = "RNFetchBlob-" + mTaskId;
80 84
         ArrayList<FormField> fields = countFormDataLength();
81 85
         ReactApplicationContext ctx = RNFetchBlob.RCTContext;
@@ -184,6 +188,33 @@ public class RNFetchBlobBody extends RequestBody{
184 188
 
185 189
     }
186 190
 
191
+
192
+	/**
193
+     * Write form-encoded data to request body
194
+     * @param sink
195
+     */
196
+	 // This is NOT working since sink.write, creates a Transfer-Encoding: chunked
197
+	 // header, which is not expected from servers
198
+	private void writeEncodedData(BufferedSink sink) throws IOException {
199
+		FormBody.Builder body = new FormBody.Builder();
200
+
201
+		// String[] pairs = rawBody.split("&");
202
+		// for ( String pair : pairs ) {
203
+		// 	String[] kv = pair.split("=");
204
+		// 	body.add(kv[0], kv[1]);
205
+		// }
206
+		// body.build().writeTo(sink);
207
+
208
+		// String header = "Content-Disposition: form-data; \r\n";
209
+		// String header = "Content-Type: application/x-www-form-urlencoded\r\n\r\n";
210
+		// sink.write(header.getBytes());
211
+		// byte[] fieldData = field.data.getBytes();
212
+		// bytesWritten += fieldData.length;
213
+		sink.write(rawBody.getBytes());
214
+
215
+
216
+	}
217
+
187 218
     /**
188 219
      * Pipe input stream to request body output stream
189 220
      * @param stream    The input stream

+ 1
- 1
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobConst.java Näytä tiedosto

@@ -11,7 +11,7 @@ public class RNFetchBlobConst {
11 11
     public static final String FILE_PREFIX = "RNFetchBlob-file://";
12 12
     public static final MediaType MIME_OCTET = MediaType.parse("application/octet-stream");
13 13
     public static final MediaType MIME_MULTIPART = MediaType.parse("multipart/form-data");
14
+	public static final MediaType MIME_ENCODED = MediaType.parse("application/x-www-form-urlencoded");
14 15
     public static final String FILE_PREFIX_BUNDLE_ASSET = "bundle-assets://";
15 16
     public static final String FILE_PREFIX_CONTENT = "content://";
16
-
17 17
 }

+ 0
- 2
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobFS.java Näytä tiedosto

@@ -799,5 +799,3 @@ public class RNFetchBlobFS {
799 799
     }
800 800
 
801 801
 }
802
-
803
-

+ 37
- 14
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobReq.java Näytä tiedosto

@@ -8,6 +8,7 @@ import android.content.IntentFilter;
8 8
 import android.database.Cursor;
9 9
 import android.net.Uri;
10 10
 import android.util.Base64;
11
+import android.util.Log;
11 12
 
12 13
 import com.RNFetchBlob.Response.RNFetchBlobDefaultResp;
13 14
 import com.RNFetchBlob.Response.RNFetchBlobFileResp;
@@ -34,6 +35,7 @@ import okhttp3.Request;
34 35
 import okhttp3.RequestBody;
35 36
 import okhttp3.Response;
36 37
 import okhttp3.ResponseBody;
38
+import okhttp3.FormBody;
37 39
 
38 40
 /**
39 41
  * Created by wkh237 on 2016/6/21.
@@ -42,6 +44,7 @@ public class RNFetchBlobReq extends BroadcastReceiver implements Runnable {
42 44
 
43 45
     enum RequestType  {
44 46
         Form,
47
+		Encoded,
45 48
         SingleFile,
46 49
         WithoutBody,
47 50
         Others
@@ -85,7 +88,9 @@ public class RNFetchBlobReq extends BroadcastReceiver implements Runnable {
85 88
         else
86 89
             responseType = ResponseType.KeepInMemory;
87 90
 
88
-        if (body != null)
91
+        if (body != null && headers.hasKey("content-type") && "application/x-www-form-urlencoded".equals(headers.getString("content-type")))
92
+			requestType = RequestType.Encoded;
93
+		else if (body != null)
89 94
             requestType = RequestType.SingleFile;
90 95
         else if (arrayBody != null)
91 96
             requestType = RequestType.Form;
@@ -135,23 +140,26 @@ public class RNFetchBlobReq extends BroadcastReceiver implements Runnable {
135 140
 
136 141
         // find cached result if `key` property exists
137 142
         String cacheKey = this.taskId;
138
-//        if (this.options.key != null) {
139
-//            cacheKey = RNFetchBlobUtils.getMD5(this.options.key);
140
-//            if (cacheKey == null) {
141
-//                cacheKey = this.taskId;
142
-//            }
143
-//
144
-//            File file = new File(RNFetchBlobFS.getTmpPath(ctx, cacheKey));
145
-//            if (file.exists()) {
146
-//                callback.invoke(null, file.getAbsolutePath());
147
-//                return;
148
-//            }
149
-//        }
143
+		String ext = this.options.appendExt != "" ? "." + this.options.appendExt : "";
144
+
145
+       	if (this.options.key != null) {
146
+           cacheKey = RNFetchBlobUtils.getMD5(this.options.key);
147
+           if (cacheKey == null) {
148
+               cacheKey = this.taskId;
149
+           }
150
+
151
+           File file = new File(RNFetchBlobFS.getTmpPath(RNFetchBlob.RCTContext, cacheKey) + ext);
152
+
153
+           if (file.exists()) {
154
+               callback.invoke(null, file.getAbsolutePath());
155
+               return;
156
+           }
157
+       }
150 158
 
151 159
         if(this.options.path != null)
152 160
             this.destPath = this.options.path;
153 161
         else if(this.options.fileCache == true)
154
-            this.destPath = RNFetchBlobFS.getTmpPath(RNFetchBlob.RCTContext, cacheKey);
162
+            this.destPath = RNFetchBlobFS.getTmpPath(RNFetchBlob.RCTContext, cacheKey) + ext;
155 163
 
156 164
         OkHttpClient.Builder clientBuilder;
157 165
 
@@ -197,6 +205,21 @@ public class RNFetchBlobReq extends BroadcastReceiver implements Runnable {
197 205
                             MediaType.parse("multipart/form-data; boundary=RNFetchBlob-" + taskId)
198 206
                     ));
199 207
                     break;
208
+				case Encoded:
209
+					// rawRequestBody has an expected format of
210
+					// key1=value1&key2=value&...
211
+					FormBody.Builder formBuilder = new FormBody.Builder();
212
+
213
+					String[] pairs = rawRequestBody.split("&");
214
+					for ( String pair : pairs ) {
215
+						String[] kv = pair.split("=");
216
+						formBuilder.add(kv[0], kv[1]);
217
+					}
218
+
219
+					RequestBody body = formBuilder.build();
220
+
221
+					builder.method(method, body);
222
+					break;
200 223
                 case WithoutBody:
201 224
                     builder.method(method, null);
202 225
                     break;

+ 46
- 37
src/ios/RNFetchBlob/RNFetchBlob.m Näytä tiedosto

@@ -62,14 +62,14 @@ RCT_EXPORT_METHOD(fetchBlobForm:(NSDictionary *)options
62 62
                   form:(NSArray *)form
63 63
                   callback:(RCTResponseSenderBlock)callback)
64 64
 {
65
-    
65
+
66 66
     [RNFetchBlobReqBuilder buildMultipartRequest:options taskId:taskId method:method url:url headers:headers form:form onComplete:^(NSURLRequest *req, long bodyLength) {
67 67
         // send HTTP request
68 68
         RNFetchBlobNetwork * utils = [[RNFetchBlobNetwork alloc] init];
69 69
         [utils sendRequest:options contentLength:bodyLength bridge:self.bridge taskId:taskId withRequest:req callback:callback];
70 70
         utils = nil;
71 71
     }];
72
-    
72
+
73 73
 }
74 74
 
75 75
 // Fetch blob data request
@@ -80,20 +80,29 @@ RCT_EXPORT_METHOD(fetchBlob:(NSDictionary *)options
80 80
                   headers:(NSDictionary *)headers
81 81
                   body:(NSString *)body callback:(RCTResponseSenderBlock)callback)
82 82
 {
83
-    [RNFetchBlobReqBuilder buildOctetRequest:options taskId:taskId method:method url:url headers:headers body:body onComplete:^(NSURLRequest *req, long bodyLength) {
84
-        // send HTTP request
85
-        RNFetchBlobNetwork * utils = [[RNFetchBlobNetwork alloc] init];
86
-        [utils sendRequest:options contentLength:bodyLength bridge:self.bridge taskId:taskId withRequest:req callback:callback];
87
-        utils = nil;
88
-    }];
89
-    
83
+	NSString *cType = [headers valueForKey:"content-type"]
84
+	if (cType != nil && cType == @"application/x-www-form-urlencoded") {
85
+		[RNFetchBlobReqBuilder buildEncodedRequest:options taskId:taskId method:method url:url headers:headers body:body onComplete:^(NSURLRequest *req, long bodyLength) {
86
+	        // send HTTP request
87
+	        RNFetchBlobNetwork * utils = [[RNFetchBlobNetwork alloc] init];
88
+	        [utils sendRequest:options contentLength:bodyLength bridge:self.bridge taskId:taskId withRequest:req callback:callback];
89
+	        utils = nil;
90
+	    }];
91
+	} else {
92
+		[RNFetchBlobReqBuilder buildOctetRequest:options taskId:taskId method:method url:url headers:headers body:body onComplete:^(NSURLRequest *req, long bodyLength) {
93
+	        // send HTTP request
94
+	        RNFetchBlobNetwork * utils = [[RNFetchBlobNetwork alloc] init];
95
+	        [utils sendRequest:options contentLength:bodyLength bridge:self.bridge taskId:taskId withRequest:req callback:callback];
96
+	        utils = nil;
97
+	    }];
98
+	}
90 99
 }
91 100
 
92 101
 RCT_EXPORT_METHOD(createFile:(NSString *)path data:(NSString *)data encoding:(NSString *)encoding callback:(RCTResponseSenderBlock)callback) {
93
-    
102
+
94 103
     NSFileManager * fm = [NSFileManager defaultManager];
95 104
     NSData * fileContent = nil;
96
-    
105
+
97 106
     if([[encoding lowercaseString] isEqualToString:@"utf8"]) {
98 107
         fileContent = [[NSData alloc] initWithData:[data dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
99 108
     }
@@ -103,18 +112,18 @@ RCT_EXPORT_METHOD(createFile:(NSString *)path data:(NSString *)data encoding:(NS
103 112
     else {
104 113
         fileContent = [[NSData alloc] initWithData:[data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
105 114
     }
106
-    
115
+
107 116
     BOOL success = [fm createFileAtPath:path contents:fileContent attributes:NULL];
108 117
     if(success == YES)
109 118
         callback(@[[NSNull null]]);
110 119
     else
111 120
         callback(@[[NSString stringWithFormat:@"failed to create new file at path %@ please ensure the folder exists"]]);
112
-    
121
+
113 122
 }
114 123
 
115 124
 // method for create file with ASCII content
116 125
 RCT_EXPORT_METHOD(createFileASCII:(NSString *)path data:(NSArray *)dataArray callback:(RCTResponseSenderBlock)callback) {
117
-    
126
+
118 127
     NSFileManager * fm = [NSFileManager defaultManager];
119 128
     NSMutableData * fileContent = [NSMutableData alloc];
120 129
     // prevent stack overflow, alloc on heap
@@ -130,7 +139,7 @@ RCT_EXPORT_METHOD(createFileASCII:(NSString *)path data:(NSArray *)dataArray cal
130 139
         callback(@[[NSNull null]]);
131 140
     else
132 141
         callback(@[[NSString stringWithFormat:@"failed to create new file at path %@ please ensure the folder exists"]]);
133
-    
142
+
134 143
 }
135 144
 
136 145
 
@@ -139,7 +148,7 @@ RCT_EXPORT_METHOD(exists:(NSString *)path callback:(RCTResponseSenderBlock)callb
139 148
     BOOL exists = NO;
140 149
     exists = [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory: &isDir];
141 150
     callback(@[@(exists), @(isDir)]);
142
-    
151
+
143 152
 }
144 153
 
145 154
 RCT_EXPORT_METHOD(writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
@@ -202,7 +211,7 @@ RCT_EXPORT_METHOD(unlink:(NSString *)path callback:(RCTResponseSenderBlock) call
202 211
 RCT_EXPORT_METHOD(removeSession:(NSArray *)paths callback:(RCTResponseSenderBlock) callback) {
203 212
     NSError * error = nil;
204 213
     NSString * tmpPath = nil;
205
-    
214
+
206 215
     for(NSString * path in paths) {
207 216
         [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
208 217
         if(error != nil) {
@@ -211,7 +220,7 @@ RCT_EXPORT_METHOD(removeSession:(NSArray *)paths callback:(RCTResponseSenderBloc
211 220
         }
212 221
     }
213 222
     callback(@[[NSNull null]]);
214
-    
223
+
215 224
 }
216 225
 
217 226
 RCT_EXPORT_METHOD(ls:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
@@ -225,12 +234,12 @@ RCT_EXPORT_METHOD(ls:(NSString *)path callback:(RCTResponseSenderBlock) callback
225 234
     }
226 235
     NSError * error = nil;
227 236
     NSArray * result = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
228
-    
237
+
229 238
     if(error == nil)
230 239
         callback(@[[NSNull null], result == nil ? [NSNull null] :result ]);
231 240
     else
232 241
         callback(@[[error localizedDescription], [NSNull null]]);
233
-    
242
+
234 243
 }
235 244
 
236 245
 RCT_EXPORT_METHOD(stat:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
@@ -238,30 +247,30 @@ RCT_EXPORT_METHOD(stat:(NSString *)path callback:(RCTResponseSenderBlock) callba
238 247
     BOOL exist = nil;
239 248
     BOOL isDir = nil;
240 249
     NSError * error = nil;
241
-    
250
+
242 251
     path = [RNFetchBlobFS getPathOfAsset:path];
243
-    
252
+
244 253
     exist = [fm fileExistsAtPath:path isDirectory:&isDir];
245 254
     if(exist == NO) {
246 255
         callback(@[[NSString stringWithFormat:@"failed to list path `%@` for it is not exist or it is not exist", path]]);
247 256
         return ;
248 257
     }
249 258
     NSData * res = [RNFetchBlobFS stat:path error:&error];
250
-    
259
+
251 260
     if(error == nil)
252 261
         callback(@[[NSNull null], res]);
253 262
     else
254 263
         callback(@[[error localizedDescription], [NSNull null]]);
255
-    
264
+
256 265
 }
257 266
 
258 267
 RCT_EXPORT_METHOD(lstat:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
259 268
     NSFileManager* fm = [NSFileManager defaultManager];
260 269
     BOOL exist = nil;
261 270
     BOOL isDir = nil;
262
-    
271
+
263 272
     path = [RNFetchBlobFS getPathOfAsset:path];
264
-    
273
+
265 274
     exist = [fm fileExistsAtPath:path isDirectory:&isDir];
266 275
     if(exist == NO) {
267 276
         callback(@[[NSString stringWithFormat:@"failed to list path `%@` for it is not exist or it is not exist", path]]);
@@ -269,7 +278,7 @@ RCT_EXPORT_METHOD(lstat:(NSString *)path callback:(RCTResponseSenderBlock) callb
269 278
     }
270 279
     NSError * error = nil;
271 280
     NSArray * files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
272
-    
281
+
273 282
     NSMutableArray * res = [[NSMutableArray alloc] init];
274 283
     if(isDir == YES) {
275 284
         for(NSString * p in files) {
@@ -280,35 +289,35 @@ RCT_EXPORT_METHOD(lstat:(NSString *)path callback:(RCTResponseSenderBlock) callb
280 289
     else {
281 290
         [res addObject:[RNFetchBlobFS stat:path error:&error]];
282 291
     }
283
-    
292
+
284 293
     if(error == nil)
285 294
         callback(@[[NSNull null], res == nil ? [NSNull null] :res ]);
286 295
     else
287 296
         callback(@[[error localizedDescription], [NSNull null]]);
288
-    
297
+
289 298
 }
290 299
 
291 300
 RCT_EXPORT_METHOD(cp:(NSString *)path toPath:(NSString *)dest callback:(RCTResponseSenderBlock) callback) {
292 301
     NSError * error = nil;
293 302
     path = [RNFetchBlobFS getPathOfAsset:path];
294 303
     BOOL result = [[NSFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:path] toURL:[NSURL fileURLWithPath:dest] error:&error];
295
-    
304
+
296 305
     if(error == nil)
297 306
         callback(@[[NSNull null], @YES]);
298 307
     else
299 308
         callback(@[[error localizedDescription], @NO]);
300
-    
309
+
301 310
 }
302 311
 
303 312
 RCT_EXPORT_METHOD(mv:(NSString *)path toPath:(NSString *)dest callback:(RCTResponseSenderBlock) callback) {
304 313
     NSError * error = nil;
305 314
     BOOL result = [[NSFileManager defaultManager] moveItemAtURL:[NSURL fileURLWithPath:path] toURL:[NSURL fileURLWithPath:dest] error:&error];
306
-    
315
+
307 316
     if(error == nil)
308 317
         callback(@[[NSNull null], @YES]);
309 318
     else
310 319
         callback(@[[error localizedDescription], @NO]);
311
-    
320
+
312 321
 }
313 322
 
314 323
 RCT_EXPORT_METHOD(mkdir:(NSString *)path callback:(RCTResponseSenderBlock) callback) {
@@ -322,12 +331,12 @@ RCT_EXPORT_METHOD(mkdir:(NSString *)path callback:(RCTResponseSenderBlock) callb
322 331
 }
323 332
 
324 333
 RCT_EXPORT_METHOD(readFile:(NSString *)path encoding:(NSString *)encoding resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
325
-    
334
+
326 335
     [RNFetchBlobFS readFile:path encoding:encoding resolver:resolve rejecter:reject onComplete:nil];
327 336
 })
328 337
 
329 338
 RCT_EXPORT_METHOD(readStream:(NSString *)path withEncoding:(NSString *)encoding bufferSize:(int)bufferSize) {
330
-    
339
+
331 340
     RNFetchBlobFS *fileStream = [[RNFetchBlobFS alloc] initWithBridgeRef:self.bridge];
332 341
     if(bufferSize == nil) {
333 342
         if([[encoding lowercaseString] isEqualToString:@"base64"])
@@ -340,7 +349,7 @@ RCT_EXPORT_METHOD(readStream:(NSString *)path withEncoding:(NSString *)encoding
340 349
 }
341 350
 
342 351
 RCT_EXPORT_METHOD(getEnvironmentDirs:(RCTResponseSenderBlock) callback) {
343
-    
352
+
344 353
     callback(@[
345 354
                [RNFetchBlobFS getDocumentDir],
346 355
                [RNFetchBlobFS getCacheDir],
@@ -350,7 +359,7 @@ RCT_EXPORT_METHOD(getEnvironmentDirs:(RCTResponseSenderBlock) callback) {
350 359
 RCT_EXPORT_METHOD(cancelRequest:(NSString *)taskId callback:(RCTResponseSenderBlock)callback) {
351 360
     [RNFetchBlobNetwork cancelRequest:taskId];
352 361
     callback(@[[NSNull null], taskId]);
353
-    
362
+
354 363
 }
355 364
 
356 365
 #pragma mark RNFetchBlob private methods

+ 1
- 0
src/ios/RNFetchBlobConst.h Näytä tiedosto

@@ -27,6 +27,7 @@ extern NSString *const CONFIG_FILE_PATH;
27 27
 extern NSString *const CONFIG_FILE_EXT;
28 28
 extern NSString *const CONFIG_TRUSTY;
29 29
 extern NSString *const CONFIG_INDICATOR;
30
+extern NSString *const CONFIG_KEY;
30 31
 
31 32
 // fs events
32 33
 extern NSString *const FS_EVENT_DATA;

+ 1
- 0
src/ios/RNFetchBlobConst.m Näytä tiedosto

@@ -19,6 +19,7 @@ extern NSString *const CONFIG_FILE_PATH = @"path";
19 19
 extern NSString *const CONFIG_FILE_EXT = @"appendExt";
20 20
 extern NSString *const CONFIG_TRUSTY = @"trusty";
21 21
 extern NSString *const CONFIG_INDICATOR = @"indicator";
22
+extern NSString *const CONFIG_KEY = "@key";
22 23
 
23 24
 
24 25
 extern NSString *const MSG_EVENT = @"RNFetchBlobMessage";

+ 43
- 14
src/ios/RNFetchBlobNetwork.m Näytä tiedosto

@@ -14,6 +14,7 @@
14 14
 #import "RNFetchBlobFS.h"
15 15
 #import "RNFetchBlobNetwork.h"
16 16
 #import "RNFetchBlobConst.h"
17
+#import <CommonCrypto/CommonDigest.h>
17 18
 
18 19
 ////////////////////////////////////////
19 20
 //
@@ -64,15 +65,27 @@ NSOperationQueue *taskQueue;
64 65
 
65 66
 // removing case from headers
66 67
 + (NSMutableDictionary *) normalizeHeaders:(NSDictionary *)headers {
67
-    
68
+
68 69
     NSMutableDictionary * mheaders = [[NSMutableDictionary alloc]init];
69 70
     for(NSString * key in headers) {
70 71
         [mheaders setValue:[headers valueForKey:key] forKey:[key lowercaseString]];
71 72
     }
72
-    
73
+
73 74
     return mheaders;
74 75
 }
75 76
 
77
+- (NSString *)md5 {
78
+    const char* str = [self UTF8String];
79
+    unsigned char result[CC_MD5_DIGEST_LENGTH];
80
+    CC_MD5(str, (CC_LONG)strlen(str), result);
81
+
82
+    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
83
+    for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
84
+        [ret appendFormat:@"%02x",result[i]];
85
+    }
86
+    return ret;
87
+}
88
+
76 89
 // send HTTP request
77 90
 - (void) sendRequest:(NSDictionary  * _Nullable )options
78 91
        contentLength:(long) contentLength
@@ -88,25 +101,41 @@ NSOperationQueue *taskQueue;
88 101
     self.expectedBytes = 0;
89 102
     self.receivedBytes = 0;
90 103
     self.options = options;
91
-    
104
+
92 105
     NSString * path = [self.options valueForKey:CONFIG_FILE_PATH];
93 106
     NSString * ext = [self.options valueForKey:CONFIG_FILE_EXT];
107
+	NSString * key = [self.options valueForKey:CONFIG_KEY];
94 108
     NSURLSession * session;
95
-    
109
+
96 110
     bodyLength = contentLength;
97
-    
111
+
98 112
     // the session trust any SSL certification
99 113
 
100 114
     NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
101 115
     session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:[NSOperationQueue mainQueue]];
102
-    
116
+
103 117
     if(path != nil || [self.options valueForKey:CONFIG_USE_TEMP]!= nil)
104 118
     {
105 119
         respFile = YES;
120
+
121
+		NSString* cacheKey = taskId;
122
+		if (key != nil) {
123
+			cacheKey = [key md5];
124
+			if (cacheKey == nil) {
125
+				cacheKey = taskId;
126
+			}
127
+
128
+			destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
129
+            if ([[NSFileManager defaultManager] fileExistsAtPath:destPath]) {
130
+				callback([NSNull null], destPath]);
131
+                return;
132
+            }
133
+		}
134
+
106 135
         if(path != nil)
107 136
             destPath = path;
108
-        else
109
-            destPath = [RNFetchBlobFS getTempPath:taskId withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
137
+        // else
138
+        //     destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
110 139
     }
111 140
     else
112 141
     {
@@ -116,7 +145,7 @@ NSOperationQueue *taskQueue;
116 145
     NSURLSessionDataTask * task = [session dataTaskWithRequest:req];
117 146
     [taskTable setValue:task forKey:taskId];
118 147
     [task resume];
119
-    
148
+
120 149
     // network status indicator
121 150
     if([[options objectForKey:CONFIG_INDICATOR] boolValue] == YES)
122 151
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
@@ -135,7 +164,7 @@ NSOperationQueue *taskQueue;
135 164
 - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
136 165
 {
137 166
     expectedBytes = [response expectedContentLength];
138
-    
167
+
139 168
     if(respFile == YES)
140 169
     {
141 170
         NSFileManager * fm = [NSFileManager defaultManager];
@@ -163,7 +192,7 @@ NSOperationQueue *taskQueue;
163 192
     {
164 193
         [writeStream write:[data bytes] maxLength:[data length]];
165 194
     }
166
-    
195
+
167 196
     [self.bridge.eventDispatcher
168 197
      sendDeviceEventWithName:@"RNFetchBlobProgress"
169 198
      body:@{
@@ -172,7 +201,7 @@ NSOperationQueue *taskQueue;
172 201
             @"total": [NSString stringWithFormat:@"%d", expectedBytes]
173 202
             }
174 203
      ];
175
-    
204
+
176 205
 }
177 206
 
178 207
 - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
@@ -211,7 +240,7 @@ NSOperationQueue *taskQueue;
211 240
 }
212 241
 
213 242
 //- (void) application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
214
-//    
243
+//
215 244
 //}
216 245
 
217 246
 //- (void) URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
@@ -257,4 +286,4 @@ NSOperationQueue *taskQueue;
257 286
     }
258 287
 }
259 288
 
260
-@end
289
+@end

+ 9
- 0
src/ios/RNFetchBlobReqBuilder.h Näytä tiedosto

@@ -29,6 +29,15 @@
29 29
                      body:(NSString *)body
30 30
                onComplete:(void(^)(NSURLRequest * req, long bodyLength))onComplete;
31 31
 
32
++(void) buildEncodedRequest:(NSDictionary *)options
33
+                      taskId:(NSString *)taskId
34
+                      method:(NSString *)method
35
+                         url:(NSString *)url
36
+                     headers:(NSDictionary *)headers
37
+                        form:(NSString *)body
38
+                  onComplete:(void(^)(NSURLRequest * req, long bodyLength))onComplete;
39
+
40
+
32 41
 @end
33 42
 
34 43
 #endif /* RNFetchBlobReqBuilder_h */

+ 24
- 10
src/ios/RNFetchBlobReqBuilder.m Näytä tiedosto

@@ -14,7 +14,7 @@
14 14
 
15 15
 @interface RNFetchBlobReqBuilder()
16 16
 {
17
-    
17
+
18 18
 }
19 19
 @end
20 20
 
@@ -36,7 +36,7 @@
36 36
     NSMutableDictionary *mheaders = [[NSMutableDictionary alloc] initWithDictionary:[RNFetchBlobNetwork normalizeHeaders:headers]];
37 37
     NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
38 38
     NSNumber * timeStampObj = [NSNumber numberWithDouble: timeStamp];
39
-    
39
+
40 40
     // generate boundary
41 41
     NSString * boundary = [NSString stringWithFormat:@"RNFetchBlob%d", timeStampObj];
42 42
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
@@ -58,7 +58,7 @@
58 58
             [request setAllHTTPHeaderFields:mheaders];
59 59
             onComplete(request, [formData length]);
60 60
         }];
61
-        
61
+
62 62
     });
63 63
 }
64 64
 
@@ -76,7 +76,7 @@
76 76
     NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
77 77
                                     initWithURL:[NSURL
78 78
                                                  URLWithString: encodedUrl]];
79
-    
79
+
80 80
     NSMutableDictionary *mheaders = [[NSMutableDictionary alloc] initWithDictionary:[RNFetchBlobNetwork normalizeHeaders:headers]];
81 81
     // move heavy task to another thread
82 82
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
@@ -86,7 +86,7 @@
86 86
         if([[method lowercaseString] isEqualToString:@"post"] || [[method lowercaseString] isEqualToString:@"put"]) {
87 87
             // generate octet-stream body
88 88
             if(body != nil) {
89
-                
89
+
90 90
                 // when body is a string contains file path prefix, try load file from the path
91 91
                 if([body hasPrefix:FILE_PREFIX]) {
92 92
                     NSString * orgPath = [body substringFromIndex:[FILE_PREFIX length]];
@@ -110,19 +110,33 @@
110 110
                     blobData = [[NSData alloc] initWithBase64EncodedString:body options:0];
111 111
                     [request setHTTPBody:blobData];
112 112
                 }
113
-                
113
+
114 114
                 [mheaders setValue:@"application/octet-stream" forKey:@"content-type"];
115
-                
115
+
116 116
             }
117 117
         }
118
-        
118
+
119 119
         [request setHTTPMethod: method];
120 120
         [request setAllHTTPHeaderFields:mheaders];
121
-        
121
+
122 122
         onComplete(request, size);
123 123
     });
124 124
 }
125 125
 
126
++(void) buildEncodedRequest:(NSDictionary *)options
127
+                   taskId:(NSString *)taskId
128
+                   method:(NSString *)method
129
+                      url:(NSString *)url
130
+                  headers:(NSDictionary *)headers
131
+                     body:(NSString *)body
132
+               onComplete:(void(^)(NSURLRequest * req, long bodyLength))onComplete
133
+{
134
+	NSMutableData * formData = [[NSMutableData alloc] init];
135
+	[formData appendData:[[NSString stringWithFormat:@"%@", body] dataUsingEncoding:NSUTF8StringEncoding]];
136
+	onComplete(formData);
137
+}
138
+
139
+
126 140
 +(void) buildFormBody:(NSArray *)form boundary:(NSString *)boundary onComplete:(void(^)(NSData * formData))onComplete
127 141
 {
128 142
     NSMutableData * formData = [[NSMutableData alloc] init];
@@ -189,7 +203,7 @@
189 203
             }
190 204
             else
191 205
                 onComplete(formData);
192
-            
206
+
193 207
         };
194 208
         getFieldData([form objectAtIndex:i]);
195 209
     }