1 // NOTE: copied from widget-toolkit's Utils.js, as we only need a few utils
2 // from there, and loading the whole proxmoxlib creates more trouble..
5 Ext
.ns('Proxmox.Setup');
7 if (!Ext
.isDefined(Proxmox
.Setup
.auth_cookie_name
)) {
8 throw "Proxmox library not initialized";
11 // avoid errors when running without development tools
12 if (!Ext
.isDefined(Ext
.global
.console
)) {
24 Ext
.global
.console
= console
;
27 Ext
.Ajax
.defaultHeaders
= {
28 'Accept': 'application/json',
31 Ext
.Ajax
.on('beforerequest', function(conn
, options
) {
32 if (Proxmox
.CSRFPreventionToken
) {
33 if (!options
.headers
) {
36 options
.headers
.CSRFPreventionToken
= Proxmox
.CSRFPreventionToken
;
38 let storedAuth
= Proxmox
.Utils
.getStoredAuth();
39 if (storedAuth
.token
) {
40 options
.headers
.Authorization
= storedAuth
.token
;
44 Ext
.define('Proxmox.Utils', { // a singleton
47 yesText
: gettext('Yes'),
48 noText
: gettext('No'),
49 enabledText
: gettext('Enabled'),
50 disabledText
: gettext('Disabled'),
51 noneText
: gettext('none'),
52 NoneText
: gettext('None'),
53 errorText
: gettext('Error'),
54 warningsText
: gettext('Warnings'),
55 unknownText
: gettext('Unknown'),
56 defaultText
: gettext('Default'),
57 daysText
: gettext('days'),
58 dayText
: gettext('day'),
59 runningText
: gettext('running'),
60 stoppedText
: gettext('stopped'),
61 neverText
: gettext('never'),
62 totalText
: gettext('Total'),
63 usedText
: gettext('Used'),
64 directoryText
: gettext('Directory'),
65 stateText
: gettext('State'),
66 groupText
: gettext('Group'),
68 language_map
: { //language map is sorted alphabetically by iso 639-1
69 ar
: `العربية - ${gettext("Arabic")}`,
70 ca
: `Català - ${gettext("Catalan")}`,
71 da
: `Dansk - ${gettext("Danish")}`,
72 de
: `Deutsch - ${gettext("German")}`,
73 en
: `English - ${gettext("English")}`,
74 es
: `Español - ${gettext("Spanish")}`,
75 eu
: `Euskera (Basque) - ${gettext("Euskera (Basque)")}`,
76 fa
: `فارسی - ${gettext("Persian (Farsi)")}`,
77 fr
: `Français - ${gettext("French")}`,
78 he
: `עברית - ${gettext("Hebrew")}`,
79 it
: `Italiano - ${gettext("Italian")}`,
80 ja
: `日本語 - ${gettext("Japanese")}`,
81 kr
: `한국어 - ${gettext("Korean")}`,
82 nb
: `Bokmål - ${gettext("Norwegian (Bokmal)")}`,
83 nl
: `Nederlands - ${gettext("Dutch")}`,
84 nn
: `Nynorsk - ${gettext("Norwegian (Nynorsk)")}`,
85 pl
: `Polski - ${gettext("Polish")}`,
86 pt_BR
: `Português Brasileiro - ${gettext("Portuguese (Brazil)")}`,
87 ru
: `Русский - ${gettext("Russian")}`,
88 sl
: `Slovenščina - ${gettext("Slovenian")}`,
89 sv
: `Svenska - ${gettext("Swedish")}`,
90 tr
: `Türkçe - ${gettext("Turkish")}`,
91 zh_CN
: `中文(简体)- ${gettext("Chinese (Simplified)")}`,
92 zh_TW
: `中文(繁體)- ${gettext("Chinese (Traditional)")}`,
95 render_language: function(value
) {
96 if (!value
|| value
=== '__default__') {
97 return Proxmox
.Utils
.defaultText
+ ' (English)';
99 let text
= Proxmox
.Utils
.language_map
[value
];
101 return text
+ ' (' + value
+ ')';
106 renderEnabledIcon
: enabled
=> `<i class="fa fa-${enabled ? 'check' : 'minus'}"></i>`,
108 language_array: function() {
109 let data
= [['__default__', Proxmox
.Utils
.render_language('')]];
110 Ext
.Object
.each(Proxmox
.Utils
.language_map
, function(key
, value
) {
111 data
.push([key
, Proxmox
.Utils
.render_language(value
)]);
117 getNoSubKeyHtml: function(url
) {
118 // url http://www.proxmox.com/products/proxmox-ve/subscription-service-plans
119 return Ext
.String
.format('You do not have a valid subscription for this server. Please visit <a target="_blank" href="{0}">www.proxmox.com</a> to get a list of available options.', url
|| 'https://www.proxmox.com');
122 format_boolean_with_default: function(value
) {
123 if (Ext
.isDefined(value
) && value
!== '__default__') {
124 return value
? Proxmox
.Utils
.yesText
: Proxmox
.Utils
.noText
;
126 return Proxmox
.Utils
.defaultText
;
129 format_boolean: function(value
) {
130 return value
? Proxmox
.Utils
.yesText
: Proxmox
.Utils
.noText
;
133 format_neg_boolean: function(value
) {
134 return !value
? Proxmox
.Utils
.yesText
: Proxmox
.Utils
.noText
;
137 format_enabled_toggle: function(value
) {
138 return value
? Proxmox
.Utils
.enabledText
: Proxmox
.Utils
.disabledText
;
141 format_expire: function(date
) {
143 return Proxmox
.Utils
.neverText
;
145 return Ext
.Date
.format(date
, "Y-m-d");
148 // somewhat like a human would tell durations, omit zero values and do not
149 // give seconds precision if we talk days already
150 format_duration_human: function(ut
) {
151 let seconds
= 0, minutes
= 0, hours
= 0, days
= 0, years
= 0;
158 seconds
= Number((remaining
% 60).toFixed(1));
159 remaining
= Math
.trunc(remaining
/ 60);
161 minutes
= remaining
% 60;
162 remaining
= Math
.trunc(remaining
/ 60);
164 hours
= remaining
% 24;
165 remaining
= Math
.trunc(remaining
/ 24);
167 days
= remaining
% 365;
168 remaining
= Math
.trunc(remaining
/ 365); // yea, just lets ignore leap years...
177 let add
= (t
, unit
) => {
178 if (t
> 0) res
.push(t
+ unit
);
182 let addMinutes
= !add(years
, 'y');
183 let addSeconds
= !add(days
, 'd');
191 return res
.join(' ');
194 format_duration_long: function(ut
) {
195 let days
= Math
.floor(ut
/ 86400);
197 let hours
= Math
.floor(ut
/ 3600);
199 let mins
= Math
.floor(ut
/ 60);
202 let hours_str
= '00' + hours
.toString();
203 hours_str
= hours_str
.substr(hours_str
.length
- 2);
204 let mins_str
= "00" + mins
.toString();
205 mins_str
= mins_str
.substr(mins_str
.length
- 2);
206 let ut_str
= "00" + ut
.toString();
207 ut_str
= ut_str
.substr(ut_str
.length
- 2);
210 let ds
= days
> 1 ? Proxmox
.Utils
.daysText
: Proxmox
.Utils
.dayText
;
211 return days
.toString() + ' ' + ds
+ ' ' +
212 hours_str
+ ':' + mins_str
+ ':' + ut_str
;
214 return hours_str
+ ':' + mins_str
+ ':' + ut_str
;
218 format_subscription_level: function(level
) {
221 } else if (level
=== 'b') {
223 } else if (level
=== 's') {
225 } else if (level
=== 'p') {
228 return Proxmox
.Utils
.noneText
;
232 compute_min_label_width: function(text
, width
) {
233 if (width
=== undefined) { width
= 100; }
235 let tm
= new Ext
.util
.TextMetrics();
236 let min
= tm
.getWidth(text
+ ':');
238 return min
< width
? width
: min
;
241 // returns username + realm
242 parse_userid: function(userid
) {
243 if (!Ext
.isString(userid
)) {
244 return [undefined, undefined];
247 let match
= userid
.match(/^(.+)@([^@]+)$/);
248 if (match
!== null) {
249 return [match
[1], match
[2]];
252 return [undefined, undefined];
255 render_username: function(userid
) {
256 let username
= Proxmox
.Utils
.parse_userid(userid
)[0] || "";
257 return Ext
.htmlEncode(username
);
260 render_realm: function(userid
) {
261 let username
= Proxmox
.Utils
.parse_userid(userid
)[1] || "";
262 return Ext
.htmlEncode(username
);
265 getStoredAuth: function() {
266 let storedAuth
= JSON
.parse(window
.localStorage
.getItem('ProxmoxUser'));
267 return storedAuth
|| {};
270 setAuthData: function(data
) {
271 Proxmox
.UserName
= data
.username
;
272 Proxmox
.LoggedOut
= data
.LoggedOut
;
273 // creates a session cookie (expire = null)
274 // that way the cookie gets deleted after the browser window is closed
276 Proxmox
.CSRFPreventionToken
= data
.CSRFPreventionToken
;
277 Ext
.util
.Cookies
.set(Proxmox
.Setup
.auth_cookie_name
, data
.ticket
, null, '/', null, true);
281 window
.localStorage
.setItem('ProxmoxUser', JSON
.stringify(data
));
286 if (Proxmox
.LoggedOut
) {
289 let storedAuth
= Proxmox
.Utils
.getStoredAuth();
290 let cookie
= Ext
.util
.Cookies
.get(Proxmox
.Setup
.auth_cookie_name
);
291 if ((Proxmox
.UserName
!== '' && cookie
&& !cookie
.startsWith("PVE:tfa!")) || storedAuth
.token
) {
292 return cookie
|| storedAuth
.token
;
298 authClear: function() {
299 if (Proxmox
.LoggedOut
) {
302 // ExtJS clear is basically the same, but browser may complain if any cookie isn't "secure"
303 Ext
.util
.Cookies
.set(Proxmox
.Setup
.auth_cookie_name
, "", new Date(0), null, null, true);
304 window
.localStorage
.removeItem("ProxmoxUser");
307 // The End-User gets redirected back here after login on the OpenID auth. portal, and in the
308 // redirection URL the state and auth.code are passed as URL GET params, this helper parses those
309 getOpenIDRedirectionAuthorization: function() {
310 const auth
= Ext
.Object
.fromQueryString(window
.location
.search
);
311 if (auth
.state
!== undefined && auth
.code
!== undefined) {
317 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
318 // use el.mask() instead
319 setErrorMask: function(comp
, msg
) {
326 } else if (msg
=== true) {
327 el
.mask(gettext("Loading..."));
333 getResponseErrorMessage
: (err
) => {
334 if (!err
.statusText
) {
335 return gettext('Connection error');
337 let msg
= [`${err.statusText} (${err.status})`];
338 if (err
.response
&& err
.response
.responseText
) {
339 let txt
= err
.response
.responseText
;
341 let res
= JSON
.parse(txt
);
342 if (res
.errors
&& typeof res
.errors
=== 'object') {
343 for (let [key
, value
] of Object
.entries(res
.errors
)) {
344 msg
.push(Ext
.String
.htmlEncode(`${key}: ${value}`));
348 // fallback to string
349 msg
.push(Ext
.String
.htmlEncode(txt
));
352 return msg
.join('<br>');
355 monStoreErrors: function(component
, store
, clearMaskBeforeLoad
, errorCallback
) {
356 if (clearMaskBeforeLoad
) {
357 component
.mon(store
, 'beforeload', function(s
, operation
, eOpts
) {
358 Proxmox
.Utils
.setErrorMask(component
, false);
361 component
.mon(store
, 'beforeload', function(s
, operation
, eOpts
) {
362 if (!component
.loadCount
) {
363 component
.loadCount
= 0; // make sure it is nucomponent.ic
364 Proxmox
.Utils
.setErrorMask(component
, true);
369 // only works with 'proxmox' proxy
370 component
.mon(store
.proxy
, 'afterload', function(proxy
, request
, success
) {
371 component
.loadCount
++;
374 Proxmox
.Utils
.setErrorMask(component
, false);
378 let error
= request
._operation
.getError();
379 let msg
= Proxmox
.Utils
.getResponseErrorMessage(error
);
380 if (!errorCallback
|| !errorCallback(error
, msg
)) {
381 Proxmox
.Utils
.setErrorMask(component
, msg
);
386 extractRequestError: function(result
, verbose
) {
387 let msg
= gettext('Successful');
389 if (!result
.success
) {
390 msg
= gettext("Unknown error");
391 if (result
.message
) {
392 msg
= Ext
.htmlEncode(result
.message
);
394 msg
+= ` (${result.status})`;
397 if (verbose
&& Ext
.isObject(result
.errors
)) {
399 Ext
.Object
.each(result
.errors
, (prop
, desc
) => {
400 msg
+= `<br><b>${Ext.htmlEncode(prop)}</b>: ${Ext.htmlEncode(desc)}`;
409 API2Request: function(reqOpts
) {
410 let newopts
= Ext
.apply({
411 waitMsg
: gettext('Please wait...'),
414 // default to enable if user isn't handling the failure already explicitly
415 let autoErrorAlert
= reqOpts
.autoErrorAlert
??
416 (typeof reqOpts
.failure
!== 'function' && typeof reqOpts
.callback
!== 'function');
418 if (!newopts
.url
.match(/^\/api2/)) {
419 newopts
.url
= '/api2/extjs' + newopts
.url
;
421 delete newopts
.callback
;
423 let createWrapper = function(successFn
, callbackFn
, failureFn
) {
425 success: function(response
, options
) {
426 if (options
.waitMsgTarget
) {
427 if (Proxmox
.Utils
.toolkit
=== 'touch') {
428 options
.waitMsgTarget
.setMasked(false);
430 options
.waitMsgTarget
.setLoading(false);
433 let result
= Ext
.decode(response
.responseText
);
434 response
.result
= result
;
435 if (!result
.success
) {
436 response
.htmlStatus
= Proxmox
.Utils
.extractRequestError(result
, true);
437 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
438 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
439 if (autoErrorAlert
) {
440 Ext
.Msg
.alert(gettext('Error'), response
.htmlStatus
);
444 Ext
.callback(callbackFn
, options
.scope
, [options
, true, response
]);
445 Ext
.callback(successFn
, options
.scope
, [response
, options
]);
447 failure: function(response
, options
) {
448 if (options
.waitMsgTarget
) {
449 if (Proxmox
.Utils
.toolkit
=== 'touch') {
450 options
.waitMsgTarget
.setMasked(false);
452 options
.waitMsgTarget
.setLoading(false);
455 response
.result
= {};
457 response
.result
= Ext
.decode(response
.responseText
);
461 let msg
= gettext('Connection error') + ' - server offline?';
462 if (response
.aborted
) {
463 msg
= gettext('Connection error') + ' - aborted.';
464 } else if (response
.timedout
) {
465 msg
= gettext('Connection error') + ' - Timeout.';
466 } else if (response
.status
&& response
.statusText
) {
467 msg
= gettext('Connection error') + ' ' + response
.status
+ ': ' + response
.statusText
;
469 response
.htmlStatus
= msg
;
470 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
471 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
476 createWrapper(reqOpts
.success
, reqOpts
.callback
, reqOpts
.failure
);
478 let target
= newopts
.waitMsgTarget
;
480 if (Proxmox
.Utils
.toolkit
=== 'touch') {
481 target
.setMasked({ xtype
: 'loadmask', message
: newopts
.waitMsg
});
483 // Note: ExtJS bug - this does not work when component is not rendered
484 target
.setLoading(newopts
.waitMsg
);
487 Ext
.Ajax
.request(newopts
);
490 // can be useful for catching displaying errors from the API, e.g.:
491 // Proxmox.Async.api2({
493 // }).catch(Proxmox.Utils.alertResponseFailure);
494 alertResponseFailure
: (response
) => {
497 response
.htmlStatus
|| response
.result
.message
,
501 checked_command: function(orig_cmd
) {
502 Proxmox
.Utils
.API2Request(
504 url
: '/nodes/localhost/subscription',
506 failure: function(response
, opts
) {
507 Ext
.Msg
.alert(gettext('Error'), response
.htmlStatus
);
509 success: function(response
, opts
) {
510 let res
= response
.result
;
511 if (res
=== null || res
=== undefined || !res
|| res
512 .data
.status
.toLowerCase() !== 'active') {
514 title
: gettext('No valid subscription'),
515 icon
: Ext
.Msg
.WARNING
,
516 message
: Proxmox
.Utils
.getNoSubKeyHtml(res
.data
.url
),
518 callback: function(btn
) {
533 assemble_field_data: function(values
, data
) {
534 if (!Ext
.isObject(data
)) {
537 Ext
.Object
.each(data
, function(name
, val
) {
538 if (Object
.prototype.hasOwnProperty
.call(values
, name
)) {
539 let bucket
= values
[name
];
540 if (!Ext
.isArray(bucket
)) {
541 bucket
= values
[name
] = [bucket
];
543 if (Ext
.isArray(val
)) {
544 values
[name
] = bucket
.concat(val
);
554 network_iface_types
: {
555 eth
: gettext("Network Device"),
556 bridge
: 'Linux Bridge',
559 OVSBridge
: 'OVS Bridge',
562 OVSIntPort
: 'OVS IntPort',
565 render_network_iface_type: function(value
) {
566 return Proxmox
.Utils
.network_iface_types
[value
] ||
567 Proxmox
.Utils
.unknownText
;
570 // NOTE: only add general, product agnostic, ones here! Else use override helper in product repos
572 aptupdate
: ['', gettext('Update package database')],
573 diskinit
: ['Disk', gettext('Initialize Disk with GPT')],
574 spiceshell
: ['', gettext('Shell') + ' (Spice)'],
575 srvreload
: ['SRV', gettext('Reload')],
576 srvrestart
: ['SRV', gettext('Restart')],
577 srvstart
: ['SRV', gettext('Start')],
578 srvstop
: ['SRV', gettext('Stop')],
579 termproxy
: ['', gettext('Console') + ' (xterm.js)'],
580 vncshell
: ['', gettext('Shell')],
583 // to add or change existing for product specific ones
584 override_task_descriptions: function(extra
) {
585 for (const [key
, value
] of Object
.entries(extra
)) {
586 Proxmox
.Utils
.task_desc_table
[key
] = value
;
590 format_task_description: function(type
, id
) {
591 let farray
= Proxmox
.Utils
.task_desc_table
[type
];
599 } else if (Ext
.isFunction(farray
)) {
600 return farray(type
, id
);
602 let prefix
= farray
[0];
604 if (prefix
&& id
!== undefined) {
605 return prefix
+ ' ' + id
+ ' - ' + text
;
610 format_size: function(size
, useSI
) {
611 let units
= ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
613 const baseValue
= useSI
? 1000 : 1024;
614 while (size
>= baseValue
&& order
< units
.length
) {
615 size
= size
/ baseValue
;
619 let unit
= units
[order
], commaDigits
= 2;
625 return `${size.toFixed(commaDigits)} ${unit}B`;
633 'GiB': 1024*1024*1024,
634 'TiB': 1024*1024*1024*1024,
635 'PiB': 1024*1024*1024*1024*1024,
639 'GB': 1000*1000*1000,
640 'TB': 1000*1000*1000*1000,
641 'PB': 1000*1000*1000*1000*1000,
644 parse_size_unit: function(val
) {
645 //let m = val.match(/([.\d])+\s?([KMGTP]?)(i?)B?\s*$/i);
646 let m
= val
.match(/(\d+(?:\.\d+)?)\s?([KMGTP]?)(i?)B?\s*$/i);
647 let size
= parseFloat(m
[1]);
648 let scale
= m
[2].toUpperCase();
649 let binary
= m
[3].toLowerCase();
651 let unit
= `${scale}${binary}B`;
652 let factor
= Proxmox
.Utils
.SizeUnits
[unit
];
654 return { size
, factor
, unit
, binary
}; // for convenience return all we got
657 size_unit_to_bytes: function(val
) {
658 let { size
, factor
} = Proxmox
.Utils
.parse_size_unit(val
);
659 return size
* factor
;
662 autoscale_size_unit: function(val
) {
663 let { size
, factor
, binary
} = Proxmox
.Utils
.parse_size_unit(val
);
664 return Proxmox
.Utils
.format_size(size
* factor
, binary
!== "i");
667 size_unit_ratios: function(a
, b
) {
668 a
= typeof a
!== "undefined" ? a
: 0;
669 b
= typeof b
!== "undefined" ? b
: Infinity
;
670 let aBytes
= typeof a
=== "number" ? a
: Proxmox
.Utils
.size_unit_to_bytes(a
);
671 let bBytes
= typeof b
=== "number" ? b
: Proxmox
.Utils
.size_unit_to_bytes(b
);
672 return aBytes
/ (bBytes
|| Infinity
); // avoid division by zero
675 render_upid: function(value
, metaData
, record
) {
676 let task
= record
.data
;
677 let type
= task
.type
|| task
.worker_type
;
678 let id
= task
.id
|| task
.worker_id
;
680 return Proxmox
.Utils
.format_task_description(type
, id
);
683 render_uptime: function(value
) {
686 if (uptime
=== undefined) {
694 return Proxmox
.Utils
.format_duration_long(uptime
);
697 systemd_unescape: function(string_value
) {
698 const charcode_0
= '0'.charCodeAt(0);
699 const charcode_9
= '9'.charCodeAt(0);
700 const charcode_A
= 'A'.charCodeAt(0);
701 const charcode_F
= 'F'.charCodeAt(0);
702 const charcode_a
= 'a'.charCodeAt(0);
703 const charcode_f
= 'f'.charCodeAt(0);
704 const charcode_x
= 'x'.charCodeAt(0);
705 const charcode_minus
= '-'.charCodeAt(0);
706 const charcode_slash
= '/'.charCodeAt(0);
707 const charcode_backslash
= '\\'.charCodeAt(0);
709 let parse_hex_digit = function(d
) {
710 if (d
>= charcode_0
&& d
<= charcode_9
) {
711 return d
- charcode_0
;
713 if (d
>= charcode_A
&& d
<= charcode_F
) {
714 return d
- charcode_A
+ 10;
716 if (d
>= charcode_a
&& d
<= charcode_f
) {
717 return d
- charcode_a
+ 10;
719 throw "got invalid hex digit";
722 let value
= new TextEncoder().encode(string_value
);
723 let result
= new Uint8Array(value
.length
);
728 while (i
< value
.length
) {
730 if (c0
=== charcode_minus
) {
731 result
.set([charcode_slash
], result_len
);
736 if ((i
+ 4) < value
.length
) {
738 if (c0
=== charcode_backslash
&& c1
=== charcode_x
) {
739 let h1
= parse_hex_digit(value
[i
+2]);
740 let h0
= parse_hex_digit(value
[i
+3]);
742 result
.set([ord
], result_len
);
748 result
.set([c0
], result_len
);
753 return new TextDecoder().decode(result
.slice(0, result
.len
));
756 parse_task_upid: function(upid
) {
759 let res
= upid
.match(/^UPID:([^\s:]+):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8,9}):(([0-9A-Fa-f]{8,16}):)?([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/);
761 throw "unable to parse upid '" + upid
+ "'";
764 task
.pid
= parseInt(res
[2], 16);
765 task
.pstart
= parseInt(res
[3], 16);
766 if (res
[5] !== undefined) {
767 task
.task_id
= parseInt(res
[5], 16);
769 task
.starttime
= parseInt(res
[6], 16);
771 task
.id
= Proxmox
.Utils
.systemd_unescape(res
[8]);
774 task
.desc
= Proxmox
.Utils
.format_task_description(task
.type
, task
.id
);
779 parse_task_status: function(status
) {
780 if (status
=== 'OK') {
784 if (status
=== 'unknown') {
788 let match
= status
.match(/^WARNINGS: (.*)$/);
796 format_task_status: function(status
) {
797 let parsed
= Proxmox
.Utils
.parse_task_status(status
);
799 case 'unknown': return Proxmox
.Utils
.unknownText
;
800 case 'error': return Proxmox
.Utils
.errorText
+ ': ' + status
;
801 case 'warning': return status
.replace('WARNINGS', Proxmox
.Utils
.warningsText
);
802 case 'ok': // fall-through
803 default: return status
;
807 render_duration: function(value
) {
808 if (value
=== undefined) {
811 return Proxmox
.Utils
.format_duration_human(value
);
814 render_timestamp: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
815 let servertime
= new Date(value
* 1000);
816 return Ext
.Date
.format(servertime
, 'Y-m-d H:i:s');
819 render_zfs_health: function(value
) {
820 if (typeof value
=== 'undefined') {
823 var iconCls
= 'question-circle';
827 iconCls
= 'check-circle good';
831 iconCls
= 'exclamation-circle warning';
836 iconCls
= 'times-circle critical';
841 return '<i class="fa fa-' + iconCls
+ '"></i> ' + value
;
844 get_help_info: function(section
) {
846 if (typeof proxmoxOnlineHelpInfo
!== 'undefined') {
847 helpMap
= proxmoxOnlineHelpInfo
; // eslint-disable-line no-undef
848 } else if (typeof pveOnlineHelpInfo
!== 'undefined') {
849 // be backward compatible with older pve-doc-generators
850 helpMap
= pveOnlineHelpInfo
; // eslint-disable-line no-undef
852 throw "no global OnlineHelpInfo map declared";
855 if (helpMap
[section
]) {
856 return helpMap
[section
];
858 // try to normalize - and _ separators, to support asciidoc and sphinx
859 // references at the same time.
860 let section_minus_normalized
= section
.replace(/_
/g
, '-');
861 if (helpMap
[section_minus_normalized
]) {
862 return helpMap
[section_minus_normalized
];
864 let section_underscore_normalized
= section
.replace(/-/g
, '_');
865 return helpMap
[section_underscore_normalized
];
868 get_help_link: function(section
) {
869 let info
= Proxmox
.Utils
.get_help_info(section
);
873 return window
.location
.origin
+ info
.link
;
876 openXtermJsViewer: function(vmtype
, vmid
, nodename
, vmname
, cmd
) {
877 let url
= Ext
.Object
.toQueryString({
878 console
: vmtype
, // kvm, lxc, upgrade or shell
886 let nw
= window
.open("?" + url
, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
892 render_optional_url: function(value
) {
893 if (value
&& value
.match(/^https?:\/\//) !== null) {
894 return '<a target="_blank" href="' + value
+ '">' + value
+ '</a>';
899 render_san: function(value
) {
901 if (Ext
.isArray(value
)) {
902 value
.forEach(function(val
) {
903 if (!Ext
.isNumber(val
)) {
907 return names
.join('<br>');
912 render_usage
: val
=> (val
* 100).toFixed(2) + '%',
914 render_cpu_usage: function(val
, max
) {
915 return Ext
.String
.format(
916 `${gettext('{0}% of {1}')} ${gettext('CPU(s)')}`,
917 (val
*100).toFixed(2),
922 render_size_usage: function(val
, max
, useSI
) {
924 return gettext('N/A');
926 let fmt
= v
=> Proxmox
.Utils
.format_size(v
, useSI
);
927 let ratio
= (val
* 100 / max
).toFixed(2);
928 return ratio
+ '% (' + Ext
.String
.format(gettext('{0} of {1}'), fmt(val
), fmt(max
)) + ')';
931 render_cpu: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
932 if (!(record
.data
.uptime
&& Ext
.isNumeric(value
))) {
936 let maxcpu
= record
.data
.maxcpu
|| 1;
937 if (!Ext
.isNumeric(maxcpu
) || maxcpu
< 1) {
940 let cpuText
= maxcpu
> 1 ? 'CPUs' : 'CPU';
941 let ratio
= (value
* 100).toFixed(1);
942 return `${ratio}% of ${maxcpu.toString()} ${cpuText}`;
945 render_size: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
946 if (!Ext
.isNumeric(value
)) {
949 return Proxmox
.Utils
.format_size(value
);
952 render_cpu_model: function(cpu
) {
953 let socketText
= cpu
.sockets
> 1 ? gettext('Sockets') : gettext('Socket');
954 return `${cpu.cpus} x ${cpu.model} (${cpu.sockets.toString()} ${socketText})`;
957 /* this is different for nodes */
958 render_node_cpu_usage: function(value
, record
) {
959 return Proxmox
.Utils
.render_cpu_usage(value
, record
.cpus
);
962 render_node_size_usage: function(record
) {
963 return Proxmox
.Utils
.render_size_usage(record
.used
, record
.total
);
966 loadTextFromFile: function(file
, callback
, maxBytes
) {
967 let maxSize
= maxBytes
|| 8192;
968 if (file
.size
> maxSize
) {
969 Ext
.Msg
.alert(gettext('Error'), gettext("Invalid file size: ") + file
.size
);
972 let reader
= new FileReader();
973 reader
.onload
= evt
=> callback(evt
.target
.result
);
974 reader
.readAsText(file
);
977 parsePropertyString: function(value
, defaultKey
) {
981 if (typeof value
!== 'string' || value
=== '') {
985 Ext
.Array
.each(value
.split(','), function(p
) {
986 var kv
= p
.split('=', 2);
987 if (Ext
.isDefined(kv
[1])) {
989 } else if (Ext
.isDefined(defaultKey
)) {
990 if (Ext
.isDefined(res
[defaultKey
])) {
991 error
= 'defaultKey may be only defined once in propertyString';
992 return false; // break
994 res
[defaultKey
] = kv
[0];
996 error
= 'invalid propertyString, not a key=value pair and no defaultKey defined';
997 return false; // break
1002 if (error
!== undefined) {
1003 console
.error(error
);
1010 printPropertyString: function(data
, defaultKey
) {
1011 var stringparts
= [],
1012 gotDefaultKeyVal
= false,
1015 Ext
.Object
.each(data
, function(key
, value
) {
1016 if (defaultKey
!== undefined && key
=== defaultKey
) {
1017 gotDefaultKeyVal
= true;
1018 defaultKeyVal
= value
;
1019 } else if (Ext
.isArray(value
)) {
1020 stringparts
.push(key
+ '=' + value
.join(';'));
1021 } else if (value
!== '') {
1022 stringparts
.push(key
+ '=' + value
);
1026 stringparts
= stringparts
.sort();
1027 if (gotDefaultKeyVal
) {
1028 stringparts
.unshift(defaultKeyVal
);
1031 return stringparts
.join(',');
1034 acmedomain_count
: 5,
1036 parseACMEPluginData: function(data
) {
1039 data
.split('\n').forEach((line
) => {
1040 // capture everything after the first = as value
1041 let [key
, value
] = line
.split('=');
1042 if (value
!== undefined) {
1045 extradata
.push(line
);
1048 return [res
, extradata
];
1051 delete_if_default: function(values
, fieldname
, default_val
, create
) {
1052 if (values
[fieldname
] === '' || values
[fieldname
] === default_val
) {
1054 if (values
.delete) {
1055 if (Ext
.isArray(values
.delete)) {
1056 values
.delete.push(fieldname
);
1058 values
.delete += ',' + fieldname
;
1061 values
.delete = fieldname
;
1065 delete values
[fieldname
];
1069 printACME: function(value
) {
1070 if (Ext
.isArray(value
.domains
)) {
1071 value
.domains
= value
.domains
.join(';');
1073 return Proxmox
.Utils
.printPropertyString(value
);
1076 parseACME: function(value
) {
1084 Ext
.Array
.each(value
.split(','), function(p
) {
1085 var kv
= p
.split('=', 2);
1086 if (Ext
.isDefined(kv
[1])) {
1089 error
= 'Failed to parse key-value pair: '+p
;
1095 if (error
!== undefined) {
1096 console
.error(error
);
1100 if (res
.domains
!== undefined) {
1101 res
.domains
= res
.domains
.split(/;/);
1107 add_domain_to_acme: function(acme
, domain
) {
1108 if (acme
.domains
=== undefined) {
1109 acme
.domains
= [domain
];
1111 acme
.domains
.push(domain
);
1112 acme
.domains
= acme
.domains
.filter((value
, index
, self
) => self
.indexOf(value
) === index
);
1117 remove_domain_from_acme: function(acme
, domain
) {
1118 if (acme
.domains
!== undefined) {
1119 acme
.domains
= acme
.domains
.filter(
1120 (value
, index
, self
) => self
.indexOf(value
) === index
&& value
!== domain
,
1126 get_health_icon: function(state
, circle
) {
1127 if (circle
=== undefined) {
1131 if (state
=== undefined) {
1135 var icon
= 'faded fa-question';
1138 icon
= 'good fa-check';
1141 icon
= 'warning fa-upload';
1144 icon
= 'warning fa-refresh';
1147 icon
= 'warning fa-exclamation';
1150 icon
= 'critical fa-times';
1162 formatNodeRepoStatus: function(status
, product
) {
1163 let fmt
= (txt
, cls
) => `<i class="fa fa-fw fa-lg fa-${cls}"></i>${txt}`;
1165 let getUpdates
= Ext
.String
.format(gettext('{0} updates'), product
);
1166 let noRepo
= Ext
.String
.format(gettext('No {0} repository enabled!'), product
);
1168 if (status
=== 'ok') {
1169 return fmt(getUpdates
, 'check-circle good') + ' ' +
1170 fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good');
1171 } else if (status
=== 'no-sub') {
1172 return fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good') + ' ' +
1173 fmt(gettext('Enterprise repository needs valid subscription'), 'exclamation-circle warning');
1174 } else if (status
=== 'non-production') {
1175 return fmt(getUpdates
, 'check-circle good') + ' ' +
1176 fmt(gettext('Non production-ready repository enabled!'), 'exclamation-circle warning');
1177 } else if (status
=== 'no-repo') {
1178 return fmt(noRepo
, 'exclamation-circle critical');
1181 return Proxmox
.Utils
.unknownText
;
1184 render_u2f_error: function(error
) {
1186 '1': gettext('Other Error'),
1187 '2': gettext('Bad Request'),
1188 '3': gettext('Configuration Unsupported'),
1189 '4': gettext('Device Ineligible'),
1190 '5': gettext('Timeout'),
1192 return "U2F Error: " + ErrorNames
[error
] || Proxmox
.Utils
.unknownText
;
1195 // Convert an ArrayBuffer to a base64url encoded string.
1196 // A `null` value will be preserved for convenience.
1197 bytes_to_base64url: function(bytes
) {
1198 if (bytes
=== null) {
1203 .from(new Uint8Array(bytes
))
1204 .map(val
=> String
.fromCharCode(val
))
1207 .replace(/\+/g, '-')
1208 .replace(/\//g, '_')
1209 .replace(/[=]/g, '');
1212 // Convert an a base64url string to an ArrayBuffer.
1213 // A `null` value will be preserved for convenience.
1214 base64url_to_bytes: function(b64u
) {
1215 if (b64u
=== null) {
1219 return new Uint8Array(
1222 .replace(/_/g, '/'),
1225 .map(val => val.charCodeAt(0)),
1229 stringToRGB: function(string) {
1234 string += 'prox
'; // give short strings more variance
1235 for (let i = 0; i < string.length; i++) {
1236 hash = string.charCodeAt(i) + ((hash << 5) - hash);
1237 hash = hash & hash; // to int
1240 let alpha = 0.7; // make the color a bit brighter
1241 let bg = 255; // assume white background
1244 (hash & 255) * alpha + bg * (1 - alpha),
1245 ((hash >> 8) & 255) * alpha + bg * (1 - alpha),
1246 ((hash >> 16) & 255) * alpha + bg * (1 - alpha),
1250 rgbToCss: function(rgb) {
1251 return `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
1254 rgbToHex: function(rgb) {
1255 let r = Math.round(rgb[0]).toString(16);
1256 let g = Math.round(rgb[1]).toString(16);
1257 let b = Math.round(rgb[2]).toString(16);
1258 return `${r}${g}${b}`;
1261 hexToRGB: function(hex) {
1265 if (hex.length === 7) {
1268 let r = parseInt(hex.slice(0, 2), 16);
1269 let g = parseInt(hex.slice(2, 4), 16);
1270 let b = parseInt(hex.slice(4, 6), 16);
1274 // optimized & simplified SAPC function
1275 // https://github.com/Myndex/SAPC-APCA
1276 getTextContrastClass: function(rgb) {
1277 const blkThrs = 0.022;
1278 const blkClmp = 1.414;
1280 // linearize & gamma correction
1281 let r = (rgb[0] / 255) ** 2.4;
1282 let g = (rgb[1] / 255) ** 2.4;
1283 let b = (rgb[2] / 255) ** 2.4;
1285 // relative luminance sRGB
1286 let bg = r * 0.2126729 + g * 0.7151522 + b * 0.0721750;
1289 bg = bg > blkThrs ? bg : bg + (blkThrs - bg) ** blkClmp;
1291 // SAPC with white text
1292 let contrastLight = bg ** 0.65 - 1;
1293 // SAPC with black text
1294 let contrastDark = bg ** 0.56 - 0.046134502;
1296 if (Math.abs(contrastLight) >= Math.abs(contrastDark)) {
1303 getTagElement: function(string, color_overrides) {
1304 let rgb = color_overrides?.[string] || Proxmox.Utils.stringToRGB(string);
1305 let style = `background-color: ${Proxmox.Utils.rgbToCss(rgb)};`;
1307 if (rgb.length > 3) {
1308 style += `color: ${Proxmox.Utils.rgbToCss([rgb[3], rgb[4], rgb[5]])}`;
1309 cls = "proxmox-tag-dark";
1311 let txtCls = Proxmox.Utils.getTextContrastClass(rgb);
1312 cls = `proxmox-tag-${txtCls}`;
1314 return `<span class="${cls}" style="${style}">${string}</span>`;
1317 // Setting filename here when downloading from a remote url sometimes fails in chromium browsers
1318 // because of a bug when using attribute download in conjunction with a self signed certificate.
1319 // For more info see https://bugs.chromium.org/p/chromium/issues/detail?id=993362
1320 downloadAsFile: function(source, fileName) {
1321 let hiddenElement = document.createElement('a
');
1322 hiddenElement.href = source;
1323 hiddenElement.target = '_blank
';
1325 hiddenElement.download = fileName;
1327 hiddenElement.click();
1332 constructor: function() {
1334 Ext.apply(me, me.utilities);
1336 let IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
1337 let IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
1338 let IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
1339 let IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
1340 let IPV4_CIDR_MASK = "([0-9]{1,2})";
1341 let IPV6_CIDR_MASK = "([0-9]{1,3})";
1344 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
1345 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")/" + IPV4_CIDR_MASK + "$");
1347 /* eslint-disable no-useless-concat,no-multi-spaces */
1348 let IPV6_REGEXP = "(?:" +
1349 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
1350 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
1351 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
1352 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
1353 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
1354 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
1355 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
1356 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
1357 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
1359 /* eslint-enable no-useless-concat,no-multi-spaces */
1361 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
1362 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")/" + IPV6_CIDR_MASK + "$");
1363 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
1365 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
1366 me.IP64_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + "/" + IPV6_CIDR_MASK + ")|(?:" + IPV4_REGEXP + "/" + IPV4_CIDR_MASK + ")$");
1368 let DnsName_REGEXP = "(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-]*[a-zA-Z0-9])?)\\.)*(?:[A-Za-z0-9](?:[A-Za-z0-9\\-]*[A-Za-z0-9])?))";
1369 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
1370 me.DnsName_or_Wildcard_match = new RegExp("^(?:\\*\\.)?" + DnsName_REGEXP + "$");
1372 me.CpuSet_match = /^[0-9]+(?:-[0-9]+)?(?:,[0-9]+(?:-[0-9]+)?)*$/;
1374 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(?::(\\d+))?$");
1375 me.HostPortBrackets_match = new RegExp("^\\[(" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](?::(\\d+))?$");
1376 me.IP6_dotnotation_match = new RegExp("^(" + IPV6_REGEXP + ")(?:\\.(\\d+))?$");
1377 me.Vlan_match = /^vlan(\d+)/;
1378 me.VlanInterface_match = /(\w+)\.(\d+)/;
1382 Ext.define('Proxmox
.Async
', {
1385 // Returns a Promise resolving to the result of an `API2Request` or rejecting to the error
1386 // response on failure
1387 api2: function(reqOpts) {
1388 return new Promise((resolve, reject) => {
1389 delete reqOpts.callback; // not allowed in this api
1390 reqOpts.success = response => resolve(response);
1391 reqOpts.failure = response => reject(response);
1392 Proxmox.Utils.API2Request(reqOpts);
1396 // Delay for a number of milliseconds.
1397 sleep: function(millis) {
1398 return new Promise((resolve, _reject) => setTimeout(resolve, millis));
1402 Ext.override(Ext.data.Store, {
1403 // If the store's proxy is changed
while it is waiting
for an AJAX
1404 // response, `onProxyLoad` will still be called for the outdated response.
1405 // To avoid displaying inconsistent information, only process responses
1406 // belonging to the current proxy. However, do not apply this workaround
1407 // to the mobile UI, as Sencha Touch has an incompatible internal API.
1408 onProxyLoad: function(operation
) {
1410 if (Proxmox
.Utils
.toolkit
=== 'touch' || operation
.getProxy() === me
.getProxy()) {
1411 me
.callParent(arguments
);
1413 console
.log(`ignored outdated response: ${operation.getRequest().getUrl()}`);