The weeb for the next gen discord boat - Wamellow wamellow.com
bot discord
at master 91 lines 2.5 kB view raw
1import { gt4init } from "@/lib/gt4"; 2import { useEffect, useRef, useState } from "react"; 3 4export enum State { 5 Idle = 0, 6 Loading = 1, 7 Success = 2 8} 9 10export function useCaptcha(path: string, userId?: string) { 11 const [state, setState] = useState<State>(State.Idle); 12 const [error, setError] = useState<string | null>(null); 13 14 const button = useRef<HTMLButtonElement | null>(null); 15 16 useEffect(() => { 17 if (!userId) return; 18 const { init } = gt4init(); 19 20 init( 21 { 22 captchaId: process.env.NEXT_PUBLIC_CAPTCHA_ID, 23 product: "bind", 24 hideSuccess: true, 25 userInfo: userId 26 }, 27 handlerForBind 28 ); 29 30 // @ts-expect-error GeeTest types suck 31 function handlerForBind(captcha) { 32 const btn = button.current; 33 let isReady = false; 34 35 captcha.onReady(() => { 36 isReady = true; 37 }); 38 39 btn?.addEventListener("click", () => { 40 if (!isReady || state === State.Success) return; 41 42 setState(State.Idle); 43 setError(null); 44 45 captcha.showCaptcha(); 46 }); 47 48 captcha.onSuccess(async () => { 49 setState(State.Loading); 50 51 const result = captcha.getValidate(); 52 const res = await fetch(process.env.NEXT_PUBLIC_API + path, { 53 method: "POST", 54 credentials: "include", 55 headers: { 56 "Content-Type": "application/json" 57 }, 58 body: JSON.stringify(result) 59 }) 60 .catch(() => null); 61 62 if (!res?.ok) { 63 captcha.destroy(); 64 setState(State.Idle); 65 66 const { message } = res 67 ? await res.json() 68 : { message: "Unknown server error" }; 69 70 setError(message); 71 return; 72 } 73 74 setState(State.Success); 75 }); 76 77 captcha.onError((err: string) => { 78 captcha.reset(); 79 setState(State.Idle); 80 setError(err || "Unknown captcha error"); 81 }); 82 83 captcha.onClose(() => { 84 captcha.reset(); 85 setState(State.Idle); 86 }); 87 } 88 }, [path, userId]); 89 90 return { state, error, button }; 91}