WIP replace image selector

This commit is contained in:
Patrick Fic
2025-10-07 13:40:37 -07:00
parent f95b0e1263
commit 83fe7059e9
3 changed files with 134 additions and 451 deletions

View File

@@ -6,7 +6,7 @@ import { client } from "../graphql/client";
import { INSERT_NEW_DOCUMENT } from "../graphql/documents.queries";
import { axiosAuthInterceptorId } from "./CleanAxios";
//import { splitClient } from "../components/screen-main/screen-main.component";
import * as FileSystem from "expo-file-system";
import { File } from "expo-file-system";
//Context: currentUserEmail, bodyshop, jobid, invoiceid
@@ -16,55 +16,35 @@ cleanAxios.interceptors.request.eject(axiosAuthInterceptorId);
export const handleUpload = async (ev, context) => {
const { mediaId, onError, onSuccess, onProgress } = ev;
const { bodyshop, jobId } = context;
const { bodyshop, jobId, photo } = context;
try {
console.log("**** I GOT HERE AT LEAST ****")
const imageData = await MediaLibrary.getAssetInfoAsync(mediaId);
const imageUri = imageData.localUri || imageData.uri
const newFile = await (
await fetch(imageUri)
).blob();
let extension = imageData.filename.split(".").pop();
//Default to Cloudinary in case of split treatment errors.
let destination =
splitClient?.getTreatment("Imgproxy") === "on" ? "imgproxy" : "cloudinary";
let key = `${bodyshop.id}/${jobId}/${replaceAccents(
imageData.filename || imageUri.split("/").pop()
).replace(/[^A-Z0-9]+/gi, "_")}-${new Date().getTime()}.${extension}`
let key =
destination === "imgproxy"
? `${bodyshop.id}/${jobId}/${replaceAccents(
imageData.filename || imageUri.split("/").pop()
).replace(/[^A-Z0-9]+/gi, "_")}-${new Date().getTime()}.${extension}`
: `${bodyshop.id}/${jobId}/${(
imageData.filename || imageUri.split("/").pop()
).replace(/\.[^/.]+$/, "")}-${new Date().getTime()}`;
const res =
destination === "imgproxy"
? await uploadToImgproxy(
key,
mediaId,
imageData,
extension,
newFile.type, //Filetype
newFile, //File
onError,
onSuccess,
onProgress,
context
)
: await uploadToCloudinary(
key,
mediaId,
imageData,
extension,
newFile.type, //Filetype
newFile, //File
onError,
onSuccess,
onProgress,
context
);
await uploadToImgproxy(
key,
mediaId,
imageData,
extension,
newFile.type, //Filetype
newFile, //File
onError,
onSuccess,
onProgress,
context
)
return res;
} catch (error) {
console.log("Error creating upload promise", error.message, error.stack);
@@ -79,34 +59,6 @@ export const handleUpload = async (ev, context) => {
}
};
export const handleUploadImgproxy = async (ev, context) => {
const { mediaId, onError, onSuccess, onProgress } = ev;
const { bodyshop, jobId } = context;
const imageData = await MediaLibrary.getAssetInfoAsync(mediaId);
const imageUri = imageData.localUri || imageData.uri
const newFile = await (
await fetch(imageUri)
).blob();
let extension = imageUri.split(".").pop();
let key = `${bodyshop.id}/${jobId}/${(
imageData.filename || imageUri.split("/").pop()
).replace(/\.[^/.]+$/, "")}-${new Date().getTime()}`;
const res = await uploadToImgproxy(
key,
mediaId,
imageData,
extension,
newFile.type, //Filetype
newFile, //File
onError,
onSuccess,
onProgress,
context
);
return res;
};
export const uploadToImgproxy = async (
key,
mediaId,
@@ -230,142 +182,6 @@ export const uploadToImgproxy = async (
return { success: true, mediaId };
};
export const uploadToCloudinary = async (
key,
mediaId,
imageData,
extension,
fileType,
file,
onError,
onSuccess,
onProgress,
context
) => {
const { bodyshop, jobId, uploaded_by } = context;
//Set variables for getting the signed URL.
let timestamp = Math.floor(Date.now() / 1000);
let public_id = key;
const upload_preset = fileType.startsWith("video")
? "incoming_upload_video"
: "incoming_upload";
//Get the signed url.
let signedURLResponse;
try {
signedURLResponse = await axios.post(`${env.API_URL}/media/sign`, {
public_id: public_id,
timestamp: timestamp,
upload_preset: upload_preset,
});
} catch (error) {
console.log("ERROR GETTING SIGNED URL", error);
Sentry.captureException(error);
return { success: false, error: error };
}
if (signedURLResponse.status !== 200) {
console.log("Error Getting Signed URL", signedURLResponse.statusText);
if (onError) onError(signedURLResponse.statusText);
return { success: false, error: signedURLResponse.statusText };
}
//Build request to end to cloudinary.
var signature = signedURLResponse.data;
var options = {
headers: {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "multipart/form-data",
},
onUploadProgress: (e) => {
if (onProgress)
onProgress({ percent: e.loaded / e.total, loaded: e.loaded });
},
};
const formData = new FormData();
formData.append("file", {
uri: imageData.localUri,
type: fileType,
name: file.data.name,
});
formData.append("upload_preset", upload_preset);
formData.append("api_key", env.REACT_APP_CLOUDINARY_API_KEY);
formData.append("public_id", public_id);
formData.append("timestamp", timestamp);
formData.append("signature", signature);
//Upload request to Cloudinary
let cloudinaryUploadResponse;
try {
cloudinaryUploadResponse = await cleanAxios.post(
`${env.REACT_APP_CLOUDINARY_ENDPOINT_API}/${DetermineFileType(
fileType
)}/upload`,
formData,
options
);
} catch (error) {
console.log("CLOUDINARY error", error.response, cloudinaryUploadResponse);
Sentry.captureException(error);
if (onError) onError(error.message);
return { success: false, error: error };
}
if (cloudinaryUploadResponse.status !== 200) {
console.log(
"Error uploading to cloudinary.",
cloudinaryUploadResponse.statusText,
cloudinaryUploadResponse
);
if (onError) onError(cloudinaryUploadResponse.statusText);
return { success: false, error: cloudinaryUploadResponse.statusText };
}
//Insert the document with the matching key.
const documentInsert = await client.mutate({
mutation: INSERT_NEW_DOCUMENT,
variables: {
docInput: [
{
...(jobId ? { jobid: jobId } : {}),
uploaded_by: uploaded_by,
key: key,
type: fileType,
extension: extension,
bodyshopid: bodyshop.id,
size: cloudinaryUploadResponse.data.bytes || file.size,
...(imageData.creationTime
? { takenat: new Date(imageData.creationTime) }
: {}),
},
],
},
});
if (!documentInsert.errors) {
if (onSuccess)
onSuccess({
uid: documentInsert.data.insert_documents.returning[0].id,
name: documentInsert.data.insert_documents.returning[0].name,
status: "done",
key: documentInsert.data.insert_documents.returning[0].key,
});
} else {
if (onError) onError(JSON.stringify(documentInsert.errors));
return {
success: false,
error: JSON.stringify(documentInsert.errors),
mediaId,
};
}
return { success: true, mediaId };
};
export function DetermineFileType(filetype) {
if (!filetype) return "auto";
else if (filetype.startsWith("image")) return "image";