2 Ext
.ns('Proxmox.Setup');
4 if (!Ext
.isDefined(Proxmox
.Setup
.auth_cookie_name
)) {
5 throw "Proxmox library not initialized";
8 // avoid errors when running without development tools
9 if (!Ext
.isDefined(Ext
.global
.console
)) {
21 Ext
.global
.console
= console
;
24 Ext
.Ajax
.defaultHeaders
= {
25 'Accept': 'application/json',
28 Ext
.Ajax
.on('beforerequest', function(conn
, options
) {
29 if (Proxmox
.CSRFPreventionToken
) {
30 if (!options
.headers
) {
33 options
.headers
.CSRFPreventionToken
= Proxmox
.CSRFPreventionToken
;
35 let storedAuth
= Proxmox
.Utils
.getStoredAuth();
36 if (storedAuth
.token
) {
37 options
.headers
.Authorization
= storedAuth
.token
;
41 Ext
.define('Proxmox.Utils', { // a singleton
44 yesText
: gettext('Yes'),
45 noText
: gettext('No'),
46 enabledText
: gettext('Enabled'),
47 disabledText
: gettext('Disabled'),
48 noneText
: gettext('none'),
49 NoneText
: gettext('None'),
50 errorText
: gettext('Error'),
51 warningsText
: gettext('Warnings'),
52 unknownText
: gettext('Unknown'),
53 defaultText
: gettext('Default'),
54 daysText
: gettext('days'),
55 dayText
: gettext('day'),
56 runningText
: gettext('running'),
57 stoppedText
: gettext('stopped'),
58 neverText
: gettext('never'),
59 totalText
: gettext('Total'),
60 usedText
: gettext('Used'),
61 directoryText
: gettext('Directory'),
62 stateText
: gettext('State'),
63 groupText
: gettext('Group'),
65 language_map
: { //language map is sorted alphabetically by iso 639-1
66 ar
: `العربية - ${gettext("Arabic")}`,
67 ca
: `Català - ${gettext("Catalan")}`,
68 da
: `Dansk - ${gettext("Danish")}`,
69 de
: `Deutsch - ${gettext("German")}`,
70 en
: `English - ${gettext("English")}`,
71 es
: `Español - ${gettext("Spanish")}`,
72 eu
: `Euskera (Basque) - ${gettext("Euskera (Basque)")}`,
73 fa
: `فارسی - ${gettext("Persian (Farsi)")}`,
74 fr
: `Français - ${gettext("French")}`,
75 he
: `עברית - ${gettext("Hebrew")}`,
76 it
: `Italiano - ${gettext("Italian")}`,
77 ja
: `日本語 - ${gettext("Japanese")}`,
78 ka
: `ქართული - ${gettext("Georgian")}`,
79 kr
: `한국어 - ${gettext("Korean")}`,
80 nb
: `Bokmål - ${gettext("Norwegian (Bokmal)")}`,
81 nl
: `Nederlands - ${gettext("Dutch")}`,
82 nn
: `Nynorsk - ${gettext("Norwegian (Nynorsk)")}`,
83 pl
: `Polski - ${gettext("Polish")}`,
84 pt_BR
: `Português Brasileiro - ${gettext("Portuguese (Brazil)")}`,
85 ru
: `Русский - ${gettext("Russian")}`,
86 sl
: `Slovenščina - ${gettext("Slovenian")}`,
87 sv
: `Svenska - ${gettext("Swedish")}`,
88 tr
: `Türkçe - ${gettext("Turkish")}`,
89 ukr
: `Українська - ${gettext("Ukrainian")}`,
90 zh_CN
: `中文(简体)- ${gettext("Chinese (Simplified)")}`,
91 zh_TW
: `中文(繁體)- ${gettext("Chinese (Traditional)")}`,
94 render_language: function(value
) {
95 if (!value
|| value
=== '__default__') {
96 return Proxmox
.Utils
.defaultText
+ ' (English)';
98 let text
= Proxmox
.Utils
.language_map
[value
];
100 return text
+ ' (' + value
+ ')';
105 renderEnabledIcon
: enabled
=> `<i class="fa fa-${enabled ? 'check' : 'minus'}"></i>`,
107 language_array: function() {
108 let data
= [['__default__', Proxmox
.Utils
.render_language('')]];
109 Ext
.Object
.each(Proxmox
.Utils
.language_map
, function(key
, value
) {
110 data
.push([key
, Proxmox
.Utils
.render_language(value
)]);
117 crisp
: 'Light theme',
118 "proxmox-dark": 'Proxmox Dark',
121 render_theme: function(value
) {
122 if (!value
|| value
=== '__default__') {
123 return Proxmox
.Utils
.defaultText
+ ' (auto)';
125 let text
= Proxmox
.Utils
.theme_map
[value
];
132 theme_array: function() {
133 let data
= [['__default__', Proxmox
.Utils
.render_theme('')]];
134 Ext
.Object
.each(Proxmox
.Utils
.theme_map
, function(key
, value
) {
135 data
.push([key
, Proxmox
.Utils
.render_theme(value
)]);
141 bond_mode_gettext_map
: {
142 '802.3ad': 'LACP (802.3ad)',
143 'lacp-balance-slb': 'LACP (balance-slb)',
144 'lacp-balance-tcp': 'LACP (balance-tcp)',
147 render_bond_mode
: value
=> Proxmox
.Utils
.bond_mode_gettext_map
[value
] || value
|| '',
149 bond_mode_array: function(modes
) {
150 return modes
.map(mode
=> [mode
, Proxmox
.Utils
.render_bond_mode(mode
)]);
153 getNoSubKeyHtml: function(url
) {
154 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');
157 format_boolean_with_default: function(value
) {
158 if (Ext
.isDefined(value
) && value
!== '__default__') {
159 return value
? Proxmox
.Utils
.yesText
: Proxmox
.Utils
.noText
;
161 return Proxmox
.Utils
.defaultText
;
164 format_boolean: function(value
) {
165 return value
? Proxmox
.Utils
.yesText
: Proxmox
.Utils
.noText
;
168 format_neg_boolean: function(value
) {
169 return !value
? Proxmox
.Utils
.yesText
: Proxmox
.Utils
.noText
;
172 format_enabled_toggle: function(value
) {
173 return value
? Proxmox
.Utils
.enabledText
: Proxmox
.Utils
.disabledText
;
176 format_expire: function(date
) {
178 return Proxmox
.Utils
.neverText
;
180 return Ext
.Date
.format(date
, "Y-m-d");
183 // somewhat like a human would tell durations, omit zero values and do not
184 // give seconds precision if we talk days already
185 format_duration_human: function(ut
) {
186 let seconds
= 0, minutes
= 0, hours
= 0, days
= 0, years
= 0;
193 seconds
= Number((remaining
% 60).toFixed(1));
194 remaining
= Math
.trunc(remaining
/ 60);
196 minutes
= remaining
% 60;
197 remaining
= Math
.trunc(remaining
/ 60);
199 hours
= remaining
% 24;
200 remaining
= Math
.trunc(remaining
/ 24);
202 days
= remaining
% 365;
203 remaining
= Math
.trunc(remaining
/ 365); // yea, just lets ignore leap years...
212 let add
= (t
, unit
) => {
213 if (t
> 0) res
.push(t
+ unit
);
217 let addMinutes
= !add(years
, 'y');
218 let addSeconds
= !add(days
, 'd');
226 return res
.join(' ');
229 format_duration_long: function(ut
) {
230 let days
= Math
.floor(ut
/ 86400);
232 let hours
= Math
.floor(ut
/ 3600);
234 let mins
= Math
.floor(ut
/ 60);
237 let hours_str
= '00' + hours
.toString();
238 hours_str
= hours_str
.substr(hours_str
.length
- 2);
239 let mins_str
= "00" + mins
.toString();
240 mins_str
= mins_str
.substr(mins_str
.length
- 2);
241 let ut_str
= "00" + ut
.toString();
242 ut_str
= ut_str
.substr(ut_str
.length
- 2);
245 let ds
= days
> 1 ? Proxmox
.Utils
.daysText
: Proxmox
.Utils
.dayText
;
246 return days
.toString() + ' ' + ds
+ ' ' +
247 hours_str
+ ':' + mins_str
+ ':' + ut_str
;
249 return hours_str
+ ':' + mins_str
+ ':' + ut_str
;
253 format_subscription_level: function(level
) {
256 } else if (level
=== 'b') {
258 } else if (level
=== 's') {
260 } else if (level
=== 'p') {
263 return Proxmox
.Utils
.noneText
;
267 compute_min_label_width: function(text
, width
) {
268 if (width
=== undefined) { width
= 100; }
270 let tm
= new Ext
.util
.TextMetrics();
271 let min
= tm
.getWidth(text
+ ':');
273 return min
< width
? width
: min
;
276 // returns username + realm
277 parse_userid: function(userid
) {
278 if (!Ext
.isString(userid
)) {
279 return [undefined, undefined];
282 let match
= userid
.match(/^(.+)@([^@]+)$/);
283 if (match
!== null) {
284 return [match
[1], match
[2]];
287 return [undefined, undefined];
290 render_username: function(userid
) {
291 let username
= Proxmox
.Utils
.parse_userid(userid
)[0] || "";
292 return Ext
.htmlEncode(username
);
295 render_realm: function(userid
) {
296 let username
= Proxmox
.Utils
.parse_userid(userid
)[1] || "";
297 return Ext
.htmlEncode(username
);
300 getStoredAuth: function() {
301 let storedAuth
= JSON
.parse(window
.localStorage
.getItem('ProxmoxUser'));
302 return storedAuth
|| {};
305 setAuthData: function(data
) {
306 Proxmox
.UserName
= data
.username
;
307 Proxmox
.LoggedOut
= data
.LoggedOut
;
308 // creates a session cookie (expire = null)
309 // that way the cookie gets deleted after the browser window is closed
311 Proxmox
.CSRFPreventionToken
= data
.CSRFPreventionToken
;
312 Ext
.util
.Cookies
.set(Proxmox
.Setup
.auth_cookie_name
, data
.ticket
, null, '/', null, true, "strict");
316 window
.localStorage
.setItem('ProxmoxUser', JSON
.stringify(data
));
321 if (Proxmox
.LoggedOut
) {
324 let storedAuth
= Proxmox
.Utils
.getStoredAuth();
325 let cookie
= Ext
.util
.Cookies
.get(Proxmox
.Setup
.auth_cookie_name
);
326 if ((Proxmox
.UserName
!== '' && cookie
&& !cookie
.startsWith("PVE:tfa!")) || storedAuth
.token
) {
327 return cookie
|| storedAuth
.token
;
333 authClear: function() {
334 if (Proxmox
.LoggedOut
) {
337 // ExtJS clear is basically the same, but browser may complain if any cookie isn't "secure"
338 Ext
.util
.Cookies
.set(Proxmox
.Setup
.auth_cookie_name
, "", new Date(0), null, null, true, "strict");
339 window
.localStorage
.removeItem("ProxmoxUser");
342 // The End-User gets redirected back here after login on the OpenID auth. portal, and in the
343 // redirection URL the state and auth.code are passed as URL GET params, this helper parses those
344 getOpenIDRedirectionAuthorization: function() {
345 const auth
= Ext
.Object
.fromQueryString(window
.location
.search
);
346 if (auth
.state
!== undefined && auth
.code
!== undefined) {
352 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
353 // use el.mask() instead
354 setErrorMask: function(comp
, msg
) {
361 } else if (msg
=== true) {
362 el
.mask(gettext("Loading..."));
368 getResponseErrorMessage
: (err
) => {
369 if (!err
.statusText
) {
370 return gettext('Connection error');
372 let msg
= [`${err.statusText} (${err.status})`];
373 if (err
.response
&& err
.response
.responseText
) {
374 let txt
= err
.response
.responseText
;
376 let res
= JSON
.parse(txt
);
377 if (res
.errors
&& typeof res
.errors
=== 'object') {
378 for (let [key
, value
] of Object
.entries(res
.errors
)) {
379 msg
.push(Ext
.String
.htmlEncode(`${key}: ${value}`));
383 // fallback to string
384 msg
.push(Ext
.String
.htmlEncode(txt
));
387 return msg
.join('<br>');
390 monStoreErrors: function(component
, store
, clearMaskBeforeLoad
, errorCallback
) {
391 if (clearMaskBeforeLoad
) {
392 component
.mon(store
, 'beforeload', function(s
, operation
, eOpts
) {
393 Proxmox
.Utils
.setErrorMask(component
, false);
396 component
.mon(store
, 'beforeload', function(s
, operation
, eOpts
) {
397 if (!component
.loadCount
) {
398 component
.loadCount
= 0; // make sure it is nucomponent.ic
399 Proxmox
.Utils
.setErrorMask(component
, true);
404 // only works with 'proxmox' proxy
405 component
.mon(store
.proxy
, 'afterload', function(proxy
, request
, success
) {
406 component
.loadCount
++;
409 Proxmox
.Utils
.setErrorMask(component
, false);
413 let error
= request
._operation
.getError();
414 let msg
= Proxmox
.Utils
.getResponseErrorMessage(error
);
415 if (!errorCallback
|| !errorCallback(error
, msg
)) {
416 Proxmox
.Utils
.setErrorMask(component
, msg
);
421 extractRequestError: function(result
, verbose
) {
422 let msg
= gettext('Successful');
424 if (!result
.success
) {
425 msg
= gettext("Unknown error");
426 if (result
.message
) {
427 msg
= Ext
.htmlEncode(result
.message
);
429 msg
+= ` (${result.status})`;
432 if (verbose
&& Ext
.isObject(result
.errors
)) {
434 Ext
.Object
.each(result
.errors
, (prop
, desc
) => {
435 msg
+= `<br><b>${Ext.htmlEncode(prop)}</b>: ${Ext.htmlEncode(desc)}`;
444 API2Request: function(reqOpts
) {
445 let newopts
= Ext
.apply({
446 waitMsg
: gettext('Please wait...'),
449 // default to enable if user isn't handling the failure already explicitly
450 let autoErrorAlert
= reqOpts
.autoErrorAlert
??
451 (typeof reqOpts
.failure
!== 'function' && typeof reqOpts
.callback
!== 'function');
453 if (!newopts
.url
.match(/^\/api2/)) {
454 newopts
.url
= '/api2/extjs' + newopts
.url
;
456 delete newopts
.callback
;
458 let createWrapper = function(successFn
, callbackFn
, failureFn
) {
460 success: function(response
, options
) {
461 if (options
.waitMsgTarget
) {
462 if (Proxmox
.Utils
.toolkit
=== 'touch') {
463 options
.waitMsgTarget
.setMasked(false);
465 options
.waitMsgTarget
.setLoading(false);
468 let result
= Ext
.decode(response
.responseText
);
469 response
.result
= result
;
470 if (!result
.success
) {
471 response
.htmlStatus
= Proxmox
.Utils
.extractRequestError(result
, true);
472 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
473 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
474 if (autoErrorAlert
) {
475 Ext
.Msg
.alert(gettext('Error'), response
.htmlStatus
);
479 Ext
.callback(callbackFn
, options
.scope
, [options
, true, response
]);
480 Ext
.callback(successFn
, options
.scope
, [response
, options
]);
482 failure: function(response
, options
) {
483 if (options
.waitMsgTarget
) {
484 if (Proxmox
.Utils
.toolkit
=== 'touch') {
485 options
.waitMsgTarget
.setMasked(false);
487 options
.waitMsgTarget
.setLoading(false);
490 response
.result
= {};
492 response
.result
= Ext
.decode(response
.responseText
);
496 let msg
= gettext('Connection error') + ' - server offline?';
497 if (response
.aborted
) {
498 msg
= gettext('Connection error') + ' - aborted.';
499 } else if (response
.timedout
) {
500 msg
= gettext('Connection error') + ' - Timeout.';
501 } else if (response
.status
&& response
.statusText
) {
502 msg
= gettext('Connection error') + ' ' + response
.status
+ ': ' + response
.statusText
;
504 response
.htmlStatus
= msg
;
505 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
506 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
511 createWrapper(reqOpts
.success
, reqOpts
.callback
, reqOpts
.failure
);
513 let target
= newopts
.waitMsgTarget
;
515 if (Proxmox
.Utils
.toolkit
=== 'touch') {
516 target
.setMasked({ xtype
: 'loadmask', message
: newopts
.waitMsg
});
518 // Note: ExtJS bug - this does not work when component is not rendered
519 target
.setLoading(newopts
.waitMsg
);
522 Ext
.Ajax
.request(newopts
);
525 // can be useful for catching displaying errors from the API, e.g.:
526 // Proxmox.Async.api2({
528 // }).catch(Proxmox.Utils.alertResponseFailure);
529 alertResponseFailure
: (response
) => {
532 response
.htmlStatus
|| response
.result
.message
,
536 checked_command: function(orig_cmd
) {
537 Proxmox
.Utils
.API2Request(
539 url
: '/nodes/localhost/subscription',
541 failure: function(response
, opts
) {
542 Ext
.Msg
.alert(gettext('Error'), response
.htmlStatus
);
544 success: function(response
, opts
) {
545 let res
= response
.result
;
546 if (res
=== null || res
=== undefined || !res
|| res
547 .data
.status
.toLowerCase() !== 'active') {
549 title
: gettext('No valid subscription'),
550 icon
: Ext
.Msg
.WARNING
,
551 message
: Proxmox
.Utils
.getNoSubKeyHtml(res
.data
.url
),
553 callback: function(btn
) {
568 assemble_field_data: function(values
, data
) {
569 if (!Ext
.isObject(data
)) {
572 Ext
.Object
.each(data
, function(name
, val
) {
573 if (Object
.prototype.hasOwnProperty
.call(values
, name
)) {
574 let bucket
= values
[name
];
575 if (!Ext
.isArray(bucket
)) {
576 bucket
= values
[name
] = [bucket
];
578 if (Ext
.isArray(val
)) {
579 values
[name
] = bucket
.concat(val
);
589 updateColumnWidth: function(container
, thresholdWidth
) {
590 let mode
= Ext
.state
.Manager
.get('summarycolumns') || 'auto';
592 if (mode
!== 'auto') {
593 factor
= parseInt(mode
, 10);
594 if (Number
.isNaN(factor
)) {
598 thresholdWidth
= (thresholdWidth
|| 1400) + 1;
599 factor
= Math
.ceil(container
.getSize().width
/ thresholdWidth
);
602 if (container
.oldFactor
=== factor
) {
606 let items
= container
.query('>'); // direct children
607 factor
= Math
.min(factor
, items
.length
);
608 container
.oldFactor
= factor
;
610 items
.forEach((item
) => {
611 item
.columnWidth
= 1 / factor
;
614 // we have to update the layout twice, since the first layout change
615 // can trigger the scrollbar which reduces the amount of space left
616 container
.updateLayout();
617 container
.updateLayout();
620 // NOTE: depreacated, use updateColumnWidth
621 updateColumns
: container
=> Proxmox
.Utils
.updateColumnWidth(container
),
623 dialog_title: function(subject
, create
, isAdd
) {
626 return gettext('Add') + ': ' + subject
;
628 return gettext('Create') + ': ' + subject
;
631 return gettext('Edit') + ': ' + subject
;
635 network_iface_types
: {
636 eth
: gettext("Network Device"),
637 bridge
: 'Linux Bridge',
640 OVSBridge
: 'OVS Bridge',
643 OVSIntPort
: 'OVS IntPort',
646 render_network_iface_type: function(value
) {
647 return Proxmox
.Utils
.network_iface_types
[value
] ||
648 Proxmox
.Utils
.unknownText
;
651 // NOTE: only add general, product agnostic, ones here! Else use override helper in product repos
653 aptupdate
: ['', gettext('Update package database')],
654 diskinit
: ['Disk', gettext('Initialize Disk with GPT')],
655 spiceshell
: ['', gettext('Shell') + ' (Spice)'],
656 srvreload
: ['SRV', gettext('Reload')],
657 srvrestart
: ['SRV', gettext('Restart')],
658 srvstart
: ['SRV', gettext('Start')],
659 srvstop
: ['SRV', gettext('Stop')],
660 termproxy
: ['', gettext('Console') + ' (xterm.js)'],
661 vncshell
: ['', gettext('Shell')],
664 // to add or change existing for product specific ones
665 override_task_descriptions: function(extra
) {
666 for (const [key
, value
] of Object
.entries(extra
)) {
667 Proxmox
.Utils
.task_desc_table
[key
] = value
;
671 format_task_description: function(type
, id
) {
672 let farray
= Proxmox
.Utils
.task_desc_table
[type
];
680 } else if (Ext
.isFunction(farray
)) {
681 return farray(type
, id
);
683 let prefix
= farray
[0];
685 if (prefix
&& id
!== undefined) {
686 return prefix
+ ' ' + id
+ ' - ' + text
;
691 format_size: function(size
, useSI
) {
692 let unitsSI
= [gettext('B'), gettext('KB'), gettext('MB'), gettext('GB'),
693 gettext('TB'), gettext('PB'), gettext('EB'), gettext('ZB'), gettext('YB')];
694 let unitsIEC
= [gettext('B'), gettext('KiB'), gettext('MiB'), gettext('GiB'),
695 gettext('TiB'), gettext('PiB'), gettext('EiB'), gettext('ZiB'), gettext('YiB')];
698 const baseValue
= useSI
? 1000 : 1024;
699 while (size
>= baseValue
&& order
< unitsSI
.length
) {
700 size
= size
/ baseValue
;
704 let unit
= useSI
? unitsSI
[order
] : unitsIEC
[order
];
708 return `${size.toFixed(commaDigits)} ${unit}`;
716 'GiB': 1024*1024*1024,
717 'TiB': 1024*1024*1024*1024,
718 'PiB': 1024*1024*1024*1024*1024,
722 'GB': 1000*1000*1000,
723 'TB': 1000*1000*1000*1000,
724 'PB': 1000*1000*1000*1000*1000,
727 parse_size_unit: function(val
) {
728 //let m = val.match(/([.\d])+\s?([KMGTP]?)(i?)B?\s*$/i);
729 let m
= val
.match(/(\d+(?:\.\d+)?)\s?([KMGTP]?)(i?)B?\s*$/i);
730 let size
= parseFloat(m
[1]);
731 let scale
= m
[2].toUpperCase();
732 let binary
= m
[3].toLowerCase();
734 let unit
= `${scale}${binary}B`;
735 let factor
= Proxmox
.Utils
.SizeUnits
[unit
];
737 return { size
, factor
, unit
, binary
}; // for convenience return all we got
740 size_unit_to_bytes: function(val
) {
741 let { size
, factor
} = Proxmox
.Utils
.parse_size_unit(val
);
742 return size
* factor
;
745 autoscale_size_unit: function(val
) {
746 let { size
, factor
, binary
} = Proxmox
.Utils
.parse_size_unit(val
);
747 return Proxmox
.Utils
.format_size(size
* factor
, binary
!== "i");
750 size_unit_ratios: function(a
, b
) {
751 a
= typeof a
!== "undefined" ? a
: 0;
752 b
= typeof b
!== "undefined" ? b
: Infinity
;
753 let aBytes
= typeof a
=== "number" ? a
: Proxmox
.Utils
.size_unit_to_bytes(a
);
754 let bBytes
= typeof b
=== "number" ? b
: Proxmox
.Utils
.size_unit_to_bytes(b
);
755 return aBytes
/ (bBytes
|| Infinity
); // avoid division by zero
758 render_upid: function(value
, metaData
, record
) {
759 let task
= record
.data
;
760 let type
= task
.type
|| task
.worker_type
;
761 let id
= task
.id
|| task
.worker_id
;
763 return Proxmox
.Utils
.format_task_description(type
, id
);
766 render_uptime: function(value
) {
769 if (uptime
=== undefined) {
777 return Proxmox
.Utils
.format_duration_long(uptime
);
780 systemd_unescape: function(string_value
) {
781 const charcode_0
= '0'.charCodeAt(0);
782 const charcode_9
= '9'.charCodeAt(0);
783 const charcode_A
= 'A'.charCodeAt(0);
784 const charcode_F
= 'F'.charCodeAt(0);
785 const charcode_a
= 'a'.charCodeAt(0);
786 const charcode_f
= 'f'.charCodeAt(0);
787 const charcode_x
= 'x'.charCodeAt(0);
788 const charcode_minus
= '-'.charCodeAt(0);
789 const charcode_slash
= '/'.charCodeAt(0);
790 const charcode_backslash
= '\\'.charCodeAt(0);
792 let parse_hex_digit = function(d
) {
793 if (d
>= charcode_0
&& d
<= charcode_9
) {
794 return d
- charcode_0
;
796 if (d
>= charcode_A
&& d
<= charcode_F
) {
797 return d
- charcode_A
+ 10;
799 if (d
>= charcode_a
&& d
<= charcode_f
) {
800 return d
- charcode_a
+ 10;
802 throw "got invalid hex digit";
805 let value
= new TextEncoder().encode(string_value
);
806 let result
= new Uint8Array(value
.length
);
811 while (i
< value
.length
) {
813 if (c0
=== charcode_minus
) {
814 result
.set([charcode_slash
], result_len
);
819 if ((i
+ 4) < value
.length
) {
821 if (c0
=== charcode_backslash
&& c1
=== charcode_x
) {
822 let h1
= parse_hex_digit(value
[i
+2]);
823 let h0
= parse_hex_digit(value
[i
+3]);
825 result
.set([ord
], result_len
);
831 result
.set([c0
], result_len
);
836 return new TextDecoder().decode(result
.slice(0, result
.len
));
839 parse_task_upid: function(upid
) {
842 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]+):$/);
844 throw "unable to parse upid '" + upid
+ "'";
847 task
.pid
= parseInt(res
[2], 16);
848 task
.pstart
= parseInt(res
[3], 16);
849 if (res
[5] !== undefined) {
850 task
.task_id
= parseInt(res
[5], 16);
852 task
.starttime
= parseInt(res
[6], 16);
854 task
.id
= Proxmox
.Utils
.systemd_unescape(res
[8]);
857 task
.desc
= Proxmox
.Utils
.format_task_description(task
.type
, task
.id
);
862 parse_task_status: function(status
) {
863 if (status
=== 'OK') {
867 if (status
=== 'unknown') {
871 let match
= status
.match(/^WARNINGS: (.*)$/);
879 format_task_status: function(status
) {
880 let parsed
= Proxmox
.Utils
.parse_task_status(status
);
882 case 'unknown': return Proxmox
.Utils
.unknownText
;
883 case 'error': return Proxmox
.Utils
.errorText
+ ': ' + status
;
884 case 'warning': return status
.replace('WARNINGS', Proxmox
.Utils
.warningsText
);
885 case 'ok': // fall-through
886 default: return status
;
890 render_duration: function(value
) {
891 if (value
=== undefined) {
894 return Proxmox
.Utils
.format_duration_human(value
);
897 render_timestamp: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
898 let servertime
= new Date(value
* 1000);
899 return Ext
.Date
.format(servertime
, 'Y-m-d H:i:s');
902 render_zfs_health: function(value
) {
903 if (typeof value
=== 'undefined') {
906 var iconCls
= 'question-circle';
910 iconCls
= 'check-circle good';
914 iconCls
= 'exclamation-circle warning';
919 iconCls
= 'times-circle critical';
924 return '<i class="fa fa-' + iconCls
+ '"></i> ' + value
;
927 get_help_info: function(section
) {
929 if (typeof proxmoxOnlineHelpInfo
!== 'undefined') {
930 helpMap
= proxmoxOnlineHelpInfo
; // eslint-disable-line no-undef
931 } else if (typeof pveOnlineHelpInfo
!== 'undefined') {
932 // be backward compatible with older pve-doc-generators
933 helpMap
= pveOnlineHelpInfo
; // eslint-disable-line no-undef
935 throw "no global OnlineHelpInfo map declared";
938 if (helpMap
[section
]) {
939 return helpMap
[section
];
941 // try to normalize - and _ separators, to support asciidoc and sphinx
942 // references at the same time.
943 let section_minus_normalized
= section
.replace(/_
/g
, '-');
944 if (helpMap
[section_minus_normalized
]) {
945 return helpMap
[section_minus_normalized
];
947 let section_underscore_normalized
= section
.replace(/-/g
, '_');
948 return helpMap
[section_underscore_normalized
];
951 get_help_link: function(section
) {
952 let info
= Proxmox
.Utils
.get_help_info(section
);
956 return window
.location
.origin
+ info
.link
;
959 openXtermJsViewer: function(vmtype
, vmid
, nodename
, vmname
, cmd
) {
960 let url
= Ext
.Object
.toQueryString({
961 console
: vmtype
, // kvm, lxc, upgrade or shell
969 let nw
= window
.open("?" + url
, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
975 render_optional_url: function(value
) {
976 if (value
&& value
.match(/^https?:\/\//) !== null) {
977 return '<a target="_blank" href="' + value
+ '">' + value
+ '</a>';
982 render_san: function(value
) {
984 if (Ext
.isArray(value
)) {
985 value
.forEach(function(val
) {
986 if (!Ext
.isNumber(val
)) {
990 return names
.join('<br>');
995 render_usage
: val
=> (val
* 100).toFixed(2) + '%',
997 render_cpu_usage: function(val
, max
) {
998 return Ext
.String
.format(
999 `${gettext('{0}% of {1}')} ${gettext('CPU(s)')}`,
1000 (val
*100).toFixed(2),
1005 render_size_usage: function(val
, max
, useSI
) {
1007 return gettext('N/A');
1009 let fmt
= v
=> Proxmox
.Utils
.format_size(v
, useSI
);
1010 let ratio
= (val
* 100 / max
).toFixed(2);
1011 return ratio
+ '% (' + Ext
.String
.format(gettext('{0} of {1}'), fmt(val
), fmt(max
)) + ')';
1014 render_cpu: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
1015 if (!(record
.data
.uptime
&& Ext
.isNumeric(value
))) {
1019 let maxcpu
= record
.data
.maxcpu
|| 1;
1020 if (!Ext
.isNumeric(maxcpu
) || maxcpu
< 1) {
1023 let cpuText
= maxcpu
> 1 ? 'CPUs' : 'CPU';
1024 let ratio
= (value
* 100).toFixed(1);
1025 return `${ratio}% of ${maxcpu.toString()} ${cpuText}`;
1028 render_size: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
1029 if (!Ext
.isNumeric(value
)) {
1032 return Proxmox
.Utils
.format_size(value
);
1035 render_cpu_model: function(cpu
) {
1036 let socketText
= cpu
.sockets
> 1 ? gettext('Sockets') : gettext('Socket');
1037 return `${cpu.cpus} x ${cpu.model} (${cpu.sockets.toString()} ${socketText})`;
1040 /* this is different for nodes */
1041 render_node_cpu_usage: function(value
, record
) {
1042 return Proxmox
.Utils
.render_cpu_usage(value
, record
.cpus
);
1045 render_node_size_usage: function(record
) {
1046 return Proxmox
.Utils
.render_size_usage(record
.used
, record
.total
);
1049 loadTextFromFile: function(file
, callback
, maxBytes
) {
1050 let maxSize
= maxBytes
|| 8192;
1051 if (file
.size
> maxSize
) {
1052 Ext
.Msg
.alert(gettext('Error'), gettext("Invalid file size: ") + file
.size
);
1055 let reader
= new FileReader();
1056 reader
.onload
= evt
=> callback(evt
.target
.result
);
1057 reader
.readAsText(file
);
1060 parsePropertyString: function(value
, defaultKey
) {
1064 if (typeof value
!== 'string' || value
=== '') {
1068 Ext
.Array
.each(value
.split(','), function(p
) {
1069 var kv
= p
.split('=', 2);
1070 if (Ext
.isDefined(kv
[1])) {
1072 } else if (Ext
.isDefined(defaultKey
)) {
1073 if (Ext
.isDefined(res
[defaultKey
])) {
1074 error
= 'defaultKey may be only defined once in propertyString';
1075 return false; // break
1077 res
[defaultKey
] = kv
[0];
1079 error
= 'invalid propertyString, not a key=value pair and no defaultKey defined';
1080 return false; // break
1085 if (error
!== undefined) {
1086 console
.error(error
);
1093 printPropertyString: function(data
, defaultKey
) {
1094 var stringparts
= [],
1095 gotDefaultKeyVal
= false,
1098 Ext
.Object
.each(data
, function(key
, value
) {
1099 if (defaultKey
!== undefined && key
=== defaultKey
) {
1100 gotDefaultKeyVal
= true;
1101 defaultKeyVal
= value
;
1102 } else if (Ext
.isArray(value
)) {
1103 stringparts
.push(key
+ '=' + value
.join(';'));
1104 } else if (value
!== '') {
1105 stringparts
.push(key
+ '=' + value
);
1109 stringparts
= stringparts
.sort();
1110 if (gotDefaultKeyVal
) {
1111 stringparts
.unshift(defaultKeyVal
);
1114 return stringparts
.join(',');
1117 acmedomain_count
: 5,
1119 parseACMEPluginData: function(data
) {
1122 data
.split('\n').forEach((line
) => {
1123 // capture everything after the first = as value
1124 let [key
, value
] = line
.split('=');
1125 if (value
!== undefined) {
1128 extradata
.push(line
);
1131 return [res
, extradata
];
1134 delete_if_default: function(values
, fieldname
, default_val
, create
) {
1135 if (values
[fieldname
] === '' || values
[fieldname
] === default_val
) {
1137 if (values
.delete) {
1138 if (Ext
.isArray(values
.delete)) {
1139 values
.delete.push(fieldname
);
1141 values
.delete += ',' + fieldname
;
1144 values
.delete = fieldname
;
1148 delete values
[fieldname
];
1152 printACME: function(value
) {
1153 if (Ext
.isArray(value
.domains
)) {
1154 value
.domains
= value
.domains
.join(';');
1156 return Proxmox
.Utils
.printPropertyString(value
);
1159 parseACME: function(value
) {
1167 Ext
.Array
.each(value
.split(','), function(p
) {
1168 var kv
= p
.split('=', 2);
1169 if (Ext
.isDefined(kv
[1])) {
1172 error
= 'Failed to parse key-value pair: '+p
;
1178 if (error
!== undefined) {
1179 console
.error(error
);
1183 if (res
.domains
!== undefined) {
1184 res
.domains
= res
.domains
.split(/;/);
1190 add_domain_to_acme: function(acme
, domain
) {
1191 if (acme
.domains
=== undefined) {
1192 acme
.domains
= [domain
];
1194 acme
.domains
.push(domain
);
1195 acme
.domains
= acme
.domains
.filter((value
, index
, self
) => self
.indexOf(value
) === index
);
1200 remove_domain_from_acme: function(acme
, domain
) {
1201 if (acme
.domains
!== undefined) {
1202 acme
.domains
= acme
.domains
.filter(
1203 (value
, index
, self
) => self
.indexOf(value
) === index
&& value
!== domain
,
1209 get_health_icon: function(state
, circle
) {
1210 if (circle
=== undefined) {
1214 if (state
=== undefined) {
1218 var icon
= 'faded fa-question';
1221 icon
= 'good fa-check';
1224 icon
= 'warning fa-upload';
1227 icon
= 'warning fa-refresh';
1230 icon
= 'warning fa-exclamation';
1233 icon
= 'critical fa-times';
1245 formatNodeRepoStatus: function(status
, product
) {
1246 let fmt
= (txt
, cls
) => `<i class="fa fa-fw fa-lg fa-${cls}"></i>${txt}`;
1248 let getUpdates
= Ext
.String
.format(gettext('{0} updates'), product
);
1249 let noRepo
= Ext
.String
.format(gettext('No {0} repository enabled!'), product
);
1251 if (status
=== 'ok') {
1252 return fmt(getUpdates
, 'check-circle good') + ' ' +
1253 fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good');
1254 } else if (status
=== 'no-sub') {
1255 return fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good') + ' ' +
1256 fmt(gettext('Enterprise repository needs valid subscription'), 'exclamation-circle warning');
1257 } else if (status
=== 'non-production') {
1258 return fmt(getUpdates
, 'check-circle good') + ' ' +
1259 fmt(gettext('Non production-ready repository enabled!'), 'exclamation-circle warning');
1260 } else if (status
=== 'no-repo') {
1261 return fmt(noRepo
, 'exclamation-circle critical');
1264 return Proxmox
.Utils
.unknownText
;
1267 render_u2f_error: function(error
) {
1269 '1': gettext('Other Error'),
1270 '2': gettext('Bad Request'),
1271 '3': gettext('Configuration Unsupported'),
1272 '4': gettext('Device Ineligible'),
1273 '5': gettext('Timeout'),
1275 return "U2F Error: " + ErrorNames
[error
] || Proxmox
.Utils
.unknownText
;
1278 // Convert an ArrayBuffer to a base64url encoded string.
1279 // A `null` value will be preserved for convenience.
1280 bytes_to_base64url: function(bytes
) {
1281 if (bytes
=== null) {
1286 .from(new Uint8Array(bytes
))
1287 .map(val
=> String
.fromCharCode(val
))
1290 .replace(/\+/g, '-')
1291 .replace(/\//g, '_')
1292 .replace(/[=]/g, '');
1295 // Convert an a base64url string to an ArrayBuffer.
1296 // A `null` value will be preserved for convenience.
1297 base64url_to_bytes: function(b64u
) {
1298 if (b64u
=== null) {
1302 return new Uint8Array(
1305 .replace(/_/g, '/'),
1308 .map(val => val.charCodeAt(0)),
1312 stringToRGB: function(string) {
1317 string += 'prox
'; // give short strings more variance
1318 for (let i = 0; i < string.length; i++) {
1319 hash = string.charCodeAt(i) + ((hash << 5) - hash);
1320 hash = hash & hash; // to int
1323 let alpha = 0.7; // make the color a bit brighter
1324 let bg = 255; // assume white background
1327 (hash & 255) * alpha + bg * (1 - alpha),
1328 ((hash >> 8) & 255) * alpha + bg * (1 - alpha),
1329 ((hash >> 16) & 255) * alpha + bg * (1 - alpha),
1333 rgbToCss: function(rgb) {
1334 return `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
1337 rgbToHex: function(rgb) {
1338 let r = Math.round(rgb[0]).toString(16);
1339 let g = Math.round(rgb[1]).toString(16);
1340 let b = Math.round(rgb[2]).toString(16);
1341 return `${r}${g}${b}`;
1344 hexToRGB: function(hex) {
1348 if (hex.length === 7) {
1351 let r = parseInt(hex.slice(0, 2), 16);
1352 let g = parseInt(hex.slice(2, 4), 16);
1353 let b = parseInt(hex.slice(4, 6), 16);
1357 // optimized & simplified SAPC function
1358 // https://github.com/Myndex/SAPC-APCA
1359 getTextContrastClass: function(rgb) {
1360 const blkThrs = 0.022;
1361 const blkClmp = 1.414;
1363 // linearize & gamma correction
1364 let r = (rgb[0] / 255) ** 2.4;
1365 let g = (rgb[1] / 255) ** 2.4;
1366 let b = (rgb[2] / 255) ** 2.4;
1368 // relative luminance sRGB
1369 let bg = r * 0.2126729 + g * 0.7151522 + b * 0.0721750;
1372 bg = bg > blkThrs ? bg : bg + (blkThrs - bg) ** blkClmp;
1374 // SAPC with white text
1375 let contrastLight = bg ** 0.65 - 1;
1376 // SAPC with black text
1377 let contrastDark = bg ** 0.56 - 0.046134502;
1379 if (Math.abs(contrastLight) >= Math.abs(contrastDark)) {
1386 getTagElement: function(string, color_overrides) {
1387 let rgb = color_overrides?.[string] || Proxmox.Utils.stringToRGB(string);
1388 let style = `background-color: ${Proxmox.Utils.rgbToCss(rgb)};`;
1390 if (rgb.length > 3) {
1391 style += `color: ${Proxmox.Utils.rgbToCss([rgb[3], rgb[4], rgb[5]])}`;
1392 cls = "proxmox-tag-dark";
1394 let txtCls = Proxmox.Utils.getTextContrastClass(rgb);
1395 cls = `proxmox-tag-${txtCls}`;
1397 return `<span class="${cls}" style="${style}">${string}</span>`;
1400 // Setting filename here when downloading from a remote url sometimes fails in chromium browsers
1401 // because of a bug when using attribute download in conjunction with a self signed certificate.
1402 // For more info see https://bugs.chromium.org/p/chromium/issues/detail?id=993362
1403 downloadAsFile: function(source, fileName) {
1404 let hiddenElement = document.createElement('a
');
1405 hiddenElement.href = source;
1406 hiddenElement.target = '_blank
';
1408 hiddenElement.download = fileName;
1410 hiddenElement.click();
1415 constructor: function() {
1417 Ext.apply(me, me.utilities);
1419 let IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
1420 let IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
1421 let IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
1422 let IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
1423 let IPV4_CIDR_MASK = "([0-9]{1,2})";
1424 let IPV6_CIDR_MASK = "([0-9]{1,3})";
1427 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
1428 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")/" + IPV4_CIDR_MASK + "$");
1430 /* eslint-disable no-useless-concat,no-multi-spaces */
1431 let IPV6_REGEXP = "(?:" +
1432 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
1433 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
1434 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
1435 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
1436 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
1437 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
1438 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
1439 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
1440 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
1442 /* eslint-enable no-useless-concat,no-multi-spaces */
1444 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
1445 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")/" + IPV6_CIDR_MASK + "$");
1446 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
1448 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
1449 me.IP64_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + "/" + IPV6_CIDR_MASK + ")|(?:" + IPV4_REGEXP + "/" + IPV4_CIDR_MASK + ")$");
1451 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])?))";
1452 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
1453 me.DnsName_or_Wildcard_match = new RegExp("^(?:\\*\\.)?" + DnsName_REGEXP + "$");
1455 me.CpuSet_match = /^[0-9]+(?:-[0-9]+)?(?:,[0-9]+(?:-[0-9]+)?)*$/;
1457 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(?::(\\d+))?$");
1458 me.HostPortBrackets_match = new RegExp("^\\[(" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](?::(\\d+))?$");
1459 me.IP6_dotnotation_match = new RegExp("^(" + IPV6_REGEXP + ")(?:\\.(\\d+))?$");
1460 me.Vlan_match = /^vlan(\d+)/;
1461 me.VlanInterface_match = /(\w+)\.(\d+)/;
1465 Ext.define('Proxmox
.Async
', {
1468 // Returns a Promise resolving to the result of an `API2Request` or rejecting to the error
1469 // response on failure
1470 api2: function(reqOpts) {
1471 return new Promise((resolve, reject) => {
1472 delete reqOpts.callback; // not allowed in this api
1473 reqOpts.success = response => resolve(response);
1474 reqOpts.failure = response => reject(response);
1475 Proxmox.Utils.API2Request(reqOpts);
1479 // Delay for a number of milliseconds.
1480 sleep: function(millis) {
1481 return new Promise((resolve, _reject) => setTimeout(resolve, millis));
1485 Ext.override(Ext.data.Store, {
1486 // If the store's proxy is changed
while it is waiting
for an AJAX
1487 // response, `onProxyLoad` will still be called for the outdated response.
1488 // To avoid displaying inconsistent information, only process responses
1489 // belonging to the current proxy. However, do not apply this workaround
1490 // to the mobile UI, as Sencha Touch has an incompatible internal API.
1491 onProxyLoad: function(operation
) {
1493 if (Proxmox
.Utils
.toolkit
=== 'touch' || operation
.getProxy() === me
.getProxy()) {
1494 me
.callParent(arguments
);
1496 console
.log(`ignored outdated response: ${operation.getRequest().getUrl()}`);