Cofem/assets/script.js

499 lines
15 KiB
JavaScript
Raw Normal View History

2024-02-06 20:57:25 +01:00
let UserInfo = {};
2024-02-22 14:08:55 +01:00
let PageIntervals = [];
2024-02-07 18:31:01 +01:00
2024-02-07 18:41:15 +01:00
function isLoggedIn(){
2024-02-08 10:49:14 +01:00
return UserInfo.Email && UserInfo.Email.length > 0;
2024-02-07 18:41:15 +01:00
}
2024-02-06 20:53:57 +01:00
async function handleResponse(data, successMessage, failureMessage) {
2024-02-06 19:33:25 +01:00
const statusMessageContainer = document.getElementById("statusMessageContainer");
const statusMessage = document.createElement("div");
statusMessage.classList.add("status-message");
if (data.Status === 'Success') {
statusMessage.innerText = successMessage;
statusMessage.classList.add("success");
} else {
statusMessage.innerText = failureMessage;
statusMessage.classList.add("failure");
}
statusMessageContainer.appendChild(statusMessage);
// Automatically remove the message after 3 seconds
setTimeout(() => {
statusMessage.style.opacity = "0";
setTimeout(() => {
statusMessage.remove();
}, 500);
2024-02-06 21:11:37 +01:00
}, 2000);
2024-02-06 19:33:25 +01:00
}
2024-02-06 20:00:32 +01:00
async function showDashboardGreeting() {
2024-02-06 20:59:03 +01:00
document.getElementById("welcomeMsg").innerText = `Ahoj, ${UserInfo.FirstName}.`;
2024-02-06 20:00:32 +01:00
}
2024-02-06 16:24:57 +01:00
async function doAction(url, requestData, successMessage, failureMessage, silent = false) {
try {
const params = new URLSearchParams();
2024-02-05 22:15:10 +01:00
2024-02-06 16:24:57 +01:00
for (const key in requestData) {
params.append(key, requestData[key]);
}
const response = await fetch(url, {
method: 'POST',
body: params,
2024-02-03 16:08:26 +01:00
});
2024-02-06 16:24:57 +01:00
if (!response.ok) {
2024-02-06 20:19:36 +01:00
console.error(`HTTP error! Status: ${response.status}`);
2024-02-06 16:24:57 +01:00
}
2024-02-05 21:21:04 +01:00
2024-02-06 16:24:57 +01:00
const data = await response.json();
2024-02-05 21:21:04 +01:00
2024-02-06 16:24:57 +01:00
if (!silent) {
2024-02-06 20:19:36 +01:00
await handleResponse(data, successMessage, failureMessage);
2024-02-06 16:24:57 +01:00
}
return data;
} catch (error) {
console.error('Error:', error);
2024-02-05 21:21:04 +01:00
}
}
2024-02-06 20:19:36 +01:00
async function handlePageResponse(data) {
2024-02-06 20:00:32 +01:00
const navbar = document.getElementById("navbar_container");
const pageArea = document.getElementById("page_container");
2024-02-06 16:24:57 +01:00
if (data.Navigation) {
navbar.innerHTML = data.Navigation;
}
if (data.Page) {
pageArea.innerHTML = data.Page;
2024-02-07 18:31:01 +01:00
if (data.PageLocation) {
2024-02-06 16:38:23 +01:00
history.pushState({}, "", data.PageLocation);
}
2024-02-06 16:24:57 +01:00
}
2024-02-05 21:21:04 +01:00
}
2024-02-06 20:19:36 +01:00
async function displayList(data, elementId, deleteFunction) {
2024-02-06 16:24:57 +01:00
const tableContainer = document.getElementById(elementId);
2024-02-04 09:50:04 +01:00
tableContainer.innerHTML = ""; // Clear previous content
const table = document.createElement("table");
table.classList.add("list-table");
const headerRow = table.insertRow(0);
for (const key in data[0]) {
const th = document.createElement("th");
th.appendChild(document.createTextNode(key));
headerRow.appendChild(th);
}
2024-02-06 16:24:57 +01:00
if (typeof deleteFunction === "function") {
2024-02-04 09:50:04 +01:00
const th = document.createElement("th");
th.appendChild(document.createTextNode("Delete"));
headerRow.appendChild(th);
}
for (const line of data) {
const dataRow = table.insertRow();
for (const key in line) {
const td = document.createElement("td");
td.appendChild(document.createTextNode(line[key]));
dataRow.appendChild(td);
}
2024-02-06 16:24:57 +01:00
if (typeof deleteFunction === "function") {
2024-02-04 09:50:04 +01:00
const td = document.createElement("td");
2024-02-06 16:24:57 +01:00
const deleteButton = document.createElement('button');
deleteButton.textContent = "Delete";
deleteButton.onclick = () => deleteFunction(line.ID);
td.appendChild(deleteButton);
2024-02-04 09:50:04 +01:00
dataRow.appendChild(td);
}
}
tableContainer.appendChild(table);
}
2024-02-06 16:24:57 +01:00
async function doPageAction(requestData, wantsReturn = false) {
try {
const response = await fetch('/page', {
method: 'POST',
body: new URLSearchParams(requestData),
});
2024-02-05 21:21:04 +01:00
2024-02-06 16:24:57 +01:00
if (!response.ok) {
2024-02-06 20:19:36 +01:00
console.error(`HTTP error! Status: ${response.status}`);
2024-02-06 16:24:57 +01:00
}
2024-02-03 16:08:26 +01:00
2024-02-06 16:37:23 +01:00
const data = await response.json();
2024-02-06 20:19:36 +01:00
await handlePageResponse(data);
2024-02-06 16:24:57 +01:00
if (wantsReturn) {
2024-02-06 16:37:23 +01:00
return data;
2024-02-06 16:24:57 +01:00
}
} catch (error) {
console.error('Error:', error);
}
2024-02-03 16:08:26 +01:00
}
2024-02-07 18:31:01 +01:00
async function initAjaxNavigationEvents() {
2024-02-07 18:17:38 +01:00
const allLinks = document.querySelectorAll('.navsite_link, .navpage_link');
const pageLinks = document.querySelectorAll('.navpage_link');
pageLinks.forEach(function (link) {
link.addEventListener('click', function () {
navLinks.classList.remove("active");
});
});
2024-02-05 21:21:04 +01:00
2024-02-07 18:17:38 +01:00
allLinks.forEach(function (link) {
2024-02-05 21:23:21 +01:00
link.addEventListener('click', function (e) {
e.preventDefault();
2024-02-05 21:25:41 +01:00
let site = this.dataset.site;
let page = this.dataset.page;
2024-02-05 21:23:21 +01:00
if (site && page) {
navigateTo(site, page);
}
});
2024-02-05 21:21:04 +01:00
});
2024-02-06 20:58:14 +01:00
const toggleButton = document.getElementById("toggle_button")
const navLinks = document.getElementById("navsite_list")
toggleButton.addEventListener('click', () => {
navLinks.classList.toggle("active")
})
2024-02-07 18:17:38 +01:00
}
async function initAjax() {
await initAjaxNavigationEvents();
2024-02-06 20:19:36 +01:00
await onPageLoad();
2024-02-05 21:23:21 +01:00
}
2024-02-05 22:22:52 +01:00
2024-02-22 10:43:18 +01:00
async function togglearticlecreate(){
let articleContainerElement = document.getElementById("articlecreatecontainer");
articleContainerElement.classList.toggle("hidden");
}
2024-02-22 14:08:55 +01:00
async function renderarticles(){
let template = document.querySelector('template[data-template-name="article"]').content.toString();
let articles = await doAction(
"/newsarticle",
{
action: "getNewsArticles"
},
"Články načítané",
"Nastala chyba pri načítavaní článkov",
true
);
2024-02-22 13:57:05 +01:00
2024-02-22 14:08:55 +01:00
let articleout = "";
for (const article of articles) {
articleout += template.replace("__TEMPLATE_ARTICLE_TITLE__", article.Title).replace("__TEMPLATE_ARTICLE_AUTHOR__", article.WrittenByName).replace("__TEMPLATE_ARTICLE_DATE__", article.WrittenAt).replace("__TEMPLATE_ARTICLE_BODY__", article.Body)
}
document.getElementById("articleslist").innerHTML = articleout;
2024-02-22 13:57:05 +01:00
}
2024-02-22 10:43:18 +01:00
async function submitarticle(){
let articleTitleElement = document.getElementById("articletitleinput");
let articleBodyElement = document.getElementById("articlebodyinput");
2024-02-22 13:57:05 +01:00
await doAction(
"/newsarticle",
{
action: "addNewsArticle",
title: articleTitleElement.value,
body: articleBodyElement.value
},
"Článok úspešne pridaný",
2024-02-22 12:28:16 +01:00
"Nastala chyba pri pridávaní článku",
2024-02-22 13:57:05 +01:00
false
);
2024-02-22 14:09:14 +01:00
togglearticlecreate();
2024-02-22 10:43:18 +01:00
}
async function articleInit(){
2024-02-22 12:19:57 +01:00
let articleContainerElement = document.getElementById("articlecreatecontainer");
articleContainerElement.addEventListener("keyup", function (ev) {
if(ev.which === 27){
togglearticlecreate();
}
})
2024-02-22 14:08:55 +01:00
PageIntervals.push(setInterval(renderarticles, 300000));
2024-02-22 10:43:18 +01:00
}
2024-02-07 18:31:01 +01:00
async function onPageLoad() {
2024-02-06 20:46:31 +01:00
await restoreUserInfo();
2024-02-05 22:52:44 +01:00
let currentSite = localStorage.getItem("currentSite");
let currentPage = localStorage.getItem("currentPage");
2024-02-22 14:08:55 +01:00
for(let interval of PageIntervals) {
clearInterval(interval);
}
2024-02-07 18:31:01 +01:00
if (currentSite === "home" && currentPage === "settings") {
if (document.getElementById("user-settings")) {
2024-02-06 20:19:36 +01:00
await populateUserInfoFields(UserInfo);
2024-02-05 22:52:44 +01:00
}
2024-02-07 18:31:01 +01:00
if (document.getElementById("admin-settings")) {
2024-02-06 21:09:33 +01:00
await listActivationCodes(true);
await listUsers(true);
2024-02-05 22:52:44 +01:00
}
}
2024-02-07 18:41:15 +01:00
if (currentSite === "home" && currentPage === "account" && isLoggedIn()) {
2024-02-06 20:19:36 +01:00
await showDashboardGreeting();
2024-02-06 20:00:32 +01:00
}
2024-02-22 10:43:18 +01:00
if (currentSite === "news" && currentPage === "index" && isLoggedIn()) {
await articleInit();
}
2024-02-05 22:52:44 +01:00
}
2024-02-07 18:31:01 +01:00
async function navigateTo(site, page) {
2024-02-06 16:24:57 +01:00
const data = {
action: "getPage",
site: site,
page: page,
};
2024-02-06 16:47:51 +01:00
doPageAction(data, true).then(() => {
2024-02-06 16:24:57 +01:00
localStorage.setItem("currentSite", site);
localStorage.setItem("currentPage", page);
onPageLoad();
2024-02-06 16:47:51 +01:00
});
2024-02-06 16:24:57 +01:00
}
2024-02-07 18:31:01 +01:00
async function softReload() {
2024-02-06 17:04:56 +01:00
let currentSite = localStorage.getItem("currentSite");
let currentPage = localStorage.getItem("currentPage");
2024-02-06 20:19:36 +01:00
await navigateTo(currentSite, currentPage);
2024-02-06 17:04:56 +01:00
umami.track("softReload");
2024-02-06 16:24:57 +01:00
}
2024-02-07 18:31:01 +01:00
async function refreshNavbar() {
2024-02-06 16:24:57 +01:00
const data = {
action: "getNavigation",
};
2024-02-06 20:19:36 +01:00
await doPageAction(data);
2024-02-06 17:04:56 +01:00
umami.track("refreshNavbar");
2024-02-07 18:43:04 +01:00
await initAjaxNavigationEvents();
2024-02-06 16:24:57 +01:00
}
2024-02-06 20:19:36 +01:00
async function logout() {
2024-02-06 16:24:57 +01:00
const data = {
action: "logout",
};
2024-02-06 20:19:36 +01:00
doAction('/account', data, "Logout Successful!", "Logout failed.")
.then(async () => {
await refreshNavbar();
await navigateTo(localStorage.getItem("defaultSite"), localStorage.getItem("defaultPage"));
2024-02-06 20:48:30 +01:00
localStorage.clear();
2024-02-06 20:19:36 +01:00
umami.track("logout");
})
.catch((error) => {
// Handle errors if needed
console.error("An error occurred during logout:", error);
});
2024-02-06 16:24:57 +01:00
}
2024-02-05 22:22:52 +01:00
2024-02-06 20:19:36 +01:00
async function login() {
2024-02-05 22:22:52 +01:00
const email = document.getElementById("login_email").value;
const password = document.getElementById("login_password").value;
2024-02-06 20:19:36 +01:00
await doLogin(email, password);
await getUserInfo();
await refreshNavbar();
await softReload();
2024-02-05 22:22:52 +01:00
}
2024-02-06 16:24:57 +01:00
async function doLogin(email, password) {
const data = {
action: "login",
email: email,
password: password,
};
2024-02-05 22:22:52 +01:00
2024-02-06 16:24:57 +01:00
await doAction('/account', data, "Login Successful!", "Login failed. Please check your credentials.");
2024-02-06 17:04:56 +01:00
umami.track("login");
2024-02-05 22:22:52 +01:00
}
2024-02-06 20:19:36 +01:00
async function register() {
2024-02-05 22:22:52 +01:00
const firstName = document.getElementById("register_firstName").value;
const lastName = document.getElementById("register_lastName").value;
const email = document.getElementById("register_email").value;
const password = document.getElementById("register_password").value;
const activationToken = document.getElementById("register_activationToken").value;
2024-02-06 16:24:57 +01:00
const data = {
action: "register",
firstname: firstName,
lastname: lastName,
email: email,
password: password,
activation_token: activationToken,
};
2024-02-05 22:22:52 +01:00
2024-02-06 20:19:36 +01:00
await doRegister(data);
2024-02-05 22:22:52 +01:00
}
2024-02-06 16:24:57 +01:00
async function doRegister(requestData) {
await doAction('/account', requestData, "Registration Successful!", "Registration failed.");
2024-02-06 17:04:56 +01:00
umami.track("register");
2024-02-05 22:22:52 +01:00
}
//User settings start
2024-02-06 20:19:36 +01:00
async function changePassword() {
2024-02-05 22:22:52 +01:00
const oldPassword = document.getElementById("changeOldPassword").value;
const newPassword = document.getElementById("changeNewPassword").value;
2024-02-06 16:24:57 +01:00
const data = {
action: "change_password",
old_password: oldPassword,
new_password: newPassword,
};
2024-02-05 22:22:52 +01:00
2024-02-06 20:19:36 +01:00
await doChangePassword(data, "Password change Successful!", "Password change failed.");
2024-02-05 22:22:52 +01:00
}
2024-02-06 16:24:57 +01:00
async function doChangePassword(requestData, successMessage, failureMessage) {
await doAction('/account', requestData, successMessage, failureMessage);
2024-02-06 17:04:56 +01:00
umami.track("passwordChange");
2024-02-05 22:22:52 +01:00
}
2024-02-06 20:19:36 +01:00
async function updateUserProfile() {
2024-02-05 22:22:52 +01:00
const firstName = document.getElementById("updateFirstName").value;
const lastName = document.getElementById("updateLastName").value;
const nickname = document.getElementById("updateNickname").value;
const minecraftNick = document.getElementById("updateMinecraftNick").value;
2024-02-06 16:24:57 +01:00
const data = {
action: "update_user_profile",
first_name: firstName,
last_name: lastName,
nickname: nickname,
minecraft_nick: minecraftNick,
};
2024-02-05 22:22:52 +01:00
2024-02-06 20:19:36 +01:00
await doAction('/account', data, "Profile update Successful!", "Profile update failed.");
2024-02-06 17:04:56 +01:00
umami.track("updateUserProfile");
2024-02-05 22:22:52 +01:00
}
2024-02-06 20:19:36 +01:00
async function updateEmail() {
2024-02-05 22:22:52 +01:00
const newEmail = document.getElementById("updateNewEmail").value;
2024-02-06 16:24:57 +01:00
const data = {
action: "update_user_email",
email: newEmail,
};
2024-02-05 22:22:52 +01:00
2024-02-06 20:19:36 +01:00
await doAction('/account', data, "Email update Successful!", "Email update failed.");
2024-02-06 17:04:56 +01:00
umami.track("updateEmail");
2024-02-05 22:22:52 +01:00
}
2024-02-06 20:19:36 +01:00
async function populateUserInfoFields(userData) {
2024-02-05 22:22:52 +01:00
document.getElementById("updateFirstName").value = userData.FirstName || "";
document.getElementById("updateLastName").value = userData.LastName || "";
document.getElementById("updateNickname").value = userData.Nickname || "";
document.getElementById("updateMinecraftNick").value = userData.MinecraftNick || "";
document.getElementById("updateNewEmail").value = userData.Email || "";
}
2024-02-07 18:31:01 +01:00
async function restoreUserInfo() {
2024-02-06 20:46:31 +01:00
for (let i = 0; i < localStorage.length; i++) {
let key = localStorage.key(i);
2024-02-07 18:31:01 +01:00
if (key.startsWith("UserInfo_")) {
2024-02-06 20:46:31 +01:00
let keyClean = key.replace("UserInfo_", "");
UserInfo[keyClean] = localStorage.getItem(key);
}
}
}
2024-02-06 20:19:36 +01:00
async function getUserInfo() {
2024-02-06 16:24:57 +01:00
const data = {
action: "get_user_info",
};
2024-02-07 18:31:01 +01:00
const result = await doAction('/account', data, "User info retrieved Successfully!", "User info retrieval failed.", true);
if (result && result.Status === "Success") {
2024-02-07 18:38:36 +01:00
Object.keys(result.UserInfo).forEach(index => {
let value = result.UserInfo[index];
2024-02-07 18:31:01 +01:00
localStorage.setItem("UserInfo_" + index, value);
UserInfo[index] = value;
});
}
2024-02-05 22:22:52 +01:00
}
//User settings end
//Admin settings start
2024-02-06 20:19:36 +01:00
async function addActivationCodes() {
2024-02-05 22:22:52 +01:00
const count = document.getElementById("activationCodeCount").value;
2024-02-06 16:24:57 +01:00
const data = {
action: "add_activation_codes",
count: count,
};
2024-02-05 22:22:52 +01:00
2024-02-06 20:10:06 +01:00
doAction('/account', data, "Activation codes added Successfully!", "Activation codes addition failed.").then((result) => {
displayList(result.ActivationCodes, "codeListTable", deleteActivationCode);
umami.track("addActivationCodes");
});
2024-02-05 22:22:52 +01:00
}
2024-02-07 18:31:01 +01:00
async function listUsers(silent = false) {
2024-02-06 16:24:57 +01:00
const data = {
action: "list_users",
};
2024-02-05 22:22:52 +01:00
2024-02-06 21:09:33 +01:00
doAction('/account', data, "User list retrieved Successfully!", "User list retrieval failed.", silent).then((result) => {
2024-02-05 22:22:52 +01:00
2024-02-06 20:10:06 +01:00
if (result && result.Status === "Success") {
displayList(result.Users, "userListTable", deleteUser);
}
});
2024-02-05 22:22:52 +01:00
}
2024-02-07 18:31:01 +01:00
async function listActivationCodes(silent = false) {
2024-02-06 16:24:57 +01:00
const data = {
action: "list_activation_codes",
};
2024-02-05 22:22:52 +01:00
2024-02-06 21:09:33 +01:00
doAction('/account', data, "Activation code list retrieved Successfully!", "Activation code list retrieval failed.", silent).then((result) => {
2024-02-06 20:10:06 +01:00
displayList(result.ActivationCodes, "codeListTable", deleteActivationCode);
});
2024-02-05 22:22:52 +01:00
}
2024-02-06 20:19:36 +01:00
async function deleteUser(userId) {
2024-02-06 16:24:57 +01:00
const data = {
action: "delete_user",
user_id: userId,
};
2024-02-05 22:22:52 +01:00
2024-02-06 20:19:36 +01:00
await doAction('/account', data, "User deleted Successfully!", "User deletion failed.");
await listUsers();
2024-02-06 17:04:56 +01:00
umami.track("deleteUser");
2024-02-05 22:22:52 +01:00
}
2024-02-06 20:19:36 +01:00
async function deleteActivationCode(activationCode) {
2024-02-06 16:24:57 +01:00
const data = {
action: "delete_activation_code",
activation_code: activationCode,
};
2024-02-05 22:22:52 +01:00
2024-02-06 20:19:36 +01:00
await doAction('/account', data, "Activation code deleted Successfully!", "Activation code deletion failed.");
await listActivationCodes();
2024-02-06 17:04:56 +01:00
umami.track("deleteActivationCode");
2024-02-05 22:22:52 +01:00
}
2024-02-07 18:31:01 +01:00
2024-02-05 22:22:52 +01:00
//Admin settings end
2024-02-07 18:13:24 +01:00
if (document.readyState !== "loading") {
setTimeout(initAjax, 0);
} else {
document.addEventListener("DOMContentLoaded", initAjax);
}