From a89f67fe9c34bde4b878f7f3b284fcccfe0c5aff Mon Sep 17 00:00:00 2001 From: Fabrizio Cucci Date: Tue, 15 Apr 2025 15:05:38 -0700 Subject: [PATCH] Kotlinify BlobModule Summary: As per title. Changelog: [Internal] Reviewed By: rshest Differential Revision: D72866832 fbshipit-source-id: 7e67224859a4526ce535f6fc1b17daa08ee1a046 --- .../ReactAndroid/api/ReactAndroid.api | 21 +- .../react/modules/blob/BlobModule.java | 423 ------------------ .../facebook/react/modules/blob/BlobModule.kt | 342 ++++++++++++++ 3 files changed, 355 insertions(+), 431 deletions(-) delete mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobModule.java create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobModule.kt diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index 08fc78ea5a8..9389778db0f 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -2641,23 +2641,28 @@ public abstract interface class com/facebook/react/modules/appregistry/AppRegist public abstract fun unmountApplicationComponentAtRootTag (I)V } -public class com/facebook/react/modules/blob/BlobModule : com/facebook/fbreact/specs/NativeBlobModuleSpec { +public final class com/facebook/react/modules/blob/BlobModule : com/facebook/fbreact/specs/NativeBlobModuleSpec { + public static final field Companion Lcom/facebook/react/modules/blob/BlobModule$Companion; + public static final field NAME Ljava/lang/String; public fun (Lcom/facebook/react/bridge/ReactApplicationContext;)V public fun addNetworkingHandler ()V public fun addWebSocketHandler (D)V public fun createFromParts (Lcom/facebook/react/bridge/ReadableArray;Ljava/lang/String;)V - public fun getLengthOfBlob (Ljava/lang/String;)J + public final fun getLengthOfBlob (Ljava/lang/String;)J public fun getTypedExportedConstants ()Ljava/util/Map; public fun initialize ()V public fun release (Ljava/lang/String;)V - public fun remove (Ljava/lang/String;)V + public final fun remove (Ljava/lang/String;)V public fun removeWebSocketHandler (D)V - public fun resolve (Landroid/net/Uri;)[B - public fun resolve (Lcom/facebook/react/bridge/ReadableMap;)[B - public fun resolve (Ljava/lang/String;II)[B + public final fun resolve (Landroid/net/Uri;)[B + public final fun resolve (Lcom/facebook/react/bridge/ReadableMap;)[B + public final fun resolve (Ljava/lang/String;II)[B public fun sendOverSocket (Lcom/facebook/react/bridge/ReadableMap;D)V - public fun store ([B)Ljava/lang/String; - public fun store ([BLjava/lang/String;)V + public final fun store ([B)Ljava/lang/String; + public final fun store ([BLjava/lang/String;)V +} + +public final class com/facebook/react/modules/blob/BlobModule$Companion { } public final class com/facebook/react/modules/blob/BlobProvider : android/content/ContentProvider { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobModule.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobModule.java deleted file mode 100644 index 9c024a75a54..00000000000 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobModule.java +++ /dev/null @@ -1,423 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and 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.infer.annotation.Assertions; -import com.facebook.infer.annotation.Nullsafe; -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; - -@Nullsafe(Nullsafe.Mode.LOCAL) -@ReactModule(name = NativeBlobModuleSpec.NAME) -public class BlobModule extends NativeBlobModuleSpec { - - private final Map 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, @Nullable String contentType) { - String type = contentType; - if (data.hasKey("type") - && data.getString("type") != null - && !data.getString("type").isEmpty()) { - type = data.getString("type"); - } - if (type == null) { - type = "application/octet-stream"; - } - ReadableMap blob = data.getMap("blob"); - - // supports() ensures blob is not null, but for nullability we have to check it - Assertions.assertNotNull(blob, "Blob is null even though supports() returned true"); - - byte[] bytes = - resolve(blob.getString("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 Map 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.of(); - } - - return MapBuilder.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 long getLengthOfBlob(String blobId) { - synchronized (mBlobs) { - byte[] data = mBlobs.get(blobId); - return data != null ? data.length : 0; - } - } - - @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(@Nullable 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); - } - - try { - // Allocate a buffer upto the number of bytes that can be read without blocking - // available() typically returns the file size if the uri represents an underlying file (i.e. - // is instanceof FileInputStream) - byte[] buffer = - new byte - [Math.max( - 1024, - is.available())]; // fallback to 1024 if available returns 0 or a small size. - int len; - byte[] prevBuffer = new byte[1024]; - int prevLen = 0; - - ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); - while ((len = is.read(buffer)) != -1) { - // this performs a no-op on the first iteration of while. prevLen is zero - byteBuffer.write(prevBuffer, 0, prevLen); - // swap buffers. - byte[] temp = prevBuffer; - prevBuffer = buffer; - buffer = temp; - // set prevLen = length of data in prevBuffer - prevLen = len; - } - - if (byteBuffer.size() == 0 && prevBuffer.length == prevLen) { - // If EOF AND prevBuffer contains entire stream avoid using ByteArrayOutputStream - return prevBuffer; - } - byteBuffer.write(prevBuffer, 0, prevLen); - return byteBuffer.toByteArray(); - } finally { - is.close(); - } - } - - private @Nullable 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 @Nullable 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); - Assertions.assertNotNull(networkingModule, "NetworkingModule is null"); - 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); - } - } - } - - @Override - public void createFromParts(ReadableArray parts, String blobId) { - int totalBlobSize = 0; - ArrayList partList = new ArrayList<>(parts.size()); - for (int i = 0; i < parts.size(); i++) { - ReadableMap part = parts.getMap(i); - Assertions.assertNotNull(part, "Blob part is null"); - String type = part.getString("type"); - Assertions.assertNotNull(type, "Invalid type for blob: null"); - switch (type) { - case "blob": - ReadableMap blob = part.getMap("data"); - Assertions.assertNotNull(blob, "Blob is null"); - totalBlobSize += blob.getInt("size"); - partList.add(i, resolve(blob)); - break; - case "string": - String data = part.getString("data"); - Assertions.assertNotNull(data, "Data is null"); - byte[] bytes = 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); - } -} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobModule.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobModule.kt new file mode 100644 index 00000000000..2524e819f1f --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobModule.kt @@ -0,0 +1,342 @@ +/* + * Copyright (c) Meta Platforms, Inc. and 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.net.Uri +import android.provider.MediaStore +import android.webkit.MimeTypeMap +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.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.nio.ByteBuffer +import java.nio.charset.Charset +import java.util.ArrayList +import java.util.Arrays +import java.util.HashMap +import java.util.UUID +import okhttp3.MediaType +import okhttp3.RequestBody +import okhttp3.ResponseBody +import okio.ByteString + +@ReactModule(name = NativeBlobModuleSpec.NAME) +public class BlobModule(reactContext: ReactApplicationContext) : + NativeBlobModuleSpec(reactContext) { + + private val blobs = HashMap() + + private val webSocketContentHandler = + object : WebSocketModule.ContentHandler { + override fun onMessage(text: String, params: WritableMap) { + params.putString("data", text) + } + + override fun onMessage(bytes: ByteString, params: WritableMap) { + val data = bytes.toByteArray() + + val blob = Arguments.createMap() + blob.putString("blobId", store(data)) + blob.putInt("offset", 0) + blob.putInt("size", data.size) + + params.putMap("data", blob) + params.putString("type", "blob") + } + } + + private val networkingUriHandler = + object : NetworkingModule.UriHandler { + override fun supports(uri: Uri, responseType: String): Boolean { + val scheme = uri.scheme + val isRemote = scheme == "http" || scheme == "https" + return !isRemote && responseType == "blob" + } + + override fun fetch(uri: Uri): WritableMap { + val data = getBytesFromUri(uri) + + val blob = Arguments.createMap() + blob.putString("blobId", store(data)) + blob.putInt("offset", 0) + blob.putInt("size", data.size) + blob.putString("type", getMimeTypeFromUri(uri)) + + // Needed for files + blob.putString("name", getNameFromUri(uri)) + blob.putDouble("lastModified", getLastModifiedFromUri(uri)) + + return blob + } + } + + private val networkingRequestBodyHandler = + object : NetworkingModule.RequestBodyHandler { + override fun supports(data: ReadableMap): Boolean { + return data.hasKey("blob") + } + + override fun toRequestBody(data: ReadableMap, contentType: String?): RequestBody { + var type: String? = contentType + if (data.hasKey("type") && !data.getString("type").isNullOrEmpty()) { + type = data.getString("type") + } + if (type == null) { + type = "application/octet-stream" + } + + val blob = checkNotNull(data.getMap("blob")) + val bytes = + checkNotNull( + resolve(blob.getString("blobId"), blob.getInt("offset"), blob.getInt("size"))) + + return RequestBody.create(MediaType.parse(type), bytes) + } + } + + private val networkingResponseHandler = + object : NetworkingModule.ResponseHandler { + override fun supports(responseType: String): Boolean { + return responseType == "blob" + } + + override fun toResponseData(body: ResponseBody): WritableMap { + val data = body.bytes() + val blob = Arguments.createMap() + blob.putString("blobId", store(data)) + blob.putInt("offset", 0) + blob.putInt("size", data.size) + return blob + } + } + + public override fun initialize() { + BlobCollector.install(getReactApplicationContext(), this) + } + + public override fun getTypedExportedConstants(): Map { + val resources = getReactApplicationContext().resources + val packageName = getReactApplicationContext().packageName + val resourceId = resources.getIdentifier("blob_provider_authority", "string", packageName) + if (resourceId == 0) { + return mapOf() + } + + return mapOf("BLOB_URI_SCHEME" to "content", "BLOB_URI_HOST" to resources.getString(resourceId)) + } + + public fun store(data: ByteArray): String { + val blobId = UUID.randomUUID().toString() + store(data, blobId) + return blobId + } + + public fun store(data: ByteArray, blobId: String) { + synchronized(blobs) { blobs[blobId] = data } + } + + @DoNotStrip + public fun getLengthOfBlob(blobId: String): Long { + synchronized(blobs) { + val data = blobs[blobId] + return data?.size?.toLong() ?: 0 + } + } + + @DoNotStrip + public fun remove(blobId: String) { + synchronized(blobs) { blobs.remove(blobId) } + } + + public fun resolve(uri: Uri): ByteArray? { + val blobId = uri.lastPathSegment + var offset = 0 + var size = -1 + val offsetParam = uri.getQueryParameter("offset") + if (offsetParam != null) { + offset = offsetParam.toInt() + } + val sizeParam = uri.getQueryParameter("size") + if (sizeParam != null) { + size = sizeParam.toInt() + } + return resolve(blobId, offset, size) + } + + public fun resolve(blobId: String?, offset: Int, size: Int): ByteArray? { + synchronized(blobs) { + val data = blobs[blobId] + if (data == null) { + return null + } + var newSize = size + if (newSize == -1) { + newSize = data.size - offset + } + if (offset > 0 || newSize != data.size) { + return Arrays.copyOfRange(data, offset, offset + newSize) + } + return data + } + } + + public fun resolve(blob: ReadableMap): ByteArray? { + return resolve(blob.getString("blobId"), blob.getInt("offset"), blob.getInt("size")) + } + + @Throws(IOException::class) + private fun getBytesFromUri(contentUri: Uri): ByteArray { + val inputStream = + getReactApplicationContext().contentResolver.openInputStream(contentUri) + ?: throw FileNotFoundException("File not found for $contentUri") + + try { + var buffer = ByteArray(maxOf(1024, inputStream.available())) + var len: Int + var prevBuffer = ByteArray(1024) + var prevLen = 0 + + val byteBuffer = ByteArrayOutputStream() + while (inputStream.read(buffer).also { len = it } != -1) { + byteBuffer.write(prevBuffer, 0, prevLen) + // swap buffers + val temp = prevBuffer + prevBuffer = buffer + buffer = temp + // set prevLen = length of data in prevBuffer + prevLen = len + } + + if (byteBuffer.size() == 0 && prevBuffer.size == prevLen) { + // If EOF AND prevBuffer contains entire stream avoid using ByteArrayOutputStream + return prevBuffer + } + byteBuffer.write(prevBuffer, 0, prevLen) + return byteBuffer.toByteArray() + } finally { + inputStream.close() + } + } + + private fun getNameFromUri(contentUri: Uri): String? { + if (contentUri.scheme == "file") { + return contentUri.lastPathSegment + } + val projection = arrayOf(MediaStore.MediaColumns.DISPLAY_NAME) + val metaCursor = + getReactApplicationContext().contentResolver.query(contentUri, projection, null, null, null) + metaCursor?.use { + if (it.moveToFirst()) { + return it.getString(0) + } + } + return contentUri.lastPathSegment + } + + private fun getLastModifiedFromUri(contentUri: Uri): Double { + return if (contentUri.scheme == "file") { + File(contentUri.toString()).lastModified().toDouble() + } else 0.0 + } + + private fun getMimeTypeFromUri(contentUri: Uri): String { + var type = getReactApplicationContext().contentResolver.getType(contentUri) + if (type == null) { + val ext = MimeTypeMap.getFileExtensionFromUrl(contentUri.path) + if (ext != null) { + type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext) + } + } + return type.orEmpty() + } + + private fun getWebSocketModule(reason: String): WebSocketModule? { + val reactApplicationContext = getReactApplicationContext() + return reactApplicationContext?.getNativeModule(WebSocketModule::class.java) + } + + public override fun addNetworkingHandler() { + val reactApplicationContext = getReactApplicationContext() + + reactApplicationContext?.let { + val networkingModule = checkNotNull(it.getNativeModule(NetworkingModule::class.java)) + networkingModule.addUriHandler(networkingUriHandler) + networkingModule.addRequestBodyHandler(networkingRequestBodyHandler) + networkingModule.addResponseHandler(networkingResponseHandler) + } + } + + public override fun addWebSocketHandler(idDouble: Double) { + val id = idDouble.toInt() + val webSocketModule = getWebSocketModule("addWebSocketHandler") + webSocketModule?.setContentHandler(id, webSocketContentHandler) + } + + public override fun removeWebSocketHandler(idDouble: Double) { + val id = idDouble.toInt() + val webSocketModule = getWebSocketModule("removeWebSocketHandler") + webSocketModule?.setContentHandler(id, null) + } + + public override fun sendOverSocket(blob: ReadableMap, idDouble: Double) { + val id = idDouble.toInt() + val webSocketModule = getWebSocketModule("sendOverSocket") + webSocketModule?.let { + val data = resolve(blob.getString("blobId"), blob.getInt("offset"), blob.getInt("size")) + data?.let { bytes -> it.sendBinary(ByteString.of(ByteBuffer.wrap(bytes)), id) } + } + } + + public override fun createFromParts(parts: ReadableArray, blobId: String): Unit { + var totalBlobSize = 0 + val partList = ArrayList(parts.size()) + + for (i in 0 until parts.size()) { + val part = checkNotNull(parts.getMap(i)) + val type = checkNotNull(part.getString("type")) + when (type) { + "blob" -> { + val blob = checkNotNull(part.getMap("data")) + totalBlobSize += blob.getInt("size") + partList.add(i, checkNotNull(resolve(blob))) + } + "string" -> { + val data = checkNotNull(part.getString("data")) + val bytes = data.toByteArray(Charset.forName("UTF-8")) + totalBlobSize += bytes.size + partList.add(i, bytes) + } + else -> throw IllegalArgumentException("Invalid type for blob: ${part.getString("type")}") + } + } + + val buffer = ByteBuffer.allocate(totalBlobSize) + for (bytes in partList) { + buffer.put(bytes) + } + store(buffer.array(), blobId) + } + + public override fun release(blobId: String) { + remove(blobId) + } + + public companion object { + public const val NAME: String = NativeBlobModuleSpec.NAME + } +}