1import React, {createContext, useEffect, useState} from "react";
2import {useAlert} from "../Alert";
3import {request} from "@/common/utils/RequestUtil";
4import {apiErrorDialog, passwordRequiredDialog} from "@/common/contexts/Config/dialog";
5import WelcomeDialog from "@/common/components/WelcomeDialog";
6import {useNavigate} from "react-router-dom";
7
8export const ConfigContext = createContext({});
9
10export const ConfigProvider = (props) => {
11 const [config, setConfig] = useState({});
12 const alert = useAlert();
13 const [welcomeShown, setWelcomeShown] = useState(false);
14 const navigate = useNavigate();
15
16
17 const reloadConfig = () => {
18 request("/config").then(async res => {
19 if (res.status === 401) throw 1;
20 if (!res.ok) throw 2;
21
22 try {
23 return JSON.parse(await res.text());
24 } catch (e) {
25 throw 2;
26 }
27 }).then(result => {
28 if (config !== result)
29 result.viewMode && localStorage.getItem("currentNode") !== null && localStorage.getItem("currentNode") !== "0"
30 ? navigate("/nodes") : setConfig(result);
31 }).catch((code) => {
32 localStorage.getItem("currentNode") !== null && localStorage.getItem("currentNode") !== "0"
33 ? navigate("/nodes") : showErrorDialog(code);
34 });
35 }
36
37 const showErrorDialog = async (code) => {
38 const dialogConfig = code === 1 ? passwordRequiredDialog() : apiErrorDialog();
39
40 if (code === 1) {
41 const result = await alert.openInput(dialogConfig.title, {
42 placeholder: dialogConfig.placeholder,
43 description: dialogConfig.description,
44 inputType: dialogConfig.type,
45 buttonText: dialogConfig.buttonText,
46 disableClose: dialogConfig.disableCloseButton
47 });
48 if (result) dialogConfig.onSuccess(result);
49 } else {
50 await alert.openAlert(dialogConfig.title, dialogConfig.description, {
51 buttonText: dialogConfig.buttonText,
52 disableClose: dialogConfig.disableCloseButton
53 });
54 dialogConfig.onSuccess();
55 }
56 };
57
58 const checkConfig = async () => (await request("/config")).json();
59
60 useEffect(reloadConfig, []);
61
62 useEffect(() => {
63 if (config.previewMode && !localStorage.getItem("welcomeShown")) setWelcomeShown(true);
64 if (!config.previewMode && config.provider === "none") setWelcomeShown(true);
65 }, [config]);
66
67 return (
68 <ConfigContext.Provider value={[config, reloadConfig, checkConfig]}>
69 <WelcomeDialog open={welcomeShown} onClose={() => setWelcomeShown(false)}/>
70 {props.children}
71 </ConfigContext.Provider>
72 )
73}