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