]> git.proxmox.com Git - proxmox-widget-toolkit.git/blobdiff - src/Utils.js
utils: updateColumnWidth: allow overriding tresholdWidth and make that more general
[proxmox-widget-toolkit.git] / src / Utils.js
index 60c96e0ae54d228406431055e04dcc884646c780..546cd64339e77da34b035963fe7b63bcaf243368 100644 (file)
@@ -48,6 +48,7 @@ utilities: {
     noneText: gettext('none'),
     NoneText: gettext('None'),
     errorText: gettext('Error'),
+    warningsText: gettext('Warnings'),
     unknownText: gettext('Unknown'),
     defaultText: gettext('Default'),
     daysText: gettext('days'),
@@ -237,6 +238,30 @@ utilities: {
        return min < width ? width : min;
     },
 
+    // returns username + realm
+    parse_userid: function(userid) {
+       if (!Ext.isString(userid)) {
+           return [undefined, undefined];
+       }
+
+       let match = userid.match(/^(.+)@([^@]+)$/);
+       if (match !== null) {
+           return [match[1], match[2]];
+       }
+
+       return [undefined, undefined];
+    },
+
+    render_username: function(userid) {
+       let username = Proxmox.Utils.parse_userid(userid)[0] || "";
+       return Ext.htmlEncode(username);
+    },
+
+    render_realm: function(userid) {
+       let username = Proxmox.Utils.parse_userid(userid)[1] || "";
+       return Ext.htmlEncode(username);
+    },
+
     getStoredAuth: function() {
        let storedAuth = JSON.parse(window.localStorage.getItem('ProxmoxUser'));
        return storedAuth || {};
@@ -278,6 +303,16 @@ utilities: {
        window.localStorage.removeItem("ProxmoxUser");
     },
 
+    // The End-User gets redirected back here after login on the OpenID auth. portal, and in the
+    // redirection URL the state and auth.code are passed as URL GET params, this helper parses those
+    getOpenIDRedirectionAuthorization: function() {
+       const auth = Ext.Object.fromQueryString(window.location.search);
+       if (auth.state !== undefined && auth.code !== undefined) {
+           return auth;
+       }
+       return undefined;
+    },
+
     // comp.setLoading() is buggy in ExtJS 4.0.7, so we
     // use el.mask() instead
     setErrorMask: function(comp, msg) {
@@ -316,7 +351,7 @@ utilities: {
        return msg.join('<br>');
     },
 
-    monStoreErrors: function(component, store, clearMaskBeforeLoad) {
+    monStoreErrors: function(component, store, clearMaskBeforeLoad, errorCallback) {
        if (clearMaskBeforeLoad) {
            component.mon(store, 'beforeload', function(s, operation, eOpts) {
                Proxmox.Utils.setErrorMask(component, false);
@@ -341,7 +376,9 @@ utilities: {
 
            let error = request._operation.getError();
            let msg = Proxmox.Utils.getResponseErrorMessage(error);
-           Proxmox.Utils.setErrorMask(component, msg);
+           if (!errorCallback || !errorCallback(error, msg)) {
+               Proxmox.Utils.setErrorMask(component, msg);
+           }
        });
     },
 
@@ -443,6 +480,17 @@ utilities: {
        Ext.Ajax.request(newopts);
     },
 
+    // can be useful for catching displaying errors from the API, e.g.:
+    // Proxmox.Async.api2({
+    //     ...
+    // }).catch(Proxmox.Utils.alertResponseFailure);
+    alertResponseFailure: (response) => {
+       Ext.Msg.alert(
+           gettext('Error'),
+           response.htmlStatus || response.result.message,
+       );
+    },
+
     checked_command: function(orig_cmd) {
        Proxmox.Utils.API2Request(
            {
@@ -496,7 +544,7 @@ utilities: {
        });
     },
 
-    updateColumnWidth: function(container) {
+    updateColumnWidth: function(container, tresholdWidth) {
        let mode = Ext.state.Manager.get('summarycolumns') || 'auto';
        let factor;
        if (mode !== 'auto') {
@@ -505,7 +553,8 @@ utilities: {
                factor = 1;
            }
        } else {
-           factor = container.getSize().width < 1600 ? 1 : 2;
+           tresholdWidth = (tresholdWidth || 1400) + 1;
+           factor = Math.ceil(container.getSize().width / tresholdWidth);
        }
 
        if (container.oldFactor === factor) {
@@ -526,6 +575,9 @@ utilities: {
        container.updateLayout();
     },
 
+    // NOTE: depreacated, use updateColumnWidth
+    updateColumns: container => Proxmox.Utils.updateColumnWidth(container),
+
     dialog_title: function(subject, create, isAdd) {
        if (create) {
            if (isAdd) {
@@ -554,6 +606,7 @@ utilities: {
            Proxmox.Utils.unknownText;
     },
 
+    // NOTE: only add general, product agnostic, ones here! Else use override helper in product repos
     task_desc_table: {
        aptupdate: ['', gettext('Update package database')],
        diskinit: ['Disk', gettext('Initialize Disk with GPT')],
@@ -593,14 +646,22 @@ utilities: {
        return text;
     },
 
-    format_size: function(size) {
-       let units = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'];
-       let num = 0;
-       while (size >= 1024 && num++ <= units.length) {
-           size = size / 1024;
+    format_size: function(size, useSI) {
+       let units = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
+       let order = 0;
+       const baseValue = useSI ? 1000 : 1024;
+       while (size >= baseValue && order < units.length) {
+           size = size / baseValue;
+           order++;
        }
 
-       return size.toFixed(num > 0?2:0) + " " + units[num] + "B";
+       let unit = units[order], commaDigits = 2;
+       if (order === 0) {
+           commaDigits = 0;
+       } else if (!useSI) {
+           unit += 'i';
+       }
+       return `${size.toFixed(commaDigits)} ${unit}B`;
     },
 
     render_upid: function(value, metaData, record) {
@@ -724,6 +785,17 @@ utilities: {
        return 'error';
     },
 
+    format_task_status: function(status) {
+       let parsed = Proxmox.Utils.parse_task_status(status);
+       switch (parsed) {
+           case 'unknown': return Proxmox.Utils.unknownText;
+           case 'error': return Proxmox.Utils.errorText + ': ' + status;
+           case 'warning': return status.replace('WARNINGS', Proxmox.Utils.warningsText);
+           case 'ok': // fall-through
+           default: return status;
+       }
+    },
+
     render_duration: function(value) {
        if (value === undefined) {
            return '-';
@@ -829,6 +901,60 @@ utilities: {
        return value;
     },
 
+    render_usage: val => (val * 100).toFixed(2) + '%',
+
+    render_cpu_usage: function(val, max) {
+       return Ext.String.format(
+           `${gettext('{0}% of {1}')} ${gettext('CPU(s)')}`,
+           (val*100).toFixed(2),
+           max,
+       );
+    },
+
+    render_size_usage: function(val, max, useSI) {
+       if (max === 0) {
+           return gettext('N/A');
+       }
+       let fmt = v => Proxmox.Utils.format_size(v, useSI);
+       let ratio = (val * 100 / max).toFixed(2);
+       return ratio + '% (' + Ext.String.format(gettext('{0} of {1}'), fmt(val), fmt(max)) + ')';
+    },
+
+    render_cpu: function(value, metaData, record, rowIndex, colIndex, store) {
+       if (!(record.data.uptime && Ext.isNumeric(value))) {
+           return '';
+       }
+
+       let maxcpu = record.data.maxcpu || 1;
+       if (!Ext.isNumeric(maxcpu) || maxcpu < 1) {
+           return '';
+       }
+       let cpuText = maxcpu > 1 ? 'CPUs' : 'CPU';
+       let ratio = (value * 100).toFixed(1);
+       return `${ratio}% of ${maxcpu.toString()} ${cpuText}`;
+    },
+
+    render_size: function(value, metaData, record, rowIndex, colIndex, store) {
+       if (!Ext.isNumeric(value)) {
+           return '';
+       }
+       return Proxmox.Utils.format_size(value);
+    },
+
+    render_cpu_model: function(cpu) {
+       let socketText = cpu.sockets > 1 ? gettext('Sockets') : gettext('Socket');
+       return `${cpu.cpus} x ${cpu.model} (${cpu.sockets.toString()} ${socketText})`;
+    },
+
+    /* this is different for nodes */
+    render_node_cpu_usage: function(value, record) {
+       return Proxmox.Utils.render_cpu_usage(value, record.cpus);
+    },
+
+    render_node_size_usage: function(record) {
+       return Proxmox.Utils.render_size_usage(record.used, record.total);
+    },
+
     loadTextFromFile: function(file, callback, maxBytes) {
        let maxSize = maxBytes || 8192;
        if (file.size > maxSize) {
@@ -988,6 +1114,42 @@ utilities: {
        }
        return acme;
     },
+
+    get_health_icon: function(state, circle) {
+       if (circle === undefined) {
+           circle = false;
+       }
+
+       if (state === undefined) {
+           state = 'uknown';
+       }
+
+       var icon = 'faded fa-question';
+       switch (state) {
+           case 'good':
+               icon = 'good fa-check';
+               break;
+           case 'upgrade':
+               icon = 'warning fa-upload';
+               break;
+           case 'old':
+               icon = 'warning fa-refresh';
+               break;
+           case 'warning':
+               icon = 'warning fa-exclamation';
+               break;
+           case 'critical':
+               icon = 'critical fa-times';
+               break;
+           default: break;
+       }
+
+       if (circle) {
+           icon += '-circle';
+       }
+
+       return icon;
+    },
 },
 
     singleton: true,
@@ -1037,3 +1199,23 @@ utilities: {
        me.VlanInterface_match = /(\w+)\.(\d+)/;
     },
 });
+
+Ext.define('Proxmox.Async', {
+    singleton: true,
+
+    // Returns a Promise resolving to the result of an `API2Request` or rejecting to the error
+    // repsonse on failure
+    api2: function(reqOpts) {
+       return new Promise((resolve, reject) => {
+           delete reqOpts.callback; // not allowed in this api
+           reqOpts.success = response => resolve(response);
+           reqOpts.failure = response => reject(response);
+           Proxmox.Utils.API2Request(reqOpts);
+       });
+    },
+
+    // Delay for a number of milliseconds.
+    sleep: function(millis) {
+       return new Promise((resolve, _reject) => setTimeout(resolve, millis));
+    },
+});