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