]> git.proxmox.com Git - proxmox-widget-toolkit.git/blob - Utils.js
add formatters for boolean
[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 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 },
77
78 authOK: function() {
79 return (Proxmox.UserName !== '') && Ext.util.Cookies.get(Proxmox.Setup.auth_cookie_name);
80 },
81
82 authClear: function() {
83 Ext.util.Cookies.clear(Proxmox.Setup.auth_cookie_name);
84 },
85
86 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
87 // use el.mask() instead
88 setErrorMask: function(comp, msg) {
89 var el = comp.el;
90 if (!el) {
91 return;
92 }
93 if (!msg) {
94 el.unmask();
95 } else {
96 if (msg === true) {
97 el.mask(gettext("Loading..."));
98 } else {
99 el.mask(msg);
100 }
101 }
102 },
103
104 monStoreErrors: function(me, store) {
105 me.mon(store, 'beforeload', function(s, operation, eOpts) {
106 if (!me.loadCount) {
107 me.loadCount = 0; // make sure it is numeric
108 Proxmox.Utils.setErrorMask(me, true);
109 }
110 });
111
112 // only works with 'proxmox' proxy
113 me.mon(store.proxy, 'afterload', function(proxy, request, success) {
114 me.loadCount++;
115
116 if (success) {
117 Proxmox.Utils.setErrorMask(me, false);
118 return;
119 }
120
121 var msg;
122 /*jslint nomen: true */
123 var operation = request._operation;
124 var error = operation.getError();
125 if (error.statusText) {
126 msg = error.statusText + ' (' + error.status + ')';
127 } else {
128 msg = gettext('Connection error');
129 }
130 Proxmox.Utils.setErrorMask(me, msg);
131 });
132 },
133
134 extractRequestError: function(result, verbose) {
135 var msg = gettext('Successful');
136
137 if (!result.success) {
138 msg = gettext("Unknown error");
139 if (result.message) {
140 msg = result.message;
141 if (result.status) {
142 msg += ' (' + result.status + ')';
143 }
144 }
145 if (verbose && Ext.isObject(result.errors)) {
146 msg += "<br>";
147 Ext.Object.each(result.errors, function(prop, desc) {
148 msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " +
149 Ext.htmlEncode(desc);
150 });
151 }
152 }
153
154 return msg;
155 },
156
157 // Ext.Ajax.request
158 API2Request: function(reqOpts) {
159
160 var newopts = Ext.apply({
161 waitMsg: gettext('Please wait...')
162 }, reqOpts);
163
164 if (!newopts.url.match(/^\/api2/)) {
165 newopts.url = '/api2/extjs' + newopts.url;
166 }
167 delete newopts.callback;
168
169 var createWrapper = function(successFn, callbackFn, failureFn) {
170 Ext.apply(newopts, {
171 success: function(response, options) {
172 if (options.waitMsgTarget) {
173 options.waitMsgTarget.setLoading(false);
174 }
175 var result = Ext.decode(response.responseText);
176 response.result = result;
177 if (!result.success) {
178 response.htmlStatus = Proxmox.Utils.extractRequestError(result, true);
179 Ext.callback(callbackFn, options.scope, [options, false, response]);
180 Ext.callback(failureFn, options.scope, [response, options]);
181 return;
182 }
183 Ext.callback(callbackFn, options.scope, [options, true, response]);
184 Ext.callback(successFn, options.scope, [response, options]);
185 },
186 failure: function(response, options) {
187 if (options.waitMsgTarget) {
188 options.waitMsgTarget.setLoading(false);
189 }
190 response.result = {};
191 try {
192 response.result = Ext.decode(response.responseText);
193 } catch(e) {}
194 var msg = gettext('Connection error') + ' - server offline?';
195 if (response.aborted) {
196 msg = gettext('Connection error') + ' - aborted.';
197 } else if (response.timedout) {
198 msg = gettext('Connection error') + ' - Timeout.';
199 } else if (response.status && response.statusText) {
200 msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText;
201 }
202 response.htmlStatus = msg;
203 Ext.callback(callbackFn, options.scope, [options, false, response]);
204 Ext.callback(failureFn, options.scope, [response, options]);
205 }
206 });
207 };
208
209 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
210
211 var target = newopts.waitMsgTarget;
212 if (target) {
213 // Note: ExtJS bug - this does not work when component is not rendered
214 target.setLoading(newopts.waitMsg);
215 }
216 Ext.Ajax.request(newopts);
217 },
218
219 assemble_field_data: function(values, data) {
220 if (Ext.isObject(data)) {
221 Ext.Object.each(data, function(name, val) {
222 if (values.hasOwnProperty(name)) {
223 var bucket = values[name];
224 if (!Ext.isArray(bucket)) {
225 bucket = values[name] = [bucket];
226 }
227 if (Ext.isArray(val)) {
228 values[name] = bucket.concat(val);
229 } else {
230 bucket.push(val);
231 }
232 } else {
233 values[name] = val;
234 }
235 });
236 }
237 },
238
239 dialog_title: function(subject, create, isAdd) {
240 if (create) {
241 if (isAdd) {
242 return gettext('Add') + ': ' + subject;
243 } else {
244 return gettext('Create') + ': ' + subject;
245 }
246 } else {
247 return gettext('Edit') + ': ' + subject;
248 }
249 },
250
251 network_iface_types: {
252 eth: gettext("Network Device"),
253 bridge: 'Linux Bridge',
254 bond: 'Linux Bond',
255 OVSBridge: 'OVS Bridge',
256 OVSBond: 'OVS Bond',
257 OVSPort: 'OVS Port',
258 OVSIntPort: 'OVS IntPort'
259 },
260
261 render_network_iface_type: function(value) {
262 return Proxmox.Utils.network_iface_types[value] ||
263 Proxmox.Utils.unknownText;
264 },
265
266 // you can override this to provide nicer task descriptions
267 format_task_description: function(type, id) {
268 return type + ' ' + id;
269 },
270
271 render_upid: function(value, metaData, record) {
272 var type = record.data.type;
273 var id = record.data.id;
274
275 return Proxmox.Utils.format_task_description(type, id);
276 },
277
278 parse_task_upid: function(upid) {
279 var task = {};
280
281 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]+):$/);
282 if (!res) {
283 throw "unable to parse upid '" + upid + "'";
284 }
285 task.node = res[1];
286 task.pid = parseInt(res[2], 16);
287 task.pstart = parseInt(res[3], 16);
288 task.starttime = parseInt(res[4], 16);
289 task.type = res[5];
290 task.id = res[6];
291 task.user = res[7];
292
293 task.desc = Proxmox.Utils.format_task_description(task.type, task.id);
294
295 return task;
296 },
297
298 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
299 var servertime = new Date(value * 1000);
300 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
301 },
302
303 },
304
305 singleton: true,
306 constructor: function() {
307 var me = this;
308 Ext.apply(me, me.utilities);
309
310 var IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
311 var IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
312 var IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
313 var IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
314
315
316 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
317 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")\/([0-9]{1,2})$");
318
319 var IPV6_REGEXP = "(?:" +
320 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
321 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
322 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
323 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
324 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
325 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
326 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
327 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
328 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
329 ")";
330
331 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
332 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")\/([0-9]{1,3})$");
333 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
334
335 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
336
337 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])?))";
338 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
339
340 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(:\\d+)?$");
341 me.HostPortBrackets_match = new RegExp("^\\[(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](:\\d+)?$");
342 me.IP6_dotnotation_match = new RegExp("^" + IPV6_REGEXP + "(\\.\\d+)?$");
343 }
344 });