PaperParser/app/blueprints/frontend/static/add.js

115 lines
3.2 KiB
JavaScript

const API_URL = window.location.origin;
const nameInput = document.querySelector("#input-name");
const phoneInput = document.querySelector("#input-phone");
const addSessionForm = document.querySelector("#add-session-form");
const openFileButton = document.querySelector("#open-file-btn");
const secretCodeModal = new bootstrap.Modal('#secretCodeModal');
const secretCodeForm = document.querySelector("#secret-code-form");
const secretCodeInput = document.querySelector("#input-secret-code");
const passwordModal = new bootstrap.Modal('#passwordModal');
const passwordForm = document.querySelector("#password-form");
const passwordInput = document.querySelector("#input-password");
let phoneHash = "";
const handleCreation = async (e) => {
e.preventDefault();
if (phoneInput.value == "" || nameInput.value == "") {
alert("Пожалуйста, заполните все поля.");
return;
}
const data = getAuthData();
res = await fetch(`${API_URL}/api/sessions/`, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
}
});
result = await res.json();
switch(result.status) {
case "ok":
window.location = "/";
break;
case "error":
handleError(result);
break;
case "exception":
alert(`Ошибка: ${result.message}.`);
break;
default:
alert(`Неизвестная ошибка. Проверьте логи`);
}
}
const getAuthData = () => {
const inputFields = [passwordInput, secretCodeInput, nameInput, phoneInput]
data = {}
inputFields.forEach((el) => {
if (el.value !== "") {
data[el.attributes.name.value] = el.value.replace(/ /g, '');
}
})
if (phoneHash !== "")
data["phone_hash"] = phoneHash;
return data;
}
const handleRequest = async (fn) => {
}
const handleError = (result) => {
switch(result.action) {
case "code":
phoneHash = result.phone_hash;
secretCodeModal.show();
break;
case "password":
passwordModal.show();
break;
}
}
addSessionForm.addEventListener("submit", handleCreation);
secretCodeForm.addEventListener("submit", handleCreation);
passwordForm.addEventListener("submit", handleCreation);
// openFileButton.addEventListener("click", handleOpening);
function handleOpening() {
let input = document.createElement('input');
input.type = 'file';
input.accept = ".zip";
input.onchange = async () => {
// you can use this method to get file and perform respective operations
let archive = Array.from(input.files)[0];
let formData = new FormData();
formData.append("archive", archive);
response = await fetch(`${API_URL}/api/save_session_file.php`, { method: "POST", body: formData });
if (response.status == "201") {
window.location = "/"
} else {
const error_text = await response.text();
const error_status = await response.status;
alert(`${error_status}: ${error_text}`);
}
};
input.click();
}