Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / ui / static / snf / js / utils.js @ 0b416fc7

History | View | Annotate | Download (21.1 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
            'message': 'TIMEOUT', 
252
            'allow_report': false,
253
            'type': 'Network'
254
        },
255
        
256
        'error': {
257
            'message': 'API error'
258
        }, 
259

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

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

    
277

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

    
284
        return {del: removed, add: added};
285
    }
286

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
471
        this.initialize();
472
    }
473

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

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

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

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

    
514
        var critical = ajax_settings.critical === undefined ? true : ajax_settings.critical;
515

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

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

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

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

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

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

    
594
        return options;
595
    }
596

    
597

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

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

    
616

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

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

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

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

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

    
674
})(this);