Statistics
| Branch: | Tag: | Revision:

root / snf-app / synnefo / ui / static / snf / js / utils.js @ d5ba5588

History | View | Annotate | Download (19.8 kB)

1
// Copyright 2011 GRNET S.A. All rights reserved.
2
// 
3
// Redistribution and use in source and binary forms, with or
4
// without modification, are permitted provided that the following
5
// conditions are met:
6
// 
7
//   1. Redistributions of source code must retain the above
8
//      copyright notice, this list of conditions and the following
9
//      disclaimer.
10
// 
11
//   2. Redistributions in binary form must reproduce the above
12
//      copyright notice, this list of conditions and the following
13
//      disclaimer in the documentation and/or other materials
14
//      provided with the distribution.
15
// 
16
// THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
// POSSIBILITY OF SUCH DAMAGE.
28
// 
29
// The views and conclusions contained in the software and
30
// documentation are those of the authors and should not be
31
// interpreted as representing official policies, either expressed
32
// or implied, of GRNET S.A.
33
// 
34

    
35
;(function(root){
36
    
37
    var root = root;
38
    var snf = root.synnefo = root.synnefo || {};
39
    
40
    snf.i18n = {};
41

    
42
    // Logging namespace
43
    var logging = snf.logging = snf.logging || {};
44

    
45
    // logger object
46
    var logger = logging.logger = function(ns, level){
47
        var levels = ["debug", "info", "error"];
48
        var con = window.console;
49
        
50
        this.level = level || synnefo.logging.level;
51
        this.ns = ns || "";
52

    
53
        this._log = function(lvl) {
54
            if (lvl >= this.level && con) {
55
                var args = Array.prototype.slice.call(arguments[1]);
56
                var level_name = levels[lvl];
57
                    
58
                if (this.ns) {
59
                    args = ["["+this.ns+"] "].concat(args);
60
                }
61

    
62
                log = con.log
63
                if (con[level_name])
64
                    log = con[level_name]
65

    
66
                try {
67
                    con && log.apply(con, Array.prototype.slice.call(args));
68
                } catch (err) {}
69
            }
70
        }
71

    
72
        this.debug = function() {
73
            var args = [0]; args.push.call(args, arguments);
74
            this._log.apply(this, args);
75
        }
76

    
77
        this.info = function() {
78
            var args = [1]; args.push.call(args, arguments);
79
            this._log.apply(this, args);
80
        }
81

    
82
        this.error = function() {
83
            var args = [2]; args.push.call(args, arguments);
84
            this._log.apply(this, args);
85
        }
86

    
87
    };
88
    
89
    synnefo.collect_user_data = function() {
90
        var data = {}
91
        
92
        try {
93
            data.client = {'browser': $.browser, 'screen': $.extend({}, screen), 'client': $.client}
94
        } catch (err) { data.client = err }
95
        try {
96
            data.calls = synnefo.api.requests;
97
        } catch (err) { data.calls = err }
98
        try {
99
            data.errors = synnefo.api.errors;
100
        } catch (err) { data.errors = err }
101
        try {
102
            data.data = {};
103
        } catch (err) { data.data = err }
104
        try {
105
            data.data.vms = synnefo.storage.vms.toJSON();
106
        } catch (err) { data.data.vms = err }
107
        try {
108
            data.data.networks = synnefo.storage.networks.toJSON();
109
        } catch (err) { data.data.networks = err }
110
        //try {
111
            //data.data.images = synnefo.storage.images.toJSON();
112
        //} catch (err) { data.data.images = err }
113
        //try {
114
            //data.data.flavors = synnefo.storage.flavors.toJSON();
115
        //} catch (err) { data.data.flavors = err }
116
        try {
117
            data.date = new Date;
118
        } catch (err) { data.date = err }
119

    
120
        return data;
121
    }
122

    
123
    // default logger level (debug)
124
    synnefo.logging.level = 0;
125

    
126
    // generic logger
127
    synnefo.log = new logger({'ns':'SNF'});
128

    
129
    // synnefo config options
130
    synnefo.config = synnefo.config || {};
131
    synnefo.config.api_url = "/api/v1.1";
132
    
133
    // Util namespace
134
    synnefo.util = synnefo.util || {};
135

    
136
    // Extensions and Utility functions
137
    synnefo.util.ISODateString = function(d){
138
        function pad(n){
139
            return n<10 ? '0'+n : n
140
        }
141
         return d.getUTCFullYear()+'-'
142
         + pad(d.getUTCMonth()+1)+'-'
143
         + pad(d.getUTCDate())+'T'
144
         + pad(d.getUTCHours())+':'
145
         + pad(d.getUTCMinutes())+':'
146
         + pad(d.getUTCSeconds())+'Z'
147
    }
148

    
149
    
150
    synnefo.util.parseHeaders = function(headers) {
151
        var res = {};
152
        _.each(headers.split("\n"), function(h) {
153
            var tuple = h.split(/:(.+)?/);
154
            if (!tuple.length > 1 || !(tuple[0] && tuple[1])) {
155
                return;
156
            }
157
            res[tuple[0]] = tuple[1]
158
        })
159

    
160
        return res;
161
    }
162

    
163
    synnefo.util.parseUri = function(sourceUri) {
164
        var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
165
        var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri);
166
        var uri = {};
167
        
168
        for(var i = 0; i < 10; i++){
169
            uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
170
        }
171
    
172
        // Always end directoryPath with a trailing backslash if a path was present in the source URI
173
        // Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key
174
        if(uri.directoryPath.length > 0){
175
            uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
176
        }
177
        
178
        return uri;
179
    }
180

    
181
    synnefo.util.equalHeights = function() {
182
        var max_height = 0;
183
        var selectors = _.toArray(arguments);
184
            
185
        _.each(selectors, function(s){
186
            console.log($(s).height());
187
        })
188
        // TODO: implement me
189
    }
190

    
191
    synnefo.util.ClipHelper = function(wrapper, text, settings) {
192
        settings = settings || {};
193
        this.el = $('<div class="clip-copy"></div>');
194
        wrapper.append(this.el);
195
        this.clip = $(this.el).zclip(_.extend({
196
            path: synnefo.config.js_url + "lib/ZeroClipboard.swf",
197
            copy: text
198
        }, settings));
199
    }
200

    
201
    synnefo.util.truncate = function(string, size, append, words) {
202
        if (string === undefined) { return "" };
203
        if (string.length <= size) {
204
            return string;
205
        }
206

    
207
        if (append === undefined) {
208
            append = "...";
209
        }
210
        
211
        if (!append) { append = "" };
212
        // TODO: implement word truncate
213
        if (words === undefined) {
214
            words = false;
215
        }
216
        
217
        len = size - append.length;
218
        return string.substring(0, len) + append;
219
    }
220

    
221
    synnefo.util.readablizeBytes = function(bytes) {
222
        var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
223
        var e = Math.floor(Math.log(bytes)/Math.log(1024));
224
        return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
225
    }
226
    
227
    synnefo.i18n.API_ERROR_MESSAGES = {
228
        'timeout': {
229
            'message': 'TIMEOUT', 
230
            'allow_report': false,
231
            'type': 'Network'
232
        },
233
        
234
        'error': {
235
            'message': 'API error'
236
        }, 
237

    
238
        'abort': {},
239
        'parserror': {},
240
        '413': {
241
            'title': "Account warning"
242
        }
243
    }
244
    
245
    synnefo.util.array_diff = function(arr1, arr2) {
246
        var removed = [];
247
        var added = [];
248

    
249
        _.each(arr1, function(v) {
250
            if (arr2.indexOf(v) == -1) {
251
                removed[removed.length] = v;
252
            }
253
        })
254

    
255

    
256
        _.each(arr2, function(v) {
257
            if (arr1.indexOf(v) == -1) {
258
                added[added.length] = v;
259
            }
260
        })
261

    
262
        return {del: removed, add: added};
263
    }
264

    
265
    synnefo.util.open_window = function(url, name, specs) {
266
        // default specs
267
        var opts = _.extend({
268
            scrollbars: 'no',
269
            menubar: 'no',
270
            toolbar: 'no',
271
            status: 'no',
272
            top: 'no',
273
            left: 'no',
274
            height: screen.height,
275
            width: screen.width,
276
            fullscreen: 'yes',
277
            channelmode: 'yes',
278
            directories: 'no',
279
            left: 0,
280
            location: 'no',
281
            top: 0
282
        }, opts)
283
        
284
        window.open(url, name, opts);
285
    }
286
    
287
    synnefo.util.readFileContents = function(f, cb) {
288
        var reader = new FileReader();
289
        var start = 0;
290
        var stop = f.size - 1;
291

    
292
        reader.onloadend = function(e) {
293
            return cb(e.target.result);
294
        }
295
        
296
        var data = reader.readAsText(f);
297
    },
298
    
299
    synnefo.util.generateKey = function(passphrase, length) {
300
        var passphrase = passphrase || "";
301
        var length = length || 1024;
302
        var key = cryptico.generateRSAKey(passphrase, length);
303

    
304
        _.extend(key.prototype, {
305
            download: function() {
306
            }
307
        });
308

    
309
        return key;
310
    }
311
    
312
    synnefo.util.publicKeyTypesMap = {
313
        "ecdsa-sha2-nistp256": "ecdsa",
314
        "ssh-dss" : "dsa",
315
        "ssh-rsa": "rsa"
316
    }
317

    
318
    synnefo.util.validatePublicKey = function(key) {
319
        var b64 = _(key).trim().split("\n").join("").split("\r\n").join("");
320
        var type = "rsa";
321

    
322
        // in case key starts with something like ssh-rsa
323
        if (b64.split(" ").length > 1) {
324
            var parts = key.split(" ");
325
            
326
            // identify key type
327
            type_key = parts[0];
328
            if (parseInt(type_key) >= 768) {
329
                type = "rsa1";
330
                
331
                if (parts[1] == 65537) {
332
                    if (parts.length == 3) {
333
                        return [parts[0], parts[1], parts[2]].join(" ")
334
                    }
335
                }
336
                // invalid rsa1 key
337
                throw "Invalid rsa1 key";
338
            }
339
            
340
            b64 = parts[1];
341
            if (!synnefo.util.publicKeyTypesMap[type_key]) { throw "Invalid rsa key (cannot identify encryption)" }
342

    
343
            try {
344
                var data = $.base64.decode(b64);
345
                return [parts[0], parts[1]].join(" ");
346
            } catch (err) {
347
                throw "Invalid key content";
348
            }
349

    
350
            throw "Invalid key content";
351
        }
352
        
353
        // no type defined check rsa
354
        if (_(b64).startsWith("AAAAB3NzaC1yc2EA")) {
355
            try {
356
                var data = $.base64.decode(b64);
357
                return ["ssh-rsa", b64].join(" ");
358
            } catch (err) {
359
                throw "Invalid content for rsa key";
360
            }
361
        }
362

    
363
        if (_(b64).startsWith("AAAAE2Vj")) {
364
            try {
365
                var data = $.base64.decode(b64);
366
                return ["ecdsa-sha2-nistp256", b64].join(" ");
367
            } catch (err) {
368
                throw "Invalid content for ecdsa key";
369
            }
370
        }
371

    
372
        if (_(b64).startsWith("AAAAB3N")) {
373
            try {
374
                var data = $.base64.decode(b64);
375
                return ["ssh-dss", b64].join(" ");
376
            } catch (err) {
377
                throw "Invalid content for dss key (" + err + ")";
378
            }
379
        }
380

    
381
        throw "Invalid key content";
382
    }
383
    
384
    // detect flash `like a boss`
385
    // http://stackoverflow.com/questions/998245/how-can-i-detect-if-flash-is-installed-and-if-not-display-a-hidden-div-that-inf/3336320#3336320 
386
    synnefo.util.hasFlash = function() {
387
        var hasFlash = false;
388
        try {
389
            var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
390
            if (fo) hasFlash = true;
391
        } catch(e) {
392
          if(navigator.mimeTypes ["application/x-shockwave-flash"] != undefined) hasFlash = true;
393
        }
394
        return hasFlash;
395
    }
396

    
397
    synnefo.util.promptSaveFile = function(selector, filename, data, options) {
398
        if (!synnefo.util.hasFlash()) { return };
399
        try {
400
            return $(selector).downloadify(_.extend({
401
                filename: function(){ return filename },
402
                data: function(){ return data },
403
                onComplete: function(){},
404
                onCancel: function(){},
405
                onError: function(){
406
                    console.log("ERROR", arguments);
407
                },
408
                swf: synnefo.config.media_url + 'js/lib/media/downloadify.swf',
409
                downloadImage: synnefo.config.images_url + 'download.png',
410
                transparent: true,
411
                append: false,
412
                height:20,
413
                width: 20,
414
                dataType: 'string'
415
          }, options));
416
        } catch (err) {
417
            return false;
418
        }
419
    }
420

    
421
    synnefo.util.canReadFile = function() {
422
        if ($.browser.msie) { return false };
423
        if (window.FileReader && window.File) {
424
            var f = File.prototype.__proto__;
425
            if (f.slice || f.webkitSlice || f.mozSlice) {
426
                return true
427
            }
428
        }
429
        return false;
430
    }
431

    
432
    synnefo.util.errorList = function() {
433
        
434
        this.initialize = function() {
435
            this.errors = {};
436
        }
437

    
438
        this.add = function(key, msg) {
439
            this.errors[key] = this.errors[key] || [];
440
            this.errors[key].push(msg);
441
        }
442

    
443
        this.get = function(key) {
444
            return this.errors[key];
445
        }
446

    
447
        this.empty = function() {
448
            return _.isEmpty(this.errors);
449
        }
450

    
451
        this.initialize();
452
    }
453

    
454
    synnefo.util.stacktrace = function() {
455
        try {
456
            var obj = {};
457
            if (window.Error && Error.captureStackTrace) {
458
                Error.captureStackTrace(obj, synnefo.util.stacktrace);
459
                return obj.stack;
460
            } else {
461
                return printStackTrace().join("<br /><br />");
462
            }
463
        } catch (err) {}
464
        return "";
465
    },
466
    
467
    synnefo.util.array_combinations = function(arr) {
468
        if (arr.length == 1) {
469
            return arr[0];
470
        } else {
471
            var result = [];
472

    
473
            // recur with the rest of array
474
            var allCasesOfRest = synnefo.util.array_combinations(arr.slice(1));  
475
            for (var i = 0; i < allCasesOfRest.length; i++) {
476
                for (var j = 0; j < arr[0].length; j++) {
477
                    result.push(arr[0][j] + "-" + allCasesOfRest[i]);
478
                }
479
            }
480
            return result;
481
        }
482
    }
483

    
484
    synnefo.util.parse_api_error = function() {
485
        if (arguments.length == 1) { arguments = arguments[0] };
486

    
487
        var xhr = arguments[0];
488
        var error_message = arguments[1];
489
        var error_thrown = arguments[2];
490
        var ajax_settings = _.last(arguments) || {};
491
        var call_settings = ajax_settings.error_params || {};
492
        var json_data = undefined;
493

    
494
        var critical = ajax_settings.critical === undefined ? true : ajax_settings.critical;
495

    
496
        if (xhr.responseText) {
497
            try {
498
                json_data = JSON.parse(xhr.responseText)
499
            } catch (err) {}
500
        }
501
        
502
        module = "API"
503

    
504
        try {
505
            path = synnefo.util.parseUri(ajax_settings.url).path.split("/");
506
            path.splice(0,3)
507
            module = path.join("/");
508
        } catch (err) {
509
            console.error("cannot identify api error module");
510
        }
511
        
512
        defaults = {
513
            'message': 'Api error',
514
            'type': 'API',
515
            'allow_report': true,
516
            'fatal_error': ajax_settings.critical || false,
517
            'non_critical': !critical
518
        }
519

    
520
        var code = -1;
521
        try {
522
            code = xhr.status || "undefined";
523
        } catch (err) {console.error(err);}
524
        var details = "";
525
        
526
        if ([413].indexOf(code) > -1) {
527
            defaults.non_critical = true;
528
            defaults.allow_report = false;
529
            defaults.allow_reload = false;
530
            error_message = "limit_error";
531
        }
532

    
533
        if (critical) {
534
            defaults.allow_report = true;
535
        }
536
        
537
        if (json_data) {
538
            $.each(json_data, function(key, obj) {
539
                code = obj.code;
540
                details = obj.details.replace("\n","<br>");
541
                error_message = obj.message;
542
            })
543
        }
544

    
545
        extra = {'URL': ajax_settings.url};
546
        options = {};
547
        options = _.extend(options, {'details': details, 'message': error_message, 'ns': module, 'extra_details': extra});
548
        options = _.extend(options, call_settings);
549
        options = _.extend(options, synnefo.i18n.API_ERROR_MESSAGES[error_message] || {});
550
        options = _.extend(options, synnefo.i18n.API_ERROR_MESSAGES[code] || {});
551
        
552
        if (window.ERROR_OVERRIDES && window.ERROR_OVERRIDES[options.message]) {
553
            options.message = window.ERROR_OVERRIDES[options.message];
554
        }
555
        
556
        if (code && window.ERROR_OVERRIDES && window.ERROR_OVERRIDES[code]) {
557
            options.message = window.ERROR_OVERRIDES[code];
558
        }
559

    
560
        options = _.extend(defaults, options);
561
        options.code = code;
562

    
563
        return options;
564
    }
565

    
566

    
567
    // Backbone extensions
568
    //
569
    // super method
570
    Backbone.Model.prototype._super = Backbone.Collection.prototype._super = Backbone.View.prototype._super = function(funcName){
571
        return this.constructor.__super__[funcName].apply(this, _.rest(arguments));
572
    }
573

    
574
    // simple string format helper 
575
    // http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format
576
    String.prototype.format = function() {
577
        var formatted = this;
578
        for (var i = 0; i < arguments.length; i++) {
579
            var regexp = new RegExp('\\{'+i+'\\}', 'gi');
580
            formatted = formatted.replace(regexp, arguments[i]);
581
        }
582
        return formatted;
583
    };
584

    
585

    
586
    $.fn.setCursorPosition = function(pos) {
587
        if ($(this).get(0).setSelectionRange) {
588
          $(this).get(0).setSelectionRange(pos, pos);
589
        } else if ($(this).get(0).createTextRange) {
590
          var range = $(this).get(0).createTextRange();
591
          range.collapse(true);
592
          range.moveEnd('character', pos);
593
          range.moveStart('character', pos);
594
          range.select();
595
        }
596
    }
597

    
598
    // trim prototype for IE
599
    if(typeof String.prototype.trim !== 'function') {
600
        String.prototype.trim = function() {
601
            return this.replace(/^\s+|\s+$/g, '');
602
        }
603
    }
604

    
605
    // http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area 
606
    $.fn.setCursorPosition = function(pos) {
607
        // not all browsers support setSelectionRange
608
        // put it in try/catch, fallback to no text selection
609
        try {
610
            if ($(this).get(0).setSelectionRange) {
611
              $(this).get(0).setSelectionRange(pos, pos);
612
            } else if ($(this).get(0).createTextRange) {
613
              var range = $(this).get(0).createTextRange();
614
              range.collapse(true);
615
              range.moveEnd('character', pos);
616
              range.moveStart('character', pos);
617
              range.select();
618
            }
619
        } catch (err) {
620
        }
621
    }
622

    
623
    // indexOf prototype for IE
624
    if (!Array.prototype.indexOf) {
625
      Array.prototype.indexOf = function(elt /*, from*/) {
626
        var len = this.length;
627
        var from = Number(arguments[1]) || 0;
628
        from = (from < 0)
629
             ? Math.ceil(from)
630
             : Math.floor(from);
631
        if (from < 0)
632
          from += len;
633

    
634
        for (; from < len; from++) {
635
          if (from in this &&
636
              this[from] === elt)
637
            return from;
638
        }
639
        return -1;
640
      };
641
    }
642

    
643
})(this);