Add blob implementation with WebSocket integration

Summary:
This is the first PR from a series of PRs grabbou and me will make to add blob support to React Native. The next PR will include blob support for XMLHttpRequest.

I'd like to get this merged with minimal changes to preserve the attribution. My next PR can contain bigger changes.

Blobs are used to transfer binary data between server and client. Currently React Native lacks a way to deal with binary data. The only thing that comes close is uploading files through a URI.

Current workarounds to transfer binary data includes encoding and decoding them to base64 and and transferring them as string, which is not ideal, since it increases the payload size and the whole payload needs to be sent via the bridge every time changes are made.

The PR adds a way to deal with blobs via a new native module. The blob is constructed on the native side and the data never needs to pass through the bridge. Currently the only way to create a blob is to receive a blob from the server via websocket.

The PR is largely a direct port of https://github.com/silklabs/silk/tree/master/react-native-blobs by philikon into RN (with changes to integrate with RN), and attributed as such.

> **Note:** This is a breaking change for all people running iOS without CocoaPods. You will have to manually add `RCTBlob.xcodeproj` to your `Libraries` and then, add it to Build Phases. Just follow the process of manual linking. We'll also need to document this process in the release notes.

Related discussion - https://github.com/facebook/react-native/issues/11103

- `Image` can't show image when `URL.createObjectURL` is used with large images on Android

The websocket integration can be tested via a simple server,

```js
const fs = require('fs');
const http = require('http');

const WebSocketServer = require('ws').Server;

const wss = new WebSocketServer({
  server: http.createServer().listen(7232),
});

wss.on('connection', (ws) => {
  ws.on('message', (d) => {
    console.log(d);
  });

  ws.send(fs.readFileSync('./some-file'));
});
```

Then on the client,

```js
var ws = new WebSocket('ws://localhost:7232');

ws.binaryType = 'blob';

ws.onerror = (error) => {
  console.error(error);
};

ws.onmessage = (e) => {
  console.log(e.data);
  ws.send(e.data);
};
```

cc brentvatne ide
Closes https://github.com/facebook/react-native/pull/11417

Reviewed By: sahrens

Differential Revision: D5188484

Pulled By: javache

fbshipit-source-id: 6afcbc4d19aa7a27b0dc9d52701ba400e7d7e98f
This commit is contained in:
Philipp von Weitershausen
2017-07-26 08:12:12 -07:00
committed by Facebook Github Bot
parent 91493f6b9d
commit ed903099b4
26 changed files with 1800 additions and 307 deletions

153
Libraries/Blob/Blob.js Normal file
View File

@@ -0,0 +1,153 @@
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Blob
* @flow
*/
'use strict';
const invariant = require('fbjs/lib/invariant');
const uuid = require('uuid');
const { BlobModule } = require('NativeModules');
import type { BlobProps } from 'BlobTypes';
/**
* Opaque JS representation of some binary data in native.
*
* The API is modeled after the W3C Blob API, with one caveat
* regarding explicit deallocation. Refer to the `close()`
* method for further details.
*
* Example usage in a React component:
*
* class WebSocketImage extends React.Component {
* state = {blob: null};
* componentDidMount() {
* let ws = this.ws = new WebSocket(...);
* ws.binaryType = 'blob';
* ws.onmessage = (event) => {
* if (this.state.blob) {
* this.state.blob.close();
* }
* this.setState({blob: event.data});
* };
* }
* componentUnmount() {
* if (this.state.blob) {
* this.state.blob.close();
* }
* this.ws.close();
* }
* render() {
* if (!this.state.blob) {
* return <View />;
* }
* return <Image source={{uri: URL.createObjectURL(this.state.blob)}} />;
* }
* }
*
* Reference: https://developer.mozilla.org/en-US/docs/Web/API/Blob
*/
class Blob {
/**
* Size of the data contained in the Blob object, in bytes.
*/
size: number;
/*
* String indicating the MIME type of the data contained in the Blob.
* If the type is unknown, this string is empty.
*/
type: string;
/*
* Unique id to identify the blob on native side (non-standard)
*/
blobId: string;
/*
* Offset to indicate part of blob, used when sliced (non-standard)
*/
offset: number;
/**
* Construct blob instance from blob data from native.
* Used internally by modules like XHR, WebSocket, etc.
*/
static create(props: BlobProps): Blob {
return Object.assign(Object.create(Blob.prototype), props);
}
/**
* Constructor for JS consumers.
* Currently we only support creating Blobs from other Blobs.
* Reference: https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob
*/
constructor(parts: Array<Blob>, options: any) {
const blobId = uuid();
let size = 0;
parts.forEach((part) => {
invariant(part instanceof Blob, 'Can currently only create a Blob from other Blobs');
size += part.size;
});
BlobModule.createFromParts(parts, blobId);
return Blob.create({
blobId,
offset: 0,
size,
});
}
/*
* This method is used to create a new Blob object containing
* the data in the specified range of bytes of the source Blob.
* Reference: https://developer.mozilla.org/en-US/docs/Web/API/Blob/slice
*/
slice(start?: number, end?: number): Blob {
let offset = this.offset;
let size = this.size;
if (typeof start === 'number') {
if (start > size) {
start = size;
}
offset += start;
size -= start;
if (typeof end === 'number') {
if (end < 0) {
end = this.size + end;
}
size = end - start;
}
}
return Blob.create({
blobId: this.blobId,
offset,
size,
});
}
/**
* This method is in the standard, but not actually implemented by
* any browsers at this point. It's important for how Blobs work in
* React Native, however, since we cannot de-allocate resources automatically,
* so consumers need to explicitly de-allocate them.
*
* Note that the semantics around Blobs created via `blob.slice()`
* and `new Blob([blob])` are different. `blob.slice()` creates a
* new *view* onto the same binary data, so calling `close()` on any
* of those views is enough to deallocate the data, whereas
* `new Blob([blob, ...])` actually copies the data in memory.
*/
close() {
BlobModule.release(this.blobId);
}
}
module.exports = Blob;

