1.3.6-3 Test Build - Refactor local uploads to go in bulk.

This commit is contained in:
Patrick Fic
2022-05-18 09:55:48 -07:00
parent 5633eeb24d
commit e29097a6c7
4 changed files with 121 additions and 215 deletions

View File

@@ -4,19 +4,19 @@
"slug": "imexmobile", "slug": "imexmobile",
"version": "1.3.6", "version": "1.3.6",
"extra": { "extra": {
"expover": "2" "expover": "3"
}, },
"orientation": "default", "orientation": "default",
"icon": "./assets/logo192noa.png", "icon": "./assets/logo192noa.png",
"ios": { "ios": {
"supportsTablet": true, "supportsTablet": true,
"bundleIdentifier": "com.imex.imexmobile", "bundleIdentifier": "com.imex.imexmobile",
"buildNumber": "2", "buildNumber": "3",
"googleServicesFile": "./GoogleService-Info.plist" "googleServicesFile": "./GoogleService-Info.plist"
}, },
"android": { "android": {
"package": "com.imex.imexmobile", "package": "com.imex.imexmobile",
"versionCode": 1100007, "versionCode": 1100008,
"googleServicesFile": "./google-services.json" "googleServicesFile": "./google-services.json"
}, },
"splash": { "splash": {

View File

@@ -1,18 +1,16 @@
import { useApolloClient } from "@apollo/client";
import * as MediaLibrary from "expo-media-library"; import * as MediaLibrary from "expo-media-library";
import _ from "lodash";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import {
ActivityIndicator, ActivityIndicator,
Alert, Alert,
Modal, Modal,
ScrollView,
StyleSheet, StyleSheet,
Text, Text,
View, View,
} from "react-native"; } from "react-native";
import { ProgressBar } from "react-native-paper"; import { ProgressBar } from "react-native-paper";
import Toast from "react-native-toast-message";
import { connect } from "react-redux"; import { connect } from "react-redux";
import { createStructuredSelector } from "reselect"; import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.analytics"; import { logImEXEvent } from "../../firebase/firebase.analytics";
@@ -26,7 +24,6 @@ import {
} from "../../redux/user/user.selectors"; } from "../../redux/user/user.selectors";
import { formatBytes } from "../../util/document-upload.utility"; import { formatBytes } from "../../util/document-upload.utility";
import { handleLocalUpload } from "../../util/local-document-upload.utility"; import { handleLocalUpload } from "../../util/local-document-upload.utility";
import Toast from "react-native-toast-message";
const mapStateToProps = createStructuredSelector({ const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUser, currentUser: selectCurrentUser,
@@ -43,78 +40,54 @@ export function UploadProgress({
selectedCameraJobId, selectedCameraJobId,
deleteAfterUpload, deleteAfterUpload,
uploads, uploads,
setUploads,
forceRerender, forceRerender,
}) { }) {
const [progress, setProgress] = useState({ const [progress, setProgress] = useState({
loading: false, loading: false,
uploadInProgress: false, uploadInProgress: false,
speed: 0, speed: 0,
files: {}, //uri is the key, value is progress
}); });
let filesToDelete = []; let filesToDelete = [];
const client = useApolloClient();
const { t } = useTranslation(); const { t } = useTranslation();
useEffect(() => { useEffect(() => {
//Set the state of uploads to do. //Set the state of uploads to do.
if (uploads) {
if (uploads) onDone(uploads); beginUploads(uploads);
setUploads(null);
}
}, [uploads]); }, [uploads]);
//if (!uploads) return null; function handleOnSuccess({ duration }) {
function handleOnSuccess(id, asset, { duration }) {
//If it's not in production, show a toast with the time. //If it's not in production, show a toast with the time.
Toast.show({ Toast.show({
type: "success", type: "success",
text1: `${duration} - Upload completed for ${asset.filename}.`, text1: ` Upload completed in ${duration}.`,
// //
// text2: duration, // text2: duration,
}); });
logImEXEvent("imexmobile_successful_upload"); logImEXEvent("imexmobile_successful_upload");
filesToDelete.push(asset); setProgress({
speed: 0,
percent: 1,
uploadInProgress: false,
});
}
function handleOnProgress({ percent, loaded }) {
setProgress((progress) => ({ setProgress((progress) => ({
...progress, ...progress,
action: t("mediabrowser.labels.converting"), speed: loaded - progress.loaded,
files: { loaded: loaded,
...progress.files, percent,
[id]: {
...progress.files[id],
percent: 1,
action: t("mediabrowser.labels.converting"),
},
},
// });
})); }));
} }
function handleOnProgress(uri, percent, loaded) { function handleOnError({ assetid, error }) {
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,
},
},
}));
}
function handleOnError(id, error) {
logImEXEvent("imexmobile_upload_documents_error"); logImEXEvent("imexmobile_upload_documents_error");
Toast.show({ Toast.show({
type: "error", type: "error",
@@ -122,52 +95,27 @@ export function UploadProgress({
text2: (error && error.message) || JSON.stringify(error), text2: (error && error.message) || JSON.stringify(error),
autoHide: false, autoHide: false,
}); });
setProgress((progress) => ({
...progress,
action: t("mediabrowser.labels.converting"),
files: {
...progress.files,
[id]: {
...progress.files[id],
percent: 1,
action: t("mediabrowser.labels.converting"),
},
},
// });
}));
} }
const onDone = async (data) => { const beginUploads = async (data) => {
//Validate to make sure the totals for the file sizes do not exceed the total on the job. //Validate to make sure the totals for the file sizes do not exceed the total on the job.
setProgress({ setProgress({
files: _.keyBy(data, "id"), percent: 0,
loading: true, loaded: 0,
uploadInProgress: true, uploadInProgress: true,
}); });
//Sequentially await the proms. await handleLocalUpload({
files: data,
// for (const file of data) { onError: ({ assetid, error }) => handleOnError({ assetid, error }),
// await CreateUploadProm(file); onProgress: ({ percent, loaded }) =>
// } handleOnProgress({ percent, loaded }),
onSuccess: ({ duration }) => handleOnSuccess({ duration }),
for (var i = 0; i < data.length + 4; i = i + 4) { context: {
let proms = []; jobid:
if (data[i]) { selectedCameraJobId !== "temp" ? selectedCameraJobId : "temporary",
proms.push(CreateUploadProm(data[i])); },
} });
if (data[i + 1]) {
proms.push(CreateUploadProm(data[i + 1]));
}
if (data[i + 2]) {
proms.push(CreateUploadProm(data[i + 2]));
}
if (data[i + 3]) {
proms.push(CreateUploadProm(data[i + 3]));
}
await Promise.all(proms);
}
if (deleteAfterUpload) { if (deleteAfterUpload) {
try { try {
@@ -190,91 +138,55 @@ export function UploadProgress({
setProgress({ setProgress({
loading: false, loading: false,
speed: 0, speed: 0,
action: null,
uploadInProgress: false, uploadInProgress: false,
files: {}, //uri is the key, value is progress
}); });
forceRerender(); forceRerender();
}; };
const CreateUploadProm = async (p) => {
let filename;
filename = p.filename || p.uri.split("/").pop();
await handleLocalUpload({
ev: {
filename,
mediaId: p.id,
onError: (error) => handleOnError(p.id, error),
onProgress: ({ percent, loaded }) =>
handleOnProgress(p.id, percent, loaded),
onSuccess: ({ duration }) => handleOnSuccess(p.id, p, { duration }),
file: p,
},
context: {
bodyshop: bodyshop,
jobid:
selectedCameraJobId !== "temp" ? selectedCameraJobId : "temporary",
},
});
//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 ( return (
<Modal <Modal
visible={progress.uploadInProgress} visible={progress.uploadInProgress}
animationType="slide" animationType="slide"
transparent={true} transparent={true}
onRequestClose={() => {}} onRequestClose={() => {
Alert.alert("Cancel?", "Do you want to abort the upload?", [
{
text: "Yes",
onPress: () => {
setUploads(null);
setProgress(null);
},
},
{ text: "No" },
]);
}}
> >
<View style={styles.modal}> <View style={styles.modalContainer}>
{progress.loading && <ActivityIndicator />} <View style={styles.modal}>
<ActivityIndicator style={{ alignSelf: "center", marginTop: 16 }} />
<ScrollView contentContainerStyle={styles.centeredView}> <ProgressBar
{Object.keys(progress.files).map((key) => ( progress={progress.percent}
<View key={progress.files[key].id} style={styles.progressItem}> style={{ alignSelf: "center", marginTop: 16 }}
<Text style={styles.progressText}> color={progress.percent === 1 ? "green" : "blue"}
{progress.files[key].filename} />
</Text> <Text style={{ alignSelf: "center", marginTop: 16 }}>{`${formatBytes(
<View style={styles.progressBarContainer}> progress.speed
<ProgressBar )}/sec`}</Text>
progress={progress.files[key].percent} </View>
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>
</View>
))}
</ScrollView>
</View> </View>
</Modal> </Modal>
); );
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
modal: { modalContainer: {
display: "flex",
flex: 1, flex: 1,
marginTop: 80, justifyContent: "center",
marginBottom: 60, },
modal: {
// flex: 1,
display: "flex",
marginLeft: 20, marginLeft: 20,
marginRight: 20, marginRight: 20,
backgroundColor: "white", backgroundColor: "white",
@@ -289,26 +201,4 @@ const styles = StyleSheet.create({
shadowRadius: 4, shadowRadius: 4,
elevation: 5, elevation: 5,
}, },
centeredView: {
flex: 1,
// justifyContent: "center",
// alignItems: "center",
marginTop: 22,
},
progressItem: {
display: "flex",
flexDirection: "row",
alignItems: "center",
marginBottom: 12,
marginLeft: 12,
marginRight: 12,
},
progressText: {
flex: 1,
},
progressBarContainer: {
flex: 3,
marginLeft: 12,
marginRight: 12,
},
}); });

View File

@@ -155,9 +155,17 @@ export function ImageBrowserScreen({ bodyshop, selectedCameraJobId }) {
/> />
)} )}
{bodyshop.uselocalmediaserver ? ( {bodyshop.uselocalmediaserver ? (
<LocalUploadProgress uploads={uploads} forceRerender={forceRerender} /> <LocalUploadProgress
uploads={uploads}
setUploads={setUploads}
forceRerender={forceRerender}
/>
) : ( ) : (
<UploadProgress uploads={uploads} forceRerender={forceRerender} /> <UploadProgress
uploads={uploads}
setUploads={setUploads}
forceRerender={forceRerender}
/>
)} )}
</View> </View>
); );

