root / ui / static / snf / js / utils.js @ b15a0cc4
History | View | Annotate | Download (11.2 kB)
1 |
;(function(root){
|
---|---|
2 |
|
3 |
var root = root;
|
4 |
var snf = root.synnefo = root.synnefo || {};
|
5 |
|
6 |
snf.i18n = {}; |
7 |
|
8 |
// Logging namespace
|
9 |
var logging = snf.logging = snf.logging || {};
|
10 |
|
11 |
// logger object
|
12 |
var logger = logging.logger = function(ns, level){ |
13 |
var levels = ["debug", "info", "error"]; |
14 |
var con = window.console;
|
15 |
|
16 |
this.level = level || synnefo.logging.level;
|
17 |
this.ns = ns || ""; |
18 |
|
19 |
this._log = function(lvl) { |
20 |
if (lvl >= this.level && con) { |
21 |
var args = Array.prototype.slice.call(arguments[1]); |
22 |
var level_name = levels[lvl];
|
23 |
|
24 |
if (this.ns) { |
25 |
args = ["["+this.ns+"] "].concat(args); |
26 |
} |
27 |
|
28 |
log = con.log |
29 |
if (con[level_name])
|
30 |
log = con[level_name] |
31 |
|
32 |
try {
|
33 |
con && log.apply(con, Array.prototype.slice.call(args)); |
34 |
} catch (err) {}
|
35 |
} |
36 |
} |
37 |
|
38 |
this.debug = function() { |
39 |
var args = [0]; args.push.call(args, arguments); |
40 |
this._log.apply(this, args); |
41 |
} |
42 |
|
43 |
this.info = function() { |
44 |
var args = [1]; args.push.call(args, arguments); |
45 |
this._log.apply(this, args); |
46 |
} |
47 |
|
48 |
this.error = function() { |
49 |
var args = [2]; args.push.call(args, arguments); |
50 |
try {
|
51 |
console.trace() |
52 |
} catch (err) {}
|
53 |
this._log.apply(this, args); |
54 |
} |
55 |
|
56 |
}; |
57 |
|
58 |
synnefo.collect_user_data = function() { |
59 |
var data = {}
|
60 |
|
61 |
try {
|
62 |
data.calls = synnefo.api.requests; |
63 |
} catch (err) { data.calls = err }
|
64 |
try {
|
65 |
data.errors = synnefo.api.errors; |
66 |
} catch (err) { data.errors = err }
|
67 |
try {
|
68 |
data.data = {}; |
69 |
} catch (err) { data.data = err }
|
70 |
try {
|
71 |
data.data.vms = synnefo.storage.vms.toJSON(); |
72 |
} catch (err) { data.data.vms = err }
|
73 |
try {
|
74 |
data.data.networks = synnefo.storage.vms.toJSON(); |
75 |
} catch (err) { data.data.networks = err }
|
76 |
try {
|
77 |
data.data.images = synnefo.storage.images.toJSON(); |
78 |
} catch (err) { data.data.images = err }
|
79 |
try {
|
80 |
data.data.flavors = synnefo.storage.flavors.toJSON(); |
81 |
} catch (err) { data.data.flavors = err }
|
82 |
try {
|
83 |
data.date = new Date;
|
84 |
} catch (err) { data.date = err }
|
85 |
|
86 |
return data;
|
87 |
} |
88 |
|
89 |
// default logger level (debug)
|
90 |
synnefo.logging.level = 0;
|
91 |
|
92 |
// generic logger
|
93 |
synnefo.log = new logger({'ns':'SNF'}); |
94 |
|
95 |
// synnefo config options
|
96 |
synnefo.config = synnefo.config || {}; |
97 |
synnefo.config.api_url = "/api/v1.1";
|
98 |
|
99 |
// Util namespace
|
100 |
synnefo.util = synnefo.util || {}; |
101 |
|
102 |
// Extensions and Utility functions
|
103 |
synnefo.util.ISODateString = function(d){ |
104 |
function pad(n){ |
105 |
return n<10 ? '0'+n : n |
106 |
} |
107 |
return d.getUTCFullYear()+'-' |
108 |
+ pad(d.getUTCMonth()+1)+'-' |
109 |
+ pad(d.getUTCDate())+'T'
|
110 |
+ pad(d.getUTCHours())+':'
|
111 |
+ pad(d.getUTCMinutes())+':'
|
112 |
+ pad(d.getUTCSeconds())+'Z'
|
113 |
} |
114 |
|
115 |
|
116 |
synnefo.util.parseUri = function(sourceUri) { |
117 |
var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"]; |
118 |
var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri); |
119 |
var uri = {};
|
120 |
|
121 |
for(var i = 0; i < 10; i++){ |
122 |
uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
|
123 |
} |
124 |
|
125 |
// Always end directoryPath with a trailing backslash if a path was present in the source URI
|
126 |
// Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key
|
127 |
if(uri.directoryPath.length > 0){ |
128 |
uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/"); |
129 |
} |
130 |
|
131 |
return uri;
|
132 |
} |
133 |
|
134 |
synnefo.util.equalHeights = function() { |
135 |
var max_height = 0; |
136 |
var selectors = _.toArray(arguments); |
137 |
|
138 |
_.each(selectors, function(s){
|
139 |
console.log($(s).height());
|
140 |
}) |
141 |
// TODO: implement me
|
142 |
} |
143 |
|
144 |
synnefo.util.ClipHelper = function(cont) { |
145 |
this.cont = cont || $('<div class="clip-copy"></div>'); |
146 |
this.clip = new ZeroClipboard.Client(); |
147 |
this.clip.setHandCursor(true); |
148 |
|
149 |
this.el = this.cont; |
150 |
this.el.append(this.clip.getHTML(20,20)); |
151 |
|
152 |
this.setText = function(t) { |
153 |
this.clip.setText(t);
|
154 |
} |
155 |
|
156 |
this.el.attr({title: "Click to copy to clipboard"}) |
157 |
this.clip.addEventListener('complete', _.bind(function(client, text) { |
158 |
//$(".tooltip").text("Copied");
|
159 |
}, this));
|
160 |
} |
161 |
|
162 |
synnefo.util.truncate = function(string, size, append, words) { |
163 |
if (string.length <= size) {
|
164 |
return string;
|
165 |
} |
166 |
|
167 |
if (append === undefined) { |
168 |
append = "...";
|
169 |
} |
170 |
|
171 |
if (!append) { append = "" }; |
172 |
// TODO: implement word truncate
|
173 |
if (words === undefined) { |
174 |
words = false;
|
175 |
} |
176 |
|
177 |
len = size - append.length; |
178 |
return string.substring(0, len) + append; |
179 |
} |
180 |
|
181 |
synnefo.util.readablizeBytes = function(bytes) { |
182 |
var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB']; |
183 |
var e = Math.floor(Math.log(bytes)/Math.log(1024)); |
184 |
return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e]; |
185 |
} |
186 |
|
187 |
synnefo.i18n.API_ERROR_MESSAGES = { |
188 |
'timeout': {
|
189 |
'message': 'TIMEOUT', |
190 |
'allow_report': false, |
191 |
'type': 'Network' |
192 |
}, |
193 |
|
194 |
'error': {
|
195 |
'message': 'API error' |
196 |
}, |
197 |
|
198 |
'abort': {},
|
199 |
'parserror': {}
|
200 |
} |
201 |
|
202 |
synnefo.util.array_diff = function(arr1, arr2) { |
203 |
var removed = [];
|
204 |
var added = [];
|
205 |
|
206 |
_.each(arr1, function(v) {
|
207 |
if (arr2.indexOf(v) == -1) { |
208 |
removed[removed.length] = v; |
209 |
} |
210 |
}) |
211 |
|
212 |
|
213 |
_.each(arr2, function(v) {
|
214 |
if (arr1.indexOf(v) == -1) { |
215 |
added[added.length] = v; |
216 |
} |
217 |
}) |
218 |
|
219 |
return {del: removed, add: added}; |
220 |
} |
221 |
|
222 |
synnefo.util.open_window = function(url, name, specs) { |
223 |
// default specs
|
224 |
var opts = _.extend({
|
225 |
scrollbars: 'no', |
226 |
menubar: 'no', |
227 |
toolbar: 'no', |
228 |
status: 'no', |
229 |
top: 'no', |
230 |
left: 'no', |
231 |
height: screen.height,
|
232 |
width: screen.width,
|
233 |
fullscreen: 'yes', |
234 |
channelmode: 'yes', |
235 |
directories: 'no', |
236 |
left: 0, |
237 |
location: 'no', |
238 |
top: 0 |
239 |
}, opts) |
240 |
|
241 |
window.open(url, name, opts); |
242 |
} |
243 |
|
244 |
synnefo.util.stacktrace = function() { |
245 |
try {
|
246 |
var obj = {};
|
247 |
if (window.Error && Error.captureStackTrace) {
|
248 |
Error.captureStackTrace(obj, synnefo.util.stacktrace); |
249 |
return obj.stack;
|
250 |
} else {
|
251 |
return printStackTrace().join("<br /><br />"); |
252 |
} |
253 |
} catch (err) {}
|
254 |
return ""; |
255 |
}, |
256 |
|
257 |
synnefo.util.array_combinations = function(arr) { |
258 |
if (arr.length == 1) { |
259 |
return arr[0]; |
260 |
} else {
|
261 |
var result = [];
|
262 |
|
263 |
// recur with the rest of array
|
264 |
var allCasesOfRest = synnefo.util.array_combinations(arr.slice(1)); |
265 |
for (var i = 0; i < allCasesOfRest.length; i++) { |
266 |
for (var j = 0; j < arr[0].length; j++) { |
267 |
result.push(arr[0][j] + "-" + allCasesOfRest[i]); |
268 |
} |
269 |
} |
270 |
return result;
|
271 |
} |
272 |
} |
273 |
|
274 |
synnefo.util.parse_api_error = function(arguments) { |
275 |
arguments = arguments[0]; |
276 |
|
277 |
var xhr = arguments[0]; |
278 |
var error_message = arguments[1]; |
279 |
var error_thrown = arguments[2]; |
280 |
var ajax_settings = arguments.ajax || {}; |
281 |
var call_settings = arguments.ajax ? arguments.ajax.error_params || {} : {}; |
282 |
|
283 |
var json_data = undefined; |
284 |
if (xhr.responseText) {
|
285 |
try {
|
286 |
json_data = JSON.parse(xhr.responseText) |
287 |
} catch (err) {}
|
288 |
} |
289 |
|
290 |
module = "API"
|
291 |
|
292 |
try {
|
293 |
path = synnefo.util.parseUri(ajax_settings.url).path.split("/");
|
294 |
path.splice(0,3) |
295 |
module = path.join("/");
|
296 |
} catch (err) {
|
297 |
console.error("cannot identify api error module");
|
298 |
} |
299 |
|
300 |
defaults = { |
301 |
'message': 'Api error', |
302 |
'type': 'API', |
303 |
'allow_report': true, |
304 |
'fatal_error': ajax_settings.critical || false |
305 |
} |
306 |
|
307 |
var code = -1; |
308 |
try {
|
309 |
code = xhr.status || "undefined";
|
310 |
} catch (err) {console.error(err);}
|
311 |
var details = ""; |
312 |
|
313 |
if ([413].indexOf(code) > -1) { |
314 |
defaults.non_critical = true;
|
315 |
defaults.allow_report = false;
|
316 |
defaults.allow_reload = false;
|
317 |
} |
318 |
|
319 |
if (json_data) {
|
320 |
$.each(json_data, function(key, obj) { |
321 |
code = obj.code; |
322 |
details = obj.details.replace("\n","<br>"); |
323 |
error_message = obj.message; |
324 |
}) |
325 |
} |
326 |
|
327 |
extra = {'URL': ajax_settings.url};
|
328 |
options = {}; |
329 |
options = _.extend(options, {'details': details, 'message': error_message, 'ns': module, 'extra_details': extra}); |
330 |
options = _.extend(options, call_settings); |
331 |
options = _.extend(options, synnefo.i18n.API_ERROR_MESSAGES[error_message] || {}); |
332 |
|
333 |
if (window.ERROR_OVERRIDES && window.ERROR_OVERRIDES[options.message]) {
|
334 |
options.message = window.ERROR_OVERRIDES[options.message]; |
335 |
} |
336 |
|
337 |
if (options.code && window.ERROR_OVERRIDES && window.ERROR_OVERRIDES[code]) {
|
338 |
options.message = window.ERROR_OVERRIDES[code]; |
339 |
} |
340 |
|
341 |
options = _.extend(defaults, options); |
342 |
options.code = code; |
343 |
|
344 |
return options;
|
345 |
} |
346 |
|
347 |
|
348 |
// Backbone extensions
|
349 |
//
|
350 |
// super method
|
351 |
Backbone.Model.prototype._super = Backbone.Collection.prototype._super = Backbone.View.prototype._super = function(funcName){ |
352 |
return this.constructor.__super__[funcName].apply(this, _.rest(arguments)); |
353 |
} |
354 |
|
355 |
// simple string format helper
|
356 |
// http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format
|
357 |
String.prototype.format = function() { |
358 |
var formatted = this; |
359 |
for (var i = 0; i < arguments.length; i++) { |
360 |
var regexp = new RegExp('\\{'+i+'\\}', 'gi'); |
361 |
formatted = formatted.replace(regexp, arguments[i]);
|
362 |
} |
363 |
return formatted;
|
364 |
}; |
365 |
|
366 |
|
367 |
$.fn.setCursorPosition = function(pos) { |
368 |
if ($(this).get(0).setSelectionRange) { |
369 |
$(this).get(0).setSelectionRange(pos, pos); |
370 |
} else if ($(this).get(0).createTextRange) { |
371 |
var range = $(this).get(0).createTextRange(); |
372 |
range.collapse(true);
|
373 |
range.moveEnd('character', pos);
|
374 |
range.moveStart('character', pos);
|
375 |
range.select(); |
376 |
} |
377 |
} |
378 |
})(this);
|