Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / ui / static / snf / js / utils.js @ 738a9b18

History | View | Annotate | Download (20 kB)

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

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

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

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

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

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

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

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

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

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

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

    
120
        return data;
121
    }
122

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

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

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

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

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

    
160
        return res;
161
    }
162

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

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

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

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

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

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

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

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

    
255

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
449
        this.initialize();
450
    }
451

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

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

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

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

    
492
        var critical = ajax_settings.critical === undefined ? true : ajax_settings.critical;
493

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

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

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

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

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

    
564
        options = _.extend(defaults, options);
565
        options.code = code;
566

    
567
        return options;
568
    }
569

    
570

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

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

    
589

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

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

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

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

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

    
647
})(this);