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