diff --git a/src/Common/hooks/useMSEplayer.ts b/src/Common/hooks/useMSEplayer.ts index 898da28f3ad..23f9e7b70c7 100644 --- a/src/Common/hooks/useMSEplayer.ts +++ b/src/Common/hooks/useMSEplayer.ts @@ -1,5 +1,4 @@ import { useEffect, useRef } from "react"; -import axios from "axios"; export interface IAsset { middlewareHostname: string; @@ -45,9 +44,18 @@ const stopStream = (payload: { id: string }, options: IOptions) => { const { id } = payload; ws?.close(); - axios - .post(`https://${middlewareHostname}/stop`, { - id, + fetch(`https://${middlewareHostname}/stop`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ id }), + }) + .then((res) => { + if (!res.ok) { + throw new Error("network response was not ok"); + } + return res.json(); }) .then((res) => options?.onSuccess && options.onSuccess(res)) .catch((err) => options.onError && options.onError(err)); diff --git a/src/Components/Assets/AssetType/ONVIFCamera.tsx b/src/Components/Assets/AssetType/ONVIFCamera.tsx index 86b7199cdac..ba023788496 100644 --- a/src/Components/Assets/AssetType/ONVIFCamera.tsx +++ b/src/Components/Assets/AssetType/ONVIFCamera.tsx @@ -2,7 +2,6 @@ import { useEffect, useState } from "react"; import { AssetData, ResolvedMiddleware } from "../AssetTypes"; import * as Notification from "../../../Utils/Notifications.js"; import { BedModel } from "../../Facility/models"; -import axios from "axios"; import { getCameraConfig } from "../../../Utils/transformUtils"; import CameraConfigure from "../configure/CameraConfigure"; import Loading from "../../Common/Loading"; @@ -100,13 +99,18 @@ const ONVIFCamera = ({ assetId, facilityId, asset, onUpdated }: Props) => { }; try { setLoadingAddPreset(true); - const presetData = await axios.get( + + const response = await fetch( `https://${resolvedMiddleware?.hostname}/status?hostname=${config.hostname}&port=${config.port}&username=${config.username}&password=${config.password}` ); + if (!response.ok) { + throw new Error("Network error"); + } + const presetData = await response.json(); const { res } = await request(routes.createAssetBed, { body: { - meta: { ...data, ...presetData.data }, + meta: { ...data, ...presetData }, asset: assetId, bed: bed?.id as string, }, diff --git a/src/Components/Facility/CoverImageEditModal.tsx b/src/Components/Facility/CoverImageEditModal.tsx index 8de463ad9b5..5e6e505617f 100644 --- a/src/Components/Facility/CoverImageEditModal.tsx +++ b/src/Components/Facility/CoverImageEditModal.tsx @@ -1,4 +1,3 @@ -import axios from "axios"; import { ChangeEventHandler, useCallback, @@ -20,6 +19,7 @@ import { LocalStorageKeys } from "../../Common/constants"; import DialogModal from "../Common/Dialog"; import request from "../../Utils/request/request"; import routes from "../../Redux/api"; +import uploadFile from "../../Utils/request/uploadFile"; interface Props { open: boolean; onClose: (() => void) | undefined; @@ -105,34 +105,35 @@ const CoverImageEditModal = ({ const formData = new FormData(); formData.append("cover_image", selectedFile); - + const url = `/api/v1/facility/${facility.id}/cover_image/`; setIsUploading(true); - try { - const response = await axios.post( - `/api/v1/facility/${facility.id}/cover_image/`, - formData, - { - headers: { - "Content-Type": "multipart/form-data", - Authorization: - "Bearer " + localStorage.getItem(LocalStorageKeys.accessToken), - }, + + uploadFile( + url, + formData, + "POST", + { + Authorization: + "Bearer " + localStorage.getItem(LocalStorageKeys.accessToken), + }, + (xhr: XMLHttpRequest) => { + if (xhr.status === 200) { + Success({ msg: "Cover image updated." }); + } else { + Notification.Error({ + msg: "Something went wrong!", + }); + setIsUploading(false); } - ); - if (response.status === 200) { - Success({ msg: "Cover image updated." }); - } else { + }, + null, + () => { Notification.Error({ - msg: "Something went wrong!", + msg: "Network Failure. Please check your internet connectivity.", }); setIsUploading(false); } - } catch (e) { - Notification.Error({ - msg: "Network Failure. Please check your internet connectivity.", - }); - setIsUploading(false); - } + ); await sleep(1000); setIsUploading(false); diff --git a/src/Components/Patient/FileUpload.tsx b/src/Components/Patient/FileUpload.tsx index f8d6583f24c..1b1ee8f67dd 100644 --- a/src/Components/Patient/FileUpload.tsx +++ b/src/Components/Patient/FileUpload.tsx @@ -1,4 +1,3 @@ -import axios from "axios"; import CircularProgress from "../Common/components/CircularProgress"; import { useCallback, @@ -33,6 +32,7 @@ import useQuery from "../../Utils/request/useQuery"; import routes from "../../Redux/api"; import request from "../../Utils/request/request"; import FilePreviewDialog from "../Common/FilePreviewDialog"; +import uploadFile from "../../Utils/request/uploadFile"; const Loading = lazy(() => import("../Common/Loading")); @@ -936,42 +936,41 @@ export const FileUpload = (props: FileUploadProps) => { const f = file; if (!f) return; const newFile = new File([f], `${internal_name}`); - - const config = { - headers: { - "Content-type": file?.type, - "Content-disposition": "inline", - }, - onUploadProgress: (progressEvent: any) => { - const percentCompleted = Math.round( - (progressEvent.loaded * 100) / progressEvent.total - ); - setUploadPercent(percentCompleted); - }, - }; - + console.log("filetype: ", newFile.type); return new Promise((resolve, reject) => { - axios - .put(url, newFile, config) - .then(() => { - setUploadStarted(false); - // setUploadSuccess(true); - setFile(null); - setUploadFileName(""); - fetchData(); - Notification.Success({ - msg: "File Uploaded Successfully", - }); - setUploadFileError(""); - resolve(); - }) - .catch((e) => { + uploadFile( + url, + newFile, + "PUT", + { "Content-Type": file?.type }, + (xhr: XMLHttpRequest) => { + if (xhr.status >= 200 && xhr.status < 300) { + setUploadStarted(false); + setFile(null); + setUploadFileName(""); + fetchData(); + Notification.Success({ + msg: "File Uploaded Successfully", + }); + setUploadFileError(""); + resolve(); + } else { + Notification.Error({ + msg: "Error Uploading File: " + xhr.statusText, + }); + setUploadStarted(false); + reject(); + } + }, + setUploadPercent, + () => { Notification.Error({ - msg: "Error Uploading File: " + e.message, + msg: "Error Uploading File: Network Error", }); setUploadStarted(false); reject(); - }); + } + ); }); }; @@ -1049,33 +1048,30 @@ export const FileUpload = (props: FileUploadProps) => { const f = audioBlob; if (f === undefined) return; const newFile = new File([f], `${internal_name}`, { type: f.type }); - const config = { - headers: { - "Content-type": newFile?.type, - "Content-disposition": "inline", - }, - onUploadProgress: (progressEvent: any) => { - const percentCompleted = Math.round( - (progressEvent.loaded * 100) / progressEvent.total - ); - setUploadPercent(percentCompleted); - }, - }; - axios - .put(url, newFile, config) - .then(() => { - setAudioUploadStarted(false); - // setUploadSuccess(true); - setAudioName(""); - fetchData(); - Notification.Success({ - msg: "File Uploaded Successfully", - }); - }) - .catch(() => { + uploadFile( + url, + newFile, + "PUT", + { "Content-Type": newFile?.type }, + (xhr: XMLHttpRequest) => { + if (xhr.status >= 200 && xhr.status < 300) { + setAudioUploadStarted(false); + // setUploadSuccess(true); + setAudioName(""); + fetchData(); + Notification.Success({ + msg: "File Uploaded Successfully", + }); + } else { + setAudioUploadStarted(false); + } + }, + setUploadPercent, + () => { setAudioUploadStarted(false); - }); + } + ); }; const validateAudioUpload = () => { diff --git a/src/Components/Patient/UpdateStatusDialog.tsx b/src/Components/Patient/UpdateStatusDialog.tsx index c302aa1b957..064e19ff2ee 100644 --- a/src/Components/Patient/UpdateStatusDialog.tsx +++ b/src/Components/Patient/UpdateStatusDialog.tsx @@ -1,5 +1,4 @@ import { useEffect, useState, useReducer } from "react"; -import axios from "axios"; import { SAMPLE_TEST_STATUS, SAMPLE_TEST_RESULT, @@ -18,6 +17,7 @@ import CheckBoxFormField from "../Form/FormFields/CheckBoxFormField"; import { useTranslation } from "react-i18next"; import request from "../../Utils/request/request"; import routes from "../../Redux/api"; +import uploadFile from "../../Utils/request/uploadFile"; interface Props { sample: SampleTestModel; @@ -104,36 +104,36 @@ const UpdateStatusDialog = (props: Props) => { if (f === undefined) return; const newFile = new File([f], `${internal_name}`); - const config = { - headers: { - "Content-type": contentType, + uploadFile( + url, + newFile, + "PUT", + { + "Content-Type": contentType, "Content-disposition": "inline", }, - onUploadProgress: (progressEvent: any) => { - const percentCompleted = Math.round( - (progressEvent.loaded * 100) / progressEvent.total - ); - setUploadPercent(percentCompleted); + (xhr: XMLHttpRequest) => { + if (xhr.status >= 200 && xhr.status < 300) { + setUploadStarted(false); + setUploadDone(true); + request(routes.editUpload, { + pathParams: { + id: data.id, + fileType: "SAMPLE_MANAGEMENT", + associatingId: sample.id?.toString() ?? "", + }, + body: { upload_completed: true }, + }); + Notification.Success({ msg: "File Uploaded Successfully" }); + } else { + setUploadStarted(false); + } }, - }; - - axios - .put(url, newFile, config) - .then(() => { + setUploadPercent, + () => { setUploadStarted(false); - setUploadDone(true); - request(routes.editUpload, { - pathParams: { - id: data.id, - fileType: "SAMPLE_MANAGEMENT", - associatingId: sample.id?.toString() ?? "", - }, - body: { upload_completed: true }, - }); - - Notification.Success({ msg: "File Uploaded Successfully" }); - }) - .catch(() => setUploadStarted(false)); + } + ); }; const onFileChange = (e: React.ChangeEvent) => { diff --git a/src/Utils/request/uploadFile.ts b/src/Utils/request/uploadFile.ts new file mode 100644 index 00000000000..1576c86b0cc --- /dev/null +++ b/src/Utils/request/uploadFile.ts @@ -0,0 +1,36 @@ +import { Dispatch, SetStateAction } from "react"; +import { handleUploadPercentage } from "./utils"; + +const uploadFile = ( + url: string, + file: File | FormData, + reqMethod: string, + headers: object, + onLoad: (xhr: XMLHttpRequest) => void, + setUploadPercent: Dispatch> | null, + onError: () => void +) => { + const xhr = new XMLHttpRequest(); + xhr.open(reqMethod, url); + + Object.entries(headers).forEach(([key, value]) => { + xhr.setRequestHeader(key, value); + }); + + xhr.onload = () => { + onLoad(xhr); + }; + + if (setUploadPercent != null) { + xhr.upload.onprogress = (event: ProgressEvent) => { + handleUploadPercentage(event, setUploadPercent); + }; + } + + xhr.onerror = () => { + onError(); + }; + xhr.send(file); +}; + +export default uploadFile; diff --git a/src/Utils/request/utils.ts b/src/Utils/request/utils.ts index 9b98e1ae3bf..bd715f818c3 100644 --- a/src/Utils/request/utils.ts +++ b/src/Utils/request/utils.ts @@ -1,3 +1,4 @@ +import { Dispatch, SetStateAction } from "react"; import { LocalStorageKeys } from "../../Common/constants"; import * as Notification from "../Notifications"; import { QueryParams, RequestOptions } from "./types"; @@ -96,3 +97,13 @@ export function mergeRequestOptions( silent: overrides.silent ?? options.silent, }; } + +export function handleUploadPercentage( + event: ProgressEvent, + setUploadPercent: Dispatch> +) { + if (event.lengthComputable) { + const percentComplete = Math.round((event.loaded / event.total) * 100); + setUploadPercent(percentComplete); + } +}