Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / ui / static / snf / js / utils.js @ 986bcfe4

History | View | Annotate | Download (21.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
    synnefo.util.FormatDigits = function(num, length) {
137
        var r = "" + num;
138
        while (r.length < length) {
139
            r = "0" + r;
140
        }
141
        return r;
142
    }
143

    
144
    synnefo.util.formatDate = function(d) {
145
        var dt = synnefo.util.FormatDigits(d.getDate()) + '/';
146
        dt += synnefo.util.FormatDigits(d.getMonth(), 2);
147
        dt += '/' + d.getFullYear();
148
        dt += ' ' + synnefo.util.FormatDigits(d.getHours(), 2) + ':';
149
        dt += synnefo.util.FormatDigits(d.getMinutes(), 2) + ':';
150
        dt += synnefo.util.FormatDigits(d.getSeconds(), 2);
151
        return dt;
152
    },
153

    
154
    // Extensions and Utility functions
155
    synnefo.util.ISODateString = function(d){
156
        function pad(n){
157
            return n<10 ? '0'+n : n
158
        }
159
         return d.getUTCFullYear()+'-'
160
         + pad(d.getUTCMonth()+1)+'-'
161
         + pad(d.getUTCDate())+'T'
162
         + pad(d.getUTCHours())+':'
163
         + pad(d.getUTCMinutes())+':'
164
         + pad(d.getUTCSeconds())+'Z'
165
    }
166

    
167
    
168
    synnefo.util.parseHeaders = function(headers) {
169
        var res = {};
170
        _.each(headers.split("\n"), function(h) {
171
            var tuple = h.split(/:(.+)?/);
172
            if (!tuple.length > 1 || !(tuple[0] && tuple[1])) {
173
                return;
174
            }
175
            res[tuple[0]] = tuple[1]
176
        })
177

    
178
        return res;
179
    }
180

    
181
    synnefo.util.parseUri = function(sourceUri) {
182
        var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
183
        var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri);
184
        var uri = {};
185
        
186
        for(var i = 0; i < 10; i++){
187
            uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
188
        }
189
    
190
        // Always end directoryPath with a trailing backslash if a path was present in the source URI
191
        // Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key
192
        if(uri.directoryPath.length > 0){
193
            uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
194
        }
195
        
196
        return uri;
197
    }
198

    
199
    synnefo.util.equalHeights = function() {
200
        var max_height = 0;
201
        var selectors = _.toArray(arguments);
202
            
203
        _.each(selectors, function(s){
204
            console.log($(s).height());
205
        })
206
        // TODO: implement me
207
    }
208

    
209
    synnefo.util.ClipHelper = function(wrapper, text, settings) {
210
        settings = settings || {};
211
        this.el = $('<div class="clip-copy"></div>');
212
        wrapper.append(this.el);
213
        this.clip = $(this.el).zclip(_.extend({
214
            path: synnefo.config.js_url + "lib/ZeroClipboard.swf",
215
            copy: text
216
        }, settings));
217
    }
218

    
219
    synnefo.util.truncate = function(string, size, append, words) {
220
        if (string === undefined) { return "" };
221
        if (string.length <= size) {
222
            return string;
223
        }
224

    
225
        if (append === undefined) {
226
            append = "...";
227
        }
228
        
229
        if (!append) { append = "" };
230
        // TODO: implement word truncate
231
        if (words === undefined) {
232
            words = false;
233
        }
234
        
235
        len = size - append.length;
236
        return string.substring(0, len) + append;
237
    }
238

    
239
    synnefo.util.readablizeBytes = function(bytes, fix) {
240
        if (fix === undefined) { fix = 2; }
241
        var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
242
        var e = Math.floor(Math.log(bytes)/Math.log(1024));
243
        return (bytes/Math.pow(1024, Math.floor(e))).toFixed(fix)+" "+s[e];
244
    }
245
    
246

    
247
    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]?)$/
248

    
249
    synnefo.i18n.API_ERROR_MESSAGES = {
250
        'timeout': {
251
            'title': 'API error',
252
            'message': 'TIMEOUT', 
253
            'allow_report': false,
254
            'type': 'Network'
255
        },
256
        
257
        'error': {
258
            'title': 'API error',
259
            'message': null
260
        }, 
261

    
262
        'abort': {},
263
        'parserror': {},
264
        '413': {
265
            'title': "Account warning"
266
        }
267
    }
268
    
