1
0
dwelling-home/web/assets/js/captcha_refresh.js

41 lines
1.7 KiB
JavaScript
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const g_captcha_timeout_seconds = 600;
const e_captcha = document.getElementsByClassName("captcha")[0];
let g_captcha_timeout_remain = g_captcha_timeout_seconds;
let g_current_captcha_id = e_captcha.children[0].value;
async function getNewCaptcha() {
const id = await fetch("/api/captcha/", { method: "POST"}).then(r => r.text());
g_current_captcha_id = e_captcha.children[0].value = id;
const style = window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark";
setTimeout(() => { e_captcha.children[1].src = `/api/captcha/${id}/image?style=${style}` }, 600);
g_captcha_timeout_remain = g_captcha_timeout_seconds;
}
e_captcha.children[3].innerHTML = document.cookie.includes("lang=ru") ?
`<button id="refresh">Обновит</button>ся через <b><span id="remain">600</span></b> секунд(у).`
: `<button id="refresh">Refresh</button>ed in <b><span id="remain">600</span></b> seconds.`;
const captcha_refresh = document.getElementById("refresh");
const captcha_remain = document.getElementById("remain");
captcha_refresh.classList.toggle("refresh");
captcha_refresh.addEventListener("click", async e => {
e.preventDefault();
e.target.disabled = true;
setTimeout(async () => {
e.target.disabled = false;
await fetch(`/api/captcha/${g_current_captcha_id}?remove`, { method: "POST"}); }, 3000);
e_captcha.children[2].value = "";
await getNewCaptcha();
});
// Remove unused CAPTCHA on a server.
window.addEventListener("unload", () => fetch(`/api/captcha/${g_current_captcha_id}?remove`, { method: "POST"}));
setInterval(async () => {
captcha_remain.innerText = --g_captcha_timeout_remain;
if (g_captcha_timeout_remain == 0)
await getNewCaptcha();
}, 1000);