View File

@@ -1,8 +1,7 @@
import axios from "axios"; import axios from "axios";
import * as ImageManipulator from "expo-image-manipulator";
import * as MediaLibrary from "expo-media-library";
import mime from "mime";
import { store } from "../redux/store"; import { store } from "../redux/store";
import mime from "mime";
import * as MediaLibrary from "expo-media-library";
axios.interceptors.request.use( axios.interceptors.request.use(
function (config) { function (config) {
@@ -29,9 +28,14 @@ axios.interceptors.response.use(
} }
); );
export const handleLocalUpload = async ({ ev, context }) => { export const handleLocalUpload = async ({
const { onError, onSuccess, onProgress, filename, mediaId } = ev; files,
const { jobid, invoice_number, vendorid, callbackAfterUpload } = context; onError,
onSuccess,
onProgress,
context,
}) => {
const { jobid } = context;
const bodyshop = store.getState().user.bodyshop; const bodyshop = store.getState().user.bodyshop;
try { try {
var options = { var options = {
@@ -41,26 +45,22 @@ export const handleLocalUpload = async ({ ev, context }) => {
}, },
onUploadProgress: (e) => { onUploadProgress: (e) => {
if (onProgress) if (onProgress)
onProgress({ percent: (e.loaded / e.total) * 100, loaded: e.loaded }); onProgress({ percent: e.loaded / e.total, loaded: e.loaded });
}, },
}; };
const formData = new FormData(); const formData = new FormData();
formData.append("jobid", jobid); formData.append("jobid", jobid);
if (invoice_number) { // const imageData = await MediaLibrary.getAssetInfoAsync(mediaId);
formData.append("invoice_number", invoice_number); // const mimeType = mime.getType(imageData.uri);
formData.append("vendorid", vendorid);
}
const imageData = await MediaLibrary.getAssetInfoAsync(mediaId);
const mimeType = mime.getType(imageData.uri);
//let thumb; // //let thumb;
let fileData = { // let fileData = {
uri: null, // uri: null,
type: null, // type: null,
name: null, // name: null,
}; // };
// if (mimeType === "image/heic") { // if (mimeType === "image/heic") {
// try { // try {
// thumb = await ImageManipulator.manipulateAsync(imageData.uri, [], { // thumb = await ImageManipulator.manipulateAsync(imageData.uri, [], {
@@ -80,25 +80,37 @@ export const handleLocalUpload = async ({ ev, context }) => {
// onError && onError(error.message); // onError && onError(error.message);
// } // }
// } else { // } else {
fileData = { // fileData = {
uri: imageData.localUri || imageData.uri, // uri: imageData.localUri || imageData.uri,
type: mimeType, // type: mimeType,
name: filename, // name: filename,
}; // };
//} //}
formData.append("file", fileData); const filesList = [];
for (const file of files) {
const imageData = await MediaLibrary.getAssetInfoAsync(file.id);
const mimeType = mime.getType(imageData.uri);
filesList.push({
uri: imageData.localUri || imageData.uri,
type: mimeType,
name: imageData.filename,
});
formData.append("file", {
uri: imageData.localUri || imageData.uri,
type: mimeType,
name: imageData.filename,
});
}
//formData.append("file", files);
formData.append("skip_thumbnail", true); formData.append("skip_thumbnail", true);
try { try {
const imexMediaServerResponse = await axios.post( const imexMediaServerResponse = await axios.post(
`${bodyshop.localmediaserverhttp}/${ `${bodyshop.localmediaserverhttp}/jobs/upload`,
invoice_number ? "bills" : "jobs"
}/upload`,
formData, formData,
{ options
...options,
}
); );
if (imexMediaServerResponse.status !== 200) { if (imexMediaServerResponse.status !== 200) {
@@ -113,10 +125,6 @@ export const handleLocalUpload = async ({ ev, context }) => {
duration: imexMediaServerResponse.headers["x-response-time"], duration: imexMediaServerResponse.headers["x-response-time"],
}); });
} }
if (callbackAfterUpload) {
callbackAfterUpload();
}
} catch (error) { } catch (error) {
console.log("Error uploading documents:", error); console.log("Error uploading documents:", error);
onError && onError(error.message); onError && onError(error.message);