269
    synnefo.util.array_diff = function(arr1, arr2) {
270
        var removed = [];
271
        var added = [];
272

    
273
        _.each(arr1, function(v) {
274
            if (arr2.indexOf(v) == -1) {
275
                removed[removed.length] = v;
276
            }
277
        })
278

    
279

    
280
        _.each(arr2, function(v) {
281
            if (arr1.indexOf(v) == -1) {
282
                added[added.length] = v;
283
            }
284
        })
285

    
286
        return {del: removed, add: added};
287
    }
288

    
289
    synnefo.util.open_window = function(url, name, opts) {
290
        // default specs
291
        opts = _.extend({
292
            menubar: 'no',
293
            toolbar: 'no',
294
            status: 'no',
295
            height: screen.height,
296
            width: screen.width,
297
            fullscreen: 'yes',
298
            channelmode: 'yes',
299
            directories: 'no',
300
            left: 0,
301
            location: 'no',
302
            top: 0
303
        }, opts)
304
        
305
        var specs = _.map(opts, function(v,k) {return k + "=" + v}).join(",");
306
        window.open(url, name, specs);
307
    }
308
    
309
    synnefo.util.readFileContents = function(f, cb) {
310
        var reader = new FileReader();
311
        var start = 0;
312
        var stop = f.size - 1;
313

    
314
        reader.onloadend = function(e) {
315
            return cb(e.target.result);
316
        }
317
        
318
        var data = reader.readAsText(f);
319
    },
320
    
321
    synnefo.util.generateKey = function(passphrase, length) {
322
        var passphrase = passphrase || "";
323
        var length = length || 1024;
324
        var key = cryptico.generateRSAKey(passphrase, length);
325

    
326
        _.extend(key.prototype, {
327
            download: function() {
328
            }
329
        });
330

    
331
        return key;
332
    }
333
    
334
    synnefo.util.publicKeyTypesMap = {
335
        "ecdsa-sha2-nistp256": "ecdsa",
336
        "ssh-dss" : "dsa",
337
        "ssh-rsa": "rsa"
338
    }
339

    
340
    synnefo.util.validatePublicKey = function(key) {
341
        var b64 = _(key).trim().split("\n").join("").split("\r\n").join("");
342
        var type = "rsa";
343

    
344
        // in case key starts with something like ssh-rsa
345
        if (b64.split(" ").length > 1) {
346
            var parts = key.split(" ");
347
            
348
            // identify key type
349
            type_key = parts[0];
350
            if (parseInt(type_key) >= 768) {
351
                type = "rsa1";
352
                
353
                if (parts[1] == 65537) {
354
                    if (parts.length == 3) {
355
                        return [parts[0], parts[1], parts[2]].join(" ")
356
                    }
357
                }
358
                // invalid rsa1 key
359
                throw "Invalid rsa1 key";
360
            }
361
            
362
            b64 = parts[1];
363
            if (!synnefo.util.publicKeyTypesMap[type_key]) { throw "Invalid rsa key (cannot identify encryption)" }
364

    
365
            try {
366
                var data = $.base64.decode(b64);
367
                return [parts[0], parts[1]].join(" ");
368
            } catch (err) {
369
                throw "Invalid key content";
370
            }
371

    
372
            throw "Invalid key content";
373
        }
374
        
375
        // no type defined check rsa
376
        if (_(b64).startsWith("AAAAB3NzaC1yc2EA")) {
377
            try {
378
                var data = $.base64.decode(b64);
379
                return ["ssh-rsa", b64].join(" ");
380
            } catch (err) {
381
                throw "Invalid content for rsa key";
382
            }
383
        }
384

    
385
        if (_(b64).startsWith("AAAAE2Vj")) {
386
            try {
387
                var data = $.base64.decode(b64);
388
                return ["ecdsa-sha2-nistp256", b64].join(" ");
389
            } catch (err) {
390
                throw "Invalid content for ecdsa key";
391
            }
392
        }
393

    
394
        if (_(b64).startsWith("AAAAB3N")) {
395
            try {
396
                var data = $.base64.decode(b64);
397
                return ["ssh-dss", b64].join(" ");
398
            } catch (err) {
399
                throw "Invalid content for dss key (" + err + ")";
400
            }
401
        }
402

    
403
        throw "Invalid key content";
404
    }
405
    
406
    // detect flash `like a boss`
407
    // http://stackoverflow.com/questions/998245/how-can-i-detect-if-flash-is-installed-and-if-not-display-a-hidden-div-that-inf/3336320#3336320 
