<commit_before>function getWidth(){
    var xWidth = null;
    if(window.screen != null)
        xWidth = window.screen.availWidth;

    if(window.innerWidth != null)
        xWidth = window.innerWidth;

    if(document.body != null)
        xWidth = document.body.clientWidth;

    return xWidth;
}

function getHeight(){
    var xHeight = null;

    if(window.screen != null)
        xHeight = window.screen.availHeight;

    if(window.innerHeight != null)
        xHeight =   window.innerHeight;

    if(document.body != null)
        xHeight = document.body.clientHeight;

    return xHeight;
}

var world = (function(){

    this.game = null;
    this.scene = null;

    this.init = function(game){
        this.game = game;
        this.scene = new Scene();
    };

    this.size = new Vec2(getWidth(), getHeight());
    this.animals = [];
    this.obstacles = {};

    this.addAnimal = function(animal){
        this.animals.push(animal);
        this.scene.addChild(animal);
    };
    this.addAnimalsAss = function(ass){
        this.scene.addChild(ass);
    };

    this.isObstacleAt = function(pos){
        var p = pos.divV(this.field_size);
        if(this.obstacles[Math.floor(p.y)] && this.obstacles[Math.floor(p.y)][Math.floor(p.x)])
                return true;

        return false;
    };

    this.field_size = null;

    this.readMap = function(map){
        var maps_size = new Vec2(map[0].length, map.length);
        this.field_size = this.size.divV(maps_size);

        for(var i = 0; i < map.length; i++){
            this.obstacles[i] = {};

            for(var j = 0; j < map[i].length; j++){

                var path = null;
                switch(map[i][j]){
                    case 0:
                        continue;
                    case 1:
                        path = 'trees_1.png'
                        break;
                    case 2:
                        path = 'trees_2.png'
                        break;
                    case 3:
                        path = 'trees_3.png'
                        break;
                    case 4:
                        path = 'trees_4.png'
                        break;
                    case 20:
                        var a1 = new Player(this.field_size.mulV(new Vec2(j, i)));
                        a1.type = "player_cow";
                        //new Player(new Vec2(i, j).mulV(this.field_size));
                        continue;
                    case 30:
                        new Cow(this.field_size.mulV(new Vec2(j, i)));
                        continue;
                    case 40:
                        //new Wombat(this.field_size.mulV(new Vec2(j, i)));
                        continue;
                }

                var img = world.game.assets['img/' + path];
                var sprite = new Sprite(img.width, img.height);
                sprite.image = img;

                var padding = 0.02;
                var paddedField = this.field_size.mulS(1 + padding * 2);

                sprite.scale(paddedField.x / img.width, paddedField.y / img.height);
                sprite.pos = this.field_size.mulV(new Vec2(j * (1 - padding),i * (1 - padding)));

                this.obstacles[i][j] = sprite;
                this.scene.addChild(sprite);
            }
        }
    };

    this.par = null;
    this.music = null;
    this.onStartStash = [];
    this.registerOnGameStart = function(param, item){
        this.onStartStash.push({fun: item, par: param});
    }

    this.onUpdateStash = [];
    this.registerOnUpdate = function(param, item){
        this.onUpdateStash.push({fun: item, par: param});
    }

    this.onClickStash = [];
    this.registerOnClick = function(param, item){
        this.onClickStash.push({fun: item, par: param});
    }

    this.preloadStash = [];
    this.registerPreload = function(item){
        this.preloadStash.push(item);
    }

    this.start = function(){
        this.par   = new Particle();
        this.music = new Music();

        this.game.preload(this.par.preload);
        this.game.preload(this.music.preload);
        this.game.preload("img/grass2.png");
        this.game.preload("img/trees_1.png");
        this.game.preload("img/trees_2.png");
        this.game.preload("img/trees_3.png");
        this.game.preload("img/trees_4.png");
        this.game.preload("img/cow_animation.png");
        this.game.preload("img/cow_ass.png");
        this.game.preload("img/cow_animation.png");
        this.game.preload("img/cow_ass.png");
        this.game.preload("img/beaver_animation.png");
        this.game.preload("img/beaver_ass.png");

        for(var i = 0; i < this.preloadStash.length; i++){
            this.game.preload( this.preloadStash[i]);
        }

        world.game.onload = function(){
            world.game.pushScene(scene);
            world.load_level(1);

            world.par.init();
            //world.music.init();

            for(var i = 0; i < world.onStartStash.length; i++){
                world.onStartStash[i].fun(world.onStartStash[i].par);
            }
        };
        this.game.start();
    }
    return this;
})();
<commit_msg>new things to do in map<commit_after>function getWidth(){
    var xWidth = null;
    if(window.screen != null)
        xWidth = window.screen.availWidth;

    if(window.innerWidth != null)
        xWidth = window.innerWidth;

    if(document.body != null)
        xWidth = document.body.clientWidth;

    return xWidth;
}

function getHeight(){
    var xHeight = null;

    if(window.screen != null)
        xHeight = window.screen.availHeight;

    if(window.innerHeight != null)
        xHeight =   window.innerHeight;

    if(document.body != null)
        xHeight = document.body.clientHeight;

    return xHeight;
}

var world = (function(){

    this.game = null;
    this.scene = null;

    this.init = function(game){
        this.game = game;
        this.scene = new Scene();
    };

    this.size = new Vec2(getWidth(), getHeight());
    this.animals = [];
    this.obstacles = {};

    this.addAnimal = function(animal){
        this.animals.push(animal);
        this.scene.addChild(animal);
    };
    this.addAnimalsAss = function(ass){
        this.scene.addChild(ass);
    };

    this.isObstacleAt = function(pos){
        var p = pos.divV(this.field_size);
        if(this.obstacles[Math.floor(p.y)] && this.obstacles[Math.floor(p.y)][Math.floor(p.x)])
                return true;

        return false;
    };

    this.field_size = null;

    this.readMap = function(map){
        var maps_size = new Vec2(map[0].length, map.length);
        this.field_size = this.size.divV(maps_size);

        for(var i = 0; i < map.length; i++){
            this.obstacles[i] = {};

            for(var j = 0; j < map[i].length; j++){

                var path = null;
                switch(map[i][j]){
                    case 0:
                        continue;
                    case 1:
                        path = 'wood.png'
                        break;
                    case 2:
                        path = 'brick.png'
                        break;
                    case 3:
                        path = 'house.png'
                        break;
                    case 4:
                        path = 'camp.png'
                        break;
                    case 20:
                        var a1 = new Player(this.field_size.mulV(new Vec2(j, i)));
                        a1.type = "player_cow";
                        //new Player(new Vec2(i, j).mulV(this.field_size));
                        continue;
                    case 30:
                        new Cow(this.field_size.mulV(new Vec2(j, i)));
                        continue;
                    case 40:
                        //new Wombat(this.field_size.mulV(new Vec2(j, i)));
                        continue;
                }

                var img = world.game.assets['img/' + path];
                var sprite = new Sprite(img.width, img.height);
                sprite.image = img;

                var padding = 0.02;
                var paddedField = this.field_size.mulS(1 + padding * 2);

                sprite.scale(paddedField.x / img.width, paddedField.y / img.height);
                sprite.pos = this.field_size.mulV(new Vec2(j * (1 - padding),i * (1 - padding)));

                this.obstacles[i][j] = sprite;
                this.scene.addChild(sprite);
            }
        }
    };

    this.par = null;
    this.music = null;
    this.onStartStash = [];
    this.registerOnGameStart = function(param, item){
        this.onStartStash.push({fun: item, par: param});
    }

    this.onUpdateStash = [];
    this.registerOnUpdate = function(param, item){
        this.onUpdateStash.push({fun: item, par: param});
    }

    this.onClickStash = [];
    this.registerOnClick = function(param, item){
        this.onClickStash.push({fun: item, par: param});
    }

    this.preloadStash = [];
    this.registerPreload = function(item){
        this.preloadStash.push(item);
    }

    this.start = function(){
        this.par   = new Particle();
        this.music = new Music();

        this.game.preload(this.par.preload);
        this.game.preload(this.music.preload);
        this.game.preload("img/grass2.png");
        this.game.preload("img/brick.png");
        this.game.preload("img/camp.png");
        this.game.preload("img/house.png");
        this.game.preload("img/wood.png");
        this.game.preload("img/cow_animation.png");
        this.game.preload("img/cow_ass.png");
        this.game.preload("img/cow_animation.png");
        this.game.preload("img/cow_ass.png");
        this.game.preload("img/beaver_animation.png");
        this.game.preload("img/beaver_ass.png");

        for(var i = 0; i < this.preloadStash.length; i++){
            this.game.preload( this.preloadStash[i]);
        }

        world.game.onload = function(){
            world.game.pushScene(scene);
            world.load_level(1);

            world.par.init();
            //world.music.init();

            for(var i = 0; i < world.onStartStash.length; i++){
                world.onStartStash[i].fun(world.onStartStash[i].par);
            }
        };
        this.game.start();
    }
    return this;
})();
<|endoftext|>


<commit_before>
  function showpoint(point) {
    var latdegrees = Math.abs(point.latitude);
    var latdegreepart = Math.floor(latdegrees);
    var latminutepart = 60 * (latdegrees - latdegreepart);
    var latdir = (point.lat > 0) ? "N" : "S";
    var lngdegrees = Math.abs(point.longitude);
    var lngdegreepart = Math.floor(lngdegrees);
    var lngminutepart = 60 * (lngdegrees - lngdegreepart);
    var lngdir = (point.longitude > 0) ? "E" : "W";
    var retstr = latdegreepart.toString() + "°" + latminutepart.toFixed(3) + "′" + latdir + " " + lngdegreepart.toString() + "°" + lngminutepart.toFixed(3) + "′" + lngdir;
    return retstr;
  }

 function leginfo(start, end) {
    var earthrad = 6378; // km
    var lat1 = start['latitude'] * Math.PI / 180;
    var lat2 = end['latitude'] * Math.PI / 180;
    var lon1 = start['longitude'] * Math.PI / 180;
    var lon2 = end['longitude'] * Math.PI / 180;
    var deltaLat = lat2 - lat1;
    var deltaLon = (end['longitude'] - start['longitude']) * Math.PI / 180;
    var a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = earthrad * c;
    var y = Math.sin(lon2 - lon1) * Math.cos(lat2);
    var x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);
    var brng = Math.round((360 + Math.atan2(y, x) * 180 / Math.PI) % 360);
    return {
      distance: d,
      bearing: brng
    };
  }
