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