"use client"; import React, { useState, useRef, useEffect } from "react"; import { useMutation, useQuery, RefetchOptions, useQueryClient, } from "@tanstack/react-query"; import { GenerateKeyPair, GetKeys, AddKey, ChangeKey } from "@/utils/adminApi"; import { FaRegEdit } from "react-icons/fa"; import { IoMdClose } from "react-icons/io"; import { useRouter } from "next/navigation"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, } from "@/components/ui/alert-dialog"; import { Button } from "@/components/ui/button"; import { ThreeDots } from "react-loader-spinner"; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { toast } from "sonner"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; import * as z from "zod"; import { Textarea } from "./ui/textarea"; import { Check, KeyRound } from "lucide-react"; import { Progress } from "./ui/progress"; import { cn } from "@/lib/utils"; const MAX_FILE_SIZE = 5242880; // 5 MB // Edit Key Form const FormSchemaEditKey = z.object({ uploadPrivateKey: z.any(), // .instanceof(File) // .custom((val) => val instanceof FileList, "Required") // .refine((files) => files.length <= 1, "Maximum of 1 file is allowed.") // .refine( // (files) => // Array.from(files).every((file) => file.size <= MAX_IMAGE_SIZE), // "Each file size should be less than 5 MB." // ), // .refine((files) => files?.length === 0, "File is required.") // .refine((files) => files?.length >= 1, "Maximum of 1 file is allowed.") // .refine((files) => files?.[0]?.size <= MAX_FILE_SIZE, `Max file size is 5MB.`) // publicKeyId: z // .string() // .nullable(), }); // Add Key Form const FormSchemaAddKey = z.object({ title: z.string().min(2, { message: "عنوان کلید را وارد کنید", }), publicKey: z.string().min(4, { message: "کلید عمومی را وارد کنید", }), }); export default function AdminKeysManagement() { const router = useRouter(); const queryClient = useQueryClient(); const [keyId, setKeyId] = useState(""); const [done, setDone] = useState(0); const [total, setTotal] = useState(0); const [polling, setPolling] = useState(false); const [openAdd, setOpenAdd] = React.useState(false); const [openEdit, setOpenEdit] = React.useState(false); const inputPubRef = useRef(null); const inputPrvRef = useRef(null); const intervalRef = useRef(null); // ..............Read .txt const [selectedFile, setSelectedFile] = useState(null); const handleFileChange = (event: any) => { const file = event.target.files[0]; const reader = new FileReader(); reader.onload = (e) => { const contents = e?.target?.result; // Process the contents of the file here setSelectedFile(contents); }; reader?.readAsText(file); }; // Edit Form const formEdit = useForm>({ resolver: zodResolver(FormSchemaEditKey), defaultValues: { // publicKeyId: "", // uploadFile: null, }, }); // ............'Mutation' Change Key Submit const ChangeKeyMutation = useMutation({ mutationKey: ["ChangeKey"], mutationFn: ChangeKey, onSuccess: (res) => { if (res.total == res.done) { localStorage.removeItem("isChangingKey"); setPolling(false); queryClient.invalidateQueries({ queryKey: ["KeysList"] }); if (res.failed == 0) { refetch1(); toast("عملیات شما با موفقیت انجام شد. ", { className: "!bg-green-500 !text-white", }); } else if (res.failed > 0) { toast("مشکلی در تغییر کلید به وجود آمد.", { className: "!bg-red-500 !text-white", }); } if (intervalRef.current !== null) { clearInterval(intervalRef.current); intervalRef.current = null; // Reset the ref value after clearing } } else { localStorage.setItem("isChangingKey", "true"); setPolling(true); } setOpenEdit(false); setDone(res.done); setTotal(res.total); // router.refresh() }, onError: (err: any | string) => { toast(<>{err.response.data.detail}, { className: "!bg-red-500 !text-white", }); }, }); function onSubmitEdit(data: z.infer) { ChangeKeyMutation.mutate({ privateKey: selectedFile, publicKeyId: keyId, isPolling: false, }); } // Add Form const formAdd = useForm>({ resolver: zodResolver(FormSchemaAddKey), defaultValues: { title: "", publicKey: "", }, }); // ............'Mutation' Add Key Submit const AddKeyMutation = useMutation({ mutationKey: ["AddKey"], mutationFn: AddKey, onSuccess: (res) => { setOpenAdd(false); refetch1(); formAdd.reset(); if (inputPubRef.current && inputPrvRef.current) { inputPrvRef.current.value = ""; inputPubRef.current.value = ""; } toast("عملیات شما با موفقیت انجام شد. ", { className: "!bg-green-500 !text-white", }); // inputPubRef.current.clear(); // router.refresh() }, onError: (err: any | string) => { toast(<>{err.response.data.detail}, { className: "!bg-red-500 !text-white", }); }, }); function onSubmitAdd(data: z.infer) { AddKeyMutation.mutate({ title: data.title, publicKey: data.publicKey, }); } // const { resetField } = useForm(); // List Keys const { data: data1, error: Error1, isLoading: isListLoading, refetch: refetch1, isSuccess: isSuccess1, } = useQuery({ queryKey: ["KeysList"], queryFn: () => GetKeys(), // refetchOnWindowFocus: false, }); // GenerateKeyPair const { data: data2, error: Error2, isLoading: isNewKeyLoading, refetch: refetch2, isSuccess: isSuccess2, } = useQuery({ queryKey: ["GenerateKey"], queryFn: () => GenerateKeyPair(), enabled: false, // Disable automatic fetching }); // Define the type for refetch2 // type RefetchFunction = (options?: RefetchOptions) => Promise; const handleClickGenerate = () => { refetch2(); }; useEffect(() => { if (isSuccess2) { formAdd.setValue("publicKey", data2?.publicKey); } }, [isSuccess2]); useEffect(() => { if (inputPubRef.current && inputPrvRef.current) { inputPubRef.current.value = data2?.publicKey ?? ""; inputPrvRef.current.value = data2?.privateKey ?? ""; } }, [handleClickGenerate]); // useEffect(() => { // const isChangingKey = localStorage.getItem("isChangingKey"); // if (isChangingKey) { // setPolling(true); // ChangeKeyMutation.mutate({ // privateKey: "", // publicKeyId: "cb7258da-64b0-4f43-b4f7-8ee11799d643", // isPolling: true, // }); // } // }, [polling]); const refethKey = () => { ChangeKeyMutation.mutate({ privateKey: "", publicKeyId: "cb7258da-64b0-4f43-b4f7-8ee11799d643", isPolling: true, }); }; useEffect(() => { const isChangingKey = localStorage.getItem("isChangingKey"); if (isChangingKey) { setTimeout(() => {}, 10000); intervalRef.current = setInterval(refethKey, 10000); return () => { if (intervalRef.current !== null) { clearInterval(intervalRef.current); intervalRef.current = null; // Reset the ref value after clearing } }; } }, [polling]); const saveTextFile = () => { const textToSave = data2?.privateKey ?? ""; const fileName = "privateKey.txt"; // Create a Blob containing the file data const blob = new Blob([textToSave], { type: "text/plain" }); // Create a link element const link = document.createElement("a"); // Set the download attribute and create a URL for the Blob link.download = fileName; link.href = window.URL.createObjectURL(blob); // Append the link to the document and trigger the click event document.body.appendChild(link); link.click(); // Remove the link from the document document.body.removeChild(link); }; useEffect(() => { if (AddKeyMutation.isSuccess) { saveTextFile(); } }, [AddKeyMutation.isSuccess]); const resetFormAdd = () => { formAdd.reset({ title: "", publicKey: "", }); }; return (
{polling && (

درحال تغییر کلید({Math.floor((done * 100) / total)}%) ...

)} {/* 1 */}

افزودن کلید جدید

{ resetFormAdd(); }} >
افزودن کلید جدید
( عنوان کلید )} /> ( کلید خصوصی