<commit_msg>Correct bug (typo) in geocalc causing latitude to display in wrong hemisphere<commit_after>
  function showpoint(point) {
    var latdegrees = Math.abs(point.latitude);
    var latdegreepart = Math.floor(latdegrees);
    var latminutepart = 60 * (latdegrees - latdegreepart);
    var latdir = (point.latitude > 0) ? "N" : "S";
    var lngdegrees = Math.abs(point.longitude);
    var lngdegreepart = Math.floor(lngdegrees);
    var lngminutepart = 60 * (lngdegrees - lngdegreepart);
    var lngdir = (point.longitude > 0) ? "E" : "W";
    var retstr = latdegreepart.toString() + "°" + latminutepart.toFixed(3) + "′" + latdir + " " + lngdegreepart.toString() + "°" + lngminutepart.toFixed(3) + "′" + lngdir;
    return retstr;
  }

 function leginfo(start, end) {
    var earthrad = 6378; // km
    var lat1 = start['latitude'] * Math.PI / 180;
    var lat2 = end['latitude'] * Math.PI / 180;
    var lon1 = start['longitude'] * Math.PI / 180;
    var lon2 = end['longitude'] * Math.PI / 180;
    var deltaLat = lat2 - lat1;
    var deltaLon = (end['longitude'] - start['longitude']) * Math.PI / 180;
    var a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = earthrad * c;
    var y = Math.sin(lon2 - lon1) * Math.cos(lat2);
    var x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);
    var brng = Math.round((360 + Math.atan2(y, x) * 180 / Math.PI) % 360);
    return {
      distance: d,
      bearing: brng
    };
  }
<|endoftext|>


<commit_before>'use strict';

// ---------------------------------------------------------------------------

const liqui = require ('./liqui.js');
const { ExchangeError, InsufficientFunds, DDoSProtection } = require ('./base/errors');

// ---------------------------------------------------------------------------

module.exports = class yobit extends liqui {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'yobit',
            'name': 'YoBit',
            'countries': 'RU',
            'rateLimit': 3000, // responses are cached every 2 seconds
            'version': '3',
            'has': {
                'createDepositAddress': true,
                'fetchDepositAddress': true,
                'CORS': false,
                'withdraw': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766910-cdcbfdae-5eea-11e7-9859-03fea873272d.jpg',
                'api': {
                    'public': 'https://yobit.net/api',
                    'private': 'https://yobit.net/tapi',
                },
                'www': 'https://www.yobit.net',
                'doc': 'https://www.yobit.net/en/api/',
                'fees': 'https://www.yobit.net/en/fees/',
            },
            'api': {
                'public': {
                    'get': [
                        'depth/{pair}',
                        'info',
                        'ticker/{pair}',
                        'trades/{pair}',
                    ],
                },
                'private': {
                    'post': [
                        'ActiveOrders',
                        'CancelOrder',
                        'GetDepositAddress',
                        'getInfo',
                        'OrderInfo',
                        'Trade',
                        'TradeHistory',
                        'WithdrawCoinsToAddress',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'maker': 0.002,
                    'taker': 0.002,
                },
                'funding': {
                    'withdraw': {},
                },
            },
            'commonCurrencies': {
                'AIR': 'AirCoin',
                'ANI': 'ANICoin',
                'ANT': 'AntsCoin',
                'ATM': 'Autumncoin',
                'BCC': 'BCH',
                'BCS': 'BitcoinStake',
                'BTS': 'Bitshares2',
                'DCT': 'Discount',
                'DGD': 'DarkGoldCoin',
                'ICN': 'iCoin',
                'LIZI': 'LiZi',
                'LUN': 'LunarCoin',
                'MDT': 'Midnight',
                'NAV': 'NavajoCoin',
                'OMG': 'OMGame',
                'PAY': 'EPAY',
                'PLC': 'Platin Coin',
                'REP': 'Republicoin',
                'RUR': 'RUB',
            },
            'options': {
                'fetchOrdersRequiresSymbol': true,
            },
        });
    }

    parseOrderStatus (status) {
        let statuses = {
            '0': 'open',
            '1': 'closed',
            '2': 'canceled',
            '3': 'open', // or partially-filled and closed? https://github.com/ccxt/ccxt/issues/1594
        };
        if (status in statuses)
            return statuses[status];
        return status;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostGetInfo ();
        let balances = response['return'];
        let result = { 'info': balances };
        let sides = { 'free': 'funds', 'total': 'funds_incl_orders' };
        let keys = Object.keys (sides);
        for (let i = 0; i < keys.length; i++) {
            let key = keys[i];
            let side = sides[key];
            if (side in balances) {
                let currencies = Object.keys (balances[side]);
                for (let j = 0; j < currencies.length; j++) {
                    let lowercase = currencies[j];
                    let uppercase = lowercase.toUpperCase ();
                    let currency = this.commonCurrencyCode (uppercase);
                    let account = undefined;
                    if (currency in result) {
                        account = result[currency];
                    } else {
                        account = this.account ();
                    }
                    account[key] = balances[side][lowercase];
                    if (account['total'] && account['free'])
                        account['used'] = account['total'] - account['free'];
                    result[currency] = account;
                }
            }
        }
        return this.parseBalance (result);
    }

    async createDepositAddress (code, params = {}) {
        let response = await this.fetchDepositAddress (code, this.extend ({
            'need_new': 1,
        }, params));
        let address = this.safeString (response, 'address');
        this.checkAddress (address);
        return {
            'currency': code,
            'address': address,
            'status': 'ok',
            'info': response['info'],
        };
    }

    async fetchDepositAddress (code, params = {}) {
        let currency = this.currency (code);
        let request = {
            'coinName': currency['id'],
            'need_new': 0,
        };
        let response = await this.privatePostGetDepositAddress (this.extend (request, params));
        let address = this.safeString (response['return'], 'address');
        this.checkAddress (address);
        return {
            'currency': code,
            'address': address,
            'status': 'ok',
            'info': response,
        };
    }

    async withdraw (currency, amount, address, tag = undefined, params = {}) {
        this.checkAddress (address);
        await this.loadMarkets ();
        let response = await this.privatePostWithdrawCoinsToAddress (this.extend ({
            'coinName': currency,
            'amount': amount,
            'address': address,
        }, params));
        return {
            'info': response,
            'id': undefined,
        };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if ('success' in response) {
            if (!response['success']) {
                if (response['error'].indexOf ('Insufficient funds') >= 0) { // not enougTh is a typo inside Liqui's own API...
                    throw new InsufficientFunds (this.id + ' ' + this.json (response));
                } else if (response['error'] === 'Requests too often') {
                    throw new DDoSProtection (this.id + ' ' + this.json (response));
                } else if ((response['error'] === 'not available') || (response['error'] === 'external service unavailable')) {
                    throw new DDoSProtection (this.id + ' ' + this.json (response));
                } else {
                    throw new ExchangeError (this.id + ' ' + this.json (response));
                }
            }
        }
        return response;
    }
};
<commit_msg>yobit AST → Astral fix #2500<commit_after>'use strict';

// ---------------------------------------------------------------------------

const liqui = require ('./liqui.js');
const { ExchangeError, InsufficientFunds, DDoSProtection } = require ('./base/errors');

// ---------------------------------------------------------------------------

module.exports = class yobit extends liqui {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'yobit',
            'name': 'YoBit',
            'countries': 'RU',
            'rateLimit': 3000, // responses are cached every 2 seconds
            'version': '3',
            'has': {
                'createDepositAddress': true,
                'fetchDepositAddress': true,
                'CORS': false,
                'withdraw': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766910-cdcbfdae-5eea-11e7-9859-03fea873272d.jpg',
                'api': {
                    'public': 'https://yobit.net/api',
                    'private': 'https://yobit.net/tapi',
                },
                'www': 'https://www.yobit.net',
                'doc': 'https://www.yobit.net/en/api/',
                'fees': 'https://www.yobit.net/en/fees/',
            },
            'api': {
                'public': {
                    'get': [
                        'depth/{pair}',
                        'info',
                        'ticker/{pair}',
                        'trades/{pair}',
                    ],
                },
                'private': {
                    'post': [
                        'ActiveOrders',
                        'CancelOrder',
                        'GetDepositAddress',
                        'getInfo',
                        'OrderInfo',
                        'Trade',
                        'TradeHistory',
                        'WithdrawCoinsToAddress',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'maker': 0.002,
                    'taker': 0.002,
                },
                'funding': {
                    'withdraw': {},
                },
            },
            'commonCurrencies': {
                'AIR': 'AirCoin',
                'ANI': 'ANICoin',
                'ANT': 'AntsCoin',
                'AST': 'Astral',
                'ATM': 'Autumncoin',
                'BCC': 'BCH',
                'BCS': 'BitcoinStake',
                'BTS': 'Bitshares2',
                'DCT': 'Discount',
                'DGD': 'DarkGoldCoin',
                'ICN': 'iCoin',
                'LIZI': 'LiZi',
                'LUN': 'LunarCoin',
                'MDT': 'Midnight',
                'NAV': 'NavajoCoin',
                'OMG': 'OMGame',
                'PAY': 'EPAY',
                'PLC': 'Platin Coin',
                'REP': 'Republicoin',
                'RUR': 'RUB',
            },
            'options': {
                'fetchOrdersRequiresSymbol': true,
            },
        });
    }

    parseOrderStatus (status) {
        let statuses = {
            '0': 'open',
            '1': 'closed',
            '2': 'canceled',
            '3': 'open', // or partially-filled and closed? https://github.com/ccxt/ccxt/issues/1594
        };
        if (status in statuses)
            return statuses[status];
        return status;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostGetInfo ();
        let balances = response['return'];
        let result = { 'info': balances };
        let sides = { 'free': 'funds', 'total': 'funds_incl_orders' };
        let keys = Object.keys (sides);
        for (let i = 0; i < keys.length; i++) {
            let key = keys[i];
            let side = sides[key];
            if (side in balances) {
                let currencies = Object.keys (balances[side]);
                for (let j = 0; j < currencies.length; j++) {
                    let lowercase = currencies[j];
                    let uppercase = lowercase.toUpperCase ();
                    let currency = this.commonCurrencyCode (uppercase);
                    let account = undefined;
                    if (currency in result) {
                        account = result[currency];
                    } else {
                        account = this.account ();
                    }
                    account[key] = balances[side][lowercase];
                    if (account['total'] && account['free'])
                        account['used'] = account['total'] - account['free'];
                    result[currency] = account;
                }
            }
        }
        return this.parseBalance (result);
    }

    async createDepositAddress (code, params = {}) {
        let response = await this.fetchDepositAddress (code, this.extend ({
            'need_new': 1,
        }, params));
        let address = this.safeString (response, 'address');
        this.checkAddress (address);
        return {
            'currency': code,
            'address': address,
            'status': 'ok',
            'info': response['info'],
        };
    }

    async fetchDepositAddress (code, params = {}) {
        let currency = this.currency (code);
        let request = {
            'coinName': currency['id'],
            'need_new': 0,
        };
        let response = await this.privatePostGetDepositAddress (this.extend (request, params));
        let address = this.safeString (response['return'], 'address');
        this.checkAddress (address);
        return {
            'currency': code,
            'address': address,
            'status': 'ok',
            'info': response,
        };
    }

    async withdraw (currency, amount, address, tag = undefined, params = {}) {
        this.checkAddress (address);
        await this.loadMarkets ();
        let response = await this.privatePostWithdrawCoinsToAddress (this.extend ({
            'coinName': currency,
            'amount': amount,
            'address': address,
        }, params));
        return {
            'info': response,
            'id': undefined,
        };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if ('success' in response) {
            if (!response['success']) {
                if (response['error'].indexOf ('Insufficient funds') >= 0) { // not enougTh is a typo inside Liqui's own API...
                    throw new InsufficientFunds (this.id + ' ' + this.json (response));
                } else if (response['error'] === 'Requests too often') {
                    throw new DDoSProtection (this.id + ' ' + this.json (response));
                } else if ((response['error'] === 'not available') || (response['error'] === 'external service unavailable')) {
                    throw new DDoSProtection (this.id + ' ' + this.json (response));
                } else {
                    throw new ExchangeError (this.id + ' ' + this.json (response));
                }
            }
        }
        return response;
    }
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
	LocalStrategy = require('passport-local').Strategy,
	User = require('mongoose').model('User');

