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