// React, Redux, Router import { useTheme } from "@emotion/react"; import { useNavigate, useParams } from "react-router-dom"; import { useEffect } from "react"; import { useState } from "react"; import { useSelector, useDispatch } from "react-redux"; // Utility and Network import { checkEndpointResolution } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; import { monitorValidation } from "../../../Validation/validation"; import { getUptimeMonitorById } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; import { createUptimeMonitor } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; // MUI import { Box, Stack, Typography, Button, ButtonGroup } from "@mui/material"; import LoadingButton from "@mui/lab/LoadingButton"; //Components import Breadcrumbs from "../../../Components/Breadcrumbs"; import TextInput from "../../../Components/Inputs/TextInput"; import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments"; import { createToast } from "../../../Utils/toastUtils"; import Radio from "../../../Components/Inputs/Radio"; import Checkbox from "../../../Components/Inputs/Checkbox"; import Select from "../../../Components/Inputs/Select"; import ConfigBox from "../../../Components/ConfigBox"; const CreateMonitor = () => { const MS_PER_MINUTE = 60000; const SELECT_VALUES = [ { _id: 1, name: "1 minute" }, { _id: 2, name: "2 minutes" }, { _id: 3, name: "3 minutes" }, { _id: 4, name: "4 minutes" }, { _id: 5, name: "5 minutes" }, ]; const monitorTypeMaps = { http: { label: "URL to monitor", placeholder: "google.com", namePlaceholder: "Google", }, ping: { label: "IP address to monitor", placeholder: "1.1.1.1", namePlaceholder: "Google", }, docker: { label: "Container ID", placeholder: "abc123", namePlaceholder: "My Container", }, port: { label: "URL to monitor", placeholder: "localhost", namePlaceholder: "Localhost:5173", }, }; const { user, authToken } = useSelector((state) => state.auth); const { isLoading } = useSelector((state) => state.uptimeMonitors); const dispatch = useDispatch(); const navigate = useNavigate(); const theme = useTheme(); const { monitorId } = useParams(); const crumbs = [ { name: "uptime", path: "/uptime" }, { name: "create", path: `/uptime/create` }, ]; // State const [errors, setErrors] = useState({}); const [https, setHttps] = useState(true); const [monitor, setMonitor] = useState({ url: "", name: "", type: "http", notifications: [], interval: 1, }); const handleCreateMonitor = async (event) => { event.preventDefault(); let form = { url: //prepending protocol for url monitor.type === "http" ? `http${https ? "s" : ""}://` + monitor.url : monitor.url, port: monitor.type === "port" ? monitor.port : undefined, name: monitor.name || monitor.url.substring(0, 50), type: monitor.type, interval: monitor.interval * MS_PER_MINUTE, }; const { error } = monitorValidation.validate(form, { abortEarly: false, }); if (error) { const newErrors = {}; error.details.forEach((err) => { newErrors[err.path[0]] = err.message; }); setErrors(newErrors); createToast({ body: "Please check the form for errors." }); return; } if (monitor.type === "http") { // const checkEndpointAction = await dispatch( // checkEndpointResolution({ authToken, monitorURL: form.url }) // ); // if (checkEndpointAction.meta.requestStatus === "rejected") { // createToast({ // body: "The endpoint you entered doesn't resolve. Check the URL again.", // }); // setErrors({ url: "The entered URL is not reachable." }); // return; // } } form = { ...form, description: monitor.name || monitor.url, teamId: user.teamId, userId: user._id, notifications: monitor.notifications, }; const action = await dispatch(createUptimeMonitor({ authToken, monitor: form })); if (action.meta.requestStatus === "fulfilled") { createToast({ body: "Monitor created successfully!" }); navigate("/uptime"); } else { createToast({ body: "Failed to create monitor." }); } }; const handleChange = (event, formName) => { const { value } = event.target; const newMonitor = { ...monitor, [formName]: value, }; if (formName === 'type') { newMonitor.url = ''; } setMonitor(newMonitor); const { error } = monitorValidation.validate( { type: monitor.type, [formName]: value }, { abortEarly: false } ); setErrors((prev) => ({ ...prev, url: undefined, ...(error ? { [formName]: error.details[0].message } : { [formName]: undefined }), })); }; const handleNotifications = (event, type) => { const { value } = event.target; let notifications = [...monitor.notifications]; const notificationExists = notifications.some((notification) => { if (notification.type === type && notification.address === value) { return true; } return false; }); if (notificationExists) { notifications = notifications.filter((notification) => { if (notification.type === type && notification.address === value) { return false; } return true; }); } else { notifications.push({ type, address: value }); } setMonitor((prev) => ({ ...prev, notifications, })); }; useEffect(() => { const fetchMonitor = async () => { if (monitorId) { const action = await dispatch(getUptimeMonitorById({ authToken, monitorId })); if (action.payload.success) { const data = action.payload.data; const { name, ...rest } = data; //data.name is read-only if (rest.type === "http") { const url = new URL(rest.url); rest.url = url.host; } rest.name = `${name} (Clone)`; rest.interval /= MS_PER_MINUTE; setMonitor({ ...rest, }); } else { navigate("/not-found", { replace: true }); createToast({ body: "There was an error cloning the monitor.", }); } } }; fetchMonitor(); }, [monitorId, authToken, dispatch, navigate]); return ( Create your{" "} monitor Checks to perform You can always add or remove checks after adding your site. handleChange(event, "type")} /> {monitor.type === "http" ? ( ) : ( "" )} handleChange(event, "type")} /> handleChange(event, "type")} /> handleChange(event, "type")} /> {errors["type"] ? ( {errors["type"]} ) : ( "" )} General settings Here you can select the URL of the host, together with the type of monitor. : null } label={monitorTypeMaps[monitor.type].label || "URL to monitor"} https={https} placeholder={monitorTypeMaps[monitor.type].placeholder || ""} value={monitor.url} onChange={(event) => handleChange(event, "url")} error={errors["url"] ? true : false} helperText={errors["url"]} /> handleChange(event, "port")} error={errors["port"] ? true : false} helperText={errors["port"]} hidden={monitor.type !== "port"} /> handleChange(event, "name")} error={errors["name"] ? true : false} helperText={errors["name"]} /> Incident notifications When there is an incident, notify users. notification.type === "email" )} value={user?.email} onChange={(event) => handleNotifications(event, "email")} /> Advanced settings