/
BlobModule.java
382 lines (324 loc) · 11.7 KB
/
BlobModule.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
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.modules.blob;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.webkit.MimeTypeMap;
import androidx.annotation.Nullable;
import com.facebook.fbreact.specs.NativeBlobModuleSpec;
import com.facebook.proguard.annotations.DoNotStrip;
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.common.MapBuilder;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.modules.network.NetworkingModule;
import com.facebook.react.modules.websocket.WebSocketModule;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okio.ByteString;
@ReactModule(name = BlobModule.NAME)
public class BlobModule extends NativeBlobModuleSpec {
public static final String NAME = "BlobModule";
private final Map<String, byte[]> mBlobs = new HashMap<>();
private final WebSocketModule.ContentHandler mWebSocketContentHandler =
new WebSocketModule.ContentHandler() {
@Override
public void onMessage(String text, WritableMap params) {
params.putString("data", text);
}
@Override
public void onMessage(ByteString bytes, WritableMap params) {
byte[] data = bytes.toByteArray();
WritableMap blob = Arguments.createMap();
blob.putString("blobId", store(data));
blob.putInt("offset", 0);
blob.putInt("size", data.length);
params.putMap("data", blob);
params.putString("type", "blob");
}
};
private final NetworkingModule.UriHandler mNetworkingUriHandler =
new NetworkingModule.UriHandler() {
@Override
public boolean supports(Uri uri, String responseType) {
String scheme = uri.getScheme();
boolean isRemote = "http".equals(scheme) || "https".equals(scheme);
return (!isRemote && "blob".equals(responseType));
}
@Override
public WritableMap fetch(Uri uri) throws IOException {
byte[] data = getBytesFromUri(uri);
WritableMap blob = Arguments.createMap();
blob.putString("blobId", store(data));
blob.putInt("offset", 0);
blob.putInt("size", data.length);
blob.putString("type", getMimeTypeFromUri(uri));
// Needed for files
blob.putString("name", getNameFromUri(uri));
blob.putDouble("lastModified", getLastModifiedFromUri(uri));
return blob;
}
};
private final NetworkingModule.RequestBodyHandler mNetworkingRequestBodyHandler =
new NetworkingModule.RequestBodyHandler() {
@Override
public boolean supports(ReadableMap data) {
return data.hasKey("blob");
}
@Override
public RequestBody toRequestBody(ReadableMap data, String contentType) {
String type = contentType;
if (data.hasKey("type") && !data.getString("type").isEmpty()) {
type = data.getString("type");
}
if (type == null) {
type = "application/octet-stream";
}
ReadableMap blob = data.getMap("blob");
String blobId = blob.getString("blobId");
byte[] bytes = resolve(blobId, blob.getInt("offset"), blob.getInt("size"));
return RequestBody.create(MediaType.parse(type), bytes);
}
};
private final NetworkingModule.ResponseHandler mNetworkingResponseHandler =
new NetworkingModule.ResponseHandler() {
@Override
public boolean supports(String responseType) {
return "blob".equals(responseType);
}
@Override
public WritableMap toResponseData(ResponseBody body) throws IOException {
byte[] data = body.bytes();
WritableMap blob = Arguments.createMap();
blob.putString("blobId", store(data));
blob.putInt("offset", 0);
blob.putInt("size", data.length);
return blob;
}
};
public BlobModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public void initialize() {
BlobCollector.install(getReactApplicationContext(), this);
}
@Override
public String getName() {
return NAME;
}
@Override
public @Nullable Map<String, Object> getTypedExportedConstants() {
// The application can register BlobProvider as a ContentProvider so that blobs are resolvable.
// If it does, it needs to tell us what authority was used via this string resource.
Resources resources = getReactApplicationContext().getResources();
String packageName = getReactApplicationContext().getPackageName();
int resourceId = resources.getIdentifier("blob_provider_authority", "string", packageName);
if (resourceId == 0) {
return MapBuilder.<String, Object>of();
}
return MapBuilder.<String, Object>of(
"BLOB_URI_SCHEME", "content", "BLOB_URI_HOST", resources.getString(resourceId));
}
public String store(byte[] data) {
String blobId = UUID.randomUUID().toString();
store(data, blobId);
return blobId;
}
public void store(byte[] data, String blobId) {
synchronized (mBlobs) {
mBlobs.put(blobId, data);
}
}
@DoNotStrip
public void remove(String blobId) {
synchronized (mBlobs) {
mBlobs.remove(blobId);
}
}
public @Nullable byte[] resolve(Uri uri) {
String blobId = uri.getLastPathSegment();
int offset = 0;
int size = -1;
String offsetParam = uri.getQueryParameter("offset");
if (offsetParam != null) {
offset = Integer.parseInt(offsetParam, 10);
}
String sizeParam = uri.getQueryParameter("size");
if (sizeParam != null) {
size = Integer.parseInt(sizeParam, 10);
}
return resolve(blobId, offset, size);
}
public @Nullable byte[] resolve(String blobId, int offset, int size) {
synchronized (mBlobs) {
byte[] data = mBlobs.get(blobId);
if (data == null) {
return null;
}
if (size == -1) {
size = data.length - offset;
}
if (offset > 0 || size != data.length) {
data = Arrays.copyOfRange(data, offset, offset + size);
}
return data;
}
}
public @Nullable byte[] resolve(ReadableMap blob) {
return resolve(blob.getString("blobId"), blob.getInt("offset"), blob.getInt("size"));
}
private byte[] getBytesFromUri(Uri contentUri) throws IOException {
InputStream is = getReactApplicationContext().getContentResolver().openInputStream(contentUri);
if (is == null) {
throw new FileNotFoundException("File not found for " + contentUri);
}
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len;
while ((len = is.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
private String getNameFromUri(Uri contentUri) {
if ("file".equals(contentUri.getScheme())) {
return contentUri.getLastPathSegment();
}
String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME};
Cursor metaCursor =
getReactApplicationContext()
.getContentResolver()
.query(contentUri, projection, null, null, null);
if (metaCursor != null) {
try {
if (metaCursor.moveToFirst()) {
return metaCursor.getString(0);
}
} finally {
metaCursor.close();
}
}
return contentUri.getLastPathSegment();
}
private long getLastModifiedFromUri(Uri contentUri) {
if ("file".equals(contentUri.getScheme())) {
return new File(contentUri.toString()).lastModified();
}
return 0;
}
private String getMimeTypeFromUri(Uri contentUri) {
String type = getReactApplicationContext().getContentResolver().getType(contentUri);
if (type == null) {
String ext = MimeTypeMap.getFileExtensionFromUrl(contentUri.getPath());
if (ext != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
}
}
if (type == null) {
type = "";
}
return type;
}
private WebSocketModule getWebSocketModule(String reason) {
ReactApplicationContext reactApplicationContext = getReactApplicationContextIfActiveOrWarn();
if (reactApplicationContext != null) {
return reactApplicationContext.getNativeModule(WebSocketModule.class);
}
return null;
}
@Override
public void addNetworkingHandler() {
ReactApplicationContext reactApplicationContext = getReactApplicationContextIfActiveOrWarn();
if (reactApplicationContext != null) {
NetworkingModule networkingModule =
reactApplicationContext.getNativeModule(NetworkingModule.class);
networkingModule.addUriHandler(mNetworkingUriHandler);
networkingModule.addRequestBodyHandler(mNetworkingRequestBodyHandler);
networkingModule.addResponseHandler(mNetworkingResponseHandler);
}
}
@Override
public void addWebSocketHandler(final double idDouble) {
final int id = (int) idDouble;
WebSocketModule webSocketModule = getWebSocketModule("addWebSocketHandler");
if (webSocketModule != null) {
webSocketModule.setContentHandler(id, mWebSocketContentHandler);
}
}
@Override
public void removeWebSocketHandler(final double idDouble) {
final int id = (int) idDouble;
WebSocketModule webSocketModule = getWebSocketModule("removeWebSocketHandler");
if (webSocketModule != null) {
webSocketModule.setContentHandler(id, null);
}
}
@Override
public void sendOverSocket(ReadableMap blob, double idDouble) {
int id = (int) idDouble;
WebSocketModule webSocketModule = getWebSocketModule("sendOverSocket");
if (webSocketModule != null) {
byte[] data = resolve(blob.getString("blobId"), blob.getInt("offset"), blob.getInt("size"));
if (data != null) {
webSocketModule.sendBinary(ByteString.of(data), id);
} else {
webSocketModule.sendBinary((ByteString) null, id);
}
}
}
@Override
public void createFromParts(ReadableArray parts, String blobId) {
int totalBlobSize = 0;
ArrayList<byte[]> partList = new ArrayList<>(parts.size());
for (int i = 0; i < parts.size(); i++) {
ReadableMap part = parts.getMap(i);
switch (part.getString("type")) {
case "blob":
ReadableMap blob = part.getMap("data");
totalBlobSize += blob.getInt("size");
partList.add(i, resolve(blob));
break;
case "string":
byte[] bytes = part.getString("data").getBytes(Charset.forName("UTF-8"));
totalBlobSize += bytes.length;
partList.add(i, bytes);
break;
default:
throw new IllegalArgumentException("Invalid type for blob: " + part.getString("type"));
}
}
ByteBuffer buffer = ByteBuffer.allocate(totalBlobSize);
for (byte[] bytes : partList) {
buffer.put(bytes);
}
store(buffer.array(), blobId);
}
@Override
public void release(String blobId) {
remove(blobId);
}
}