module.exports = function() {
	// Use local strategy
	passport.use(new LocalStrategy({
			usernameField: 'username',
			passwordField: 'password'
		},
		function(username, password, done) {
			User.findOne({
				username: username
			}, function(err, user) {
				if (err) {
					return done(err);
				}
				if (!user) {
					return done(null, false, {
						message: 'Unknown user or invalid password'
					});
				}
				if (!user.authenticate(password)) {
					return done(null, false, {
						message: 'Unknown user or invalid password'
					});
				}

				return done(null, user);
			});
		}
	));
};
<commit_msg>fix:user<commit_after>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
	LocalStrategy = require('passport-local').Strategy,
	User = require('mongoose').model('User');

module.exports = function() {
	// Use local strategy
	passport.use(new LocalStrategy({
			usernameField: 'username',
			passwordField: 'password'
		},
		function(username, password, done) {
			User.findOne({
				username: username
			}, function(err, user) {
				if (err) {
					return done(err);
				}
				if (!user) {
					return done(null, false, {
						message: '未注册的用户，请检查后重试。/Unknown user'
					});
				}
				if (!user.authenticate(password)) {
					return done(null, false, {
						message: '密码出错。/invalid password'
					});
				}

				return done(null, user);
			});
		}
	));
};
<|endoftext|>


<commit_before>// report/search

