Improve cloudinary media upload experience.

This commit is contained in:
Patrick Fic
2022-06-21 11:41:42 -07:00
parent 49b77315ba
commit 9eb8a43884
8 changed files with 196 additions and 235 deletions

View File

@@ -1,6 +1,6 @@
import * as MediaLibrary from "expo-media-library";
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
ActivityIndicator,
Alert,
@@ -18,16 +18,11 @@ import {
selectCurrentCameraJobId,
selectDeleteAfterUpload,
} from "../../redux/app/app.selectors";
import {
selectBodyshop,
selectCurrentUser,
} from "../../redux/user/user.selectors";
import { formatBytes } from "../../util/document-upload.utility";
import { handleLocalUpload } from "../../util/local-document-upload.utility";
const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUser,
bodyshop: selectBodyshop,
selectedCameraJobId: selectCurrentCameraJobId,
deleteAfterUpload: selectDeleteAfterUpload,
});
@@ -35,8 +30,6 @@ const mapStateToProps = createStructuredSelector({
export default connect(mapStateToProps, null)(UploadProgress);
export function UploadProgress({
currentUser,
bodyshop,
selectedCameraJobId,
deleteAfterUpload,
uploads,
@@ -49,8 +42,6 @@ export function UploadProgress({
speed: 0,
});
const { t } = useTranslation();
useEffect(() => {
//Set the state of uploads to do.
if (uploads) {

View File

@@ -169,25 +169,23 @@ export function ScreenMainComponent({
}, [checkUserSession]);
return (
<SafeAreaView style={{ flex: 1 }}>
<NavigationContainer>
{currentUser.authorized === null ? (
<ScreenSplash />
) : currentUser.authorized ? (
bodyshop ? (
HasAccess(bodyshop) ? (
<BottomTabsNavigator />
) : (
<ScreenSplash noAccess />
)
<NavigationContainer>
{currentUser.authorized === null ? (
<ScreenSplash />
) : currentUser.authorized ? (
bodyshop ? (
HasAccess(bodyshop) ? (
<BottomTabsNavigator />
) : (
<ScreenSplash />
<ScreenSplash noAccess />
)
) : (
<ScreenSignIn />
)}
</NavigationContainer>
</SafeAreaView>
<ScreenSplash />
)
) : (
<ScreenSignIn />
)}
</NavigationContainer>
);
}
export default connect(

View File

@@ -28,6 +28,8 @@ import {
selectCurrentUser,
} from "../../redux/user/user.selectors";
import { formatBytes, handleUpload } from "../../util/document-upload.utility";
import Toast from "react-native-toast-message";
import { validateArgCount } from "@firebase/util";
const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUser,
@@ -44,12 +46,17 @@ export function UploadProgress({
selectedCameraJobId,
deleteAfterUpload,
uploads,
setUploads,
forceRerender,
}) {
const [progress, setProgress] = useState({
loading: false,
uploadInProgress: false,
speed: 0,
totalToUpload: 0,
totalUploaded: 0,
startTime: null,
totalFiles: 0,
totalFilesCompleted: 0,
currentFile: null,
files: {}, //uri is the key, value is progress
});
@@ -59,65 +66,71 @@ export function UploadProgress({
const { t } = useTranslation();
useEffect(() => {
//Set the state of uploads to do.
if (uploads) onDone(uploads);
if (uploads) {
onDone(uploads);
setUploads(null);
}
}, [uploads]);
//if (!uploads) return null;
function handleOnSuccess(id, asset) {
logImEXEvent("imexmobile_successful_upload");
function handleOnSuccess(asset) {
//NEEDS REDO.
filesToDelete.push(asset);
setProgress((progress) => ({
...progress,
action: t("mediabrowser.labels.converting"),
// totalUploaded: progress.totalToUpload + asset.size,
totalFilesCompleted: progress.totalFilesCompleted + 1,
files: {
...progress.files,
[id]: {
...progress.files[id],
percent: 1,
action: t("mediabrowser.labels.converting"),
},
},
// });
}));
}
function handleOnProgress(uri, percent, loaded) {
setProgress((progress) => ({
...progress,
speed: loaded - progress.files[uri].loaded,
action:
percent === 1
? t("mediabrowser.labels.converting")
: t("mediabrowser.labels.uploading"),
files: {
...progress.files,
[uri]: {
...progress.files[uri],
percent,
speed: loaded - progress.files[uri].loaded,
action:
percent === 1
? t("mediabrowser.labels.converting")
: t("mediabrowser.labels.uploading"),
loaded: loaded,
[asset.uri]: {
...progress.files[asset.uri],
uploadEnd: new Date(),
},
},
}));
}
function handleOnError(...props) {
logImEXEvent("imexmobile_upload_documents_error", { props });
}
const onDone = async (data) => {
//Validate to make sure the totals for the file sizes do not exceed the total on the job.
setProgress({
files: _.keyBy(data, "id"),
loading: true,
uploadInProgress: true,
function handleOnProgress({ uri, filename }, percent, loaded) {
//NEED REDO
setProgress((progress) => {
return {
...progress,
totalUploaded:
progress.totalUploaded +
(loaded - (progress.files[uri]?.loaded || 0)),
files: {
...progress.files,
[uri]: {
...progress.files[uri],
percent,
filename,
speed: loaded - (progress.files[uri]?.loaded || 0),
loaded: loaded,
uploadStart: progress.files[uri]?.uploadStart || new Date(),
},
},
};
});
}
function handleOnError(error) {
logImEXEvent("imexmobile_upload_documents_error", { error });
Toast.show({
type: "error",
text1: "Unable to upload documents.",
text2: error,
autoHide: false,
});
}
const onDone = async (selectedFiles) => {
//Validate to make sure the totals for the file sizes do not exceed the total on the job.
const data = [];
const totalOfUploads = await selectedFiles.reduce(async (acc, val) => {
//Get the size of the file based on URI.
const info = await FileSystem.getInfoAsync(val.uri, { size: true });
data.push({ ...info, ...val }); //Add in the size.
val.albumId && MediaLibrary.migrateAlbumIfNeededAsync(val.albumId);
return (await acc) + info.size;
}, 0);
if (selectedCameraJobId !== "temp") {
const queryData = await client.query({
@@ -127,13 +140,6 @@ export function UploadProgress({
jobId: selectedCameraJobId,
},
});
const totalOfUploads = await data.reduce(async (acc, val) => {
//Get the size of the file based on URI.
const info = await FileSystem.getInfoAsync(val.uri, { size: true });
val.albumId && MediaLibrary.migrateAlbumIfNeededAsync(val.albumId);
return (await acc) + info.size;
}, 0);
if (
bodyshop.jobsizelimit -
@@ -145,7 +151,7 @@ export function UploadProgress({
...progress,
speed: 0,
action: null,
loading: false,
uploadInProgress: false,
}));
Alert.alert(
@@ -155,10 +161,26 @@ export function UploadProgress({
return;
}
}
//We made it this far. We have enough space, so let's start uploading.
//Sequentially await the proms.
setProgress((progress) => {
return {
...progress,
uploadInProgress: true,
totalToUpload: totalOfUploads,
totalUploaded: 0,
totalFilesCompleted: 0,
startTime: new Date(),
totalFiles: data.length,
currentFile: null,
files: {}, //uri is the key, value is progress
};
});
for (var i = 0; i < data.length + 4; i = i + 4) {
//Reset the files.
setProgress((progress) => ({ ...progress, files: {} }));
let proms = [];
if (data[i]) {
proms.push(CreateUploadProm(data[i]));
@@ -176,48 +198,51 @@ export function UploadProgress({
await Promise.all(proms);
}
//Everything is uploaded, delete the succesful ones.
if (deleteAfterUpload) {
try {
console.log("Trying to Delete", filesToDelete);
if (Platform.OS === "android") {
const res = await Promise.all(
await Promise.all(
filesToDelete.map(async (f) =>
MediaLibrary.removeAssetsFromAlbumAsync(f, f.albumId)
)
);
}
const deleteResult = await MediaLibrary.deleteAssetsAsync(
filesToDelete
console.log(
"Delete Result",
await MediaLibrary.deleteAssetsAsync(filesToDelete.map((f) => f.id))
);
} catch (error) {
console.log("Unable to delete picture.", error);
}
}
filesToDelete = [];
setProgress({
loading: false,
speed: 0,
action: null,
//Reset state.
setProgress({
uploadInProgress: false,
files: {}, //uri is the key, value is progress
totalToUpload: 0,
totalUploaded: 0,
totalFilesCompleted: 0,
startTime: null,
totalFiles: 0,
currentFile: null,
files: {},
});
forceRerender();
};
const CreateUploadProm = async (p) => {
let filename;
filename = p.filename || p.uri.split("/").pop();
await handleUpload(
return handleUpload(
{
filename,
mediaId: p.id,
onError: handleOnError,
onProgress: ({ percent, loaded }) =>
handleOnProgress(p.id, percent, loaded),
onSuccess: () => handleOnSuccess(p.id, p),
handleOnProgress(p, percent, loaded),
onSuccess: () => handleOnSuccess(p),
},
{
bodyshop: bodyshop,
@@ -226,20 +251,6 @@ export function UploadProgress({
photo: p,
}
);
//Set the state to mark that it's done.
setProgress((progress) => ({
...progress,
action: null,
speed: 0,
files: {
...progress.files,
[p.id]: {
...progress.files[p.id],
action: null,
},
},
}));
};
return (
@@ -248,15 +259,22 @@ export function UploadProgress({
animationType="slide"
transparent={true}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
Alert.alert("Cancel?", "Do you want to abort the upload?", [
{
text: "Yes",
onPress: () => {
setUploads(null);
setProgress(null);
},
},
{ text: "No" },
]);
}}
>
<View style={styles.modal}>
{progress.loading && <ActivityIndicator />}
<ScrollView contentContainerStyle={styles.centeredView}>
<View style={styles.modalContainer}>
<View style={styles.modal}>
{Object.keys(progress.files).map((key) => (
<View key={progress.files[key].id} style={styles.progressItem}>
<View key={key} style={styles.progressItem}>
<Text style={styles.progressText}>
{progress.files[key].filename}
</Text>
@@ -266,24 +284,49 @@ export function UploadProgress({
style={styles.progress}
color={progress.files[key].percent === 1 ? "green" : "blue"}
/>
{progress.files[key].speed !== 0 &&
progress.files[key].speed &&
!isNaN(progress.files[key].speed) ? (
<Text>{`${formatBytes(progress.files[key].speed)}/sec`}</Text>
) : null}
<View
style={{
display: "flex",
flexDirection: "row",
alignItems: "center",
}}
>
<Text>{`${formatBytes(
progress.files[key].loaded /
(((progress.files[key].uploadEnd || new Date()) -
progress.files[key].uploadStart) /
1000)
)}/sec`}</Text>
{progress.files[key].percent === 1 && (
<>
<ActivityIndicator style={{ marginLeft: 12 }} />
<Text style={{ marginLeft: 4 }}>Processing...</Text>
</>
)}
</View>
</View>
</View>
))}
</ScrollView>
<View style={styles.centeredView}>
<Text>{`${progress.totalFilesCompleted} of ${progress.totalFiles} uploaded.`}</Text>
<Text>{`${formatBytes(progress.totalUploaded)} of ${formatBytes(
progress.totalToUpload
)} uploaded.`}</Text>
</View>
</View>
</View>
</Modal>
);
}
const styles = StyleSheet.create({
modal: {
modalContainer: {
display: "flex",
flex: 1,
marginTop: 50,
marginBottom: 60,
justifyContent: "center",
},
modal: {
//flex: 1,
display: "flex",
marginLeft: 20,
marginRight: 20,
backgroundColor: "white",
@@ -299,9 +342,8 @@ const styles = StyleSheet.create({
elevation: 5,
},
centeredView: {
flex: 1,
// justifyContent: "center",
// alignItems: "center",
justifyContent: "center",
alignItems: "center",
marginTop: 22,
},
progressItem: {