Compare commits
34 Commits
enhancemen
...
bugfix/upl
| Author | SHA1 | Date | |
|---|---|---|---|
| 630261ac21 | |||
| c948192f10 | |||
| f47459d116 | |||
| 705d7c7040 | |||
| ca625673e9 | |||
| 538b623ac6 | |||
| 933c101cbc | |||
| af1dabc8fc | |||
| a839502421 | |||
| 39629897d4 | |||
| cd26b3b68f | |||
| a8abed2246 | |||
| cf72a1e1d3 | |||
| c8eed55801 | |||
| 907555cb0d | |||
| d6c39843c8 | |||
| a64fa76ecb | |||
| 93dcde4459 | |||
| a5b07333da | |||
| ae0a6f9249 | |||
| 350d7cf41c | |||
| 78e5da45ca | |||
| e46460f41d | |||
| 6c441a0a4b | |||
| 2d5b264041 | |||
| 251a2f5e7b | |||
| 18534ceb2c | |||
| 9975e6a6ca | |||
| c83122cd52 | |||
| abc8007fc6 | |||
| f264f4e808 | |||
| 0c6e4b57be | |||
| 4519700561 | |||
| b58181e551 |
@@ -32,7 +32,8 @@
|
|||||||
"react-tabs": "^6.1.0",
|
"react-tabs": "^6.1.0",
|
||||||
"react-use": "^17.6.0",
|
"react-use": "^17.6.0",
|
||||||
"sonner": "^2.0.7",
|
"sonner": "^2.0.7",
|
||||||
"tailwindcss": "^4.1.11"
|
"tailwindcss": "^4.1.11",
|
||||||
|
"use-debounce": "^10.0.6"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.32.0",
|
"@eslint/js": "^9.32.0",
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import FrontCamera from "./pages/FrontCamera";
|
|||||||
import RearCamera from "./pages/RearCamera";
|
import RearCamera from "./pages/RearCamera";
|
||||||
import SystemSettings from "./pages/SystemSettings";
|
import SystemSettings from "./pages/SystemSettings";
|
||||||
import Session from "./pages/Session";
|
import Session from "./pages/Session";
|
||||||
import { NPEDUserProvider } from "./context/providers/NPEDUserContextProvider";
|
import { IntegrationsProvider } from "./context/providers/IntegrationsContextProvider";
|
||||||
import { AlertHitProvider } from "./context/providers/AlertHitProvider";
|
import { AlertHitProvider } from "./context/providers/AlertHitProvider";
|
||||||
import { SoundProvider } from "react-sounds";
|
import { SoundProvider } from "react-sounds";
|
||||||
import SoundContextProvider from "./context/providers/SoundContextProvider";
|
import SoundContextProvider from "./context/providers/SoundContextProvider";
|
||||||
@@ -14,7 +14,7 @@ function App() {
|
|||||||
return (
|
return (
|
||||||
<SoundContextProvider>
|
<SoundContextProvider>
|
||||||
<SoundProvider initialEnabled={true}>
|
<SoundProvider initialEnabled={true}>
|
||||||
<NPEDUserProvider>
|
<IntegrationsProvider>
|
||||||
<AlertHitProvider>
|
<AlertHitProvider>
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/" element={<Container />}>
|
<Route path="/" element={<Container />}>
|
||||||
@@ -27,7 +27,7 @@ function App() {
|
|||||||
</Route>
|
</Route>
|
||||||
</Routes>
|
</Routes>
|
||||||
</AlertHitProvider>
|
</AlertHitProvider>
|
||||||
</NPEDUserProvider>
|
</IntegrationsProvider>
|
||||||
</SoundProvider>
|
</SoundProvider>
|
||||||
</SoundContextProvider>
|
</SoundContextProvider>
|
||||||
);
|
);
|
||||||
|
|||||||
BIN
src/assets/sounds/ui/Attention.wav
Normal file
BIN
src/assets/sounds/ui/Attention.wav
Normal file
Binary file not shown.
Binary file not shown.
@@ -1,30 +1,36 @@
|
|||||||
import Card from "../UI/Card";
|
import Card from "../UI/Card";
|
||||||
import CardHeader from "../UI/CardHeader";
|
import CardHeader from "../UI/CardHeader";
|
||||||
import { useNPEDContext } from "../../context/NPEDUserContext";
|
import { useIntegrationsContext } from "../../context/IntegrationsContext";
|
||||||
import type { ReducedSightingType } from "../../types/types";
|
import type { ReducedSightingType } from "../../types/types";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||||
|
import { faFloppyDisk, faPause, faPlay, faStop } from "@fortawesome/free-solid-svg-icons";
|
||||||
|
import VehicleSessionItem from "../UI/VehicleSessionItem";
|
||||||
|
import { useCameraBlackboard } from "../../hooks/useCameraBlackboard";
|
||||||
|
|
||||||
const SessionCard = () => {
|
const SessionCard = () => {
|
||||||
const { sessionStarted, setSessionStarted, sessionList } = useNPEDContext();
|
const { state, dispatch } = useIntegrationsContext();
|
||||||
|
const { mutation } = useCameraBlackboard();
|
||||||
|
|
||||||
const handleStartClick = () => {
|
const sessionStarted = state.sessionStarted;
|
||||||
setSessionStarted(!sessionStarted);
|
const sessionPaused = state.sessionPaused;
|
||||||
toast(`${sessionStarted ? "Vehicle tracking session Ended" : "Vehicle tracking session Started"}`);
|
const sessionList = state.sessionList;
|
||||||
};
|
|
||||||
|
|
||||||
const sightings = [...new Map(sessionList.map((vehicle) => [vehicle.vrm, vehicle]))];
|
const sightings = [...new Map(sessionList?.map((vehicle) => [vehicle.vrm, vehicle]))];
|
||||||
|
|
||||||
const dedupedSightings = sightings.map((sighting) => sighting[1]);
|
const dedupedSightings = sightings.map((sighting) => sighting[1]);
|
||||||
|
|
||||||
const vehicles = dedupedSightings.reduce<Record<string, ReducedSightingType[]>>(
|
const vehicles = dedupedSightings.reduce<Record<string, ReducedSightingType[]>>(
|
||||||
(acc, item) => {
|
(acc, item) => {
|
||||||
|
const hotlisthit = Object.values(item.metadata?.hotlistMatches ?? {}).includes(true);
|
||||||
if (item.metadata?.npedJSON["NPED CATEGORY"] === "A") acc.npedCatA.push(item);
|
if (item.metadata?.npedJSON["NPED CATEGORY"] === "A") acc.npedCatA.push(item);
|
||||||
if (item.metadata?.npedJSON["NPED CATEGORY"] === "B") acc.npedCatB.push(item);
|
if (item.metadata?.npedJSON["NPED CATEGORY"] === "B") acc.npedCatB.push(item);
|
||||||
if (item.metadata?.npedJSON["NPED CATEGORY"] === "C") acc.npedCatC.push(item);
|
if (item.metadata?.npedJSON["NPED CATEGORY"] === "C") acc.npedCatC.push(item);
|
||||||
if (item.metadata?.npedJSON["NPED CATEGORY"] === "D") acc.npedCatD.push(item);
|
if (item.metadata?.npedJSON["NPED CATEGORY"] === "D") acc.npedCatD.push(item);
|
||||||
if (item.metadata?.npedJSON["TAX STATUS"] === false) acc.notTaxed.push(item);
|
if (item.metadata?.npedJSON["TAX STATUS"] === false) acc.notTaxed.push(item);
|
||||||
if (item.metadata?.npedJSON["MOT STATUS"] === false) acc.notMOT.push(item);
|
if (item.metadata?.npedJSON["MOT STATUS"] === false) acc.notMOT.push(item);
|
||||||
|
if (hotlisthit) acc.hotlistHit.push(item);
|
||||||
|
acc.vehicles.push(item);
|
||||||
return acc;
|
return acc;
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -34,9 +40,32 @@ const SessionCard = () => {
|
|||||||
npedCatD: [],
|
npedCatD: [],
|
||||||
notTaxed: [],
|
notTaxed: [],
|
||||||
notMOT: [],
|
notMOT: [],
|
||||||
|
hotlistHit: [],
|
||||||
|
vehicles: [],
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const handleStartClick = () => {
|
||||||
|
dispatch({ type: "SESSIONSTART", payload: !sessionStarted });
|
||||||
|
dispatch({ type: "SESSIONPAUSE", payload: false });
|
||||||
|
toast(`${sessionStarted ? "Vehicle tracking session ended" : "Vehicle tracking session started"}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlepauseClick = () => {
|
||||||
|
dispatch({ type: "SESSIONPAUSE", payload: !sessionPaused });
|
||||||
|
toast(`${sessionStarted ? "Vehicle tracking session paused" : "Vehicle tracking session resumed"}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSaveCick = async () => {
|
||||||
|
const result = await mutation.mutateAsync({
|
||||||
|
operation: "INSERT",
|
||||||
|
path: "sessionStats",
|
||||||
|
value: dedupedSightings,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.reason === "OK") toast.success("Session saved");
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="p-4 col-span-3">
|
<Card className="p-4 col-span-3">
|
||||||
<CardHeader title="Session" />
|
<CardHeader title="Session" />
|
||||||
@@ -47,34 +76,72 @@ const SessionCard = () => {
|
|||||||
} transition w-full`}
|
} transition w-full`}
|
||||||
onClick={handleStartClick}
|
onClick={handleStartClick}
|
||||||
>
|
>
|
||||||
{sessionStarted ? "End Session" : "Start Session"}
|
<div className="flex flex-row gap-3 items-center justify-self-center">
|
||||||
|
<FontAwesomeIcon icon={sessionStarted ? faStop : faPlay} />
|
||||||
|
<p>{sessionStarted ? "End Session" : "Start Session"}</p>
|
||||||
|
</div>
|
||||||
</button>
|
</button>
|
||||||
|
<div className="flex flex-col lg:flex-row gap-5">
|
||||||
|
{sessionStarted && (
|
||||||
|
<button
|
||||||
|
className={`bg-blue-600 text-white px-4 py-2 rounded transition w-full lg:w-[50%]`}
|
||||||
|
onClick={handleSaveCick}
|
||||||
|
>
|
||||||
|
<div className="flex flex-row gap-3 items-center justify-self-center">
|
||||||
|
<FontAwesomeIcon icon={faFloppyDisk} />
|
||||||
|
<p>Save session</p>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{sessionStarted && (
|
||||||
|
<button
|
||||||
|
className={`bg-gray-300 text-gray-800 px-4 py-2 rounded transition w-full lg:w-[50%]`}
|
||||||
|
onClick={handlepauseClick}
|
||||||
|
>
|
||||||
|
<div className="flex flex-row gap-3 items-center justify-self-center">
|
||||||
|
<FontAwesomeIcon icon={sessionPaused ? faPlay : faPause} />
|
||||||
|
<p>{sessionPaused ? "Resume session" : "Pause session"}</p>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<ul className="text-white space-y-2">
|
<ul className="text-white space-y-2">
|
||||||
<li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
|
<VehicleSessionItem
|
||||||
<p>Number of Vehicles:</p>
|
sessionNumber={vehicles.vehicles.length}
|
||||||
<span className="font-bold text-green-600 text-xl">{dedupedSightings.length}</span>
|
textColour="text-green-400"
|
||||||
</li>
|
vehicleTag={"Number of Vehicles sightings:"}
|
||||||
<li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
|
/>
|
||||||
<p>Vehicles without Tax:</p>
|
<VehicleSessionItem
|
||||||
<span className="font-bold text-amber-600 text-xl">{vehicles.notTaxed.length}</span>
|
sessionNumber={vehicles.notTaxed.length}
|
||||||
</li>
|
textColour="text-amber-400"
|
||||||
<li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
|
vehicleTag={"Vehicles without Tax:"}
|
||||||
<p>Vehicles without MOT:</p>{" "}
|
/>
|
||||||
<span className="font-bold text-red-500 text-xl">{vehicles.notMOT.length}</span>
|
<VehicleSessionItem
|
||||||
</li>
|
sessionNumber={vehicles.notMOT.length}
|
||||||
<li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
|
textColour="text-red-500"
|
||||||
<p>Vehicles with NPED Cat A:</p>
|
vehicleTag={"Vehicles without MOT:"}
|
||||||
<span className="font-bold text-gray-300 text-xl">{vehicles.npedCatA.length}</span>
|
/>
|
||||||
</li>
|
<VehicleSessionItem
|
||||||
<li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
|
sessionNumber={vehicles.hotlistHit.length}
|
||||||
<p>Vehicles with NPED Cat B:</p>{" "}
|
textColour="text-blue-400"
|
||||||
<span className="font-bold text-gray-300text-xl">{vehicles.npedCatB.length}</span>
|
vehicleTag={"Vehicles on Hotlists:"}
|
||||||
</li>
|
/>
|
||||||
<li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
|
<VehicleSessionItem
|
||||||
Vehicles with NPED Cat C:{" "}
|
sessionNumber={vehicles.npedCatA.length}
|
||||||
<span className="font-bold text-gray-300 text-xl">{vehicles.npedCatC.length}</span>
|
textColour="text-gray-300"
|
||||||
</li>
|
vehicleTag={"Vehicles with NPED Cat A:"}
|
||||||
|
/>
|
||||||
|
<VehicleSessionItem
|
||||||
|
sessionNumber={vehicles.npedCatB.length}
|
||||||
|
textColour="text-gray-300"
|
||||||
|
vehicleTag={"Vehicles with NPED Cat B:"}
|
||||||
|
/>
|
||||||
|
<VehicleSessionItem
|
||||||
|
sessionNumber={vehicles.npedCatC.length}
|
||||||
|
textColour="text-gray-300"
|
||||||
|
vehicleTag={"Vehicles with NPED Cat C:"}
|
||||||
|
/>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -1,37 +1,12 @@
|
|||||||
import { Field, Form, Formik } from "formik";
|
import { Field, useFormikContext } from "formik";
|
||||||
import FormToggle from "../components/FormToggle";
|
import FormToggle from "../components/FormToggle";
|
||||||
import { useCameraOutput } from "../../../hooks/useCameraOutput";
|
|
||||||
import { cleanArray } from "../../../utils/utils";
|
|
||||||
import FormGroup from "../components/FormGroup";
|
import FormGroup from "../components/FormGroup";
|
||||||
import type { BearerTypeFieldType } from "../../../types/types";
|
import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types";
|
||||||
|
|
||||||
export const ValuesComponent = () => {
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const BearerTypeFields = () => {
|
const BearerTypeFields = () => {
|
||||||
const { dispatcherQuery, dispatcherMutation } = useCameraOutput();
|
useFormikContext<BearerTypeFieldType & InitialValuesForm>();
|
||||||
|
|
||||||
const format = dispatcherQuery?.data?.propFormat?.value;
|
|
||||||
const rawOptions = dispatcherQuery?.data?.propFormat?.accepted;
|
|
||||||
const enabled = dispatcherQuery?.data?.propEnabled?.value;
|
|
||||||
const verbose = dispatcherQuery?.data?.propVerbose?.value;
|
|
||||||
const options = cleanArray(rawOptions);
|
|
||||||
|
|
||||||
const initialValues: BearerTypeFieldType = {
|
|
||||||
format: format ?? "JSON",
|
|
||||||
enabled: enabled === "true",
|
|
||||||
verbose: verbose === "true",
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = async (values: BearerTypeFieldType) => {
|
|
||||||
await dispatcherMutation.mutateAsync(values);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize>
|
|
||||||
{({ isSubmitting }) => (
|
|
||||||
<Form>
|
|
||||||
<div className="flex flex-col space-y-4 px-2">
|
<div className="flex flex-col space-y-4 px-2">
|
||||||
<FormGroup>
|
<FormGroup>
|
||||||
<label htmlFor="format">Format</label>
|
<label htmlFor="format">Format</label>
|
||||||
@@ -41,29 +16,20 @@ const BearerTypeFields = () => {
|
|||||||
id="format"
|
id="format"
|
||||||
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
|
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
|
||||||
>
|
>
|
||||||
{options?.map((option: string) => (
|
<option key={"JSON"} value={"JSON"}>
|
||||||
<option key={option} value={option}>
|
JSON
|
||||||
{option}
|
</option>
|
||||||
|
<option key={"BOF2"} value={"BOF2"}>
|
||||||
|
BOF2
|
||||||
</option>
|
</option>
|
||||||
))}
|
|
||||||
</Field>
|
</Field>
|
||||||
</FormGroup>
|
</FormGroup>
|
||||||
<FormGroup>
|
<FormGroup>
|
||||||
<div className="flex flex-col space-y-4">
|
<div className="flex flex-col space-y-4">
|
||||||
<FormToggle name="enabled" label="Enabled" />
|
<FormToggle name="enabled" label="Enabled" />
|
||||||
<FormToggle name="verbose" label="Verbose" />
|
|
||||||
</div>
|
</div>
|
||||||
</FormGroup>
|
</FormGroup>
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
|
|
||||||
>
|
|
||||||
{isSubmitting || dispatcherMutation.isPending ? "Saving..." : "Save Changes"}
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</Form>
|
|
||||||
)}
|
|
||||||
</Formik>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,47 @@
|
|||||||
|
import { useFormikContext, type FormikTouched } from "formik";
|
||||||
import Card from "../../UI/Card";
|
import Card from "../../UI/Card";
|
||||||
import CardHeader from "../../UI/CardHeader";
|
import CardHeader from "../../UI/CardHeader";
|
||||||
import ChannelFields from "./ChannelFields";
|
import ChannelFields from "./ChannelFields";
|
||||||
|
import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types";
|
||||||
|
import { useCameraBackOfficeOutput } from "../../../hooks/useBackOfficeConfig";
|
||||||
|
import { useEffect, useMemo } from "react";
|
||||||
|
|
||||||
|
type ChannelCardProps = {
|
||||||
|
touched: FormikTouched<BearerTypeFieldType & InitialValuesForm>;
|
||||||
|
isSubmitting: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ChannelCard = ({ touched, isSubmitting }: ChannelCardProps) => {
|
||||||
|
const { values, setFieldValue } = useFormikContext<BearerTypeFieldType & InitialValuesForm>();
|
||||||
|
const { backOfficeQuery } = useCameraBackOfficeOutput(values?.format);
|
||||||
|
|
||||||
|
const mapped = useMemo(() => {
|
||||||
|
const d = backOfficeQuery.data;
|
||||||
|
return {
|
||||||
|
backOfficeURL: d?.propBackofficeURL?.value ?? "",
|
||||||
|
username: d?.propUsername?.value ?? "",
|
||||||
|
password: d?.propPassword?.value ?? "",
|
||||||
|
connectTimeoutSeconds: Number(d?.propConnectTimeoutSeconds?.value),
|
||||||
|
readTimeoutSeconds: Number(d?.propReadTimeoutSeconds?.value),
|
||||||
|
};
|
||||||
|
}, [backOfficeQuery.data]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!backOfficeQuery.isSuccess) return;
|
||||||
|
for (const [key, value] of Object.entries(mapped)) {
|
||||||
|
setFieldValue(key, value);
|
||||||
|
}
|
||||||
|
}, [backOfficeQuery.isSuccess, mapped, setFieldValue]);
|
||||||
|
|
||||||
const ChannelCard = () => {
|
|
||||||
return (
|
return (
|
||||||
<Card className="p-4">
|
<Card className="p-4">
|
||||||
<CardHeader title="Channel 1 (JSON)" />
|
<CardHeader title={`Channel (${values?.format})`} />
|
||||||
<ChannelFields />
|
<ChannelFields
|
||||||
|
touched={touched}
|
||||||
|
isSubmitting={isSubmitting}
|
||||||
|
backOfficeData={backOfficeQuery}
|
||||||
|
format={values?.format}
|
||||||
|
/>
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,79 +1,52 @@
|
|||||||
import { Field, Form, Formik, useFormikContext } from "formik";
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
|
import { Field, useFormikContext, type FormikTouched } from "formik";
|
||||||
import FormGroup from "../components/FormGroup";
|
import FormGroup from "../components/FormGroup";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons";
|
import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons";
|
||||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||||
import { useCameraOutput } from "../../../hooks/useCameraOutput";
|
import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types";
|
||||||
import type { InitialValuesForm, InitialValuesFormErrors } from "../../../types/types";
|
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import type { UseQueryResult } from "@tanstack/react-query";
|
||||||
|
|
||||||
const ChannelFields = () => {
|
type ChannelFieldsProps = {
|
||||||
|
touched: FormikTouched<BearerTypeFieldType & InitialValuesForm>;
|
||||||
|
isSubmitting: boolean;
|
||||||
|
|
||||||
|
backOfficeData: UseQueryResult<any, Error>;
|
||||||
|
format?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ChannelFields = ({ touched, isSubmitting, format }: ChannelFieldsProps) => {
|
||||||
const [showPwd, setShowPwd] = useState(false);
|
const [showPwd, setShowPwd] = useState(false);
|
||||||
const { backOfficeQuery, backOfficeMutation } = useCameraOutput();
|
const { submitCount, isValid, values, errors } = useFormikContext<BearerTypeFieldType & InitialValuesForm>();
|
||||||
|
|
||||||
const backOfficeURL = backOfficeQuery?.data?.propBackofficeURL?.value;
|
|
||||||
const username = backOfficeQuery?.data?.propUsername?.value;
|
|
||||||
const password = backOfficeQuery?.data?.propPassword?.value;
|
|
||||||
const connectTimeoutSeconds = backOfficeQuery?.data?.propConnectTimeoutSeconds?.value;
|
|
||||||
const readTimeoutSeconds = backOfficeQuery?.data?.propReadTimeoutSeconds?.value;
|
|
||||||
|
|
||||||
const initialValues: InitialValuesForm = {
|
|
||||||
backOfficeURL: backOfficeURL ?? "",
|
|
||||||
username: username ?? "",
|
|
||||||
password: password ?? "",
|
|
||||||
connectTimeoutSeconds: Number(connectTimeoutSeconds),
|
|
||||||
readTimeoutSeconds: Number(readTimeoutSeconds),
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = async (values: InitialValuesForm) => {
|
|
||||||
await backOfficeMutation.mutateAsync(values);
|
|
||||||
};
|
|
||||||
|
|
||||||
const ValidationToastOnce = () => {
|
const ValidationToastOnce = () => {
|
||||||
const { submitCount, isValid } = useFormikContext();
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (submitCount > 0 && !isValid) {
|
if (submitCount > 0 && !isValid) {
|
||||||
toast.error("Check fields are filled in");
|
toast.error("Check fields are filled in");
|
||||||
}
|
}
|
||||||
}, [submitCount, isValid]);
|
}, []);
|
||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const validateValues = (values: InitialValuesForm): InitialValuesFormErrors => {
|
|
||||||
const errors: InitialValuesFormErrors = {};
|
|
||||||
|
|
||||||
const url = values.backOfficeURL?.trim();
|
|
||||||
const username = values.username?.trim();
|
|
||||||
const password = values.password?.trim();
|
|
||||||
|
|
||||||
if (!url) {
|
|
||||||
errors.backOfficeURL = "Required";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!username) errors.username = "Required";
|
|
||||||
if (!password) errors.password = "Required";
|
|
||||||
|
|
||||||
const read = Number(values.readTimeoutSeconds);
|
|
||||||
if (!Number.isFinite(read)) {
|
|
||||||
errors.readTimeoutSeconds = "Must be a number";
|
|
||||||
} else if (read < 0) {
|
|
||||||
errors.readTimeoutSeconds = "Must be ≥ 0";
|
|
||||||
}
|
|
||||||
|
|
||||||
const connect = Number(values.connectTimeoutSeconds);
|
|
||||||
if (!Number.isFinite(connect)) {
|
|
||||||
errors.connectTimeoutSeconds = "Must be a number";
|
|
||||||
} else if (connect < 0) {
|
|
||||||
errors.connectTimeoutSeconds = "Must be ≥ 0";
|
|
||||||
}
|
|
||||||
|
|
||||||
return errors;
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize validate={validateValues}>
|
<>
|
||||||
{({ errors, touched, isSubmitting }) => (
|
{format?.toLowerCase() !== "bof2" && format?.toLowerCase() !== "json" ? (
|
||||||
<Form>
|
<>
|
||||||
|
<div className="mt-4 flex flex-col items-center justify-center rounded-2xl border border-slate-800 bg-slate-900/40 p-10 text-center">
|
||||||
|
<div className="mb-3 rounded-xl bg-slate-800 px-3 py-1 text-xs uppercase tracking-wider text-slate-400">
|
||||||
|
Format coming soon
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="max-w-md text-slate-300">
|
||||||
|
Output configuration currently supports <span className="font-bold text-blue-400">JSON</span> or{" "}
|
||||||
|
<span className="font-bold text-emerald-400">BOF2</span>. <br /> More formats will be added in future
|
||||||
|
updates.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
<div className="flex flex-col space-y-2 px-2">
|
<div className="flex flex-col space-y-2 px-2">
|
||||||
<FormGroup>
|
<FormGroup>
|
||||||
<label htmlFor="backoffice" className="m-0">
|
<label htmlFor="backoffice" className="m-0">
|
||||||
@@ -146,17 +119,78 @@ const ChannelFields = () => {
|
|||||||
} rounded-lg w-full md:w-60`}
|
} rounded-lg w-full md:w-60`}
|
||||||
/>
|
/>
|
||||||
</FormGroup>
|
</FormGroup>
|
||||||
|
|
||||||
|
{format?.toLowerCase() === "bof2" && (
|
||||||
|
<>
|
||||||
|
<div className="border-b border-gray-500 my-3">
|
||||||
|
<h2 className="font-bold">{values.format} Constants</h2>
|
||||||
</div>
|
</div>
|
||||||
|
<FormGroup>
|
||||||
|
<label htmlFor="FFID">Feed ID / Force ID</label>
|
||||||
|
<Field
|
||||||
|
name={"FFID"}
|
||||||
|
type="text"
|
||||||
|
id="FFID"
|
||||||
|
placeholder="ABC123"
|
||||||
|
className={`p-1.5 border ${
|
||||||
|
errors.readTimeoutSeconds && touched.readTimeoutSeconds ? "border-red-500" : "border-gray-400 "
|
||||||
|
} rounded-lg w-full md:w-60`}
|
||||||
|
/>
|
||||||
|
</FormGroup>
|
||||||
|
|
||||||
|
<FormGroup>
|
||||||
|
<label htmlFor="SCID">Source ID / Camera ID</label>
|
||||||
|
<Field
|
||||||
|
name={"SCID"}
|
||||||
|
type="text"
|
||||||
|
id="SCID"
|
||||||
|
placeholder="DEF345"
|
||||||
|
className={`p-1.5 border ${
|
||||||
|
errors.readTimeoutSeconds && touched.readTimeoutSeconds ? "border-red-500" : "border-gray-400 "
|
||||||
|
} rounded-lg w-full md:w-60`}
|
||||||
|
/>
|
||||||
|
</FormGroup>
|
||||||
|
|
||||||
|
<FormGroup>
|
||||||
|
<label htmlFor="timestampSource">Timestamp Source</label>
|
||||||
|
<Field
|
||||||
|
name={"timestampSource"}
|
||||||
|
as="select"
|
||||||
|
id="timestampSource"
|
||||||
|
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
|
||||||
|
>
|
||||||
|
<option value="">-- Select format --</option>
|
||||||
|
<option value={"UTC"}>UTC</option>
|
||||||
|
<option value={"local"}>Local</option>
|
||||||
|
</Field>
|
||||||
|
</FormGroup>
|
||||||
|
<FormGroup>
|
||||||
|
<label htmlFor="GPSFormat">GPS Format</label>
|
||||||
|
<Field
|
||||||
|
name={"GPSFormat"}
|
||||||
|
as="select"
|
||||||
|
id="GPSFormat"
|
||||||
|
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
|
||||||
|
>
|
||||||
|
<option value="">-- Select format --</option>
|
||||||
|
<option value={"Decimal degrees"}>Decimal degrees</option>
|
||||||
|
<option value={"minutes"}>Minutes</option>
|
||||||
|
</Field>
|
||||||
|
</FormGroup>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
|
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
|
||||||
>
|
>
|
||||||
{isSubmitting || backOfficeMutation.isPending ? "Saving..." : "Save Changes"}
|
{isSubmitting ? "Saving..." : "Save Changes"}
|
||||||
</button>
|
</button>
|
||||||
<ValidationToastOnce />
|
<ValidationToastOnce />
|
||||||
</Form>
|
</>
|
||||||
)}
|
)}
|
||||||
</Formik>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -6,16 +6,18 @@ import { toast } from "sonner";
|
|||||||
import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons";
|
import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons";
|
||||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
import { useIntegrationsContext } from "../../../context/IntegrationsContext";
|
||||||
|
|
||||||
const NPEDFields = () => {
|
const NPEDFields = () => {
|
||||||
|
const { state } = useIntegrationsContext();
|
||||||
const [showPwd, setShowPwd] = useState(false);
|
const [showPwd, setShowPwd] = useState(false);
|
||||||
const { signIn, user, signOut } = useNPEDAuth();
|
const { signIn, signOut } = useNPEDAuth();
|
||||||
|
|
||||||
const initialValues = user
|
const initialValues = state.npedUser
|
||||||
? {
|
? {
|
||||||
username: user?.propUsername?.value,
|
username: state.npedUser?.propUsername?.value,
|
||||||
password: user?.propPassword?.value,
|
password: state.npedUser?.propPassword?.value,
|
||||||
clientId: user?.propClientID?.value,
|
clientId: state.npedUser?.propClientID?.value,
|
||||||
frontId: "NPED",
|
frontId: "NPED",
|
||||||
rearId: "NPED",
|
rearId: "NPED",
|
||||||
}
|
}
|
||||||
@@ -48,20 +50,13 @@ const NPEDFields = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Formik
|
<Formik initialValues={initialValues} onSubmit={handleSubmit} validate={validateValues} enableReinitialize>
|
||||||
initialValues={initialValues}
|
|
||||||
onSubmit={handleSubmit}
|
|
||||||
validate={validateValues}
|
|
||||||
enableReinitialize
|
|
||||||
>
|
|
||||||
{({ errors, touched, isSubmitting }) => (
|
{({ errors, touched, isSubmitting }) => (
|
||||||
<Form className="flex flex-col space-y-5 px-2">
|
<Form className="flex flex-col space-y-5 px-2">
|
||||||
<FormGroup>
|
<FormGroup>
|
||||||
<label htmlFor="username">Username</label>
|
<label htmlFor="username">Username</label>
|
||||||
{touched.username && errors.username && (
|
{touched.username && errors.username && (
|
||||||
<small className="absolute right-0 -top-5 text-red-500">
|
<small className="absolute right-0 -top-5 text-red-500">{errors.username}</small>
|
||||||
{errors.username}
|
|
||||||
</small>
|
|
||||||
)}
|
)}
|
||||||
<Field
|
<Field
|
||||||
name="username"
|
name="username"
|
||||||
@@ -82,9 +77,7 @@ const NPEDFields = () => {
|
|||||||
className="p-2 border border-gray-400 rounded-lg w-full"
|
className="p-2 border border-gray-400 rounded-lg w-full"
|
||||||
/>
|
/>
|
||||||
{touched.password && errors.password && (
|
{touched.password && errors.password && (
|
||||||
<small className="absolute right-0 -top-5 text-red-500">
|
<small className="absolute right-0 -top-5 text-red-500">{errors.password}</small>
|
||||||
{errors.password}
|
|
||||||
</small>
|
|
||||||
)}
|
)}
|
||||||
<FontAwesomeIcon
|
<FontAwesomeIcon
|
||||||
type="button"
|
type="button"
|
||||||
@@ -97,9 +90,7 @@ const NPEDFields = () => {
|
|||||||
<FormGroup>
|
<FormGroup>
|
||||||
<label htmlFor="clientId">Client ID</label>
|
<label htmlFor="clientId">Client ID</label>
|
||||||
{touched.clientId && errors.clientId && (
|
{touched.clientId && errors.clientId && (
|
||||||
<small className="absolute right-0 -top-5 text-red-500">
|
<small className="absolute right-0 -top-5 text-red-500">{errors.clientId}</small>
|
||||||
{errors.clientId}
|
|
||||||
</small>
|
|
||||||
)}
|
)}
|
||||||
<Field
|
<Field
|
||||||
name="clientId"
|
name="clientId"
|
||||||
@@ -109,7 +100,7 @@ const NPEDFields = () => {
|
|||||||
className="p-1.5 border border-gray-400 rounded-lg"
|
className="p-1.5 border border-gray-400 rounded-lg"
|
||||||
/>
|
/>
|
||||||
</FormGroup>
|
</FormGroup>
|
||||||
{!user?.propClientID?.value ? (
|
{!state.npedUser?.propClientID?.value ? (
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5 hover:cursor-pointer"
|
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5 hover:cursor-pointer"
|
||||||
|
|||||||
@@ -1,12 +1,120 @@
|
|||||||
|
import { Form, Formik } from "formik";
|
||||||
import BearerTypeCard from "../BearerType/BearerTypeCard";
|
import BearerTypeCard from "../BearerType/BearerTypeCard";
|
||||||
import ChannelCard from "../Channel1-JSON/ChannelCard";
|
import ChannelCard from "../Channel1-JSON/ChannelCard";
|
||||||
|
import { useCameraOutput, useGetDispatcherConfig } from "../../../hooks/useCameraOutput";
|
||||||
|
import type {
|
||||||
|
BearerTypeFieldType,
|
||||||
|
InitialValuesForm,
|
||||||
|
InitialValuesFormErrors,
|
||||||
|
OptionalBOF2Constants,
|
||||||
|
} from "../../../types/types";
|
||||||
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { useUpdateBackOfficeConfig } from "../../../hooks/useBackOfficeConfig";
|
||||||
|
import { useFormVaidate } from "../../../hooks/useFormValidate";
|
||||||
|
|
||||||
const SettingForms = () => {
|
const SettingForms = () => {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const { dispatcherQuery, dispatcherMutation, backOfficeDispatcherMutation } = useCameraOutput();
|
||||||
|
const { backOfficeMutation } = useUpdateBackOfficeConfig();
|
||||||
|
const { bof2ConstantsQuery } = useGetDispatcherConfig();
|
||||||
|
const { validateMutation } = useFormVaidate();
|
||||||
|
|
||||||
|
const format = dispatcherQuery?.data?.propFormat?.value;
|
||||||
|
const enabled = dispatcherQuery?.data?.propEnabled?.value;
|
||||||
|
|
||||||
|
const FFID = bof2ConstantsQuery?.data?.propFeedIdentifier?.value;
|
||||||
|
const SCID = bof2ConstantsQuery?.data?.propSourceIdentifier?.value;
|
||||||
|
const GPSFormat = bof2ConstantsQuery?.data?.propGpsFormat?.value;
|
||||||
|
const timestampSource = bof2ConstantsQuery?.data?.propTimeZoneType?.value;
|
||||||
|
|
||||||
|
const initialValues: BearerTypeFieldType & InitialValuesForm & OptionalBOF2Constants = {
|
||||||
|
format: format ?? "JSON",
|
||||||
|
enabled: enabled === "true",
|
||||||
|
backOfficeURL: "",
|
||||||
|
username: "",
|
||||||
|
password: "",
|
||||||
|
connectTimeoutSeconds: Number(5),
|
||||||
|
readTimeoutSeconds: Number(15),
|
||||||
|
|
||||||
|
// Bof2 - optional constants
|
||||||
|
FFID: FFID ?? "",
|
||||||
|
SCID: SCID ?? "",
|
||||||
|
timestampSource: timestampSource ?? "",
|
||||||
|
GPSFormat: GPSFormat ?? "",
|
||||||
|
};
|
||||||
|
|
||||||
|
const validateValues = (values: InitialValuesForm): InitialValuesFormErrors => {
|
||||||
|
const errors: InitialValuesFormErrors = {};
|
||||||
|
|
||||||
|
const url = values.backOfficeURL?.trim();
|
||||||
|
const username = values.username?.trim();
|
||||||
|
const password = values.password?.trim();
|
||||||
|
if (!url) {
|
||||||
|
errors.backOfficeURL = "Required";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!username) errors.username = "Required";
|
||||||
|
if (!password) errors.password = "Required";
|
||||||
|
|
||||||
|
const read = Number(values.readTimeoutSeconds);
|
||||||
|
if (!Number.isFinite(read)) {
|
||||||
|
errors.readTimeoutSeconds = "Must be a number";
|
||||||
|
} else if (read < 0) {
|
||||||
|
errors.readTimeoutSeconds = "Must be ≥ 0";
|
||||||
|
}
|
||||||
|
|
||||||
|
const connect = Number(values.connectTimeoutSeconds);
|
||||||
|
if (!Number.isFinite(connect)) {
|
||||||
|
errors.connectTimeoutSeconds = "Must be a number";
|
||||||
|
} else if (connect < 0) {
|
||||||
|
errors.connectTimeoutSeconds = "Must be ≥ 0";
|
||||||
|
}
|
||||||
|
return errors;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async (values: BearerTypeFieldType & InitialValuesForm & OptionalBOF2Constants) => {
|
||||||
|
// if (formErrors && Object.entries(formErrors).length > 0) {
|
||||||
|
// return;
|
||||||
|
// }
|
||||||
|
const dispatcherData = {
|
||||||
|
format: values.format,
|
||||||
|
enabled: values.enabled,
|
||||||
|
};
|
||||||
|
const result = await dispatcherMutation.mutateAsync(dispatcherData);
|
||||||
|
|
||||||
|
if (result?.id) {
|
||||||
|
qc.invalidateQueries({ queryKey: ["dispatcher"] });
|
||||||
|
qc.invalidateQueries({ queryKey: ["backoffice", values.format] });
|
||||||
|
const validResponse = await validateMutation.mutateAsync(values);
|
||||||
|
if (validResponse?.reason === "OK") {
|
||||||
|
await backOfficeMutation.mutateAsync(values);
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (values.format.toLowerCase() === "bof2") {
|
||||||
|
const bof2ConstantsData: OptionalBOF2Constants = {
|
||||||
|
FFID: values.FFID,
|
||||||
|
SCID: values.SCID,
|
||||||
|
timestampSource: values.timestampSource,
|
||||||
|
GPSFormat: values.GPSFormat,
|
||||||
|
};
|
||||||
|
await backOfficeDispatcherMutation.mutateAsync(bof2ConstantsData);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<Formik initialValues={initialValues} onSubmit={handleSubmit} validate={validateValues} enableReinitialize>
|
||||||
|
{({ isSubmitting, touched }) => (
|
||||||
|
<Form>
|
||||||
<div className="mx-auto grid grid-cols-1 sm:grid-cols-1 lg:grid-cols-2 gap-2 px-2 sm:px-4 lg:px-0 w-full">
|
<div className="mx-auto grid grid-cols-1 sm:grid-cols-1 lg:grid-cols-2 gap-2 px-2 sm:px-4 lg:px-0 w-full">
|
||||||
<BearerTypeCard />
|
<BearerTypeCard />
|
||||||
<ChannelCard />
|
<ChannelCard touched={touched} isSubmitting={isSubmitting} />
|
||||||
</div>
|
</div>
|
||||||
|
</Form>
|
||||||
|
)}
|
||||||
|
</Formik>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -32,7 +32,6 @@ const SoundSettingsFields = () => {
|
|||||||
hotlistSoundVolume: state.hotlistSoundVolume,
|
hotlistSoundVolume: state.hotlistSoundVolume,
|
||||||
soundOptions: [...(state.soundOptions ?? [])],
|
soundOptions: [...(state.soundOptions ?? [])],
|
||||||
};
|
};
|
||||||
|
|
||||||
dispatch({ type: "UPDATE", payload: updatedValues });
|
dispatch({ type: "UPDATE", payload: updatedValues });
|
||||||
|
|
||||||
const result = await mutation.mutateAsync({
|
const result = await mutation.mutateAsync({
|
||||||
|
|||||||
@@ -4,16 +4,21 @@ import type { SoundUploadValue } from "../../../types/types";
|
|||||||
import { useSoundContext } from "../../../context/SoundContext";
|
import { useSoundContext } from "../../../context/SoundContext";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { useCameraBlackboard } from "../../../hooks/useCameraBlackboard";
|
import { useCameraBlackboard } from "../../../hooks/useCameraBlackboard";
|
||||||
|
import { useFileUpload } from "../../../hooks/useFileUpload";
|
||||||
|
|
||||||
const SoundUpload = () => {
|
const SoundUpload = () => {
|
||||||
const { state, dispatch } = useSoundContext();
|
const { state, dispatch } = useSoundContext();
|
||||||
const { mutation } = useCameraBlackboard();
|
const { mutation } = useCameraBlackboard();
|
||||||
|
const { mutation: fileMutation } = useFileUpload({
|
||||||
|
queryKey: state.sightingSound ? [state.sightingSound] : undefined,
|
||||||
|
});
|
||||||
|
|
||||||
const initialValues: SoundUploadValue = {
|
const initialValues: SoundUploadValue = {
|
||||||
name: "",
|
name: "",
|
||||||
soundFile: null,
|
soundFile: null,
|
||||||
soundFileName: "",
|
soundFileName: "",
|
||||||
soundUrl: "",
|
soundUrl: "",
|
||||||
|
uploadedAt: Date.now(),
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSubmit = async (values: SoundUploadValue) => {
|
const handleSubmit = async (values: SoundUploadValue) => {
|
||||||
@@ -37,10 +42,9 @@ const SoundUpload = () => {
|
|||||||
path: "soundSettings",
|
path: "soundSettings",
|
||||||
value: updatedValues,
|
value: updatedValues,
|
||||||
});
|
});
|
||||||
|
await fileMutation.mutateAsync(values.soundFile);
|
||||||
if (result.reason !== "OK") {
|
if (result.reason !== "OK") {
|
||||||
toast.error("Cannot update sound settings");
|
toast.error("Cannot update sound settings");
|
||||||
} else {
|
|
||||||
toast.success(`${values.name} file added`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
dispatch({ type: "ADD", payload: values });
|
dispatch({ type: "ADD", payload: values });
|
||||||
@@ -48,7 +52,7 @@ const SoundUpload = () => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize>
|
<Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize>
|
||||||
{({ setFieldValue, errors, setFieldError, values }) => (
|
{({ setFieldValue, errors, setFieldError }) => (
|
||||||
<Form>
|
<Form>
|
||||||
<label htmlFor="soundFile" className="">
|
<label htmlFor="soundFile" className="">
|
||||||
Sound File
|
Sound File
|
||||||
@@ -67,6 +71,12 @@ const SoundUpload = () => {
|
|||||||
setFieldValue("name", e.target.files[0].name);
|
setFieldValue("name", e.target.files[0].name);
|
||||||
setFieldValue("soundFileName", e.target.files[0].name);
|
setFieldValue("soundFileName", e.target.files[0].name);
|
||||||
setFieldValue("soundFile", e.target.files[0]);
|
setFieldValue("soundFile", e.target.files[0]);
|
||||||
|
setFieldValue("uploadedAt", Date.now());
|
||||||
|
if (e?.target?.files[0]?.size >= 1 * 1024 * 1024) {
|
||||||
|
setFieldError("soundFile", "larger than 1mb");
|
||||||
|
toast.error("File larger than 1MB");
|
||||||
|
return;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
setFieldError("soundFile", "Not an mp3 file");
|
setFieldError("soundFile", "Not an mp3 file");
|
||||||
toast.error("Not an mp3 file");
|
toast.error("Not an mp3 file");
|
||||||
@@ -76,11 +86,6 @@ const SoundUpload = () => {
|
|||||||
</FormGroup>
|
</FormGroup>
|
||||||
|
|
||||||
<div className="mt-4 flex flex-col items-center justify-center rounded-2xl border border-slate-800 bg-slate-900/40 p-10 text-center">
|
<div className="mt-4 flex flex-col items-center justify-center rounded-2xl border border-slate-800 bg-slate-900/40 p-10 text-center">
|
||||||
{!values.soundFile && (
|
|
||||||
<div className="mb-3 rounded-xl bg-slate-800 px-3 py-1 text-xs uppercase tracking-wider text-slate-400">
|
|
||||||
No uploaded sound files
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<p className="max-w-md text-slate-300">
|
<p className="max-w-md text-slate-300">
|
||||||
Uploaded Sound files will appear in the <span className="font-bold">drop downs</span> once they are
|
Uploaded Sound files will appear in the <span className="font-bold">drop downs</span> once they are
|
||||||
uploaded. They can be used for any <span className="text-blue-400">Sighting,</span>{" "}
|
uploaded. They can be used for any <span className="text-blue-400">Sighting,</span>{" "}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import SoundUpload from "./SoundUpload";
|
|||||||
|
|
||||||
const SoundUploadCard = () => {
|
const SoundUploadCard = () => {
|
||||||
return (
|
return (
|
||||||
<Card className="p-4 col-span-3 w-full">
|
<Card className="p-4 col-span-5 lg:col-span-3 w-full">
|
||||||
<CardHeader title={"Sound upload"} />
|
<CardHeader title={"Sound upload"} />
|
||||||
<SoundUpload />
|
<SoundUpload />
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -10,10 +10,7 @@ type BlobFileUpload = {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function sendBlobFileUpload({
|
export async function sendBlobFileUpload({ file, opts }: BlobFileUpload): Promise<string> {
|
||||||
file,
|
|
||||||
opts,
|
|
||||||
}: BlobFileUpload): Promise<string> {
|
|
||||||
if (!file) throw new Error("No file supplied");
|
if (!file) throw new Error("No file supplied");
|
||||||
if (!opts?.uploadUrl) throw new Error("No URL supplied");
|
if (!opts?.uploadUrl) throw new Error("No URL supplied");
|
||||||
|
|
||||||
@@ -42,9 +39,7 @@ export async function sendBlobFileUpload({
|
|||||||
const bodyText = await resp.text();
|
const bodyText = await resp.text();
|
||||||
|
|
||||||
if (!resp.ok) {
|
if (!resp.ok) {
|
||||||
throw new Error(
|
throw new Error(`Upload failed (${resp.status} ${resp.statusText}) from ${opts.uploadUrl} — ${bodyText}`);
|
||||||
`Upload failed (${resp.status} ${resp.statusText}) from ${opts.uploadUrl} — ${bodyText}`
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return bodyText;
|
return bodyText;
|
||||||
@@ -54,9 +49,7 @@ export async function sendBlobFileUpload({
|
|||||||
}
|
}
|
||||||
// In browsers, fetch throws TypeError on network-level failures
|
// In browsers, fetch throws TypeError on network-level failures
|
||||||
if (err instanceof TypeError) {
|
if (err instanceof TypeError) {
|
||||||
throw new Error(
|
throw new Error(`HTTP error uploading to ${opts.uploadUrl}: ${err.message}`);
|
||||||
`HTTP error uploading to ${opts.uploadUrl}: ${err.message}`
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
// Todo: fix error message response
|
// Todo: fix error message response
|
||||||
return `Hotlist Load OK`;
|
return `Hotlist Load OK`;
|
||||||
|
|||||||
@@ -127,8 +127,8 @@ const SightingModal = ({ isSightingModalOpen, handleClose, sighting, onDelete }:
|
|||||||
<div className="flex flex-col border-b border-gray-600 mb-4">
|
<div className="flex flex-col border-b border-gray-600 mb-4">
|
||||||
<p className="text-gray-300">Hotlists</p>
|
<p className="text-gray-300">Hotlists</p>
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-x-[90%] lg:gap-x-[15%] w-[50%]">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-x-[90%] lg:gap-x-[15%] w-[50%]">
|
||||||
{hotlistNames.map((hotlistName) => (
|
{hotlistNames.map((hotlistName, index) => (
|
||||||
<div className="items-center px-2.5 py-0.5 rounded-sm me-2 bg-amber-500 w-55 m-2">
|
<div className="items-center px-2.5 py-0.5 rounded-sm me-2 bg-amber-500 w-55 m-2" key={index}>
|
||||||
<p className="font-medium text-2xl break-all text-amber-800">
|
<p className="font-medium text-2xl break-all text-amber-800">
|
||||||
{hotlistName ? hotlistName?.replace(/\.csv$/i, "") : "-"}
|
{hotlistName ? hotlistName?.replace(/\.csv$/i, "") : "-"}
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import type { HitKind, QueuedHit, ReducedSightingType, SightingType } from "../../types/types";
|
import type { HitKind, QueuedHit, ReducedSightingType, SightingType } from "../../types/types";
|
||||||
import { BLANK_IMG, getSoundFileURL } from "../../utils/utils";
|
import { BLANK_IMG } from "../../utils/utils";
|
||||||
import NumberPlate from "../PlateStack/NumberPlate";
|
import NumberPlate from "../PlateStack/NumberPlate";
|
||||||
import Card from "../UI/Card";
|
import Card from "../UI/Card";
|
||||||
import CardHeader from "../UI/CardHeader";
|
import CardHeader from "../UI/CardHeader";
|
||||||
@@ -15,10 +15,11 @@ import NPED_CAT_C from "/NPED_Cat_C.svg";
|
|||||||
import popup from "../../assets/sounds/ui/popup_open.mp3";
|
import popup from "../../assets/sounds/ui/popup_open.mp3";
|
||||||
import notification from "../../assets/sounds/ui/notification.mp3";
|
import notification from "../../assets/sounds/ui/notification.mp3";
|
||||||
import { useSound } from "react-sounds";
|
import { useSound } from "react-sounds";
|
||||||
import { useNPEDContext } from "../../context/NPEDUserContext";
|
import { useIntegrationsContext } from "../../context/IntegrationsContext";
|
||||||
import { useSoundContext } from "../../context/SoundContext";
|
import { useSoundContext } from "../../context/SoundContext";
|
||||||
import Loading from "../UI/Loading";
|
import Loading from "../UI/Loading";
|
||||||
import { checkIsHotListHit, getNPEDCategory } from "../../utils/utils";
|
import { checkIsHotListHit, getNPEDCategory } from "../../utils/utils";
|
||||||
|
import { useCachedSoundSrc } from "../../hooks/usecachedSoundSrc";
|
||||||
|
|
||||||
function useNow(tickMs = 1000) {
|
function useNow(tickMs = 1000) {
|
||||||
const [, setNow] = useState(() => Date.now());
|
const [, setNow] = useState(() => Date.now());
|
||||||
@@ -43,21 +44,8 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
|
|||||||
useNow(1000);
|
useNow(1000);
|
||||||
const { state } = useSoundContext();
|
const { state } = useSoundContext();
|
||||||
|
|
||||||
const soundSrcNped = useMemo(() => {
|
const { src: soundSrcHotlist } = useCachedSoundSrc(state?.hotlistSound, state?.soundOptions, notification);
|
||||||
if (state?.NPEDsound?.includes(".mp3") || state.NPEDsound?.includes(".wav")) {
|
const { src: soundSrcNped } = useCachedSoundSrc(state?.NPEDsound, state?.soundOptions, popup);
|
||||||
const file = state.soundOptions?.find((item) => item.name === state.NPEDsound);
|
|
||||||
return file?.soundUrl ?? popup;
|
|
||||||
}
|
|
||||||
return getSoundFileURL(state.NPEDsound) ?? popup;
|
|
||||||
}, [state.NPEDsound, state.soundOptions]);
|
|
||||||
|
|
||||||
const soundSrcHotlist = useMemo(() => {
|
|
||||||
if (state?.hotlistSound?.includes(".mp3") || state.hotlistSound?.includes(".wav")) {
|
|
||||||
const file = state.soundOptions?.find((item) => item.name === state.hotlistSound);
|
|
||||||
return file?.soundUrl ?? notification;
|
|
||||||
}
|
|
||||||
return getSoundFileURL(state?.hotlistSound) ?? notification;
|
|
||||||
}, [state.hotlistSound, state.soundOptions]);
|
|
||||||
|
|
||||||
const { play: npedSound } = useSound(soundSrcNped, { volume: state.NPEDsoundVolume });
|
const { play: npedSound } = useSound(soundSrcNped, { volume: state.NPEDsoundVolume });
|
||||||
const { play: hotlistsound } = useSound(soundSrcHotlist, { volume: state.hotlistSoundVolume });
|
const { play: hotlistsound } = useSound(soundSrcHotlist, { volume: state.hotlistSoundVolume });
|
||||||
@@ -72,7 +60,9 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
|
|||||||
} = useSightingFeedContext();
|
} = useSightingFeedContext();
|
||||||
|
|
||||||
const { dispatch } = useAlertHitContext();
|
const { dispatch } = useAlertHitContext();
|
||||||
const { sessionStarted, setSessionList, sessionList } = useNPEDContext();
|
const { state: integrationState, dispatch: integrationDispatch } = useIntegrationsContext();
|
||||||
|
const sessionStarted = integrationState.sessionStarted;
|
||||||
|
const sessionPaused = integrationState.sessionPaused;
|
||||||
|
|
||||||
const processedRefs = useRef<Set<number | string>>(new Set());
|
const processedRefs = useRef<Set<number | string>>(new Set());
|
||||||
|
|
||||||
@@ -97,11 +87,12 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (sessionStarted) {
|
if (sessionStarted) {
|
||||||
if (!mostRecent) return;
|
if (!mostRecent) return;
|
||||||
|
if (sessionPaused) return;
|
||||||
const reducedMostRecent = reduceObject(mostRecent);
|
const reducedMostRecent = reduceObject(mostRecent);
|
||||||
setSessionList([...sessionList, reducedMostRecent]);
|
integrationDispatch({ type: "ADD", payload: reducedMostRecent });
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [mostRecent, sessionStarted, setSessionList]);
|
}, [mostRecent, sessionStarted]);
|
||||||
|
|
||||||
const onRowClick = useCallback(
|
const onRowClick = useCallback(
|
||||||
(sighting: SightingType) => {
|
(sighting: SightingType) => {
|
||||||
|
|||||||
@@ -11,25 +11,18 @@ type CameraOverviewHeaderProps = {
|
|||||||
sighting?: SightingType | null;
|
sighting?: SightingType | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const CardHeader = ({
|
const CardHeader = ({ title, icon, img, sighting }: CameraOverviewHeaderProps) => {
|
||||||
title,
|
|
||||||
icon,
|
|
||||||
img,
|
|
||||||
sighting,
|
|
||||||
}: CameraOverviewHeaderProps) => {
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"w-full border-b border-gray-600 flex flex-row items-center space-x-2 md:mb-6 relative justify-between"
|
"w-full border-b border-gray-600 flex flex-row items-center space-x-2 mb-6 relative justify-between"
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className="flex items-center space-x-2">
|
<div className="flex items-center space-x-2">
|
||||||
{icon && <FontAwesomeIcon icon={icon} className="size-4" />}
|
{icon && <FontAwesomeIcon icon={icon} className="size-4" />}
|
||||||
<h2 className="text-xl">{title}</h2>
|
<h2 className="text-xl">{title}</h2>
|
||||||
</div>
|
</div>
|
||||||
{img && (
|
{img && <img src={img} alt="Logo" width={100} height={50} className="ml-auto" />}
|
||||||
<img src={img} alt="Logo" width={100} height={50} className="ml-auto" />
|
|
||||||
)}
|
|
||||||
{sighting?.vrm && <NumberPlate vrm={sighting.vrm} motion={false} />}
|
{sighting?.vrm && <NumberPlate vrm={sighting.vrm} motion={false} />}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,21 +1,18 @@
|
|||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
import Logo from "/MAV.svg";
|
import Logo from "/MAV.svg";
|
||||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||||
import {
|
import { faGear, faHome, faListCheck, faMaximize, faMinimize, faRotate } from "@fortawesome/free-solid-svg-icons";
|
||||||
faGear,
|
|
||||||
faHome,
|
|
||||||
faListCheck,
|
|
||||||
faMaximize,
|
|
||||||
faMinimize,
|
|
||||||
faRotate,
|
|
||||||
} from "@fortawesome/free-solid-svg-icons";
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import SoundBtn from "./SoundBtn";
|
import SoundBtn from "./SoundBtn";
|
||||||
import { useNPEDContext } from "../../context/NPEDUserContext";
|
import { useIntegrationsContext } from "../../context/IntegrationsContext";
|
||||||
|
|
||||||
export default function Header() {
|
export default function Header() {
|
||||||
const [isFullscreen, setIsFullscreen] = useState(false);
|
const [isFullscreen, setIsFullscreen] = useState(false);
|
||||||
const { sessionStarted } = useNPEDContext();
|
const { state } = useIntegrationsContext();
|
||||||
|
|
||||||
|
const sessionStarted = state.sessionStarted;
|
||||||
|
|
||||||
|
const sessionPaused = state.sessionPaused;
|
||||||
|
|
||||||
const toggleFullscreen = () => {
|
const toggleFullscreen = () => {
|
||||||
if (!document.fullscreenElement) {
|
if (!document.fullscreenElement) {
|
||||||
@@ -39,9 +36,13 @@ export default function Header() {
|
|||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col lg:flex-row items-center space-x-24 justify-items-center">
|
<div className="flex flex-col lg:flex-row items-center space-x-24 justify-items-center">
|
||||||
{sessionStarted && (
|
<div className="flex flex-row lg:flex-row space-x-2">
|
||||||
<div className="text-green-400 font-bold">Session Active</div>
|
{sessionStarted && sessionPaused ? (
|
||||||
|
<p className="text-gray-400 font-bold">Session Paused</p>
|
||||||
|
) : (
|
||||||
|
sessionStarted && <p className="text-green-400 font-bold">Session Active</p>
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-row space-x-8">
|
<div className="flex flex-row space-x-8">
|
||||||
<Link to={"/"}>
|
<Link to={"/"}>
|
||||||
@@ -59,11 +60,7 @@ export default function Header() {
|
|||||||
</div>
|
</div>
|
||||||
<SoundBtn />
|
<SoundBtn />
|
||||||
<Link to={"/session-settings"}>
|
<Link to={"/session-settings"}>
|
||||||
<FontAwesomeIcon
|
<FontAwesomeIcon className="text-white" icon={faListCheck} size="2x" />
|
||||||
className="text-white"
|
|
||||||
icon={faListCheck}
|
|
||||||
size="2x"
|
|
||||||
/>
|
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
<Link to={"/system-settings"}>
|
<Link to={"/system-settings"}>
|
||||||
|
|||||||
18
src/components/UI/VehicleSessionItem.tsx
Normal file
18
src/components/UI/VehicleSessionItem.tsx
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import clsx from "clsx";
|
||||||
|
|
||||||
|
type VehicleSessionItemProps = {
|
||||||
|
sessionNumber: number;
|
||||||
|
textColour: string;
|
||||||
|
vehicleTag: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const VehicleSessionItem = ({ sessionNumber, textColour, vehicleTag }: VehicleSessionItemProps) => {
|
||||||
|
return (
|
||||||
|
<li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between items-center">
|
||||||
|
<p>{vehicleTag}</p>
|
||||||
|
<span className={`font-bold text-xl bg-slate-700 px-2 rounded-md ${clsx(textColour)}`}>{sessionNumber}</span>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default VehicleSessionItem;
|
||||||
14
src/context/IntegrationsContext.ts
Normal file
14
src/context/IntegrationsContext.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { createContext, useContext, type ActionDispatch } from "react";
|
||||||
|
import type { NPEDACTION, NPEDSTATE } from "../types/types";
|
||||||
|
|
||||||
|
type IntegrationsValue = {
|
||||||
|
state: NPEDSTATE;
|
||||||
|
dispatch: ActionDispatch<[action: NPEDACTION]>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const IntegrationsContext = createContext<IntegrationsValue | undefined>(undefined);
|
||||||
|
export const useIntegrationsContext = () => {
|
||||||
|
const ctx = useContext(IntegrationsContext);
|
||||||
|
if (!ctx) throw new Error("useNPEDContext must be used within <IntegrationsProvider>");
|
||||||
|
return ctx;
|
||||||
|
};
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import { createContext, useContext, type SetStateAction } from "react";
|
|
||||||
import type { NPEDUser, ReducedSightingType } from "../types/types";
|
|
||||||
|
|
||||||
type UserContextValue = {
|
|
||||||
user: NPEDUser | null;
|
|
||||||
setUser: React.Dispatch<SetStateAction<NPEDUser | null>>;
|
|
||||||
sessionStarted: boolean;
|
|
||||||
setSessionStarted: React.Dispatch<SetStateAction<boolean>>;
|
|
||||||
sessionList: ReducedSightingType[];
|
|
||||||
setSessionList: React.Dispatch<SetStateAction<ReducedSightingType[]>>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const NPEDUserContext = createContext<UserContextValue | undefined>(
|
|
||||||
undefined
|
|
||||||
);
|
|
||||||
export const useNPEDContext = () => {
|
|
||||||
const ctx = useContext(NPEDUserContext);
|
|
||||||
if (!ctx)
|
|
||||||
throw new Error("useNPEDContext must be used within <NPEDUserProvider>");
|
|
||||||
return ctx;
|
|
||||||
};
|
|
||||||
36
src/context/providers/IntegrationsContextProvider.tsx
Normal file
36
src/context/providers/IntegrationsContextProvider.tsx
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import { useEffect, useReducer, type ReactNode } from "react";
|
||||||
|
import { IntegrationsContext } from "../IntegrationsContext";
|
||||||
|
import { useCameraBlackboard } from "../../hooks/useCameraBlackboard";
|
||||||
|
import { initialState, reducer } from "../reducers/IntegrationsContextReducer";
|
||||||
|
|
||||||
|
type IntegrationsProviderType = {
|
||||||
|
children: ReactNode;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const IntegrationsProvider = ({ children }: IntegrationsProviderType) => {
|
||||||
|
const [state, dispatch] = useReducer(reducer, initialState);
|
||||||
|
const { mutation } = useCameraBlackboard();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchData = async () => {
|
||||||
|
const result = await mutation.mutateAsync({
|
||||||
|
operation: "VIEW",
|
||||||
|
path: "sessionStats",
|
||||||
|
});
|
||||||
|
if (!result.result || typeof result.result === "string") return;
|
||||||
|
|
||||||
|
dispatch({ type: "UPDATE", payload: result?.result });
|
||||||
|
};
|
||||||
|
fetchData();
|
||||||
|
}, []);
|
||||||
|
return (
|
||||||
|
<IntegrationsContext.Provider
|
||||||
|
value={{
|
||||||
|
state,
|
||||||
|
dispatch,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</IntegrationsContext.Provider>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
import { useState, type ReactNode } from "react";
|
|
||||||
import type { NPEDUser, ReducedSightingType } from "../../types/types";
|
|
||||||
import { NPEDUserContext } from "../NPEDUserContext";
|
|
||||||
|
|
||||||
type NPEDUserProviderType = {
|
|
||||||
children: ReactNode;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const NPEDUserProvider = ({ children }: NPEDUserProviderType) => {
|
|
||||||
const [user, setUser] = useState<NPEDUser | null>(null);
|
|
||||||
const [sessionStarted, setSessionStarted] = useState(false);
|
|
||||||
const [sessionList, setSessionList] = useState<ReducedSightingType[]>([]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<NPEDUserContext.Provider
|
|
||||||
value={{
|
|
||||||
user,
|
|
||||||
setUser,
|
|
||||||
setSessionStarted,
|
|
||||||
sessionStarted,
|
|
||||||
sessionList,
|
|
||||||
setSessionList,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</NPEDUserContext.Provider>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
46
src/context/reducers/IntegrationsContextReducer.ts
Normal file
46
src/context/reducers/IntegrationsContextReducer.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import type { NPEDACTION, NPEDSTATE } from "../../types/types";
|
||||||
|
|
||||||
|
export const initialState = {
|
||||||
|
sessionStarted: false,
|
||||||
|
sessionList: [],
|
||||||
|
sessionPaused: false,
|
||||||
|
savedSightings: [],
|
||||||
|
npedUser: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
export function reducer(state: NPEDSTATE, action: NPEDACTION) {
|
||||||
|
switch (action.type) {
|
||||||
|
case "SESSIONSTART":
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
sessionStarted: action.payload,
|
||||||
|
};
|
||||||
|
case "LOGIN":
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
npedUser: action.payload,
|
||||||
|
};
|
||||||
|
case "LOGOUT":
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
npedUser: action.payload,
|
||||||
|
};
|
||||||
|
case "SESSIONPAUSE":
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
sessionPaused: action.payload,
|
||||||
|
};
|
||||||
|
case "ADD":
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
sessionList: [...state.sessionList, action.payload],
|
||||||
|
};
|
||||||
|
case "UPDATE":
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
sessionList: action.payload,
|
||||||
|
};
|
||||||
|
default:
|
||||||
|
return { ...state };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,10 +13,12 @@ export const initialState: SoundState = {
|
|||||||
{ name: "Ding", soundFileName: "ding" },
|
{ name: "Ding", soundFileName: "ding" },
|
||||||
{ name: "Shutter", soundFileName: "shutter" },
|
{ name: "Shutter", soundFileName: "shutter" },
|
||||||
{ name: "Warning (voice)", soundFileName: "warning" },
|
{ name: "Warning (voice)", soundFileName: "warning" },
|
||||||
|
{ name: "Attention (voice)", soundFileName: "attention" },
|
||||||
],
|
],
|
||||||
sightingVolume: 1,
|
sightingVolume: 1,
|
||||||
NPEDsoundVolume: 1,
|
NPEDsoundVolume: 1,
|
||||||
hotlistSoundVolume: 1,
|
hotlistSoundVolume: 1,
|
||||||
|
uploadedSound: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function reducer(state: SoundState, action: SoundAction): SoundState {
|
export function reducer(state: SoundState, action: SoundAction): SoundState {
|
||||||
@@ -62,7 +64,11 @@ export function reducer(state: SoundState, action: SoundAction): SoundState {
|
|||||||
...state,
|
...state,
|
||||||
hotlistSoundVolume: action.payload,
|
hotlistSoundVolume: action.payload,
|
||||||
};
|
};
|
||||||
|
case "UPLOADEDSOUND":
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
uploadedSound: action.payload,
|
||||||
|
};
|
||||||
default:
|
default:
|
||||||
return state;
|
return state;
|
||||||
}
|
}
|
||||||
|
|||||||
75
src/hooks/useBackOfficeConfig.ts
Normal file
75
src/hooks/useBackOfficeConfig.ts
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import type { InitialValuesForm } from "../types/types";
|
||||||
|
import { CAM_BASE } from "../utils/config";
|
||||||
|
|
||||||
|
const getBackOfficeConfig = async (format: string) => {
|
||||||
|
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Dispatcher-${format?.toLowerCase()}`);
|
||||||
|
if (!response.ok) throw new Error("Cannot get Back Office configuration");
|
||||||
|
return response.json();
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateBackOfficeConfig = async (data: InitialValuesForm) => {
|
||||||
|
const updateConfigPayload = {
|
||||||
|
id: `Dispatcher-${data.format.toLowerCase()}`,
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
property: "propBackofficeURL",
|
||||||
|
value: data.backOfficeURL,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
property: "propConnectTimeoutSeconds",
|
||||||
|
value: data.connectTimeoutSeconds,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
property: "propPassword",
|
||||||
|
value: data.password,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
property: "propReadTimeoutSeconds",
|
||||||
|
value: data.readTimeoutSeconds,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
property: "propUsername",
|
||||||
|
value: data.username,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const response = await fetch(`${CAM_BASE}/api/update-config?id=Dispatcher`, {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(updateConfigPayload),
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error("Cannot update Back Office configuration");
|
||||||
|
return response.json();
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useCameraBackOfficeOutput = (format: string) => {
|
||||||
|
const backOfficeQuery = useQuery({
|
||||||
|
queryKey: ["backoffice", format],
|
||||||
|
queryFn: () => getBackOfficeConfig(format),
|
||||||
|
enabled: !!format,
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (backOfficeQuery.isError) toast.error(backOfficeQuery.error.message);
|
||||||
|
}, [backOfficeQuery?.error?.message, backOfficeQuery.isError]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
backOfficeQuery,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useUpdateBackOfficeConfig = () => {
|
||||||
|
const backOfficeMutation = useMutation({
|
||||||
|
mutationKey: ["backOfficeUpdate"],
|
||||||
|
mutationFn: updateBackOfficeConfig,
|
||||||
|
onError: (error) => toast.error(error.message),
|
||||||
|
onSuccess: (data) => {
|
||||||
|
if (data) {
|
||||||
|
toast.success("Settings successfully updated", { id: "dispatchSettings" });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return { backOfficeMutation };
|
||||||
|
};
|
||||||
@@ -2,7 +2,7 @@ import { useMutation, useQuery } from "@tanstack/react-query";
|
|||||||
import { CAM_BASE } from "../utils/config";
|
import { CAM_BASE } from "../utils/config";
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import type { BearerTypeFieldType, InitialValuesForm } from "../types/types";
|
import type { BearerTypeFieldType, OptionalBOF2Constants } from "../types/types";
|
||||||
|
|
||||||
const getDispatcherConfig = async () => {
|
const getDispatcherConfig = async () => {
|
||||||
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Dispatcher`);
|
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Dispatcher`);
|
||||||
@@ -18,7 +18,6 @@ const updateDispatcherConfig = async (data: BearerTypeFieldType) => {
|
|||||||
property: "propEnabled",
|
property: "propEnabled",
|
||||||
value: data.enabled,
|
value: data.enabled,
|
||||||
},
|
},
|
||||||
// Todo: figure out how to add verbose conditionally
|
|
||||||
{
|
{
|
||||||
property: "propFormat",
|
property: "propFormat",
|
||||||
value: data.format,
|
value: data.format,
|
||||||
@@ -33,43 +32,39 @@ const updateDispatcherConfig = async (data: BearerTypeFieldType) => {
|
|||||||
return response.json();
|
return response.json();
|
||||||
};
|
};
|
||||||
|
|
||||||
const getBackOfficeConfig = async () => {
|
const updateBackOfficeDispatcher = async (data: OptionalBOF2Constants) => {
|
||||||
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Dispatcher-json`);
|
const bof2ContantsPayload = {
|
||||||
if (!response.ok) throw new Error("Cannot get Back Office configuration");
|
id: "Dispatcher-bof2-constants",
|
||||||
return response.json();
|
|
||||||
};
|
|
||||||
|
|
||||||
const updateBackOfficeConfig = async (data: InitialValuesForm) => {
|
|
||||||
const updateConfigPayload = {
|
|
||||||
id: "Dispatcher-json",
|
|
||||||
fields: [
|
fields: [
|
||||||
{
|
{
|
||||||
property: "propBackofficeURL",
|
property: "propFeedIdentifier",
|
||||||
value: data.backOfficeURL,
|
value: data?.FFID,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
property: "propConnectTimeoutSeconds",
|
property: "propSourceIdentifier",
|
||||||
value: data.connectTimeoutSeconds,
|
value: data?.SCID,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
property: "propPassword",
|
property: "propTimeZoneType",
|
||||||
value: data.password,
|
value: data?.timestampSource,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
property: "propReadTimeoutSeconds",
|
property: "propGpsFormat",
|
||||||
value: data.readTimeoutSeconds,
|
value: data?.GPSFormat,
|
||||||
},
|
|
||||||
{
|
|
||||||
property: "propUsername",
|
|
||||||
value: data.username,
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
const response = await fetch(`${CAM_BASE}/api/update-config?id=Dispatcher-json`, {
|
const response = await fetch(`${CAM_BASE}/api/update-config?id=Dispatcher-bof2-constants`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: JSON.stringify(updateConfigPayload),
|
body: JSON.stringify(bof2ContantsPayload),
|
||||||
});
|
});
|
||||||
if (!response.ok) throw new Error("Cannot update Back Office configuration");
|
if (!response.ok) throw new Error("Cannot update dispatcher configuration");
|
||||||
|
return response.json();
|
||||||
|
};
|
||||||
|
|
||||||
|
const getBof2DispatcherData = async () => {
|
||||||
|
const response = await fetch(`http://100.118.196.113:8080/api/fetch-config?id=Dispatcher-bof2-constants`);
|
||||||
|
if (!response.ok) throw new Error("Cannot get BOF2 dispatcher config");
|
||||||
return response.json();
|
return response.json();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -79,29 +74,23 @@ export const useCameraOutput = () => {
|
|||||||
queryFn: getDispatcherConfig,
|
queryFn: getDispatcherConfig,
|
||||||
});
|
});
|
||||||
|
|
||||||
const backOfficeQuery = useQuery({
|
|
||||||
queryKey: ["backoffice"],
|
|
||||||
queryFn: getBackOfficeConfig,
|
|
||||||
});
|
|
||||||
|
|
||||||
const dispatcherMutation = useMutation({
|
const dispatcherMutation = useMutation({
|
||||||
mutationFn: updateDispatcherConfig,
|
mutationFn: updateDispatcherConfig,
|
||||||
mutationKey: ["dispatcherUpdate"],
|
mutationKey: ["dispatcherUpdate"],
|
||||||
onError: (error) => toast.error(error.message),
|
onError: (error) => toast.error(error.message),
|
||||||
onSuccess: (data) => {
|
onSuccess: (data) => {
|
||||||
if (data) {
|
if (data) {
|
||||||
toast.success("Settings successfully updated");
|
toast.success("Settings successfully updated", { id: "dispatchSettings" });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const backOfficeMutation = useMutation({
|
const backOfficeDispatcherMutation = useMutation({
|
||||||
mutationKey: ["backOfficeUpdate"],
|
mutationKey: ["backofficedDispatcher"],
|
||||||
mutationFn: updateBackOfficeConfig,
|
mutationFn: updateBackOfficeDispatcher,
|
||||||
onError: (error) => toast.error(error.message),
|
|
||||||
onSuccess: (data) => {
|
onSuccess: (data) => {
|
||||||
if (data) {
|
if (data) {
|
||||||
toast.success("Settings successfully updated");
|
toast.success("Settings successfully updated", { id: "dispatchSettings" });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -110,14 +99,18 @@ export const useCameraOutput = () => {
|
|||||||
if (dispatcherQuery.isError) toast.error(dispatcherQuery.error.message);
|
if (dispatcherQuery.isError) toast.error(dispatcherQuery.error.message);
|
||||||
}, [dispatcherQuery?.error?.message, dispatcherQuery.isError]);
|
}, [dispatcherQuery?.error?.message, dispatcherQuery.isError]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (backOfficeQuery.isError) toast.error(backOfficeQuery.error.message);
|
|
||||||
}, [backOfficeQuery?.error?.message, backOfficeQuery.isError]);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
dispatcherQuery,
|
dispatcherQuery,
|
||||||
dispatcherMutation,
|
dispatcherMutation,
|
||||||
backOfficeQuery,
|
backOfficeDispatcherMutation,
|
||||||
backOfficeMutation,
|
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const useGetDispatcherConfig = () => {
|
||||||
|
const bof2ConstantsQuery = useQuery({
|
||||||
|
queryKey: ["getBof2DispatcherData"],
|
||||||
|
queryFn: getBof2DispatcherData,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { bof2ConstantsQuery };
|
||||||
|
};
|
||||||
|
|||||||
45
src/hooks/useFileUpload.ts
Normal file
45
src/hooks/useFileUpload.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||||
|
import { CAM_BASE } from "../utils/config";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { getOrCacheBlob } from "../utils/cacheSound";
|
||||||
|
const camBase = import.meta.env.MODE !== "development" ? CAM_BASE : CAM_BASE;
|
||||||
|
|
||||||
|
type UseFileUploadProps = {
|
||||||
|
queryKey?: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const uploadFile = async (file: File) => {
|
||||||
|
const form = new FormData();
|
||||||
|
form.append("upload", file, file.name);
|
||||||
|
const response = await fetch(`${camBase}/upload/file-upload/3`, {
|
||||||
|
method: "POST",
|
||||||
|
body: form,
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Cannot reach upload file endpoint");
|
||||||
|
}
|
||||||
|
return response.text();
|
||||||
|
};
|
||||||
|
|
||||||
|
const getUploadFiles = async ({ queryKey }: { queryKey: string[] }) => {
|
||||||
|
const [, fileName] = queryKey;
|
||||||
|
const url = fileName;
|
||||||
|
return getOrCacheBlob(url);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useFileUpload = ({ queryKey }: UseFileUploadProps) => {
|
||||||
|
const query = useQuery({
|
||||||
|
queryKey: ["getUploadFiles", ...(queryKey ?? [])],
|
||||||
|
queryFn: () => getUploadFiles({ queryKey: ["getUploadFiles", ...(queryKey ?? [])] }),
|
||||||
|
enabled: !!queryKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: (file: File) => uploadFile(file),
|
||||||
|
mutationKey: ["uploadFile"],
|
||||||
|
onError: (err) => toast.error(err ? err.message : ""),
|
||||||
|
onSuccess: async (msg) => toast.success(msg),
|
||||||
|
});
|
||||||
|
|
||||||
|
return { query: queryKey ? query : undefined, mutation };
|
||||||
|
};
|
||||||
46
src/hooks/useFormValidate.ts
Normal file
46
src/hooks/useFormValidate.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import { useMutation } from "@tanstack/react-query";
|
||||||
|
import { CAM_BASE } from "../utils/config";
|
||||||
|
import type { InitialValuesForm } from "../types/types";
|
||||||
|
|
||||||
|
const sendToValidate = async (data: InitialValuesForm) => {
|
||||||
|
const updateConfigPayload = {
|
||||||
|
id: `Dispatcher-${data.format.toLowerCase()}`,
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
property: "propBackofficeURL",
|
||||||
|
value: data.backOfficeURL,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
property: "propConnectTimeoutSeconds",
|
||||||
|
value: data.connectTimeoutSeconds,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
property: "propPassword",
|
||||||
|
value: data.password,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
property: "propReadTimeoutSeconds",
|
||||||
|
value: data.readTimeoutSeconds,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
property: "propUsername",
|
||||||
|
value: data.username,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const response = await fetch(`${CAM_BASE}/api/update-config-isvalid`, {
|
||||||
|
method: "post",
|
||||||
|
body: JSON.stringify(updateConfigPayload),
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error("Cannot send to validate");
|
||||||
|
return response.json();
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useFormVaidate = () => {
|
||||||
|
const validateMutation = useMutation({
|
||||||
|
mutationKey: ["sendToValidate"],
|
||||||
|
mutationFn: sendToValidate,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { validateMutation };
|
||||||
|
};
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||||
import type { NPEDFieldType } from "../types/types";
|
import type { NPEDFieldType } from "../types/types";
|
||||||
import { useNPEDContext } from "../context/NPEDUserContext";
|
import { useIntegrationsContext } from "../context/IntegrationsContext";
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
import { CAM_BASE } from "../utils/config";
|
import { CAM_BASE } from "../utils/config";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
@@ -42,8 +42,7 @@ async function signIn(loginDetails: NPEDFieldType) {
|
|||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (!frontRes.ok || !rearRes.ok)
|
if (!frontRes.ok || !rearRes.ok) throw new Error("Cannot reach NPED endpoint");
|
||||||
throw new Error("Cannot reach NPED endpoint");
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
frontResponse: frontRes.json(),
|
frontResponse: frontRes.json(),
|
||||||
@@ -73,7 +72,7 @@ async function signOut() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const useNPEDAuth = () => {
|
export const useNPEDAuth = () => {
|
||||||
const { setUser, user } = useNPEDContext();
|
const { dispatch } = useIntegrationsContext();
|
||||||
|
|
||||||
const signInMutation = useMutation({
|
const signInMutation = useMutation({
|
||||||
mutationKey: ["NPEDSignin"],
|
mutationKey: ["NPEDSignin"],
|
||||||
@@ -84,7 +83,8 @@ export const useNPEDAuth = () => {
|
|||||||
onSuccess: async (data) => {
|
onSuccess: async (data) => {
|
||||||
toast.dismiss();
|
toast.dismiss();
|
||||||
toast.success("Signed in successfully!");
|
toast.success("Signed in successfully!");
|
||||||
setUser(await data.frontResponse);
|
|
||||||
|
dispatch({ type: "LOGIN", payload: await data.frontResponse });
|
||||||
},
|
},
|
||||||
onError: (error) => {
|
onError: (error) => {
|
||||||
toast.dismiss();
|
toast.dismiss();
|
||||||
@@ -101,7 +101,7 @@ export const useNPEDAuth = () => {
|
|||||||
mutationFn: signOut,
|
mutationFn: signOut,
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
toast.success("Signed out successfully");
|
toast.success("Signed out successfully");
|
||||||
setUser(null);
|
dispatch({ type: "LOGOUT", payload: null });
|
||||||
},
|
},
|
||||||
onError: (error) => {
|
onError: (error) => {
|
||||||
toast.error(`Sign-out failed: ${error.message}`);
|
toast.error(`Sign-out failed: ${error.message}`);
|
||||||
@@ -115,11 +115,11 @@ export const useNPEDAuth = () => {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (fetchdataQuery.isSuccess && fetchdataQuery.data) {
|
if (fetchdataQuery.isSuccess && fetchdataQuery.data) {
|
||||||
setUser(fetchdataQuery.data);
|
dispatch({ type: "LOGIN", payload: fetchdataQuery.data });
|
||||||
} else {
|
} else {
|
||||||
setUser(null);
|
dispatch({ type: "LOGOUT", payload: null });
|
||||||
}
|
}
|
||||||
}, [fetchdataQuery.data, fetchdataQuery.isSuccess, setUser]);
|
}, [dispatch, fetchdataQuery.data, fetchdataQuery.isSuccess]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (fetchdataQuery.isError) toast.error(fetchdataQuery.error.message);
|
if (fetchdataQuery.isError) toast.error(fetchdataQuery.error.message);
|
||||||
@@ -134,8 +134,6 @@ export const useNPEDAuth = () => {
|
|||||||
data: signInMutation.data,
|
data: signInMutation.data,
|
||||||
fetchdataQueryError: fetchdataQuery.error,
|
fetchdataQueryError: fetchdataQuery.error,
|
||||||
fetchdataQueryLoading: fetchdataQuery.isLoading,
|
fetchdataQueryLoading: fetchdataQuery.isLoading,
|
||||||
user,
|
|
||||||
setUser,
|
|
||||||
signOut: signOutMutation.mutate,
|
signOut: signOutMutation.mutate,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { useDebouncedCallback } from "use-debounce";
|
||||||
import { Query, useQuery } from "@tanstack/react-query";
|
import { Query, useQuery } from "@tanstack/react-query";
|
||||||
import type { SightingType } from "../types/types";
|
import type { SightingType } from "../types/types";
|
||||||
import { useSoundOnChange } from "react-sounds";
|
import { useSound } from "react-sounds";
|
||||||
import { useSoundContext } from "../context/SoundContext";
|
import { useSoundContext } from "../context/SoundContext";
|
||||||
import { getSoundFileURL } from "../utils/utils";
|
import { checkIsHotListHit, getNPEDCategory } from "../utils/utils";
|
||||||
import switchSound from "../assets/sounds/ui/switch.mp3";
|
import switchSound from "../assets/sounds/ui/switch.mp3";
|
||||||
|
import notification from "../assets/sounds/ui/notification.mp3";
|
||||||
|
import popup from "../assets/sounds/ui/popup_open.mp3";
|
||||||
|
import { useCachedSoundSrc } from "./usecachedSoundSrc";
|
||||||
|
|
||||||
async function fetchSighting(url: string | undefined, ref: number): Promise<SightingType> {
|
async function fetchSighting(url: string | undefined, ref: number): Promise<SightingType> {
|
||||||
const res = await fetch(`${url}${ref}`, {
|
const res = await fetch(`${url}${ref}`, {
|
||||||
@@ -21,35 +25,19 @@ export function useSightingFeed(url: string | undefined) {
|
|||||||
const [sessionStarted, setSessionStarted] = useState(false);
|
const [sessionStarted, setSessionStarted] = useState(false);
|
||||||
const [selectedSighting, setSelectedSighting] = useState<SightingType | null>(null);
|
const [selectedSighting, setSelectedSighting] = useState<SightingType | null>(null);
|
||||||
|
|
||||||
const mostRecent = sightings[0] ?? null;
|
const { src: soundSrc } = useCachedSoundSrc(state?.sightingSound, state?.soundOptions, switchSound);
|
||||||
const latestRef = mostRecent?.ref ?? null;
|
const { src: soundSrcHotlist } = useCachedSoundSrc(state?.hotlistSound, state?.soundOptions, notification);
|
||||||
|
const { src: soundSrcNped } = useCachedSoundSrc(state?.NPEDsound, state?.soundOptions, popup);
|
||||||
|
|
||||||
|
const { play: hotlistsound } = useSound(soundSrcHotlist, { volume: state.hotlistSoundVolume });
|
||||||
|
const { play: npedSound } = useSound(soundSrcNped, { volume: state.NPEDsoundVolume });
|
||||||
|
const { play: sightingSound } = useSound(soundSrc, { volume: state.sightingVolume });
|
||||||
|
|
||||||
|
const mostRecent = sightings[0] ?? null;
|
||||||
|
|
||||||
const first = useRef(true);
|
|
||||||
const lastSoundAt = useRef(0);
|
|
||||||
const COOLDOWN_MS = 1500;
|
|
||||||
const currentRef = useRef<number>(-1);
|
const currentRef = useRef<number>(-1);
|
||||||
const lastValidTimestamp = useRef<number>(Date.now());
|
const lastValidTimestamp = useRef<number>(Date.now());
|
||||||
|
|
||||||
const trigger = useMemo(() => {
|
|
||||||
if (latestRef == null || !audioArmed) return null;
|
|
||||||
if (first.current) {
|
|
||||||
first.current = false;
|
|
||||||
return Symbol("skip");
|
|
||||||
}
|
|
||||||
const now = Date.now();
|
|
||||||
if (now - lastSoundAt.current < COOLDOWN_MS) return Symbol("skip");
|
|
||||||
lastSoundAt.current = now;
|
|
||||||
return latestRef;
|
|
||||||
}, [audioArmed, latestRef]);
|
|
||||||
|
|
||||||
const soundSrc = useMemo(() => {
|
|
||||||
if (state?.sightingSound?.includes(".mp3") || state.sightingSound?.includes(".wav")) {
|
|
||||||
const file = state.soundOptions?.find((item) => item.name === state.sightingSound);
|
|
||||||
return file?.soundUrl ?? switchSound;
|
|
||||||
}
|
|
||||||
return getSoundFileURL(state?.sightingSound) ?? switchSound;
|
|
||||||
}, [state.sightingSound, state.soundOptions]);
|
|
||||||
|
|
||||||
function refetchInterval(query: Query<SightingType, Error, SightingType, (string | undefined)[]>) {
|
function refetchInterval(query: Query<SightingType, Error, SightingType, (string | undefined)[]>) {
|
||||||
if (!query) return;
|
if (!query) return;
|
||||||
const data = query.state.data as SightingType | undefined;
|
const data = query.state.data as SightingType | undefined;
|
||||||
@@ -78,16 +66,36 @@ export function useSightingFeed(url: string | undefined) {
|
|||||||
staleTime: 0,
|
staleTime: 0,
|
||||||
});
|
});
|
||||||
|
|
||||||
//use latestref instead of trigger to revert back
|
const playHotlistsound = useDebouncedCallback(() => {
|
||||||
|
hotlistsound();
|
||||||
|
}, 500);
|
||||||
|
|
||||||
useSoundOnChange(soundSrc, trigger, {
|
const playNPEDHitSound = useDebouncedCallback(() => {
|
||||||
volume: state.sightingVolume,
|
npedSound();
|
||||||
initial: false,
|
}, 500);
|
||||||
});
|
|
||||||
|
const playSightingHitSound = useDebouncedCallback(() => {
|
||||||
|
sightingSound();
|
||||||
|
}, 500);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const data = query.data;
|
const data = query.data;
|
||||||
|
|
||||||
if (!data || data.ref === -1) return;
|
if (!data || data.ref === -1) return;
|
||||||
|
const isHotListHit = checkIsHotListHit(data);
|
||||||
|
const cat = getNPEDCategory(data);
|
||||||
|
|
||||||
|
const isNPEDHitA = cat === "A";
|
||||||
|
const isNPEDHitB = cat === "B";
|
||||||
|
const isNPEDHitC = cat === "C";
|
||||||
|
|
||||||
|
if ((isNPEDHitA && audioArmed) || (isNPEDHitB && audioArmed) || (isNPEDHitC && audioArmed)) {
|
||||||
|
playNPEDHitSound();
|
||||||
|
} else if (isHotListHit && audioArmed) {
|
||||||
|
playHotlistsound();
|
||||||
|
} else if (audioArmed) {
|
||||||
|
playSightingHitSound();
|
||||||
|
}
|
||||||
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
|
||||||
|
|||||||
56
src/hooks/usecachedSoundSrc.ts
Normal file
56
src/hooks/usecachedSoundSrc.ts
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import { useFileUpload } from "./useFileUpload";
|
||||||
|
import { getSoundFileURL } from "../utils/utils";
|
||||||
|
import type { SoundUploadValue } from "../types/types";
|
||||||
|
import { resolveSoundSource } from "../utils/soundResolver";
|
||||||
|
|
||||||
|
export function useCachedSoundSrc(
|
||||||
|
selected: string | undefined,
|
||||||
|
soundOptions: SoundUploadValue[] | undefined,
|
||||||
|
fallbackUrl: string
|
||||||
|
) {
|
||||||
|
const isUploaded = !!selected && (selected.endsWith(".mp3") || selected.endsWith(".wav"));
|
||||||
|
|
||||||
|
const resolved = resolveSoundSource(selected, soundOptions);
|
||||||
|
|
||||||
|
const { query } = useFileUpload({
|
||||||
|
queryKey: resolved?.type === "uploaded" ? [resolved?.url] : undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
const [objectUrl, setObjectUrl] = useState<string>();
|
||||||
|
const objRef = useRef<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const blob = query?.data;
|
||||||
|
|
||||||
|
if (blob instanceof Blob) {
|
||||||
|
if (objRef.current) URL.revokeObjectURL(objRef.current);
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
objRef.current = url;
|
||||||
|
setObjectUrl(url);
|
||||||
|
} else {
|
||||||
|
if (objRef.current) URL.revokeObjectURL(objRef.current);
|
||||||
|
objRef.current = null;
|
||||||
|
setObjectUrl(undefined);
|
||||||
|
}
|
||||||
|
}, [query?.data]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
if (objRef.current) URL.revokeObjectURL(objRef.current);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const src = useMemo(() => {
|
||||||
|
if (isUploaded && objectUrl) return objectUrl;
|
||||||
|
if (!selected) return fallbackUrl;
|
||||||
|
return getSoundFileURL(selected) ?? fallbackUrl;
|
||||||
|
}, [isUploaded, objectUrl, selected, fallbackUrl]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
src,
|
||||||
|
isUploaded,
|
||||||
|
isLoading: !!query?.isLoading,
|
||||||
|
error: (query?.error as Error) || undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -48,10 +48,11 @@ export type CameraSettingErrorValues = Partial<Record<keyof CameraSettingValues,
|
|||||||
export type BearerTypeFieldType = {
|
export type BearerTypeFieldType = {
|
||||||
format: string;
|
format: string;
|
||||||
enabled: boolean;
|
enabled: boolean;
|
||||||
verbose: boolean;
|
verbose?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type InitialValuesForm = {
|
export type InitialValuesForm = {
|
||||||
|
format: string;
|
||||||
backOfficeURL: string;
|
backOfficeURL: string;
|
||||||
username: string;
|
username: string;
|
||||||
password: string;
|
password: string;
|
||||||
@@ -67,6 +68,13 @@ export type InitialValuesFormErrors = {
|
|||||||
readTimeoutSeconds?: string;
|
readTimeoutSeconds?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type OptionalBOF2Constants = {
|
||||||
|
FFID?: "";
|
||||||
|
SCID?: "";
|
||||||
|
timestampSource?: "";
|
||||||
|
GPSFormat?: "";
|
||||||
|
};
|
||||||
|
|
||||||
export type NPEDFieldType = {
|
export type NPEDFieldType = {
|
||||||
frontId: string;
|
frontId: string;
|
||||||
username: string | undefined;
|
username: string | undefined;
|
||||||
@@ -294,6 +302,7 @@ export type SoundUploadValue = {
|
|||||||
soundFileName?: string;
|
soundFileName?: string;
|
||||||
soundFile?: File | null;
|
soundFile?: File | null;
|
||||||
soundUrl?: string;
|
soundUrl?: string;
|
||||||
|
uploadedAt?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type SoundState = {
|
export type SoundState = {
|
||||||
@@ -305,6 +314,7 @@ export type SoundState = {
|
|||||||
sightingVolume: number;
|
sightingVolume: number;
|
||||||
NPEDsoundVolume: number;
|
NPEDsoundVolume: number;
|
||||||
hotlistSoundVolume: number;
|
hotlistSoundVolume: number;
|
||||||
|
uploadedSound?: Blob | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
type UpdateAction = {
|
type UpdateAction = {
|
||||||
@@ -331,7 +341,12 @@ type VolumeAction = {
|
|||||||
payload: number;
|
payload: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type SoundAction = UpdateAction | AddAction | VolumeAction;
|
type UploadedState = {
|
||||||
|
type: "UPLOADEDSOUND";
|
||||||
|
payload: Blob | undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SoundAction = UpdateAction | AddAction | VolumeAction | UploadedState;
|
||||||
export type WifiSettingValues = {
|
export type WifiSettingValues = {
|
||||||
ssid: string;
|
ssid: string;
|
||||||
password: string;
|
password: string;
|
||||||
@@ -379,3 +394,18 @@ export type QueuedHit = {
|
|||||||
sighting: SightingType;
|
sighting: SightingType;
|
||||||
kind: HitKind;
|
kind: HitKind;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type DedupedSightings = ReducedSightingType[];
|
||||||
|
|
||||||
|
export type NPEDSTATE = {
|
||||||
|
sessionStarted: boolean;
|
||||||
|
sessionList: ReducedSightingType[];
|
||||||
|
sessionPaused: boolean;
|
||||||
|
savedSightings: DedupedSightings;
|
||||||
|
npedUser: NPEDUser;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type NPEDACTION = {
|
||||||
|
type: string;
|
||||||
|
payload: any;
|
||||||
|
};
|
||||||
|
|||||||
16
src/utils/cacheSound.ts
Normal file
16
src/utils/cacheSound.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
export async function getOrCacheBlob(url: string) {
|
||||||
|
const cache = await caches.open("app-sounds-v1");
|
||||||
|
const hit = await cache.match(url);
|
||||||
|
if (hit) return await hit.blob();
|
||||||
|
|
||||||
|
const res = await fetch(url, { cache: "no-store" });
|
||||||
|
if (!res.ok) throw new Error(`Fetch failed: ${res.status}`);
|
||||||
|
|
||||||
|
await cache.put(url, res.clone());
|
||||||
|
return await res.blob();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function evictFromCache(url: string) {
|
||||||
|
const cache = await caches.open("app-sounds-v1");
|
||||||
|
await cache.delete(url);
|
||||||
|
}
|
||||||
24
src/utils/soundResolver.ts
Normal file
24
src/utils/soundResolver.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { getSoundFileURL } from "./utils";
|
||||||
|
import { CAM_BASE } from "./config";
|
||||||
|
import type { SoundUploadValue } from "../types/types";
|
||||||
|
|
||||||
|
export function resolveSoundSource(
|
||||||
|
selected: string | undefined,
|
||||||
|
soundOptions: SoundUploadValue[] | undefined
|
||||||
|
): { type: "uploaded"; url: string } | { type: "builtin"; url: string } | undefined {
|
||||||
|
if (!selected) return undefined;
|
||||||
|
|
||||||
|
const isFile = selected.endsWith(".mp3") || selected.endsWith(".wav");
|
||||||
|
|
||||||
|
if (isFile) {
|
||||||
|
const match = soundOptions?.find((o) => o.soundFileName === selected);
|
||||||
|
const version = match?.uploadedAt ?? 0;
|
||||||
|
const url = `${CAM_BASE}/Mobile/${encodeURIComponent(selected)}?v=${version}`;
|
||||||
|
return { type: "uploaded", url };
|
||||||
|
}
|
||||||
|
|
||||||
|
const builtin = getSoundFileURL(selected);
|
||||||
|
if (builtin) return { type: "builtin", url: builtin };
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@ import beep from "../assets/sounds/ui/Beep.wav";
|
|||||||
import warning from "../assets/sounds/ui/Warning.wav";
|
import warning from "../assets/sounds/ui/Warning.wav";
|
||||||
import ding from "../assets/sounds/ui/Ding.wav";
|
import ding from "../assets/sounds/ui/Ding.wav";
|
||||||
import shutter from "../assets/sounds/ui/shutter.mp3";
|
import shutter from "../assets/sounds/ui/shutter.mp3";
|
||||||
|
import attention from "../assets/sounds/ui/Attention.wav";
|
||||||
import type { HotlistMatches, SightingType } from "../types/types";
|
import type { HotlistMatches, SightingType } from "../types/types";
|
||||||
|
|
||||||
export function getSoundFileURL(name: string) {
|
export function getSoundFileURL(name: string) {
|
||||||
@@ -17,6 +17,7 @@ export function getSoundFileURL(name: string) {
|
|||||||
warning: warning,
|
warning: warning,
|
||||||
ding: ding,
|
ding: ding,
|
||||||
shutter: shutter,
|
shutter: shutter,
|
||||||
|
attention: attention,
|
||||||
};
|
};
|
||||||
return sounds[name] ?? null;
|
return sounds[name] ?? null;
|
||||||
}
|
}
|
||||||
@@ -156,4 +157,4 @@ export function getHotlistName(obj: HotlistMatches | undefined) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const getNPEDCategory = (r?: SightingType | null) =>
|
export const getNPEDCategory = (r?: SightingType | null) =>
|
||||||
r?.metadata?.npedJSON?.["NPED CATEGORY"] as "A" | "B" | "C" | undefined;
|
r?.metadata?.npedJSON?.["NPED CATEGORY"] as "A" | "B" | "C" | "D" | undefined;
|
||||||
|
|||||||
@@ -2267,6 +2267,11 @@ uri-js@^4.2.2:
|
|||||||
dependencies:
|
dependencies:
|
||||||
punycode "^2.1.0"
|
punycode "^2.1.0"
|
||||||
|
|
||||||
|
use-debounce@^10.0.6:
|
||||||
|
version "10.0.6"
|
||||||
|
resolved "https://registry.yarnpkg.com/use-debounce/-/use-debounce-10.0.6.tgz#e05060a5e561432ec740c653698f3eb162bd28ec"
|
||||||
|
integrity sha512-C5OtPyhAZgVoteO9heXMTdW7v/IbFI+8bSVKYCJrSmiWWCLsbUxiBSp4t9v0hNBTGY97bT72ydDIDyGSFWfwXg==
|
||||||
|
|
||||||
vite@^7.1.0:
|
vite@^7.1.0:
|
||||||
version "7.1.2"
|
version "7.1.2"
|
||||||
resolved "https://registry.npmjs.org/vite/-/vite-7.1.2.tgz"
|
resolved "https://registry.npmjs.org/vite/-/vite-7.1.2.tgz"
|
||||||
|
|||||||
Reference in New Issue
Block a user