add js linting, fix js linting issues

This commit is contained in:
Arthur Lu 2023-06-29 22:20:15 +00:00
parent 6ce1cc332a
commit e66d3ceb33
9 changed files with 1643 additions and 1568 deletions

42
.eslintrc.json Normal file
View File

@ -0,0 +1,42 @@
{
"env": {
"browser": true,
"es2021": true
},
"extends": "standard",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"rules": {
"no-tabs": [
"error",
{
"allowIndentationTabs": true
}
],
"indent": [
"error",
"tab"
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"double"
],
"semi": [
"error",
"always"
],
"brace-style": [
"error",
"stroustrup",
{
"allowSingleLine": false
}
]
}
}

2
.gitignore vendored
View File

@ -1 +1,3 @@
vars.js vars.js
**/package-lock.json
**/node_modules

16
package.json Normal file
View File

@ -0,0 +1,16 @@
{
"name": "proxmoxaas-client",
"version": "0.0.1",
"description": "Front-end for ProxmoxAAS",
"type": "module",
"scripts": {
"lint": "eslint --fix ."
},
"devDependencies": {
"eslint": "^8.43.0",
"eslint-config-standard": "^17.1.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-n": "^16.0.1",
"eslint-plugin-promise": "^6.1.1"
}
}

View File

