]> git.proxmox.com Git - proxmox-widget-toolkit.git/blob - Utils.js
add all languages from pve
[proxmox-widget-toolkit.git] / Utils.js
1 Ext.ns('Proxmox');
2 Ext.ns('Proxmox.Setup');
3
4 if (!Ext.isFunction(gettext)) {
5 function gettext(buf) { return buf; }
6 }
7
8 if (!Ext.isDefined(Proxmox.Setup.auth_cookie_name)) {
9 throw "Proxmox library not initialized";
10 }
11
12 // avoid errors related to Accessible Rich Internet Applications
13 // (access for people with disabilities)
14 // TODO reenable after all components are upgraded
15 Ext.enableAria = false;
16 Ext.enableAriaButtons = false;
17 Ext.enableAriaPanels = false;
18
19 // avoid errors when running without development tools
20 if (!Ext.isDefined(Ext.global.console)) {
21 var console = {
22 dir: function() {},
23 log: function() {}
24 };
25 }
26
27 Ext.Ajax.defaultHeaders = {
28 'Accept': 'application/json'
29 };
30
31 Ext.Ajax.on('beforerequest', function(conn, options) {
32 if (Proxmox.CSRFPreventionToken) {
33 if (!options.headers) {
34 options.headers = {};
35 }
36 options.headers.CSRFPreventionToken = Proxmox.CSRFPreventionToken;
37 }
38 });
39
40 Ext.define('Proxmox.Utils', { utilities: {
41
42 // this singleton contains miscellaneous utilities
43
44 yesText: gettext('Yes'),
45 noText: gettext('No'),
46 enabledText: gettext('Enabled'),
47 disabledText: gettext('Disabled'),
48 noneText: gettext('none'),
49 errorText: gettext('Error'),
50 unknownText: gettext('Unknown'),
51 defaultText: gettext('Default'),
52 daysText: gettext('days'),
53 dayText: gettext('day'),
54 runningText: gettext('running'),
55 stoppedText: gettext('stopped'),
56 neverText: gettext('never'),
57 totalText: gettext('Total'),
58 usedText: gettext('Used'),
59 directoryText: gettext('Directory'),
60 stateText: gettext('State'),
61 groupText: gettext('Group'),
62
63 language_map: {
64 zh_CN: 'Chinese',
65 ca: 'Catalan',
66 da: 'Danish',
67 en: 'English',
68 eu: 'Euskera (Basque)',
69 fr: 'French',
70 de: 'German',
71 it: 'Italian',
72 es: 'Spanish',
73 ja: 'Japanese',
74 nb: 'Norwegian (Bokmal)',
75 nn: 'Norwegian (Nynorsk)',
76 fa: 'Persian (Farsi)',
77 pl: 'Polish',
78 pt_BR: 'Portuguese (Brazil)',
79 ru: 'Russian',
80 sl: 'Slovenian',
81 sv: 'Swedish',
82 tr: 'Turkish'
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
105 getNoSubKeyHtml: function(url) {
106 // url http://www.proxmox.com/products/proxmox-ve/subscription-service-plans
107 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 || 'http://www.proxmox.com');
108 },
109
110 format_boolean_with_default: function(value) {
111 if (Ext.isDefined(value) && value !== '__default__') {
112 return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
113 }
114 return Proxmox.Utils.defaultText;
115 },
116
117 format_boolean: function(value) {
118 return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
119 },
120
121 format_neg_boolean: function(value) {
122 return !value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
123 },
124
125 format_enabled_toggle: function(value) {
126 return value ? Proxmox.Utils.enabledText : Proxmox.Utils.disabledText;
127 },
128
129 format_expire: function(date) {
130 if (!date) {
131 return Proxmox.Utils.neverText;
132 }
133 return Ext.Date.format(date, "Y-m-d");
134 },
135
136 format_duration_long: function(ut) {
137
138 var days = Math.floor(ut / 86400);
139 ut -= days*86400;
140 var hours = Math.floor(ut / 3600);
141 ut -= hours*3600;
142 var mins = Math.floor(ut / 60);
143 ut -= mins*60;
144
145 var hours_str = '00' + hours.toString();
146 hours_str = hours_str.substr(hours_str.length - 2);
147 var mins_str = "00" + mins.toString();
148 mins_str = mins_str.substr(mins_str.length - 2);
149 var ut_str = "00" + ut.toString();
150 ut_str = ut_str.substr(ut_str.length - 2);
151
152 if (days) {
153 var ds = days > 1 ? Proxmox.Utils.daysText : Proxmox.Utils.dayText;
154 return days.toString() + ' ' + ds + ' ' +
155 hours_str + ':' + mins_str + ':' + ut_str;
156 } else {
157 return hours_str + ':' + mins_str + ':' + ut_str;
158 }
159 },
160
161 format_duration_short: function(ut) {
162
163 if (ut < 60) {
164 return ut.toString() + 's';
165 }
166
167 if (ut < 3600) {
168 var mins = ut / 60;
169 return mins.toFixed(0) + 'm';
170 }
171
172 if (ut < 86400) {
173 var hours = ut / 3600;
174 return hours.toFixed(0) + 'h';
175 }
176
177 var days = ut / 86400;
178 return days.toFixed(0) + 'd';
179 },
180
181 format_subscription_level: function(level) {
182 if (level === 'c') {
183 return 'Community';
184 } else if (level === 'b') {
185 return 'Basic';
186 } else if (level === 's') {
187 return 'Standard';
188 } else if (level === 'p') {
189 return 'Premium';
190 } else {
191 return Proxmox.Utils.noneText;
192 }
193 },
194
195 compute_min_label_width: function(text, width) {
196
197 if (width === undefined) { width = 100; }
198
199 var tm = new Ext.util.TextMetrics();
200 var min = tm.getWidth(text + ':');
201
202 return min < width ? width : min;
203 },
204
205 authOK: function() {
206 return (Proxmox.UserName !== '') && Ext.util.Cookies.get(Proxmox.Setup.auth_cookie_name);
207 },
208
209 authClear: function() {
210 Ext.util.Cookies.clear(Proxmox.Setup.auth_cookie_name);
211 },
212
213 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
214 // use el.mask() instead
215 setErrorMask: function(comp, msg) {
216 var el = comp.el;
217 if (!el) {
218 return;
219 }
220 if (!msg) {
221 el.unmask();
222 } else {
223 if (msg === true) {
224 el.mask(gettext("Loading..."));
225 } else {
226 el.mask(msg);
227 }
228 }
229 },
230
231 monStoreErrors: function(me, store, clearMaskBeforeLoad) {
232 if (clearMaskBeforeLoad) {
233 me.mon(store, 'beforeload', function(s, operation, eOpts) {
234 Proxmox.Utils.setErrorMask(me, false);
235 });
236 } else {
237 me.mon(store, 'beforeload', function(s, operation, eOpts) {
238 if (!me.loadCount) {
239 me.loadCount = 0; // make sure it is numeric
240 Proxmox.Utils.setErrorMask(me, true);
241 }
242 });
243 }
244
245 // only works with 'proxmox' proxy
246 me.mon(store.proxy, 'afterload', function(proxy, request, success) {
247 me.loadCount++;
248
249 if (success) {
250 Proxmox.Utils.setErrorMask(me, false);
251 return;
252 }
253
254 var msg;
255 /*jslint nomen: true */
256 var operation = request._operation;
257 var error = operation.getError();
258 if (error.statusText) {
259 msg = error.statusText + ' (' + error.status + ')';
260 } else {
261 msg = gettext('Connection error');
262 }
263 Proxmox.Utils.setErrorMask(me, msg);
264 });
265 },
266
267 extractRequestError: function(result, verbose) {
268 var msg = gettext('Successful');
269
270 if (!result.success) {
271 msg = gettext("Unknown error");
272 if (result.message) {
273 msg = result.message;
274 if (result.status) {
275 msg += ' (' + result.status + ')';
276 }
277 }
278 if (verbose && Ext.isObject(result.errors)) {
279 msg += "<br>";
280 Ext.Object.each(result.errors, function(prop, desc) {
281 msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " +
282 Ext.htmlEncode(desc);
283 });
284 }
285 }
286
287 return msg;
288 },
289
290 // Ext.Ajax.request
291 API2Request: function(reqOpts) {
292
293 var newopts = Ext.apply({
294 waitMsg: gettext('Please wait...')
295 }, reqOpts);
296
297 if (!newopts.url.match(/^\/api2/)) {
298 newopts.url = '/api2/extjs' + newopts.url;
299 }
300 delete newopts.callback;
301
302 var createWrapper = function(successFn, callbackFn, failureFn) {
303 Ext.apply(newopts, {
304 success: function(response, options) {
305 if (options.waitMsgTarget) {
306 options.waitMsgTarget.setLoading(false);
307 }
308 var result = Ext.decode(response.responseText);
309 response.result = result;
310 if (!result.success) {
311 response.htmlStatus = Proxmox.Utils.extractRequestError(result, true);
312 Ext.callback(callbackFn, options.scope, [options, false, response]);
313 Ext.callback(failureFn, options.scope, [response, options]);
314 return;
315 }
316 Ext.callback(callbackFn, options.scope, [options, true, response]);
317 Ext.callback(successFn, options.scope, [response, options]);
318 },
319 failure: function(response, options) {
320 if (options.waitMsgTarget) {
321 options.waitMsgTarget.setLoading(false);
322 }
323 response.result = {};
324 try {
325 response.result = Ext.decode(response.responseText);
326 } catch(e) {}
327 var msg = gettext('Connection error') + ' - server offline?';
328 if (response.aborted) {
329 msg = gettext('Connection error') + ' - aborted.';
330 } else if (response.timedout) {
331 msg = gettext('Connection error') + ' - Timeout.';
332 } else if (response.status && response.statusText) {
333 msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText;
334 }
335 response.htmlStatus = msg;
336 Ext.callback(callbackFn, options.scope, [options, false, response]);
337 Ext.callback(failureFn, options.scope, [response, options]);
338 }
339 });
340 };
341
342 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
343
344 var target = newopts.waitMsgTarget;
345 if (target) {
346 // Note: ExtJS bug - this does not work when component is not rendered
347 target.setLoading(newopts.waitMsg);
348 }
349 Ext.Ajax.request(newopts);
350 },
351
352 checked_command: function(orig_cmd) {
353 Proxmox.Utils.API2Request({
354 url: '/nodes/localhost/subscription',
355 method: 'GET',
356 //waitMsgTarget: me,
357 failure: function(response, opts) {
358 Ext.Msg.alert(gettext('Error'), response.htmlStatus);
359 },
360 success: function(response, opts) {
361 var data = response.result.data;
362
363 if (data.status !== 'Active') {
364 Ext.Msg.show({
365 title: gettext('No valid subscription'),
366 icon: Ext.Msg.WARNING,
367 msg: Proxmox.Utils.getNoSubKeyHtml(data.url),
368 buttons: Ext.Msg.OK,
369 callback: function(btn) {
370 if (btn !== 'ok') {
371 return;
372 }
373 orig_cmd();
374 }
375 });
376 } else {
377 orig_cmd();
378 }
379 }
380 });
381 },
382
383 assemble_field_data: function(values, data) {
384 if (Ext.isObject(data)) {
385 Ext.Object.each(data, function(name, val) {
386 if (values.hasOwnProperty(name)) {
387 var bucket = values[name];
388 if (!Ext.isArray(bucket)) {
389 bucket = values[name] = [bucket];
390 }
391 if (Ext.isArray(val)) {
392 values[name] = bucket.concat(val);
393 } else {
394 bucket.push(val);
395 }
396 } else {
397 values[name] = val;
398 }
399 });
400 }
401 },
402
403 dialog_title: function(subject, create, isAdd) {
404 if (create) {
405 if (isAdd) {
406 return gettext('Add') + ': ' + subject;
407 } else {
408 return gettext('Create') + ': ' + subject;
409 }
410 } else {
411 return gettext('Edit') + ': ' + subject;
412 }
413 },
414
415 network_iface_types: {
416 eth: gettext("Network Device"),
417 bridge: 'Linux Bridge',
418 bond: 'Linux Bond',
419 OVSBridge: 'OVS Bridge',
420 OVSBond: 'OVS Bond',
421 OVSPort: 'OVS Port',
422 OVSIntPort: 'OVS IntPort'
423 },
424
425 render_network_iface_type: function(value) {
426 return Proxmox.Utils.network_iface_types[value] ||
427 Proxmox.Utils.unknownText;
428 },
429
430 // you can override this to provide nicer task descriptions
431 format_task_description: function(type, id) {
432 return type + ' ' + id;
433 },
434
435 format_size: function(size) {
436 /*jslint confusion: true */
437
438 var units = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'];
439 var num = 0;
440
441 while (size >= 1024 && ((num++)+1) < units.length) {
442 size = size / 1024;
443 }
444
445 return size.toFixed((num > 0)?2:0) + " " + units[num] + "B";
446 },
447
448 render_upid: function(value, metaData, record) {
449 var type = record.data.type;
450 var id = record.data.id;
451
452 return Proxmox.Utils.format_task_description(type, id);
453 },
454
455 render_uptime: function(value) {
456
457 var uptime = value;
458
459 if (uptime === undefined) {
460 return '';
461 }
462
463 if (uptime <= 0) {
464 return '-';
465 }
466
467 return Proxmox.Utils.format_duration_long(uptime);
468 },
469
470 parse_task_upid: function(upid) {
471 var task = {};
472
473 var res = upid.match(/^UPID:(\S+):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8,9}):([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/);
474 if (!res) {
475 throw "unable to parse upid '" + upid + "'";
476 }
477 task.node = res[1];
478 task.pid = parseInt(res[2], 16);
479 task.pstart = parseInt(res[3], 16);
480 task.starttime = parseInt(res[4], 16);
481 task.type = res[5];
482 task.id = res[6];
483 task.user = res[7];
484
485 task.desc = Proxmox.Utils.format_task_description(task.type, task.id);
486
487 return task;
488 },
489
490 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
491 var servertime = new Date(value * 1000);
492 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
493 },
494
495 openXtermJsViewer: function(vmtype, vmid, nodename, vmname) {
496 var url = Ext.urlEncode({
497 console: vmtype, // kvm, lxc, upgrade or shell
498 xtermjs: 1,
499 vmid: vmid,
500 vmname: vmname,
501 node: nodename
502 });
503 var nw = window.open("?" + url, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
504 nw.focus();
505 }
506
507 },
508
509 singleton: true,
510 constructor: function() {
511 var me = this;
512 Ext.apply(me, me.utilities);
513
514 var IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
515 var IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
516 var IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
517 var IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
518
519
520 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
521 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")\/([0-9]{1,2})$");
522
523 var IPV6_REGEXP = "(?:" +
524 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
525 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
526 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
527 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
528 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
529 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
530 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
531 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
532 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
533 ")";
534
535 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
536 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")\/([0-9]{1,3})$");
537 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
538
539 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
540
541 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])?))";
542 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
543
544 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(:\\d+)?$");
545 me.HostPortBrackets_match = new RegExp("^\\[(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](:\\d+)?$");
546 me.IP6_dotnotation_match = new RegExp("^" + IPV6_REGEXP + "(\\.\\d+)?$");
547 }
548 });