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