Progress update cleanup and UI improvements.

This commit is contained in:
Patrick Fic
2025-10-16 14:29:10 -07:00
parent 93a539bd6d
commit 31d151c3b4
17 changed files with 373 additions and 109 deletions

View File

@@ -31,7 +31,25 @@ export const mediaUploadProgressBulk = (info) => ({
});
export const mediaUploadCompleted = (photo) => ({
type: PhotosActionTypes.MEDIA_UPLOAD_COMPLETED
//payload: photo,
type: PhotosActionTypes.MEDIA_UPLOAD_COMPLETED,
payload: photo,
});
export const deleteMedia = (photos) => ({
type: PhotosActionTypes.DELETE_MEDIA,
payload: photos,
});
export const deleteMediaSuccess = (photos) => ({
type: PhotosActionTypes.DELETE_MEDIA_SUCCESS,
payload: photos,
});
export const deleteMediaFailure = (photos) => ({
type: PhotosActionTypes.DELETE_MEDIA_FAILURE,
payload: photos,
});
export const clearUploadError = () => ({
type: PhotosActionTypes.CLEAR_UPLOAD_ERROR,
});

View File

@@ -33,7 +33,7 @@ const photosReducer = (state = INITIAL_STATE, action) => {
case PhotosActionTypes.MEDIA_UPLOAD_SUCCESS_ONE:
return {
...state,
progress: { ...state.progress, [action.payload.assetId]: { ...state.progress[action.payload.assetId], progress: 100, status: 'completed' } }
progress: { ...state.progress, [action.payload.assetId]: { ...state.progress[action.payload.assetId], progress: 100, status: 'completed', endTime: new Date() } }
};
case PhotosActionTypes.MEDIA_UPLOAD_PROGRESS_UPDATE_BULK:
return {
@@ -48,6 +48,12 @@ const photosReducer = (state = INITIAL_STATE, action) => {
photos: [],
progress: {}
};
case PhotosActionTypes.CLEAR_UPLOAD_ERROR:
return {
...state,
photos: [], progress: {},
uploadError: null,
};
default:
return state;
}

View File

@@ -1,15 +1,17 @@
import axios from "axios";
import Constants from "expo-constants";
import * as ImagePicker from "expo-image-picker";
import * as MediaLibrary from "expo-media-library";
import moment from 'moment';
import { all, call, delay, fork, put, select, takeEvery, takeLatest } from "redux-saga/effects";
import { all, call, delay, put, select, takeEvery, takeLatest } from "redux-saga/effects";
import env from "../../env";
import { client } from '../../graphql/client';
import { INSERT_NEW_DOCUMENT } from "../../graphql/documents.queries";
import { GET_DOC_SIZE_TOTALS, INSERT_NEW_DOCUMENT } from "../../graphql/documents.queries";
import { axiosAuthInterceptorId } from "../../util/CleanAxios";
import { fetchImageFromUri, replaceAccents } from '../../util/uploadUtils';
import { selectBodyshop, selectCurrentUser } from "../user/user.selectors";
import {
deleteMediaSuccess,
mediaUploadCompleted,
mediaUploadFailure,
mediaUploadProgressBulk,
@@ -18,14 +20,40 @@ import {
mediaUploadSuccessOne
} from "./photos.actions";
import i18n from "@/translations/i18n";
import { Platform } from "react-native";
import { selectDeleteAfterUpload } from "../app/app.selectors";
import PhotosActionTypes from "./photos.types";
axios.interceptors.request.use(
function (config) {
config.metadata = { startTime: new Date() };
return config;
},
function (error) {
return Promise.reject(error);
}
);
axios.interceptors.response.use(
function (response) {
response.config.metadata.endTime = new Date();
response.duration =
response.config.metadata.endTime - response.config.metadata.startTime;
return response;
},
function (error) {
error.config.metadata.endTime = new Date();
error.duration =
error.config.metadata.endTime - error.config.metadata.startTime;
return Promise.reject(error);
}
);
//Required to prevent headers from getting set and rejected from Cloudinary.
let cleanAxios = axios.create();
cleanAxios.interceptors.request.eject(axiosAuthInterceptorId);
export function* onOpenImagePicker() {
yield takeLatest(PhotosActionTypes.OPEN_IMAGE_PICKER, openImagePickerAction);
}
@@ -73,6 +101,17 @@ export function* mediaUploadStartAction({ payload: { photos, jobid } }) {
yield call(uploadToLocalMediaServer, photos, bodyshop, jobid);
}
else {
//Check to see if the job has enough space before uploading.
const hasEnoughSpace = yield call(checkJobSpace, jobid, photos, bodyshop);
if (!hasEnoughSpace) {
alert(i18n.t("mediabrowser.labels.storageexceeded"));
yield put(mediaUploadFailure(i18n.t("mediabrowser.labels.storageexceeded")));
return;
}
// Process photos in batches to avoid overwhelming the system
const batchSize = 3; // Upload 3 photos concurrently
const batches = [];
@@ -83,7 +122,7 @@ export function* mediaUploadStartAction({ payload: { photos, jobid } }) {
// Process each batch sequentially, but photos within batch concurrently
for (const batch of batches) {
const uploadTasks = batch.map((photo, index) =>
fork(uploadSinglePhoto, photo, bodyshop, index, jobid)
call(uploadSinglePhoto, photo, bodyshop, index, jobid)
);
// Wait for current batch to complete before starting next batch
yield all(uploadTasks);
@@ -91,7 +130,8 @@ export function* mediaUploadStartAction({ payload: { photos, jobid } }) {
yield delay(100);
}
}
yield put(mediaUploadCompleted());
console.log("All uploads completed. This shouldn't fire before the uploads are done.");
yield put(mediaUploadCompleted(photos));
} catch (error) {
console.log("Saga Error: upload start", error, error.stack);
@@ -99,6 +139,44 @@ export function* mediaUploadStartAction({ payload: { photos, jobid } }) {
}
}
function* checkJobSpace(jobid, photos, bodyshop) {
try {
const totalOfUploads = photos.reduce((acc, val) => {
//Get the size of the file based on URI.
if (val.fileSize) {
return acc + val.fileSize;
} else {
alert("Asset is missing filesize. Cannot verify job space.");
return acc
}
}, 0);
if (jobid !== "temp") {
const queryData = yield call(client.query, {
query: GET_DOC_SIZE_TOTALS,
fetchPolicy: "network-only",
variables: {
jobId: jobid,
},
});
if (
bodyshop.jobsizelimit -
queryData?.data?.documents_aggregate.aggregate.sum.size <=
totalOfUploads
) {
//No more room... abandon ship.
return false;
}
}
return true;
}
catch (error) {
console.log("Error checking job space", error, error.stack);
return false;
}
}
function* uploadSinglePhoto(photo, bodyshop, index, jobid) {
try {
yield put(mediaUploadProgressOne({ ...photo, status: 'starting', progress: 0 }));
@@ -110,9 +188,7 @@ function* uploadSinglePhoto(photo, bodyshop, index, jobid) {
photoBlob.data.name
).replace(/[^A-Z0-9]+/gi, "_")}-${new Date().getTime()}.${extension}`
yield call(uploadToImageProxy, photo, photoBlob, extension, key, bodyshop, jobid);
yield put(mediaUploadSuccessOne(photo));
} catch (error) {
console.log(`Upload failed for photo ${photo.uri}:`, error);
yield put(mediaUploadFailure({ ...photo, status: "error", error: error.message }));
@@ -127,7 +203,7 @@ function* uploadToLocalMediaServer(photos, bodyshop, jobid) {
ims_token: bodyshop.localmediatoken,
},
onUploadProgress: (e) => {
put(mediaUploadProgressBulk({ progress: e.loaded / e.total, loaded: e.loaded }));
put(mediaUploadProgressBulk({ progress: e.loaded / e.total, loaded: e.loaded, total: e.total }));
},
};
@@ -150,31 +226,22 @@ function* uploadToLocalMediaServer(photos, bodyshop, jobid) {
formData,
options
);
if (imexMediaServerResponse.status !== 200) {
console.log("Error uploading documents:", JSON.stringify(imexMediaServerResponse, null, 2));
} else {
// onSuccess({
// duration: imexMediaServerResponse.headers["x-response-time"],
// });
console.log("Local media server upload complete:", imexMediaServerResponse.data);
}
} catch (error) {
console.log("Error uploading documents:", error.message, JSON.stringify(error, null, 2));
}
} catch (error) {
console.log("Uncaught error", error);
}
}
function* uploadToImageProxy(photo, photoBlob, extension, key, bodyshop, jobid) {
try {
yield put(mediaUploadProgressOne({ ...photo, status: 'uploading', }));
yield put(mediaUploadProgressOne({ ...photo, startTime: new Date(), status: 'uploading', }));
//Get the signed url allowing us to PUT to S3.
const signedURLResponse = yield call(axios.post,
`${env.API_URL}/media/imgproxy/sign`,
@@ -184,7 +251,6 @@ function* uploadToImageProxy(photo, photoBlob, extension, key, bodyshop, jobid)
jobid,
}
);
if (signedURLResponse.status !== 200) {
console.log("Error Getting Signed URL", signedURLResponse.statusText);
throw new Error(`Error getting signed URL : ${signedURLResponse.statusText}`);
@@ -228,10 +294,17 @@ function* uploadToImageProxy(photo, photoBlob, extension, key, bodyshop, jobid)
//Create doc record.
const uploaded_by = yield select(selectCurrentUser);
const [date, time] = photo.exif?.DateTime?.split(' ') || [];
const [year, month, day] = date ? date.split(':') : [];
const [hours, minutes, seconds] = time ? time.split(':') : [];
const pictureMoment = moment(`${year}-${month}-${day}T${hours}:${minutes}:${seconds}`);
let pictureMoment = null;
try {
if (photo.exif) {
const [date, time] = photo.exif?.DateTime?.split(' ') || [];
const [year, month, day] = date ? date.split(':') : [];
const [hours, minutes, seconds] = time ? time.split(':') : [];
pictureMoment = moment(`${year}-${month}-${day}T${hours}:${minutes}:${seconds}`);
}
} catch (exifError) {
console.log('Error parsing exif date. Unable to set created date.', exifError);
}
yield call(client.mutate, ({
mutation: INSERT_NEW_DOCUMENT,
@@ -245,13 +318,14 @@ function* uploadToImageProxy(photo, photoBlob, extension, key, bodyshop, jobid)
extension: extension,
bodyshopid: bodyshop.id,
size: photoBlob.size,
...(photo.exif?.DateTime //TODO :Need to find how to do this.
...(pictureMoment && pictureMoment.isValid()
? { takenat: pictureMoment }
: {}),
},
],
},
}));
console.log("Upload and record creation successful for", photo.uri);
}
} catch (error) {
@@ -261,7 +335,7 @@ function* uploadToImageProxy(photo, photoBlob, extension, key, bodyshop, jobid)
}
// Handle cancellation of uploads
export function* onCancelUpload() {
function* onCancelUpload() {
yield takeEvery(PhotosActionTypes.CANCEL_UPLOAD, cancelUploadAction);
}
@@ -274,10 +348,62 @@ function* cancelUploadAction({ payload: photoId }) {
// }
}
function* onMediaUploadCompleted() {
yield takeLatest(PhotosActionTypes.MEDIA_UPLOAD_COMPLETED, mediaUploadCompletedAction);
}
function* mediaUploadCompletedAction({ payload: photos }) {
//Check if this should be getting deleted
const deletedAfterUpload = yield select(selectDeleteAfterUpload);
if (
!deletedAfterUpload
) {
//Nothing to do here.
return;
}
try {
// Handle the completion of media uploads
const filesToDelete = [...photos]
if (Platform.OS === "android") {
//Create a new asset with the first file to delete.
// console.log('Trying new delete.');
yield MediaLibrary.getPermissionsAsync(false);
const album = yield call(MediaLibrary.createAlbumAsync,
"ImEX Mobile Deleted",
filesToDelete.pop(),
false
);
//Move the rest.
if (filesToDelete.length > 0) {
const moveResult = yield call(MediaLibrary.addAssetsToAlbumAsync,
filesToDelete,
album,
false
);
}
yield call(MediaLibrary.deleteAlbumsAsync, album);
} else {
yield call(MediaLibrary.deleteAssetsAsync, filesToDelete.map(f => f.assetId));
}
yield put(deleteMediaSuccess(photos));
} catch (error) {
console.log("Saga Error: upload start", error, error.stack);
yield put(mediaUploadFailure(error.message));
}
}
export function* photosSagas() {
yield all([
call(onOpenImagePicker),
call(onMediaUploadStart),
call(onMediaUploadCompleted)
//call(onCancelUpload)
]);
}

View File

@@ -6,5 +6,9 @@ const PhotosActionTypes = {
MEDIA_UPLOAD_PROGRESS_UPDATE_ONE: "MEDIA_UPLOAD_PROGRESS_UPDATE_ONE",
MEDIA_UPLOAD_PROGRESS_UPDATE_BULK: "MEDIA_UPLOAD_PROGRESS_UPDATE_BULK",
MEDIA_UPLOAD_COMPLETED: "MEDIA_UPLOAD_COMPLETED",
DELETE_MEDIA: "DELETE_MEDIA",
DELETE_MEDIA_SUCCESS: "DELETE_MEDIA_SUCCESS",
DELETE_MEDIA_FAILURE: "DELETE_MEDIA_FAILURE",
CLEAR_UPLOAD_ERROR: "CLEAR_UPLOAD_ERROR",
};
export default PhotosActionTypes;