]> git.proxmox.com Git - proxmox-widget-toolkit.git/blob - Utils.js
97b6c751178e8a7edb0e0add41f7eae24eda3d35
[proxmox-widget-toolkit.git] / Utils.js
1 Ext.ns('Proxmox');
2 Ext.ns('Proxmox.Setup');
3
4 // TODO: implement 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 getNoSubKeyHtml: function(url) {
64 // url http://www.proxmox.com/products/proxmox-ve/subscription-service-plans
65 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');
66 },
67
68 format_boolean_with_default: function(value) {
69 if (Ext.isDefined(value) && value !== '__default__') {
70 return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
71 }
72 return Proxmox.Utils.defaultText;
73 },
74
75 format_boolean: function(value) {
76 return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
77 },
78
79 format_neg_boolean: function(value) {
80 return !value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
81 },
82
83 format_enabled_toggle: function(value) {
84 return value ? Proxmox.Utils.enabledText : Proxmox.Utils.disabledText;
85 },
86
87 format_expire: function(date) {
88 if (!date) {
89 return Proxmox.Utils.neverText;
90 }
91 return Ext.Date.format(date, "Y-m-d");
92 },
93
94 format_duration_long: function(ut) {
95
96 var days = Math.floor(ut / 86400);
97 ut -= days*86400;
98 var hours = Math.floor(ut / 3600);
99 ut -= hours*3600;
100 var mins = Math.floor(ut / 60);
101 ut -= mins*60;
102
103 var hours_str = '00' + hours.toString();
104 hours_str = hours_str.substr(hours_str.length - 2);
105 var mins_str = "00" + mins.toString();
106 mins_str = mins_str.substr(mins_str.length - 2);
107 var ut_str = "00" + ut.toString();
108 ut_str = ut_str.substr(ut_str.length - 2);
109
110 if (days) {
111 var ds = days > 1 ? Proxmox.Utils.daysText : Proxmox.Utils.dayText;
112 return days.toString() + ' ' + ds + ' ' +
113 hours_str + ':' + mins_str + ':' + ut_str;
114 } else {
115 return hours_str + ':' + mins_str + ':' + ut_str;
116 }
117 },
118
119 format_duration_short: function(ut) {
120
121 if (ut < 60) {
122 return ut.toString() + 's';
123 }
124
125 if (ut < 3600) {
126 var mins = ut / 60;
127 return mins.toFixed(0) + 'm';
128 }
129
130 if (ut < 86400) {
131 var hours = ut / 3600;
132 return hours.toFixed(0) + 'h';
133 }
134
135 var days = ut / 86400;
136 return days.toFixed(0) + 'd';
137 },
138
139 format_subscription_level: function(level) {
140 if (level === 'c') {
141 return 'Community';
142 } else if (level === 'b') {
143 return 'Basic';
144 } else if (level === 's') {
145 return 'Standard';
146 } else if (level === 'p') {
147 return 'Premium';
148 } else {
149 return Proxmox.Utils.noneText;
150 }
151 },
152
153 compute_min_label_width: function(text, width) {
154
155 if (width === undefined) { width = 100; }
156
157 var tm = new Ext.util.TextMetrics();
158 var min = tm.getWidth(text + ':');
159
160 return min < width ? width : min;
161 },
162
163 authOK: function() {
164 return (Proxmox.UserName !== '') && Ext.util.Cookies.get(Proxmox.Setup.auth_cookie_name);
165 },
166
167 authClear: function() {
168 Ext.util.Cookies.clear(Proxmox.Setup.auth_cookie_name);
169 },
170
171 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
172 // use el.mask() instead
173 setErrorMask: function(comp, msg) {
174 var el = comp.el;
175 if (!el) {
176 return;
177 }
178 if (!msg) {
179 el.unmask();
180 } else {
181 if (msg === true) {
182 el.mask(gettext("Loading..."));
183 } else {
184 el.mask(msg);
185 }
186 }
187 },
188
189 monStoreErrors: function(me, store, clearMaskBeforeLoad) {
190 if (clearMaskBeforeLoad) {
191 me.mon(store, 'beforeload', function(s, operation, eOpts) {
192 Proxmox.Utils.setErrorMask(me, false);
193 })
194 } else {
195 me.mon(store, 'beforeload', function(s, operation, eOpts) {
196 if (!me.loadCount) {
197 me.loadCount = 0; // make sure it is numeric
198 Proxmox.Utils.setErrorMask(me, true);
199 }
200 });
201 }
202
203 // only works with 'proxmox' proxy
204 me.mon(store.proxy, 'afterload', function(proxy, request, success) {
205 me.loadCount++;
206
207 if (success) {
208 Proxmox.Utils.setErrorMask(me, false);
209 return;
210 }
211
212 var msg;
213 /*jslint nomen: true */
214 var operation = request._operation;
215 var error = operation.getError();
216 if (error.statusText) {
217 msg = error.statusText + ' (' + error.status + ')';
218 } else {
219 msg = gettext('Connection error');
220 }
221 Proxmox.Utils.setErrorMask(me, msg);
222 });
223 },
224
225 extractRequestError: function(result, verbose) {
226 var msg = gettext('Successful');
227
228 if (!result.success) {
229 msg = gettext("Unknown error");
230 if (result.message) {
231 msg = result.message;
232 if (result.status) {
233 msg += ' (' + result.status + ')';
234 }
235 }
236 if (verbose && Ext.isObject(result.errors)) {
237 msg += "<br>";
238 Ext.Object.each(result.errors, function(prop, desc) {
239 msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " +
240 Ext.htmlEncode(desc);
241 });
242 }
243 }
244
245 return msg;
246 },
247
248 // Ext.Ajax.request
249 API2Request: function(reqOpts) {
250
251 var newopts = Ext.apply({
252 waitMsg: gettext('Please wait...')
253 }, reqOpts);
254
255 if (!newopts.url.match(/^\/api2/)) {
256 newopts.url = '/api2/extjs' + newopts.url;
257 }
258 delete newopts.callback;
259
260 var createWrapper = function(successFn, callbackFn, failureFn) {
261 Ext.apply(newopts, {
262 success: function(response, options) {
263 if (options.waitMsgTarget) {
264 options.waitMsgTarget.setLoading(false);
265 }
266 var result = Ext.decode(response.responseText);
267 response.result = result;
268 if (!result.success) {
269 response.htmlStatus = Proxmox.Utils.extractRequestError(result, true);
270 Ext.callback(callbackFn, options.scope, [options, false, response]);
271 Ext.callback(failureFn, options.scope, [response, options]);
272 return;
273 }
274 Ext.callback(callbackFn, options.scope, [options, true, response]);
275 Ext.callback(successFn, options.scope, [response, options]);
276 },
277 failure: function(response, options) {
278 if (options.waitMsgTarget) {
279 options.waitMsgTarget.setLoading(false);
280 }
281 response.result = {};
282 try {
283 response.result = Ext.decode(response.responseText);
284 } catch(e) {}
285 var msg = gettext('Connection error') + ' - server offline?';
286 if (response.aborted) {
287 msg = gettext('Connection error') + ' - aborted.';
288 } else if (response.timedout) {
289 msg = gettext('Connection error') + ' - Timeout.';
290 } else if (response.status && response.statusText) {
291 msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText;
292 }
293 response.htmlStatus = msg;
294 Ext.callback(callbackFn, options.scope, [options, false, response]);
295 Ext.callback(failureFn, options.scope, [response, options]);
296 }
297 });
298 };
299
300 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
301
302 var target = newopts.waitMsgTarget;
303 if (target) {
304 // Note: ExtJS bug - this does not work when component is not rendered
305 target.setLoading(newopts.waitMsg);
306 }
307 Ext.Ajax.request(newopts);
308 },
309
310 checked_command: function(orig_cmd) {
311 Proxmox.Utils.API2Request({
312 url: '/nodes/localhost/subscription',
313 method: 'GET',
314 //waitMsgTarget: me,
315 failure: function(response, opts) {
316 Ext.Msg.alert(gettext('Error'), response.htmlStatus);
317 },
318 success: function(response, opts) {
319 var data = response.result.data;
320
321 if (data.status !== 'Active') {
322 Ext.Msg.show({
323 title: gettext('No valid subscription'),
324 icon: Ext.Msg.WARNING,
325 msg: Proxmox.Utils.getNoSubKeyHtml(data.url),
326 buttons: Ext.Msg.OK,
327 callback: function(btn) {
328 if (btn !== 'ok') {
329 return;
330 }
331 orig_cmd();
332 }
333 });
334 } else {
335 orig_cmd();
336 }
337 }
338 });
339 },
340
341 assemble_field_data: function(values, data) {
342 if (Ext.isObject(data)) {
343 Ext.Object.each(data, function(name, val) {
344 if (values.hasOwnProperty(name)) {
345 var bucket = values[name];
346 if (!Ext.isArray(bucket)) {
347 bucket = values[name] = [bucket];
348 }
349 if (Ext.isArray(val)) {
350 values[name] = bucket.concat(val);
351 } else {
352 bucket.push(val);
353 }
354 } else {
355 values[name] = val;
356 }
357 });
358 }
359 },
360
361 dialog_title: function(subject, create, isAdd) {
362 if (create) {
363 if (isAdd) {
364 return gettext('Add') + ': ' + subject;
365 } else {
366 return gettext('Create') + ': ' + subject;
367 }
368 } else {
369 return gettext('Edit') + ': ' + subject;
370 }
371 },
372
373 network_iface_types: {
374 eth: gettext("Network Device"),
375 bridge: 'Linux Bridge',
376 bond: 'Linux Bond',
377 OVSBridge: 'OVS Bridge',
378 OVSBond: 'OVS Bond',
379 OVSPort: 'OVS Port',
380 OVSIntPort: 'OVS IntPort'
381 },
382
383 render_network_iface_type: function(value) {
384 return Proxmox.Utils.network_iface_types[value] ||
385 Proxmox.Utils.unknownText;
386 },
387
388 // you can override this to provide nicer task descriptions
389 format_task_description: function(type, id) {
390 return type + ' ' + id;
391 },
392
393 render_upid: function(value, metaData, record) {
394 var type = record.data.type;
395 var id = record.data.id;
396
397 return Proxmox.Utils.format_task_description(type, id);
398 },
399
400 render_uptime: function(value) {
401
402 var uptime = value;
403
404 if (uptime === undefined) {
405 return '';
406 }
407
408 if (uptime <= 0) {
409 return '-';
410 }
411
412 return Proxmox.Utils.format_duration_long(uptime);
413 },
414
415 parse_task_upid: function(upid) {
416 var task = {};
417
418 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]+):$/);
419 if (!res) {
420 throw "unable to parse upid '" + upid + "'";
421 }
422 task.node = res[1];
423 task.pid = parseInt(res[2], 16);
424 task.pstart = parseInt(res[3], 16);
425 task.starttime = parseInt(res[4], 16);
426 task.type = res[5];
427 task.id = res[6];
428 task.user = res[7];
429
430 task.desc = Proxmox.Utils.format_task_description(task.type, task.id);
431
432 return task;
433 },
434
435 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
436 var servertime = new Date(value * 1000);
437 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
438 },
439
440 },
441
442 singleton: true,
443 constructor: function() {
444 var me = this;
445 Ext.apply(me, me.utilities);
446
447 var IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
448 var IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
449 var IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
450 var IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
451
452
453 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
454 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")\/([0-9]{1,2})$");
455
456 var IPV6_REGEXP = "(?:" +
457 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
458 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
459 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
460 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
461 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
462 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
463 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
464 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
465 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
466 ")";
467
468 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
469 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")\/([0-9]{1,3})$");
470 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
471
472 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
473
474 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])?))";
475 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
476
477 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(:\\d+)?$");
478 me.HostPortBrackets_match = new RegExp("^\\[(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](:\\d+)?$");
479 me.IP6_dotnotation_match = new RegExp("^" + IPV6_REGEXP + "(\\.\\d+)?$");
480 }
481 });