]> git.proxmox.com Git - proxmox-widget-toolkit.git/blob - src/Utils.js
bump version to 4.2.4
[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, errorCallback) {
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 if (!errorCallback || !errorCallback(error, msg)) {
346 Proxmox.Utils.setErrorMask(component, msg);
347 }
348 });
349 },
350
351 extractRequestError: function(result, verbose) {
352 let msg = gettext('Successful');
353
354 if (!result.success) {
355 msg = gettext("Unknown error");
356 if (result.message) {
357 msg = result.message;
358 if (result.status) {
359 msg += ' (' + result.status + ')';
360 }
361 }
362 if (verbose && Ext.isObject(result.errors)) {
363 msg += "<br>";
364 Ext.Object.each(result.errors, function(prop, desc) {
365 msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " +
366 Ext.htmlEncode(desc);
367 });
368 }
369 }
370
371 return msg;
372 },
373
374 // Ext.Ajax.request
375 API2Request: function(reqOpts) {
376 let newopts = Ext.apply({
377 waitMsg: gettext('Please wait...'),
378 }, reqOpts);
379
380 if (!newopts.url.match(/^\/api2/)) {
381 newopts.url = '/api2/extjs' + newopts.url;
382 }
383 delete newopts.callback;
384
385 let createWrapper = function(successFn, callbackFn, failureFn) {
386 Ext.apply(newopts, {
387 success: function(response, options) {
388 if (options.waitMsgTarget) {
389 if (Proxmox.Utils.toolkit === 'touch') {
390 options.waitMsgTarget.setMasked(false);
391 } else {
392 options.waitMsgTarget.setLoading(false);
393 }
394 }
395 let result = Ext.decode(response.responseText);
396 response.result = result;
397 if (!result.success) {
398 response.htmlStatus = Proxmox.Utils.extractRequestError(result, true);
399 Ext.callback(callbackFn, options.scope, [options, false, response]);
400 Ext.callback(failureFn, options.scope, [response, options]);
401 return;
402 }
403 Ext.callback(callbackFn, options.scope, [options, true, response]);
404 Ext.callback(successFn, options.scope, [response, options]);
405 },
406 failure: function(response, options) {
407 if (options.waitMsgTarget) {
408 if (Proxmox.Utils.toolkit === 'touch') {
409 options.waitMsgTarget.setMasked(false);
410 } else {
411 options.waitMsgTarget.setLoading(false);
412 }
413 }
414 response.result = {};
415 try {
416 response.result = Ext.decode(response.responseText);
417 } catch (e) {
418 // ignore
419 }
420 let msg = gettext('Connection error') + ' - server offline?';
421 if (response.aborted) {
422 msg = gettext('Connection error') + ' - aborted.';
423 } else if (response.timedout) {
424 msg = gettext('Connection error') + ' - Timeout.';
425 } else if (response.status && response.statusText) {
426 msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText;
427 }
428 response.htmlStatus = msg;
429 Ext.callback(callbackFn, options.scope, [options, false, response]);
430 Ext.callback(failureFn, options.scope, [response, options]);
431 },
432 });
433 };
434
435 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
436
437 let target = newopts.waitMsgTarget;
438 if (target) {
439 if (Proxmox.Utils.toolkit === 'touch') {
440 target.setMasked({ xtype: 'loadmask', message: newopts.waitMsg });
441 } else {
442 // Note: ExtJS bug - this does not work when component is not rendered
443 target.setLoading(newopts.waitMsg);
444 }
445 }
446 Ext.Ajax.request(newopts);
447 },
448
449 // can be useful for catching displaying errors from the API, e.g.:
450 // Proxmox.Async.api2({
451 // ...
452 // }).catch(Proxmox.Utils.alertResponseFailure);
453 alertResponseFailure: (response) => {
454 Ext.Msg.alert(
455 gettext('Error'),
456 response.htmlStatus || response.result.message,
457 );
458 },
459
460 checked_command: function(orig_cmd) {
461 Proxmox.Utils.API2Request(
462 {
463 url: '/nodes/localhost/subscription',
464 method: 'GET',
465 failure: function(response, opts) {
466 Ext.Msg.alert(gettext('Error'), response.htmlStatus);
467 },
468 success: function(response, opts) {
469 let res = response.result;
470 if (res === null || res === undefined || !res || res
471 .data.status.toLowerCase() !== 'active') {
472 Ext.Msg.show({
473 title: gettext('No valid subscription'),
474 icon: Ext.Msg.WARNING,
475 message: Proxmox.Utils.getNoSubKeyHtml(res.data.url),
476 buttons: Ext.Msg.OK,
477 callback: function(btn) {
478 if (btn !== 'ok') {
479 return;
480 }
481 orig_cmd();
482 },
483 });
484 } else {
485 orig_cmd();
486 }
487 },
488 },
489 );
490 },
491
492 assemble_field_data: function(values, data) {
493 if (!Ext.isObject(data)) {
494 return;
495 }
496 Ext.Object.each(data, function(name, val) {
497 if (Object.prototype.hasOwnProperty.call(values, name)) {
498 let bucket = values[name];
499 if (!Ext.isArray(bucket)) {
500 bucket = values[name] = [bucket];
501 }
502 if (Ext.isArray(val)) {
503 values[name] = bucket.concat(val);
504 } else {
505 bucket.push(val);
506 }
507 } else {
508 values[name] = val;
509 }
510 });
511 },
512
513 updateColumnWidth: function(container) {
514 let mode = Ext.state.Manager.get('summarycolumns') || 'auto';
515 let factor;
516 if (mode !== 'auto') {
517 factor = parseInt(mode, 10);
518 if (Number.isNaN(factor)) {
519 factor = 1;
520 }
521 } else {
522 factor = container.getSize().width < 1600 ? 1 : 2;
523 }
524
525 if (container.oldFactor === factor) {
526 return;
527 }
528
529 let items = container.query('>'); // direct childs
530 factor = Math.min(factor, items.length);
531 container.oldFactor = factor;
532
533 items.forEach((item) => {
534 item.columnWidth = 1 / factor;
535 });
536
537 // we have to update the layout twice, since the first layout change
538 // can trigger the scrollbar which reduces the amount of space left
539 container.updateLayout();
540 container.updateLayout();
541 },
542
543 dialog_title: function(subject, create, isAdd) {
544 if (create) {
545 if (isAdd) {
546 return gettext('Add') + ': ' + subject;
547 } else {
548 return gettext('Create') + ': ' + subject;
549 }
550 } else {
551 return gettext('Edit') + ': ' + subject;
552 }
553 },
554
555 network_iface_types: {
556 eth: gettext("Network Device"),
557 bridge: 'Linux Bridge',
558 bond: 'Linux Bond',
559 vlan: 'Linux VLAN',
560 OVSBridge: 'OVS Bridge',
561 OVSBond: 'OVS Bond',
562 OVSPort: 'OVS Port',
563 OVSIntPort: 'OVS IntPort',
564 },
565
566 render_network_iface_type: function(value) {
567 return Proxmox.Utils.network_iface_types[value] ||
568 Proxmox.Utils.unknownText;
569 },
570
571 task_desc_table: {
572 aptupdate: ['', gettext('Update package database')],
573 diskinit: ['Disk', gettext('Initialize Disk with GPT')],
574 spiceshell: ['', gettext('Shell') + ' (Spice)'],
575 srvreload: ['SRV', gettext('Reload')],
576 srvrestart: ['SRV', gettext('Restart')],
577 srvstart: ['SRV', gettext('Start')],
578 srvstop: ['SRV', gettext('Stop')],
579 termproxy: ['', gettext('Console') + ' (xterm.js)'],
580 vncshell: ['', gettext('Shell')],
581 },
582
583 // to add or change existing for product specific ones
584 override_task_descriptions: function(extra) {
585 for (const [key, value] of Object.entries(extra)) {
586 Proxmox.Utils.task_desc_table[key] = value;
587 }
588 },
589
590 format_task_description: function(type, id) {
591 let farray = Proxmox.Utils.task_desc_table[type];
592 let text;
593 if (!farray) {
594 text = type;
595 if (id) {
596 type += ' ' + id;
597 }
598 return text;
599 } else if (Ext.isFunction(farray)) {
600 return farray(type, id);
601 }
602 let prefix = farray[0];
603 text = farray[1];
604 if (prefix && id !== undefined) {
605 return prefix + ' ' + id + ' - ' + text;
606 }
607 return text;
608 },
609
610 format_size: function(size) {
611 let units = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'];
612 let num = 0;
613 while (size >= 1024 && num++ <= units.length) {
614 size = size / 1024;
615 }
616
617 return size.toFixed(num > 0?2:0) + " " + units[num] + "B";
618 },
619
620 render_upid: function(value, metaData, record) {
621 let task = record.data;
622 let type = task.type || task.worker_type;
623 let id = task.id || task.worker_id;
624
625 return Proxmox.Utils.format_task_description(type, id);
626 },
627
628 render_uptime: function(value) {
629 let uptime = value;
630
631 if (uptime === undefined) {
632 return '';
633 }
634
635 if (uptime <= 0) {
636 return '-';
637 }
638
639 return Proxmox.Utils.format_duration_long(uptime);
640 },
641
642 systemd_unescape: function(string_value) {
643 const charcode_0 = '0'.charCodeAt(0);
644 const charcode_9 = '9'.charCodeAt(0);
645 const charcode_A = 'A'.charCodeAt(0);
646 const charcode_F = 'F'.charCodeAt(0);
647 const charcode_a = 'a'.charCodeAt(0);
648 const charcode_f = 'f'.charCodeAt(0);
649 const charcode_x = 'x'.charCodeAt(0);
650 const charcode_minus = '-'.charCodeAt(0);
651 const charcode_slash = '/'.charCodeAt(0);
652 const charcode_backslash = '\\'.charCodeAt(0);
653
654 let parse_hex_digit = function(d) {
655 if (d >= charcode_0 && d <= charcode_9) {
656 return d - charcode_0;
657 }
658 if (d >= charcode_A && d <= charcode_F) {
659 return d - charcode_A + 10;
660 }
661 if (d >= charcode_a && d <= charcode_f) {
662 return d - charcode_a + 10;
663 }
664 throw "got invalid hex digit";
665 };
666
667 let value = new TextEncoder().encode(string_value);
668 let result = new Uint8Array(value.length);
669
670 let i = 0;
671 let result_len = 0;
672
673 while (i < value.length) {
674 let c0 = value[i];
675 if (c0 === charcode_minus) {
676 result.set([charcode_slash], result_len);
677 result_len += 1;
678 i += 1;
679 continue;
680 }
681 if ((i + 4) < value.length) {
682 let c1 = value[i+1];
683 if (c0 === charcode_backslash && c1 === charcode_x) {
684 let h1 = parse_hex_digit(value[i+2]);
685 let h0 = parse_hex_digit(value[i+3]);
686 let ord = h1*16+h0;
687 result.set([ord], result_len);
688 result_len += 1;
689 i += 4;
690 continue;
691 }
692 }
693 result.set([c0], result_len);
694 result_len += 1;
695 i += 1;
696 }
697
698 return new TextDecoder().decode(result.slice(0, result.len));
699 },
700
701 parse_task_upid: function(upid) {
702 let task = {};
703
704 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]+):$/);
705 if (!res) {
706 throw "unable to parse upid '" + upid + "'";
707 }
708 task.node = res[1];
709 task.pid = parseInt(res[2], 16);
710 task.pstart = parseInt(res[3], 16);
711 if (res[5] !== undefined) {
712 task.task_id = parseInt(res[5], 16);
713 }
714 task.starttime = parseInt(res[6], 16);
715 task.type = res[7];
716 task.id = Proxmox.Utils.systemd_unescape(res[8]);
717 task.user = res[9];
718
719 task.desc = Proxmox.Utils.format_task_description(task.type, task.id);
720
721 return task;
722 },
723
724 parse_task_status: function(status) {
725 if (status === 'OK') {
726 return 'ok';
727 }
728
729 if (status === 'unknown') {
730 return 'unknown';
731 }
732
733 let match = status.match(/^WARNINGS: (.*)$/);
734 if (match) {
735 return 'warning';
736 }
737
738 return 'error';
739 },
740
741 format_task_status: function(status) {
742 let parsed = Proxmox.Utils.parse_task_status(status);
743 switch (parsed) {
744 case 'unknown': return Proxmox.Utils.unknownText;
745 case 'error': return Proxmox.Utils.errorText + ': ' + status;
746 case 'warning': return status.replace('WARNINGS', Proxmox.Utils.warningsText);
747 case 'ok': // fall-through
748 default: return status;
749 }
750 },
751
752 render_duration: function(value) {
753 if (value === undefined) {
754 return '-';
755 }
756 return Proxmox.Utils.format_duration_human(value);
757 },
758
759 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
760 let servertime = new Date(value * 1000);
761 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
762 },
763
764 render_zfs_health: function(value) {
765 if (typeof value === 'undefined') {
766 return "";
767 }
768 var iconCls = 'question-circle';
769 switch (value) {
770 case 'AVAIL':
771 case 'ONLINE':
772 iconCls = 'check-circle good';
773 break;
774 case 'REMOVED':
775 case 'DEGRADED':
776 iconCls = 'exclamation-circle warning';
777 break;
778 case 'UNAVAIL':
779 case 'FAULTED':
780 case 'OFFLINE':
781 iconCls = 'times-circle critical';
782 break;
783 default: //unknown
784 }
785
786 return '<i class="fa fa-' + iconCls + '"></i> ' + value;
787 },
788
789 get_help_info: function(section) {
790 let helpMap;
791 if (typeof proxmoxOnlineHelpInfo !== 'undefined') {
792 helpMap = proxmoxOnlineHelpInfo; // eslint-disable-line no-undef
793 } else if (typeof pveOnlineHelpInfo !== 'undefined') {
794 // be backward compatible with older pve-doc-generators
795 helpMap = pveOnlineHelpInfo; // eslint-disable-line no-undef
796 } else {
797 throw "no global OnlineHelpInfo map declared";
798 }
799
800 if (helpMap[section]) {
801 return helpMap[section];
802 }
803 // try to normalize - and _ separators, to support asciidoc and sphinx
804 // references at the same time.
805 let section_minus_normalized = section.replace(/_/g, '-');
806 if (helpMap[section_minus_normalized]) {
807 return helpMap[section_minus_normalized];
808 }
809 let section_underscore_normalized = section.replace(/-/g, '_');
810 return helpMap[section_underscore_normalized];
811 },
812
813 get_help_link: function(section) {
814 let info = Proxmox.Utils.get_help_info(section);
815 if (!info) {
816 return undefined;
817 }
818 return window.location.origin + info.link;
819 },
820
821 openXtermJsViewer: function(vmtype, vmid, nodename, vmname, cmd) {
822 let url = Ext.Object.toQueryString({
823 console: vmtype, // kvm, lxc, upgrade or shell
824 xtermjs: 1,
825 vmid: vmid,
826 vmname: vmname,
827 node: nodename,
828 cmd: cmd,
829
830 });
831 let nw = window.open("?" + url, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
832 if (nw) {
833 nw.focus();
834 }
835 },
836
837 render_optional_url: function(value) {
838 if (value && value.match(/^https?:\/\//) !== null) {
839 return '<a target="_blank" href="' + value + '">' + value + '</a>';
840 }
841 return value;
842 },
843
844 render_san: function(value) {
845 var names = [];
846 if (Ext.isArray(value)) {
847 value.forEach(function(val) {
848 if (!Ext.isNumber(val)) {
849 names.push(val);
850 }
851 });
852 return names.join('<br>');
853 }
854 return value;
855 },
856
857 render_usage: val => (val*100).toFixed(2) + '%',
858
859 render_cpu_usage: function(val, max) {
860 return Ext.String.format(
861 `${gettext('{0}% of {1}')} ${gettext('CPU(s)')}`,
862 (val*100).toFixed(2),
863 max,
864 );
865 },
866
867 render_size_usage: function(val, max) {
868 if (max === 0) {
869 return gettext('N/A');
870 }
871 return (val*100/max).toFixed(2) + '% (' +
872 Ext.String.format(gettext('{0} of {1}'),
873 Proxmox.Utils.render_size(val), Proxmox.Utils.render_size(max)) + ')';
874 },
875
876 render_cpu: function(value, metaData, record, rowIndex, colIndex, store) {
877 if (!(record.data.uptime && Ext.isNumeric(value))) {
878 return '';
879 }
880
881 let maxcpu = record.data.maxcpu || 1;
882 if (!Ext.isNumeric(maxcpu) || maxcpu < 1) {
883 return '';
884 }
885 let cpuText = maxcpu > 1 ? 'CPUs' : 'CPU';
886 let ratio = (value * 100).toFixed(1);
887 return `${ratio}% of ${maxcpu.toString()} ${cpuText}`;
888 },
889
890 render_size: function(value, metaData, record, rowIndex, colIndex, store) {
891 if (!Ext.isNumeric(value)) {
892 return '';
893 }
894 return Proxmox.Utils.format_size(value);
895 },
896
897 render_cpu_model: function(cpu) {
898 let socketText = cpu.sockets > 1 ? gettext('Sockets') : gettext('Socket');
899 return `${cpu.cpus} x ${cpu.model} (${cpu.sockets.toString()} ${socketText})`;
900 },
901
902 /* this is different for nodes */
903 render_node_cpu_usage: function(value, record) {
904 return Proxmox.Utils.render_cpu_usage(value, record.cpus);
905 },
906
907 render_node_size_usage: function(record) {
908 return Proxmox.Utils.render_size_usage(record.used, record.total);
909 },
910
911 loadTextFromFile: function(file, callback, maxBytes) {
912 let maxSize = maxBytes || 8192;
913 if (file.size > maxSize) {
914 Ext.Msg.alert(gettext('Error'), gettext("Invalid file size: ") + file.size);
915 return;
916 }
917 let reader = new FileReader();
918 reader.onload = evt => callback(evt.target.result);
919 reader.readAsText(file);
920 },
921
922 parsePropertyString: function(value, defaultKey) {
923 var res = {},
924 error;
925
926 if (typeof value !== 'string' || value === '') {
927 return res;
928 }
929
930 Ext.Array.each(value.split(','), function(p) {
931 var kv = p.split('=', 2);
932 if (Ext.isDefined(kv[1])) {
933 res[kv[0]] = kv[1];
934 } else if (Ext.isDefined(defaultKey)) {
935 if (Ext.isDefined(res[defaultKey])) {
936 error = 'defaultKey may be only defined once in propertyString';
937 return false; // break
938 }
939 res[defaultKey] = kv[0];
940 } else {
941 error = 'invalid propertyString, not a key=value pair and no defaultKey defined';
942 return false; // break
943 }
944 return true;
945 });
946
947 if (error !== undefined) {
948 console.error(error);
949 return undefined;
950 }
951
952 return res;
953 },
954
955 printPropertyString: function(data, defaultKey) {
956 var stringparts = [],
957 gotDefaultKeyVal = false,
958 defaultKeyVal;
959
960 Ext.Object.each(data, function(key, value) {
961 if (defaultKey !== undefined && key === defaultKey) {
962 gotDefaultKeyVal = true;
963 defaultKeyVal = value;
964 } else if (Ext.isArray(value)) {
965 stringparts.push(key + '=' + value.join(';'));
966 } else if (value !== '') {
967 stringparts.push(key + '=' + value);
968 }
969 });
970
971 stringparts = stringparts.sort();
972 if (gotDefaultKeyVal) {
973 stringparts.unshift(defaultKeyVal);
974 }
975
976 return stringparts.join(',');
977 },
978
979 acmedomain_count: 5,
980
981 parseACMEPluginData: function(data) {
982 let res = {};
983 let extradata = [];
984 data.split('\n').forEach((line) => {
985 // capture everything after the first = as value
986 let [key, value] = line.split('=');
987 if (value !== undefined) {
988 res[key] = value;
989 } else {
990 extradata.push(line);
991 }
992 });
993 return [res, extradata];
994 },
995
996 delete_if_default: function(values, fieldname, default_val, create) {
997 if (values[fieldname] === '' || values[fieldname] === default_val) {
998 if (!create) {
999 if (values.delete) {
1000 if (Ext.isArray(values.delete)) {
1001 values.delete.push(fieldname);
1002 } else {
1003 values.delete += ',' + fieldname;
1004 }
1005 } else {
1006 values.delete = fieldname;
1007 }
1008 }
1009
1010 delete values[fieldname];
1011 }
1012 },
1013
1014 printACME: function(value) {
1015 if (Ext.isArray(value.domains)) {
1016 value.domains = value.domains.join(';');
1017 }
1018 return Proxmox.Utils.printPropertyString(value);
1019 },
1020
1021 parseACME: function(value) {
1022 if (!value) {
1023 return {};
1024 }
1025
1026 var res = {};
1027 var error;
1028
1029 Ext.Array.each(value.split(','), function(p) {
1030 var kv = p.split('=', 2);
1031 if (Ext.isDefined(kv[1])) {
1032 res[kv[0]] = kv[1];
1033 } else {
1034 error = 'Failed to parse key-value pair: '+p;
1035 return false;
1036 }
1037 return true;
1038 });
1039
1040 if (error !== undefined) {
1041 console.error(error);
1042 return undefined;
1043 }
1044
1045 if (res.domains !== undefined) {
1046 res.domains = res.domains.split(/;/);
1047 }
1048
1049 return res;
1050 },
1051
1052 add_domain_to_acme: function(acme, domain) {
1053 if (acme.domains === undefined) {
1054 acme.domains = [domain];
1055 } else {
1056 acme.domains.push(domain);
1057 acme.domains = acme.domains.filter((value, index, self) => self.indexOf(value) === index);
1058 }
1059 return acme;
1060 },
1061
1062 remove_domain_from_acme: function(acme, domain) {
1063 if (acme.domains !== undefined) {
1064 acme.domains = acme.domains.filter(
1065 (value, index, self) => self.indexOf(value) === index && value !== domain,
1066 );
1067 }
1068 return acme;
1069 },
1070
1071 updateColumns: function(container) {
1072 let mode = Ext.state.Manager.get('summarycolumns') || 'auto';
1073 let factor;
1074 if (mode !== 'auto') {
1075 factor = parseInt(mode, 10);
1076 if (Number.isNaN(factor)) {
1077 factor = 1;
1078 }
1079 } else {
1080 factor = container.getSize().width < 1400 ? 1 : 2;
1081 }
1082
1083 if (container.oldFactor === factor) {
1084 return;
1085 }
1086
1087 let items = container.query('>'); // direct childs
1088 factor = Math.min(factor, items.length);
1089 container.oldFactor = factor;
1090
1091 items.forEach((item) => {
1092 item.columnWidth = 1 / factor;
1093 });
1094
1095 // we have to update the layout twice, since the first layout change
1096 // can trigger the scrollbar which reduces the amount of space left
1097 container.updateLayout();
1098 container.updateLayout();
1099 },
1100 },
1101
1102 singleton: true,
1103 constructor: function() {
1104 let me = this;
1105 Ext.apply(me, me.utilities);
1106
1107 let IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
1108 let IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
1109 let IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
1110 let IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
1111 let IPV4_CIDR_MASK = "([0-9]{1,2})";
1112 let IPV6_CIDR_MASK = "([0-9]{1,3})";
1113
1114
1115 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
1116 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")/" + IPV4_CIDR_MASK + "$");
1117
1118 /* eslint-disable no-useless-concat,no-multi-spaces */
1119 let IPV6_REGEXP = "(?:" +
1120 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
1121 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
1122 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
1123 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
1124 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
1125 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
1126 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
1127 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
1128 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
1129 ")";
1130 /* eslint-enable no-useless-concat,no-multi-spaces */
1131
1132 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
1133 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")/" + IPV6_CIDR_MASK + "$");
1134 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
1135
1136 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
1137 me.IP64_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + "/" + IPV6_CIDR_MASK + ")|(?:" + IPV4_REGEXP + "/" + IPV4_CIDR_MASK + ")$");
1138
1139 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])?))";
1140 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
1141
1142 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(?::(\\d+))?$");
1143 me.HostPortBrackets_match = new RegExp("^\\[(" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](?::(\\d+))?$");
1144 me.IP6_dotnotation_match = new RegExp("^(" + IPV6_REGEXP + ")(?:\\.(\\d+))?$");
1145 me.Vlan_match = /^vlan(\d+)/;
1146 me.VlanInterface_match = /(\w+)\.(\d+)/;
1147 },
1148 });
1149
1150 Ext.define('Proxmox.Async', {
1151 singleton: true,
1152
1153 // Returns a Promise resolving to the result of an `API2Request` or rejecting to the error
1154 // repsonse on failure
1155 api2: function(reqOpts) {
1156 return new Promise((resolve, reject) => {
1157 delete reqOpts.callback; // not allowed in this api
1158 reqOpts.success = response => resolve(response);
1159 reqOpts.failure = response => reject(response);
1160 Proxmox.Utils.API2Request(reqOpts);
1161 });
1162 },
1163
1164 // Delay for a number of milliseconds.
1165 sleep: function(millis) {
1166 return new Promise((resolve, _reject) => setTimeout(resolve, millis));
1167 },
1168 });