]> git.proxmox.com Git - proxmox-widget-toolkit.git/blob - src/Utils.js
cleanly separate sources from package build, move to own folder
[proxmox-widget-toolkit.git] / src / Utils.js
1 Ext.ns('Proxmox');
2 Ext.ns('Proxmox.Setup');
3
4 if (!Ext.isDefined(Proxmox.Setup.auth_cookie_name)) {
5 throw "Proxmox library not initialized";
6 }
7
8 // avoid errors related to Accessible Rich Internet Applications
9 // (access for people with disabilities)
10 // TODO reenable after all components are upgraded
11 Ext.enableAria = false;
12 Ext.enableAriaButtons = false;
13 Ext.enableAriaPanels = false;
14
15 // avoid errors when running without development tools
16 if (!Ext.isDefined(Ext.global.console)) {
17 let console = {
18 dir: function() {
19 // do nothing
20 },
21 log: function() {
22 // do nothing
23 },
24 warn: function() {
25 // do nothing
26 },
27 };
28 Ext.global.console = console;
29 }
30
31 Ext.Ajax.defaultHeaders = {
32 'Accept': 'application/json',
33 };
34
35 Ext.Ajax.on('beforerequest', function(conn, options) {
36 if (Proxmox.CSRFPreventionToken) {
37 if (!options.headers) {
38 options.headers = {};
39 }
40 options.headers.CSRFPreventionToken = Proxmox.CSRFPreventionToken;
41 }
42 });
43
44 Ext.define('Proxmox.Utils', { // a singleton
45 utilities: {
46
47 yesText: gettext('Yes'),
48 noText: gettext('No'),
49 enabledText: gettext('Enabled'),
50 disabledText: gettext('Disabled'),
51 noneText: gettext('none'),
52 NoneText: gettext('None'),
53 errorText: gettext('Error'),
54 unknownText: gettext('Unknown'),
55 defaultText: gettext('Default'),
56 daysText: gettext('days'),
57 dayText: gettext('day'),
58 runningText: gettext('running'),
59 stoppedText: gettext('stopped'),
60 neverText: gettext('never'),
61 totalText: gettext('Total'),
62 usedText: gettext('Used'),
63 directoryText: gettext('Directory'),
64 stateText: gettext('State'),
65 groupText: gettext('Group'),
66
67 language_map: {
68 ar: 'Arabic',
69 ca: 'Catalan',
70 da: 'Danish',
71 de: 'German',
72 en: 'English',
73 es: 'Spanish',
74 eu: 'Euskera (Basque)',
75 fa: 'Persian (Farsi)',
76 fr: 'French',
77 he: 'Hebrew',
78 it: 'Italian',
79 ja: 'Japanese',
80 nb: 'Norwegian (Bokmal)',
81 nn: 'Norwegian (Nynorsk)',
82 pl: 'Polish',
83 pt_BR: 'Portuguese (Brazil)',
84 ru: 'Russian',
85 sl: 'Slovenian',
86 sv: 'Swedish',
87 tr: 'Turkish',
88 zh_CN: 'Chinese (Simplified)',
89 zh_TW: 'Chinese (Traditional)',
90 },
91
92 render_language: function(value) {
93 if (!value) {
94 return Proxmox.Utils.defaultText + ' (English)';
95 }
96 let text = Proxmox.Utils.language_map[value];
97 if (text) {
98 return text + ' (' + value + ')';
99 }
100 return value;
101 },
102
103 language_array: function() {
104 let data = [['__default__', Proxmox.Utils.render_language('')]];
105 Ext.Object.each(Proxmox.Utils.language_map, function(key, value) {
106 data.push([key, Proxmox.Utils.render_language(value)]);
107 });
108
109 return data;
110 },
111
112 bond_mode_gettext_map: {
113 '802.3ad': 'LACP (802.3ad)',
114 'lacp-balance-slb': 'LACP (balance-slb)',
115 'lacp-balance-tcp': 'LACP (balance-tcp)',
116 },
117
118 render_bond_mode: value => Proxmox.Utils.bond_mode_gettext_map[value] || value || '',
119
120 bond_mode_array: function(modes) {
121 return modes.map(mode => [mode, Proxmox.Utils.render_bond_mode(mode)]);
122 },
123
124 getNoSubKeyHtml: function(url) {
125 // url http://www.proxmox.com/products/proxmox-ve/subscription-service-plans
126 return Ext.String.format('You do not have a valid subscription for this server. Please visit <a target="_blank" href="{0}">www.proxmox.com</a> to get a list of available options.', url || 'https://www.proxmox.com');
127 },
128
129 format_boolean_with_default: function(value) {
130 if (Ext.isDefined(value) && value !== '__default__') {
131 return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
132 }
133 return Proxmox.Utils.defaultText;
134 },
135
136 format_boolean: function(value) {
137 return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
138 },
139
140 format_neg_boolean: function(value) {
141 return !value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
142 },
143
144 format_enabled_toggle: function(value) {
145 return value ? Proxmox.Utils.enabledText : Proxmox.Utils.disabledText;
146 },
147
148 format_expire: function(date) {
149 if (!date) {
150 return Proxmox.Utils.neverText;
151 }
152 return Ext.Date.format(date, "Y-m-d");
153 },
154
155 // somewhat like a human would tell durations, omit zero values and do not
156 // give seconds precision if we talk days already
157 format_duration_human: function(ut) {
158 let seconds = 0, minutes = 0, hours = 0, days = 0;
159
160 if (ut <= 0) {
161 return '0s';
162 }
163
164 let remaining = ut;
165 seconds = Number((remaining % 60).toFixed(1));
166 remaining = Math.trunc(remaining / 60);
167 if (remaining > 0) {
168 minutes = remaining % 60;
169 remaining = Math.trunc(remaining / 60);
170 if (remaining > 0) {
171 hours = remaining % 24;
172 remaining = Math.trunc(remaining / 24);
173 if (remaining > 0) {
174 days = remaining;
175 }
176 }
177 }
178
179 let res = [];
180 let add = (t, unit) => {
181 if (t > 0) res.push(t + unit);
182 return t > 0;
183 };
184
185 let addSeconds = !add(days, 'd');
186 add(hours, 'h');
187 add(minutes, 'm');
188 if (addSeconds) {
189 add(seconds, 's');
190 }
191 return res.join(' ');
192 },
193
194 format_duration_long: function(ut) {
195 let days = Math.floor(ut / 86400);
196 ut -= days*86400;
197 let hours = Math.floor(ut / 3600);
198 ut -= hours*3600;
199 let mins = Math.floor(ut / 60);
200 ut -= mins*60;
201
202 let hours_str = '00' + hours.toString();
203 hours_str = hours_str.substr(hours_str.length - 2);
204 let mins_str = "00" + mins.toString();
205 mins_str = mins_str.substr(mins_str.length - 2);
206 let ut_str = "00" + ut.toString();
207 ut_str = ut_str.substr(ut_str.length - 2);
208
209 if (days) {
210 let ds = days > 1 ? Proxmox.Utils.daysText : Proxmox.Utils.dayText;
211 return days.toString() + ' ' + ds + ' ' +
212 hours_str + ':' + mins_str + ':' + ut_str;
213 } else {
214 return hours_str + ':' + mins_str + ':' + ut_str;
215 }
216 },
217
218 format_subscription_level: function(level) {
219 if (level === 'c') {
220 return 'Community';
221 } else if (level === 'b') {
222 return 'Basic';
223 } else if (level === 's') {
224 return 'Standard';
225 } else if (level === 'p') {
226 return 'Premium';
227 } else {
228 return Proxmox.Utils.noneText;
229 }
230 },
231
232 compute_min_label_width: function(text, width) {
233 if (width === undefined) { width = 100; }
234
235 let tm = new Ext.util.TextMetrics();
236 let min = tm.getWidth(text + ':');
237
238 return min < width ? width : min;
239 },
240
241 setAuthData: function(data) {
242 Proxmox.CSRFPreventionToken = data.CSRFPreventionToken;
243 Proxmox.UserName = data.username;
244 Proxmox.LoggedOut = data.LoggedOut;
245 // creates a session cookie (expire = null)
246 // that way the cookie gets deleted after the browser window is closed
247 Ext.util.Cookies.set(Proxmox.Setup.auth_cookie_name, data.ticket, null, '/', null, true);
248 },
249
250 authOK: function() {
251 if (Proxmox.LoggedOut) {
252 return undefined;
253 }
254 let cookie = Ext.util.Cookies.get(Proxmox.Setup.auth_cookie_name);
255 if (Proxmox.UserName !== '' && cookie && !cookie.startsWith("PVE:tfa!")) {
256 return cookie;
257 } else {
258 return false;
259 }
260 },
261
262 authClear: function() {
263 if (Proxmox.LoggedOut) {
264 return;
265 }
266 Ext.util.Cookies.clear(Proxmox.Setup.auth_cookie_name);
267 },
268
269 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
270 // use el.mask() instead
271 setErrorMask: function(comp, msg) {
272 let el = comp.el;
273 if (!el) {
274 return;
275 }
276 if (!msg) {
277 el.unmask();
278 } else if (msg === true) {
279 el.mask(gettext("Loading..."));
280 } else {
281 el.mask(msg);
282 }
283 },
284
285 getResponseErrorMessage: (err) => {
286 if (!err.statusText) {
287 return gettext('Connection error');
288 }
289 let msg = [`${err.statusText} (${err.status})`];
290 if (err.response && err.response.responseText) {
291 let txt = err.response.responseText;
292 try {
293 let res = JSON.parse(txt);
294 if (res.errors && typeof res.errors === 'object') {
295 for (let [key, value] of Object.entries(res.errors)) {
296 msg.push(Ext.String.htmlEncode(`${key}: ${value}`));
297 }
298 }
299 } catch (e) {
300 // fallback to string
301 msg.push(Ext.String.htmlEncode(txt));
302 }
303 }
304 return msg.join('<br>');
305 },
306
307 monStoreErrors: function(component, store, clearMaskBeforeLoad) {
308 if (clearMaskBeforeLoad) {
309 component.mon(store, 'beforeload', function(s, operation, eOpts) {
310 Proxmox.Utils.setErrorMask(component, false);
311 });
312 } else {
313 component.mon(store, 'beforeload', function(s, operation, eOpts) {
314 if (!component.loadCount) {
315 component.loadCount = 0; // make sure it is nucomponent.ic
316 Proxmox.Utils.setErrorMask(component, true);
317 }
318 });
319 }
320
321 // only works with 'proxmox' proxy
322 component.mon(store.proxy, 'afterload', function(proxy, request, success) {
323 component.loadCount++;
324
325 if (success) {
326 Proxmox.Utils.setErrorMask(component, false);
327 return;
328 }
329
330 let error = request._operation.getError();
331 let msg = Proxmox.Utils.getResponseErrorMessage(error);
332 Proxmox.Utils.setErrorMask(component, msg);
333 });
334 },
335
336 extractRequestError: function(result, verbose) {
337 let msg = gettext('Successful');
338
339 if (!result.success) {
340 msg = gettext("Unknown error");
341 if (result.message) {
342 msg = result.message;
343 if (result.status) {
344 msg += ' (' + result.status + ')';
345 }
346 }
347 if (verbose && Ext.isObject(result.errors)) {
348 msg += "<br>";
349 Ext.Object.each(result.errors, function(prop, desc) {
350 msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " +
351 Ext.htmlEncode(desc);
352 });
353 }
354 }
355
356 return msg;
357 },
358
359 // Ext.Ajax.request
360 API2Request: function(reqOpts) {
361 let newopts = Ext.apply({
362 waitMsg: gettext('Please wait...'),
363 }, reqOpts);
364
365 if (!newopts.url.match(/^\/api2/)) {
366 newopts.url = '/api2/extjs' + newopts.url;
367 }
368 delete newopts.callback;
369
370 let createWrapper = function(successFn, callbackFn, failureFn) {
371 Ext.apply(newopts, {
372 success: function(response, options) {
373 if (options.waitMsgTarget) {
374 if (Proxmox.Utils.toolkit === 'touch') {
375 options.waitMsgTarget.setMasked(false);
376 } else {
377 options.waitMsgTarget.setLoading(false);
378 }
379 }
380 let result = Ext.decode(response.responseText);
381 response.result = result;
382 if (!result.success) {
383 response.htmlStatus = Proxmox.Utils.extractRequestError(result, true);
384 Ext.callback(callbackFn, options.scope, [options, false, response]);
385 Ext.callback(failureFn, options.scope, [response, options]);
386 return;
387 }
388 Ext.callback(callbackFn, options.scope, [options, true, response]);
389 Ext.callback(successFn, options.scope, [response, options]);
390 },
391 failure: function(response, options) {
392 if (options.waitMsgTarget) {
393 if (Proxmox.Utils.toolkit === 'touch') {
394 options.waitMsgTarget.setMasked(false);
395 } else {
396 options.waitMsgTarget.setLoading(false);
397 }
398 }
399 response.result = {};
400 try {
401 response.result = Ext.decode(response.responseText);
402 } catch (e) {
403 // ignore
404 }
405 let msg = gettext('Connection error') + ' - server offline?';
406 if (response.aborted) {
407 msg = gettext('Connection error') + ' - aborted.';
408 } else if (response.timedout) {
409 msg = gettext('Connection error') + ' - Timeout.';
410 } else if (response.status && response.statusText) {
411 msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText;
412 }
413 response.htmlStatus = msg;
414 Ext.callback(callbackFn, options.scope, [options, false, response]);
415 Ext.callback(failureFn, options.scope, [response, options]);
416 },
417 });
418 };
419
420 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
421
422 let target = newopts.waitMsgTarget;
423 if (target) {
424 if (Proxmox.Utils.toolkit === 'touch') {
425 target.setMasked({ xtype: 'loadmask', message: newopts.waitMsg });
426 } else {
427 // Note: ExtJS bug - this does not work when component is not rendered
428 target.setLoading(newopts.waitMsg);
429 }
430 }
431 Ext.Ajax.request(newopts);
432 },
433
434 checked_command: function(orig_cmd) {
435 Proxmox.Utils.API2Request({
436 url: '/nodes/localhost/subscription',
437 method: 'GET',
438 failure: function(response, opts) {
439 Ext.Msg.alert(gettext('Error'), response.htmlStatus);
440 },
441 success: function(response, opts) {
442 let data = response.result.data;
443 if (data.status !== 'Active') {
444 Ext.Msg.show({
445 title: gettext('No valid subscription'),
446 icon: Ext.Msg.WARNING,
447 message: Proxmox.Utils.getNoSubKeyHtml(data.url),
448 buttons: Ext.Msg.OK,
449 callback: function(btn) {
450 if (btn !== 'ok') {
451 return;
452 }
453 orig_cmd();
454 },
455 });
456 } else {
457 orig_cmd();
458 }
459 },
460 });
461 },
462
463 assemble_field_data: function(values, data) {
464 if (!Ext.isObject(data)) {
465 return;
466 }
467 Ext.Object.each(data, function(name, val) {
468 if (Object.prototype.hasOwnProperty.call(values, name)) {
469 let bucket = values[name];
470 if (!Ext.isArray(bucket)) {
471 bucket = values[name] = [bucket];
472 }
473 if (Ext.isArray(val)) {
474 values[name] = bucket.concat(val);
475 } else {
476 bucket.push(val);
477 }
478 } else {
479 values[name] = val;
480 }
481 });
482 },
483
484 updateColumnWidth: function(container) {
485 let mode = Ext.state.Manager.get('summarycolumns') || 'auto';
486 let factor;
487 if (mode !== 'auto') {
488 factor = parseInt(mode, 10);
489 if (Number.isNaN(factor)) {
490 factor = 1;
491 }
492 } else {
493 factor = container.getSize().width < 1600 ? 1 : 2;
494 }
495
496 if (container.oldFactor === factor) {
497 return;
498 }
499
500 let items = container.query('>'); // direct childs
501 factor = Math.min(factor, items.length);
502 container.oldFactor = factor;
503
504 items.forEach((item) => {
505 item.columnWidth = 1 / factor;
506 });
507
508 // we have to update the layout twice, since the first layout change
509 // can trigger the scrollbar which reduces the amount of space left
510 container.updateLayout();
511 container.updateLayout();
512 },
513
514 dialog_title: function(subject, create, isAdd) {
515 if (create) {
516 if (isAdd) {
517 return gettext('Add') + ': ' + subject;
518 } else {
519 return gettext('Create') + ': ' + subject;
520 }
521 } else {
522 return gettext('Edit') + ': ' + subject;
523 }
524 },
525
526 network_iface_types: {
527 eth: gettext("Network Device"),
528 bridge: 'Linux Bridge',
529 bond: 'Linux Bond',
530 vlan: 'Linux VLAN',
531 OVSBridge: 'OVS Bridge',
532 OVSBond: 'OVS Bond',
533 OVSPort: 'OVS Port',
534 OVSIntPort: 'OVS IntPort',
535 },
536
537 render_network_iface_type: function(value) {
538 return Proxmox.Utils.network_iface_types[value] ||
539 Proxmox.Utils.unknownText;
540 },
541
542 task_desc_table: {
543 acmenewcert: ['SRV', gettext('Order Certificate')],
544 acmeregister: ['ACME Account', gettext('Register')],
545 acmedeactivate: ['ACME Account', gettext('Deactivate')],
546 acmeupdate: ['ACME Account', gettext('Update')],
547 acmerefresh: ['ACME Account', gettext('Refresh')],
548 acmerenew: ['SRV', gettext('Renew Certificate')],
549 acmerevoke: ['SRV', gettext('Revoke Certificate')],
550 'auth-realm-sync': [gettext('Realm'), gettext('Sync')],
551 'auth-realm-sync-test': [gettext('Realm'), gettext('Sync Preview')],
552 'move_volume': ['CT', gettext('Move Volume')],
553 clustercreate: ['', gettext('Create Cluster')],
554 clusterjoin: ['', gettext('Join Cluster')],
555 diskinit: ['Disk', gettext('Initialize Disk with GPT')],
556 vncproxy: ['VM/CT', gettext('Console')],
557 spiceproxy: ['VM/CT', gettext('Console') + ' (Spice)'],
558 vncshell: ['', gettext('Shell')],
559 spiceshell: ['', gettext('Shell') + ' (Spice)'],
560 qmsnapshot: ['VM', gettext('Snapshot')],
561 qmrollback: ['VM', gettext('Rollback')],
562 qmdelsnapshot: ['VM', gettext('Delete Snapshot')],
563 qmcreate: ['VM', gettext('Create')],
564 qmrestore: ['VM', gettext('Restore')],
565 qmdestroy: ['VM', gettext('Destroy')],
566 qmigrate: ['VM', gettext('Migrate')],
567 qmclone: ['VM', gettext('Clone')],
568 qmmove: ['VM', gettext('Move disk')],
569 qmtemplate: ['VM', gettext('Convert to template')],
570 qmstart: ['VM', gettext('Start')],
571 qmstop: ['VM', gettext('Stop')],
572 qmreset: ['VM', gettext('Reset')],
573 qmshutdown: ['VM', gettext('Shutdown')],
574 qmreboot: ['VM', gettext('Reboot')],
575 qmsuspend: ['VM', gettext('Hibernate')],
576 qmpause: ['VM', gettext('Pause')],
577 qmresume: ['VM', gettext('Resume')],
578 qmconfig: ['VM', gettext('Configure')],
579 vzsnapshot: ['CT', gettext('Snapshot')],
580 vzrollback: ['CT', gettext('Rollback')],
581 vzdelsnapshot: ['CT', gettext('Delete Snapshot')],
582 vzcreate: ['CT', gettext('Create')],
583 vzrestore: ['CT', gettext('Restore')],
584 vzdestroy: ['CT', gettext('Destroy')],
585 vzmigrate: ['CT', gettext('Migrate')],
586 vzclone: ['CT', gettext('Clone')],
587 vztemplate: ['CT', gettext('Convert to template')],
588 vzstart: ['CT', gettext('Start')],
589 vzstop: ['CT', gettext('Stop')],
590 vzmount: ['CT', gettext('Mount')],
591 vzumount: ['CT', gettext('Unmount')],
592 vzshutdown: ['CT', gettext('Shutdown')],
593 vzreboot: ['CT', gettext('Reboot')],
594 vzsuspend: ['CT', gettext('Suspend')],
595 vzresume: ['CT', gettext('Resume')],
596 push_file: ['CT', gettext('Push file')],
597 pull_file: ['CT', gettext('Pull file')],
598 hamigrate: ['HA', gettext('Migrate')],
599 hastart: ['HA', gettext('Start')],
600 hastop: ['HA', gettext('Stop')],
601 hashutdown: ['HA', gettext('Shutdown')],
602 srvstart: ['SRV', gettext('Start')],
603 srvstop: ['SRV', gettext('Stop')],
604 srvrestart: ['SRV', gettext('Restart')],
605 srvreload: ['SRV', gettext('Reload')],
606 cephcreatemgr: ['Ceph Manager', gettext('Create')],
607 cephdestroymgr: ['Ceph Manager', gettext('Destroy')],
608 cephcreatemon: ['Ceph Monitor', gettext('Create')],
609 cephdestroymon: ['Ceph Monitor', gettext('Destroy')],
610 cephcreateosd: ['Ceph OSD', gettext('Create')],
611 cephdestroyosd: ['Ceph OSD', gettext('Destroy')],
612 cephcreatepool: ['Ceph Pool', gettext('Create')],
613 cephdestroypool: ['Ceph Pool', gettext('Destroy')],
614 cephfscreate: ['CephFS', gettext('Create')],
615 cephcreatemds: ['Ceph Metadata Server', gettext('Create')],
616 cephdestroymds: ['Ceph Metadata Server', gettext('Destroy')],
617 imgcopy: ['', gettext('Copy data')],
618 imgdel: ['', gettext('Erase data')],
619 unknownimgdel: ['', gettext('Destroy image from unknown guest')],
620 download: ['', gettext('Download')],
621 vzdump: (type, id) => id ? `VM/CT ${id} - ${gettext('Backup')}` : gettext('Backup Job'),
622 aptupdate: ['', gettext('Update package database')],
623 startall: ['', gettext('Start all VMs and Containers')],
624 stopall: ['', gettext('Stop all VMs and Containers')],
625 migrateall: ['', gettext('Migrate all VMs and Containers')],
626 dircreate: [gettext('Directory Storage'), gettext('Create')],
627 lvmcreate: [gettext('LVM Storage'), gettext('Create')],
628 lvmthincreate: [gettext('LVM-Thin Storage'), gettext('Create')],
629 zfscreate: [gettext('ZFS Storage'), gettext('Create')],
630 },
631
632 // to add or change existing for product specific ones
633 override_task_descriptions: function(extra) {
634 for (const [key, value] of Object.entries(extra)) {
635 Proxmox.Utils.task_desc_table[key] = value;
636 }
637 },
638
639 format_task_description: function(type, id) {
640 let farray = Proxmox.Utils.task_desc_table[type];
641 let text;
642 if (!farray) {
643 text = type;
644 if (id) {
645 type += ' ' + id;
646 }
647 return text;
648 } else if (Ext.isFunction(farray)) {
649 return farray(type, id);
650 }
651 let prefix = farray[0];
652 text = farray[1];
653 if (prefix && id !== undefined) {
654 return prefix + ' ' + id + ' - ' + text;
655 }
656 return text;
657 },
658
659 format_size: function(size) {
660 let units = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'];
661 let num = 0;
662 while (size >= 1024 && num++ <= units.length) {
663 size = size / 1024;
664 }
665
666 return size.toFixed(num > 0?2:0) + " " + units[num] + "B";
667 },
668
669 render_upid: function(value, metaData, record) {
670 let task = record.data;
671 let type = task.type || task.worker_type;
672 let id = task.id || task.worker_id;
673
674 return Proxmox.Utils.format_task_description(type, id);
675 },
676
677 render_uptime: function(value) {
678 let uptime = value;
679
680 if (uptime === undefined) {
681 return '';
682 }
683
684 if (uptime <= 0) {
685 return '-';
686 }
687
688 return Proxmox.Utils.format_duration_long(uptime);
689 },
690
691 parse_task_upid: function(upid) {
692 let task = {};
693
694 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]+):$/);
695 if (!res) {
696 throw "unable to parse upid '" + upid + "'";
697 }
698 task.node = res[1];
699 task.pid = parseInt(res[2], 16);
700 task.pstart = parseInt(res[3], 16);
701 if (res[5] !== undefined) {
702 task.task_id = parseInt(res[5], 16);
703 }
704 task.starttime = parseInt(res[6], 16);
705 task.type = res[7];
706 task.id = res[8];
707 task.user = res[9];
708
709 task.desc = Proxmox.Utils.format_task_description(task.type, task.id);
710
711 return task;
712 },
713
714 render_duration: function(value) {
715 if (value === undefined) {
716 return '-';
717 }
718 return Proxmox.Utils.format_duration_human(value);
719 },
720
721 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
722 let servertime = new Date(value * 1000);
723 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
724 },
725
726 get_help_info: function(section) {
727 let helpMap;
728 if (typeof proxmoxOnlineHelpInfo !== 'undefined') {
729 helpMap = proxmoxOnlineHelpInfo; // eslint-disable-line no-undef
730 } else if (typeof pveOnlineHelpInfo !== 'undefined') {
731 // be backward compatible with older pve-doc-generators
732 helpMap = pveOnlineHelpInfo; // eslint-disable-line no-undef
733 } else {
734 throw "no global OnlineHelpInfo map declared";
735 }
736
737 return helpMap[section];
738 },
739
740 get_help_link: function(section) {
741 let info = Proxmox.Utils.get_help_info(section);
742 if (!info) {
743 return undefined;
744 }
745 return window.location.origin + info.link;
746 },
747
748 openXtermJsViewer: function(vmtype, vmid, nodename, vmname, cmd) {
749 let url = Ext.Object.toQueryString({
750 console: vmtype, // kvm, lxc, upgrade or shell
751 xtermjs: 1,
752 vmid: vmid,
753 vmname: vmname,
754 node: nodename,
755 cmd: cmd,
756
757 });
758 let nw = window.open("?" + url, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
759 if (nw) {
760 nw.focus();
761 }
762 },
763
764 },
765
766 singleton: true,
767 constructor: function() {
768 let me = this;
769 Ext.apply(me, me.utilities);
770
771 let IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
772 let IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
773 let IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
774 let IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
775 let IPV4_CIDR_MASK = "([0-9]{1,2})";
776 let IPV6_CIDR_MASK = "([0-9]{1,3})";
777
778
779 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
780 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")/" + IPV4_CIDR_MASK + "$");
781
782 /* eslint-disable no-useless-concat,no-multi-spaces */
783 let IPV6_REGEXP = "(?:" +
784 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
785 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
786 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
787 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
788 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
789 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
790 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
791 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
792 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
793 ")";
794 /* eslint-enable no-useless-concat,no-multi-spaces */
795
796 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
797 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")/" + IPV6_CIDR_MASK + "$");
798 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
799
800 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
801 me.IP64_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + "/" + IPV6_CIDR_MASK + ")|(?:" + IPV4_REGEXP + "/" + IPV4_CIDR_MASK + ")$");
802
803 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])?))";
804 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
805
806 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(:\\d+)?$");
807 me.HostPortBrackets_match = new RegExp("^\\[(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](:\\d+)?$");
808 me.IP6_dotnotation_match = new RegExp("^" + IPV6_REGEXP + "(\\.\\d+)?$");
809 me.Vlan_match = /^vlan(\\d+)/;
810 me.VlanInterface_match = /(\\w+)\\.(\\d+)/;
811 },
812 });