add js linting, fix js linting issues

This commit is contained in:
Arthur Lu 2023-06-29 22:20:15 +00:00
parent 5b1aaea2cb
commit 392148852a
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
**/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);
let prefixes = {
const prefixes = {
1024: [
"",
"Ki",
@ -17,17 +17,17 @@ let prefixes = {
"G",
"T"
]
}
};
async function init() {
async function init () {
setTitleAndHeader();
let cookie = document.cookie;
const cookie = document.cookie;
if (cookie === "") {
goToPage("login.html");
}
let resources = await requestAPI("/user/resources");
let instances = await requestAPI("/user/config/cluster");
let nodes = await requestAPI("/user/config/nodes");
const resources = await requestAPI("/user/resources");
const instances = await requestAPI("/user/config/cluster");
const nodes = await requestAPI("/user/config/nodes");
document.querySelector("#username").innerText = `Username: ${getCookie("username")}`;
document.querySelector("#pool").innerText = `Pool: ${instances.pool}`;
document.querySelector("#vmid").innerText = `VMID Range: ${instances.vmid.min} - ${instances.vmid.max}`;
@ -35,24 +35,25 @@ async function init() {
buildResourceTable(resources, "#resource-table");
}
function buildResourceTable(resources, tableid) {
function buildResourceTable (resources, tableid) {
if (resources instanceof Object) {
let table = document.querySelector(tableid);
let tbody = table.querySelector("tbody");
const table = document.querySelector(tableid);
const tbody = table.querySelector("tbody");
Object.keys(resources.resources).forEach((element) => {
if (resources.resources[element].display) {
if (resources.resources[element].type === "list") {
// TODO
console.error("Unimplemented");
}
else {
let row = tbody.insertRow();
let key = row.insertCell();
const row = tbody.insertRow();
const key = row.insertCell();
key.innerText = `${element}`;
let used = row.insertCell();
const used = row.insertCell();
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])}`;
let total = row.insertCell();
const total = row.insertCell();
total.innerText = `${parseNumber(resources.max[element], resources.resources[element])}`;
}
}
@ -60,20 +61,20 @@ function buildResourceTable(resources, tableid) {
}
}
function parseNumber(value, unitData) {
let compact = unitData.compact;
let multiplier = unitData.multiplier;
let base = unitData.base;
let unit = unitData.unit;
function parseNumber (value, unitData) {
const compact = unitData.compact;
const multiplier = unitData.multiplier;
const base = unitData.base;
const unit = unitData.unit;
value = multiplier * value;
if (value <= 0) {
return `0 ${unit}`;
}
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;
let unitPrefix = prefixes[base][exponent];
return `${value} ${unitPrefix}${unit}`
const unitPrefix = prefixes[base][exponent];
return `${value} ${unitPrefix}${unit}`;
}
else {
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";
window.addEventListener("DOMContentLoaded", init); // do the dumb thing where the disk config refreshes every second
let diskMetaData = resources_config.disk;
let networkMetaData = resources_config.network;
let pcieMetaData = resources_config.pcie;
const diskMetaData = resourcesConfig.disk;
const networkMetaData = resourcesConfig.network;
const pcieMetaData = resourcesConfig.pcie;
let node;
let type;
let vmid;
let config;
async function init() {
async function init () {
setTitleAndHeader();
let cookie = document.cookie;
const cookie = document.cookie;
if (cookie === "") {
goToPage("login.html");
}
let uriData = getURIData();
const uriData = getURIData();
node = uriData.node;
type = uriData.type;
vmid = uriData.vmid;
@ -34,37 +34,43 @@ async function init() {
document.querySelector("#exit").addEventListener("click", handleFormExit);
}
function getOrdered(keys) {
let ordered_keys = Object.keys(keys).sort((a, b) => { parseInt(a) - parseInt(b) }); // ordered integer list
return ordered_keys;
function getOrdered (keys) {
const orderedKeys = Object.keys(keys).sort((a, b) => {
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");
}
async function populateResources() {
let name = type === "qemu" ? "name" : "hostname";
async function populateResources () {
const name = type === "qemu" ? "name" : "hostname";
document.querySelector("#name").innerHTML = document.querySelector("#name").innerHTML.replace("%{vmname}", config.data[name]);
if (type === "qemu") {
let global = await requestAPI("/global/config/resources");
let user = await requestAPI("/user/config/resources");
const global = await requestAPI("/global/config/resources");
const user = await requestAPI("/user/config/resources");
let options = [];
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 {
let supported = await requestPVE(`/nodes/${node}/capabilities/qemu/cpu`);
const supported = await requestPVE(`/nodes/${node}/capabilities/qemu/cpu`);
supported.data.forEach((element) => {
if (!user.max.cpu.includes(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("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/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) {
let field = document.querySelector(`#${fieldset}`);
function addResourceLine (fieldset, iconHref, type, labelText, id, attributes, unitText = null) {
const field = document.querySelector(`#${fieldset}`);
let icon = document.createElement("img");
const icon = document.createElement("img");
icon.src = iconHref;
icon.alt = labelText;
field.append(icon);
let label = document.createElement("label");
const label = document.createElement("label");
label.innerText = labelText;
label.htmlFor = labelText;
field.append(label);
if (type === "input") {
let input = document.createElement("input");
for (let k in attributes) {
input.setAttribute(k, attributes[k])
const input = document.createElement("input");
for (const k in attributes) {
input.setAttribute(k, attributes[k]);
}
input.id = id;
input.name = id;
@ -99,8 +105,8 @@ function addResourceLine(fieldset, iconHref, type, labelText, id, attributes, un
field.append(input);
}
else if (type === "select") {
let select = document.createElement("select");
for (let option of attributes.options) {
const select = document.createElement("select");
for (const option of attributes.options) {
select.append(new Option(option));
}
select.value = attributes.value;
@ -113,31 +119,31 @@ function addResourceLine(fieldset, iconHref, type, labelText, id, attributes, un
}
if (unitText) {
let unit = document.createElement("p");
const unit = document.createElement("p");
unit.innerText = unitText;
field.append(unit);
}
else {
let unit = document.createElement("div");
const unit = document.createElement("div");
unit.classList.add("hidden");
field.append(unit);
}
}
async function populateDisk() {
async function populateDisk () {
document.querySelector("#disks").innerHTML = "";
for (let i = 0; i < diskMetaData[type].prefixOrder.length; i++) {
let prefix = diskMetaData[type].prefixOrder[i];
let busName = diskMetaData[type][prefix].name;
let disks = {};
const prefix = diskMetaData[type].prefixOrder[i];
const busName = diskMetaData[type][prefix].name;
const disks = {};
Object.keys(config.data).forEach((element) => {
if (element.startsWith(prefix)) {
disks[element.replace(prefix, "")] = config.data[element];
}
});
let ordered_keys = getOrdered(disks);
ordered_keys.forEach((element) => {
let disk = disks[element];
const orderedKeys = getOrdered(disks);
orderedKeys.forEach((element) => {
const disk = disks[element];
addDiskLine("disks", prefix, busName, element, disk);
});
}
@ -149,36 +155,36 @@ async function populateDisk() {
}
}
function addDiskLine(fieldset, busPrefix, busName, device, diskDetails) {
let field = document.querySelector(`#${fieldset}`);
function addDiskLine (fieldset, busPrefix, busName, device, diskDetails) {
const field = document.querySelector(`#${fieldset}`);
let diskName = `${busName} ${device}`;
let diskID = `${busPrefix}${device}`;
const diskName = `${busName} ${device}`;
const diskID = `${busPrefix}${device}`;
// 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.alt = diskName;
icon.dataset.disk = diskID;
field.append(icon);
// Add a label for the disk bus and device number
let diskLabel = document.createElement("label");
const diskLabel = document.createElement("label");
diskLabel.innerText = diskName;
diskLabel.dataset.disk = diskID;
field.append(diskLabel);
// Add text of the disk configuration
let diskDesc = document.createElement("p");
const diskDesc = document.createElement("p");
diskDesc.innerText = diskDetails;
diskDesc.dataset.disk = diskID;
diskDesc.style.overflowX = "hidden";
diskDesc.style.whiteSpace = "nowrap";
field.append(diskDesc);
let actionDiv = document.createElement("div");
const actionDiv = document.createElement("div");
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
action.src = "images/actions/disk/attach.svg";
action.title = "Attach Disk";
@ -192,7 +198,7 @@ function addDiskLine(fieldset, busPrefix, busName, device, diskDetails) {
action.classList.add("clickable");
}
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.title = "Delete Disk";
if (active === "active") {
@ -201,7 +207,7 @@ function addDiskLine(fieldset, busPrefix, busName, device, diskDetails) {
}
}
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`;
if (active === "active") {
action.title = `${element.charAt(0).toUpperCase()}${element.slice(1)} Disk`;
@ -221,19 +227,19 @@ function addDiskLine(fieldset, busPrefix, busName, device, diskDetails) {
field.append(actionDiv);
}
async function handleDiskDetach() {
let header = `Detach ${this.dataset.disk}`;
let body = `<p>Are you sure you want to detach disk</p><p>${this.dataset.disk}</p>`;
async function handleDiskDetach () {
const header = `Detach ${this.dataset.disk}`;
const body = `<p>Are you sure you want to detach disk</p><p>${this.dataset.disk}</p>`;
dialog(header, body, async (result, form) => {
if (result === "confirm") {
document.querySelector(`img[data-disk="${this.dataset.disk}"]`).src = "images/status/loading.svg";
let body = {
node: node,
type: type,
vmid: vmid,
const body = {
node,
type,
vmid,
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) {
await getConfig();
populateDisk();
@ -247,22 +253,22 @@ async function handleDiskDetach() {
});
}
async function handleDiskAttach() {
let 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>`;
async function handleDiskAttach () {
const header = `Attach ${this.dataset.disk}`;
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) => {
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";
let body = {
node: node,
type: type,
vmid: vmid,
const body = {
node,
type,
vmid,
disk: `${type === "qemu" ? "sata" : "mp"}${device}`,
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) {
await getConfig();
populateDisk();
@ -276,21 +282,21 @@ async function handleDiskAttach() {
});
}
async function handleDiskResize() {
let 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>`;
async function handleDiskResize () {
const header = `Resize ${this.dataset.disk}`;
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) => {
if (result === "confirm") {
document.querySelector(`img[data-disk="${this.dataset.disk}"]`).src = "images/status/loading.svg";
let body = {
node: node,
type: type,
vmid: vmid,
const body = {
node,
type,
vmid,
disk: this.dataset.disk,
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) {
await getConfig();
populateDisk();
@ -304,11 +310,11 @@ async function handleDiskResize() {
});
}
async function handleDiskMove() {
let content = type === "qemu" ? "images" : "rootdir";
let storage = await requestPVE(`/nodes/${node}/storage`, "GET");
async function handleDiskMove () {
const content = type === "qemu" ? "images" : "rootdir";
const storage = await requestPVE(`/nodes/${node}/storage`, "GET");
let header = `Move ${this.dataset.disk}`;
const header = `Move ${this.dataset.disk}`;
let options = "";
storage.data.forEach((element) => {
@ -316,9 +322,9 @@ async function handleDiskMove() {
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}
<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) => {
if (result === "confirm") {
document.querySelector(`img[data-disk="${this.dataset.disk}"]`).src = "images/status/loading.svg";
let body = {
node: node,
type: type,
vmid: vmid,
const body = {
node,
type,
vmid,
disk: this.dataset.disk,
storage: form.get("storage-select"),
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) {
await getConfig();
populateDisk();
@ -348,20 +354,20 @@ async function handleDiskMove() {
});
}
async function handleDiskDelete() {
let header = `Delete ${this.dataset.disk}`;
let body = `<p>Are you sure you want to <strong>delete</strong> disk</p><p>${this.dataset.disk}</p>`;
async function handleDiskDelete () {
const header = `Delete ${this.dataset.disk}`;
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) => {
if (result === "confirm") {
document.querySelector(`img[data-disk="${this.dataset.disk}"]`).src = "images/status/loading.svg";
let body = {
node: node,
type: type,
vmid: vmid,
const body = {
node,
type,
vmid,
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) {
await getConfig();
populateDisk();
@ -375,11 +381,11 @@ async function handleDiskDelete() {
});
}
async function handleDiskAdd() {
let content = type === "qemu" ? "images" : "rootdir";
let storage = await requestPVE(`/nodes/${node}/storage`, "GET");
async function handleDiskAdd () {
const content = type === "qemu" ? "images" : "rootdir";
const storage = await requestPVE(`/nodes/${node}/storage`, "GET");
let header = "Create New Disk";
const header = "Create New Disk";
let options = "";
storage.data.forEach((element) => {
@ -387,9 +393,9 @@ async function handleDiskAdd() {
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>
${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>
@ -397,15 +403,15 @@ async function handleDiskAdd() {
dialog(header, body, async (result, form) => {
if (result === "confirm") {
let body = {
node: node,
type: type,
vmid: vmid,
const body = {
node,
type,
vmid,
disk: `${type === "qemu" ? "sata" : "mp"}${form.get("device")}`,
storage: form.get("storage-select"),
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) {
await getConfig();
populateDisk();
@ -419,11 +425,11 @@ async function handleDiskAdd() {
});
}
async function handleCDAdd() {
let content = "iso";
let storage = await requestPVE(`/nodes/${node}/storage`, "GET");
async function handleCDAdd () {
const content = "iso";
const storage = await requestPVE(`/nodes/${node}/storage`, "GET");
let header = `Add a CDROM`;
const header = "Add a CDROM";
let storageOptions = "";
storage.data.forEach((element) => {
@ -431,24 +437,24 @@ async function handleCDAdd() {
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>
${storageSelect}
<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") {
let body = {
node: node,
type: type,
vmid: vmid,
const body = {
node,
type,
vmid,
disk: `ide${form.get("device")}`,
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) {
await getConfig();
populateDisk();
@ -462,10 +468,10 @@ async function handleCDAdd() {
});
d.querySelector("#storage-select").addEventListener("change", async () => {
let storage = document.querySelector("#storage-select").value;
let ISOSelect = document.querySelector("#iso-select");
ISOSelect.innerHTML = `<option hidden disabled selected value></option>`;
let isos = await requestPVE(`/nodes/${node}/storage/${storage}/content`, "GET", { content: content });
const storage = document.querySelector("#storage-select").value;
const ISOSelect = document.querySelector("#iso-select");
ISOSelect.innerHTML = "<option hidden disabled selected value></option>";
const isos = await requestPVE(`/nodes/${node}/storage/${storage}/content`, "GET", { content });
isos.data.forEach((element) => {
if (element.content.includes(content)) {
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 = "";
let networks = {};
let prefix = networkMetaData.prefix;
const networks = {};
const prefix = networkMetaData.prefix;
Object.keys(config.data).forEach((element) => {
if (element.startsWith(prefix)) {
networks[element.replace(prefix, "")] = config.data[element];
}
});
let ordered_keys = getOrdered(networks);
ordered_keys.forEach((element) => {
const orderedKeys = getOrdered(networks);
orderedKeys.forEach((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) {
let field = document.querySelector(`#${fieldset}`);
function addNetworkLine (fieldset, prefix, netID, netDetails) {
const field = document.querySelector(`#${fieldset}`);
let icon = document.createElement("img");
const icon = document.createElement("img");
icon.src = "images/resources/network.svg";
icon.alt = `${prefix}${netID}`;
icon.dataset.network = netID;
icon.dataset.values = netDetails;
field.appendChild(icon);
let netLabel = document.createElement("label");
const netLabel = document.createElement("label");
netLabel.innerText = `${prefix}${netID}`;
netLabel.dataset.network = netID;
netLabel.dataset.values = netDetails;
field.append(netLabel);
let netDesc = document.createElement("p");
const netDesc = document.createElement("p");
netDesc.innerText = netDetails;
netDesc.dataset.network = netID;
netDesc.dataset.values = netDetails;
@ -515,20 +521,20 @@ function addNetworkLine(fieldset, prefix, netID, netDetails) {
netDesc.style.whiteSpace = "nowrap";
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.src = `images/actions/network/config.svg`;
configBtn.src = "images/actions/network/config.svg";
configBtn.title = "Config Interface";
configBtn.addEventListener("click", handleNetworkConfig);
configBtn.dataset.network = netID;
configBtn.dataset.values = netDetails;
actionDiv.appendChild(configBtn);
let deleteBtn = document.createElement("img");
const deleteBtn = document.createElement("img");
deleteBtn.classList.add("clickable");
deleteBtn.src = `images/actions/delete-active.svg`;
deleteBtn.src = "images/actions/delete-active.svg";
deleteBtn.title = "Delete Interface";
deleteBtn.addEventListener("click", handleNetworkDelete);
deleteBtn.dataset.network = netID;
@ -538,23 +544,23 @@ function addNetworkLine(fieldset, prefix, netID, netDetails) {
field.append(actionDiv);
}
async function handleNetworkConfig() {
let netID = this.dataset.network;
let netDetails = this.dataset.values;
let 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">`;
async function handleNetworkConfig () {
const netID = this.dataset.network;
const netDetails = this.dataset.values;
const header = `Edit net${netID}`;
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") {
document.querySelector(`img[data-network="${netID}"]`).src = "images/status/loading.svg";
let body = {
node: node,
type: type,
vmid: vmid,
const body = {
node,
type,
vmid,
netid: netID,
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) {
await getConfig();
populateNetworks();
@ -570,21 +576,21 @@ async function handleNetworkConfig() {
d.querySelector("#rate").value = netDetails.split("rate=")[1].split(",")[0];
}
async function handleNetworkDelete() {
let netID = this.dataset.network;
let header = `Delete net${netID}`;
let body = ``;
async function handleNetworkDelete () {
const netID = this.dataset.network;
const header = `Delete net${netID}`;
const body = "";
let d = dialog(header, body, async (result, form) => {
const d = dialog(header, body, async (result, form) => {
if (result === "confirm") {
document.querySelector(`img[data-network="${netID}"]`).src = "images/status/loading.svg";
let body = {
node: node,
type: type,
vmid: vmid,
const body = {
node,
type,
vmid,
netid: netID
}
let result = await requestAPI("/instance/network/delete", "DELETE", body);
};
const result = await requestAPI("/instance/network/delete", "DELETE", body);
if (result.status === 200) {
await getConfig();
populateNetworks();
@ -598,26 +604,26 @@ async function handleNetworkDelete() {
});
}
async function handleNetworkAdd() {
let 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">`;
async function handleNetworkAdd () {
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\">";
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") {
let body = {
node: node,
type: type,
vmid: vmid,
const body = {
node,
type,
vmid,
netid: form.get("netid"),
rate: form.get("rate")
}
};
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) {
await getConfig();
populateNetworks();
@ -631,31 +637,31 @@ async function handleNetworkAdd() {
});
}
async function populateDevices() {
async function populateDevices () {
if (type === "qemu") {
document.querySelector("#devices-card").classList.remove("none");
document.querySelector("#devices").innerHTML = "";
let devices = {};
let prefix = pcieMetaData.prefix;
const devices = {};
const prefix = pcieMetaData.prefix;
Object.keys(config.data).forEach((element) => {
if (element.startsWith(prefix)) {
devices[element.replace(prefix, "")] = config.data[element];
}
});
let ordered_keys = getOrdered(devices);
ordered_keys.forEach(async (element) => {
let deviceData = await requestAPI(`/instance/pci?node=${node}&type=${type}&vmid=${vmid}&hostpci=${element}`, "GET");
const orderedKeys = getOrdered(devices);
orderedKeys.forEach(async (element) => {
const deviceData = await requestAPI(`/instance/pci?node=${node}&type=${type}&vmid=${vmid}&hostpci=${element}`, "GET");
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) {
let field = document.querySelector(`#${fieldset}`);
function addDeviceLine (fieldset, prefix, deviceID, deviceDetails, deviceName) {
const field = document.querySelector(`#${fieldset}`);
let icon = document.createElement("img");
const icon = document.createElement("img");
icon.src = "images/resources/device.svg";
icon.alt = `${prefix}${deviceID}`;
icon.dataset.device = deviceID;
@ -663,7 +669,7 @@ function addDeviceLine(fieldset, prefix, deviceID, deviceDetails, deviceName) {
icon.dataset.name = deviceName;
field.appendChild(icon);
let deviceLabel = document.createElement("p");
const deviceLabel = document.createElement("p");
deviceLabel.innerText = deviceName;
deviceLabel.dataset.device = deviceID;
@ -673,11 +679,11 @@ function addDeviceLine(fieldset, prefix, deviceID, deviceDetails, deviceName) {
deviceLabel.style.whiteSpace = "nowrap";
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.src = `images/actions/device/config.svg`;
configBtn.src = "images/actions/device/config.svg";
configBtn.title = "Config Device";
configBtn.addEventListener("click", handleDeviceConfig);
configBtn.dataset.device = deviceID;
@ -685,9 +691,9 @@ function addDeviceLine(fieldset, prefix, deviceID, deviceDetails, deviceName) {
configBtn.dataset.name = deviceName;
actionDiv.appendChild(configBtn);
let deleteBtn = document.createElement("img");
const deleteBtn = document.createElement("img");
deleteBtn.classList.add("clickable");
deleteBtn.src = `images/actions/delete-active.svg`;
deleteBtn.src = "images/actions/delete-active.svg";
deleteBtn.title = "Delete Device";
deleteBtn.addEventListener("click", handleDeviceDelete);
deleteBtn.dataset.device = deviceID;
@ -698,25 +704,25 @@ function addDeviceLine(fieldset, prefix, deviceID, deviceDetails, deviceName) {
field.append(actionDiv);
}
async function handleDeviceConfig() {
let deviceID = this.dataset.device;
let deviceDetails = this.dataset.values;
let deviceName = this.dataset.name;
let 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">`;
async function handleDeviceConfig () {
const deviceID = this.dataset.device;
const deviceDetails = this.dataset.values;
const deviceName = this.dataset.name;
const header = `Edit Expansion Card ${deviceID}`;
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") {
document.querySelector(`img[data-device="${deviceID}"]`).src = "images/status/loading.svg";
let body = {
node: node,
type: type,
vmid: vmid,
const body = {
node,
type,
vmid,
hostpci: deviceID,
device: form.get("device"),
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) {
await getConfig();
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]));
for (let availDevice of availDevices) {
for (const availDevice of availDevices) {
d.querySelector("#device").append(new Option(availDevice.device_name, availDevice.id));
}
d.querySelector("#pcie").checked = deviceDetails.includes("pcie=1");
}
async function handleDeviceDelete() {
let deviceID = this.dataset.device;
let header = `Remove Expansion Card ${deviceID}`;
let body = ``;
async function handleDeviceDelete () {
const deviceID = this.dataset.device;
const header = `Remove Expansion Card ${deviceID}`;
const body = "";
let d = dialog(header, body, async (result, form) => {
const d = dialog(header, body, async (result, form) => {
if (result === "confirm") {
document.querySelector(`img[data-device="${deviceID}"]`).src = "images/status/loading.svg";
let body = {
node: node,
type: type,
vmid: vmid,
const body = {
node,
type,
vmid,
hostpci: deviceID
}
let result = await requestAPI("/instance/pci/delete", "DELETE", body);
};
const result = await requestAPI("/instance/pci/delete", "DELETE", body);
if (result.status === 200) {
await getConfig();
populateDevices();
@ -765,20 +771,20 @@ async function handleDeviceDelete() {
});
}
async function handleDeviceAdd() {
let 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">`;
async function handleDeviceAdd () {
const header = "Add Expansion Card";
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") {
let body = {
node: node,
type: type,
vmid: vmid,
const body = {
node,
type,
vmid,
device: form.get("device"),
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) {
await getConfig();
populateDevices();
@ -791,28 +797,28 @@ async function handleDeviceAdd() {
}
});
let availDevices = await requestAPI(`/nodes/pci?node=${node}`, "GET");
for (let availDevice of availDevices) {
const availDevices = await requestAPI(`/nodes/pci?node=${node}`, "GET");
for (const availDevice of availDevices) {
d.querySelector("#device").append(new Option(availDevice.device_name, availDevice.id));
}
d.querySelector("#pcie").checked = true;
}
async function handleFormExit() {
let body = {
node: node,
type: type,
vmid: vmid,
async function handleFormExit () {
const body = {
node,
type,
vmid,
cores: document.querySelector("#cores").value,
memory: document.querySelector("#ram").value
}
};
if (type === "lxc") {
body.swap = document.querySelector("#swap").value;
}
else if (type === "qemu") {
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) {
await getConfig();
populateDisk();

View File

@ -1,5 +1,5 @@
export function dialog(header, body, callback = async (result, form) => { }) {
let dialog = document.createElement("dialog");
export function dialog (header, body, callback = async (result, form) => { }) {
const dialog = document.createElement("dialog");
dialog.innerHTML = `
<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>
@ -23,8 +23,8 @@ export function dialog(header, body, callback = async (result, form) => { }) {
return dialog;
}
export function alert(message) {
let dialog = document.createElement("dialog");
export function alert (message) {
const dialog = document.createElement("dialog");
dialog.innerHTML = `
<form method="dialog">
<p class="w3-center" style="margin-bottom: 0px;">${message}</p>
@ -40,7 +40,7 @@ export function alert(message) {
dialog.addEventListener("close", () => {
dialog.parentElement.removeChild(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 { PVE } from "../vars.js"
import { PVE } from "../vars.js";
window.addEventListener("DOMContentLoaded", init);
async function init() {
async function init () {
setTitleAndHeader();
let cookie = document.cookie;
const cookie = document.cookie;
if (cookie === "") {
goToPage("login.html");
}
await populateInstances();
let addInstanceBtn = document.querySelector("#instance-add");
const addInstanceBtn = document.querySelector("#instance-add");
addInstanceBtn.addEventListener("click", handleInstanceAdd);
}
async function populateInstances() {
let resources = await requestPVE("/cluster/resources", "GET");
let instanceContainer = document.getElementById("instance-container");
let instances = [];
async function populateInstances () {
const resources = await requestPVE("/cluster/resources", "GET");
const instanceContainer = document.getElementById("instance-container");
const instances = [];
resources.data.forEach((element) => {
if (element.type === "lxc" || element.type === "qemu") {
let nodeName = element.node;
let nodeStatus = resources.data.find(item => item.node === nodeName && item.type === "node").status;
const nodeName = element.node;
const nodeStatus = resources.data.find(item => item.node === nodeName && item.type === "node").status;
element.node = { name: nodeName, status: nodeStatus };
instances.push(element);
}
@ -59,16 +59,16 @@ async function populateInstances() {
</div>
`;
for (let i = 0; i < instances.length; i++) {
let newInstance = new Instance();
const newInstance = new Instance();
newInstance.data = instances[i];
instanceContainer.append(newInstance.shadowElement);
}
}
async function handleInstanceAdd() {
let header = "Create New Instance";
async function handleInstanceAdd () {
const header = "Create New Instance";
let body = `
const body = `
<label for="type">Instance Type</label>
<select class="w3-select w3-border" name="type" id="type" required>
<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>
`;
let d = dialog(header, body, async (result, form) => {
const d = dialog(header, body, async (result, form) => {
if (result === "confirm") {
let body = {
const body = {
node: form.get("node"),
type: form.get("type"),
name: form.get("name"),
@ -116,7 +116,7 @@ async function handleInstanceAdd() {
body.rootfslocation = form.get("rootfs-storage");
body.rootfssize = form.get("rootfs-size");
}
let result = await requestAPI("/instance", "POST", body);
const result = await requestAPI("/instance", "POST", body);
if (result.status === 200) {
populateInstances();
}
@ -127,7 +127,7 @@ async function handleInstanceAdd() {
}
});
let typeSelect = d.querySelector("#type");
const typeSelect = d.querySelector("#type");
typeSelect.selectedIndex = -1;
typeSelect.addEventListener("change", () => {
if (typeSelect.value === "qemu") {
@ -144,17 +144,17 @@ async function handleInstanceAdd() {
}
});
let templateContent = "iso";
let templateStorage = d.querySelector("#template-storage");
const templateContent = "iso";
const templateStorage = d.querySelector("#template-storage");
templateStorage.selectedIndex = -1;
let rootfsContent = "rootdir";
let rootfsStorage = d.querySelector("#rootfs-storage");
const rootfsContent = "rootdir";
const rootfsStorage = d.querySelector("#rootfs-storage");
rootfsStorage.selectedIndex = -1;
let nodeSelect = d.querySelector("#node");
let clusterNodes = await requestPVE("/nodes", "GET");
let allowedNodes = await requestAPI("/user/config/nodes", "GET");
const nodeSelect = d.querySelector("#node");
const clusterNodes = await requestPVE("/nodes", "GET");
const allowedNodes = await requestAPI("/user/config/nodes", "GET");
clusterNodes.data.forEach((element) => {
if (element.status === "online" && allowedNodes.includes(element.node)) {
nodeSelect.add(new Option(element.node));
@ -162,8 +162,8 @@ async function handleInstanceAdd() {
});
nodeSelect.selectedIndex = -1;
nodeSelect.addEventListener("change", async () => { // change template and rootfs storage based on node
let node = nodeSelect.value;
let storage = await requestPVE(`/nodes/${node}/storage`, "GET");
const node = nodeSelect.value;
const storage = await requestPVE(`/nodes/${node}/storage`, "GET");
storage.data.forEach((element) => {
if (element.content.includes(templateContent)) {
templateStorage.add(new Option(element.storage));
@ -176,11 +176,11 @@ async function handleInstanceAdd() {
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 () => {
templateImage.innerHTML = ``;
let content = "vztmpl";
let images = await requestPVE(`/nodes/${nodeSelect.value}/storage/${templateStorage.value}/content`, "GET");
templateImage.innerHTML = "";
const content = "vztmpl";
const images = await requestPVE(`/nodes/${nodeSelect.value}/storage/${templateStorage.value}/content`, "GET");
images.data.forEach((element) => {
if (element.content.includes(content)) {
templateImage.append(new Option(element.volid.replace(`${templateStorage.value}:${content}/`, ""), element.volid));
@ -189,8 +189,8 @@ async function handleInstanceAdd() {
templateImage.selectedIndex = -1;
});
let userResources = await requestAPI("/user/resources", "GET");
let userInstances = await requestAPI("/user/config/instances", "GET");
const userResources = await requestAPI("/user/resources", "GET");
const userInstances = await requestAPI("/user/config/instances", "GET");
d.querySelector("#cores").max = userResources.avail.cores;
d.querySelector("#memory").max = userResources.avail.memory;
d.querySelector("#vmid").min = userInstances.vmid.min;
@ -198,8 +198,8 @@ async function handleInstanceAdd() {
}
class Instance {
constructor() {
let shadowRoot = document.createElement("div");
constructor () {
const shadowRoot = document.createElement("div");
shadowRoot.classList.add("w3-row");
shadowRoot.innerHTML = `
@ -235,7 +235,17 @@ class Instance {
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") {
data.status = "stopped";
}
@ -247,65 +257,65 @@ class Instance {
this.update();
}
update() {
let vmidParagraph = this.shadowElement.querySelector("#instance-id");
update () {
const vmidParagraph = this.shadowElement.querySelector("#instance-id");
vmidParagraph.innerText = this.vmid;
let nameParagraph = this.shadowElement.querySelector("#instance-name");
const nameParagraph = this.shadowElement.querySelector("#instance-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;
let statusParagraph = this.shadowElement.querySelector("#instance-status");
const statusParagraph = this.shadowElement.querySelector("#instance-status");
statusParagraph.innerText = this.status;
let statusIcon = this.shadowElement.querySelector("#instance-status-icon");
statusIcon.src = instances_config[this.status].status.src;
statusIcon.alt = instances_config[this.status].status.alt;
const statusIcon = this.shadowElement.querySelector("#instance-status-icon");
statusIcon.src = instancesConfig[this.status].status.src;
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;
let nodeStatusParagraph = this.shadowElement.querySelector("#node-status");
const nodeStatusParagraph = this.shadowElement.querySelector("#node-status");
nodeStatusParagraph.innerText = this.node.status;
let nodeStatusIcon = this.shadowElement.querySelector("#node-status-icon");
nodeStatusIcon.src = nodes_config[this.node.status].status.src;
nodeStatusIcon.alt = nodes_config[this.node.status].status.src;
const nodeStatusIcon = this.shadowElement.querySelector("#node-status-icon");
nodeStatusIcon.src = nodesConfig[this.node.status].status.src;
nodeStatusIcon.alt = nodesConfig[this.node.status].status.src;
let powerButton = this.shadowElement.querySelector("#power-btn");
powerButton.src = instances_config[this.status].power.src;
powerButton.alt = instances_config[this.status].power.alt;
powerButton.title = instances_config[this.status].power.alt;
if (instances_config[this.status].power.clickable) {
const powerButton = this.shadowElement.querySelector("#power-btn");
powerButton.src = instancesConfig[this.status].power.src;
powerButton.alt = instancesConfig[this.status].power.alt;
powerButton.title = instancesConfig[this.status].power.alt;
if (instancesConfig[this.status].power.clickable) {
powerButton.classList.add("clickable");
powerButton.onclick = this.handlePowerButton.bind(this)
powerButton.onclick = this.handlePowerButton.bind(this);
}
let configButton = this.shadowElement.querySelector("#configure-btn");
configButton.src = instances_config[this.status].config.src;
configButton.alt = instances_config[this.status].config.alt;
configButton.title = instances_config[this.status].config.alt;
if (instances_config[this.status].config.clickable) {
const configButton = this.shadowElement.querySelector("#configure-btn");
configButton.src = instancesConfig[this.status].config.src;
configButton.alt = instancesConfig[this.status].config.alt;
configButton.title = instancesConfig[this.status].config.alt;
if (instancesConfig[this.status].config.clickable) {
configButton.classList.add("clickable");
configButton.onclick = this.handleConfigButton.bind(this);
}
let consoleButton = this.shadowElement.querySelector("#console-btn");
consoleButton.src = instances_config[this.status].console.src;
consoleButton.alt = instances_config[this.status].console.alt;
consoleButton.title = instances_config[this.status].console.alt;
if (instances_config[this.status].console.clickable) {
const consoleButton = this.shadowElement.querySelector("#console-btn");
consoleButton.src = instancesConfig[this.status].console.src;
consoleButton.alt = instancesConfig[this.status].console.alt;
consoleButton.title = instancesConfig[this.status].console.alt;
if (instancesConfig[this.status].console.clickable) {
consoleButton.classList.add("clickable");
consoleButton.onclick = this.handleConsoleButton.bind(this);
}
let deleteButton = this.shadowElement.querySelector("#delete-btn");
deleteButton.src = instances_config[this.status].delete.src;
deleteButton.alt = instances_config[this.status].delete.alt;
deleteButton.title = instances_config[this.status].delete.alt;
if (instances_config[this.status].delete.clickable) {
const deleteButton = this.shadowElement.querySelector("#delete-btn");
deleteButton.src = instancesConfig[this.status].delete.src;
deleteButton.alt = instancesConfig[this.status].delete.alt;
deleteButton.title = instancesConfig[this.status].delete.alt;
if (instancesConfig[this.status].delete.clickable) {
deleteButton.classList.add("clickable");
deleteButton.onclick = this.handleDeleteButton.bind(this);
}
@ -318,27 +328,27 @@ class Instance {
}
}
async handlePowerButton() {
async handlePowerButton () {
if (!this.actionLock) {
let 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 header = `${this.status === "running" ? "Stop" : "Start"} VM ${this.vmid}`;
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) => {
if (result === "confirm") {
this.actionLock = true;
let targetAction = this.status === "running" ? "stop" : "start";
let targetStatus = this.status === "running" ? "stopped" : "running";
let prevStatus = this.status;
const targetAction = this.status === "running" ? "stop" : "start";
const targetStatus = this.status === "running" ? "stopped" : "running";
const prevStatus = this.status;
this.status = "loading";
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));
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
this.status = targetStatus;
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
goToPage("config.html", { node: this.node.name, type: this.type, vmid: this.vmid });
}
}
handleConsoleButton() {
handleConsoleButton () {
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;
goToURL(PVE, data, true);
}
}
handleDeleteButton() {
handleDeleteButton () {
if (!this.actionLock && this.status === "stopped") {
let header = `Delete VM ${this.vmid}`;
let body = `<p>Are you sure you want to <strong>delete</strong> VM </p><p>${this.vmid}</p>`
const header = `Delete VM ${this.vmid}`;
const body = `<p>Are you sure you want to <strong>delete</strong> VM </p><p>${this.vmid}</p>`;
dialog(header, body, async (result, form) => {
if (result === "confirm") {
this.actionLock = true;
let prevStatus = this.status;
this.status = "loading";
this.update();
let action = {};
const action = {};
action.purge = 1;
action["destroy-unreferenced-disks"] = 1;
let body = {
const body = {
node: this.node.name,
type: this.type,
vmid: this.vmid,
action: JSON.stringify(action)
};
let result = await requestAPI("/instance", "DELETE", body);
const result = await requestAPI("/instance", "DELETE", body);
if (result.status === 200) {
this.shadowElement.parentElement.removeChild(this.shadowElement);
}

View File

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