]> git.proxmox.com Git - proxmox-widget-toolkit.git/blame - src/Utils.js
bump version to 3.6.0
[proxmox-widget-toolkit.git] / src / Utils.js
CommitLineData
ecabd437
TL
1Ext.ns('Proxmox');
2Ext.ns('Proxmox.Setup');
3
4if (!Ext.isDefined(Proxmox.Setup.auth_cookie_name)) {
5 throw "Proxmox library not initialized";
6}
7
ecabd437
TL
8// avoid errors when running without development tools
9if (!Ext.isDefined(Ext.global.console)) {
10 let console = {
11 dir: function() {
12 // do nothing
13 },
14 log: function() {
15 // do nothing
16 },
17 warn: function() {
18 // do nothing
19 },
20 };
21 Ext.global.console = console;
22}
23
24Ext.Ajax.defaultHeaders = {
25 'Accept': 'application/json',
26};
27
28Ext.Ajax.on('beforerequest', function(conn, options) {
29 if (Proxmox.CSRFPreventionToken) {
30 if (!options.headers) {
31 options.headers = {};
32 }
33 options.headers.CSRFPreventionToken = Proxmox.CSRFPreventionToken;
34 }
b6d1735a
TL
35 let storedAuth = Proxmox.Utils.getStoredAuth();
36 if (storedAuth.token) {
37 options.headers.Authorization = storedAuth.token;
63252ab6 38 }
ecabd437
TL
39});
40
41Ext.define('Proxmox.Utils', { // a singleton
42utilities: {
43
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'),
64d85d96 51 warningsText: gettext('Warnings'),
ecabd437
TL
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'),
64
65 language_map: {
66 ar: 'Arabic',
67 ca: 'Catalan',
998237fc
TL
68 zh_CN: 'Chinese (Simplified)',
69 zh_TW: 'Chinese (Traditional)',
ecabd437 70 da: 'Danish',
6127ba88 71 nl: 'Dutch',
ecabd437 72 en: 'English',
ecabd437 73 eu: 'Euskera (Basque)',
ecabd437 74 fr: 'French',
998237fc 75 de: 'German',
ecabd437
TL
76 he: 'Hebrew',
77 it: 'Italian',
78 ja: 'Japanese',
abfc1857 79 kr: 'Korean',
ecabd437
TL
80 nb: 'Norwegian (Bokmal)',
81 nn: 'Norwegian (Nynorsk)',
998237fc 82 fa: 'Persian (Farsi)',
ecabd437
TL
83 pl: 'Polish',
84 pt_BR: 'Portuguese (Brazil)',
85 ru: 'Russian',
86 sl: 'Slovenian',
998237fc 87 es: 'Spanish',
ecabd437
TL
88 sv: 'Swedish',
89 tr: 'Turkish',
ecabd437
TL
90 },
91
92 render_language: function(value) {
e06715d2 93 if (!value || value === '__default__') {
ecabd437
TL
94 return Proxmox.Utils.defaultText + ' (English)';
95 }
96 let text = Proxmox.Utils.language_map[value];
97 if (text) {
98 return text + ' (' + value + ')';
99 }
100 return value;
101 },
102
103 language_array: function() {
104 let data = [['__default__', Proxmox.Utils.render_language('')]];
105 Ext.Object.each(Proxmox.Utils.language_map, function(key, value) {
106 data.push([key, Proxmox.Utils.render_language(value)]);
107 });
108
109 return data;
110 },
111
15fddc20 112 theme_map: {
a017567b 113 crisp: 'Light theme',
15fddc20
DT
114 "proxmox-dark": 'Proxmox Dark',
115 },
116
117 render_theme: function(value) {
118 if (!value || value === '__default__') {
a017567b 119 return Proxmox.Utils.defaultText + ' (auto)';
15fddc20
DT
120 }
121 let text = Proxmox.Utils.theme_map[value];
122 if (text) {
123 return text;
124 }
125 return value;
126 },
127
128 theme_array: function() {
129 let data = [['__default__', Proxmox.Utils.render_theme('')]];
130 Ext.Object.each(Proxmox.Utils.theme_map, function(key, value) {
131 data.push([key, Proxmox.Utils.render_theme(value)]);
132 });
133
134 return data;
135 },
136
ecabd437
TL
137 bond_mode_gettext_map: {
138 '802.3ad': 'LACP (802.3ad)',
139 'lacp-balance-slb': 'LACP (balance-slb)',
140 'lacp-balance-tcp': 'LACP (balance-tcp)',
141 },
142
143 render_bond_mode: value => Proxmox.Utils.bond_mode_gettext_map[value] || value || '',
144
145 bond_mode_array: function(modes) {
146 return modes.map(mode => [mode, Proxmox.Utils.render_bond_mode(mode)]);
147 },
148
149 getNoSubKeyHtml: function(url) {
150 // url http://www.proxmox.com/products/proxmox-ve/subscription-service-plans
151 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');
152 },
153
154 format_boolean_with_default: function(value) {
155 if (Ext.isDefined(value) && value !== '__default__') {
156 return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
157 }
158 return Proxmox.Utils.defaultText;
159 },
160
161 format_boolean: function(value) {
162 return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
163 },
164
165 format_neg_boolean: function(value) {
166 return !value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
167 },
168
169 format_enabled_toggle: function(value) {
170 return value ? Proxmox.Utils.enabledText : Proxmox.Utils.disabledText;
171 },
172
173 format_expire: function(date) {
174 if (!date) {
175 return Proxmox.Utils.neverText;
176 }
177 return Ext.Date.format(date, "Y-m-d");
178 },
179
180 // somewhat like a human would tell durations, omit zero values and do not
181 // give seconds precision if we talk days already
182 format_duration_human: function(ut) {
3ccdce40 183 let seconds = 0, minutes = 0, hours = 0, days = 0, years = 0;
ecabd437 184
b2d7d422
DC
185 if (ut <= 0.1) {
186 return '<0.1s';
ecabd437
TL
187 }
188
189 let remaining = ut;
190 seconds = Number((remaining % 60).toFixed(1));
191 remaining = Math.trunc(remaining / 60);
192 if (remaining > 0) {
193 minutes = remaining % 60;
194 remaining = Math.trunc(remaining / 60);
195 if (remaining > 0) {
196 hours = remaining % 24;
197 remaining = Math.trunc(remaining / 24);
198 if (remaining > 0) {
3ccdce40
TL
199 days = remaining % 365;
200 remaining = Math.trunc(remaining / 365); // yea, just lets ignore leap years...
201 if (remaining > 0) {
202 years = remaining;
203 }
ecabd437
TL
204 }
205 }
206 }
207
208 let res = [];
209 let add = (t, unit) => {
210 if (t > 0) res.push(t + unit);
211 return t > 0;
212 };
213
3ccdce40 214 let addMinutes = !add(years, 'y');
ecabd437
TL
215 let addSeconds = !add(days, 'd');
216 add(hours, 'h');
3ccdce40
TL
217 if (addMinutes) {
218 add(minutes, 'm');
219 if (addSeconds) {
220 add(seconds, 's');
221 }
ecabd437
TL
222 }
223 return res.join(' ');
224 },
225
226 format_duration_long: function(ut) {
227 let days = Math.floor(ut / 86400);
228 ut -= days*86400;
229 let hours = Math.floor(ut / 3600);
230 ut -= hours*3600;
231 let mins = Math.floor(ut / 60);
232 ut -= mins*60;
233
234 let hours_str = '00' + hours.toString();
235 hours_str = hours_str.substr(hours_str.length - 2);
236 let mins_str = "00" + mins.toString();
237 mins_str = mins_str.substr(mins_str.length - 2);
238 let ut_str = "00" + ut.toString();
239 ut_str = ut_str.substr(ut_str.length - 2);
240
241 if (days) {
242 let ds = days > 1 ? Proxmox.Utils.daysText : Proxmox.Utils.dayText;
243 return days.toString() + ' ' + ds + ' ' +
244 hours_str + ':' + mins_str + ':' + ut_str;
245 } else {
246 return hours_str + ':' + mins_str + ':' + ut_str;
247 }
248 },
249
250 format_subscription_level: function(level) {
251 if (level === 'c') {
252 return 'Community';
253 } else if (level === 'b') {
254 return 'Basic';
255 } else if (level === 's') {
256 return 'Standard';
257 } else if (level === 'p') {
258 return 'Premium';
259 } else {
260 return Proxmox.Utils.noneText;
261 }
262 },
263
264 compute_min_label_width: function(text, width) {
265 if (width === undefined) { width = 100; }
266
267 let tm = new Ext.util.TextMetrics();
268 let min = tm.getWidth(text + ':');
269
270 return min < width ? width : min;
271 },
272
e722f108
TL
273 // returns username + realm
274 parse_userid: function(userid) {
275 if (!Ext.isString(userid)) {
276 return [undefined, undefined];
277 }
278
279 let match = userid.match(/^(.+)@([^@]+)$/);
280 if (match !== null) {
281 return [match[1], match[2]];
282 }
283
284 return [undefined, undefined];
285 },
286
287 render_username: function(userid) {
cd20320b 288 let username = Proxmox.Utils.parse_userid(userid)[0] || "";
e722f108
TL
289 return Ext.htmlEncode(username);
290 },
291
292 render_realm: function(userid) {
cd20320b 293 let username = Proxmox.Utils.parse_userid(userid)[1] || "";
e722f108
TL
294 return Ext.htmlEncode(username);
295 },
296
63252ab6
TM
297 getStoredAuth: function() {
298 let storedAuth = JSON.parse(window.localStorage.getItem('ProxmoxUser'));
299 return storedAuth || {};
300 },
301
ecabd437 302 setAuthData: function(data) {
ecabd437
TL
303 Proxmox.UserName = data.username;
304 Proxmox.LoggedOut = data.LoggedOut;
305 // creates a session cookie (expire = null)
306 // that way the cookie gets deleted after the browser window is closed
63252ab6
TM
307 if (data.ticket) {
308 Proxmox.CSRFPreventionToken = data.CSRFPreventionToken;
309 Ext.util.Cookies.set(Proxmox.Setup.auth_cookie_name, data.ticket, null, '/', null, true);
310 }
311
312 if (data.token) {
313 window.localStorage.setItem('ProxmoxUser', JSON.stringify(data));
314 }
ecabd437
TL
315 },
316
317 authOK: function() {
318 if (Proxmox.LoggedOut) {
319 return undefined;
320 }
b6d1735a 321 let storedAuth = Proxmox.Utils.getStoredAuth();
ecabd437 322 let cookie = Ext.util.Cookies.get(Proxmox.Setup.auth_cookie_name);
63252ab6
TM
323 if ((Proxmox.UserName !== '' && cookie && !cookie.startsWith("PVE:tfa!")) || storedAuth.token) {
324 return cookie || storedAuth.token;
ecabd437
TL
325 } else {
326 return false;
327 }
328 },
329
330 authClear: function() {
331 if (Proxmox.LoggedOut) {
332 return;
333 }
96fb7eaa 334 // ExtJS clear is basically the same, but browser may complain if any cookie isn't "secure"
c1a35841 335 Ext.util.Cookies.set(Proxmox.Setup.auth_cookie_name, "", new Date(0), null, null, true);
63252ab6 336 window.localStorage.removeItem("ProxmoxUser");
ecabd437
TL
337 },
338
e8c60b32
TL
339 // The End-User gets redirected back here after login on the OpenID auth. portal, and in the
340 // redirection URL the state and auth.code are passed as URL GET params, this helper parses those
341 getOpenIDRedirectionAuthorization: function() {
342 const auth = Ext.Object.fromQueryString(window.location.search);
343 if (auth.state !== undefined && auth.code !== undefined) {
344 return auth;
345 }
346 return undefined;
347 },
348
ecabd437
TL
349 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
350 // use el.mask() instead
351 setErrorMask: function(comp, msg) {
352 let el = comp.el;
353 if (!el) {
354 return;
355 }
356 if (!msg) {
357 el.unmask();
358 } else if (msg === true) {
359 el.mask(gettext("Loading..."));
360 } else {
361 el.mask(msg);
362 }
363 },
364
365 getResponseErrorMessage: (err) => {
366 if (!err.statusText) {
367 return gettext('Connection error');
368 }
369 let msg = [`${err.statusText} (${err.status})`];
370 if (err.response && err.response.responseText) {
371 let txt = err.response.responseText;
372 try {
373 let res = JSON.parse(txt);
374 if (res.errors && typeof res.errors === 'object') {
375 for (let [key, value] of Object.entries(res.errors)) {
376 msg.push(Ext.String.htmlEncode(`${key}: ${value}`));
377 }
378 }
379 } catch (e) {
380 // fallback to string
381 msg.push(Ext.String.htmlEncode(txt));
382 }
383 }
384 return msg.join('<br>');
385 },
386
661faeed 387 monStoreErrors: function(component, store, clearMaskBeforeLoad, errorCallback) {
ecabd437
TL
388 if (clearMaskBeforeLoad) {
389 component.mon(store, 'beforeload', function(s, operation, eOpts) {
390 Proxmox.Utils.setErrorMask(component, false);
391 });
392 } else {
393 component.mon(store, 'beforeload', function(s, operation, eOpts) {
394 if (!component.loadCount) {
395 component.loadCount = 0; // make sure it is nucomponent.ic
396 Proxmox.Utils.setErrorMask(component, true);
397 }
398 });
399 }
400
401 // only works with 'proxmox' proxy
402 component.mon(store.proxy, 'afterload', function(proxy, request, success) {
403 component.loadCount++;
404
405 if (success) {
406 Proxmox.Utils.setErrorMask(component, false);
407 return;
408 }
409
410 let error = request._operation.getError();
411 let msg = Proxmox.Utils.getResponseErrorMessage(error);
661faeed
SR
412 if (!errorCallback || !errorCallback(error, msg)) {
413 Proxmox.Utils.setErrorMask(component, msg);
414 }
ecabd437
TL
415 });
416 },
417
418 extractRequestError: function(result, verbose) {
419 let msg = gettext('Successful');
420
421 if (!result.success) {
422 msg = gettext("Unknown error");
423 if (result.message) {
cf93d1da 424 msg = Ext.htmlEncode(result.message);
ecabd437 425 if (result.status) {
d53046d6 426 msg += ` (${result.status})`;
ecabd437
TL
427 }
428 }
429 if (verbose && Ext.isObject(result.errors)) {
430 msg += "<br>";
d53046d6
TL
431 Ext.Object.each(result.errors, (prop, desc) => {
432 msg += `<br><b>${Ext.htmlEncode(prop)}</b>: ${Ext.htmlEncode(desc)}`;
ecabd437
TL
433 });
434 }
435 }
436
437 return msg;
438 },
439
440 // Ext.Ajax.request
441 API2Request: function(reqOpts) {
442 let newopts = Ext.apply({
443 waitMsg: gettext('Please wait...'),
444 }, reqOpts);
445
319d450b
TL
446 // default to enable if user isn't handling the failure already explicitly
447 let autoErrorAlert = reqOpts.autoErrorAlert ??
448 (typeof reqOpts.failure !== 'function' && typeof reqOpts.callback !== 'function');
449
ecabd437
TL
450 if (!newopts.url.match(/^\/api2/)) {
451 newopts.url = '/api2/extjs' + newopts.url;
452 }
453 delete newopts.callback;
454
455 let createWrapper = function(successFn, callbackFn, failureFn) {
456 Ext.apply(newopts, {
457 success: function(response, options) {
458 if (options.waitMsgTarget) {
459 if (Proxmox.Utils.toolkit === 'touch') {
460 options.waitMsgTarget.setMasked(false);
461 } else {
462 options.waitMsgTarget.setLoading(false);
463 }
464 }
465 let result = Ext.decode(response.responseText);
466 response.result = result;
467 if (!result.success) {
468 response.htmlStatus = Proxmox.Utils.extractRequestError(result, true);
469 Ext.callback(callbackFn, options.scope, [options, false, response]);
470 Ext.callback(failureFn, options.scope, [response, options]);
319d450b
TL
471 if (autoErrorAlert) {
472 Ext.Msg.alert(gettext('Error'), response.htmlStatus);
473 }
ecabd437
TL
474 return;
475 }
476 Ext.callback(callbackFn, options.scope, [options, true, response]);
477 Ext.callback(successFn, options.scope, [response, options]);
478 },
479 failure: function(response, options) {
480 if (options.waitMsgTarget) {
481 if (Proxmox.Utils.toolkit === 'touch') {
482 options.waitMsgTarget.setMasked(false);
483 } else {
484 options.waitMsgTarget.setLoading(false);
485 }
486 }
487 response.result = {};
488 try {
489 response.result = Ext.decode(response.responseText);
490 } catch (e) {
491 // ignore
492 }
493 let msg = gettext('Connection error') + ' - server offline?';
494 if (response.aborted) {
495 msg = gettext('Connection error') + ' - aborted.';
496 } else if (response.timedout) {
497 msg = gettext('Connection error') + ' - Timeout.';
498 } else if (response.status && response.statusText) {
499 msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText;
500 }
501 response.htmlStatus = msg;
502 Ext.callback(callbackFn, options.scope, [options, false, response]);
503 Ext.callback(failureFn, options.scope, [response, options]);
504 },
505 });
506 };
507
508 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
509
510 let target = newopts.waitMsgTarget;
511 if (target) {
512 if (Proxmox.Utils.toolkit === 'touch') {
513 target.setMasked({ xtype: 'loadmask', message: newopts.waitMsg });
514 } else {
515 // Note: ExtJS bug - this does not work when component is not rendered
516 target.setLoading(newopts.waitMsg);
517 }
518 }
519 Ext.Ajax.request(newopts);
520 },
521
106fe29e
TL
522 // can be useful for catching displaying errors from the API, e.g.:
523 // Proxmox.Async.api2({
524 // ...
525 // }).catch(Proxmox.Utils.alertResponseFailure);
526 alertResponseFailure: (response) => {
527 Ext.Msg.alert(
528 gettext('Error'),
529 response.htmlStatus || response.result.message,
530 );
531 },
532
ecabd437 533 checked_command: function(orig_cmd) {
a718654e
TL
534 Proxmox.Utils.API2Request(
535 {
536 url: '/nodes/localhost/subscription',
537 method: 'GET',
538 failure: function(response, opts) {
539 Ext.Msg.alert(gettext('Error'), response.htmlStatus);
540 },
541 success: function(response, opts) {
542 let res = response.result;
543 if (res === null || res === undefined || !res || res
57ba4cdc 544 .data.status.toLowerCase() !== 'active') {
a718654e
TL
545 Ext.Msg.show({
546 title: gettext('No valid subscription'),
547 icon: Ext.Msg.WARNING,
548 message: Proxmox.Utils.getNoSubKeyHtml(res.data.url),
549 buttons: Ext.Msg.OK,
550 callback: function(btn) {
551 if (btn !== 'ok') {
552 return;
553 }
554 orig_cmd();
555 },
556 });
557 } else {
558 orig_cmd();
559 }
560 },
ecabd437 561 },
a718654e 562 );
ecabd437
TL
563 },
564
565 assemble_field_data: function(values, data) {
566 if (!Ext.isObject(data)) {
567 return;
568 }
569 Ext.Object.each(data, function(name, val) {
570 if (Object.prototype.hasOwnProperty.call(values, name)) {
571 let bucket = values[name];
572 if (!Ext.isArray(bucket)) {
573 bucket = values[name] = [bucket];
574 }
575 if (Ext.isArray(val)) {
576 values[name] = bucket.concat(val);
577 } else {
578 bucket.push(val);
579 }
580 } else {
581 values[name] = val;
582 }
583 });
584 },
585
fb4bb95e 586 updateColumnWidth: function(container, thresholdWidth) {
ecabd437
TL
587 let mode = Ext.state.Manager.get('summarycolumns') || 'auto';
588 let factor;
589 if (mode !== 'auto') {
590 factor = parseInt(mode, 10);
591 if (Number.isNaN(factor)) {
592 factor = 1;
593 }
594 } else {
fb4bb95e
TL
595 thresholdWidth = (thresholdWidth || 1400) + 1;
596 factor = Math.ceil(container.getSize().width / thresholdWidth);
ecabd437
TL
597 }
598
599 if (container.oldFactor === factor) {
600 return;
601 }
602
017a6376 603 let items = container.query('>'); // direct children
ecabd437
TL
604 factor = Math.min(factor, items.length);
605 container.oldFactor = factor;
606
607 items.forEach((item) => {
608 item.columnWidth = 1 / factor;
609 });
610
611 // we have to update the layout twice, since the first layout change
612 // can trigger the scrollbar which reduces the amount of space left
613 container.updateLayout();
614 container.updateLayout();
615 },
616
8b7e349a
TL
617 // NOTE: depreacated, use updateColumnWidth
618 updateColumns: container => Proxmox.Utils.updateColumnWidth(container),
619
ecabd437
TL
620 dialog_title: function(subject, create, isAdd) {
621 if (create) {
622 if (isAdd) {
623 return gettext('Add') + ': ' + subject;
624 } else {
625 return gettext('Create') + ': ' + subject;
626 }
627 } else {
628 return gettext('Edit') + ': ' + subject;
629 }
630 },
631
632 network_iface_types: {
633 eth: gettext("Network Device"),
634 bridge: 'Linux Bridge',
635 bond: 'Linux Bond',
636 vlan: 'Linux VLAN',
637 OVSBridge: 'OVS Bridge',
638 OVSBond: 'OVS Bond',
639 OVSPort: 'OVS Port',
640 OVSIntPort: 'OVS IntPort',
641 },
642
643 render_network_iface_type: function(value) {
644 return Proxmox.Utils.network_iface_types[value] ||
645 Proxmox.Utils.unknownText;
646 },
647
fc0a18e6 648 // NOTE: only add general, product agnostic, ones here! Else use override helper in product repos
ecabd437 649 task_desc_table: {
3571d713 650 aptupdate: ['', gettext('Update package database')],
ecabd437 651 diskinit: ['Disk', gettext('Initialize Disk with GPT')],
ecabd437 652 spiceshell: ['', gettext('Shell') + ' (Spice)'],
3571d713
DC
653 srvreload: ['SRV', gettext('Reload')],
654 srvrestart: ['SRV', gettext('Restart')],
ecabd437
TL
655 srvstart: ['SRV', gettext('Start')],
656 srvstop: ['SRV', gettext('Stop')],
3571d713
DC
657 termproxy: ['', gettext('Console') + ' (xterm.js)'],
658 vncshell: ['', gettext('Shell')],
ecabd437
TL
659 },
660
661 // to add or change existing for product specific ones
662 override_task_descriptions: function(extra) {
663 for (const [key, value] of Object.entries(extra)) {
664 Proxmox.Utils.task_desc_table[key] = value;
665 }
666 },
667
668 format_task_description: function(type, id) {
669 let farray = Proxmox.Utils.task_desc_table[type];
670 let text;
671 if (!farray) {
672 text = type;
673 if (id) {
674 type += ' ' + id;
675 }
676 return text;
677 } else if (Ext.isFunction(farray)) {
678 return farray(type, id);
679 }
680 let prefix = farray[0];
681 text = farray[1];
682 if (prefix && id !== undefined) {
683 return prefix + ' ' + id + ' - ' + text;
684 }
685 return text;
686 },
687
b46ad78c
TL
688 format_size: function(size, useSI) {
689 let units = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
690 let order = 0;
691 const baseValue = useSI ? 1000 : 1024;
692 while (size >= baseValue && order < units.length) {
693 size = size / baseValue;
694 order++;
ecabd437
TL
695 }
696
b46ad78c
TL
697 let unit = units[order], commaDigits = 2;
698 if (order === 0) {
699 commaDigits = 0;
700 } else if (!useSI) {
701 unit += 'i';
702 }
703 return `${size.toFixed(commaDigits)} ${unit}B`;
ecabd437
TL
704 },
705
1fad0e88
TL
706 SizeUnits: {
707 'B': 1,
708
709 'KiB': 1024,
710 'MiB': 1024*1024,
711 'GiB': 1024*1024*1024,
712 'TiB': 1024*1024*1024*1024,
713 'PiB': 1024*1024*1024*1024*1024,
714
715 'KB': 1000,
716 'MB': 1000*1000,
717 'GB': 1000*1000*1000,
718 'TB': 1000*1000*1000*1000,
719 'PB': 1000*1000*1000*1000*1000,
720 },
721
851ebc36
TL
722 parse_size_unit: function(val) {
723 //let m = val.match(/([.\d])+\s?([KMGTP]?)(i?)B?\s*$/i);
724 let m = val.match(/(\d+(?:\.\d+)?)\s?([KMGTP]?)(i?)B?\s*$/i);
725 let size = parseFloat(m[1]);
726 let scale = m[2].toUpperCase();
727 let binary = m[3].toLowerCase();
728
729 let unit = `${scale}${binary}B`;
730 let factor = Proxmox.Utils.SizeUnits[unit];
731
732 return { size, factor, unit, binary }; // for convenience return all we got
733 },
734
735 size_unit_to_bytes: function(val) {
736 let { size, factor } = Proxmox.Utils.parse_size_unit(val);
737 return size * factor;
738 },
739
740 autoscale_size_unit: function(val) {
741 let { size, factor, binary } = Proxmox.Utils.parse_size_unit(val);
742 return Proxmox.Utils.format_size(size * factor, binary !== "i");
743 },
744
745 size_unit_ratios: function(a, b) {
746 a = typeof a !== "undefined" ? a : 0;
747 b = typeof b !== "undefined" ? b : Infinity;
748 let aBytes = typeof a === "number" ? a : Proxmox.Utils.size_unit_to_bytes(a);
749 let bBytes = typeof b === "number" ? b : Proxmox.Utils.size_unit_to_bytes(b);
750 return aBytes / (bBytes || Infinity); // avoid division by zero
751 },
752
ecabd437
TL
753 render_upid: function(value, metaData, record) {
754 let task = record.data;
755 let type = task.type || task.worker_type;
756 let id = task.id || task.worker_id;
757
758 return Proxmox.Utils.format_task_description(type, id);
759 },
760
761 render_uptime: function(value) {
762 let uptime = value;
763
764 if (uptime === undefined) {
765 return '';
766 }
767
768 if (uptime <= 0) {
769 return '-';
770 }
771
772 return Proxmox.Utils.format_duration_long(uptime);
773 },
774
6221e40c 775 systemd_unescape: function(string_value) {
6221e40c
DM
776 const charcode_0 = '0'.charCodeAt(0);
777 const charcode_9 = '9'.charCodeAt(0);
778 const charcode_A = 'A'.charCodeAt(0);
779 const charcode_F = 'F'.charCodeAt(0);
780 const charcode_a = 'a'.charCodeAt(0);
781 const charcode_f = 'f'.charCodeAt(0);
782 const charcode_x = 'x'.charCodeAt(0);
783 const charcode_minus = '-'.charCodeAt(0);
784 const charcode_slash = '/'.charCodeAt(0);
785 const charcode_backslash = '\\'.charCodeAt(0);
786
787 let parse_hex_digit = function(d) {
788 if (d >= charcode_0 && d <= charcode_9) {
789 return d - charcode_0;
790 }
791 if (d >= charcode_A && d <= charcode_F) {
792 return d - charcode_A + 10;
793 }
794 if (d >= charcode_a && d <= charcode_f) {
795 return d - charcode_a + 10;
796 }
797 throw "got invalid hex digit";
798 };
799
800 let value = new TextEncoder().encode(string_value);
801 let result = new Uint8Array(value.length);
802
803 let i = 0;
804 let result_len = 0;
805
806 while (i < value.length) {
807 let c0 = value[i];
808 if (c0 === charcode_minus) {
809 result.set([charcode_slash], result_len);
810 result_len += 1;
811 i += 1;
812 continue;
813 }
814 if ((i + 4) < value.length) {
815 let c1 = value[i+1];
816 if (c0 === charcode_backslash && c1 === charcode_x) {
817 let h1 = parse_hex_digit(value[i+2]);
818 let h0 = parse_hex_digit(value[i+3]);
819 let ord = h1*16+h0;
820 result.set([ord], result_len);
821 result_len += 1;
822 i += 4;
823 continue;
824 }
825 }
826 result.set([c0], result_len);
827 result_len += 1;
828 i += 1;
829 }
830
831 return new TextDecoder().decode(result.slice(0, result.len));
832 },
833
ecabd437
TL
834 parse_task_upid: function(upid) {
835 let task = {};
836
837 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]+):$/);
838 if (!res) {
839 throw "unable to parse upid '" + upid + "'";
840 }
841 task.node = res[1];
842 task.pid = parseInt(res[2], 16);
843 task.pstart = parseInt(res[3], 16);
844 if (res[5] !== undefined) {
845 task.task_id = parseInt(res[5], 16);
846 }
847 task.starttime = parseInt(res[6], 16);
848 task.type = res[7];
6221e40c 849 task.id = Proxmox.Utils.systemd_unescape(res[8]);
ecabd437
TL
850 task.user = res[9];
851
852 task.desc = Proxmox.Utils.format_task_description(task.type, task.id);
853
854 return task;
855 },
856
b1d446d0
DC
857 parse_task_status: function(status) {
858 if (status === 'OK') {
859 return 'ok';
860 }
861
862 if (status === 'unknown') {
863 return 'unknown';
864 }
865
866 let match = status.match(/^WARNINGS: (.*)$/);
867 if (match) {
868 return 'warning';
869 }
870
871 return 'error';
872 },
873
9865b73e
FE
874 format_task_status: function(status) {
875 let parsed = Proxmox.Utils.parse_task_status(status);
4294143f
FE
876 switch (parsed) {
877 case 'unknown': return Proxmox.Utils.unknownText;
9865b73e 878 case 'error': return Proxmox.Utils.errorText + ': ' + status;
9b4b243a 879 case 'warning': return status.replace('WARNINGS', Proxmox.Utils.warningsText);
4294143f 880 case 'ok': // fall-through
9865b73e 881 default: return status;
4294143f
FE
882 }
883 },
884
ecabd437
TL
885 render_duration: function(value) {
886 if (value === undefined) {
887 return '-';
888 }
889 return Proxmox.Utils.format_duration_human(value);
890 },
891
892 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
893 let servertime = new Date(value * 1000);
894 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
895 },
896
f29e6a66
DC
897 render_zfs_health: function(value) {
898 if (typeof value === 'undefined') {
899 return "";
900 }
901 var iconCls = 'question-circle';
902 switch (value) {
903 case 'AVAIL':
904 case 'ONLINE':
905 iconCls = 'check-circle good';
906 break;
907 case 'REMOVED':
908 case 'DEGRADED':
909 iconCls = 'exclamation-circle warning';
910 break;
911 case 'UNAVAIL':
912 case 'FAULTED':
913 case 'OFFLINE':
914 iconCls = 'times-circle critical';
915 break;
916 default: //unknown
917 }
918
919 return '<i class="fa fa-' + iconCls + '"></i> ' + value;
920 },
921
ecabd437
TL
922 get_help_info: function(section) {
923 let helpMap;
924 if (typeof proxmoxOnlineHelpInfo !== 'undefined') {
925 helpMap = proxmoxOnlineHelpInfo; // eslint-disable-line no-undef
926 } else if (typeof pveOnlineHelpInfo !== 'undefined') {
927 // be backward compatible with older pve-doc-generators
928 helpMap = pveOnlineHelpInfo; // eslint-disable-line no-undef
929 } else {
930 throw "no global OnlineHelpInfo map declared";
931 }
932
7f56fd0c
TL
933 if (helpMap[section]) {
934 return helpMap[section];
935 }
936 // try to normalize - and _ separators, to support asciidoc and sphinx
937 // references at the same time.
63ec56e5 938 let section_minus_normalized = section.replace(/_/g, '-');
7f56fd0c
TL
939 if (helpMap[section_minus_normalized]) {
940 return helpMap[section_minus_normalized];
941 }
63ec56e5 942 let section_underscore_normalized = section.replace(/-/g, '_');
7f56fd0c 943 return helpMap[section_underscore_normalized];
ecabd437
TL
944 },
945
946 get_help_link: function(section) {
947 let info = Proxmox.Utils.get_help_info(section);
948 if (!info) {
949 return undefined;
950 }
951 return window.location.origin + info.link;
952 },
953
954 openXtermJsViewer: function(vmtype, vmid, nodename, vmname, cmd) {
955 let url = Ext.Object.toQueryString({
956 console: vmtype, // kvm, lxc, upgrade or shell
957 xtermjs: 1,
958 vmid: vmid,
959 vmname: vmname,
960 node: nodename,
961 cmd: cmd,
962
963 });
964 let nw = window.open("?" + url, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
965 if (nw) {
966 nw.focus();
967 }
968 },
969
25680ef5
WB
970 render_optional_url: function(value) {
971 if (value && value.match(/^https?:\/\//) !== null) {
972 return '<a target="_blank" href="' + value + '">' + value + '</a>';
973 }
974 return value;
975 },
976
977 render_san: function(value) {
978 var names = [];
979 if (Ext.isArray(value)) {
980 value.forEach(function(val) {
981 if (!Ext.isNumber(val)) {
982 names.push(val);
983 }
984 });
985 return names.join('<br>');
986 }
987 return value;
988 },
989
ce8289fc 990 render_usage: val => (val * 100).toFixed(2) + '%',
ef3f1cfc
DC
991
992 render_cpu_usage: function(val, max) {
9e663a6a
TL
993 return Ext.String.format(
994 `${gettext('{0}% of {1}')} ${gettext('CPU(s)')}`,
995 (val*100).toFixed(2),
996 max,
997 );
ef3f1cfc
DC
998 },
999
b46ad78c 1000 render_size_usage: function(val, max, useSI) {
ef3f1cfc
DC
1001 if (max === 0) {
1002 return gettext('N/A');
1003 }
b46ad78c 1004 let fmt = v => Proxmox.Utils.format_size(v, useSI);
ce8289fc
TL
1005 let ratio = (val * 100 / max).toFixed(2);
1006 return ratio + '% (' + Ext.String.format(gettext('{0} of {1}'), fmt(val), fmt(max)) + ')';
ef3f1cfc
DC
1007 },
1008
1009 render_cpu: function(value, metaData, record, rowIndex, colIndex, store) {
1010 if (!(record.data.uptime && Ext.isNumeric(value))) {
1011 return '';
1012 }
1013
9e663a6a 1014 let maxcpu = record.data.maxcpu || 1;
1334cdca 1015 if (!Ext.isNumeric(maxcpu) || maxcpu < 1) {
ef3f1cfc
DC
1016 return '';
1017 }
9e663a6a
TL
1018 let cpuText = maxcpu > 1 ? 'CPUs' : 'CPU';
1019 let ratio = (value * 100).toFixed(1);
1020 return `${ratio}% of ${maxcpu.toString()} ${cpuText}`;
ef3f1cfc
DC
1021 },
1022
1023 render_size: function(value, metaData, record, rowIndex, colIndex, store) {
1024 if (!Ext.isNumeric(value)) {
1025 return '';
1026 }
ef3f1cfc
DC
1027 return Proxmox.Utils.format_size(value);
1028 },
1029
9e663a6a
TL
1030 render_cpu_model: function(cpu) {
1031 let socketText = cpu.sockets > 1 ? gettext('Sockets') : gettext('Socket');
1032 return `${cpu.cpus} x ${cpu.model} (${cpu.sockets.toString()} ${socketText})`;
ef3f1cfc
DC
1033 },
1034
1035 /* this is different for nodes */
1036 render_node_cpu_usage: function(value, record) {
1037 return Proxmox.Utils.render_cpu_usage(value, record.cpus);
1038 },
1039
1040 render_node_size_usage: function(record) {
1041 return Proxmox.Utils.render_size_usage(record.used, record.total);
1042 },
1043
25680ef5
WB
1044 loadTextFromFile: function(file, callback, maxBytes) {
1045 let maxSize = maxBytes || 8192;
1046 if (file.size > maxSize) {
1047 Ext.Msg.alert(gettext('Error'), gettext("Invalid file size: ") + file.size);
1048 return;
1049 }
1050 let reader = new FileReader();
1051 reader.onload = evt => callback(evt.target.result);
1052 reader.readAsText(file);
1053 },
1054
1055 parsePropertyString: function(value, defaultKey) {
1056 var res = {},
1057 error;
1058
1059 if (typeof value !== 'string' || value === '') {
1060 return res;
1061 }
1062
1063 Ext.Array.each(value.split(','), function(p) {
1064 var kv = p.split('=', 2);
1065 if (Ext.isDefined(kv[1])) {
1066 res[kv[0]] = kv[1];
1067 } else if (Ext.isDefined(defaultKey)) {
1068 if (Ext.isDefined(res[defaultKey])) {
1069 error = 'defaultKey may be only defined once in propertyString';
1070 return false; // break
1071 }
1072 res[defaultKey] = kv[0];
1073 } else {
1074 error = 'invalid propertyString, not a key=value pair and no defaultKey defined';
1075 return false; // break
1076 }
1077 return true;
1078 });
1079
1080 if (error !== undefined) {
1081 console.error(error);
1082 return undefined;
1083 }
1084
1085 return res;
1086 },
1087
1088 printPropertyString: function(data, defaultKey) {
1089 var stringparts = [],
1090 gotDefaultKeyVal = false,
1091 defaultKeyVal;
1092
1093 Ext.Object.each(data, function(key, value) {
1094 if (defaultKey !== undefined && key === defaultKey) {
1095 gotDefaultKeyVal = true;
1096 defaultKeyVal = value;
1097 } else if (Ext.isArray(value)) {
1098 stringparts.push(key + '=' + value.join(';'));
1099 } else if (value !== '') {
1100 stringparts.push(key + '=' + value);
1101 }
1102 });
1103
1104 stringparts = stringparts.sort();
1105 if (gotDefaultKeyVal) {
1106 stringparts.unshift(defaultKeyVal);
1107 }
1108
1109 return stringparts.join(',');
1110 },
1111
1112 acmedomain_count: 5,
1113
1114 parseACMEPluginData: function(data) {
1115 let res = {};
1116 let extradata = [];
1117 data.split('\n').forEach((line) => {
1118 // capture everything after the first = as value
1119 let [key, value] = line.split('=');
1120 if (value !== undefined) {
1121 res[key] = value;
1122 } else {
1123 extradata.push(line);
1124 }
1125 });
1126 return [res, extradata];
1127 },
1128
1129 delete_if_default: function(values, fieldname, default_val, create) {
1130 if (values[fieldname] === '' || values[fieldname] === default_val) {
1131 if (!create) {
1132 if (values.delete) {
1133 if (Ext.isArray(values.delete)) {
1134 values.delete.push(fieldname);
1135 } else {
1136 values.delete += ',' + fieldname;
1137 }
1138 } else {
1139 values.delete = fieldname;
1140 }
1141 }
1142
1143 delete values[fieldname];
1144 }
1145 },
1146
1147 printACME: function(value) {
1148 if (Ext.isArray(value.domains)) {
1149 value.domains = value.domains.join(';');
1150 }
1151 return Proxmox.Utils.printPropertyString(value);
1152 },
1153
1154 parseACME: function(value) {
1155 if (!value) {
1156 return {};
1157 }
1158
1159 var res = {};
1160 var error;
1161
1162 Ext.Array.each(value.split(','), function(p) {
1163 var kv = p.split('=', 2);
1164 if (Ext.isDefined(kv[1])) {
1165 res[kv[0]] = kv[1];
1166 } else {
1167 error = 'Failed to parse key-value pair: '+p;
1168 return false;
1169 }
1170 return true;
1171 });
1172
1173 if (error !== undefined) {
1174 console.error(error);
1175 return undefined;
1176 }
1177
1178 if (res.domains !== undefined) {
1179 res.domains = res.domains.split(/;/);
1180 }
1181
1182 return res;
1183 },
1184
1185 add_domain_to_acme: function(acme, domain) {
1186 if (acme.domains === undefined) {
1187 acme.domains = [domain];
1188 } else {
1189 acme.domains.push(domain);
1190 acme.domains = acme.domains.filter((value, index, self) => self.indexOf(value) === index);
1191 }
1192 return acme;
1193 },
1194
1195 remove_domain_from_acme: function(acme, domain) {
1196 if (acme.domains !== undefined) {
1197 acme.domains = acme.domains.filter(
1198 (value, index, self) => self.indexOf(value) === index && value !== domain,
1199 );
1200 }
1201 return acme;
1202 },
d365540e 1203
fbbe68fd
DC
1204 get_health_icon: function(state, circle) {
1205 if (circle === undefined) {
1206 circle = false;
1207 }
1208
1209 if (state === undefined) {
1210 state = 'uknown';
1211 }
1212
1213 var icon = 'faded fa-question';
1214 switch (state) {
1215 case 'good':
1216 icon = 'good fa-check';
1217 break;
1218 case 'upgrade':
1219 icon = 'warning fa-upload';
1220 break;
1221 case 'old':
1222 icon = 'warning fa-refresh';
1223 break;
1224 case 'warning':
1225 icon = 'warning fa-exclamation';
1226 break;
1227 case 'critical':
1228 icon = 'critical fa-times';
1229 break;
1230 default: break;
1231 }
1232
1233 if (circle) {
1234 icon += '-circle';
1235 }
1236
1237 return icon;
1238 },
40296471 1239
7c65b8bf
FE
1240 formatNodeRepoStatus: function(status, product) {
1241 let fmt = (txt, cls) => `<i class="fa fa-fw fa-lg fa-${cls}"></i>${txt}`;
1242
1243 let getUpdates = Ext.String.format(gettext('{0} updates'), product);
1244 let noRepo = Ext.String.format(gettext('No {0} repository enabled!'), product);
1245
1246 if (status === 'ok') {
1247 return fmt(getUpdates, 'check-circle good') + ' ' +
1248 fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good');
1249 } else if (status === 'no-sub') {
1250 return fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good') + ' ' +
1251 fmt(gettext('Enterprise repository needs valid subscription'), 'exclamation-circle warning');
1252 } else if (status === 'non-production') {
1253 return fmt(getUpdates, 'check-circle good') + ' ' +
1254 fmt(gettext('Non production-ready repository enabled!'), 'exclamation-circle warning');
1255 } else if (status === 'no-repo') {
1256 return fmt(noRepo, 'exclamation-circle critical');
1257 }
1258
1259 return Proxmox.Utils.unknownText;
1260 },
c7f2b15a
WB
1261
1262 render_u2f_error: function(error) {
1263 var ErrorNames = {
1264 '1': gettext('Other Error'),
1265 '2': gettext('Bad Request'),
1266 '3': gettext('Configuration Unsupported'),
1267 '4': gettext('Device Ineligible'),
1268 '5': gettext('Timeout'),
1269 };
1270 return "U2F Error: " + ErrorNames[error] || Proxmox.Utils.unknownText;
1271 },
1272
1273 // Convert an ArrayBuffer to a base64url encoded string.
1274 // A `null` value will be preserved for convenience.
1275 bytes_to_base64url: function(bytes) {
1276 if (bytes === null) {
1277 return null;
1278 }
1279
1280 return btoa(Array
1281 .from(new Uint8Array(bytes))
1282 .map(val => String.fromCharCode(val))
1283 .join(''),
1284 )
1285 .replace(/\+/g, '-')
1286 .replace(/\//g, '_')
1287 .replace(/[=]/g, '');
1288 },
1289
1290 // Convert an a base64url string to an ArrayBuffer.
1291 // A `null` value will be preserved for convenience.
1292 base64url_to_bytes: function(b64u) {
1293 if (b64u === null) {
1294 return null;
1295 }
1296
1297 return new Uint8Array(
1298 atob(b64u
1299 .replace(/-/g, '+')
1300 .replace(/_/g, '/'),
1301 )
1302 .split('')
1303 .map(val => val.charCodeAt(0)),
1304 );
1305 },
23968741
DC
1306
1307 stringToRGB: function(string) {
1308 let hash = 0;
1309 if (!string) {
1310 return hash;
1311 }
1312 string += 'prox'; // give short strings more variance
1313 for (let i = 0; i < string.length; i++) {
1314 hash = string.charCodeAt(i) + ((hash << 5) - hash);
1315 hash = hash & hash; // to int
1316 }
1317
1318 let alpha = 0.7; // make the color a bit brighter
1319 let bg = 255; // assume white background
1320
1321 return [
1322 (hash & 255) * alpha + bg * (1 - alpha),
1323 ((hash >> 8) & 255) * alpha + bg * (1 - alpha),
1324 ((hash >> 16) & 255) * alpha + bg * (1 - alpha),
1325 ];
1326 },
1327
1328 rgbToCss: function(rgb) {
1329 return `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
1330 },
1331
1332 rgbToHex: function(rgb) {
1333 let r = Math.round(rgb[0]).toString(16);
1334 let g = Math.round(rgb[1]).toString(16);
1335 let b = Math.round(rgb[2]).toString(16);
1336 return `${r}${g}${b}`;
1337 },
1338
1339 hexToRGB: function(hex) {
1340 if (!hex) {
1341 return undefined;
1342 }
1343 if (hex.length === 7) {
1344 hex = hex.slice(1);
1345 }
1346 let r = parseInt(hex.slice(0, 2), 16);
1347 let g = parseInt(hex.slice(2, 4), 16);
1348 let b = parseInt(hex.slice(4, 6), 16);
1349 return [r, g, b];
1350 },
1351
1352 // optimized & simplified SAPC function
1353 // https://github.com/Myndex/SAPC-APCA
1354 getTextContrastClass: function(rgb) {
1355 const blkThrs = 0.022;
1356 const blkClmp = 1.414;
1357
1358 // linearize & gamma correction
1359 let r = (rgb[0] / 255) ** 2.4;
1360 let g = (rgb[1] / 255) ** 2.4;
1361 let b = (rgb[2] / 255) ** 2.4;
1362
1363 // relative luminance sRGB
1364 let bg = r * 0.2126729 + g * 0.7151522 + b * 0.0721750;
1365
1366 // black clamp
1367 bg = bg > blkThrs ? bg : bg + (blkThrs - bg) ** blkClmp;
1368
1369 // SAPC with white text
1370 let contrastLight = bg ** 0.65 - 1;
1371 // SAPC with black text
1372 let contrastDark = bg ** 0.56 - 0.046134502;
1373
1374 if (Math.abs(contrastLight) >= Math.abs(contrastDark)) {
1375 return 'light';
1376 } else {
1377 return 'dark';
1378 }
1379 },
1380
1381 getTagElement: function(string, color_overrides) {
1382 let rgb = color_overrides?.[string] || Proxmox.Utils.stringToRGB(string);
1383 let style = `background-color: ${Proxmox.Utils.rgbToCss(rgb)};`;
1384 let cls;
1385 if (rgb.length > 3) {
1386 style += `color: ${Proxmox.Utils.rgbToCss([rgb[3], rgb[4], rgb[5]])}`;
1387 cls = "proxmox-tag-dark";
1388 } else {
1389 let txtCls = Proxmox.Utils.getTextContrastClass(rgb);
1390 cls = `proxmox-tag-${txtCls}`;
1391 }
1392 return `<span class="${cls}" style="${style}">${string}</span>`;
1393 },
8189ce63
DT
1394
1395 // Setting filename here when downloading from a remote url sometimes fails in chromium browsers
1396 // because of a bug when using attribute download in conjunction with a self signed certificate.
1397 // For more info see https://bugs.chromium.org/p/chromium/issues/detail?id=993362
1398 downloadAsFile: function(source, fileName) {
1399 let hiddenElement = document.createElement('a');
1400 hiddenElement.href = source;
1401 hiddenElement.target = '_blank';
1402 if (fileName) {
1403 hiddenElement.download = fileName;
1404 }
1405 hiddenElement.click();
1406 },
ecabd437
TL
1407},
1408
1409 singleton: true,
1410 constructor: function() {
1411 let me = this;
1412 Ext.apply(me, me.utilities);
1413
1414 let IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
1415 let IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
1416 let IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
1417 let IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
1418 let IPV4_CIDR_MASK = "([0-9]{1,2})";
1419 let IPV6_CIDR_MASK = "([0-9]{1,3})";
1420
1421
1422 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
1423 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")/" + IPV4_CIDR_MASK + "$");
1424
1425 /* eslint-disable no-useless-concat,no-multi-spaces */
1426 let IPV6_REGEXP = "(?:" +
1427 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
1428 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
1429 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
1430 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
1431 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
1432 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
1433 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
1434 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
1435 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
1436 ")";
1437 /* eslint-enable no-useless-concat,no-multi-spaces */
1438
1439 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
1440 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")/" + IPV6_CIDR_MASK + "$");
1441 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
1442
1443 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
1444 me.IP64_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + "/" + IPV6_CIDR_MASK + ")|(?:" + IPV4_REGEXP + "/" + IPV4_CIDR_MASK + ")$");
1445
a1d40d37 1446 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])?))";
ecabd437 1447 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
66c5ceb8 1448 me.DnsName_or_Wildcard_match = new RegExp("^(?:\\*\\.)?" + DnsName_REGEXP + "$");
ecabd437 1449
54fc2533 1450 me.CpuSet_match = /^[0-9]+(?:-[0-9]+)?(?:,[0-9]+(?:-[0-9]+)?)*$/;
9109c392 1451
a1d40d37
DC
1452 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(?::(\\d+))?$");
1453 me.HostPortBrackets_match = new RegExp("^\\[(" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](?::(\\d+))?$");
1454 me.IP6_dotnotation_match = new RegExp("^(" + IPV6_REGEXP + ")(?:\\.(\\d+))?$");
7bff067a
DJ
1455 me.Vlan_match = /^vlan(\d+)/;
1456 me.VlanInterface_match = /(\w+)\.(\d+)/;
ecabd437
TL
1457 },
1458});
c2c12542
TL
1459
1460Ext.define('Proxmox.Async', {
1461 singleton: true,
1462
106fe29e 1463 // Returns a Promise resolving to the result of an `API2Request` or rejecting to the error
017a6376 1464 // response on failure
c2c12542
TL
1465 api2: function(reqOpts) {
1466 return new Promise((resolve, reject) => {
1467 delete reqOpts.callback; // not allowed in this api
1468 reqOpts.success = response => resolve(response);
106fe29e 1469 reqOpts.failure = response => reject(response);
c2c12542
TL
1470 Proxmox.Utils.API2Request(reqOpts);
1471 });
1472 },
1473
1474 // Delay for a number of milliseconds.
1475 sleep: function(millis) {
1476 return new Promise((resolve, _reject) => setTimeout(resolve, millis));
1477 },
1478});
51083ee5
FW
1479
1480Ext.override(Ext.data.Store, {
1481 // If the store's proxy is changed while it is waiting for an AJAX
1482 // response, `onProxyLoad` will still be called for the outdated response.
1483 // To avoid displaying inconsistent information, only process responses
1484 // belonging to the current proxy.
1485 onProxyLoad: function(operation) {
1486 let me = this;
1487 if (operation.getProxy() === me.getProxy()) {
1488 me.callParent(arguments);
1489 } else {
1490 console.log(`ignored outdated response: ${operation.getRequest().getUrl()}`);
1491 }
1492 },
1493});