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