View File

@@ -0,0 +1,25 @@
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule BlobTypes
* @flow
*/
'use strict';
export type BlobProps = {
blobId: string,
offset: number,
size: number,
type?: string,
};
export type FileProps = BlobProps & {
name: string,
lastModified: number,
};

View File

@@ -0,0 +1,344 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
AD0871131E215B28007D136D /* RCTBlobManager.h in Copy Headers */ = {isa = PBXBuildFile; fileRef = AD9A43C11DFC7126008DC588 /* RCTBlobManager.h */; };
AD0871161E215EC9007D136D /* RCTBlobManager.h in Headers */ = {isa = PBXBuildFile; fileRef = AD9A43C11DFC7126008DC588 /* RCTBlobManager.h */; };
AD0871181E215ED1007D136D /* RCTBlobManager.h in Headers */ = {isa = PBXBuildFile; fileRef = AD9A43C11DFC7126008DC588 /* RCTBlobManager.h */; };
AD08711A1E2162C8007D136D /* RCTBlobManager.h in Copy Headers */ = {isa = PBXBuildFile; fileRef = AD9A43C11DFC7126008DC588 /* RCTBlobManager.h */; };
AD9A43C31DFC7126008DC588 /* RCTBlobManager.m in Sources */ = {isa = PBXBuildFile; fileRef = AD9A43C21DFC7126008DC588 /* RCTBlobManager.m */; };
ADD01A711E09404A00F6D226 /* RCTBlobManager.m in Sources */ = {isa = PBXBuildFile; fileRef = AD9A43C21DFC7126008DC588 /* RCTBlobManager.m */; };
/* End PBXBuildFile section */
/* Begin PBXCopyFilesBuildPhase section */
358F4ED51D1E81A9004DF814 /* Copy Headers */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = include/RCTBlob;
dstSubfolderSpec = 16;
files = (
AD08711A1E2162C8007D136D /* RCTBlobManager.h in Copy Headers */,
);
name = "Copy Headers";
runOnlyForDeploymentPostprocessing = 0;
};
AD0871121E215B16007D136D /* Copy Headers */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = include/RCTBlob;
dstSubfolderSpec = 16;
files = (
AD0871131E215B28007D136D /* RCTBlobManager.h in Copy Headers */,
);
name = "Copy Headers";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
358F4ED71D1E81A9004DF814 /* libRCTBlob.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRCTBlob.a; sourceTree = BUILT_PRODUCTS_DIR; };
AD9A43C11DFC7126008DC588 /* RCTBlobManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RCTBlobManager.h; sourceTree = "<group>"; };
AD9A43C21DFC7126008DC588 /* RCTBlobManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RCTBlobManager.m; sourceTree = "<group>"; };
ADD01A681E09402E00F6D226 /* libRCTBlob-tvOS.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libRCTBlob-tvOS.a"; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */
/* Begin PBXGroup section */
358F4ECE1D1E81A9004DF814 = {
isa = PBXGroup;
children = (
AD9A43C11DFC7126008DC588 /* RCTBlobManager.h */,
AD9A43C21DFC7126008DC588 /* RCTBlobManager.m */,
358F4ED81D1E81A9004DF814 /* Products */,
);
sourceTree = "<group>";
};
358F4ED81D1E81A9004DF814 /* Products */ = {
isa = PBXGroup;
children = (
358F4ED71D1E81A9004DF814 /* libRCTBlob.a */,
ADD01A681E09402E00F6D226 /* libRCTBlob-tvOS.a */,
);
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXHeadersBuildPhase section */
AD0871151E215EB7007D136D /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
AD0871161E215EC9007D136D /* RCTBlobManager.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
AD0871171E215ECC007D136D /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
AD0871181E215ED1007D136D /* RCTBlobManager.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXHeadersBuildPhase section */
/* Begin PBXNativeTarget section */
358F4ED61D1E81A9004DF814 /* RCTBlob */ = {
isa = PBXNativeTarget;
buildConfigurationList = 358F4EE01D1E81A9004DF814 /* Build configuration list for PBXNativeTarget "RCTBlob" */;
buildPhases = (
AD0871151E215EB7007D136D /* Headers */,
358F4ED51D1E81A9004DF814 /* Copy Headers */,
358F4ED31D1E81A9004DF814 /* Sources */,
);
buildRules = (
);
dependencies = (
);
name = RCTBlob;
productName = SLKBlobs;
productReference = 358F4ED71D1E81A9004DF814 /* libRCTBlob.a */;
productType = "com.apple.product-type.library.static";
};
ADD01A671E09402E00F6D226 /* RCTBlob-tvOS */ = {
isa = PBXNativeTarget;
buildConfigurationList = ADD01A6E1E09402E00F6D226 /* Build configuration list for PBXNativeTarget "RCTBlob-tvOS" */;
buildPhases = (
AD0871171E215ECC007D136D /* Headers */,
AD0871121E215B16007D136D /* Copy Headers */,
ADD01A641E09402E00F6D226 /* Sources */,
);
buildRules = (
);
dependencies = (
);
name = "RCTBlob-tvOS";
productName = "RCTBlob-tvOS";
productReference = ADD01A681E09402E00F6D226 /* libRCTBlob-tvOS.a */;
productType = "com.apple.product-type.library.static";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
358F4ECF1D1E81A9004DF814 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0730;
ORGANIZATIONNAME = "Silk Labs";
TargetAttributes = {
358F4ED61D1E81A9004DF814 = {
CreatedOnToolsVersion = 7.3;
};
ADD01A671E09402E00F6D226 = {
CreatedOnToolsVersion = 8.2;
ProvisioningStyle = Automatic;
};
};
};
buildConfigurationList = 358F4ED21D1E81A9004DF814 /* Build configuration list for PBXProject "RCTBlob" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
en,
);
mainGroup = 358F4ECE1D1E81A9004DF814;
productRefGroup = 358F4ED81D1E81A9004DF814 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
358F4ED61D1E81A9004DF814 /* RCTBlob */,
ADD01A671E09402E00F6D226 /* RCTBlob-tvOS */,
);
};
/* End PBXProject section */
/* Begin PBXSourcesBuildPhase section */
358F4ED31D1E81A9004DF814 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
AD9A43C31DFC7126008DC588 /* RCTBlobManager.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
ADD01A641E09402E00F6D226 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
ADD01A711E09404A00F6D226 /* RCTBlobManager.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
358F4EDE1D1E81A9004DF814 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
};
name = Debug;
};
358F4EDF1D1E81A9004DF814 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
358F4EE11D1E81A9004DF814 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
OTHER_LDFLAGS = "-ObjC";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
};
name = Debug;
};
358F4EE21D1E81A9004DF814 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
OTHER_LDFLAGS = "-ObjC";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
};
name = Release;
};
ADD01A6F1E09402E00F6D226 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
OTHER_LDFLAGS = "-ObjC";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos;
SKIP_INSTALL = YES;
TVOS_DEPLOYMENT_TARGET = 10.1;
};
name = Debug;
};
ADD01A701E09402E00F6D226 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
OTHER_LDFLAGS = "-ObjC";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos;
SKIP_INSTALL = YES;
TVOS_DEPLOYMENT_TARGET = 10.1;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
358F4ED21D1E81A9004DF814 /* Build configuration list for PBXProject "RCTBlob" */ = {
isa = XCConfigurationList;
buildConfigurations = (
358F4EDE1D1E81A9004DF814 /* Debug */,
358F4EDF1D1E81A9004DF814 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
358F4EE01D1E81A9004DF814 /* Build configuration list for PBXNativeTarget "RCTBlob" */ = {
isa = XCConfigurationList;
buildConfigurations = (
358F4EE11D1E81A9004DF814 /* Debug */,
358F4EE21D1E81A9004DF814 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
ADD01A6E1E09402E00F6D226 /* Build configuration list for PBXNativeTarget "RCTBlob-tvOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
ADD01A6F1E09402E00F6D226 /* Debug */,
ADD01A701E09402E00F6D226 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 358F4ECF1D1E81A9004DF814 /* Project object */;
}

16
Libraries/Blob/RCTBlobManager.h Executable file
View File

@@ -0,0 +1,16 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#import <React/RCTBridge.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTURLRequestHandler.h>
@interface RCTBlobManager : NSObject <RCTBridgeModule, RCTURLRequestHandler>
@end

213
Libraries/Blob/RCTBlobManager.m Executable file
View File

@@ -0,0 +1,213 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#import "RCTBlobManager.h"
#import <React/RCTConvert.h>
#import <React/RCTWebSocketModule.h>
static NSString *const kBlobUriScheme = @"blob";
@interface _RCTBlobContentHandler : NSObject <RCTWebSocketContentHandler>
- (instancetype)initWithBlobManager:(RCTBlobManager *)blobManager;
@end
@implementation RCTBlobManager
{
NSMutableDictionary<NSString *, NSData *> *_blobs;
_RCTBlobContentHandler *_contentHandler;
NSOperationQueue *_queue;
}
RCT_EXPORT_MODULE(BlobModule)
@synthesize bridge = _bridge;
- (NSDictionary<NSString *, id> *)constantsToExport
{
return @{
@"BLOB_URI_SCHEME": kBlobUriScheme,
@"BLOB_URI_HOST": [NSNull null],
};
}
- (dispatch_queue_t)methodQueue
{
return [[_bridge webSocketModule] methodQueue];
}
- (NSString *)store:(NSData *)data
{
NSString *blobId = [NSUUID UUID].UUIDString;
[self store:data withId:blobId];
return blobId;
}
- (void)store:(NSData *)data withId:(NSString *)blobId
{
if (!_blobs) {
_blobs = [NSMutableDictionary new];
}
_blobs[blobId] = data;
}
- (NSData *)resolve:(NSDictionary<NSString *, id> *)blob
{
NSString *blobId = [RCTConvert NSString:blob[@"blobId"]];
NSNumber *offset = [RCTConvert NSNumber:blob[@"offset"]];
NSNumber *size = [RCTConvert NSNumber:blob[@"size"]];
return [self resolve:blobId
offset:offset ? [offset integerValue] : 0
size:size ? [size integerValue] : -1];
}
- (NSData *)resolve:(NSString *)blobId offset:(NSInteger)offset size:(NSInteger)size
{
NSData *data = _blobs[blobId];
if (!data) {
return nil;
}
if (offset != 0 || (size != -1 && size != data.length)) {
data = [data subdataWithRange:NSMakeRange(offset, size)];
}
return data;
}
RCT_EXPORT_METHOD(enableBlobSupport:(nonnull NSNumber *)socketID)
{
if (!_contentHandler) {
_contentHandler = [[_RCTBlobContentHandler alloc] initWithBlobManager:self];
}
[[_bridge webSocketModule] setContentHandler:_contentHandler forSocketID:socketID];
}
RCT_EXPORT_METHOD(disableBlobSupport:(nonnull NSNumber *)socketID)
{
[[_bridge webSocketModule] setContentHandler:nil forSocketID:socketID];
}
RCT_EXPORT_METHOD(sendBlob:(NSDictionary *)blob socketID:(nonnull NSNumber *)socketID)
{
[[_bridge webSocketModule] sendData:[self resolve:blob] forSocketID:socketID];
}
RCT_EXPORT_METHOD(createFromParts:(NSArray<NSDictionary<NSString *, id> *> *)parts withId:(NSString *)blobId)
{
NSMutableData *data = [NSMutableData new];
for (NSDictionary<NSString *, id> *part in parts) {
NSData *partData = [self resolve:part];
[data appendData:partData];
}
[self store:data withId:blobId];
}
RCT_EXPORT_METHOD(release:(NSString *)blobId)
{
[_blobs removeObjectForKey:blobId];
}
#pragma mark - RCTURLRequestHandler methods
- (BOOL)canHandleRequest:(NSURLRequest *)request
{
return [request.URL.scheme caseInsensitiveCompare:kBlobUriScheme] == NSOrderedSame;
}
- (id)sendRequest:(NSURLRequest *)request withDelegate:(id<RCTURLRequestDelegate>)delegate
{
// Lazy setup
if (!_queue) {
_queue = [NSOperationQueue new];
_queue.maxConcurrentOperationCount = 2;
}
__weak __block NSBlockOperation *weakOp;
__block NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:request.URL
MIMEType:nil
expectedContentLength:-1
textEncodingName:nil];
[delegate URLRequest:weakOp didReceiveResponse:response];
NSURLComponents *components = [[NSURLComponents alloc] initWithURL:request.URL resolvingAgainstBaseURL:NO];
NSString *blobId = components.path;
NSInteger offset = 0;
NSInteger size = -1;
if (components.queryItems) {
for (NSURLQueryItem *queryItem in components.queryItems) {
if ([queryItem.name isEqualToString:@"offset"]) {
offset = [queryItem.value integerValue];
}
if ([queryItem.name isEqualToString:@"size"]) {
size = [queryItem.value integerValue];
}
}
}
NSData *data;
if (blobId) {
data = [self resolve:blobId offset:offset size:size];
}
NSError *error;
if (data) {
[delegate URLRequest:weakOp didReceiveData:data];
} else {
error = [[NSError alloc] initWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];
}
[delegate URLRequest:weakOp didCompleteWithError:error];
}];
weakOp = op;
[_queue addOperation:op];
return op;
}
- (void)cancelRequest:(NSOperation *)op
{
[op cancel];
}
@end
@implementation _RCTBlobContentHandler {
__weak RCTBlobManager *_blobManager;
}
- (instancetype)initWithBlobManager:(RCTBlobManager *)blobManager
{
if (self = [super init]) {
_blobManager = blobManager;
}
return self;
}
- (id)processMessage:(id)message forSocketID:(NSNumber *)socketID withType:(NSString *__autoreleasing _Nonnull *)type
{
if (![message isKindOfClass:[NSData class]]) {
*type = @"text";
return message;
}
*type = @"blob";
return @{
@"blobId": [_blobManager store:message],
@"offset": @0,
@"size": @(((NSData *)message).length),
};
}
@end

