This repository has been archived by the owner on Mar 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
RNFetchBlobBody.java
387 lines (353 loc) · 13.7 KB
/
RNFetchBlobBody.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package com.RNFetchBlob;
import android.util.Base64;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;
public class RNFetchBlobBody extends RequestBody{
InputStream requestStream;
long contentLength = 0;
ReadableArray form;
String mTaskId;
String rawBody;
RNFetchBlobReq.RequestType requestType;
MediaType mime;
File bodyCache;
int reported = 0;
Boolean chunkedEncoding = false;
public RNFetchBlobBody(String taskId) {
this.mTaskId = taskId;
}
RNFetchBlobBody chunkedEncoding(boolean val) {
this.chunkedEncoding = val;
return this;
}
RNFetchBlobBody setMIME(MediaType mime) {
this.mime = mime;
return this;
}
RNFetchBlobBody setRequestType( RNFetchBlobReq.RequestType type) {
this.requestType = type;
return this;
}
/**
* Set request body
* @param body A string represents the request body
* @return object itself
*/
RNFetchBlobBody setBody(String body) {
this.rawBody = body;
if(rawBody == null) {
this.rawBody = "";
requestType = RNFetchBlobReq.RequestType.AsIs;
}
try {
switch (requestType) {
case SingleFile:
requestStream = getReuqestStream();
contentLength = requestStream.available();
break;
case AsIs:
contentLength = this.rawBody.getBytes().length;
requestStream = new ByteArrayInputStream(this.rawBody.getBytes());
break;
case Others:
break;
}
} catch(Exception ex) {
ex.printStackTrace();
RNFetchBlobUtils.emitWarningEvent("RNFetchBlob failed to create single content request body :" + ex.getLocalizedMessage() + "\r\n");
}
return this;
}
/**
* Set request body (Array)
* @param body A Readable array contains form data
* @return object itself
*/
RNFetchBlobBody setBody(ReadableArray body) {
this.form = body;
try {
bodyCache = createMultipartBodyCache();
requestStream = new FileInputStream(bodyCache);
contentLength = bodyCache.length();
} catch(Exception ex) {
ex.printStackTrace();
RNFetchBlobUtils.emitWarningEvent("RNFetchBlob failed to create request multipart body :" + ex.getLocalizedMessage());
}
return this;
}
@Override
public long contentLength() {
return chunkedEncoding ? -1 : contentLength;
}
@Override
public MediaType contentType() {
return mime;
}
@Override
public void writeTo(BufferedSink sink) {
try {
pipeStreamToSink(requestStream, sink);
} catch(Exception ex) {
RNFetchBlobUtils.emitWarningEvent(ex.getLocalizedMessage());
ex.printStackTrace();
}
}
boolean clearRequestBody() {
try {
if (bodyCache != null && bodyCache.exists()) {
bodyCache.delete();
}
} catch(Exception e) {
RNFetchBlobUtils.emitWarningEvent(e.getLocalizedMessage());
return false;
}
return true;
}
private InputStream getReuqestStream() throws Exception {
// upload from storage
if (rawBody.startsWith(RNFetchBlobConst.FILE_PREFIX)) {
String orgPath = rawBody.substring(RNFetchBlobConst.FILE_PREFIX.length());
orgPath = RNFetchBlobFS.normalizePath(orgPath);
// upload file from assets
if (RNFetchBlobFS.isAsset(orgPath)) {
try {
String assetName = orgPath.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
return RNFetchBlob.RCTContext.getAssets().open(assetName);
} catch (Exception e) {
throw new Exception("error when getting request stream from asset : " +e.getLocalizedMessage());
}
} else {
File f = new File(RNFetchBlobFS.normalizePath(orgPath));
try {
if(!f.exists())
f.createNewFile();
return new FileInputStream(f);
} catch (Exception e) {
throw new Exception("error when getting request stream: " +e.getLocalizedMessage());
}
}
}
// base 64 encoded
else {
try {
byte[] bytes = Base64.decode(rawBody, 0);
return new ByteArrayInputStream(bytes);
} catch(Exception ex) {
throw new Exception("error when getting request stream: " + ex.getLocalizedMessage());
}
}
}
/**
* Create a temp file that contains content of multipart form data content
* @return The cache file object
* @throws IOException
*/
private File createMultipartBodyCache() throws IOException {
String boundary = "RNFetchBlob-" + mTaskId;
File outputDir = RNFetchBlob.RCTContext.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("rnfb-form-tmp", "", outputDir);
FileOutputStream os = new FileOutputStream(outputFile);
ArrayList<FormField> fields = countFormDataLength();
ReactApplicationContext ctx = RNFetchBlob.RCTContext;
for(int i = 0;i < fields.size(); i++) {
FormField field = fields.get(i);
String data = field.data;
String name = field.name;
// skip invalid fields
if(name == null || data == null)
continue;
// form begin
String header = "--" + boundary + "\r\n";
if (field.filename != null) {
header += "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + field.filename + "\"\r\n";
header += "Content-Type: " + field.mime + "\r\n\r\n";
os.write(header.getBytes());
// file field header end
// upload from storage
if (data.startsWith(RNFetchBlobConst.FILE_PREFIX)) {
String orgPath = data.substring(RNFetchBlobConst.FILE_PREFIX.length());
orgPath = RNFetchBlobFS.normalizePath(orgPath);
// path starts with content://
if (RNFetchBlobFS.isAsset(orgPath)) {
try {
String assetName = orgPath.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
InputStream in = ctx.getAssets().open(assetName);
pipeStreamToFileStream(in, os);
} catch (IOException e) {
RNFetchBlobUtils.emitWarningEvent("Failed to create form data asset :" + orgPath + ", " + e.getLocalizedMessage() );
}
}
// data from normal files
else {
File file = new File(RNFetchBlobFS.normalizePath(orgPath));
if(file.exists()) {
FileInputStream fs = new FileInputStream(file);
pipeStreamToFileStream(fs, os);
}
else {
RNFetchBlobUtils.emitWarningEvent("Failed to create form data from path :" + orgPath + ", file not exists.");
}
}
}
// base64 embedded file content
else {
byte[] b = Base64.decode(data, 0);
os.write(b);
}
}
// data field
else {
header += "Content-Disposition: form-data; name=\"" + name + "\"\r\n";
header += "Content-Type: " + field.mime + "\r\n\r\n";
os.write(header.getBytes());
byte[] fieldData = field.data.getBytes();
os.write(fieldData);
}
// form end
os.write("\r\n".getBytes());
}
// close the form
byte[] end = ("--" + boundary + "--\r\n").getBytes();
os.write(end);
os.flush();
os.close();
return outputFile;
}
/**
* Pipe input stream to request body output stream
* @param stream The input stream
* @param sink The request body buffer sink
* @throws IOException
*/
private void pipeStreamToSink(InputStream stream, BufferedSink sink) throws Exception {
byte [] chunk = new byte[10240];
int totalWritten = 0;
int read;
while((read = stream.read(chunk, 0, 10240)) > 0) {
if(read > 0) {
sink.write(chunk, 0, read);
totalWritten += read;
emitUploadProgress(totalWritten);
}
}
stream.close();
}
/**
* Pipe input stream to a file
* @param is The input stream
* @param os The output stream to a file
* @throws IOException
*/
private void pipeStreamToFileStream(InputStream is, FileOutputStream os) throws IOException {
byte[] buf = new byte[10240];
int len;
while ((len = is.read(buf)) > 0) {
os.write(buf, 0, len);
}
is.close();
}
/**
* Compute approximate content length for form data
* @return
*/
private ArrayList<FormField> countFormDataLength() {
long total = 0;
ArrayList<FormField> list = new ArrayList<>();
ReactApplicationContext ctx = RNFetchBlob.RCTContext;
for(int i = 0;i < form.size(); i++) {
FormField field = new FormField(form.getMap(i));
list.add(field);
String data = field.data;
if(data == null) {
RNFetchBlobUtils.emitWarningEvent("RNFetchBlob multipart request builder has found a field without `data` property, the field `"+ field.name +"` will be removed implicitly.");
}
else if (field.filename != null) {
// upload from storage
if (data.startsWith(RNFetchBlobConst.FILE_PREFIX)) {
String orgPath = data.substring(RNFetchBlobConst.FILE_PREFIX.length());
orgPath = RNFetchBlobFS.normalizePath(orgPath);
// path starts with asset://
if (RNFetchBlobFS.isAsset(orgPath)) {
try {
String assetName = orgPath.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
long length = ctx.getAssets().open(assetName).available();
total += length;
} catch (IOException e) {
RNFetchBlobUtils.emitWarningEvent(e.getLocalizedMessage());
}
}
// general files
else {
File file = new File(RNFetchBlobFS.normalizePath(orgPath));
total += file.length();
}
}
// base64 embedded file content
else {
byte[] bytes = Base64.decode(data, 0);
total += bytes.length;
}
}
// data field
else {
total += field.data != null ? field.data.getBytes().length : 0;
}
}
contentLength = total;
return list;
}
/**
* Since ReadableMap could only be access once, we have to store the field into a map for
* repeatedly access.
*/
private class FormField {
public String name;
public String filename;
public String mime;
public String data;
public FormField(ReadableMap rawData) {
if(rawData.hasKey("name"))
name = rawData.getString("name");
if(rawData.hasKey("filename"))
filename = rawData.getString("filename");
if(rawData.hasKey("type"))
mime = rawData.getString("type");
else {
mime = filename == null ? "text/plain" : "application/octet-stream";
}
if(rawData.hasKey("data")) {
data = rawData.getString("data");
}
}
}
/**
* Emit progress event
* @param written
*/
private void emitUploadProgress(int written) {
RNFetchBlobProgressConfig config = RNFetchBlobReq.getReportUploadProgress(mTaskId);
if(config != null && contentLength != 0 && config.shouldReport((float)written/contentLength)) {
WritableMap args = Arguments.createMap();
args.putString("taskId", mTaskId);
args.putString("written", String.valueOf(written));
args.putString("total", String.valueOf(contentLength));
// emit event to js context
RNFetchBlob.RCTContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(RNFetchBlobConst.EVENT_UPLOAD_PROGRESS, args);
}
}
}