]> git.proxmox.com Git - proxmox-widget-toolkit.git/blob - src/Utils.js
Utils: refactor updateColumns from pve-manager
[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: {
66 ar: 'Arabic',
67 ca: 'Catalan',
68 zh_CN: 'Chinese (Simplified)',
69 zh_TW: 'Chinese (Traditional)',
70 da: 'Danish',
71 nl: 'Dutch',
72 en: 'English',
73 eu: 'Euskera (Basque)',
74 fr: 'French',
75 de: 'German',
76 he: 'Hebrew',
77 it: 'Italian',
78 ja: 'Japanese',
79 kr: 'Korean',
80 nb: 'Norwegian (Bokmal)',
81 nn: 'Norwegian (Nynorsk)',
82 fa: 'Persian (Farsi)',
83 pl: 'Polish',
84 pt_BR: 'Portuguese (Brazil)',
85 ru: 'Russian',
86 sl: 'Slovenian',
87 es: 'Spanish',
88 sv: 'Swedish',
89 tr: 'Turkish',
90 },
91
92 render_language: function(value) {
93 if (!value) {
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) {
158 let seconds = 0, minutes = 0, hours = 0, days = 0;
159
160 if (ut <= 0.1) {
161 return '<0.1s';
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) {
174 days = remaining;
175 }
176 }
177 }
178
179 let res = [];
180 let add = (t, unit) => {
181 if (t > 0) res.push(t + unit);
182 return t > 0;
183 };
184
185 let addSeconds = !add(days, 'd');
186 add(hours, 'h');
187 add(minutes, 'm');
188 if (addSeconds) {
189 add(seconds, 's');
190 }
191 return res.join(' ');
192 },
193
194 format_duration_long: function(ut) {
195 let days = Math.floor(ut / 86400);
196 ut -= days*86400;
197 let hours = Math.floor(ut / 3600);
198 ut -= hours*3600;
199 let mins = Math.floor(ut / 60);
200 ut -= mins*60;
201
202 let hours_str = '00' + hours.toString();
203 hours_str = hours_str.substr(hours_str.length - 2);
204 let mins_str = "00" + mins.toString();
205 mins_str = mins_str.substr(mins_str.length - 2);
206 let ut_str = "00" + ut.toString();
207 ut_str = ut_str.substr(ut_str.length - 2);
208
209 if (days) {
210 let ds = days > 1 ? Proxmox.Utils.daysText : Proxmox.Utils.dayText;
211 return days.toString() + ' ' + ds + ' ' +
212 hours_str + ':' + mins_str + ':' + ut_str;
213 } else {
214 return hours_str + ':' + mins_str + ':' + ut_str;
215 }
216 },
217
218 format_subscription_level: function(level) {
219 if (level === 'c') {
220 return 'Community';
221 } else if (level === 'b') {
222 return 'Basic';
223 } else if (level === 's') {
224 return 'Standard';
225 } else if (level === 'p') {
226 return 'Premium';
227 } else {
228 return Proxmox.Utils.noneText;
229 }
230 },
231
232 compute_min_label_width: function(text, width) {
233 if (width === undefined) { width = 100; }
234
235 let tm = new Ext.util.TextMetrics();
236 let min = tm.getWidth(text + ':');
237
238 return min < width ? width : min;
239 },
240
241 getStoredAuth: function() {
242 let storedAuth = JSON.parse(window.localStorage.getItem('ProxmoxUser'));
243 return storedAuth || {};
244 },
245
246 setAuthData: function(data) {
247 Proxmox.UserName = data.username;
248 Proxmox.LoggedOut = data.LoggedOut;
249 // creates a session cookie (expire = null)
250 // that way the cookie gets deleted after the browser window is closed
251 if (data.ticket) {
252 Proxmox.CSRFPreventionToken = data.CSRFPreventionToken;
253 Ext.util.Cookies.set(Proxmox.Setup.auth_cookie_name, data.ticket, null, '/', null, true);
254 }
255
256 if (data.token) {
257 window.localStorage.setItem('ProxmoxUser', JSON.stringify(data));
258 }
259 },
260
261 authOK: function() {
262 if (Proxmox.LoggedOut) {
263 return undefined;
264 }
265 let storedAuth = Proxmox.Utils.getStoredAuth();
266 let cookie = Ext.util.Cookies.get(Proxmox.Setup.auth_cookie_name);
267 if ((Proxmox.UserName !== '' && cookie && !cookie.startsWith("PVE:tfa!")) || storedAuth.token) {
268 return cookie || storedAuth.token;
269 } else {
270 return false;
271 }
272 },
273
274 authClear: function() {
275 if (Proxmox.LoggedOut) {
276 return;
277 }
278 Ext.util.Cookies.clear(Proxmox.Setup.auth_cookie_name);
279 window.localStorage.removeItem("ProxmoxUser");
280 },
281
282 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
283 // use el.mask() instead
284 setErrorMask: function(comp, msg) {
285 let el = comp.el;
286 if (!el) {
287 return;
288 }
289 if (!msg) {
290 el.unmask();
291 } else if (msg === true) {
292 el.mask(gettext("Loading..."));
293 } else {
294 el.mask(msg);
295 }
296 },
297
298 getResponseErrorMessage: (err) => {
299 if (!err.statusText) {
300 return gettext('Connection error');
301 }
302 let msg = [`${err.statusText} (${err.status})`];
303 if (err.response && err.response.responseText) {
304 let txt = err.response.responseText;
305 try {
306 let res = JSON.parse(txt);
307 if (res.errors && typeof res.errors === 'object') {
308 for (let [key, value] of Object.entries(res.errors)) {
309 msg.push(Ext.String.htmlEncode(`${key}: ${value}`));
310 }
311 }
312 } catch (e) {
313 // fallback to string
314 msg.push(Ext.String.htmlEncode(txt));
315 }
316 }
317 return msg.join('<br>');
318 },
319
320 monStoreErrors: function(component, store, clearMaskBeforeLoad) {
321 if (clearMaskBeforeLoad) {
322 component.mon(store, 'beforeload', function(s, operation, eOpts) {
323 Proxmox.Utils.setErrorMask(component, false);
324 });
325 } else {
326 component.mon(store, 'beforeload', function(s, operation, eOpts) {
327 if (!component.loadCount) {
328 component.loadCount = 0; // make sure it is nucomponent.ic
329 Proxmox.Utils.setErrorMask(component, true);
330 }
331 });
332 }
333
334 // only works with 'proxmox' proxy
335 component.mon(store.proxy, 'afterload', function(proxy, request, success) {
336 component.loadCount++;
337
338 if (success) {
339 Proxmox.Utils.setErrorMask(component, false);
340 return;
341 }
342
343 let error = request._operation.getError();
344 let msg = Proxmox.Utils.getResponseErrorMessage(error);
345 Proxmox.Utils.setErrorMask(component, msg);
346 });
347 },
348
349 extractRequestError: function(result, verbose) {
350 let msg = gettext('Successful');
351
352 if (!result.success) {
353 msg = gettext("Unknown error");
354 if (result.message) {
355 msg = result.message;
356 if (result.status) {
357 msg += ' (' + result.status + ')';
358 }
359 }
360 if (verbose && Ext.isObject(result.errors)) {
361 msg += "<br>";
362 Ext.Object.each(result.errors, function(prop, desc) {
363 msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " +
364 Ext.htmlEncode(desc);
365 });
366 }
367 }
368
369 return msg;
370 },
371
372 // Ext.Ajax.request
373 API2Request: function(reqOpts) {
374 let newopts = Ext.apply({
375 waitMsg: gettext('Please wait...'),
376 }, reqOpts);
377
378 if (!newopts.url.match(/^\/api2/)) {
379 newopts.url = '/api2/extjs' + newopts.url;
380 }
381 delete newopts.callback;
382
383 let createWrapper = function(successFn, callbackFn, failureFn) {
384 Ext.apply(newopts, {
385 success: function(response, options) {
386 if (options.waitMsgTarget) {
387 if (Proxmox.Utils.toolkit === 'touch') {
388 options.waitMsgTarget.setMasked(false);
389 } else {
390 options.waitMsgTarget.setLoading(false);
391 }
392 }
393 let result = Ext.decode(response.responseText);
394 response.result = result;
395 if (!result.success) {
396 response.htmlStatus = Proxmox.Utils.extractRequestError(result, true);
397 Ext.callback(callbackFn, options.scope, [options, false, response]);
398 Ext.callback(failureFn, options.scope, [response, options]);
399 return;
400 }
401 Ext.callback(callbackFn, options.scope, [options, true, response]);
402 Ext.callback(successFn, options.scope, [response, options]);
403 },
404 failure: function(response, options) {
405 if (options.waitMsgTarget) {
406 if (Proxmox.Utils.toolkit === 'touch') {
407 options.waitMsgTarget.setMasked(false);
408 } else {
409 options.waitMsgTarget.setLoading(false);
410 }
411 }
412 response.result = {};
413 try {
414 response.result = Ext.decode(response.responseText);
415 } catch (e) {
416 // ignore
417 }
418 let msg = gettext('Connection error') + ' - server offline?';
419 if (response.aborted) {
420 msg = gettext('Connection error') + ' - aborted.';
421 } else if (response.timedout) {
422 msg = gettext('Connection error') + ' - Timeout.';
423 } else if (response.status && response.statusText) {
424 msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText;
425 }
426 response.htmlStatus = msg;
427 Ext.callback(callbackFn, options.scope, [options, false, response]);
428 Ext.callback(failureFn, options.scope, [response, options]);
429 },
430 });
431 };
432
433 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
434
435 let target = newopts.waitMsgTarget;
436 if (target) {
437 if (Proxmox.Utils.toolkit === 'touch') {
438 target.setMasked({ xtype: 'loadmask', message: newopts.waitMsg });
439 } else {
440 // Note: ExtJS bug - this does not work when component is not rendered
441 target.setLoading(newopts.waitMsg);
442 }
443 }
444 Ext.Ajax.request(newopts);
445 },
446
447 // can be useful for catching displaying errors from the API, e.g.:
448 // Proxmox.Async.api2({
449 // ...
450 // }).catch(Proxmox.Utils.alertResponseFailure);
451 alertResponseFailure: (response) => {
452 Ext.Msg.alert(
453 gettext('Error'),
454 response.htmlStatus || response.result.message,
455 );
456 },
457
458 checked_command: function(orig_cmd) {
459 Proxmox.Utils.API2Request(
460 {
461 url: '/nodes/localhost/subscription',
462 method: 'GET',
463 failure: function(response, opts) {
464 Ext.Msg.alert(gettext('Error'), response.htmlStatus);
465 },
466 success: function(response, opts) {
467 let res = response.result;
468 if (res === null || res === undefined || !res || res
469 .data.status.toLowerCase() !== 'active') {
470 Ext.Msg.show({
471 title: gettext('No valid subscription'),
472 icon: Ext.Msg.WARNING,
473 message: Proxmox.Utils.getNoSubKeyHtml(res.data.url),
474 buttons: Ext.Msg.OK,
475 callback: function(btn) {
476 if (btn !== 'ok') {
477 return;
478 }
479 orig_cmd();
480 },
481 });
482 } else {
483 orig_cmd();
484 }
485 },
486 },
487 );
488 },
489
490 assemble_field_data: function(values, data) {
491 if (!Ext.isObject(data)) {
492 return;
493 }
494 Ext.Object.each(data, function(name, val) {
495 if (Object.prototype.hasOwnProperty.call(values, name)) {
496 let bucket = values[name];
497 if (!Ext.isArray(bucket)) {
498 bucket = values[name] = [bucket];
499 }
500 if (Ext.isArray(val)) {
501 values[name] = bucket.concat(val);
502 } else {
503 bucket.push(val);
504 }
505 } else {
506 values[name] = val;
507 }
508 });
509 },
510
511 updateColumnWidth: function(container) {
512 let mode = Ext.state.Manager.get('summarycolumns') || 'auto';
513 let factor;
514 if (mode !== 'auto') {
515 factor = parseInt(mode, 10);
516 if (Number.isNaN(factor)) {
517 factor = 1;
518 }
519 } else {
520 factor = container.getSize().width < 1600 ? 1 : 2;
521 }
522
523 if (container.oldFactor === factor) {
524 return;
525 }
526
527 let items = container.query('>'); // direct childs
528 factor = Math.min(factor, items.length);
529 container.oldFactor = factor;
530
531 items.forEach((item) => {
532 item.columnWidth = 1 / factor;
533 });
534
535 // we have to update the layout twice, since the first layout change
536 // can trigger the scrollbar which reduces the amount of space left
537 container.updateLayout();
538 container.updateLayout();
539 },
540
541 dialog_title: function(subject, create, isAdd) {
542 if (create) {
543 if (isAdd) {
544 return gettext('Add') + ': ' + subject;
545 } else {
546 return gettext('Create') + ': ' + subject;
547 }
548 } else {
549 return gettext('Edit') + ': ' + subject;
550 }
551 },
552
553 network_iface_types: {
554 eth: gettext("Network Device"),
555 bridge: 'Linux Bridge',
556 bond: 'Linux Bond',
557 vlan: 'Linux VLAN',
558 OVSBridge: 'OVS Bridge',
559 OVSBond: 'OVS Bond',
560 OVSPort: 'OVS Port',
561 OVSIntPort: 'OVS IntPort',
562 },
563
564 render_network_iface_type: function(value) {
565 return Proxmox.Utils.network_iface_types[value] ||
566 Proxmox.Utils.unknownText;
567 },
568
569 task_desc_table: {
570 aptupdate: ['', gettext('Update package database')],
571 diskinit: ['Disk', gettext('Initialize Disk with GPT')],
572 spiceshell: ['', gettext('Shell') + ' (Spice)'],
573 srvreload: ['SRV', gettext('Reload')],
574 srvrestart: ['SRV', gettext('Restart')],
575 srvstart: ['SRV', gettext('Start')],
576 srvstop: ['SRV', gettext('Stop')],
577 termproxy: ['', gettext('Console') + ' (xterm.js)'],
578 vncshell: ['', gettext('Shell')],
579 },
580
581 // to add or change existing for product specific ones
582 override_task_descriptions: function(extra) {
583 for (const [key, value] of Object.entries(extra)) {
584 Proxmox.Utils.task_desc_table[key] = value;
585 }
586 },
587
588 format_task_description: function(type, id) {
589 let farray = Proxmox.Utils.task_desc_table[type];
590 let text;
591 if (!farray) {
592 text = type;
593 if (id) {
594 type += ' ' + id;
595 }
596 return text;
597 } else if (Ext.isFunction(farray)) {
598 return farray(type, id);
599 }
600 let prefix = farray[0];
601 text = farray[1];
602 if (prefix && id !== undefined) {
603 return prefix + ' ' + id + ' - ' + text;
604 }
605 return text;
606 },
607
608 format_size: function(size) {
609 let units = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'];
610 let num = 0;
611 while (size >= 1024 && num++ <= units.length) {
612 size = size / 1024;
613 }
614
615 return size.toFixed(num > 0?2:0) + " " + units[num] + "B";
616 },
617
618 render_upid: function(value, metaData, record) {
619 let task = record.data;
620 let type = task.type || task.worker_type;
621 let id = task.id || task.worker_id;
622
623 return Proxmox.Utils.format_task_description(type, id);
624 },
625
626 render_uptime: function(value) {
627 let uptime = value;
628
629 if (uptime === undefined) {
630 return '';
631 }
632
633 if (uptime <= 0) {
634 return '-';
635 }
636
637 return Proxmox.Utils.format_duration_long(uptime);
638 },
639
640 systemd_unescape: function(string_value) {
641 const charcode_0 = '0'.charCodeAt(0);
642 const charcode_9 = '9'.charCodeAt(0);
643 const charcode_A = 'A'.charCodeAt(0);
644 const charcode_F = 'F'.charCodeAt(0);
645 const charcode_a = 'a'.charCodeAt(0);
646 const charcode_f = 'f'.charCodeAt(0);
647 const charcode_x = 'x'.charCodeAt(0);
648 const charcode_minus = '-'.charCodeAt(0);
649 const charcode_slash = '/'.charCodeAt(0);
650 const charcode_backslash = '\\'.charCodeAt(0);
651
652 let parse_hex_digit = function(d) {
653 if (d >= charcode_0 && d <= charcode_9) {
654 return d - charcode_0;
655 }
656 if (d >= charcode_A && d <= charcode_F) {
657 return d - charcode_A + 10;
658 }
659 if (d >= charcode_a && d <= charcode_f) {
660 return d - charcode_a + 10;
661 }
662 throw "got invalid hex digit";
663 };
664
665 let value = new TextEncoder().encode(string_value);
666 let result = new Uint8Array(value.length);
667
668 let i = 0;
669 let result_len = 0;
670
671 while (i < value.length) {
672 let c0 = value[i];
673 if (c0 === charcode_minus) {
674 result.set([charcode_slash], result_len);
675 result_len += 1;
676 i += 1;
677 continue;
678 }
679 if ((i + 4) < value.length) {
680 let c1 = value[i+1];
681 if (c0 === charcode_backslash && c1 === charcode_x) {
682 let h1 = parse_hex_digit(value[i+2]);
683 let h0 = parse_hex_digit(value[i+3]);
684 let ord = h1*16+h0;
685 result.set([ord], result_len);
686 result_len += 1;
687 i += 4;
688 continue;
689 }
690 }
691 result.set([c0], result_len);
692 result_len += 1;
693 i += 1;
694 }
695
696 return new TextDecoder().decode(result.slice(0, result.len));
697 },
698
699 parse_task_upid: function(upid) {
700 let task = {};
701
702 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]+):$/);
703 if (!res) {
704 throw "unable to parse upid '" + upid + "'";
705 }
706 task.node = res[1];
707 task.pid = parseInt(res[2], 16);
708 task.pstart = parseInt(res[3], 16);
709 if (res[5] !== undefined) {
710 task.task_id = parseInt(res[5], 16);
711 }
712 task.starttime = parseInt(res[6], 16);
713 task.type = res[7];
714 task.id = Proxmox.Utils.systemd_unescape(res[8]);
715 task.user = res[9];
716
717 task.desc = Proxmox.Utils.format_task_description(task.type, task.id);
718
719 return task;
720 },
721
722 parse_task_status: function(status) {
723 if (status === 'OK') {
724 return 'ok';
725 }
726
727 if (status === 'unknown') {
728 return 'unknown';
729 }
730
731 let match = status.match(/^WARNINGS: (.*)$/);
732 if (match) {
733 return 'warning';
734 }
735
736 return 'error';
737 },
738
739 render_duration: function(value) {
740 if (value === undefined) {
741 return '-';
742 }
743 return Proxmox.Utils.format_duration_human(value);
744 },
745
746 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
747 let servertime = new Date(value * 1000);
748 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
749 },
750
751 render_zfs_health: function(value) {
752 if (typeof value === 'undefined') {
753 return "";
754 }
755 var iconCls = 'question-circle';
756 switch (value) {
757 case 'AVAIL':
758 case 'ONLINE':
759 iconCls = 'check-circle good';
760 break;
761 case 'REMOVED':
762 case 'DEGRADED':
763 iconCls = 'exclamation-circle warning';
764 break;
765 case 'UNAVAIL':
766 case 'FAULTED':
767 case 'OFFLINE':
768 iconCls = 'times-circle critical';
769 break;
770 default: //unknown
771 }
772
773 return '<i class="fa fa-' + iconCls + '"></i> ' + value;
774 },
775
776 get_help_info: function(section) {
777 let helpMap;
778 if (typeof proxmoxOnlineHelpInfo !== 'undefined') {
779 helpMap = proxmoxOnlineHelpInfo; // eslint-disable-line no-undef
780 } else if (typeof pveOnlineHelpInfo !== 'undefined') {
781 // be backward compatible with older pve-doc-generators
782 helpMap = pveOnlineHelpInfo; // eslint-disable-line no-undef
783 } else {
784 throw "no global OnlineHelpInfo map declared";
785 }
786
787 if (helpMap[section]) {
788 return helpMap[section];
789 }
790 // try to normalize - and _ separators, to support asciidoc and sphinx
791 // references at the same time.
792 let section_minus_normalized = section.replace(/_/g, '-');
793 if (helpMap[section_minus_normalized]) {
794 return helpMap[section_minus_normalized];
795 }
796 let section_underscore_normalized = section.replace(/-/g, '_');
797 return helpMap[section_underscore_normalized];
798 },
799
800 get_help_link: function(section) {
801 let info = Proxmox.Utils.get_help_info(section);
802 if (!info) {
803 return undefined;
804 }
805 return window.location.origin + info.link;
806 },
807
808 openXtermJsViewer: function(vmtype, vmid, nodename, vmname, cmd) {
809 let url = Ext.Object.toQueryString({
810 console: vmtype, // kvm, lxc, upgrade or shell
811 xtermjs: 1,
812 vmid: vmid,
813 vmname: vmname,
814 node: nodename,
815 cmd: cmd,
816
817 });
818 let nw = window.open("?" + url, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
819 if (nw) {
820 nw.focus();
821 }
822 },
823
824 render_optional_url: function(value) {
825 if (value && value.match(/^https?:\/\//) !== null) {
826 return '<a target="_blank" href="' + value + '">' + value + '</a>';
827 }
828 return value;
829 },
830
831 render_san: function(value) {
832 var names = [];
833 if (Ext.isArray(value)) {
834 value.forEach(function(val) {
835 if (!Ext.isNumber(val)) {
836 names.push(val);
837 }
838 });
839 return names.join('<br>');
840 }
841 return value;
842 },
843
844 render_usage: function(val) {
845 return (val*100).toFixed(2) + '%';
846 },
847
848 render_cpu_usage: function(val, max) {
849 return Ext.String.format(gettext('{0}% of {1}') +
850 ' ' + gettext('CPU(s)'), (val*100).toFixed(2), max);
851 },
852
853 render_size_usage: function(val, max) {
854 if (max === 0) {
855 return gettext('N/A');
856 }
857 return (val*100/max).toFixed(2) + '% (' +
858 Ext.String.format(gettext('{0} of {1}'),
859 Proxmox.Utils.render_size(val), Proxmox.Utils.render_size(max)) + ')';
860 },
861
862 render_cpu: function(value, metaData, record, rowIndex, colIndex, store) {
863 if (!(record.data.uptime && Ext.isNumeric(value))) {
864 return '';
865 }
866
867 var maxcpu = record.data.maxcpu || 1;
868
869 if (!Ext.isNumeric(maxcpu) && maxcpu >= 1) {
870 return '';
871 }
872
873 var per = value * 100;
874
875 return per.toFixed(1) + '% of ' + maxcpu.toString() + (maxcpu > 1 ? 'CPUs' : 'CPU');
876 },
877
878 render_size: function(value, metaData, record, rowIndex, colIndex, store) {
879 if (!Ext.isNumeric(value)) {
880 return '';
881 }
882
883 return Proxmox.Utils.format_size(value);
884 },
885
886 render_cpu_model: function(cpuinfo) {
887 return cpuinfo.cpus + " x " + cpuinfo.model + " (" +
888 cpuinfo.sockets.toString() + " " +
889 (cpuinfo.sockets > 1
890 ? gettext('Sockets')
891 : gettext('Socket')
892 ) + ")";
893 },
894
895 /* this is different for nodes */
896 render_node_cpu_usage: function(value, record) {
897 return Proxmox.Utils.render_cpu_usage(value, record.cpus);
898 },
899
900 render_node_size_usage: function(record) {
901 return Proxmox.Utils.render_size_usage(record.used, record.total);
902 },
903
904 loadTextFromFile: function(file, callback, maxBytes) {
905 let maxSize = maxBytes || 8192;
906 if (file.size > maxSize) {
907 Ext.Msg.alert(gettext('Error'), gettext("Invalid file size: ") + file.size);
908 return;
909 }
910 let reader = new FileReader();
911 reader.onload = evt => callback(evt.target.result);
912 reader.readAsText(file);
913 },
914
915 parsePropertyString: function(value, defaultKey) {
916 var res = {},
917 error;
918
919 if (typeof value !== 'string' || value === '') {
920 return res;
921 }
922
923 Ext.Array.each(value.split(','), function(p) {
924 var kv = p.split('=', 2);
925 if (Ext.isDefined(kv[1])) {
926 res[kv[0]] = kv[1];
927 } else if (Ext.isDefined(defaultKey)) {
928 if (Ext.isDefined(res[defaultKey])) {
929 error = 'defaultKey may be only defined once in propertyString';
930 return false; // break
931 }
932 res[defaultKey] = kv[0];
933 } else {
934 error = 'invalid propertyString, not a key=value pair and no defaultKey defined';
935 return false; // break
936 }
937 return true;
938 });
939
940 if (error !== undefined) {
941 console.error(error);
942 return undefined;
943 }
944
945 return res;
946 },
947
948 printPropertyString: function(data, defaultKey) {
949 var stringparts = [],
950 gotDefaultKeyVal = false,
951 defaultKeyVal;
952
953 Ext.Object.each(data, function(key, value) {
954 if (defaultKey !== undefined && key === defaultKey) {
955 gotDefaultKeyVal = true;
956 defaultKeyVal = value;
957 } else if (Ext.isArray(value)) {
958 stringparts.push(key + '=' + value.join(';'));
959 } else if (value !== '') {
960 stringparts.push(key + '=' + value);
961 }
962 });
963
964 stringparts = stringparts.sort();
965 if (gotDefaultKeyVal) {
966 stringparts.unshift(defaultKeyVal);
967 }
968
969 return stringparts.join(',');
970 },
971
972 acmedomain_count: 5,
973
974 parseACMEPluginData: function(data) {
975 let res = {};
976 let extradata = [];
977 data.split('\n').forEach((line) => {
978 // capture everything after the first = as value
979 let [key, value] = line.split('=');
980 if (value !== undefined) {
981 res[key] = value;
982 } else {
983 extradata.push(line);
984 }
985 });
986 return [res, extradata];
987 },
988
989 delete_if_default: function(values, fieldname, default_val, create) {
990 if (values[fieldname] === '' || values[fieldname] === default_val) {
991 if (!create) {
992 if (values.delete) {
993 if (Ext.isArray(values.delete)) {
994 values.delete.push(fieldname);
995 } else {
996 values.delete += ',' + fieldname;
997 }
998 } else {
999 values.delete = fieldname;
1000 }
1001 }
1002
1003 delete values[fieldname];
1004 }
1005 },
1006
1007 printACME: function(value) {
1008 if (Ext.isArray(value.domains)) {
1009 value.domains = value.domains.join(';');
1010 }
1011 return Proxmox.Utils.printPropertyString(value);
1012 },
1013
1014 parseACME: function(value) {
1015 if (!value) {
1016 return {};
1017 }
1018
1019 var res = {};
1020 var error;
1021
1022 Ext.Array.each(value.split(','), function(p) {
1023 var kv = p.split('=', 2);
1024 if (Ext.isDefined(kv[1])) {
1025 res[kv[0]] = kv[1];
1026 } else {
1027 error = 'Failed to parse key-value pair: '+p;
1028 return false;
1029 }
1030 return true;
1031 });
1032
1033 if (error !== undefined) {
1034 console.error(error);
1035 return undefined;
1036 }
1037
1038 if (res.domains !== undefined) {
1039 res.domains = res.domains.split(/;/);
1040 }
1041
1042 return res;
1043 },
1044
1045 add_domain_to_acme: function(acme, domain) {
1046 if (acme.domains === undefined) {
1047 acme.domains = [domain];
1048 } else {
1049 acme.domains.push(domain);
1050 acme.domains = acme.domains.filter((value, index, self) => self.indexOf(value) === index);
1051 }
1052 return acme;
1053 },
1054
1055 remove_domain_from_acme: function(acme, domain) {
1056 if (acme.domains !== undefined) {
1057 acme.domains = acme.domains.filter(
1058 (value, index, self) => self.indexOf(value) === index && value !== domain,
1059 );
1060 }
1061 return acme;
1062 },
1063
1064 updateColumns: function(container) {
1065 let mode = Ext.state.Manager.get('summarycolumns') || 'auto';
1066 let factor;
1067 if (mode !== 'auto') {
1068 factor = parseInt(mode, 10);
1069 if (Number.isNaN(factor)) {
1070 factor = 1;
1071 }
1072 } else {
1073 factor = container.getSize().width < 1400 ? 1 : 2;
1074 }
1075
1076 if (container.oldFactor === factor) {
1077 return;
1078 }
1079
1080 let items = container.query('>'); // direct childs
1081 factor = Math.min(factor, items.length);
1082 container.oldFactor = factor;
1083
1084 items.forEach((item) => {
1085 item.columnWidth = 1 / factor;
1086 });
1087
1088 // we have to update the layout twice, since the first layout change
1089 // can trigger the scrollbar which reduces the amount of space left
1090 container.updateLayout();
1091 container.updateLayout();
1092 },
1093 },
1094
1095 singleton: true,
1096 constructor: function() {
1097 let me = this;
1098 Ext.apply(me, me.utilities);
1099
1100 let IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
1101 let IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
1102 let IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
1103 let IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
1104 let IPV4_CIDR_MASK = "([0-9]{1,2})";
1105 let IPV6_CIDR_MASK = "([0-9]{1,3})";
1106
1107
1108 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
1109 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")/" + IPV4_CIDR_MASK + "$");
1110
1111 /* eslint-disable no-useless-concat,no-multi-spaces */
1112 let IPV6_REGEXP = "(?:" +
1113 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
1114 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
1115 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
1116 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
1117 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
1118 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
1119 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
1120 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
1121 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
1122 ")";
1123 /* eslint-enable no-useless-concat,no-multi-spaces */
1124
1125 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
1126 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")/" + IPV6_CIDR_MASK + "$");
1127 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
1128
1129 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
1130 me.IP64_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + "/" + IPV6_CIDR_MASK + ")|(?:" + IPV4_REGEXP + "/" + IPV4_CIDR_MASK + ")$");
1131
1132 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])?))";
1133 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
1134
1135 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(?::(\\d+))?$");
1136 me.HostPortBrackets_match = new RegExp("^\\[(" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](?::(\\d+))?$");
1137 me.IP6_dotnotation_match = new RegExp("^(" + IPV6_REGEXP + ")(?:\\.(\\d+))?$");
1138 me.Vlan_match = /^vlan(\d+)/;
1139 me.VlanInterface_match = /(\w+)\.(\d+)/;
1140 },
1141 });
1142
1143 Ext.define('Proxmox.Async', {
1144 singleton: true,
1145
1146 // Returns a Promise resolving to the result of an `API2Request` or rejecting to the error
1147 // repsonse on failure
1148 api2: function(reqOpts) {
1149 return new Promise((resolve, reject) => {
1150 delete reqOpts.callback; // not allowed in this api
1151 reqOpts.success = response => resolve(response);
1152 reqOpts.failure = response => reject(response);
1153 Proxmox.Utils.API2Request(reqOpts);
1154 });
1155 },
1156
1157 // Delay for a number of milliseconds.
1158 sleep: function(millis) {
1159 return new Promise((resolve, _reject) => setTimeout(resolve, millis));
1160 },
1161 });