408
    synnefo.util.hasFlash = function() {
409
        var hasFlash = false;
410
        try {
411
            var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
412
            if (fo) hasFlash = true;
413
        } catch(e) {
414
          if(navigator.mimeTypes ["application/x-shockwave-flash"] != undefined) hasFlash = true;
415
        }
416
        return hasFlash;
417
    }
418

    
419
    synnefo.util.promptSaveFile = function(selector, filename, data, options) {
420
        if (!synnefo.util.hasFlash()) { return };
421
        try {
422
            return $(selector).downloadify(_.extend({
423
                filename: function(){ return filename },
424
                data: function(){ return data },
425
                onComplete: function(){},
426
                onCancel: function(){},
427
                onError: function(){
428
                    console.log("ERROR", arguments);
429
                },
430
                swf: synnefo.config.media_url + 'js/lib/media/downloadify.swf',
431
                downloadImage: synnefo.config.images_url + 'download.png',
432
                transparent: true,
433
                append: false,
434
                height:20,
435
                width: 20,
436
                dataType: 'string'
437
          }, options));
438
        } catch (err) {
439
            return false;
440
        }
441
    }
442

    
443
    synnefo.util.canReadFile = function() {
444
        if ($.browser.msie) { return false };
445
        if (window.FileReader && window.File) {
446
            var f = File.prototype.__proto__;
447
            if (f.slice || f.webkitSlice || f.mozSlice) {
448
                return true
449
            }
450
        }
451
        return false;
452
    }
453

    
454
    synnefo.util.errorList = function() {
455
        
456
        this.initialize = function() {
457
            this.errors = {};
458
        }
459

    
460
        this.add = function(key, msg) {
461
            this.errors[key] = this.errors[key] || [];
462
            this.errors[key].push(msg);
463
        }
464

    
465
        this.get = function(key) {
466
            return this.errors[key];
467
        }
468

    
469
        this.empty = function() {
470
            return _.isEmpty(this.errors);
471
        }
472

    
473
        this.initialize();
474
    }
475

    
476
    synnefo.util.stacktrace = function() {
477
        try {
478
            var obj = {};
479
            if (window.Error && Error.captureStackTrace) {
480
                Error.captureStackTrace(obj, synnefo.util.stacktrace);
481
                return obj.stack;
482
            } else {
483
                return printStackTrace().join("<br /><br />");
484
            }
485
        } catch (err) {}
486
        return "";
487
    },
488
    
489
    synnefo.util.array_combinations = function(arr) {
490
        if (arr.length == 1) {
491
            return arr[0];
492
        } else {
493
            var result = [];
494

    
495
            // recur with the rest of array
496
            var allCasesOfRest = synnefo.util.array_combinations(arr.slice(1));  
497
            for (var i = 0; i < allCasesOfRest.length; i++) {
498
                for (var j = 0; j < arr[0].length; j++) {
499
                    result.push(arr[0][j] + "-" + allCasesOfRest[i]);
500
                }
501
            }
502
            return result;
503
        }
504
    }
