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