@ -2,7 +2,7 @@ import { requestAPI, goToPage, getCookie, setTitleAndHeader } from "./utils.js";
window.addEventListener("DOMContentLoaded", init); window.addEventListener("DOMContentLoaded", init);
let prefixes = { const prefixes = {
1024: [ 1024: [
"", "",
"Ki", "Ki",
@ -17,17 +17,17 @@ let prefixes = {
"G", "G",
"T" "T"
] ]
} };
async function init() { async function init () {
setTitleAndHeader(); setTitleAndHeader();
let cookie = document.cookie; const cookie = document.cookie;
if (cookie === "") { if (cookie === "") {
goToPage("login.html"); goToPage("login.html");
} }
let resources = await requestAPI("/user/resources"); const resources = await requestAPI("/user/resources");
let instances = await requestAPI("/user/config/cluster"); const instances = await requestAPI("/user/config/cluster");
let nodes = await requestAPI("/user/config/nodes"); const nodes = await requestAPI("/user/config/nodes");
document.querySelector("#username").innerText = `Username: ${getCookie("username")}`; document.querySelector("#username").innerText = `Username: ${getCookie("username")}`;
document.querySelector("#pool").innerText = `Pool: ${instances.pool}`; document.querySelector("#pool").innerText = `Pool: ${instances.pool}`;
document.querySelector("#vmid").innerText = `VMID Range: ${instances.vmid.min} - ${instances.vmid.max}`; document.querySelector("#vmid").innerText = `VMID Range: ${instances.vmid.min} - ${instances.vmid.max}`;
@ -35,24 +35,25 @@ async function init() {
buildResourceTable(resources, "#resource-table"); buildResourceTable(resources, "#resource-table");
} }
function buildResourceTable(resources, tableid) { function buildResourceTable (resources, tableid) {
if (resources instanceof Object) { if (resources instanceof Object) {
let table = document.querySelector(tableid); const table = document.querySelector(tableid);
let tbody = table.querySelector("tbody"); const tbody = table.querySelector("tbody");
Object.keys(resources.resources).forEach((element) => { Object.keys(resources.resources).forEach((element) => {
if (resources.resources[element].display) { if (resources.resources[element].display) {
if (resources.resources[element].type === "list") { if (resources.resources[element].type === "list") {
// TODO
console.error("Unimplemented");
} }
else { else {
let row = tbody.insertRow(); const row = tbody.insertRow();
let key = row.insertCell(); const key = row.insertCell();
key.innerText = `${element}`; key.innerText = `${element}`;
let used = row.insertCell(); const used = row.insertCell();
used.innerText = `${parseNumber(resources.used[element], resources.resources[element])}`; used.innerText = `${parseNumber(resources.used[element], resources.resources[element])}`;
let val = row.insertCell(); const val = row.insertCell();
val.innerText = `${parseNumber(resources.avail[element], resources.resources[element])}`; val.innerText = `${parseNumber(resources.avail[element], resources.resources[element])}`;
let total = row.insertCell(); const total = row.insertCell();
total.innerText = `${parseNumber(resources.max[element], resources.resources[element])}`; total.innerText = `${parseNumber(resources.max[element], resources.resources[element])}`;
} }
} }
@ -60,20 +61,20 @@ function buildResourceTable(resources, tableid) {
} }
} }
function parseNumber(value, unitData) { function parseNumber (value, unitData) {
let compact = unitData.compact; const compact = unitData.compact;
let multiplier = unitData.multiplier; const multiplier = unitData.multiplier;
let base = unitData.base; const base = unitData.base;
let unit = unitData.unit; const unit = unitData.unit;
value = multiplier * value; value = multiplier * value;
if (value <= 0) { if (value <= 0) {
return `0 ${unit}`; return `0 ${unit}`;
} }
else if (compact) { else if (compact) {
let exponent = Math.floor(Math.log(value) / Math.log(base)); const exponent = Math.floor(Math.log(value) / Math.log(base));
value = value / base ** exponent; value = value / base ** exponent;
let unitPrefix = prefixes[base][exponent]; const unitPrefix = prefixes[base][exponent];
return `${value} ${unitPrefix}${unit}` return `${value} ${unitPrefix}${unit}`;
} }
else { else {
return `${value} ${unit}`; return `${value} ${unit}`;

View File

@ -1,25 +1,25 @@
import { requestPVE, requestAPI, goToPage, getURIData, resources_config, setTitleAndHeader } from "./utils.js"; import { requestPVE, requestAPI, goToPage, getURIData, resourcesConfig, setTitleAndHeader } from "./utils.js";
import { alert, dialog } from "./dialog.js"; import { alert, dialog } from "./dialog.js";
window.addEventListener("DOMContentLoaded", init); // do the dumb thing where the disk config refreshes every second window.addEventListener("DOMContentLoaded", init); // do the dumb thing where the disk config refreshes every second
let diskMetaData = resources_config.disk; const diskMetaData = resourcesConfig.disk;
let networkMetaData = resources_config.network; const networkMetaData = resourcesConfig.network;
let pcieMetaData = resources_config.pcie; const pcieMetaData = resourcesConfig.pcie;
let node; let node;
let type; let type;
let vmid; let vmid;
let config; let config;
async function init() { async function init () {
setTitleAndHeader(); setTitleAndHeader();
let cookie = document.cookie; const cookie = document.cookie;
if (cookie === "") { if (cookie === "") {
goToPage("login.html"); goToPage("login.html");
} }
let uriData = getURIData(); const uriData = getURIData();
node = uriData.node; node = uriData.node;
type = uriData.type; type = uriData.type;
vmid = uriData.vmid; vmid = uriData.vmid;
@ -34,37 +34,43 @@ async function init() {
document.querySelector("#exit").addEventListener("click", handleFormExit); document.querySelector("#exit").addEventListener("click", handleFormExit);
} }
function getOrdered(keys) { function getOrdered (keys) {
let ordered_keys = Object.keys(keys).sort((a, b) => { parseInt(a) - parseInt(b) }); // ordered integer list const orderedKeys = Object.keys(keys).sort((a, b) => {
return ordered_keys; return parseInt(a) - parseInt(b);
}); // ordered integer list
return orderedKeys;
} }
async function getConfig() { async function getConfig () {
config = await requestPVE(`/nodes/${node}/${type}/${vmid}/config`, "GET"); config = await requestPVE(`/nodes/${node}/${type}/${vmid}/config`, "GET");
} }
async function populateResources() { async function populateResources () {
let name = type === "qemu" ? "name" : "hostname"; const name = type === "qemu" ? "name" : "hostname";
document.querySelector("#name").innerHTML = document.querySelector("#name").innerHTML.replace("%{vmname}", config.data[name]); document.querySelector("#name").innerHTML = document.querySelector("#name").innerHTML.replace("%{vmname}", config.data[name]);
if (type === "qemu") { if (type === "qemu") {
let global = await requestAPI("/global/config/resources"); const global = await requestAPI("/global/config/resources");
let user = await requestAPI("/user/config/resources"); const user = await requestAPI("/user/config/resources");
let options = []; let options = [];
if (global.cpu.whitelist) { if (global.cpu.whitelist) {
options = user.max.cpu.sort((a, b) => { return a.localeCompare(b) }); options = user.max.cpu.sort((a, b) => {
return a.localeCompare(b);
});
} }
else { else {
let supported = await requestPVE(`/nodes/${node}/capabilities/qemu/cpu`); const supported = await requestPVE(`/nodes/${node}/capabilities/qemu/cpu`);
supported.data.forEach((element) => { supported.data.forEach((element) => {
if (!user.max.cpu.includes(element.name)) { if (!user.max.cpu.includes(element.name)) {
options.push(element.name); options.push(element.name);
} }
}); });
options = options.sort((a, b) => { return a.localeCompare(b) }) options = options.sort((a, b) => {
return a.localeCompare(b);
});
console.log(options); console.log(options);
console.log("blacklist not yet supported") console.log("blacklist not yet supported");
} }
addResourceLine("resources", "images/resources/cpu.svg", "select", "CPU Type", "proctype", { value: config.data.cpu, options: options }); addResourceLine("resources", "images/resources/cpu.svg", "select", "CPU Type", "proctype", { value: config.data.cpu, options });
} }
addResourceLine("resources", "images/resources/cpu.svg", "input", "CPU Amount", "cores", { type: "number", value: config.data.cores, min: 1, max: 8192 }, "Cores"); addResourceLine("resources", "images/resources/cpu.svg", "input", "CPU Amount", "cores", { type: "number", value: config.data.cores, min: 1, max: 8192 }, "Cores");
addResourceLine("resources", "images/resources/ram.svg", "input", "Memory", "ram", { type: "number", value: config.data.memory, min: 16, step: 1 }, "MiB"); addResourceLine("resources", "images/resources/ram.svg", "input", "Memory", "ram", { type: "number", value: config.data.memory, min: 16, step: 1 }, "MiB");
@ -73,23 +79,23 @@ async function populateResources() {
} }
} }
function addResourceLine(fieldset, iconHref, type, labelText, id, attributes, unitText = null) { function addResourceLine (fieldset, iconHref, type, labelText, id, attributes, unitText = null) {
let field = document.querySelector(`#${fieldset}`); const field = document.querySelector(`#${fieldset}`);
let icon = document.createElement("img"); const icon = document.createElement("img");
icon.src = iconHref; icon.src = iconHref;
icon.alt = labelText; icon.alt = labelText;
field.append(icon); field.append(icon);
let label = document.createElement("label"); const label = document.createElement("label");
label.innerText = labelText; label.innerText = labelText;
label.htmlFor = labelText; label.htmlFor = labelText;
field.append(label); field.append(label);
if (type === "input") { if (type === "input") {
let input = document.createElement("input"); const input = document.createElement("input");
for (let k in attributes) { for (const k in attributes) {
input.setAttribute(k, attributes[k]) input.setAttribute(k, attributes[k]);
} }
input.id = id; input.id = id;
input.name = id; input.name = id;
@ -99,8 +105,8 @@ function addResourceLine(fieldset, iconHref, type, labelText, id, attributes, un
field.append(input); field.append(input);
} }
else if (type === "select") { else if (type === "select") {
let select = document.createElement("select"); const select = document.createElement("select");
for (let option of attributes.options) { for (const option of attributes.options) {
select.append(new Option(option)); select.append(new Option(option));
} }
select.value = attributes.value; select.value = attributes.value;
@ -113,31 +119,31 @@ function addResourceLine(fieldset, iconHref, type, labelText, id, attributes, un
} }
if (unitText) { if (unitText) {
let unit = document.createElement("p"); const unit = document.createElement("p");
unit.innerText = unitText; unit.innerText = unitText;
field.append(unit); field.append(unit);
} }
else { else {
let unit = document.createElement("div"); const unit = document.createElement("div");
unit.classList.add("hidden"); unit.classList.add("hidden");
field.append(unit); field.append(unit);
} }
} }
async function populateDisk() { async function populateDisk () {
document.querySelector("#disks").innerHTML = ""; document.querySelector("#disks").innerHTML = "";
for (let i = 0; i < diskMetaData[type].prefixOrder.length; i++) { for (let i = 0; i < diskMetaData[type].prefixOrder.length; i++) {
let prefix = diskMetaData[type].prefixOrder[i]; const prefix = diskMetaData[type].prefixOrder[i];
let busName = diskMetaData[type][prefix].name; const busName = diskMetaData[type][prefix].name;
let disks = {}; const disks = {};
Object.keys(config.data).forEach((element) => { Object.keys(config.data).forEach((element) => {
if (element.startsWith(prefix)) { if (element.startsWith(prefix)) {
disks[element.replace(prefix, "")] = config.data[element]; disks[element.replace(prefix, "")] = config.data[element];
} }
}); });
let ordered_keys = getOrdered(disks); const orderedKeys = getOrdered(disks);
ordered_keys.forEach((element) => { orderedKeys.forEach((element) => {
let disk = disks[element]; const disk = disks[element];
addDiskLine("disks", prefix, busName, element, disk); addDiskLine("disks", prefix, busName, element, disk);
}); });
} }
@ -149,36 +155,36 @@ async function populateDisk() {
} }
} }
function addDiskLine(fieldset, busPrefix, busName, device, diskDetails) { function addDiskLine (fieldset, busPrefix, busName, device, diskDetails) {
let field = document.querySelector(`#${fieldset}`); const field = document.querySelector(`#${fieldset}`);
let diskName = `${busName} ${device}`; const diskName = `${busName} ${device}`;
let diskID = `${busPrefix}${device}`; const diskID = `${busPrefix}${device}`;
// Set the disk icon, either drive.svg or disk.svg // Set the disk icon, either drive.svg or disk.svg
let icon = document.createElement("img"); const icon = document.createElement("img");
icon.src = diskMetaData[type][busPrefix].icon; icon.src = diskMetaData[type][busPrefix].icon;
icon.alt = diskName; icon.alt = diskName;
icon.dataset.disk = diskID; icon.dataset.disk = diskID;
field.append(icon); field.append(icon);
// Add a label for the disk bus and device number // Add a label for the disk bus and device number
let diskLabel = document.createElement("label"); const diskLabel = document.createElement("label");
diskLabel.innerText = diskName; diskLabel.innerText = diskName;
diskLabel.dataset.disk = diskID; diskLabel.dataset.disk = diskID;
field.append(diskLabel); field.append(diskLabel);
// Add text of the disk configuration // Add text of the disk configuration
let diskDesc = document.createElement("p"); const diskDesc = document.createElement("p");
diskDesc.innerText = diskDetails; diskDesc.innerText = diskDetails;
diskDesc.dataset.disk = diskID; diskDesc.dataset.disk = diskID;
diskDesc.style.overflowX = "hidden"; diskDesc.style.overflowX = "hidden";
diskDesc.style.whiteSpace = "nowrap"; diskDesc.style.whiteSpace = "nowrap";
field.append(diskDesc); field.append(diskDesc);
let actionDiv = document.createElement("div"); const actionDiv = document.createElement("div");
diskMetaData.actionBarOrder.forEach((element) => { diskMetaData.actionBarOrder.forEach((element) => {
let action = document.createElement("img"); const action = document.createElement("img");
if (element === "detach_attach" && diskMetaData[type][busPrefix].actions.includes("attach")) { // attach if (element === "detach_attach" && diskMetaData[type][busPrefix].actions.includes("attach")) { // attach
action.src = "images/actions/disk/attach.svg"; action.src = "images/actions/disk/attach.svg";
action.title = "Attach Disk"; action.title = "Attach Disk";
@ -192,7 +198,7 @@ function addDiskLine(fieldset, busPrefix, busName, device, diskDetails) {
action.classList.add("clickable"); action.classList.add("clickable");
} }
else if (element === "delete") { else if (element === "delete") {
let active = diskMetaData[type][busPrefix].actions.includes(element) ? "active" : "inactive"; // resize const active = diskMetaData[type][busPrefix].actions.includes(element) ? "active" : "inactive"; // resize
action.src = `images/actions/delete-${active}.svg`; action.src = `images/actions/delete-${active}.svg`;
action.title = "Delete Disk"; action.title = "Delete Disk";
if (active === "active") { if (active === "active") {
@ -201,7 +207,7 @@ function addDiskLine(fieldset, busPrefix, busName, device, diskDetails) {
} }
} }
else { else {
let active = diskMetaData[type][busPrefix].actions.includes(element) ? "active" : "inactive"; // resize const active = diskMetaData[type][busPrefix].actions.includes(element) ? "active" : "inactive"; // resize
action.src = `images/actions/disk/${element}-${active}.svg`; action.src = `images/actions/disk/${element}-${active}.svg`;
if (active === "active") { if (active === "active") {
action.title = `${element.charAt(0).toUpperCase()}${element.slice(1)} Disk`; action.title = `${element.charAt(0).toUpperCase()}${element.slice(1)} Disk`;
@ -221,19 +227,19 @@ function addDiskLine(fieldset, busPrefix, busName, device, diskDetails) {
field.append(actionDiv); field.append(actionDiv);
} }
async function handleDiskDetach() { async function handleDiskDetach () {
let header = `Detach ${this.dataset.disk}`; const header = `Detach ${this.dataset.disk}`;
let body = `<p>Are you sure you want to detach disk</p><p>${this.dataset.disk}</p>`; const body = `<p>Are you sure you want to detach disk</p><p>${this.dataset.disk}</p>`;
dialog(header, body, async (result, form) => { dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
document.querySelector(`img[data-disk="${this.dataset.disk}"]`).src = "images/status/loading.svg"; document.querySelector(`img[data-disk="${this.dataset.disk}"]`).src = "images/status/loading.svg";
let body = { const body = {
node: node, node,
type: type, type,
vmid: vmid, vmid,
disk: this.dataset.disk disk: this.dataset.disk
}; };
let result = await requestAPI("/instance/disk/detach", "POST", body); const result = await requestAPI("/instance/disk/detach", "POST", body);
if (result.status === 200) { if (result.status === 200) {
await getConfig(); await getConfig();
populateDisk(); populateDisk();
@ -247,22 +253,22 @@ async function handleDiskDetach() {
}); });
} }
async function handleDiskAttach() { async function handleDiskAttach () {
let header = `Attach ${this.dataset.disk}`; const header = `Attach ${this.dataset.disk}`;
let body = `<label for="device">${type === "qemu" ? "SATA" : "MP"}</label><input class="w3-input w3-border" name="device" id="device" type="number" min="0" max="${type === "qemu" ? "5" : "255"}" required></input>`; const body = `<label for="device">${type === "qemu" ? "SATA" : "MP"}</label><input class="w3-input w3-border" name="device" id="device" type="number" min="0" max="${type === "qemu" ? "5" : "255"}" required></input>`;
dialog(header, body, async (result, form) => { dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
let device = form.get("device"); const device = form.get("device");
document.querySelector(`img[data-disk="${this.dataset.disk}"]`).src = "images/status/loading.svg"; document.querySelector(`img[data-disk="${this.dataset.disk}"]`).src = "images/status/loading.svg";
let body = { const body = {
node: node, node,
type: type, type,
vmid: vmid, vmid,
disk: `${type === "qemu" ? "sata" : "mp"}${device}`, disk: `${type === "qemu" ? "sata" : "mp"}${device}`,
source: this.dataset.disk.replace("unused", "") source: this.dataset.disk.replace("unused", "")
} };
let result = await requestAPI("/instance/disk/attach", "POST", body); const result = await requestAPI("/instance/disk/attach", "POST", body);
if (result.status === 200) { if (result.status === 200) {
await getConfig(); await getConfig();
populateDisk(); populateDisk();
@ -276,21 +282,21 @@ async function handleDiskAttach() {
}); });
} }
async function handleDiskResize() { async function handleDiskResize () {
let header = `Resize ${this.dataset.disk}`; const header = `Resize ${this.dataset.disk}`;
let body = `<label for="size-increment">Size Increment (GiB)</label><input class="w3-input w3-border" name="size-increment" id="size-increment" type="number" min="0" max="131072"></input>`; const body = "<label for=\"size-increment\">Size Increment (GiB)</label><input class=\"w3-input w3-border\" name=\"size-increment\" id=\"size-increment\" type=\"number\" min=\"0\" max=\"131072\"></input>";
dialog(header, body, async (result, form) => { dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
document.querySelector(`img[data-disk="${this.dataset.disk}"]`).src = "images/status/loading.svg"; document.querySelector(`img[data-disk="${this.dataset.disk}"]`).src = "images/status/loading.svg";
let body = { const body = {
node: node, node,
type: type, type,
vmid: vmid, vmid,
disk: this.dataset.disk, disk: this.dataset.disk,
size: form.get("size-increment") size: form.get("size-increment")
} };
let result = await requestAPI("/instance/disk/resize", "POST", body); const result = await requestAPI("/instance/disk/resize", "POST", body);
if (result.status === 200) { if (result.status === 200) {
await getConfig(); await getConfig();
populateDisk(); populateDisk();
@ -304,11 +310,11 @@ async function handleDiskResize() {
}); });
} }
async function handleDiskMove() { async function handleDiskMove () {
let content = type === "qemu" ? "images" : "rootdir"; const content = type === "qemu" ? "images" : "rootdir";
let storage = await requestPVE(`/nodes/${node}/storage`, "GET"); const storage = await requestPVE(`/nodes/${node}/storage`, "GET");
let header = `Move ${this.dataset.disk}`; const header = `Move ${this.dataset.disk}`;
let options = ""; let options = "";
storage.data.forEach((element) => { storage.data.forEach((element) => {
@ -316,9 +322,9 @@ async function handleDiskMove() {
options += `<option value="${element.storage}">${element.storage}</option>"`; options += `<option value="${element.storage}">${element.storage}</option>"`;
} }
}); });
let select = `<label for="storage-select">Storage</label><select class="w3-select w3-border" name="storage-select" id="storage-select"><option hidden disabled selected value></option>${options}</select>`; const select = `<label for="storage-select">Storage</label><select class="w3-select w3-border" name="storage-select" id="storage-select"><option hidden disabled selected value></option>${options}</select>`;
let body = ` const body = `
${select} ${select}
<label for="delete-check">Delete Source</label><input class="w3-input w3-border" name="delete-check" id="delete-check" type="checkbox" checked required> <label for="delete-check">Delete Source</label><input class="w3-input w3-border" name="delete-check" id="delete-check" type="checkbox" checked required>
`; `;
@ -326,15 +332,15 @@ async function handleDiskMove() {
dialog(header, body, async (result, form) => { dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
document.querySelector(`img[data-disk="${this.dataset.disk}"]`).src = "images/status/loading.svg"; document.querySelector(`img[data-disk="${this.dataset.disk}"]`).src = "images/status/loading.svg";
let body = { const body = {
node: node, node,
type: type, type,
vmid: vmid, vmid,
disk: this.dataset.disk, disk: this.dataset.disk,
storage: form.get("storage-select"), storage: form.get("storage-select"),
delete: form.get("delete-check") === "on" ? "1" : "0" delete: form.get("delete-check") === "on" ? "1" : "0"
} };
let result = await requestAPI("/instance/disk/move", "POST", body); const result = await requestAPI("/instance/disk/move", "POST", body);
if (result.status === 200) { if (result.status === 200) {
await getConfig(); await getConfig();
populateDisk(); populateDisk();
@ -348,20 +354,20 @@ async function handleDiskMove() {
}); });
} }
async function handleDiskDelete() { async function handleDiskDelete () {
let header = `Delete ${this.dataset.disk}`; const header = `Delete ${this.dataset.disk}`;
let body = `<p>Are you sure you want to <strong>delete</strong> disk</p><p>${this.dataset.disk}</p>`; const body = `<p>Are you sure you want to <strong>delete</strong> disk</p><p>${this.dataset.disk}</p>`;
dialog(header, body, async (result, form) => { dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
document.querySelector(`img[data-disk="${this.dataset.disk}"]`).src = "images/status/loading.svg"; document.querySelector(`img[data-disk="${this.dataset.disk}"]`).src = "images/status/loading.svg";
let body = { const body = {
node: node, node,
type: type, type,
vmid: vmid, vmid,
disk: this.dataset.disk disk: this.dataset.disk
}; };
let result = await requestAPI("/instance/disk/delete", "DELETE", body); const result = await requestAPI("/instance/disk/delete", "DELETE", body);
if (result.status === 200) { if (result.status === 200) {
await getConfig(); await getConfig();
populateDisk(); populateDisk();
@ -375,11 +381,11 @@ async function handleDiskDelete() {
}); });
} }
async function handleDiskAdd() { async function handleDiskAdd () {
let content = type === "qemu" ? "images" : "rootdir"; const content = type === "qemu" ? "images" : "rootdir";
let storage = await requestPVE(`/nodes/${node}/storage`, "GET"); const storage = await requestPVE(`/nodes/${node}/storage`, "GET");
let header = "Create New Disk"; const header = "Create New Disk";
let options = ""; let options = "";
storage.data.forEach((element) => { storage.data.forEach((element) => {
@ -387,9 +393,9 @@ async function handleDiskAdd() {
options += `<option value="${element.storage}">${element.storage}</option>"`; options += `<option value="${element.storage}">${element.storage}</option>"`;
} }
}); });
let select = `<label for="storage-select">Storage</label><select class="w3-select w3-border" name="storage-select" id="storage-select" required><option hidden disabled selected value></option>${options}</select>`; const select = `<label for="storage-select">Storage</label><select class="w3-select w3-border" name="storage-select" id="storage-select" required><option hidden disabled selected value></option>${options}</select>`;
let body = ` const body = `
<label for="device">${type === "qemu" ? "SATA" : "MP"}</label><input class="w3-input w3-border" name="device" id="device" type="number" min="0" max="${type === "qemu" ? "5" : "255"}" value="0" required></input> <label for="device">${type === "qemu" ? "SATA" : "MP"}</label><input class="w3-input w3-border" name="device" id="device" type="number" min="0" max="${type === "qemu" ? "5" : "255"}" value="0" required></input>
${select} ${select}
<label for="size">Size (GiB)</label><input class="w3-input w3-border" name="size" id="size" type="number" min="0" max="131072" required></input> <label for="size">Size (GiB)</label><input class="w3-input w3-border" name="size" id="size" type="number" min="0" max="131072" required></input>
@ -397,15 +403,15 @@ async function handleDiskAdd() {
dialog(header, body, async (result, form) => { dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
let body = { const body = {
node: node, node,
type: type, type,
vmid: vmid, vmid,
disk: `${type === "qemu" ? "sata" : "mp"}${form.get("device")}`, disk: `${type === "qemu" ? "sata" : "mp"}${form.get("device")}`,
storage: form.get("storage-select"), storage: form.get("storage-select"),
size: form.get("size") size: form.get("size")
}; };
let result = await requestAPI("/instance/disk/create", "POST", body); const result = await requestAPI("/instance/disk/create", "POST", body);
if (result.status === 200) { if (result.status === 200) {
await getConfig(); await getConfig();
populateDisk(); populateDisk();
@ -419,11 +425,11 @@ async function handleDiskAdd() {
}); });
} }
async function handleCDAdd() { async function handleCDAdd () {
let content = "iso"; const content = "iso";
let storage = await requestPVE(`/nodes/${node}/storage`, "GET"); const storage = await requestPVE(`/nodes/${node}/storage`, "GET");
let header = `Add a CDROM`; const header = "Add a CDROM";
let storageOptions = ""; let storageOptions = "";
storage.data.forEach((element) => { storage.data.forEach((element) => {
@ -431,24 +437,24 @@ async function handleCDAdd() {
storageOptions += `<option value="${element.storage}">${element.storage}</option>"`; storageOptions += `<option value="${element.storage}">${element.storage}</option>"`;
} }
}); });
let storageSelect = `<label for="storage-select">Storage</label><select class="w3-select w3-border" name="storage-select" id="storage-select" required><option hidden disabled selected value></option>${storageOptions}</select>`; const storageSelect = `<label for="storage-select">Storage</label><select class="w3-select w3-border" name="storage-select" id="storage-select" required><option hidden disabled selected value></option>${storageOptions}</select>`;
let body = ` const body = `
<label for="device">IDE</label><input class="w3-input w3-border" name="device" id="device" type="number" min="0" max="3" required></input> <label for="device">IDE</label><input class="w3-input w3-border" name="device" id="device" type="number" min="0" max="3" required></input>
${storageSelect} ${storageSelect}
<label for="iso-select">Image</label><select class="w3-select w3-border" name="iso-select" id="iso-select" required></select> <label for="iso-select">Image</label><select class="w3-select w3-border" name="iso-select" id="iso-select" required></select>
`; `;
let d = dialog(header, body, async (result, form) => { const d = dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
let body = { const body = {
node: node, node,
type: type, type,
vmid: vmid, vmid,
disk: `ide${form.get("device")}`, disk: `ide${form.get("device")}`,
iso: form.get("iso-select") iso: form.get("iso-select")
}; };
let result = await requestAPI("/instance/disk/create", "POST", body); const result = await requestAPI("/instance/disk/create", "POST", body);
if (result.status === 200) { if (result.status === 200) {
await getConfig(); await getConfig();
populateDisk(); populateDisk();
@ -462,10 +468,10 @@ async function handleCDAdd() {
}); });
d.querySelector("#storage-select").addEventListener("change", async () => { d.querySelector("#storage-select").addEventListener("change", async () => {
let storage = document.querySelector("#storage-select").value; const storage = document.querySelector("#storage-select").value;
let ISOSelect = document.querySelector("#iso-select"); const ISOSelect = document.querySelector("#iso-select");
ISOSelect.innerHTML = `<option hidden disabled selected value></option>`; ISOSelect.innerHTML = "<option hidden disabled selected value></option>";
let isos = await requestPVE(`/nodes/${node}/storage/${storage}/content`, "GET", { content: content }); const isos = await requestPVE(`/nodes/${node}/storage/${storage}/content`, "GET", { content });
isos.data.forEach((element) => { isos.data.forEach((element) => {
if (element.content.includes(content)) { if (element.content.includes(content)) {
ISOSelect.append(new Option(element.volid.replace(`${storage}:${content}/`, ""), element.volid)); ISOSelect.append(new Option(element.volid.replace(`${storage}:${content}/`, ""), element.volid));
@ -474,40 +480,40 @@ async function handleCDAdd() {
}); });
} }
async function populateNetworks() { async function populateNetworks () {
document.querySelector("#networks").innerHTML = ""; document.querySelector("#networks").innerHTML = "";
let networks = {}; const networks = {};
let prefix = networkMetaData.prefix; const prefix = networkMetaData.prefix;
Object.keys(config.data).forEach((element) => { Object.keys(config.data).forEach((element) => {
if (element.startsWith(prefix)) { if (element.startsWith(prefix)) {
networks[element.replace(prefix, "")] = config.data[element]; networks[element.replace(prefix, "")] = config.data[element];
} }
}); });
let ordered_keys = getOrdered(networks); const orderedKeys = getOrdered(networks);
ordered_keys.forEach((element) => { orderedKeys.forEach((element) => {
addNetworkLine("networks", prefix, element, networks[element]); addNetworkLine("networks", prefix, element, networks[element]);
}); });
document.querySelector("#network-add").addEventListener("click", handleNetworkAdd) document.querySelector("#network-add").addEventListener("click", handleNetworkAdd);
} }
function addNetworkLine(fieldset, prefix, netID, netDetails) { function addNetworkLine (fieldset, prefix, netID, netDetails) {
let field = document.querySelector(`#${fieldset}`); const field = document.querySelector(`#${fieldset}`);
let icon = document.createElement("img"); const icon = document.createElement("img");
icon.src = "images/resources/network.svg"; icon.src = "images/resources/network.svg";
icon.alt = `${prefix}${netID}`; icon.alt = `${prefix}${netID}`;
icon.dataset.network = netID; icon.dataset.network = netID;
icon.dataset.values = netDetails; icon.dataset.values = netDetails;
field.appendChild(icon); field.appendChild(icon);
let netLabel = document.createElement("label"); const netLabel = document.createElement("label");
netLabel.innerText = `${prefix}${netID}`; netLabel.innerText = `${prefix}${netID}`;
netLabel.dataset.network = netID; netLabel.dataset.network = netID;
netLabel.dataset.values = netDetails; netLabel.dataset.values = netDetails;
field.append(netLabel); field.append(netLabel);
let netDesc = document.createElement("p"); const netDesc = document.createElement("p");
netDesc.innerText = netDetails; netDesc.innerText = netDetails;
netDesc.dataset.network = netID; netDesc.dataset.network = netID;
netDesc.dataset.values = netDetails; netDesc.dataset.values = netDetails;
@ -515,20 +521,20 @@ function addNetworkLine(fieldset, prefix, netID, netDetails) {
netDesc.style.whiteSpace = "nowrap"; netDesc.style.whiteSpace = "nowrap";
field.append(netDesc); field.append(netDesc);
let actionDiv = document.createElement("div"); const actionDiv = document.createElement("div");
let configBtn = document.createElement("img"); const configBtn = document.createElement("img");
configBtn.classList.add("clickable"); configBtn.classList.add("clickable");
configBtn.src = `images/actions/network/config.svg`; configBtn.src = "images/actions/network/config.svg";
configBtn.title = "Config Interface"; configBtn.title = "Config Interface";
configBtn.addEventListener("click", handleNetworkConfig); configBtn.addEventListener("click", handleNetworkConfig);
configBtn.dataset.network = netID; configBtn.dataset.network = netID;
configBtn.dataset.values = netDetails; configBtn.dataset.values = netDetails;
actionDiv.appendChild(configBtn); actionDiv.appendChild(configBtn);
let deleteBtn = document.createElement("img"); const deleteBtn = document.createElement("img");
deleteBtn.classList.add("clickable"); deleteBtn.classList.add("clickable");
deleteBtn.src = `images/actions/delete-active.svg`; deleteBtn.src = "images/actions/delete-active.svg";
deleteBtn.title = "Delete Interface"; deleteBtn.title = "Delete Interface";
deleteBtn.addEventListener("click", handleNetworkDelete); deleteBtn.addEventListener("click", handleNetworkDelete);
deleteBtn.dataset.network = netID; deleteBtn.dataset.network = netID;
@ -538,23 +544,23 @@ function addNetworkLine(fieldset, prefix, netID, netDetails) {
field.append(actionDiv); field.append(actionDiv);
} }
async function handleNetworkConfig() { async function handleNetworkConfig () {
let netID = this.dataset.network; const netID = this.dataset.network;
let netDetails = this.dataset.values; const netDetails = this.dataset.values;
let header = `Edit net${netID}`; const header = `Edit net${netID}`;
let body = `<label for="rate">Rate Limit (MB/s)</label><input type="number" id="rate" name="rate" class="w3-input w3-border">`; const body = "<label for=\"rate\">Rate Limit (MB/s)</label><input type=\"number\" id=\"rate\" name=\"rate\" class=\"w3-input w3-border\">";
let d = dialog(header, body, async (result, form) => { const d = dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
document.querySelector(`img[data-network="${netID}"]`).src = "images/status/loading.svg"; document.querySelector(`img[data-network="${netID}"]`).src = "images/status/loading.svg";
let body = { const body = {
node: node, node,
type: type, type,
vmid: vmid, vmid,
netid: netID, netid: netID,
rate: form.get("rate") rate: form.get("rate")
} };
let result = await requestAPI("/instance/network/modify", "POST", body); const result = await requestAPI("/instance/network/modify", "POST", body);
if (result.status === 200) { if (result.status === 200) {
await getConfig(); await getConfig();
populateNetworks(); populateNetworks();
@ -570,21 +576,21 @@ async function handleNetworkConfig() {
d.querySelector("#rate").value = netDetails.split("rate=")[1].split(",")[0]; d.querySelector("#rate").value = netDetails.split("rate=")[1].split(",")[0];
} }
async function handleNetworkDelete() { async function handleNetworkDelete () {
let netID = this.dataset.network; const netID = this.dataset.network;
let header = `Delete net${netID}`; const header = `Delete net${netID}`;
let body = ``; const body = "";
let d = dialog(header, body, async (result, form) => { const d = dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
document.querySelector(`img[data-network="${netID}"]`).src = "images/status/loading.svg"; document.querySelector(`img[data-network="${netID}"]`).src = "images/status/loading.svg";
let body = { const body = {
node: node, node,
type: type, type,
vmid: vmid, vmid,
netid: netID netid: netID
} };
let result = await requestAPI("/instance/network/delete", "DELETE", body); const result = await requestAPI("/instance/network/delete", "DELETE", body);
if (result.status === 200) { if (result.status === 200) {
await getConfig(); await getConfig();
populateNetworks(); populateNetworks();
@ -598,26 +604,26 @@ async function handleNetworkDelete() {
}); });
} }
async function handleNetworkAdd() { async function handleNetworkAdd () {
let header = `Create Network Interface`; const header = "Create Network Interface";
let body = `<label for="netid">Interface ID</label><input type="number" id="netid" name="netid" class="w3-input w3-border"><label for="rate">Rate Limit (MB/s)</label><input type="number" id="rate" name="rate" class="w3-input w3-border">`; let body = "<label for=\"netid\">Interface ID</label><input type=\"number\" id=\"netid\" name=\"netid\" class=\"w3-input w3-border\"><label for=\"rate\">Rate Limit (MB/s)</label><input type=\"number\" id=\"rate\" name=\"rate\" class=\"w3-input w3-border\">";
if (type === "lxc") { if (type === "lxc") {
body += `<label for="name">Interface Name</label><input type="text" id="name" name="name" class="w3-input w3-border"></input>`; body += "<label for=\"name\">Interface Name</label><input type=\"text\" id=\"name\" name=\"name\" class=\"w3-input w3-border\"></input>";
} }
let d = dialog(header, body, async (result, form) => { const d = dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
let body = { const body = {
node: node, node,
type: type, type,
vmid: vmid, vmid,
netid: form.get("netid"), netid: form.get("netid"),
rate: form.get("rate") rate: form.get("rate")
} };
if (type === "lxc") { if (type === "lxc") {
body.name = form.get("name") body.name = form.get("name");
} }
let result = await requestAPI("/instance/network/create", "POST", body); const result = await requestAPI("/instance/network/create", "POST", body);
if (result.status === 200) { if (result.status === 200) {
await getConfig(); await getConfig();
populateNetworks(); populateNetworks();
@ -631,31 +637,31 @@ async function handleNetworkAdd() {
}); });
} }
async function populateDevices() { async function populateDevices () {
if (type === "qemu") { if (type === "qemu") {
document.querySelector("#devices-card").classList.remove("none"); document.querySelector("#devices-card").classList.remove("none");
document.querySelector("#devices").innerHTML = ""; document.querySelector("#devices").innerHTML = "";
let devices = {}; const devices = {};
let prefix = pcieMetaData.prefix; const prefix = pcieMetaData.prefix;
Object.keys(config.data).forEach((element) => { Object.keys(config.data).forEach((element) => {
if (element.startsWith(prefix)) { if (element.startsWith(prefix)) {
devices[element.replace(prefix, "")] = config.data[element]; devices[element.replace(prefix, "")] = config.data[element];
} }
}); });
let ordered_keys = getOrdered(devices); const orderedKeys = getOrdered(devices);
ordered_keys.forEach(async (element) => { orderedKeys.forEach(async (element) => {
let deviceData = await requestAPI(`/instance/pci?node=${node}&type=${type}&vmid=${vmid}&hostpci=${element}`, "GET"); const deviceData = await requestAPI(`/instance/pci?node=${node}&type=${type}&vmid=${vmid}&hostpci=${element}`, "GET");
addDeviceLine("devices", prefix, element, devices[element], deviceData.device_name); addDeviceLine("devices", prefix, element, devices[element], deviceData.device_name);
}); });
document.querySelector("#device-add").addEventListener("click", handleDeviceAdd) document.querySelector("#device-add").addEventListener("click", handleDeviceAdd);
} }
} }
function addDeviceLine(fieldset, prefix, deviceID, deviceDetails, deviceName) { function addDeviceLine (fieldset, prefix, deviceID, deviceDetails, deviceName) {
let field = document.querySelector(`#${fieldset}`); const field = document.querySelector(`#${fieldset}`);
let icon = document.createElement("img"); const icon = document.createElement("img");
icon.src = "images/resources/device.svg"; icon.src = "images/resources/device.svg";
icon.alt = `${prefix}${deviceID}`; icon.alt = `${prefix}${deviceID}`;
icon.dataset.device = deviceID; icon.dataset.device = deviceID;
@ -663,7 +669,7 @@ function addDeviceLine(fieldset, prefix, deviceID, deviceDetails, deviceName) {
icon.dataset.name = deviceName; icon.dataset.name = deviceName;
field.appendChild(icon); field.appendChild(icon);
let deviceLabel = document.createElement("p"); const deviceLabel = document.createElement("p");
deviceLabel.innerText = deviceName; deviceLabel.innerText = deviceName;
deviceLabel.dataset.device = deviceID; deviceLabel.dataset.device = deviceID;
@ -673,11 +679,11 @@ function addDeviceLine(fieldset, prefix, deviceID, deviceDetails, deviceName) {
deviceLabel.style.whiteSpace = "nowrap"; deviceLabel.style.whiteSpace = "nowrap";
field.append(deviceLabel); field.append(deviceLabel);
let actionDiv = document.createElement("div"); const actionDiv = document.createElement("div");
let configBtn = document.createElement("img"); const configBtn = document.createElement("img");
configBtn.classList.add("clickable"); configBtn.classList.add("clickable");
configBtn.src = `images/actions/device/config.svg`; configBtn.src = "images/actions/device/config.svg";
configBtn.title = "Config Device"; configBtn.title = "Config Device";
configBtn.addEventListener("click", handleDeviceConfig); configBtn.addEventListener("click", handleDeviceConfig);
configBtn.dataset.device = deviceID; configBtn.dataset.device = deviceID;
@ -685,9 +691,9 @@ function addDeviceLine(fieldset, prefix, deviceID, deviceDetails, deviceName) {
configBtn.dataset.name = deviceName; configBtn.dataset.name = deviceName;
actionDiv.appendChild(configBtn); actionDiv.appendChild(configBtn);
let deleteBtn = document.createElement("img"); const deleteBtn = document.createElement("img");
deleteBtn.classList.add("clickable"); deleteBtn.classList.add("clickable");
deleteBtn.src = `images/actions/delete-active.svg`; deleteBtn.src = "images/actions/delete-active.svg";
deleteBtn.title = "Delete Device"; deleteBtn.title = "Delete Device";
deleteBtn.addEventListener("click", handleDeviceDelete); deleteBtn.addEventListener("click", handleDeviceDelete);
deleteBtn.dataset.device = deviceID; deleteBtn.dataset.device = deviceID;
@ -698,25 +704,25 @@ function addDeviceLine(fieldset, prefix, deviceID, deviceDetails, deviceName) {
field.append(actionDiv); field.append(actionDiv);
} }
async function handleDeviceConfig() { async function handleDeviceConfig () {
let deviceID = this.dataset.device; const deviceID = this.dataset.device;
let deviceDetails = this.dataset.values; const deviceDetails = this.dataset.values;
let deviceName = this.dataset.name; const deviceName = this.dataset.name;
let header = `Edit Expansion Card ${deviceID}`; const header = `Edit Expansion Card ${deviceID}`;
let body = `<label for="device">Device</label><select id="device" name="device" required></select><label for="pcie">PCI-Express</label><input type="checkbox" id="pcie" name="pcie" class="w3-input w3-border">`; const body = "<label for=\"device\">Device</label><select id=\"device\" name=\"device\" required></select><label for=\"pcie\">PCI-Express</label><input type=\"checkbox\" id=\"pcie\" name=\"pcie\" class=\"w3-input w3-border\">";
let d = dialog(header, body, async (result, form) => { const d = dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
document.querySelector(`img[data-device="${deviceID}"]`).src = "images/status/loading.svg"; document.querySelector(`img[data-device="${deviceID}"]`).src = "images/status/loading.svg";
let body = { const body = {
node: node, node,
type: type, type,
vmid: vmid, vmid,
hostpci: deviceID, hostpci: deviceID,
device: form.get("device"), device: form.get("device"),
pcie: form.get("pcie") ? 1 : 0 pcie: form.get("pcie") ? 1 : 0
} };
let result = await requestAPI("/instance/pci/modify", "POST", body); const result = await requestAPI("/instance/pci/modify", "POST", body);
if (result.status === 200) { if (result.status === 200) {
await getConfig(); await getConfig();
populateDevices(); populateDevices();
@ -729,29 +735,29 @@ async function handleDeviceConfig() {
} }
}); });
let availDevices = await requestAPI(`/nodes/pci?node=${node}`, "GET"); const availDevices = await requestAPI(`/nodes/pci?node=${node}`, "GET");
d.querySelector("#device").append(new Option(deviceName, deviceDetails.split(",")[0])); d.querySelector("#device").append(new Option(deviceName, deviceDetails.split(",")[0]));
for (let availDevice of availDevices) { for (const availDevice of availDevices) {
d.querySelector("#device").append(new Option(availDevice.device_name, availDevice.id)); d.querySelector("#device").append(new Option(availDevice.device_name, availDevice.id));
} }
d.querySelector("#pcie").checked = deviceDetails.includes("pcie=1"); d.querySelector("#pcie").checked = deviceDetails.includes("pcie=1");
} }
async function handleDeviceDelete() { async function handleDeviceDelete () {
let deviceID = this.dataset.device; const deviceID = this.dataset.device;
let header = `Remove Expansion Card ${deviceID}`; const header = `Remove Expansion Card ${deviceID}`;
let body = ``; const body = "";
let d = dialog(header, body, async (result, form) => { const d = dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
document.querySelector(`img[data-device="${deviceID}"]`).src = "images/status/loading.svg"; document.querySelector(`img[data-device="${deviceID}"]`).src = "images/status/loading.svg";
let body = { const body = {
node: node, node,
type: type, type,
vmid: vmid, vmid,
hostpci: deviceID hostpci: deviceID
} };
let result = await requestAPI("/instance/pci/delete", "DELETE", body); const result = await requestAPI("/instance/pci/delete", "DELETE", body);
if (result.status === 200) { if (result.status === 200) {
await getConfig(); await getConfig();
populateDevices(); populateDevices();
@ -765,20 +771,20 @@ async function handleDeviceDelete() {
}); });
} }
async function handleDeviceAdd() { async function handleDeviceAdd () {
let header = `Add Expansion Card`; const header = "Add Expansion Card";
let body = `<label for="device">Device</label><select id="device" name="device" required></select><label for="pcie">PCI-Express</label><input type="checkbox" id="pcie" name="pcie" class="w3-input w3-border">`; const body = "<label for=\"device\">Device</label><select id=\"device\" name=\"device\" required></select><label for=\"pcie\">PCI-Express</label><input type=\"checkbox\" id=\"pcie\" name=\"pcie\" class=\"w3-input w3-border\">";
let d = dialog(header, body, async (result, form) => { const d = dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
let body = { const body = {
node: node, node,
type: type, type,
vmid: vmid, vmid,
device: form.get("device"), device: form.get("device"),
pcie: form.get("pcie") ? 1 : 0 pcie: form.get("pcie") ? 1 : 0
} };
let result = await requestAPI("/instance/pci/create", "POST", body); const result = await requestAPI("/instance/pci/create", "POST", body);
if (result.status === 200) { if (result.status === 200) {
await getConfig(); await getConfig();
populateDevices(); populateDevices();
@ -791,28 +797,28 @@ async function handleDeviceAdd() {
} }
}); });
let availDevices = await requestAPI(`/nodes/pci?node=${node}`, "GET"); const availDevices = await requestAPI(`/nodes/pci?node=${node}`, "GET");
for (let availDevice of availDevices) { for (const availDevice of availDevices) {
d.querySelector("#device").append(new Option(availDevice.device_name, availDevice.id)); d.querySelector("#device").append(new Option(availDevice.device_name, availDevice.id));
} }
d.querySelector("#pcie").checked = true; d.querySelector("#pcie").checked = true;
} }
async function handleFormExit() { async function handleFormExit () {
let body = { const body = {
node: node, node,
type: type, type,
vmid: vmid, vmid,
cores: document.querySelector("#cores").value, cores: document.querySelector("#cores").value,
memory: document.querySelector("#ram").value memory: document.querySelector("#ram").value
} };
if (type === "lxc") { if (type === "lxc") {
body.swap = document.querySelector("#swap").value; body.swap = document.querySelector("#swap").value;
} }
else if (type === "qemu") { else if (type === "qemu") {
body.proctype = document.querySelector("#proctype").value; body.proctype = document.querySelector("#proctype").value;
} }
let result = await requestAPI("/instance/resources", "POST", body); const result = await requestAPI("/instance/resources", "POST", body);
if (result.status === 200) { if (result.status === 200) {
await getConfig(); await getConfig();
populateDisk(); populateDisk();

View File

@ -1,5 +1,5 @@
export function dialog(header, body, callback = async (result, form) => { }) { export function dialog (header, body, callback = async (result, form) => { }) {
let dialog = document.createElement("dialog"); const dialog = document.createElement("dialog");
dialog.innerHTML = ` dialog.innerHTML = `
<p class="w3-large" id="prompt" style="text-align: center;"></p> <p class="w3-large" id="prompt" style="text-align: center;"></p>
<form method="dialog" class="input-grid" style="grid-template-columns: auto 1fr;" id="form"></form> <form method="dialog" class="input-grid" style="grid-template-columns: auto 1fr;" id="form"></form>
@ -23,8 +23,8 @@ export function dialog(header, body, callback = async (result, form) => { }) {
return dialog; return dialog;
} }
export function alert(message) { export function alert (message) {
let dialog = document.createElement("dialog"); const dialog = document.createElement("dialog");
dialog.innerHTML = ` dialog.innerHTML = `
<form method="dialog"> <form method="dialog">
<p class="w3-center" style="margin-bottom: 0px;">${message}</p> <p class="w3-center" style="margin-bottom: 0px;">${message}</p>
@ -40,7 +40,7 @@ export function alert(message) {
dialog.addEventListener("close", () => { dialog.addEventListener("close", () => {
dialog.parentElement.removeChild(dialog); dialog.parentElement.removeChild(dialog);
}) });
return dialog; return dialog;
} }

View File

@ -1,31 +1,31 @@
import { requestPVE, requestAPI, goToPage, goToURL, instances_config, nodes_config, setTitleAndHeader } from "./utils.js"; import { requestPVE, requestAPI, goToPage, goToURL, instancesConfig, nodesConfig, setTitleAndHeader } from "./utils.js";
import { alert, dialog } from "./dialog.js"; import { alert, dialog } from "./dialog.js";
import { PVE } from "../vars.js" import { PVE } from "../vars.js";
window.addEventListener("DOMContentLoaded", init); window.addEventListener("DOMContentLoaded", init);
async function init() { async function init () {
setTitleAndHeader(); setTitleAndHeader();
let cookie = document.cookie; const cookie = document.cookie;
if (cookie === "") { if (cookie === "") {
goToPage("login.html"); goToPage("login.html");
} }
await populateInstances(); await populateInstances();
let addInstanceBtn = document.querySelector("#instance-add"); const addInstanceBtn = document.querySelector("#instance-add");
addInstanceBtn.addEventListener("click", handleInstanceAdd); addInstanceBtn.addEventListener("click", handleInstanceAdd);
} }
async function populateInstances() { async function populateInstances () {
let resources = await requestPVE("/cluster/resources", "GET"); const resources = await requestPVE("/cluster/resources", "GET");
let instanceContainer = document.getElementById("instance-container"); const instanceContainer = document.getElementById("instance-container");
let instances = []; const instances = [];
resources.data.forEach((element) => { resources.data.forEach((element) => {
if (element.type === "lxc" || element.type === "qemu") { if (element.type === "lxc" || element.type === "qemu") {
let nodeName = element.node; const nodeName = element.node;
let nodeStatus = resources.data.find(item => item.node === nodeName && item.type === "node").status; const nodeStatus = resources.data.find(item => item.node === nodeName && item.type === "node").status;
element.node = { name: nodeName, status: nodeStatus }; element.node = { name: nodeName, status: nodeStatus };
instances.push(element); instances.push(element);
} }
@ -59,16 +59,16 @@ async function populateInstances() {
</div> </div>
`; `;
for (let i = 0; i < instances.length; i++) { for (let i = 0; i < instances.length; i++) {
let newInstance = new Instance(); const newInstance = new Instance();
newInstance.data = instances[i]; newInstance.data = instances[i];
instanceContainer.append(newInstance.shadowElement); instanceContainer.append(newInstance.shadowElement);
} }
} }
async function handleInstanceAdd() { async function handleInstanceAdd () {
let header = "Create New Instance"; const header = "Create New Instance";
let body = ` const body = `
<label for="type">Instance Type</label> <label for="type">Instance Type</label>
<select class="w3-select w3-border" name="type" id="type" required> <select class="w3-select w3-border" name="type" id="type" required>
<option value="lxc">Container</option> <option value="lxc">Container</option>
@ -99,9 +99,9 @@ async function handleInstanceAdd() {
<input class="w3-input w3-border container-specific none" name="password" id="password" type="password" required disabled></input> <input class="w3-input w3-border container-specific none" name="password" id="password" type="password" required disabled></input>
`; `;
let d = dialog(header, body, async (result, form) => { const d = dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
let body = { const body = {
node: form.get("node"), node: form.get("node"),
type: form.get("type"), type: form.get("type"),
name: form.get("name"), name: form.get("name"),
@ -116,7 +116,7 @@ async function handleInstanceAdd() {
body.rootfslocation = form.get("rootfs-storage"); body.rootfslocation = form.get("rootfs-storage");
body.rootfssize = form.get("rootfs-size"); body.rootfssize = form.get("rootfs-size");
} }
let result = await requestAPI("/instance", "POST", body); const result = await requestAPI("/instance", "POST", body);
if (result.status === 200) { if (result.status === 200) {
populateInstances(); populateInstances();
} }
@ -127,7 +127,7 @@ async function handleInstanceAdd() {
} }
}); });
let typeSelect = d.querySelector("#type"); const typeSelect = d.querySelector("#type");
typeSelect.selectedIndex = -1; typeSelect.selectedIndex = -1;
typeSelect.addEventListener("change", () => { typeSelect.addEventListener("change", () => {
if (typeSelect.value === "qemu") { if (typeSelect.value === "qemu") {
@ -144,17 +144,17 @@ async function handleInstanceAdd() {
} }
}); });
let templateContent = "iso"; const templateContent = "iso";
let templateStorage = d.querySelector("#template-storage"); const templateStorage = d.querySelector("#template-storage");
templateStorage.selectedIndex = -1; templateStorage.selectedIndex = -1;
let rootfsContent = "rootdir"; const rootfsContent = "rootdir";
let rootfsStorage = d.querySelector("#rootfs-storage"); const rootfsStorage = d.querySelector("#rootfs-storage");
rootfsStorage.selectedIndex = -1; rootfsStorage.selectedIndex = -1;
let nodeSelect = d.querySelector("#node"); const nodeSelect = d.querySelector("#node");
let clusterNodes = await requestPVE("/nodes", "GET"); const clusterNodes = await requestPVE("/nodes", "GET");
let allowedNodes = await requestAPI("/user/config/nodes", "GET"); const allowedNodes = await requestAPI("/user/config/nodes", "GET");
clusterNodes.data.forEach((element) => { clusterNodes.data.forEach((element) => {
if (element.status === "online" && allowedNodes.includes(element.node)) { if (element.status === "online" && allowedNodes.includes(element.node)) {
nodeSelect.add(new Option(element.node)); nodeSelect.add(new Option(element.node));
@ -162,8 +162,8 @@ async function handleInstanceAdd() {
}); });
nodeSelect.selectedIndex = -1; nodeSelect.selectedIndex = -1;
nodeSelect.addEventListener("change", async () => { // change template and rootfs storage based on node nodeSelect.addEventListener("change", async () => { // change template and rootfs storage based on node
let node = nodeSelect.value; const node = nodeSelect.value;
let storage = await requestPVE(`/nodes/${node}/storage`, "GET"); const storage = await requestPVE(`/nodes/${node}/storage`, "GET");
storage.data.forEach((element) => { storage.data.forEach((element) => {
if (element.content.includes(templateContent)) { if (element.content.includes(templateContent)) {
templateStorage.add(new Option(element.storage)); templateStorage.add(new Option(element.storage));
@ -176,11 +176,11 @@ async function handleInstanceAdd() {
rootfsStorage.selectedIndex = -1; rootfsStorage.selectedIndex = -1;
}); });
let templateImage = d.querySelector("#template-image"); // populate templateImage depending on selected image storage const templateImage = d.querySelector("#template-image"); // populate templateImage depending on selected image storage
templateStorage.addEventListener("change", async () => { templateStorage.addEventListener("change", async () => {
templateImage.innerHTML = ``; templateImage.innerHTML = "";
let content = "vztmpl"; const content = "vztmpl";
let images = await requestPVE(`/nodes/${nodeSelect.value}/storage/${templateStorage.value}/content`, "GET"); const images = await requestPVE(`/nodes/${nodeSelect.value}/storage/${templateStorage.value}/content`, "GET");
images.data.forEach((element) => { images.data.forEach((element) => {
if (element.content.includes(content)) { if (element.content.includes(content)) {
templateImage.append(new Option(element.volid.replace(`${templateStorage.value}:${content}/`, ""), element.volid)); templateImage.append(new Option(element.volid.replace(`${templateStorage.value}:${content}/`, ""), element.volid));
@ -189,8 +189,8 @@ async function handleInstanceAdd() {
templateImage.selectedIndex = -1; templateImage.selectedIndex = -1;
}); });
let userResources = await requestAPI("/user/resources", "GET"); const userResources = await requestAPI("/user/resources", "GET");
let userInstances = await requestAPI("/user/config/instances", "GET"); const userInstances = await requestAPI("/user/config/instances", "GET");
d.querySelector("#cores").max = userResources.avail.cores; d.querySelector("#cores").max = userResources.avail.cores;
d.querySelector("#memory").max = userResources.avail.memory; d.querySelector("#memory").max = userResources.avail.memory;
d.querySelector("#vmid").min = userInstances.vmid.min; d.querySelector("#vmid").min = userInstances.vmid.min;
@ -198,8 +198,8 @@ async function handleInstanceAdd() {
} }
class Instance { class Instance {
constructor() { constructor () {
let shadowRoot = document.createElement("div"); const shadowRoot = document.createElement("div");
shadowRoot.classList.add("w3-row"); shadowRoot.classList.add("w3-row");
shadowRoot.innerHTML = ` shadowRoot.innerHTML = `
@ -235,7 +235,17 @@ class Instance {
this.actionLock = false; this.actionLock = false;
} }
set data(data) { get data () {
return {
type: this.type,
status: this.status,
vmid: this.status,
name: this.name,
node: this.node
};
}
set data (data) {
if (data.status === "unknown") { if (data.status === "unknown") {
data.status = "stopped"; data.status = "stopped";
} }
@ -247,65 +257,65 @@ class Instance {
this.update(); this.update();
} }
update() { update () {
let vmidParagraph = this.shadowElement.querySelector("#instance-id"); const vmidParagraph = this.shadowElement.querySelector("#instance-id");
vmidParagraph.innerText = this.vmid; vmidParagraph.innerText = this.vmid;
let nameParagraph = this.shadowElement.querySelector("#instance-name"); const nameParagraph = this.shadowElement.querySelector("#instance-name");
nameParagraph.innerText = this.name ? this.name : ""; nameParagraph.innerText = this.name ? this.name : "";
let typeParagraph = this.shadowElement.querySelector("#instance-type"); const typeParagraph = this.shadowElement.querySelector("#instance-type");
typeParagraph.innerText = this.type; typeParagraph.innerText = this.type;
let statusParagraph = this.shadowElement.querySelector("#instance-status"); const statusParagraph = this.shadowElement.querySelector("#instance-status");
statusParagraph.innerText = this.status; statusParagraph.innerText = this.status;
let statusIcon = this.shadowElement.querySelector("#instance-status-icon"); const statusIcon = this.shadowElement.querySelector("#instance-status-icon");
statusIcon.src = instances_config[this.status].status.src; statusIcon.src = instancesConfig[this.status].status.src;
statusIcon.alt = instances_config[this.status].status.alt; statusIcon.alt = instancesConfig[this.status].status.alt;
let nodeNameParagraph = this.shadowElement.querySelector("#node-name"); const nodeNameParagraph = this.shadowElement.querySelector("#node-name");
nodeNameParagraph.innerText = this.node.name; nodeNameParagraph.innerText = this.node.name;
let nodeStatusParagraph = this.shadowElement.querySelector("#node-status"); const nodeStatusParagraph = this.shadowElement.querySelector("#node-status");
nodeStatusParagraph.innerText = this.node.status; nodeStatusParagraph.innerText = this.node.status;
let nodeStatusIcon = this.shadowElement.querySelector("#node-status-icon"); const nodeStatusIcon = this.shadowElement.querySelector("#node-status-icon");
nodeStatusIcon.src = nodes_config[this.node.status].status.src; nodeStatusIcon.src = nodesConfig[this.node.status].status.src;
nodeStatusIcon.alt = nodes_config[this.node.status].status.src; nodeStatusIcon.alt = nodesConfig[this.node.status].status.src;
let powerButton = this.shadowElement.querySelector("#power-btn"); const powerButton = this.shadowElement.querySelector("#power-btn");
powerButton.src = instances_config[this.status].power.src; powerButton.src = instancesConfig[this.status].power.src;
powerButton.alt = instances_config[this.status].power.alt; powerButton.alt = instancesConfig[this.status].power.alt;
powerButton.title = instances_config[this.status].power.alt; powerButton.title = instancesConfig[this.status].power.alt;
if (instances_config[this.status].power.clickable) { if (instancesConfig[this.status].power.clickable) {
powerButton.classList.add("clickable"); powerButton.classList.add("clickable");
powerButton.onclick = this.handlePowerButton.bind(this) powerButton.onclick = this.handlePowerButton.bind(this);
} }
let configButton = this.shadowElement.querySelector("#configure-btn"); const configButton = this.shadowElement.querySelector("#configure-btn");
configButton.src = instances_config[this.status].config.src; configButton.src = instancesConfig[this.status].config.src;
configButton.alt = instances_config[this.status].config.alt; configButton.alt = instancesConfig[this.status].config.alt;
configButton.title = instances_config[this.status].config.alt; configButton.title = instancesConfig[this.status].config.alt;
if (instances_config[this.status].config.clickable) { if (instancesConfig[this.status].config.clickable) {
configButton.classList.add("clickable"); configButton.classList.add("clickable");
configButton.onclick = this.handleConfigButton.bind(this); configButton.onclick = this.handleConfigButton.bind(this);
} }
let consoleButton = this.shadowElement.querySelector("#console-btn"); const consoleButton = this.shadowElement.querySelector("#console-btn");
consoleButton.src = instances_config[this.status].console.src; consoleButton.src = instancesConfig[this.status].console.src;
consoleButton.alt = instances_config[this.status].console.alt; consoleButton.alt = instancesConfig[this.status].console.alt;
consoleButton.title = instances_config[this.status].console.alt; consoleButton.title = instancesConfig[this.status].console.alt;
if (instances_config[this.status].console.clickable) { if (instancesConfig[this.status].console.clickable) {
consoleButton.classList.add("clickable"); consoleButton.classList.add("clickable");
consoleButton.onclick = this.handleConsoleButton.bind(this); consoleButton.onclick = this.handleConsoleButton.bind(this);
} }
let deleteButton = this.shadowElement.querySelector("#delete-btn"); const deleteButton = this.shadowElement.querySelector("#delete-btn");
deleteButton.src = instances_config[this.status].delete.src; deleteButton.src = instancesConfig[this.status].delete.src;
deleteButton.alt = instances_config[this.status].delete.alt; deleteButton.alt = instancesConfig[this.status].delete.alt;
deleteButton.title = instances_config[this.status].delete.alt; deleteButton.title = instancesConfig[this.status].delete.alt;
if (instances_config[this.status].delete.clickable) { if (instancesConfig[this.status].delete.clickable) {
deleteButton.classList.add("clickable"); deleteButton.classList.add("clickable");
deleteButton.onclick = this.handleDeleteButton.bind(this); deleteButton.onclick = this.handleDeleteButton.bind(this);
} }
@ -318,27 +328,27 @@ class Instance {
} }
} }
async handlePowerButton() { async handlePowerButton () {
if (!this.actionLock) { if (!this.actionLock) {
let header = `${this.status === "running" ? "Stop" : "Start"} VM ${this.vmid}`; const header = `${this.status === "running" ? "Stop" : "Start"} VM ${this.vmid}`;
let body = `<p>Are you sure you want to ${this.status === "running" ? "stop" : "start"} VM</p><p>${this.vmid}</p>` const body = `<p>Are you sure you want to ${this.status === "running" ? "stop" : "start"} VM</p><p>${this.vmid}</p>`;
dialog(header, body, async (result, form) => { dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
this.actionLock = true; this.actionLock = true;
let targetAction = this.status === "running" ? "stop" : "start"; const targetAction = this.status === "running" ? "stop" : "start";
let targetStatus = this.status === "running" ? "stopped" : "running"; const targetStatus = this.status === "running" ? "stopped" : "running";
let prevStatus = this.status; const prevStatus = this.status;
this.status = "loading"; this.status = "loading";
this.update(); this.update();
let result = await requestPVE(`/nodes/${this.node.name}/${this.type}/${this.vmid}/status/${targetAction}`, "POST", { node: this.node.name, vmid: this.vmid }); const result = await requestPVE(`/nodes/${this.node.name}/${this.type}/${this.vmid}/status/${targetAction}`, "POST", { node: this.node.name, vmid: this.vmid });
const waitFor = delay => new Promise(resolve => setTimeout(resolve, delay)); const waitFor = delay => new Promise(resolve => setTimeout(resolve, delay));
while (true) { while (true) {
let taskStatus = await requestPVE(`/nodes/${this.node.name}/tasks/${result.data}/status`, "GET"); const taskStatus = await requestPVE(`/nodes/${this.node.name}/tasks/${result.data}/status`, "GET");
if (taskStatus.data.status === "stopped" && taskStatus.data.exitstatus === "OK") { // task stopped and was successful if (taskStatus.data.status === "stopped" && taskStatus.data.exitstatus === "OK") { // task stopped and was successful
this.status = targetStatus; this.status = targetStatus;
this.update(); this.update();
@ -361,45 +371,43 @@ class Instance {
} }
} }
handleConfigButton() { handleConfigButton () {
if (!this.actionLock && this.status === "stopped") { // if the action lock is false, and the node is stopped, then navigate to the conig page with the node infor in the search query if (!this.actionLock && this.status === "stopped") { // if the action lock is false, and the node is stopped, then navigate to the conig page with the node infor in the search query
goToPage("config.html", { node: this.node.name, type: this.type, vmid: this.vmid }); goToPage("config.html", { node: this.node.name, type: this.type, vmid: this.vmid });
} }
} }
handleConsoleButton() { handleConsoleButton () {
if (!this.actionLock && this.status === "running") { if (!this.actionLock && this.status === "running") {
let data = { console: `${this.type === "qemu" ? "kvm" : "lxc"}`, vmid: this.vmid, vmname: this.name, node: this.node.name, resize: "off", cmd: "" }; const data = { console: `${this.type === "qemu" ? "kvm" : "lxc"}`, vmid: this.vmid, vmname: this.name, node: this.node.name, resize: "off", cmd: "" };
data[`${this.type === "qemu" ? "novnc" : "xtermjs"}`] = 1; data[`${this.type === "qemu" ? "novnc" : "xtermjs"}`] = 1;
goToURL(PVE, data, true); goToURL(PVE, data, true);
} }
} }
handleDeleteButton() { handleDeleteButton () {
if (!this.actionLock && this.status === "stopped") { if (!this.actionLock && this.status === "stopped") {
const header = `Delete VM ${this.vmid}`;
let header = `Delete VM ${this.vmid}`; const body = `<p>Are you sure you want to <strong>delete</strong> VM </p><p>${this.vmid}</p>`;
let body = `<p>Are you sure you want to <strong>delete</strong> VM </p><p>${this.vmid}</p>`
dialog(header, body, async (result, form) => { dialog(header, body, async (result, form) => {
if (result === "confirm") { if (result === "confirm") {
this.actionLock = true; this.actionLock = true;
let prevStatus = this.status;
this.status = "loading"; this.status = "loading";
this.update(); this.update();
let action = {}; const action = {};
action.purge = 1; action.purge = 1;
action["destroy-unreferenced-disks"] = 1; action["destroy-unreferenced-disks"] = 1;
let body = { const body = {
node: this.node.name, node: this.node.name,
type: this.type, type: this.type,
vmid: this.vmid, vmid: this.vmid,
action: JSON.stringify(action) action: JSON.stringify(action)
}; };
let result = await requestAPI("/instance", "DELETE", body); const result = await requestAPI("/instance", "DELETE", body);
if (result.status === 200) { if (result.status === 200) {
this.shadowElement.parentElement.removeChild(this.shadowElement); this.shadowElement.parentElement.removeChild(this.shadowElement);
} }

View File

@ -3,12 +3,12 @@ import { alert } from "./dialog.js";
window.addEventListener("DOMContentLoaded", init); window.addEventListener("DOMContentLoaded", init);
async function init() { async function init () {
setTitleAndHeader(); setTitleAndHeader();
await deleteAllCookies(); await deleteAllCookies();
let formSubmitButton = document.querySelector("#submit"); const formSubmitButton = document.querySelector("#submit");
let realms = await requestPVE("/access/domains", "GET"); const realms = await requestPVE("/access/domains", "GET");
let realmSelect = document.querySelector("#realm"); const realmSelect = document.querySelector("#realm");
realms.data.forEach((element) => { realms.data.forEach((element) => {
realmSelect.add(new Option(element.comment, element.realm)); realmSelect.add(new Option(element.comment, element.realm));
if ("default" in element && element.default === 1) { if ("default" in element && element.default === 1) {
@ -17,11 +17,11 @@ async function init() {
}); });
formSubmitButton.addEventListener("click", async (e) => { formSubmitButton.addEventListener("click", async (e) => {
e.preventDefault(); e.preventDefault();
let form = document.querySelector("form"); const form = document.querySelector("form");
let formData = new FormData(form); const formData = new FormData(form);
formSubmitButton.innerText = "Authenticating..."; formSubmitButton.innerText = "Authenticating...";
let ticket = await requestTicket(formData.get("username"), formData.get("password"), formData.get("realm")); const ticket = await requestTicket(formData.get("username"), formData.get("password"), formData.get("realm"));
if (ticket.status === 200) { if (ticket.status === 200) {
formSubmitButton.innerText = "LOGIN"; formSubmitButton.innerText = "LOGIN";
goToPage("index.html"); goToPage("index.html");

View File

@ -1,6 +1,6 @@
import { API, organization } from "/vars.js"; import { API, organization } from "../../../../../vars.js";
export const resources_config = { export const resourcesConfig = {
disk: { disk: {
actionBarOrder: ["move", "resize", "detach_attach", "delete"], actionBarOrder: ["move", "resize", "detach_attach", "delete"],
lxc: { lxc: {
@ -22,9 +22,9 @@ export const resources_config = {
pcie: { pcie: {
prefix: "hostpci" prefix: "hostpci"
} }
} };
export const instances_config = { export const instancesConfig = {
running: { running: {
status: { status: {
src: "images/status/active.svg", src: "images/status/active.svg",
@ -34,22 +34,22 @@ export const instances_config = {
power: { power: {
src: "images/actions/instance/stop.svg", src: "images/actions/instance/stop.svg",
alt: "Shutdown Instance", alt: "Shutdown Instance",
clickable: true, clickable: true
}, },
config: { config: {
src: "images/actions/instance/config-inactive.svg", src: "images/actions/instance/config-inactive.svg",
alt: "Change Configuration (Inactive)", alt: "Change Configuration (Inactive)",
clickable: false, clickable: false
}, },
console: { console: {
src: "images/actions/instance/console-active.svg", src: "images/actions/instance/console-active.svg",
alt: "Open Console", alt: "Open Console",
clickable: true, clickable: true
}, },
delete: { delete: {
src: "images/actions/delete-inactive.svg", src: "images/actions/delete-inactive.svg",
alt: "Delete Instance (Inactive)", alt: "Delete Instance (Inactive)",
clickable: false, clickable: false
} }
}, },
stopped: { stopped: {
@ -61,22 +61,22 @@ export const instances_config = {
power: { power: {
src: "images/actions/instance/start.svg", src: "images/actions/instance/start.svg",
alt: "Start Instance", alt: "Start Instance",
clickable: true, clickable: true
}, },
config: { config: {
src: "images/actions/instance/config-active.svg", src: "images/actions/instance/config-active.svg",
alt: "Change Configuration", alt: "Change Configuration",
clickable: true, clickable: true
}, },
console: { console: {
src: "images/actions/instance/console-inactive.svg", src: "images/actions/instance/console-inactive.svg",
alt: "Open Console (Inactive)", alt: "Open Console (Inactive)",
clickable: false, clickable: false
}, },
delete: { delete: {
src: "images/actions/delete-active.svg", src: "images/actions/delete-active.svg",
alt: "Delete Instance", alt: "Delete Instance",
clickable: true, clickable: true
} }
}, },
loading: { loading: {
@ -88,27 +88,27 @@ export const instances_config = {
power: { power: {
src: "images/status/loading.svg", src: "images/status/loading.svg",
alt: "Loading Instance", alt: "Loading Instance",
clickable: false, clickable: false
}, },
config: { config: {
src: "images/actions/instance/config-inactive.svg", src: "images/actions/instance/config-inactive.svg",
alt: "Change Configuration (Inactive)", alt: "Change Configuration (Inactive)",
clickable: false, clickable: false
}, },
console: { console: {
src: "images/actions/instance/console-inactive.svg", src: "images/actions/instance/console-inactive.svg",
alt: "Open Console (Inactive)", alt: "Open Console (Inactive)",
clickable: false, clickable: false
}, },
delete: { delete: {
src: "images/actions/delete-inactive.svg", src: "images/actions/delete-inactive.svg",
alt: "Delete Instance (Inactive)", alt: "Delete Instance (Inactive)",
clickable: false, clickable: false
} }
} }
} };
export const nodes_config = { export const nodesConfig = {
online: { online: {
status: { status: {
src: "images/status/active.svg", src: "images/status/active.svg",
@ -127,12 +127,12 @@ export const nodes_config = {
alt: "Node is offline" alt: "Node is offline"
} }
} }
} };
export function getCookie(cname) { export function getCookie (cname) {
let name = cname + "="; const name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie); const decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(";"); const ca = decodedCookie.split(";");
for (let i = 0; i < ca.length; i++) { for (let i = 0; i < ca.length; i++) {
let c = ca[i]; let c = ca[i];
while (c.charAt(0) === " ") { while (c.charAt(0) === " ") {
@ -145,40 +145,40 @@ export function getCookie(cname) {
return ""; return "";
} }
export async function requestTicket(username, password, realm) { export async function requestTicket (username, password, realm) {
let response = await requestAPI("/ticket", "POST", { username: `${username}@${realm}`, password: password }, false); const response = await requestAPI("/ticket", "POST", { username: `${username}@${realm}`, password }, false);
return response; return response;
} }
export async function requestPVE(path, method, body = null) { export async function requestPVE (path, method, body = null) {
let prms = new URLSearchParams(body); const prms = new URLSearchParams(body);
let content = { const content = {
method: method, method,
mode: "cors", mode: "cors",
credentials: "include", credentials: "include",
headers: { headers: {
"Content-Type": "application/x-www-form-urlencoded" "Content-Type": "application/x-www-form-urlencoded"
} }
} };
if (method === "POST") { if (method === "POST") {
content.body = prms.toString(); content.body = prms.toString();
content.headers.CSRFPreventionToken = getCookie("CSRFPreventionToken"); content.headers.CSRFPreventionToken = getCookie("CSRFPreventionToken");
} }
let response = await request(`${API}/proxmox${path}`, content); const response = await request(`${API}/proxmox${path}`, content);
return response; return response;
} }
export async function requestAPI(path, method, body = null) { export async function requestAPI (path, method, body = null) {
let prms = new URLSearchParams(body); const prms = new URLSearchParams(body);
let content = { const content = {
method: method, method,
mode: "cors", mode: "cors",
credentials: "include", credentials: "include",
headers: { headers: {
"Content-Type": "application/x-www-form-urlencoded" "Content-Type": "application/x-www-form-urlencoded"
} }
} };
if (method === "POST" || method === "DELETE") { if (method === "POST" || method === "DELETE") {
content.headers.CSRFPreventionToken = getCookie("CSRFPreventionToken"); content.headers.CSRFPreventionToken = getCookie("CSRFPreventionToken");
} }
@ -186,12 +186,12 @@ export async function requestAPI(path, method, body = null) {
content.body = prms.toString(); content.body = prms.toString();
} }
let response = await request(`${API}${path}`, content); const response = await request(`${API}${path}`, content);
return response; return response;
} }
async function request(url, content) { async function request (url, content) {
let response = await fetch(url, content); const response = await fetch(url, content);
let data = null; let data = null;
try { try {
data = await response.json(); data = await response.json();
@ -206,13 +206,13 @@ async function request(url, content) {
} }
else { else {
data.status = response.status; data.status = response.status;
return data ? data : response; return data || response;
} }
} }
export function goToPage(page, data = {}, newwindow = false) { export function goToPage (page, data = {}, newwindow = false) {
let url = new URL(`https://${window.location.host}/${page}`); const url = new URL(`https://${window.location.host}/${page}`);
for (let k in data) { for (const k in data) {
url.searchParams.append(k, data[k]); url.searchParams.append(k, data[k]);
} }
@ -224,9 +224,9 @@ export function goToPage(page, data = {}, newwindow = false) {
} }
} }
export function goToURL(href, data = {}, newwindow = false) { export function goToURL (href, data = {}, newwindow = false) {
let url = new URL(href); const url = new URL(href);
for (let k in data) { for (const k in data) {
url.searchParams.append(k, data[k]); url.searchParams.append(k, data[k]);
} }
@ -238,16 +238,16 @@ export function goToURL(href, data = {}, newwindow = false) {
} }
} }
export function getURIData() { export function getURIData () {
let url = new URL(window.location.href); const url = new URL(window.location.href);
return Object.fromEntries(url.searchParams); return Object.fromEntries(url.searchParams);
} }
export async function deleteAllCookies() { export async function deleteAllCookies () {
await requestAPI("/ticket", "DELETE"); await requestAPI("/ticket", "DELETE");
} }
export function setTitleAndHeader() { export function setTitleAndHeader () {
document.title = `${organization} - client`; document.title = `${organization} - client`;
document.querySelector("h1").innerText = organization; document.querySelector("h1").innerText = organization;
} }