69
Libraries/Blob/URL.js Normal file
View File

@@ -0,0 +1,69 @@
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule URL
* @flow
*/
'use strict';
const Blob = require('Blob');
const { BlobModule } = require('NativeModules');
let BLOB_URL_PREFIX = null;
if (typeof BlobModule.BLOB_URI_SCHEME === 'string') {
BLOB_URL_PREFIX = BlobModule.BLOB_URI_SCHEME + ':';
if (typeof BlobModule.BLOB_URI_HOST === 'string') {
BLOB_URL_PREFIX += `//${BlobModule.BLOB_URI_HOST}/`;
}
}
/**
* To allow Blobs be accessed via `content://` URIs,
* you need to register `BlobProvider` as a ContentProvider in your app's `AndroidManifest.xml`:
*
* ```xml
* <manifest>
* <application>
* <provider
* android:name="com.facebook.react.modules.blob.BlobProvider"
* android:authorities="@string/blob_provider_authority"
* android:exported="false"
* />
* </application>
* </manifest>
* ```
* And then define the `blob_provider_authority` string in `res/values/strings.xml`.
* Use a dotted name that's entirely unique to your app:
*
* ```xml
* <resources>
* <string name="blob_provider_authority">your.app.package.blobs</string>
* </resources>
* ```
*/
class URL {
constructor() {
throw new Error('Creating BlobURL objects is not supported yet.');
}
static createObjectURL(blob: Blob) {
if (BLOB_URL_PREFIX === null) {
throw new Error('Cannot create URL for blob!');
}
return `${BLOB_URL_PREFIX}${blob.blobId}?offset=${blob.offset}&size=${blob.size}`;
}
static revokeObjectURL(url: string) {
// Do nothing.
}
}
module.exports = URL;

