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