Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / ui / static / snf / js / utils.js @ 126a01f2

History | View | Annotate | Download (20.2 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

    
228
    synnefo.util.IP_REGEX = /(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/([0-9]|[1-2][0-9]|3[0-2]?)$/
229

    
230
    synnefo.i18n.API_ERROR_MESSAGES = {
231
        'timeout': {
232
            'message': 'TIMEOUT', 
233
            'allow_report': false,
234
            'type': 'Network'
235
        },
236
        
237
        'error': {
238
            'message': 'API error'
239
        }, 
240

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

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

    
258

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

    
265
        return {del: removed, add: added};
266
    }
267

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
452
        this.initialize();
453
    }
454

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

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

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

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

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

    
497
        if (xhr.responseText) {
498
            try {
499
                json_data = JSON.parse(xhr.responseText)
500
            } catch (err) {
501
                json_data = 'Raw error response contnent (could not parse as JSON):\n\n' + xhr.responseText;
502
            }
503
        }
504
        
505
        module = "API"
506

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

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

    
536
        if (critical) {
537
            defaults.allow_report = true;
538
        }
539
        
540
        if (json_data) {
541
            if (_.isObject(json_data)) {
542
                $.each(json_data, function(key, obj) {
543
                    code = obj.code;
544
                    details = obj.details;
545
                    error_message = obj.message;
546
                })
547
            } else {
548
                details = json_data;
549
            }
550
        }
551

    
552
        extra = {'URL': ajax_settings.url};
553
        options = {};
554
        options = _.extend(options, {'details': details, 'message': error_message, 'ns': module, 'extra_details': extra});
555
        options = _.extend(options, call_settings);
556
        options = _.extend(options, synnefo.i18n.API_ERROR_MESSAGES[error_message] || {});
557
        options = _.extend(options, synnefo.i18n.API_ERROR_MESSAGES[code] || {});
558
        
559
        if (window.ERROR_OVERRIDES && window.ERROR_OVERRIDES[options.message]) {
560
            options.message = window.ERROR_OVERRIDES[options.message];
561
        }
562
        
563
        if (code && window.ERROR_OVERRIDES && window.ERROR_OVERRIDES[code]) {
564
            options.message = window.ERROR_OVERRIDES[code];
565
        }
566

    
567
        options = _.extend(defaults, options);
568
        options.code = code;
569

    
570
        return options;
571
    }
572

    
573

    
574
    // Backbone extensions
575
    //
576
    // super method
577
    Backbone.Model.prototype._super = Backbone.Collection.prototype._super = Backbone.View.prototype._super = function(funcName){
578
        return this.constructor.__super__[funcName].apply(this, _.rest(arguments));
579
    }
580

    
581
    // simple string format helper 
582
    // http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format
583
    String.prototype.format = function() {
584
        var formatted = this;
585
        for (var i = 0; i < arguments.length; i++) {
586
            var regexp = new RegExp('\\{'+i+'\\}', 'gi');
587
            formatted = formatted.replace(regexp, arguments[i]);
588
        }
589
        return formatted;
590
    };
591

    
592

    
593
    $.fn.setCursorPosition = function(pos) {
594
        if ($(this).get(0).setSelectionRange) {
595
          $(this).get(0).setSelectionRange(pos, pos);
596
        } else if ($(this).get(0).createTextRange) {
597
          var range = $(this).get(0).createTextRange();
598
          range.collapse(true);
599
          range.moveEnd('character', pos);
600
          range.moveStart('character', pos);
601
          range.select();
602
        }
603
    }
604

    
605
    // trim prototype for IE
606
    if(typeof String.prototype.trim !== 'function') {
607
        String.prototype.trim = function() {
608
            return this.replace(/^\s+|\s+$/g, '');
609
        }
610
    }
611

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

    
630
    // indexOf prototype for IE
631
    if (!Array.prototype.indexOf) {
632
      Array.prototype.indexOf = function(elt /*, from*/) {
633
        var len = this.length;
634
        var from = Number(arguments[1]) || 0;
635
        from = (from < 0)
636
             ? Math.ceil(from)
637
             : Math.floor(from);
638
        if (from < 0)
639
          from += len;
640

    
641
        for (; from < len; from++) {
642
          if (from in this &&
643
              this[from] === elt)
644
            return from;
645
        }
646
        return -1;
647
      };
648
    }
649

    
650
})(this);