View File

@@ -170,6 +170,8 @@ polyfillGlobal('Headers', () => require('fetch').Headers);
polyfillGlobal('Request', () => require('fetch').Request);
polyfillGlobal('Response', () => require('fetch').Response);
polyfillGlobal('WebSocket', () => require('WebSocket'));
polyfillGlobal('Blob', () => require('Blob'));
polyfillGlobal('URL', () => require('URL'));
// Set up alert
if (!global.alert) {

View File

@@ -9,6 +9,28 @@
#import <React/RCTEventEmitter.h>
@interface RCTWebSocketModule : RCTEventEmitter
NS_ASSUME_NONNULL_BEGIN
@protocol RCTWebSocketContentHandler <NSObject>
- (id)processMessage:(id __nullable)message forSocketID:(NSNumber *)socketID
withType:(NSString *__nonnull __autoreleasing *__nonnull)type;
@end
@interface RCTWebSocketModule : RCTEventEmitter
// Register a custom handler for a specific websocket. The handler will be strongly held by the WebSocketModule.
- (void)setContentHandler:(id<RCTWebSocketContentHandler> __nullable)handler forSocketID:(NSNumber *)socketID;
- (void)sendData:(NSData *)data forSocketID:(nonnull NSNumber *)socketID;
@end
@interface RCTBridge (RCTWebSocketModule)
- (RCTWebSocketModule *)webSocketModule;
@end
NS_ASSUME_NONNULL_END

View File

@@ -36,11 +36,15 @@
@implementation RCTWebSocketModule
{
NSMutableDictionary<NSNumber *, RCTSRWebSocket *> *_sockets;
NSMutableDictionary<NSNumber *, RCTSRWebSocket *> *_sockets;
NSMutableDictionary<NSNumber *, id> *_contentHandlers;
}
RCT_EXPORT_MODULE()
// Used by RCTBlobModule
@synthesize methodQueue = _methodQueue;
- (NSArray *)supportedEvents
{
return @[@"websocketMessage",
@@ -60,7 +64,7 @@ RCT_EXPORT_MODULE()
RCT_EXPORT_METHOD(connect:(NSURL *)URL protocols:(NSArray *)protocols headers:(NSDictionary *)headers socketID:(nonnull NSNumber *)socketID)
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
// We load cookies from sharedHTTPCookieStorage (shared with XHR and
// fetch). To get secure cookies for wss URLs, replace wss with https
// in the URL.
@@ -72,7 +76,7 @@ RCT_EXPORT_METHOD(connect:(NSURL *)URL protocols:(NSArray *)protocols headers:(N
// Load and set the cookie header.
NSArray<NSHTTPCookie *> *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:components.URL];
request.allHTTPHeaderFields = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
// Load supplied headers
[headers enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
[request addValue:[RCTConvert NSString:value] forHTTPHeaderField:key];
@@ -88,15 +92,19 @@ RCT_EXPORT_METHOD(connect:(NSURL *)URL protocols:(NSArray *)protocols headers:(N
[webSocket open];
}
RCT_EXPORT_METHOD(send:(NSString *)message socketID:(nonnull NSNumber *)socketID)
RCT_EXPORT_METHOD(send:(NSString *)message forSocketID:(nonnull NSNumber *)socketID)
{
[_sockets[socketID] send:message];
}
RCT_EXPORT_METHOD(sendBinary:(NSString *)base64String socketID:(nonnull NSNumber *)socketID)
RCT_EXPORT_METHOD(sendBinary:(NSString *)base64String forSocketID:(nonnull NSNumber *)socketID)
{
NSData *message = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
[_sockets[socketID] send:message];
[self sendData:[[NSData alloc] initWithBase64EncodedString:base64String options:0] forSocketID:socketID];
}
- (void)sendData:(NSData *)data forSocketID:(nonnull NSNumber *)socketID
{
[_sockets[socketID] send:data];
}
RCT_EXPORT_METHOD(ping:(nonnull NSNumber *)socketID)
@@ -110,14 +118,36 @@ RCT_EXPORT_METHOD(close:(nonnull NSNumber *)socketID)
[_sockets removeObjectForKey:socketID];
}
- (void)setContentHandler:(id<RCTWebSocketContentHandler>)handler forSocketID:(NSString *)socketID
{
if (!_contentHandlers) {
_contentHandlers = [NSMutableDictionary new];
}
_contentHandlers[socketID] = handler;
}
#pragma mark - RCTSRWebSocketDelegate methods
- (void)webSocket:(RCTSRWebSocket *)webSocket didReceiveMessage:(id)message
{
BOOL binary = [message isKindOfClass:[NSData class]];
NSString *type;
NSNumber *socketID = [webSocket reactTag];
id contentHandler = _contentHandlers[socketID];
if (contentHandler) {
message = [contentHandler processMessage:message forSocketID:socketID withType:&type];
} else {
if ([message isKindOfClass:[NSData class]]) {
type = @"binary";
message = [message base64EncodedStringWithOptions:0];
} else {
type = @"text";
}
}
[self sendEventWithName:@"websocketMessage" body:@{
@"data": binary ? [message base64EncodedStringWithOptions:0] : message,
@"type": binary ? @"binary" : @"text",
@"data": message,
@"type": type,
@"id": webSocket.reactTag
}];
}
@@ -131,21 +161,36 @@ RCT_EXPORT_METHOD(close:(nonnull NSNumber *)socketID)
- (void)webSocket:(RCTSRWebSocket *)webSocket didFailWithError:(NSError *)error
{
NSNumber *socketID = [webSocket reactTag];
_contentHandlers[socketID] = nil;
[self sendEventWithName:@"websocketFailed" body:@{
@"message":error.localizedDescription,
@"id": webSocket.reactTag
@"message": error.localizedDescription,
@"id": socketID
}];
}
- (void)webSocket:(RCTSRWebSocket *)webSocket didCloseWithCode:(NSInteger)code
reason:(NSString *)reason wasClean:(BOOL)wasClean
- (void)webSocket:(RCTSRWebSocket *)webSocket
didCloseWithCode:(NSInteger)code
reason:(NSString *)reason
wasClean:(BOOL)wasClean
{
NSNumber *socketID = [webSocket reactTag];
_contentHandlers[socketID] = nil;
[self sendEventWithName:@"websocketClosed" body:@{
@"code": @(code),
@"reason": RCTNullIfNil(reason),
@"clean": @(wasClean),
@"id": webSocket.reactTag
@"id": socketID
}];
}
@end
@implementation RCTBridge (RCTWebSocketModule)
- (RCTWebSocketModule *)webSocketModule
{
return [self moduleForClass:[RCTWebSocketModule class]];
}
@end

View File

@@ -8,11 +8,24 @@
*/
#import <React/RCTDefines.h>
#import <React/RCTWebSocketObserverProtocol.h>
#if RCT_DEV // Only supported in dev mode
@interface RCTWebSocketObserver : NSObject <RCTWebSocketObserver>
@protocol RCTWebSocketObserverDelegate
- (void)didReceiveWebSocketMessage:(NSDictionary<NSString *, id> *)message;
@end
@interface RCTWebSocketObserver : NSObject
- (instancetype)initWithURL:(NSURL *)url;
@property (nonatomic, weak) id<RCTWebSocketObserverDelegate> delegate;
- (void)start;
- (void)stop;
@end
#endif

View File

@@ -0,0 +1,25 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#import <React/RCTDefines.h>
#if RCT_DEV // Only supported in dev mode
@protocol RCTWebSocketObserverDelegate
- (void)didReceiveWebSocketMessage:(NSDictionary<NSString *, id> *)message;
@end
@protocol RCTWebSocketObserver
- (instancetype)initWithURL:(NSURL *)url;
@property (nonatomic, weak) id<RCTWebSocketObserverDelegate> delegate;
- (void)start;
- (void)stop;
@end
#endif

View File

@@ -11,17 +11,35 @@
*/
'use strict';
const NativeEventEmitter = require('NativeEventEmitter');
const Platform = require('Platform');
const RCTWebSocketModule = require('NativeModules').WebSocketModule;
const WebSocketEvent = require('WebSocketEvent');
const binaryToBase64 = require('binaryToBase64');
const Blob = require('Blob');
const EventTarget = require('event-target-shim');
const NativeEventEmitter = require('NativeEventEmitter');
const NativeModules = require('NativeModules');
const Platform = require('Platform');
const WebSocketEvent = require('WebSocketEvent');
const base64 = require('base64-js');
const binaryToBase64 = require('binaryToBase64');
const invariant = require('fbjs/lib/invariant');
const {WebSocketModule} = NativeModules;
import type EventSubscription from 'EventSubscription';
type ArrayBufferView =
| Int8Array
| Uint8Array
| Uint8ClampedArray
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Float32Array
| Float64Array
| DataView
type BinaryType = 'blob' | 'arraybuffer'
const CONNECTING = 0;
const OPEN = 1;
const CLOSING = 2;
@@ -58,22 +76,22 @@ class WebSocket extends EventTarget(...WEBSOCKET_EVENTS) {
_socketId: number;
_eventEmitter: NativeEventEmitter;
_subscriptions: Array<EventSubscription>;
_binaryType: ?BinaryType;
onclose: ?Function;
onerror: ?Function;
onmessage: ?Function;
onopen: ?Function;
binaryType: ?string;
bufferedAmount: number;
extension: ?string;
protocol: ?string;
readyState: number = CONNECTING;
url: ?string;
// This module depends on the native `RCTWebSocketModule` module. If you don't include it,
// This module depends on the native `WebSocketModule` module. If you don't include it,
// `WebSocket.isAvailable` will return `false`, and WebSocket constructor will throw an error
static isAvailable: boolean = !!RCTWebSocketModule;
static isAvailable: boolean = !!WebSocketModule;
constructor(url: string, protocols: ?string | ?Array<string>, options: ?{origin?: string}) {
super();
@@ -87,13 +105,35 @@ class WebSocket extends EventTarget(...WEBSOCKET_EVENTS) {
if (!WebSocket.isAvailable) {
throw new Error('Cannot initialize WebSocket module. ' +
'Native module RCTWebSocketModule is missing.');
'Native module WebSocketModule is missing.');
}
this._eventEmitter = new NativeEventEmitter(RCTWebSocketModule);
this._eventEmitter = new NativeEventEmitter(WebSocketModule);
this._socketId = nextWebSocketId++;
this._registerEvents();
RCTWebSocketModule.connect(url, protocols, options, this._socketId);
WebSocketModule.connect(url, protocols, options, this._socketId);
}
get binaryType(): ?BinaryType {
return this._binaryType;
}
set binaryType(binaryType: BinaryType): void {
if (binaryType !== 'blob' && binaryType !== 'arraybuffer') {
throw new Error('binaryType must be either \'blob\' or \'arraybuffer\'');
}
if (this._binaryType === 'blob' || binaryType === 'blob') {
const BlobModule = NativeModules.BlobModule;
invariant(BlobModule, 'Native module BlobModule is required for blob support');
if (BlobModule) {
if (binaryType === 'blob') {
BlobModule.enableBlobSupport(this._socketId);
} else {
BlobModule.disableBlobSupport(this._socketId);
}
}
}
this._binaryType = binaryType;
}
close(code?: number, reason?: string): void {
@@ -106,18 +146,25 @@ class WebSocket extends EventTarget(...WEBSOCKET_EVENTS) {
this._close(code, reason);
}
send(data: string | ArrayBuffer | $ArrayBufferView): void {
send(data: string | ArrayBuffer | ArrayBufferView | Blob): void {
if (this.readyState === this.CONNECTING) {
throw new Error('INVALID_STATE_ERR');
}
if (data instanceof Blob) {
const BlobModule = NativeModules.BlobModule;
invariant(BlobModule, 'Native module BlobModule is required for blob support');
BlobModule.sendBlob(data, this._socketId);
return;
}
if (typeof data === 'string') {
RCTWebSocketModule.send(data, this._socketId);
WebSocketModule.send(data, this._socketId);
return;
}
if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
RCTWebSocketModule.sendBinary(binaryToBase64(data), this._socketId);
WebSocketModule.sendBinary(binaryToBase64(data), this._socketId);
return;
}
@@ -129,7 +176,7 @@ class WebSocket extends EventTarget(...WEBSOCKET_EVENTS) {
throw new Error('INVALID_STATE_ERR');
}
RCTWebSocketModule.ping(this._socketId);
WebSocketModule.ping(this._socketId);
}
_close(code?: number, reason?: string): void {
@@ -137,9 +184,9 @@ class WebSocket extends EventTarget(...WEBSOCKET_EVENTS) {
// See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
const statusCode = typeof code === 'number' ? code : CLOSE_NORMAL;
const closeReason = typeof reason === 'string' ? reason : '';
RCTWebSocketModule.close(statusCode, closeReason, this._socketId);
WebSocketModule.close(statusCode, closeReason, this._socketId);
} else {
RCTWebSocketModule.close(this._socketId);
WebSocketModule.close(this._socketId);
}
}
@@ -154,9 +201,16 @@ class WebSocket extends EventTarget(...WEBSOCKET_EVENTS) {
if (ev.id !== this._socketId) {
return;
}
this.dispatchEvent(new WebSocketEvent('message', {
data: (ev.type === 'binary') ? base64.toByteArray(ev.data).buffer : ev.data
}));
let data = ev.data;
switch (ev.type) {
case 'binary':
data = base64.toByteArray(ev.data).buffer;
break;
case 'blob':
data = Blob.create(ev.data);
break;
}
this.dispatchEvent(new WebSocketEvent('message', { data }));
}),
this._eventEmitter.addListener('websocketOpen', ev => {
if (ev.id !== this._socketId) {