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