505

    
506
    synnefo.util.parse_api_error = function() {
507
        if (arguments.length == 1) { arguments = arguments[0] };
508

    
509
        var xhr = arguments[0];
510
        var error_message = arguments[1];
511
        var error_thrown = arguments[2];
512
        var ajax_settings = _.last(arguments) || {};
513
        var call_settings = ajax_settings.error_params || {};
514
        var json_data = undefined;
515

    
516
        var critical = ajax_settings.critical === undefined ? true : ajax_settings.critical;
517

    
518
        if (xhr.responseText) {
519
            try {
520
                json_data = JSON.parse(xhr.responseText)
521
            } catch (err) {
522
                json_data = 'Raw error response contnent (could not parse as JSON):\n\n' + xhr.responseText;
523
            }
524
        }
525
        
526
        module = "API"
527

    
528
        try {
529
            path = synnefo.util.parseUri(ajax_settings.url).path.split("/");
530
            path.splice(0,3)
531
            module = path.join("/");
532
        } catch (err) {
533
            console.error("cannot identify api error module");
534
        }
535
        
536
        defaults = {
537
            'message': 'Api error',
538
            'type': 'API',
539
            'allow_report': true,
540
            'fatal_error': ajax_settings.critical || false,
541
            'non_critical': !critical
542
        }
543

    
544
        var code = -1;
545
        try {
546
            code = xhr.status || "undefined";
547
        } catch (err) {console.error(err);}
548
        var details = "";
549
        
550
        if ([413].indexOf(code) > -1) {
551
            defaults.non_critical = true;
552
            defaults.allow_report = false;
553
            defaults.allow_reload = false;
554
            error_message = "limit_error";
555
        }
556

    
557
        if (critical) {
558
            defaults.allow_report = true;
559
        }
560
        
561
        if (json_data) {
562
            if (_.isObject(json_data)) {
563
                $.each(json_data, function(key, obj) {
564
                    code = obj.code;
565
                    details = obj.details;
566
                    error_message = obj.message;
567
                })
568
            } else {
569
                details = json_data;
570
            }
571
        }
572

    
573
        extra = {'URL': ajax_settings.url};
574
        options = {};
575
        options = _.extend(options, {'details': details, 'message': error_message, 'ns': module, 'extra_details': extra});
576
        options = _.extend(options, call_settings);
577
        options = _.extend(options, synnefo.i18n.API_ERROR_MESSAGES[error_message] || {});
578
        options = _.extend(options, synnefo.i18n.API_ERROR_MESSAGES[code] || {});
579
        
580
        options.api_message = options.message;
581

    
582
        if (window.ERROR_OVERRIDES && window.ERROR_OVERRIDES[options.message]) {
583
            options.message = window.ERROR_OVERRIDES[options.message];
584
            options.api_message = '';
585
        }
586
        
587
        if (code && window.ERROR_OVERRIDES && window.ERROR_OVERRIDES[code]) {
588
            options.message = window.ERROR_OVERRIDES[code];
589
        }
590
        
591
        if (options.api_message == options.message) {
592
          options.api_message = '';
593
        }
594
        options = _.extend(defaults, options);
595
        options.code = code;
596

    
597
        return options;
598
    }
599

    
600

    
601
    // Backbone extensions
602
    //
603
    // super method
604
    Backbone.Model.prototype._super = Backbone.Collection.prototype._super = Backbone.View.prototype._super = function(funcName){
605
        return this.constructor.__super__[funcName].apply(this, _.rest(arguments));
606
    }
607

    
608
    // simple string format helper 
609
    // http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format
610
    String.prototype.format = function() {
611
        var formatted = this;
612
        for (var i = 0; i < arguments.length; i++) {
613
            var regexp = new RegExp('\\{'+i+'\\}', 'gi');
614
            formatted = formatted.replace(regexp, arguments[i]);
615
        }
616
        return formatted;
617
    };
618

    
619

    
620
    $.fn.setCursorPosition = function(pos) {
621
        if ($(this).get(0).setSelectionRange) {
622
          $(this).get(0).setSelectionRange(pos, pos);
623
        } else if ($(this).get(0).createTextRange) {
624
          var range = $(this).get(0).createTextRange();
625
          range.collapse(true);
626
          range.moveEnd('character', pos);
627
          range.moveStart('character', pos);
628
          range.select();
629
        }
630
    }
631

    
632
    // trim prototype for IE
633
    if(typeof String.prototype.trim !== 'function') {
634
        String.prototype.trim = function() {
635
            return this.replace(/^\s+|\s+$/g, '');
636
        }
637
    }
638

    
639
    // http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area 
640
    $.fn.setCursorPosition = function(pos) {
641
        // not all browsers support setSelectionRange
642
        // put it in try/catch, fallback to no text selection
643
        try {
644
            if ($(this).get(0).setSelectionRange) {
645
              $(this).get(0).setSelectionRange(pos, pos);
646
            } else if ($(this).get(0).createTextRange) {
647
              var range = $(this).get(0).createTextRange();
648
              range.collapse(true);
649
              range.moveEnd('character', pos);
650
              range.moveStart('character', pos);
651
              range.select();
652
            }
653
        } catch (err) {
654
        }
655
    }
656

    
657
    // indexOf prototype for IE
658
    if (!Array.prototype.indexOf) {
659
      Array.prototype.indexOf = function(elt /*, from*/) {
660
        var len = this.length;
661
        var from = Number(arguments[1]) || 0;
662
        from = (from < 0)
663
             ? Math.ceil(from)
664
             : Math.floor(from);
665
        if (from < 0)
666
          from += len;
667

    
668
        for (; from < len; from++) {
669
          if (from in this &&
670
              this[from] === elt)
671
            return from;
672
        }
673
        return -1;
674
      };
675
    }
676

    
677
})(this);