require.def(

    'report/search',

    ['rest/datasource', 'rest/renderer', 'report/templates', 'lib/jquery.ui', 'lib/json2'],

    function(m_datasource, m_renderer, m_templates) {

        function init() {

            var body = $('body'),
                columns = $('#columns'),
                active_columns = $('#active-columns'),

                searchdialog = $('#search-dialog'),
                searchinput = $('#search'),
                searchform = $('form', searchdialog),
                searchbutton = $('#search-button');

            var perspective_uri = searchdialog.attr('data-uri'),
                column_uri = searchform.attr('action');

            /*
             * Pre-setup and event handler binding
             */
            body.bind('update.perspective', function(evt, params) {
                $.putJSON(perspective_uri, JSON.stringify(params), function() {
                    body.trigger('update.report');
                });
                return false;
            });

            searchdialog.cache = {};

            searchdialog.get = function(id) {
                if (!searchdialog.cache[id]) {
                    var sel = '[data-model=column][data-id=' + id + ']';

                    searchdialog.cache[id] = {
                        'src': columns.find(sel),
                        'tgt': active_columns.find(sel)
                    };
                }
                return searchdialog.cache[id];
            };

            searchdialog.bind('addall.column', function(evt, id) {
                var category = $('[data-model=category][data-id=' + id + ']'),
                    columns = category.find('.active:not(.filtered)');

                category.hide();
                for (var i=columns.length; i--;)
                    searchdialog.trigger('add.column', [$(columns[i]).attr('data-id')]);

                return false;
            });

            searchdialog.bind('add.column', function(evt, id) {
                map = searchdialog.get(id);

                map.src.removeClass('active');

                // check to see if this is the last child being 'activated',
                // if so then hide the category
                var sibs = map.src.siblings('.active:not(.filtered)');
                if (sibs.length == 0)
                    map.src.parents('[data-model=category]').hide();

                // detach from wherever it is and append it to the end of the
                // list. since non-active columns are not shown, this will be
                // perceived as being added to the end of the 'visible' list
                active_columns.append(
                    map.tgt.detach().addClass('active')
                );

                return false;
            });

            searchdialog.bind('remove.column', function(evt, id) {
                map = searchdialog.get(id);

                map.tgt.removeClass('active');
                map.src.addClass('active').parents('[data-model=category]').show();

                return false;
            });

            searchdialog.bind('removeall.column', function(evt) {
                for (var id in searchdialog.cache)
                    searchdialog.trigger('remove.column', [id]);

                return false;
            });

            searchdialog.bind('search.column', function(evt, value) {
                searchinput.trigger('search', value);
                return false;
            });

            searchdialog.bind('save.column', function(evt) {
                var children = active_columns.children('.active'),
                    ids = $.map(children, function(e, i) {
                        return parseInt($(e).attr('data-id'));
                    });

                body.trigger('update.perspective', [{columns: ids}]);
                return false;
            });

            searchdialog.bind('filter.column', function(evt, id) {
                map = searchdialog.get(id);
                map.src.addClass('filtered');
                var sibs = map.src.siblings('.active:not(.filtered)');
                if (sibs.length == 0)
                    map.src.parents('[data-model=category]').hide();
            });

            searchdialog.bind('filterall.column', function(evt) {
                var objs = columns.find('[data-model=column]');
                for (var i = objs.length; i--;)
                    searchdialog.trigger('filter.column', [$(objs[i]).attr('data-id')]);
                return false;
            });

            searchdialog.bind('unfilter.column', function(evt, id) {
                map = searchdialog.get(id);
                map.src.removeClass('filtered');
                map.src.parents('[data-model=category]').show();
                return false;
            });

//            var rnd = {
//                columns: new m_renderer.template({
//                    target: columns,
//                    template: m_templates.columns
//                }),
//                active_columns: new m_renderer.template({
//                    target: active_columns,
//                    template: m_templates.active_columns
//                })
//            };

            var src = {
//                columns: new m_datasource.ajax({
//                    uri: column_uri,
//                    success: function(json) {
//                        rnd.columns.render(json);
//
//                        // only the columns are needed for setting up the list
//                        // of potential 'active columns'
//                        var columns = json.map(function(e) {
//                            return e['columns'];
//                        });
//                        columns = Array.prototype.concat.apply([], columns);
//                        rnd.active_columns.render(columns);
//
//                    }
//                }),
                perspective: new m_datasource.ajax({
                    uri: perspective_uri,
                    success: function(json) {
                        if (json.store) {
                            var rcols = json.store.columns;
                            for (var i=0; i < rcols.length; i++)
                                searchdialog.trigger('add.column', [rcols[i]]);
                        }
                    }
                })
            };

//            src.columns.get();
            src.perspective.get();

            // $('#columns li').bind({
            //     'mouseover': function() {
            //         var target = $(this);
            //         target.find('.info').css('display', 'inline-block');
            //     },
            //     'mouseout': function() {
            //         var target = $(this);
            //         target.find('.info').hide();
            //     }
            // });

            var descriptionBox = $('

')
                .appendTo('body');

            $('#columns').delegate('.actions > .info', 'mouseover', function() {
                var target = $(this).closest('li'),
                    offset = target.offset(),
                    width = target.outerWidth(),
                    description = target.children('.description').html();

                descriptionBox.html(description);
                descriptionBox.css({
                    left: offset.left + width + 20,
                    top: offset.top
                }).show();
            }).delegate('.actions > .info', 'mouseout', function() {
                descriptionBox.hide();
            });

            searchinput.autocomplete2({
                success: function(value, json) {
                    console.log(json);
                    searchinput.trigger('filterall.column');
                    for (var i = 0; i < json.length; i++)
                        searchinput.trigger('unfilter.column', [json[i]]);
                }
            });

            columns.delegate('.add-column', 'click', function(evt) {
                var id = evt.target.hash.substr(1);
                searchdialog.trigger('add.column', [id]);
                return false;
            });

            columns.delegate('.add-all', 'click', function(evt) {
                var id = evt.target.hash.substr(1);
                searchdialog.trigger('addall.column', [id]);
                return false;
            });

            active_columns.delegate('.remove-column', 'click', function(evt) {
                var id = evt.target.hash.substr(1);
                searchdialog.trigger('remove.column', [id]);
                return false;
            });

            searchdialog.delegate('.remove-all', 'click', function(evt) {
                searchdialog.trigger('removeall.column');
                return false;
            });

            searchdialog.dialog({
                autoOpen: false,
                draggable: true,
                resizable: true,
                title: 'Show/Hide Columns',
                height: 550,
                width: 700,
                minWidth: 700,
                buttons: {
                    Cancel: function() {
                        searchdialog.dialog('close');
                    },
                    Save: function() {
                        searchdialog.trigger('save.column');
                        searchdialog.dialog('close');
                    }
                }
            });

            /*
             * The active columns list is sortable to easily define the order
             * of display of the columns. That is, the order defined in the
             * list (top-bottom) translates to the order in the table
             * (left-right).
             */
            active_columns.sortable({
                placeholder: 'placeholder',
                forcePlaceholderSize: true,
                forceHelperSize: true,
                opacity: 0.5,
                cursor: 'move',
                tolerance: 'intersect'
            }).disableSelection();

            searchbutton.bind('click', function(evt) {
                searchdialog.dialog('open');
            });
        };

        return {init: init};
    }
);
<commit_msg>cleaned up js<commit_after>// report/search

require.def(

    'report/search',

    ['rest/datasource', 'rest/renderer', 'report/templates', 'lib/jquery.ui', 'lib/json2'],

    function(m_datasource, m_renderer, m_templates) {

        function init() {

            var body = $('body'),
                columns = $('#columns'),
                active_columns = $('#active-columns'),

                searchdialog = $('#search-dialog'),
                searchinput = $('#search'),
                searchform = $('form', searchdialog),
                searchbutton = $('#search-button');

            var perspective_uri = searchdialog.attr('data-uri'),
                column_uri = searchform.attr('action');

            /*
             * Pre-setup and event handler binding
             */
            body.bind('update.perspective', function(evt, params) {
                $.putJSON(perspective_uri, JSON.stringify(params), function() {
                    body.trigger('update.report');
                });
                return false;
            });

            searchdialog.cache = {};

            searchdialog.get = function(id) {
                if (!searchdialog.cache[id]) {
                    var sel = '[data-model=column][data-id=' + id + ']';

                    searchdialog.cache[id] = {
                        'src': columns.find(sel),
                        'tgt': active_columns.find(sel)
                    };
                }
                return searchdialog.cache[id];
            };

            searchdialog.bind('addall.column', function(evt, id) {
                var category = $('[data-model=category][data-id=' + id + ']'),
                    columns = category.find('.active:not(.filtered)');

                category.hide();
                for (var i=columns.length; i--;)
                    searchdialog.trigger('add.column', [$(columns[i]).attr('data-id')]);

                return false;
            });

            searchdialog.bind('add.column', function(evt, id) {
                map = searchdialog.get(id);

                map.src.removeClass('active');

                // check to see if this is the last child being 'activated',
                // if so then hide the category
                var sibs = map.src.siblings('.active:not(.filtered)');
                if (sibs.length == 0)
                    map.src.parents('[data-model=category]').hide();

                // detach from wherever it is and append it to the end of the
                // list. since non-active columns are not shown, this will be
                // perceived as being added to the end of the 'visible' list
                active_columns.append(
                    map.tgt.detach().addClass('active')
                );

                return false;
            });

            searchdialog.bind('remove.column', function(evt, id) {
                map = searchdialog.get(id);

                map.tgt.removeClass('active');
                map.src.addClass('active').parents('[data-model=category]').show();

                return false;
            });

            searchdialog.bind('removeall.column', function(evt) {
                for (var id in searchdialog.cache)
                    searchdialog.trigger('remove.column', [id]);

                return false;
            });

            searchdialog.bind('search.column', function(evt, value) {
                searchinput.trigger('search', value);
                return false;
            });

            searchdialog.bind('save.column', function(evt) {
                var children = active_columns.children('.active'),
                    ids = $.map(children, function(e, i) {
                        return parseInt($(e).attr('data-id'));
                    });

                body.trigger('update.perspective', [{columns: ids}]);
                return false;
            });

            searchdialog.bind('filter.column', function(evt, id) {
                map = searchdialog.get(id);
                map.src.addClass('filtered');
                var sibs = map.src.siblings('.active:not(.filtered)');
                if (sibs.length == 0)
                    map.src.parents('[data-model=category]').hide();
            });

            searchdialog.bind('filterall.column', function(evt) {
                var objs = columns.find('[data-model=column]');
                for (var i = objs.length; i--;)
                    searchdialog.trigger('filter.column', [$(objs[i]).attr('data-id')]);
                return false;
            });

            searchdialog.bind('unfilter.column', function(evt, id) {
                map = searchdialog.get(id);
                map.src.removeClass('filtered');
                map.src.parents('[data-model=category]').show();
                return false;
            });

            var src = {
                perspective: new m_datasource.ajax({
                    uri: perspective_uri,
                    success: function(json) {
                        if (json.store) {
                            var rcols = json.store.columns;
                            for (var i=0; i < rcols.length; i++)
                                searchdialog.trigger('add.column', [rcols[i]]);
                        }
                    }
                })
            };

            src.perspective.get();

            var descriptionBox = $('

')
                .appendTo('body');

            $('#columns').delegate('.actions > .info', 'mouseover', function() {
                var target = $(this).closest('li'),
                    offset = target.offset(),
                    width = target.outerWidth(),
                    description = target.children('.description').html();

                descriptionBox.html(description);
                descriptionBox.css({
                    left: offset.left + width + 20,
                    top: offset.top
                }).show();
            }).delegate('.actions > .info', 'mouseout', function() {
                descriptionBox.hide();
            });

            searchinput.autocomplete2({
                success: function(value, json) {
                    console.log(json);
                    searchinput.trigger('filterall.column');
                    for (var i = 0; i < json.length; i++)
                        searchinput.trigger('unfilter.column', [json[i]]);
                }
            });

            columns.delegate('.add-column', 'click', function(evt) {
                var id = evt.target.hash.substr(1);
                searchdialog.trigger('add.column', [id]);
                return false;
            });

            columns.delegate('.add-all', 'click', function(evt) {
                var id = evt.target.hash.substr(1);
                searchdialog.trigger('addall.column', [id]);
                return false;
            });

            active_columns.delegate('.remove-column', 'click', function(evt) {
                var id = evt.target.hash.substr(1);
                searchdialog.trigger('remove.column', [id]);
                return false;
            });

            searchdialog.delegate('.remove-all', 'click', function(evt) {
                searchdialog.trigger('removeall.column');
                return false;
            });

            searchdialog.dialog({
                autoOpen: false,
                draggable: true,
                resizable: true,
                title: 'Add or Remove Columns from this Report',
                height: 550,
                width: 700,
                minWidth: 700,
                buttons: {
                    Cancel: function() {
                        searchdialog.dialog('close');
                    },
                    Save: function() {
                        searchdialog.trigger('save.column');
                        searchdialog.dialog('close');
                    }
                }
            });

            /*
             * The active columns list is sortable to easily define the order
             * of display of the columns. That is, the order defined in the
             * list (top-bottom) translates to the order in the table
             * (left-right).
             */
            active_columns.sortable({
                placeholder: 'placeholder',
                forcePlaceholderSize: true,
                forceHelperSize: true,
                opacity: 0.5,
                cursor: 'move',
                tolerance: 'intersect'
            }).disableSelection();

            searchbutton.bind('click', function(evt) {
                searchdialog.dialog('open');
            });
        };

        return {init: init};
    }
);
<|endoftext|>


<commit_before>/* global _ */

/*
 * Complex scripted dashboard
 * This script generates a dashboard object that Grafana can load. It also takes a number of user
 * supplied URL parameters (int ARGS variable)
 */

// Accessable variables in this scope
var window, document, ARGS, $, jQuery, moment, kbn;

return function (callback) {
  'use strict';

  // Setup some variables
  var dashboard;
  var hostSeries = [];

  // GET variables
  var displayHost = '';
  var displayMetric = '';
  var displayTime;

  if(!_.isUndefined(ARGS.host))
    displayHost = ARGS.host;

  if(!_.isUndefined(ARGS.metric))
    displayMetric = ARGS.metric;

  if(!_.isUndefined(ARGS.time))
    displayTime = ARGS.time;

  // InfluxDB setup
  var influxUser = 'root';
  var influxPass = 'root';
  var influxDB = 'graphite';
  var influxDBUrl = window.location.protocol + '//' + window.location.host + ':8086';
  var influxdbQueryUrl = influxDBUrl + '/db/' + influxDB + '/series?u=' + influxUser +
                         '&p=' + influxPass + '&q=list series /\.' + displayHost + '\./';

  var getdashConfig = '/app/getdash/getdash.conf.js';

  // Intialize a skeleton with nothing but a rows array and service object
  dashboard = {
    'rows': [],
    'services': {}
  };

  // Set default time
  // time can be overriden in the url using from/to parameteres, but this is
  // handled automatically in grafana core during dashboard initialization

  // Dashboard time and interval setup function
  var getDashTimeInterval = function (time) {
    var defaultTimeInterval = {
      'time': {
        'from': "now-6h",
        'to': "now"
      },
      'interval': '1m',
    };

    if (!time)
      return defaultTimeInterval;

    var timeM = 0;
    var interval = '';
    var regexpTime = /(\d+)(m|h|d)/;
    var rTime = regexpTime.exec(time);

    if (!rTime)
      return defaultTimeInterval;

    if (rTime[2] === 'm')
      timeM = parseInt(rTime[1]);
    else if (rTime[2] === 'h')
      timeM = parseInt(rTime[1]) * 60;
    else if (rTime[2] === 'd')
      timeM = parseInt(rTime[1]) * 60 * 24;

    if (timeM > 360)
      interval = (Math.ceil((Math.floor(timeM / 360) + 1) / 5) * 5).toString() + 'm';
    else if (timeM === 360)
      interval = '1m';
    else
      interval = '30s';

    return {
      'time': {
        'from': "now-" + time,
        'to': "now"
      },
      'interval': interval,
    };
  };

  var dashTimeInterval = getDashTimeInterval(displayTime);
  var interval = dashTimeInterval.interval;
  dashboard.time = dashTimeInterval.time;

  // Set a title
  dashboard.title = 'Scripted Dashboard for ' + displayHost;

  // Dashboard setup helper functions
  var targetGen = function (series, alias, interval, column, apply) {
    return {
      'series': series,
      'alias': alias,
      'column': (column === undefined) ? 'value' : column,
      'interval': (interval === undefined) ? '1m' : interval,
      'function': (apply === undefined) ? 'mean' : apply,
    };
  };

  var targetsGen = function (series, seriesAlias, span, interval, graphConf, aliasConf) {
    var targets = [];
    var aliasColors = {};
    var aliasColor = '';
    var alias = '';
    var column = '';
    var apply = '';
    for (var match in graphConf) {
      var graph = graphConf[match];
      for (var i = 0, len = series.length; i < len; i++) {
        var s = series[i];
        seriesAlias = (seriesAlias) ? seriesAlias : s.split('.')[2];
        if (s.lastIndexOf(match) === s.length - match.length) {
          if ((aliasConf) && ('position' in aliasConf))
            alias = seriesAlias + '.' + s.split('.')[aliasConf.position];
          else if (graph.alias)
            alias = seriesAlias + '.' + graph.alias;
          else
            alias = seriesAlias + '.' + match;

          column = graph.column;
          apply = graph.apply;
          targets.push(targetGen(s, alias, interval, column, apply));
          if (graph.color)
            aliasColor = graph.color;
          else
            aliasColor = '#' + ((1 << 24) * Math.random() | 0).toString(16);

          aliasColors[alias] = aliasColor;
        }
      }
    }
    return {
      'targets': targets,
      'aliasColors': aliasColors,
    };
  };

  var panelFactory = function (gConf) {
    return function (series, seriesAlias, span, interval) {
      span = (span === undefined) ? 12 : span;
      interval = (interval === undefined) ? '1m' : interval;
      var graph = gConf.graph;
      var alias = gConf.alias;
      var targets = targetsGen(series, seriesAlias, span, interval, graph, alias);
      var panel = {
        'title': 'Default Title',
        'type': 'graphite',
        'span': span,
        'y_formats': [ 'none' ],
        'grid': { 'max': null, 'min': 0, 'leftMin': 0 },
        'lines': true,
        'fill': 1,
        'linewidth': 1,
        'nullPointMode': 'null',
        'targets': targets.targets,
        'aliasColors': targets.aliasColors,
      };

      if (('title' in gConf.panel) && (gConf.panel.title.match('@metric')))
        return $.extend({}, panel, gConf.panel,
            { 'title': gConf.panel.title.replace('@metric', series[0].split('.')[2]) });

      return $.extend({}, panel, gConf.panel);
   };
  };

  var setupRow = function (title, panels) {
    return {
      'title': title,
      'height': '250px',
      'panels': panels,
      'grid': { 'max': null, 'min': 0 },
    };
  };

  var getExtendedMetrics = function (series, prefix) {
    var metricsExt = [];
    var postfix = '';
    for (var i = 0, len = series.length; i < len; i++) {
      if (series[i].indexOf(prefix) === 0) {
        postfix = series[i].slice(prefix.length);
        postfix = postfix.slice(0, postfix.indexOf('.'));
        if (metricsExt.indexOf(postfix) === -1)
          metricsExt.push(postfix);
      }
    }
    return metricsExt;
  };

  var setupDash = function (plugin) {
    var p = {
      func: [],
      config: plugin.config,
    };
    for (var name in plugin) {
      p.func.push(panelFactory(plugin[name]));
    }
    return p;
  };

  var genDashs = function (metrics, plugins) {
    var dashs = {};
    if (metrics) {
      var groups = plugins.groups;
      for (var i = 0, mlen = metrics.length; i < mlen; i++) {
        var metric = metrics[i];
        if (metric in plugins) {
          dashs[metric] = setupDash(plugins[metric]);
        } else if (metric in groups) {
          var group = groups[metric];
          for (var j = 0, glen = group.length; j < glen; j++) {
            var member = group[j];
            if (!(member in dashs) && (member in plugins)) {
              dashs[member] = setupDash(plugins[member]);
            }
          }
        }
      }
      return dashs;
    } else {
      for (var plugin in plugins) {
        dashs[plugin] = setupDash(plugins[plugin]);
      }
      return dashs;
    }
  };

  var matchSeries = function (prefix, metric, plugin, series, dash) {
    var matchedSeries = [];
    for (var i = 0, len = series.length; i < len; i++) {
      if ((series[i].indexOf(prefix + metric) === 0) &&
        (!('regexp' in dash[plugin].config) ||
        dash[plugin].config.regexp.test(series[i].split('.')[2]))) {
          matchedSeries.push(series[i]);
      }
    }
    return matchedSeries;
  };

  // AJAX configuration
  $.ajaxSetup({
    async: true,
    cache: false,
  });

  // Get series and panel configuration to perepare dashboard
  $.when(
    $.getJSON(influxdbQueryUrl)
      .done(function (jsonData) {
        var points = jsonData[0].points;
        for (var i = 0, len = points.length; i < len; i++) {
          hostSeries.push(points[i][1]);
        }
      })
      .fail(function () {
        throw new Error('Error loading InfluxDB data JSON from: ' + influxdbQueryUrl);
      }),

    $.getScript(getdashConfig)
      .fail(function () {
        throw new Error('Error loading getdash config from: ' + getdashConfig);
      }),

    $.Deferred(function (deferred) {
      $(deferred.resolve);
    })
  ).done(function () {
    if (hostSeries.length === 0)
      return dashboard;

    var displayMetrics = (displayMetric) ? displayMetric.split(',') : null;
    var showDashs = genDashs(displayMetrics, plugins);

    for (var plugin in showDashs) {
      var metric = plugin;
      var seriesAlias = ('alias' in showDashs[plugin].config) ? showDashs[plugin].config.alias : null;
      var seriesPrefix = showDashs[plugin].config.prefix + displayHost + '.';
      var matchedSeries = [];

      if (showDashs[plugin].config.multi) {
        var metricsExt = getExtendedMetrics(matchSeries(seriesPrefix, metric, plugin, hostSeries, showDashs), seriesPrefix);
        for (var i = 0, mlen = metricsExt.length; i < mlen; i++) {
          matchedSeries.push(matchSeries(seriesPrefix, metricsExt[i], plugin, hostSeries, showDashs));
        }
      } else {
        matchedSeries.push(matchSeries(seriesPrefix, metric, plugin, hostSeries, showDashs));
      }

      for (var j = 0, slen = matchedSeries.length; j < slen; j++) {
        for (var k = 0, flen = showDashs[plugin].func.length; k < flen; k++) {
          var metricFunc = showDashs[plugin].func[k];
          dashboard.rows.push(setupRow(metric.toUpperCase, [metricFunc(matchedSeries[j], seriesAlias, 12, interval)]));
        }
      }
    }

    // Return dashboard
    callback(dashboard);
  });
};
<commit_msg>Minor refactoring.<commit_after>/* global _ */

/*
 * Complex scripted dashboard
 * This script generates a dashboard object that Grafana can load. It also takes a number of user
 * supplied URL parameters (int ARGS variable)
 */

// Accessable variables in this scope
var window, document, ARGS, $, jQuery, moment, kbn;

return function (callback) {
  'use strict';

  // Setup some variables
  var dashboard;
  var hostSeries = [];

  // GET variables
  var displayHost = '';
  var displayMetric = '';
  var displayTime;

  if(!_.isUndefined(ARGS.host))
    displayHost = ARGS.host;

  if(!_.isUndefined(ARGS.metric))
    displayMetric = ARGS.metric;

  if(!_.isUndefined(ARGS.time))
    displayTime = ARGS.time;

  // InfluxDB setup
  var influxUser = 'root';
  var influxPass = 'root';
  var influxDB = 'graphite';
  var influxDBUrl = window.location.protocol + '//' + window.location.host + ':8086';
  var influxdbQueryUrl = influxDBUrl + '/db/' + influxDB + '/series?u=' + influxUser +
                         '&p=' + influxPass + '&q=list series /\.' + displayHost + '\./';

  var getdashConfig = '/app/getdash/getdash.conf.js';

  // Intialize a skeleton with nothing but a rows array and service object
  dashboard = {
    'rows': [],
    'services': {}
  };

  // Set default time
  // time can be overriden in the url using from/to parameteres, but this is
  // handled automatically in grafana core during dashboard initialization

  // Dashboard time and interval setup function
  var getDashTimeInterval = function getDashTimeInterval (time) {
    var defaultTimeInterval = {
      'time': {
        'from': "now-6h",
        'to': "now"
      },
      'interval': '1m',
    };

    if (!time)
      return defaultTimeInterval;

    var timeM = 0;
    var interval = '';
    var regexpTime = /(\d+)(m|h|d)/;
    var rTime = regexpTime.exec(time);

    if (!rTime)
      return defaultTimeInterval;

    if (rTime[2] === 'm')
      timeM = parseInt(rTime[1]);
    else if (rTime[2] === 'h')
      timeM = parseInt(rTime[1]) * 60;
    else if (rTime[2] === 'd')
      timeM = parseInt(rTime[1]) * 60 * 24;

    if (timeM > 360)
      interval = (Math.ceil((Math.floor(timeM / 360) + 1) / 5) * 5).toString() + 'm';
    else if (timeM === 360)
      interval = '1m';
    else
      interval = '30s';

    return {
      'time': {
        'from': "now-" + time,
        'to': "now"
      },
      'interval': interval,
    };
  };

  var dashTimeInterval = getDashTimeInterval(displayTime);
  var interval = dashTimeInterval.interval;
  dashboard.time = dashTimeInterval.time;

  // Set a title
  dashboard.title = 'Scripted Dashboard for ' + displayHost;

  // Object prototypes
  var targetProto = {
    'series': '',
    'alias': '',
    'column': 'value',
    'interval': '1m',
    'function': 'mean',
  };

  var panelProto = {
    'title': 'Default Title',
    'type': 'graphite',
    'span': 12,
    'y_formats': [ 'none' ],
    'grid': { 'max': null, 'min': 0, 'leftMin': 0 },
    'lines': true,
    'fill': 1,
    'linewidth': 1,
    'nullPointMode': 'null',
    'targets': {},
    'aliasColors': {},
  };

  var rowProto = {
    'title': 'Default Row Title',
    'height': '250px',
    'panels': [],
  };

  // Dashboard setup helper functions
  var setupTarget = function setupTarget (target) {
    return $.extend({}, targetProto, target);
  };

  var genRandomColor = function genRandomColor () {
    return '#' + ((1 << 24) * Math.random() | 0).toString(16);
  };

  var genTargets = function genTargets (seriesArr, seriesAlias, interval, pluginConf) {
    var targets = [];
    var aliasColors = {};
    var alias = '';
    for (var match in pluginConf.graph) {
      var graph = pluginConf.graph[match];
      for (var i = 0, len = seriesArr.length; i < len; i++) {
        var series = seriesArr[i];
        seriesAlias = (seriesAlias) ? seriesAlias : series.split('.')[2];

        if (series.lastIndexOf(match) !== series.length - match.length)
          continue;

        if ((pluginConf.alias) && ('position' in pluginConf.alias))
          alias = seriesAlias + '.' + series.split('.')[pluginConf.alias.position];
        else if (graph.alias)
          alias = seriesAlias + '.' + graph.alias;
        else
          alias = seriesAlias + '.' + match;

        targets.push(setupTarget({
          'series': series,
          'alias': alias,
          'interval': interval,
          'column': graph.column,
          'apply': graph.apply,
        }));

        if (graph.color)
          aliasColors[alias] = graph.color;
        else
          aliasColors[alias] = genRandomColor();
      }
    }
    return {
      'targets': targets,
      'aliasColors': aliasColors,
    };
  };

  var panelFactory = function panelFactory (pluginConf) {
    return function (series, seriesAlias, span, interval) {
      interval = (interval === undefined) ? '1m' : interval;
      var targets = genTargets(series, seriesAlias, interval, pluginConf);
      var panel = {
        'span': span,
        'targets': targets.targets,
        'aliasColors': targets.aliasColors,
      };

      if (('title' in pluginConf.panel) && (pluginConf.panel.title.match('@metric')))
        return $.extend({}, panelProto, panel, pluginConf.panel,
            { 'title': pluginConf.panel.title.replace('@metric', series[0].split('.')[2]) });

      return $.extend({}, panelProto, panel, pluginConf.panel);
   };
  };

  var setupRow = function setupRow (row) {
    return $.extend({}, rowProto, row);
  };

  var getExtendedMetrics = function getExtendedMetrics (series, prefix) {
    var metricsExt = [];
    var postfix = '';
    for (var i = 0, len = series.length; i < len; i++) {
      if (series[i].indexOf(prefix) === 0) {
        postfix = series[i].slice(prefix.length);
        postfix = postfix.slice(0, postfix.indexOf('.'));
        if (metricsExt.indexOf(postfix) === -1)
          metricsExt.push(postfix);
      }
    }
    return metricsExt;
  };

  var setupDash = function setupDash (plugin) {
    var p = {
      func: [],
      config: plugin.config,
    };
    for (var name in plugin) {
      p.func.push(panelFactory(plugin[name]));
    }
    return p;
  };

  var genDashs = function genDashs (metrics, plugins) {
    var dashs = {};
    if (metrics) {
      var groups = plugins.groups;
      for (var i = 0, mlen = metrics.length; i < mlen; i++) {
        var metric = metrics[i];
        if (metric in plugins) {
          dashs[metric] = setupDash(plugins[metric]);
        } else if (metric in groups) {
          var group = groups[metric];
          for (var j = 0, glen = group.length; j < glen; j++) {
            var member = group[j];
            if (!(member in dashs) && (member in plugins)) {
              dashs[member] = setupDash(plugins[member]);
            }
          }
        }
      }
      return dashs;
    } else {
      for (var plugin in plugins) {
        dashs[plugin] = setupDash(plugins[plugin]);
      }
      return dashs;
    }
  };

  var matchSeries = function matchSeries (prefix, metric, plugin, series, dash) {
    var matchedSeries = [];
    for (var i = 0, len = series.length; i < len; i++) {
      if ((series[i].indexOf(prefix + metric) === 0) &&
        (!('regexp' in dash[plugin].config) ||
        dash[plugin].config.regexp.test(series[i].split('.')[2]))) {
          matchedSeries.push(series[i]);
      }
    }
    return matchedSeries;
  };

  // AJAX configuration
  $.ajaxSetup({
    async: true,
    cache: false,
  });

  // Get series and panel configuration to perepare dashboard
  $.when(
    $.getJSON(influxdbQueryUrl)
      .done(function (jsonData) {
        var points = jsonData[0].points;
        for (var i = 0, len = points.length; i < len; i++) {
          hostSeries.push(points[i][1]);
        }
      })
      .fail(function () {
        throw new Error('Error loading InfluxDB data JSON from: ' + influxdbQueryUrl);
      }),

    $.getScript(getdashConfig)
      .fail(function () {
        throw new Error('Error loading getdash config from: ' + getdashConfig);
      }),

    $.Deferred(function (deferred) {
      $(deferred.resolve);
    })
  ).done(function () {
    if (hostSeries.length === 0)
      return dashboard;

    var displayMetrics = (displayMetric) ? displayMetric.split(',') : null;
    var showDashs = genDashs(displayMetrics, plugins);

    for (var plugin in showDashs) {
      var metric = plugin;
      var seriesAlias = ('alias' in showDashs[plugin].config) ? showDashs[plugin].config.alias : null;
      var seriesPrefix = showDashs[plugin].config.prefix + displayHost + '.';
      var matchedSeries = [];

      if (showDashs[plugin].config.multi) {
        var metricsExt = getExtendedMetrics(matchSeries(seriesPrefix, metric, plugin, hostSeries, showDashs), seriesPrefix);
        for (var i = 0, mlen = metricsExt.length; i < mlen; i++) {
          matchedSeries.push(matchSeries(seriesPrefix, metricsExt[i], plugin, hostSeries, showDashs));
        }
      } else {
        matchedSeries.push(matchSeries(seriesPrefix, metric, plugin, hostSeries, showDashs));
      }

      for (var j = 0, slen = matchedSeries.length; j < slen; j++) {
        for (var k = 0, flen = showDashs[plugin].func.length; k < flen; k++) {
          var metricFunc = showDashs[plugin].func[k];
          dashboard.rows.push(setupRow({
            'title': metric.toUpperCase,
            'panels': [ metricFunc(matchedSeries[j], seriesAlias, 12, interval) ],
          }));
        }
      }
    }

    // Return dashboard
    callback(dashboard);
  });
};
<|endoftext|>


<commit_before>import Immutable from 'immutable'

import Model from '../../models/ModelInfo'
import Context, {
    ParameterContainer,
    Parameter,
    Body,
    Response
} from '../../models/Core'
import { Info, License, Contact } from '../../models/Utils'
import Group from '../../models/Group'
import Request from '../../models/Request'
import URL from '../../models/URL'
import Auth from '../../models/Auth'
import Constraint from '../../models/Constraint'

import ReferenceContainer from '../../models/references/Container'
import ReferenceCache from '../../models/references/Cache'
import Reference from '../../models/references/Reference'
import ExoticReference from '../../models/references/Exotic'
import JSONSchemaReference from '../../models/references/JSONSchema'
import LateResolutionReference from '../../models/references/LateResolution'

export default class InternalParser {
    static format = '__internal__'
    static version = 'v0.1.0'

    static detect(content) {
        let detection = {
            format: InternalParser.format,
            version: InternalParser.version,
            score: 0
        }

        let internal
        try {
            internal = JSON.parse(content)
        }
        catch (jsonParseError) {
            return [ detection ]
        }
        if (typeof internal === 'object') {
            let score = 0
            /* eslint-disable no-extra-paren */
            score += internal._model ? 1 / 2 : 0
            score += (internal._model || {}).version === '0.1.0' ? 1 / 2 : 0
            score = score < 1 ? score : 1
            detection.score = score
            return [ detection ]
            /* eslint-enable no-extra-paren */
        }
        return [ detection ]
    }

    static getAPIName(content) {
        let internal
        try {
            internal = JSON.parse(content)
        }
        catch (jsonParseError) {
            return null
        }

        return ((internal || {}).info || {}).title || null
    }

    constructor() {
        this.classMap = {
            'context.core.models': ::this._extractContext,
            'info.utils.models': ::this._extractInfo,
            'license.utils.models': ::this._extractLicense,
            'contact.utils.models': ::this._extractContact,
            'group.models': ::this._extractGroup,
            'request.models': ::this._extractRequest,
            'url.models': ::this._extractURL,
            'parameter-container.core.models':
                ::this._extractParameterContainer,
            'parameter.core.models': ::this._extractParameter,
            'basic.auth.models': ::this._extractBasicAuth,
            'digest.auth.models': ::this._extractDigestAuth,
            'ntlm.auth.models': ::this._extractNTLMAuth,
            'negotiate.auth.models': ::this._extractNegotiateAuth,
            'api-key.auth.models': ::this._extractApiKeyAuth,
            'oauth-1.auth.models': ::this._extractOAuth1Auth,
            'oauth-2.auth.models': ::this._extractOAuth2Auth,
            'aws-sig-4.auth.models': ::this._extractAWSSig4Auth,
            'hawk.auth.models': ::this._extractHawkAuth,
            'body.core.models': ::this._extractBody,
            'response.core.models': ::this._extractResponse,
            'constraint.constraint.models': ::this._extractConstraint,
            'multiple-of.constraint.models':
                ::this._extractMultipleOfConstraint,
            'maximum.constraint.models': ::this._extractMaximumConstraint,
            'exclusive-maximum.constraint.models':
                ::this._extractExclusiveMaximumConstraint,
            'minimum.constraint.models': ::this._extractMinimumConstraint,
            'exclusive-minimum.constraint.models':
                ::this._extractExclusiveMinimumConstraint,
            'maximum-length.constraint.models':
                ::this._extractMaximumLengthConstraint,
            'minimum-length.constraint.models':
                ::this._extractMinimumLengthConstraint,
            'pattern.constraint.models': ::this._extractPatternConstraint,
            'maximum-items.constraint.models':
                ::this._extractMaximumItemsConstraint,
            'minimum-items.constraint.models':
                ::this._extractMinimumItemsConstraint,
            'unique-items.constraint.models':
                ::this._extractUniqueItemsConstraint,
            'maximum-properties.constraint.models':
                ::this._extractMaximumPropertiesConstraint,
            'minimum-properties.constraint.models':
                ::this._extractMinimumPropertiesConstraint,
            'enum.constraint.models': ::this._extractEnumConstraint,
            'reference-container.references.models':
                ::this._extractReferenceContainer,
            'reference-cache.references.models':
                ::this._extractReferenceCache,
            'exotic.references.models': ::this._extractExoticReference,
            'json-schema.references.models': ::this._extractJSONSchemaReference,
            'late-resolution.references.models':
                ::this._extractLateResolutionReference,
            'reference.references.models': ::this._extractReference
        }
    }

    detect() {
        return this.constructor.detect(...arguments)
    }

    getAPIName() {
        return InternalParser.getAPIName(...arguments)
    }

    // @tested
    parse(item) {
        let obj
        try {
            obj = JSON.parse(item.content)
        }
        catch (e) {
            throw new Error('Invalid Internal file (not a valid JSON)')
        }

        let context = this._extract(obj)

        return context
    }

    _extract(obj) {
        const classMap = this.classMap

        if (obj && obj._model && classMap[obj._model.name]) {
            obj._model = new Model(obj._model)
            return classMap[obj._model.name](obj)
        }

        return obj
    }

    _extractContext(obj) {
        let references = {}

        if (obj.references) {
            let refs = Object.keys(obj.references || {})
            for (let ref of refs) {
                references[ref] = this._extract(obj.references[ref])
            }
        }

        const context = new Context({
            group: this._extract(obj.group),
            references: new Immutable.OrderedMap(references),
            info: this._extract(obj.info)
        })
        return context
    }

    _extractInfo(_obj) {
        let obj = _obj
        obj.contact = this._extract(obj.contact)
        obj.license = this._extract(obj.license)

        const info = new Info(obj)
        return info
    }

    _extractLicense(obj) {
        return new License(obj)
    }

    _extractContact(obj) {
        return new Contact(obj)
    }

    _extractGroup(obj) {
        let children = {}

        if (obj.children) {
            let refs = Object.keys(obj.children || {})
            for (let ref of refs) {
                children[ref] = this._extract(obj.children[ref])
            }
        }

        const group = new Group({
            id: obj.id,
            name: obj.name,
            children: new Immutable.OrderedMap(children)
        })

        return group
    }

    _extractRequest(_obj) {
        let obj = _obj
        obj.url = this._extract(obj.url)
        obj.parameters = this._extract(obj.parameters)

        if (obj.bodies) {
            obj.bodies = new Immutable.List(obj.bodies.map(body => {
                return this._extract(body)
            }))
        }

        if (obj.auths) {
            obj.auths = new Immutable.List(obj.auths.map(auth => {
                return this._extract(auth)
            }))
        }

        if (obj.responses) {
            obj.responses = new Immutable.List(obj.responses.map(res => {
                return this._extract(res)
            }))
        }

        if (obj.tags) {
            obj.tags = new Immutable.List(obj.tags)
        }

        const request = new Request(obj)
        return request
    }

    _extractURL(_obj) {
        let obj = _obj

        let keys = Object.keys(obj)
        for (let key of keys) {
            obj[key] = this._extract(obj[key])
        }

        let url = new URL(obj)
        return url
    }

    _extractParameterContainer(_obj) {
        let obj = _obj

        if (obj.headers) {
            obj.headers = new Immutable.List(obj.headers.map(header => {
                return this._extract(header)
            }))
        }

        if (obj.queries) {
            obj.queries = new Immutable.List(obj.queries.map(query => {
                return this._extract(query)
            }))
        }

        if (obj.body) {
            obj.body = new Immutable.List(obj.body.map(body => {
                return this._extract(body)
            }))
        }

        if (obj.path) {
            obj.path = new Immutable.List(obj.path.map(path => {
                return this._extract(path)
            }))
        }

        let container = new ParameterContainer(obj)
        return container
    }

    _extractParameter(_obj) {
        let obj = _obj
        if (Object.prototype.toString.call(obj.value) === '[object Array]') {
            obj.value = new Immutable.List(obj.value.map(value => {
                return this._extract(value)
            }))
        }
        else {
            obj.value = this._extract(obj.value)
        }

        if (obj.internals) {
            obj.internals = new Immutable.List(obj.internals.map(internal => {
                const _internal = this._extract(internal)
                return _internal
            }))
        }

        if (obj.externals) {
            obj.externals = new Immutable.List(obj.externals.map(external => {
                return this._extract(external)
            }))
        }

        return new Parameter(obj)
    }

    _extractBasicAuth(obj) {
        return new Auth.Basic(obj)
    }

    _extractDigestAuth(obj) {
        return new Auth.Digest(obj)
    }

    _extractNTLMAuth(obj) {
        return new Auth.NTLM(obj)
    }

    _extractNegotiateAuth(obj) {
        return new Auth.Negotiate(obj)
    }

    _extractApiKeyAuth(obj) {
        return new Auth.ApiKey(obj)
    }

    _extractOAuth1Auth(obj) {
        return new Auth.OAuth1(obj)
    }

    _extractOAuth2Auth(_obj) {
        let obj = _obj

        if (obj.scopes) {
            obj.scopes = new Immutable.List(obj.scopes)
        }

        return new Auth.OAuth2(obj)
    }

    _extractAWSSig4Auth(obj) {
        return new Auth.AWSSig4Auth(obj)
    }

    _extractHawkAuth(obj) {
        return new Auth.Hawk(obj)
    }

    _extractBody(_obj) {
        let obj = _obj
        if (obj.constraints) {
            obj.constraints = new Immutable.List(obj.constraints.map(constr => {
                return this._extract(constr)
            }))
        }

        return new Body(obj)
    }

    _extractResponse(_obj) {
        let obj = _obj
        if (obj.parameters) {
            obj.parameters = this._extract(obj.parameters)
        }

        if (obj.bodies) {
            obj.bodies = new Immutable.List(obj.bodies.map(body => {
                return this._extract(body)
            }))
        }

        return new Response(obj)
    }

    _extractConstraint(obj) {
        return new Constraint.Constraint(obj)
    }

    _extractMultipleOfConstraint(obj) {
        return new Constraint.MultipleOf(obj.value)
    }

    _extractMaximumConstraint(obj) {
        return new Constraint.Maximum(obj.value)
    }

    _extractExclusiveMaximumConstraint(obj) {
        return new Constraint.ExclusiveMaximum(obj.value)
    }

    _extractMinimumConstraint(obj) {
        return new Constraint.Minimum(obj.value)
    }

    _extractExclusiveMinimumConstraint(obj) {
        return new Constraint.ExclusiveMinimum(obj.value)
    }

    _extractMaximumLengthConstraint(obj) {
        return new Constraint.MaximumLength(obj.value)
    }

    _extractMinimumLengthConstraint(obj) {
        return new Constraint.MinimumLength(obj.value)
    }

    _extractPatternConstraint(obj) {
        return new Constraint.Pattern(obj.value)
    }

    _extractMaximumItemsConstraint(obj) {
        return new Constraint.MaximumItems(obj.value)
    }

    _extractMinimumItemsConstraint(obj) {
        return new Constraint.MinimumItems(obj.value)
    }

    _extractUniqueItemsConstraint(obj) {
        return new Constraint.UniqueItems(obj.value)
    }

    _extractMaximumPropertiesConstraint(obj) {
        return new Constraint.MaximumProperties(obj.value)
    }

    _extractMinimumPropertiesConstraint(obj) {
        return new Constraint.MinimumProperties(obj.value)
    }

    _extractEnumConstraint(obj) {
        return new Constraint.Enum(obj.value)
    }

    _extractReferenceContainer(_obj) {
        let obj = _obj

        const cache = {}
        if (obj.cache) {
            let keys = Object.keys(obj.cache)
            for (let key of keys) {
                cache[key] = this._extract(obj.cache[key])
            }
        }
        obj.cache = new Immutable.OrderedMap(cache)

        return new ReferenceContainer(obj)
    }

    _extractReferenceCache(_obj) {
        let obj = _obj

        const resolved = {}
        if (obj.resolved) {
            let keys = Object.keys(obj.resolved)
            for (let key of keys) {
                resolved[key] = this._extract(obj.resolved[key])
            }
        }

        if (obj.cached) {
            obj.cached = this._extract(obj.cached)
        }

        return new ReferenceCache(obj)
    }

    _extractReference(_obj) {
        let obj = _obj
        if (obj.dependencies) {
            obj.dependencies = new Immutable.List(obj.dependencies)
        }

        return new Reference(obj)
    }

    _extractExoticReference(_obj) {
        let obj = _obj
        if (obj.dependencies) {
            obj.dependencies = new Immutable.List(obj.dependencies)
        }
        return new ExoticReference(obj)
    }

    _extractJSONSchemaReference(_obj) {
        let obj = _obj
        if (obj.dependencies) {
            obj.dependencies = new Immutable.List(obj.dependencies)
        }
        return new JSONSchemaReference(obj)
    }

    _extractLateResolutionReference(_obj) {
        let obj = _obj
        if (obj.dependencies) {
            obj.dependencies = new Immutable.List(obj.dependencies)
        }

        return new LateResolutionReference(obj)
    }
}
<commit_msg>updated internal parser to match new context model<commit_after>import Immutable from 'immutable'

import Model from '../../models/ModelInfo'
import Context, {
    ParameterContainer,
    Parameter,
    Body,
    Response
} from '../../models/Core'
import { Info, License, Contact } from '../../models/Utils'
import Group from '../../models/Group'
import Request from '../../models/Request'
import URL from '../../models/URL'
import Auth from '../../models/Auth'
import Constraint from '../../models/Constraint'

import ReferenceContainer from '../../models/references/Container'
import ReferenceCache from '../../models/references/Cache'
import Reference from '../../models/references/Reference'
import ExoticReference from '../../models/references/Exotic'
import JSONSchemaReference from '../../models/references/JSONSchema'
import LateResolutionReference from '../../models/references/LateResolution'

export default class InternalParser {
    static format = '__internal__'
    static version = 'v0.1.0'

    static detect(content) {
        let detection = {
            format: InternalParser.format,
            version: InternalParser.version,
            score: 0
        }

        let internal
        try {
            internal = JSON.parse(content)
        }
        catch (jsonParseError) {
            return [ detection ]
        }
        if (typeof internal === 'object') {
            let score = 0
            /* eslint-disable no-extra-paren */
            score += internal._model ? 1 / 2 : 0
            score += (internal._model || {}).version === '0.1.0' ? 1 / 2 : 0
            score = score < 1 ? score : 1
            detection.score = score
            return [ detection ]
            /* eslint-enable no-extra-paren */
        }
        return [ detection ]
    }

    static getAPIName(content) {
        let internal
        try {
            internal = JSON.parse(content)
        }
        catch (jsonParseError) {
            return null
        }

        return ((internal || {}).info || {}).title || null
    }

    constructor() {
        this.classMap = {
            'context.core.models': ::this._extractContext,
            'info.utils.models': ::this._extractInfo,
            'license.utils.models': ::this._extractLicense,
            'contact.utils.models': ::this._extractContact,
            'group.models': ::this._extractGroup,
            'request.models': ::this._extractRequest,
            'url.models': ::this._extractURL,
            'parameter-container.core.models':
                ::this._extractParameterContainer,
            'parameter.core.models': ::this._extractParameter,
            'basic.auth.models': ::this._extractBasicAuth,
            'digest.auth.models': ::this._extractDigestAuth,
            'ntlm.auth.models': ::this._extractNTLMAuth,
            'negotiate.auth.models': ::this._extractNegotiateAuth,
            'api-key.auth.models': ::this._extractApiKeyAuth,
            'oauth-1.auth.models': ::this._extractOAuth1Auth,
            'oauth-2.auth.models': ::this._extractOAuth2Auth,
            'aws-sig-4.auth.models': ::this._extractAWSSig4Auth,
            'hawk.auth.models': ::this._extractHawkAuth,
            'body.core.models': ::this._extractBody,
            'response.core.models': ::this._extractResponse,
            'constraint.constraint.models': ::this._extractConstraint,
            'multiple-of.constraint.models':
                ::this._extractMultipleOfConstraint,
            'maximum.constraint.models': ::this._extractMaximumConstraint,
            'exclusive-maximum.constraint.models':
                ::this._extractExclusiveMaximumConstraint,
            'minimum.constraint.models': ::this._extractMinimumConstraint,
            'exclusive-minimum.constraint.models':
                ::this._extractExclusiveMinimumConstraint,
            'maximum-length.constraint.models':
                ::this._extractMaximumLengthConstraint,
            'minimum-length.constraint.models':
                ::this._extractMinimumLengthConstraint,
            'pattern.constraint.models': ::this._extractPatternConstraint,
            'maximum-items.constraint.models':
                ::this._extractMaximumItemsConstraint,
            'minimum-items.constraint.models':
                ::this._extractMinimumItemsConstraint,
            'unique-items.constraint.models':
                ::this._extractUniqueItemsConstraint,
            'maximum-properties.constraint.models':
                ::this._extractMaximumPropertiesConstraint,
            'minimum-properties.constraint.models':
                ::this._extractMinimumPropertiesConstraint,
            'enum.constraint.models': ::this._extractEnumConstraint,
            'reference-container.references.models':
                ::this._extractReferenceContainer,
            'reference-cache.references.models':
                ::this._extractReferenceCache,
            'exotic.references.models': ::this._extractExoticReference,
            'json-schema.references.models': ::this._extractJSONSchemaReference,
            'late-resolution.references.models':
                ::this._extractLateResolutionReference,
            'reference.references.models': ::this._extractReference
        }
    }

    detect() {
        return this.constructor.detect(...arguments)
    }

    getAPIName() {
        return InternalParser.getAPIName(...arguments)
    }

    // @tested
    parse(item) {
        let obj
        try {
            obj = JSON.parse(item.content)
        }
        catch (e) {
            throw new Error('Invalid Internal file (not a valid JSON)')
        }

        let context = this._extract(obj)

        return context
    }

    _extract(obj) {
        const classMap = this.classMap

        if (obj && obj._model && classMap[obj._model.name]) {
            obj._model = new Model(obj._model)
            return classMap[obj._model.name](obj)
        }

        return obj
    }

    _extractContext(obj) {
        let references = {}
        let requests = {}

        if (obj.references) {
            let refs = Object.keys(obj.references || {})
            for (let ref of refs) {
                references[ref] = this._extract(obj.references[ref])
            }
        }

        if (obj.requests) {
            let reqs = Object.keys(obj.requests || {})
            for (let req of reqs) {
                requests[req] = this._extract(obj.requests[req])
            }
        }

        const context = new Context({
            requests: new Immutable.OrderedMap(requests),
            group: this._extract(obj.group),
            references: new Immutable.OrderedMap(references),
            info: this._extract(obj.info)
        })
        return context
    }

    _extractInfo(_obj) {
        let obj = _obj
        obj.contact = this._extract(obj.contact)
        obj.license = this._extract(obj.license)

        const info = new Info(obj)
        return info
    }

    _extractLicense(obj) {
        return new License(obj)
    }

    _extractContact(obj) {
        return new Contact(obj)
    }

    _extractGroup(obj) {
        let children = {}

        if (obj.children) {
            let refs = Object.keys(obj.children || {})
            for (let ref of refs) {
                children[ref] = this._extract(obj.children[ref])
            }
        }

        const group = new Group({
            id: obj.id,
            name: obj.name,
            children: new Immutable.OrderedMap(children)
        })

        return group
    }

    _extractRequest(_obj) {
        let obj = _obj
        obj.url = this._extract(obj.url)
        obj.parameters = this._extract(obj.parameters)

        if (obj.bodies) {
            obj.bodies = new Immutable.List(obj.bodies.map(body => {
                return this._extract(body)
            }))
        }

        if (obj.auths) {
            obj.auths = new Immutable.List(obj.auths.map(auth => {
                return this._extract(auth)
            }))
        }

        if (obj.responses) {
            obj.responses = new Immutable.List(obj.responses.map(res => {
                return this._extract(res)
            }))
        }

        if (obj.tags) {
            obj.tags = new Immutable.List(obj.tags)
        }

        const request = new Request(obj)
        return request
    }

    _extractURL(_obj) {
        let obj = _obj

        let keys = Object.keys(obj)
        for (let key of keys) {
            obj[key] = this._extract(obj[key])
        }

        let url = new URL(obj)
        return url
    }

    _extractParameterContainer(_obj) {
        let obj = _obj

        if (obj.headers) {
            obj.headers = new Immutable.List(obj.headers.map(header => {
                return this._extract(header)
            }))
        }

        if (obj.queries) {
            obj.queries = new Immutable.List(obj.queries.map(query => {
                return this._extract(query)
            }))
        }

        if (obj.body) {
            obj.body = new Immutable.List(obj.body.map(body => {
                return this._extract(body)
            }))
        }

        if (obj.path) {
            obj.path = new Immutable.List(obj.path.map(path => {
                return this._extract(path)
            }))
        }

        let container = new ParameterContainer(obj)
        return container
    }

    _extractParameter(_obj) {
        let obj = _obj
        if (Object.prototype.toString.call(obj.value) === '[object Array]') {
            obj.value = new Immutable.List(obj.value.map(value => {
                return this._extract(value)
            }))
        }
        else {
            obj.value = this._extract(obj.value)
        }

        if (obj.internals) {
            obj.internals = new Immutable.List(obj.internals.map(internal => {
                const _internal = this._extract(internal)
                return _internal
            }))
        }

        if (obj.externals) {
            obj.externals = new Immutable.List(obj.externals.map(external => {
                return this._extract(external)
            }))
        }

        return new Parameter(obj)
    }

    _extractBasicAuth(obj) {
        return new Auth.Basic(obj)
    }

    _extractDigestAuth(obj) {
        return new Auth.Digest(obj)
    }

    _extractNTLMAuth(obj) {
        return new Auth.NTLM(obj)
    }

    _extractNegotiateAuth(obj) {
        return new Auth.Negotiate(obj)
    }

    _extractApiKeyAuth(obj) {
        return new Auth.ApiKey(obj)
    }

    _extractOAuth1Auth(obj) {
        return new Auth.OAuth1(obj)
    }

    _extractOAuth2Auth(_obj) {
        let obj = _obj

        if (obj.scopes) {
            obj.scopes = new Immutable.List(obj.scopes)
        }

        return new Auth.OAuth2(obj)
    }

    _extractAWSSig4Auth(obj) {
        return new Auth.AWSSig4Auth(obj)
    }

    _extractHawkAuth(obj) {
        return new Auth.Hawk(obj)
    }

    _extractBody(_obj) {
        let obj = _obj
        if (obj.constraints) {
            obj.constraints = new Immutable.List(obj.constraints.map(constr => {
                return this._extract(constr)
            }))
        }

        return new Body(obj)
    }

    _extractResponse(_obj) {
        let obj = _obj
        if (obj.parameters) {
            obj.parameters = this._extract(obj.parameters)
        }

        if (obj.bodies) {
            obj.bodies = new Immutable.List(obj.bodies.map(body => {
                return this._extract(body)
            }))
        }

        return new Response(obj)
    }

    _extractConstraint(obj) {
        return new Constraint.Constraint(obj)
    }

    _extractMultipleOfConstraint(obj) {
        return new Constraint.MultipleOf(obj.value)
    }

    _extractMaximumConstraint(obj) {
        return new Constraint.Maximum(obj.value)
    }

    _extractExclusiveMaximumConstraint(obj) {
        return new Constraint.ExclusiveMaximum(obj.value)
    }

    _extractMinimumConstraint(obj) {
        return new Constraint.Minimum(obj.value)
    }

    _extractExclusiveMinimumConstraint(obj) {
        return new Constraint.ExclusiveMinimum(obj.value)
    }

    _extractMaximumLengthConstraint(obj) {
        return new Constraint.MaximumLength(obj.value)
    }

    _extractMinimumLengthConstraint(obj) {
        return new Constraint.MinimumLength(obj.value)
    }

    _extractPatternConstraint(obj) {
        return new Constraint.Pattern(obj.value)
    }

    _extractMaximumItemsConstraint(obj) {
        return new Constraint.MaximumItems(obj.value)
    }

    _extractMinimumItemsConstraint(obj) {
        return new Constraint.MinimumItems(obj.value)
    }

    _extractUniqueItemsConstraint(obj) {
        return new Constraint.UniqueItems(obj.value)
    }

    _extractMaximumPropertiesConstraint(obj) {
        return new Constraint.MaximumProperties(obj.value)
    }

    _extractMinimumPropertiesConstraint(obj) {
        return new Constraint.MinimumProperties(obj.value)
    }

    _extractEnumConstraint(obj) {
        return new Constraint.Enum(obj.value)
    }

    _extractReferenceContainer(_obj) {
        let obj = _obj

        const cache = {}
        if (obj.cache) {
            let keys = Object.keys(obj.cache)
            for (let key of keys) {
                cache[key] = this._extract(obj.cache[key])
            }
        }
        obj.cache = new Immutable.OrderedMap(cache)

        return new ReferenceContainer(obj)
    }

    _extractReferenceCache(_obj) {
        let obj = _obj

        const resolved = {}
        if (obj.resolved) {
            let keys = Object.keys(obj.resolved)
            for (let key of keys) {
                resolved[key] = this._extract(obj.resolved[key])
            }
        }

        if (obj.cached) {
            obj.cached = this._extract(obj.cached)
        }

        return new ReferenceCache(obj)
    }

    _extractReference(_obj) {
        let obj = _obj
        if (obj.dependencies) {
            obj.dependencies = new Immutable.List(obj.dependencies)
        }

        return new Reference(obj)
    }

    _extractExoticReference(_obj) {
        let obj = _obj
        if (obj.dependencies) {
            obj.dependencies = new Immutable.List(obj.dependencies)
        }
        return new ExoticReference(obj)
    }

    _extractJSONSchemaReference(_obj) {
        let obj = _obj
        if (obj.dependencies) {
            obj.dependencies = new Immutable.List(obj.dependencies)
        }
        return new JSONSchemaReference(obj)
    }

    _extractLateResolutionReference(_obj) {
        let obj = _obj
        if (obj.dependencies) {
            obj.dependencies = new Immutable.List(obj.dependencies)
        }

        return new LateResolutionReference(obj)
    }
}
<|endoftext|>