Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/progressive upload #8

Merged
merged 13 commits into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# Changelog
All changes to this project will be documented in this file.

## [1.2.0] - 2024-04-03
- Add support of progressive uploads

## [1.1.0] - 2024-02-16
- Add support for RN new architecture: Turbo Native Modules
- Add an API to set time out
Expand Down
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
- [Getting started](#getting-started)
- [Installation](#installation)
- [Code sample](#code-sample)
- [Regular upload](#regular-upload)
- [Progressive upload](#progressive-upload)
- [Android](#android)
- [Permissions](#permissions)
- [Notifications](#notifications)
Expand Down Expand Up @@ -54,6 +56,8 @@ yarn add @api.video/react-native-video-uploader

### Code sample

#### Regular upload

```js
import ApiVideoUploader from '@api.video/react-native-video-uploader';

Expand All @@ -66,6 +70,27 @@ ApiVideoUploader.uploadWithUploadToken('YOUR_UPLOAD_TOKEN', 'path/to/my-video.mp
});
```

#### Progressive upload

For more details about progressive uploads, see the [progressive upload documentation](https://docs.api.video/vod/progressive-upload).

```js
import ApiVideoUploader from '@api.video/react-native-video-uploader';

(async () => {
const uploadSession = ApiVideoUploader.createProgressiveUploadSession({token: 'YOUR_UPLOAD_TOKEN'});
try {
await session.uploadPart("path/to/video.mp4.part1");
await session.uploadPart("path/to/video.mp4.part2");
// ...
const video = await session.uploadLastPart("path/to/video.mp4.partn");
// ...
} catch(e: any) {
// Manages error here
}
})();
```

### Android

#### Permissions
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,60 @@ class UploaderModule(reactContext: ReactApplicationContext) :
}
}

// Progressive upload
@ReactMethod
override fun createProgressiveUploadSession(sessionId: String, videoId: String) {
uploaderModuleImpl.createUploadProgressiveSession(sessionId, videoId)
}

@ReactMethod
override fun createProgressiveUploadWithUploadTokenSession(
sessionId: String,
token: String,
videoId: String?
) {
uploaderModuleImpl.createUploadWithUploadTokenProgressiveSession(sessionId, token, videoId)
}

@ReactMethod
override fun uploadPart(sessionId: String, filePath: String, promise: Promise) {
uploadPart(sessionId, filePath, false, promise)
}

@ReactMethod
override fun uploadLastPart(sessionId: String, filePath: String, promise: Promise) {
uploadPart(sessionId, filePath, true, promise)
}

@ReactMethod
override fun disposeProgressiveUploadSession(sessionId: String) {
uploaderModuleImpl.disposeProgressiveUploadSession(sessionId)
}

private fun uploadPart(
sessionId: String,
filePath: String,
isLastPart: Boolean,
promise: Promise
) {
try {
uploaderModuleImpl.uploadPart(sessionId, filePath, isLastPart, { _ ->
}, { video ->
promise.resolve(video)
}, {
promise.reject(CancellationException("Upload was cancelled"))
}, { e ->
promise.reject(e)
})
} catch (e: Exception) {
promise.reject(e)
}
}

companion object {
const val NAME = "ApiVideoUploader"

const val SDK_NAME = "reactnative-uploader"
const val SDK_VERSION = "1.1.0"
const val SDK_VERSION = "1.2.0"
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package video.api.reactnative.uploader;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.facebook.react.TurboReactPackage;
Expand All @@ -14,7 +15,7 @@
public class UploaderPackage extends TurboReactPackage {
@Nullable
@Override
public NativeModule getModule(String name, ReactApplicationContext reactContext) {
public NativeModule getModule(String name, @NonNull ReactApplicationContext reactContext) {
if (name.equals(UploaderModule.NAME)) {
return new UploaderModule(reactContext);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,14 @@ abstract class UploaderModuleSpec(reactContext: ReactApplicationContext) :
abstract fun uploadWithUploadToken(token: String, filePath: String, videoId: String?, promise: Promise)

abstract fun upload(videoId: String, filePath: String, promise: Promise)

abstract fun createProgressiveUploadSession(sessionId: String, videoId: String)

abstract fun createProgressiveUploadWithUploadTokenSession(sessionId: String, token: String, videoId: String?)

abstract fun uploadPart(sessionId: String, filePath: String, promise: Promise)

abstract fun uploadLastPart(sessionId: String, filePath: String, promise: Promise)

abstract fun disposeProgressiveUploadSession(sessionId: String)
}
82 changes: 70 additions & 12 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
SafeAreaView,
ScrollView,
StyleSheet,
Switch,
Text,
TextInput,
View,
Expand All @@ -22,6 +23,7 @@
export default function App() {
const [videoFile, setVideoFile] = React.useState<string | null>(null);
const [uploading, setUploading] = React.useState<boolean>(false);
const [isProgressive, setIsProgressive] = React.useState<boolean>(false);
const [uploadToken, setUploadToken] = React.useState<string>('');
const [chunkSize, setChunkSize] = React.useState<string>('20');
const [uploadResult, setUploadResult] = React.useState<any | null>(null);
Expand Down Expand Up @@ -58,8 +60,13 @@
}, []);

const onUploadButtonPress = React.useCallback(
(token: string, uri: string | null, chunkSize: string) => {
(
token: string,
uri: string | null,
chunkSize: string,

Check warning on line 66 in example/src/App.tsx

View workflow job for this annotation

GitHub Actions / lint

'chunkSize' is already declared in the upper scope on line 28 column 10
isProgressive: boolean

Check warning on line 67 in example/src/App.tsx

View workflow job for this annotation

GitHub Actions / lint

'isProgressive' is already declared in the upper scope on line 26 column 10
) => {
const chunkSizeInt = parseInt(chunkSize);

Check warning on line 69 in example/src/App.tsx

View workflow job for this annotation

GitHub Actions / lint

Missing radix parameter

if (!uri) {
return;
Expand All @@ -75,24 +82,51 @@

setUploading(true);

ApiVideoUploader.setChunkSize(1024 * 1024 * parseInt(chunkSize));

Check warning on line 85 in example/src/App.tsx

View workflow job for this annotation

GitHub Actions / lint

Missing radix parameter

const resolveUri = (u: string): Promise<string> => {
return Platform.OS === 'android'
? ReactNativeBlobUtil.fs.stat(u).then((stat) => stat.path)
: new Promise((resolve, _) => resolve(u));
: new Promise((resolve, _) => resolve(u.replace('file://', '')));
};

resolveUri(uri).then((u) => {
ApiVideoUploader.uploadWithUploadToken(token, u)
.then((value: Video) => {
setUploadResult(value);
setUploading(false);
})
.catch((e: any) => {
Alert.alert('Upload failed', e?.message || JSON.stringify(e));
setUploading(false);
resolveUri(uri).then(async (u) => {
if (isProgressive) {
const size = (await ReactNativeBlobUtil.fs.stat(u)).size;

const session = ApiVideoUploader.createProgressiveUploadSession({
token,
});
const chunkSizeBytes = 1024 * 1024 * chunkSizeInt;
let start = 0;
for (
let i = 0;
start <= size - chunkSizeBytes;
start += chunkSizeBytes, i++
) {
await ReactNativeBlobUtil.fs.slice(
u,
`${u}.part${i}`,
start,
start + chunkSizeBytes
);
await session.uploadPart(`${u}.part${i}`);
}
await ReactNativeBlobUtil.fs.slice(u, `${u}.lastpart`, start, size);
const value = await session.uploadLastPart(u + '.lastpart');
setUploadResult(value);
setUploading(false);
} else {
ApiVideoUploader.uploadWithUploadToken(token, u)
.then((value: Video) => {
setUploadResult(value);
setUploading(false);
})
.catch((e: any) => {
Alert.alert('Upload failed', e?.message || JSON.stringify(e));
setUploading(false);
});
}
});
},
[]
Expand Down Expand Up @@ -165,11 +199,35 @@
keyboardType="numeric"
/>
</View>
<View
style={{
borderLeftWidth: 1,
marginLeft: 8,
borderLeftColor: '#F64325',
marginVertical: 5,
alignItems: 'flex-start',
}}
>
<Text style={styles.label}>Progressive upload</Text>
<Switch
disabled={uploading}
trackColor={{ false: '#767577', true: '#767577' }}
thumbColor={isProgressive ? '#F64325' : '#f4f3f4'}
ios_backgroundColor="#3e3e3e"
onValueChange={() => setIsProgressive(!isProgressive)}
value={isProgressive}
/>
</View>
<Text style={styles.textSectionTitle}>And finally... upload!</Text>
<DemoButton
disabled={uploading}
onPress={() =>
onUploadButtonPress(uploadToken, videoFile, chunkSize)
onUploadButtonPress(
uploadToken,
videoFile,
chunkSize,
isProgressive
)
}
>
{uploading ? 'UPLOADING...' : 'UPLOAD'}
Expand Down
20 changes: 17 additions & 3 deletions ios/RNUploader.mm
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,30 @@ @interface RCT_EXTERN_REMAP_MODULE(ApiVideoUploader, RNUploader, NSObject<RCTBri
withResolver:(RCTPromiseResolveBlock)resolve
withRejecter:(RCTPromiseRejectBlock)reject)

RCT_EXTERN_METHOD(setTimeout:(NSNumber)timeout)
RCT_EXTERN_METHOD(setTimeout:(nonnull NSNumber)timeout)

RCT_EXTERN_METHOD(uploadWithUploadToken:(NSString)token:(NSString)filePath:(NSString)videoId
// MARK: Regular upload
RCT_EXTERN_METHOD(uploadWithUploadToken:(nonnull NSString)token:(nonnull NSString)filePath:(NSString)videoId
withResolver:(RCTPromiseResolveBlock)resolve
withRejecter:(RCTPromiseRejectBlock)reject)

RCT_EXTERN_METHOD(upload:(NSString)videoId:(NSString)filePath
RCT_EXTERN_METHOD(upload:(nonnull NSString)videoId:(nonnull NSString)filePath
withResolver:(RCTPromiseResolveBlock)resolve
withRejecter:(RCTPromiseRejectBlock)reject)

// MARK: Progressive upload
RCT_EXTERN_METHOD(createUploadProgressiveSession:(nonnull NSString)sessionId:(nonnull NSString)videoId)
RCT_EXTERN_METHOD(createProgressiveUploadWithUploadTokenSession:(nonnull NSString)sessionId:(nonnull NSString)token:(NSString)videoId)

RCT_EXTERN_METHOD(uploadPart:(nonnull NSString)sessionId:(nonnull NSString)filePath
withResolver:(RCTPromiseResolveBlock)resolve
withRejecter:(RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(uploadLastPart:(nonnull NSString)sessionId:(nonnull NSString)filePath
withResolver:(RCTPromiseResolveBlock)resolve
withRejecter:(RCTPromiseRejectBlock)reject)

RCT_EXTERN_METHOD(disposeProgressiveUploadSession:(nonnull NSString)sessionId)

// Don't compile this code when we build for the old architecture.
#ifdef RCT_NEW_ARCH_ENABLED
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params {
Expand Down
43 changes: 42 additions & 1 deletion ios/RNUploader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class RNUploader: NSObject {

override init() {
do {
try uploadModule.setSdkName(name: "reactnative-uploader", version: "1.1.0")
try uploadModule.setSdkName(name: "reactnative-uploader", version: "1.2.0")
} catch {
fatalError("Failed to set SDK name: \(error)")
}
Expand Down Expand Up @@ -75,4 +75,45 @@ class RNUploader: NSObject {
reject("upload_failed", error.localizedDescription, error)
}
}

@objc(createUploadProgressiveSession::)
func createUploadProgressiveSession(sessionId: String, videoId: String) {
do {
try uploadModule.createUploadProgressiveSession(sessionId: sessionId, videoId: videoId)
} catch {
fatalError("Failed to create progressive upload session: \(error)")
}
}

@objc(createProgressiveUploadWithUploadTokenSession:::)
func createProgressiveUploadWithUploadTokenSession(sessionId: String, token: String, videoId: String?) {
do {
try uploadModule.createProgressiveUploadWithUploadTokenSession(sessionId: sessionId, token: token, videoId: videoId)
} catch {
fatalError("Failed to create progressive upload with upload token session: \(error)")
}
}

@objc(uploadPart::withResolver:withRejecter:)
func uploadPart(sessionId: String, filePath: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
uploadModule.uploadPart(sessionId: sessionId, filePath: filePath, onProgress: { _ in }, onSuccess: { video in
resolve(video)
}, onError: { error in
reject("upload_part_failed", error.localizedDescription, error)
})
}

@objc(uploadLastPart::withResolver:withRejecter:)
func uploadLastPart(sessionId: String, filePath: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
uploadModule.uploadLastPart(sessionId: sessionId, filePath: filePath, onProgress: { _ in }, onSuccess: { video in
resolve(video)
}, onError: { error in
reject("upload_last_part_failed", error.localizedDescription, error)
})
}

@objc(disposeProgressiveUploadSession:)
func disposeProgressiveUploadSession(sessionId: String) {
uploadModule.disposeProgressiveUploadSession(sessionId)
}
}
8 changes: 4 additions & 4 deletions ios/StringExtensions.swift
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
extension String {
func deletePrefix(_ prefix: String) -> String {
guard self.hasPrefix(prefix) else { return self }
return String(self.dropFirst(prefix.count))
guard hasPrefix(prefix) else { return self }
return String(dropFirst(prefix.count))
}

var url: URL {
return URL(fileURLWithPath: self.deletePrefix("file://"))
return URL(fileURLWithPath: deletePrefix("file://"))
}
}
1 change: 0 additions & 1 deletion ios/UploaderModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,3 @@ public class UploaderModule: NSObject {
public enum UploaderError: Error {
case invalidParameter(message: String)
}

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@api.video/react-native-video-uploader",
"version": "1.1.0",
"version": "1.2.0",
"description": "The official React Native video uploader for api.video",
"main": "lib/commonjs/index",
"module": "lib/module/index",
Expand Down
Loading
Loading