Improved document uploads & remove console logs.

This commit is contained in:
Patrick Fic
2021-06-01 08:49:29 -07:00
parent fd52e72364
commit 659881e012
15 changed files with 350 additions and 190 deletions

View File

@@ -32,8 +32,6 @@ export default function JobDocumentsComponent({ job, loading, refetch }) {
[job.documents]
);
console.log(job.documents);
return (
<View style={{ flex: 1 }}>
<FlatList

View File

@@ -1,142 +1,31 @@
import { useApolloClient } from "@apollo/client";
import { Ionicons } from "@expo/vector-icons";
//const limit = plimit(2);
import * as FileSystem from "expo-file-system";
import { AssetsSelector } from "expo-images-picker";
import * as MediaLibrary from "expo-media-library";
import _ from "lodash";
import React, { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { Alert, StyleSheet, Text, View } from "react-native";
import { StyleSheet, Text, View } from "react-native";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.analytics";
import { GET_DOC_SIZE_TOTALS } from "../../graphql/documents.queries";
import {
selectCurrentCameraJobId,
selectDeleteAfterUpload,
} from "../../redux/app/app.selectors";
import {
selectBodyshop,
selectCurrentUser,
} from "../../redux/user/user.selectors";
import { handleUpload } from "../../util/document-upload.utility";
import { selectCurrentCameraJobId } from "../../redux/app/app.selectors";
import CameraSelectJob from "../camera-select-job/camera-select-job.component";
import UploadDeleteSwitch from "../upload-delete-switch/upload-delete-switch.component";
import UploadProgress from "../upload-progress/upload-progress.component";
const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUser,
bodyshop: selectBodyshop,
selectedCameraJobId: selectCurrentCameraJobId,
deleteAfterUpload: selectDeleteAfterUpload,
});
export function ImageBrowserScreen({
currentUser,
bodyshop,
selectedCameraJobId,
deleteAfterUpload,
}) {
export function ImageBrowserScreen({ selectedCameraJobId }) {
const { t } = useTranslation();
const [uploads, setUploads] = useState({});
function handleOnProgress(uri, percent) {
setUploads((prevUploads) => ({ ...prevUploads, [uri]: { percent } }));
}
const [uploads, setUploads] = useState(null);
const [tick, setTick] = useState(0);
const forceRerender = useCallback(() => {
setTick((tick) => tick + 1);
}, []);
const client = useApolloClient();
async function handleOnSuccess(uri, id) {
logImEXEvent("imexmobile_successful_upload");
setUploads((prevUploads) => _.omit(prevUploads, uri));
}
const onDone = async (data) => {
const onDone = (data) => {
logImEXEvent("imexmobile_upload_documents", { count: data.length });
//Validate to make sure the totals for the file sizes do not exceed the total on the job.
if (selectedCameraJobId !== "temp") {
const queryData = await client.query({
query: GET_DOC_SIZE_TOTALS,
fetchPolicy: "network-only",
variables: {
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 });
return (await acc) + info.size;
}, 0);
// console.log(
// "Size of uploaded documents.",
// queryData.data.documents_aggregate.aggregate.sum.size,
// "Shop Limit",
// bodyshop.jobsizelimit,
// "Space remaining",
// bodyshop.jobsizelimit -
// queryData.data.documents_aggregate.aggregate.sum.size,
// "Total of uploaded files",
// totalOfUploads
// );
if (
bodyshop.jobsizelimit -
queryData.data.documents_aggregate.aggregate.sum.size <=
totalOfUploads
) {
//No more room... abandon ship.
Alert.alert(
t("mediabrowser.labels.storageexceeded_title"),
t("mediabrowser.labels.storageexceeded")
);
return;
}
}
const ret = await Promise.all(
data.map(async (p) => {
let filename;
//Appears to work for android.
//iOS provides the filename, android doe snot.
filename = p.filename || p.uri.split("/").pop();
const result = await handleUpload(
{
//iOS provides the file name. Android does not.
filename,
mediaId: p.id,
onError: handleOnError,
onProgress: ({ percent }) => handleOnProgress(filename, percent),
onSuccess: () => handleOnSuccess(filename, p.id),
},
{
bodyshop: bodyshop,
jobId: selectedCameraJobId !== "temp" ? selectedCameraJobId : null,
uploaded_by: currentUser.email,
photo: p,
}
);
return result;
})
);
if (deleteAfterUpload) {
try {
await MediaLibrary.deleteAssetsAsync(ret.map((r) => r.mediaId));
} catch (error) {
console.log("Unable to delete picture.", error);
}
}
forceRerender();
setUploads(data);
};
return (
@@ -159,14 +48,7 @@ export function ImageBrowserScreen({
style={{ flex: 1 }}
key={tick}
options={{
// manipulate: {
// //width: 512,
// compress: 0.7,
// base64: false,
// saveTo: "jpeg",
// },
assetsType: ["photo", "video"],
//maxSelections: 5,
margin: 3,
portraitCols: 4,
landscapeCols: 6,
@@ -223,7 +105,7 @@ export function ImageBrowserScreen({
}}
/>
)}
<UploadProgress uploads={uploads} setUploads={setUploads} />
<UploadProgress uploads={uploads} forceRerender={forceRerender} />
</View>
);
}
@@ -245,9 +127,4 @@ const styles = StyleSheet.create({
},
});
function handleOnError(...props) {
console.log("HandleOnError", props);
logImEXEvent("imexmobile_upload_documents_error", { props });
}
export default connect(mapStateToProps, null)(ImageBrowserScreen);

View File

@@ -9,8 +9,6 @@ import * as Updates from "expo-updates";
export default function ScreenSettingsComponent() {
const { t } = useTranslation();
console.log(Constants.manifest);
return (
<View
style={{

View File

@@ -1,51 +1,271 @@
import { Ionicons } from "@expo/vector-icons";
import { useApolloClient } from "@apollo/client";
import * as FileSystem from "expo-file-system";
import * as MediaLibrary from "expo-media-library";
import _ from "lodash";
import React, { useMemo } from "react";
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
ActivityIndicator,
Alert,
Modal,
ScrollView,
StyleSheet,
Text,
TouchableOpacity,
View,
} from "react-native";
import * as Progress from "react-native-progress";
export default function UploadProgress({ uploads, setUploads }) {
const uploadKeys = useMemo(() => {
if (uploads) return Object.keys(uploads);
return [];
import { ProgressBar } from "react-native-paper";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.analytics";
import { GET_DOC_SIZE_TOTALS } from "../../graphql/documents.queries";
import {
selectCurrentCameraJobId,
selectDeleteAfterUpload,
} from "../../redux/app/app.selectors";
import {
selectBodyshop,
selectCurrentUser,
} from "../../redux/user/user.selectors";
import { formatBytes, handleUpload } from "../../util/document-upload.utility";
const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUser,
bodyshop: selectBodyshop,
selectedCameraJobId: selectCurrentCameraJobId,
deleteAfterUpload: selectDeleteAfterUpload,
});
export default connect(mapStateToProps, null)(UploadProgress);
export function UploadProgress({
currentUser,
bodyshop,
selectedCameraJobId,
deleteAfterUpload,
uploads,
forceRerender,
}) {
const [progress, setProgress] = useState({
loading: false,
uploadInProgress: false,
speed: 0,
files: {}, //uri is the key, value is progress
});
const client = useApolloClient();
const { t } = useTranslation();
useEffect(() => {
//Set the state of uploads to do.
if (uploads) onDone(uploads);
}, [uploads]);
//if (!uploads) return null;
function handleOnSuccess(id) {
logImEXEvent("imexmobile_successful_upload");
setProgress((progress) => ({
...progress,
action: t("mediabrowser.labels.converting"),
files: {
...progress.files,
[id]: {
...progress.files[id],
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,
action:
percent === 1
? t("mediabrowser.labels.converting")
: t("mediabrowser.labels.uploading"),
loaded: loaded,
},
},
}));
}
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,
});
if (selectedCameraJobId !== "temp") {
const queryData = await client.query({
query: GET_DOC_SIZE_TOTALS,
fetchPolicy: "network-only",
variables: {
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 });
return (await acc) + info.size;
}, 0);
if (
bodyshop.jobsizelimit -
queryData.data.documents_aggregate.aggregate.sum.size <=
totalOfUploads
) {
//No more room... abandon ship.
setProgress((progress) => ({
...progress,
speed: 0,
action: null,
loading: false,
uploadInProgress: false,
}));
Alert.alert(
t("mediabrowser.labels.storageexceeded_title"),
t("mediabrowser.labels.storageexceeded")
);
return;
}
}
//Sequentially await the proms.
for (const p of data) {
let filename;
filename = p.filename || p.uri.split("/").pop();
await handleUpload(
{
filename,
mediaId: p.id,
onError: handleOnError,
onProgress: ({ percent, loaded }) =>
handleOnProgress(p.id, percent, loaded),
onSuccess: () => handleOnSuccess(p.id),
},
{
bodyshop: bodyshop,
jobId: selectedCameraJobId !== "temp" ? selectedCameraJobId : null,
uploaded_by: currentUser.email,
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,
},
},
}));
}
if (deleteAfterUpload) {
try {
await MediaLibrary.deleteAssetsAsync(Object.keys(progress.files));
} catch (error) {
console.log("Unable to delete picture.", error);
}
}
setProgress({
loading: false,
speed: 0,
action: null,
uploadInProgress: false,
files: {}, //uri is the key, value is progress
});
forceRerender();
};
console.log("speed", progress.speed, progress.speed !== 0);
return (
<View style={styles.container}>
<ScrollView>
{uploadKeys.map((key) => (
<View key={key} style={styles.progressItem}>
<Text style={styles.progressText}>{key}</Text>
<View style={styles.progressBarContainer}>
<Progress.Bar
style={styles.progress}
height={10}
width={null}
progress={uploads[key].percent}
color={uploads[key].percent === 1 ? "green" : "blue"}
/>
<Modal
visible={progress.uploadInProgress}
animationType="slide"
transparent={true}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
}}
>
<View style={styles.modal}>
{progress.loading && <ActivityIndicator />}
{progress.action && (
<Text>{`${progress.action} ${
(progress.speed !== 0 || !progress.speed) &&
`- ${formatBytes(progress.speed)}/sec`
}`}</Text>
)}
<ScrollView contentContainerStyle={styles.centeredView}>
{Object.keys(progress.files).map((key) => (
<View key={progress.files[key].id} style={styles.progressItem}>
<Text style={styles.progressText}>
{progress.files[key].filename}
</Text>
<View style={styles.progressBarContainer}>
<ProgressBar
progress={progress.files[key].percent}
style={styles.progress}
color={progress.files[key].percent === 1 ? "green" : "blue"}
/>
</View>
</View>
<TouchableOpacity
onPress={() =>
setUploads((prevUploads) => _.omit(prevUploads, key))
}
>
<Ionicons name="ios-close" size={32} />
</TouchableOpacity>
</View>
))}
</ScrollView>
</View>
))}
</ScrollView>
</View>
</Modal>
);
}
const styles = StyleSheet.create({
container: {
display: "flex",
modal: {
flex: 1,
marginTop: 50,
marginBottom: 60,
marginLeft: 20,
marginRight: 20,
backgroundColor: "white",
borderRadius: 20,
padding: 18,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5,
},
centeredView: {
flex: 1,
// justifyContent: "center",
// alignItems: "center",
marginTop: 22,
},
progressItem: {
display: "flex",