Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / ui / static / snf / js / utils.js @ 1e882dd7

History | View | Annotate | Download (20.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
    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) {
240
        var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
241
        var e = Math.floor(Math.log(bytes)/Math.log(1024));
242
        return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
243
    }
244
    
245

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

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

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

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

    
276

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

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

    
286
    synnefo.util.open_window = function(url, name, specs) {
287
        // default specs
288
        var opts = _.extend({
289
            scrollbars: 'no',
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
        window.open(url, name, opts);
304
    }
305
    
306
    synnefo.util.readFileContents = function(f, cb) {
307
        var reader = new FileReader();
308
        var start = 0;
309
        var stop = f.size - 1;
310

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
470
        this.initialize();
471
    }
472

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

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

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

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

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

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

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

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

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

    
570
        extra = {'URL': ajax_settings.url};
571
        options = {};
572
        options = _.extend(options, {'details': details, 'message': error_message, 'ns': module, 'extra_details': extra});
573
        options = _.extend(options, call_settings);
574
        options = _.extend(options, synnefo.i18n.API_ERROR_MESSAGES[error_message] || {});
575
        options = _.extend(options, synnefo.i18n.API_ERROR_MESSAGES[code] || {});
576
        
577
        if (window.ERROR_OVERRIDES && window.ERROR_OVERRIDES[options.message]) {
578
            options.message = window.ERROR_OVERRIDES[options.message];
579
        }
580
        
581
        if (code && window.ERROR_OVERRIDES && window.ERROR_OVERRIDES[code]) {
582
            options.message = window.ERROR_OVERRIDES[code];
583
        }
584

    
585
        options = _.extend(defaults, options);
586
        options.code = code;
587

    
588
        return options;
589
    }
590

    
591

    
592
    // Backbone extensions
593
    //
594
    // super method
595
    Backbone.Model.prototype._super = Backbone.Collection.prototype._super = Backbone.View.prototype._super = function(funcName){
596
        return this.constructor.__super__[funcName].apply(this, _.rest(arguments));
597
    }
598

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

    
610

    
611
    $.fn.setCursorPosition = function(pos) {
612
        if ($(this).get(0).setSelectionRange) {
613
          $(this).get(0).setSelectionRange(pos, pos);
614
        } else if ($(this).get(0).createTextRange) {
615
          var range = $(this).get(0).createTextRange();
616
          range.collapse(true);
617
          range.moveEnd('character', pos);
618
          range.moveStart('character', pos);
619
          range.select();
620
        }
621
    }
622

    
623
    // trim prototype for IE
624
    if(typeof String.prototype.trim !== 'function') {
625
        String.prototype.trim = function() {
626
            return this.replace(/^\s+|\s+$/g, '');
627
        }
628
    }
629

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

    
648
    // indexOf prototype for IE
649
    if (!Array.prototype.indexOf) {
650
      Array.prototype.indexOf = function(elt /*, from*/) {
651
        var len = this.length;
652
        var from = Number(arguments[1]) || 0;
653
        from = (from < 0)
654
             ? Math.ceil(from)
655
             : Math.floor(from);
656
        if (from < 0)
657
          from += len;
658

    
659
        for (; from < len; from++) {
660
          if (from in this &&
661
              this[from] === elt)
662
            return from;
663
        }
664
        return -1;
665
      };
666
    }
667

    
668
})(this);