<commit_before>import React, { Component } from 'react';

// import TabContainer from './TabContainer';
// import DropdownContainer from './DropdownContainer';
import './App.css';

class App extends Component {
  render() {
    return (
      //

      //

      //     <TabContainer />
      //     <DropdownContainer />
      //

        <PopoverContainer
          id="1"
          content="If only Bradley's arm was longer. Best photo ever. #oscars pic.twitter.com/C9U5NOtGap"
          buttonMarginTop={30}
          buttonMarginLeft={20}
          direction="RIGHT"
        />
        <PopoverContainer
          id="2"
          content="To all the little girls watching...never doubt that you are valuable and powerful & deserving of every chance & opportunity in the world."
          buttonMarginTop={130}
          buttonMarginLeft={120}
          direction="RIGHT"
        />
        {/* <PopoverContainer buttonPosLeft={300} direction="LEFT" /> */}

      //

    );
  }
}

class PopoverContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      popVisible: false,
      buttonWidth: null,
      buttonHeight: null
    };
  }

  componentDidMount() {
    let btnEle = document.getElementById('pop-btn');
    let position = btnEle.getBoundingClientRect();

    this.setState({
      buttonWidth: position.width,
      buttonHeight: position.height
    });
  }

  render() {
    const popContainerStyle = {
      margin: '50px',
      position: 'relative'
    };

    const triggerStyle = {
      zIndex: '1',
      marginTop: this.props.buttonMarginTop,
      marginLeft: this.props.buttonMarginLeft
    };

    return (

        <button
          id="pop-btn"
          onClick={() => this.setState({ popVisible: !this.state.popVisible })}
          style={triggerStyle}
        >
          Popover on {this.props.direction}
        </button>
        <PopoverContent
          id={this.props.id}
          direction={this.props.direction}
          buttonMarginLeft={this.props.buttonMarginLeft}
          buttonMarginTop={this.props.buttonMarginTop}
          buttonWidth={this.state.buttonWidth}
          buttonHeight={this.state.buttonHeight}
          contentHeight={this.state.contentHeight}
          content={this.props.content}
          popVisible={this.state.popVisible}
        />

    );
  }
}

class PopoverContent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      contentHeight: 0
    };
  }
  componentWillUpdate() {
    let contentEle = document.getElementById(this.props.id);
    let contentPos = contentEle.getBoundingClientRect();
    if (this.props.popVisible) {
      this.setState({
        contentHeight: contentPos.height
      });
    }
  }
  render() {
    console.log('contentHeight', this.state.contentHeight);
    let top = null;
    let left = null;
    switch (this.props.direction) {
      case 'RIGHT':
        top =
          this.props.buttonMarginTop -
          (this.state.contentHeight - this.props.buttonHeight) / 2;
        left = this.props.buttonWidth + this.props.buttonMarginLeft + 10;
        break;
      // case 'LEFT':
      //   top = this.props.positionTop - 110;
      //   left = this.props.positionLeft - 10;
      //   break;
      default:
        break;
    }

    const infoStyle = {
      position: 'absolute',
      width: '200px',
      top: top,
      left: left,
      border: '1px solid rgba(0, 0, 0, 0.2)',
      padding: '10px 10px',
      zIndex: '100',
      background: '#fff',
      borderRadius: '4px'
    };
    if (this.props.popVisible)
      return (

          {this.props.content}

      );
    else return
;
  }
}
export default App;
<commit_msg>container spacing fixed<commit_after>import React, { Component } from 'react';

// import TabContainer from './TabContainer';
// import DropdownContainer from './DropdownContainer';
import './App.css';

class App extends Component {
  render() {
    return (
      //

      //

      //     <TabContainer />
      //     <DropdownContainer />
      //

        <PopoverContainer
          id="1"
          content="If only Bradley's arm was longer. Best photo ever. #oscars pic.twitter.com/C9U5NOtGap"
          buttonMarginTop={100}
          buttonMarginLeft={20}
          direction="RIGHT"
        />
        <PopoverContainer
          id="2"
          content="To all the little girls watching...never doubt that you are valuable and powerful & deserving of every chance & opportunity in the world."
          buttonMarginTop={50}
          buttonMarginLeft={10}
          direction="RIGHT"
        />
        {/* <PopoverContainer buttonPosLeft={300} direction="LEFT" /> */}

      //

    );
  }
}

class PopoverContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      popVisible: false,
      buttonWidth: null,
      buttonHeight: null
    };
  }

  componentDidMount() {
    let btnEle = document.getElementById('pop-btn');
    let position = btnEle.getBoundingClientRect();

    this.setState({
      buttonWidth: position.width,
      buttonHeight: position.height
    });
  }

  render() {
    const popContainerStyle = {
      position: 'relative'
    };

    const triggerStyle = {
      zIndex: '1',
      marginTop: this.props.buttonMarginTop,
      marginLeft: this.props.buttonMarginLeft
    };

    return (

        <button
          id="pop-btn"
          onClick={() => this.setState({ popVisible: !this.state.popVisible })}
          style={triggerStyle}
        >
          Popover on {this.props.direction}
        </button>
        <PopoverContent
          id={this.props.id}
          direction={this.props.direction}
          buttonMarginLeft={this.props.buttonMarginLeft}
          buttonMarginTop={this.props.buttonMarginTop}
          buttonWidth={this.state.buttonWidth}
          buttonHeight={this.state.buttonHeight}
          contentHeight={this.state.contentHeight}
          content={this.props.content}
          popVisible={this.state.popVisible}
        />

    );
  }
}

class PopoverContent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      contentHeight: 0
    };
  }
  componentWillUpdate() {
    let contentEle = document.getElementById(this.props.id);
    let contentPos = contentEle.getBoundingClientRect();
    if (this.props.popVisible) {
      this.setState({
        contentHeight: contentPos.height
      });
    }
  }
  render() {
    console.log('contentHeight', this.state.contentHeight);
    let top = null;
    let left = null;
    switch (this.props.direction) {
      case 'RIGHT':
        top =
          this.props.buttonMarginTop -
          (this.state.contentHeight - this.props.buttonHeight) / 2;
        left = this.props.buttonWidth + this.props.buttonMarginLeft + 10;
        break;
      // case 'LEFT':
      //   top = this.props.positionTop - 110;
      //   left = this.props.positionLeft - 10;
      //   break;
      default:
        break;
    }

    const infoStyle = {
      position: 'absolute',
      width: '200px',
      top: top,
      left: left,
      border: '1px solid rgba(0, 0, 0, 0.2)',
      padding: '10px 10px',
      zIndex: '100',
      background: '#fff',
      borderRadius: '4px'
    };
    if (this.props.popVisible)
      return (

          {this.props.content}

      );
    else return
;
  }
}
export default App;
<|endoftext|>


<commit_before>const fs = require('fs');
const process = require('process');

/**
 A semantic release "prepare" plugin to update elm-package.json
 */
async function prepareElmRelease(config, context) {
  function exec(command) {
    context.logger.log(`Running: ${command}`);
    execSync(command);
  }

  execCommand(`yarn elm-package diff`);
  execCommand(`yarn elm-package bump`);
}

module.exports = prepareElmRelease;
<commit_msg>fix(ci): Fix incorrect function name in prepareElmRelease<commit_after>const fs = require('fs');
const process = require('process');

/**
 A semantic release "prepare" plugin to update elm-package.json
 */
async function prepareElmRelease(config, context) {
  function exec(command) {
    context.logger.log(`Running: ${command}`);
    execSync(command);
  }

  exec(`yarn elm-package diff`);
  exec(`yarn elm-package bump`);
}

module.exports = prepareElmRelease;
<|endoftext|>


<commit_before>var crypto = require('crypto'),
	utils = require('keystone-utils');

exports.TOKEN_KEY = '_csrf';
exports.LOCAL_KEY = 'csrf_token_key';
exports.LOCAL_VALUE = 'csrf_token_value';
exports.SECRET_KEY = exports.TOKEN_KEY + '_secret';
exports.SECRET_LENGTH = 10;
exports.CSRF_HEADER_KEY = 'x-csrf-token';
exports.XSRF_HEADER_KEY = 'x-xsrf-token';
exports.XSRF_COOKIE_KEY = 'XSRF-TOKEN';

function tokenize(salt, secret) {
	return salt + crypto.createHash('sha1').update(salt + secret).digest('base64');
}

exports.createSecret = function() {
	return crypto.pseudoRandomBytes(exports.SECRET_LENGTH).toString('base64');
};

exports.getSecret = function(req) {
	return req.session[exports.SECRET_KEY] || (req.session[exports.SECRET_KEY] = exports.createSecret());
};

exports.createToken = function(req) {
	return tokenize(utils.randomString(exports.SECRET_LENGTH), exports.getSecret(req));
};

exports.getToken = function(req, res) {
	res.locals[exports.LOCAL_VALUE] = res.locals[exports.LOCAL_VALUE] || exports.createToken(req);
	res.cookie(exports.XSRF_COOKIE_KEY, res.locals[exports.LOCAL_VALUE]);
	return res.locals[exports.LOCAL_VALUE];
};

exports.requestToken = function(req) {
	if (req.body && req.body[exports.TOKEN_KEY]) {
		return req.body[exports.TOKEN_KEY];
	} else if (req.query && req.query[exports.TOKEN_KEY]) {
		return req.query[exports.TOKEN_KEY];
	} else if (req.headers[exports.XSRF_HEADER_KEY]) {
		return req.headers[exports.XSRF_HEADER_KEY];
	}	else if (req.headers[exports.CSRF_HEADER_KEY]) {
		return req.headers[exports.CSRF_HEADER_KEY];
	}
	return '';
};

exports.validate = function(req, token) {
	if (arguments.length === 1) {
		token = exports.requestToken(req);
	}
	if (typeof token !== 'string') {
		return false;
	}
	return token === tokenize(token.slice(0, exports.SECRET_LENGTH), req.session[exports.SECRET_KEY]);
};

exports.middleware = {

	init: function(req, res, next) {
		res.locals[exports.LOCAL_KEY] = exports.LOCAL_VALUE;
		exports.getToken(req, res);
		next();
	},

	validate: function(req, res, next) {

		// Bail on safe methods
		if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') {
			return next();
		}

		// Validate token
		if (exports.validate(req)) {
			next();
		} else {
			res.statusCode = 403;
			next(new Error('CSRF token mismatch'));
		}

	}

};
<commit_msg>added check for req.headers ... for unit testing with empty object<commit_after>var crypto = require('crypto'),
	utils = require('keystone-utils');

exports.TOKEN_KEY = '_csrf';
exports.LOCAL_KEY = 'csrf_token_key';
exports.LOCAL_VALUE = 'csrf_token_value';
exports.SECRET_KEY = exports.TOKEN_KEY + '_secret';
exports.SECRET_LENGTH = 10;
exports.CSRF_HEADER_KEY = 'x-csrf-token';
exports.XSRF_HEADER_KEY = 'x-xsrf-token';
exports.XSRF_COOKIE_KEY = 'XSRF-TOKEN';

function tokenize(salt, secret) {
	return salt + crypto.createHash('sha1').update(salt + secret).digest('base64');
}

exports.createSecret = function() {
	return crypto.pseudoRandomBytes(exports.SECRET_LENGTH).toString('base64');
};

exports.getSecret = function(req) {
	return req.session[exports.SECRET_KEY] || (req.session[exports.SECRET_KEY] = exports.createSecret());
};

exports.createToken = function(req) {
	return tokenize(utils.randomString(exports.SECRET_LENGTH), exports.getSecret(req));
};

exports.getToken = function(req, res) {
	res.locals[exports.LOCAL_VALUE] = res.locals[exports.LOCAL_VALUE] || exports.createToken(req);
	res.cookie(exports.XSRF_COOKIE_KEY, res.locals[exports.LOCAL_VALUE]);
	return res.locals[exports.LOCAL_VALUE];
};

exports.requestToken = function(req) {
	if (req.body && req.body[exports.TOKEN_KEY]) {
		return req.body[exports.TOKEN_KEY];
	} else if (req.query && req.query[exports.TOKEN_KEY]) {
		return req.query[exports.TOKEN_KEY];
	} else if (req.headers && req.headers[exports.XSRF_HEADER_KEY]) {
		return req.headers[exports.XSRF_HEADER_KEY];
	} else if (req.headers && req.headers[exports.CSRF_HEADER_KEY]) {
		return req.headers[exports.CSRF_HEADER_KEY];
	}
	return '';
};

exports.validate = function(req, token) {
	if (arguments.length === 1) {
		token = exports.requestToken(req);
	}
	if (typeof token !== 'string') {
		return false;
	}
	return token === tokenize(token.slice(0, exports.SECRET_LENGTH), req.session[exports.SECRET_KEY]);
};

exports.middleware = {

	init: function(req, res, next) {
		res.locals[exports.LOCAL_KEY] = exports.LOCAL_VALUE;
		exports.getToken(req, res);
		next();
	},

	validate: function(req, res, next) {

		// Bail on safe methods
		if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') {
			return next();
		}

		// Validate token
		if (exports.validate(req)) {
			next();
		} else {
			res.statusCode = 403;
			next(new Error('CSRF token mismatch'));
		}

	}

};
<|endoftext|>


<commit_before>/* Модуль сжатия js-скриптов и css*/

/* функция сжимает js-скрипты
 * и сохраняет их с именем .min.js
 */

var fs = require('fs');

/* CONSTANTS */
/* dir contains css-files */
var CSSDIR      = 'css/';

/* ---------------------------------- */
console.log('minify.js loaded...');
console.log('current dir: ' + process.cwd());
/* ---------------------------------- */

exports.jsScripts=function jsScripts(){
    'use strict';

    /* подключаем модуль uglify-js
     * если его нет - дальнейшая
     * работа функции не имеет смысла
     */
    try{
        var jsp = require("uglify-js").parser;
        var pro = require("uglify-js").uglify;
    }catch(error){
        console.log('can\'n load uglify-js\n'                  +
            'to use js-minification you need to install uglify-js\n'    +
                'npm install uglify-js\n'                               +
                'https://github.com/mishoo/UglifyJS');
        return false;
    }
    /* Константы */
    var CLIENT_JS='client.js';
    var CLOUDFUNC_JS='//app//lib//cloudfunc.js';
    var CLIENT_KEYBINDING_JS='//app//lib//client//keyBinding.js';

    var dataReaded_f=function(pFileName, pData){
            console.log('file ' + pFileName + ' readed');

            /*********************************/
            /* сжимаем код через uglify-js */
            var uglify_js=function(pDdata){
                var orig_code = pDdata.toString();
                var ast = jsp.parse(orig_code); // parse code and get the initial AST
                ast = pro.ast_mangle(ast); // get a new AST with mangled names
                ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
                var result_code = pro.gen_code(ast); // compressed code here
                return result_code;
            };
            /*********************************/
            var final_code=uglify_js(pData);

            var minFileName=pFileName.replace('.js','.min.js');
            /* если мы сжимаем client.js -
             * меняем строку cloudfunc.js на
             * cloudfunc.min.js и выводим сообщение
             *
             * меняем строку keyBinding.js на
             * keyBinding.min.js
             * если другой файл - ничего не деалем
             */
            if(pFileName===CLIENT_JS)
                console.log('file name of ' +
                    CLOUDFUNC_JS            +
                    ' in '                  +
                    CLIENT_JS               +
                    ' changed. size:',
                    (final_code=final_code
                        .replace('cloudfunc.js','cloudfunc.min.js')
                            .replace('keyBinding.js','keyBinding.min.js')).length);

            /* записываем сжатый js-скрипт*/
            fs.writeFile(minFileName, final_code, fileWrited(minFileName));
        };
     console.log('reading file ' + CLIENT_JS+'...');
    fs.readFile(CLIENT_JS,fileReaded(CLIENT_JS,dataReaded_f));

    console.log('reading file ' + CLOUDFUNC_JS+'...');
    fs.readFile(CLOUDFUNC_JS,fileReaded(CLOUDFUNC_JS,dataReaded_f));

    console.log('reading file ' + CLIENT_KEYBINDING_JS+'...');
    fs.readFile(CLIENT_KEYBINDING_JS, fileReaded(CLIENT_KEYBINDING_JS,dataReaded_f));

    return true;
};

/* функция сжимает css-стили
 * и сохраняет их с именем .min.css
 * @pImgConvertToBase64_b - булевый признак,
 * который отвечает за то, что быконвертировать
 * картинки в base64 и поместить в выходной css файл
 */
exports.cssStyles=function cssStyles(pImgConvertToBase64_b){
    'use strict';

     /* connecting cleanCSS,
      * if we can't find it -
      * return false
      */
     var cleanCSS;
     try{
        cleanCSS = require('clean-css');
    }catch(error){
        console.log('can\'n load clean-css \n'                          +
            'to use css-minification you need to install clean-css \n'  +
                'npm install clean-css\n'                               +
                'https://github.com/GoalSmashers/clean-css');
        return false;
    }

    /* Константы */
    var STYLE_CSS   = CSSDIR+'style.css';
    var RESET_CSS   = CSSDIR+'reset.css';

    var lAllStyle='';
    var lResetCssDone=false;
    var lStyleCssDone=false;
    var dataReaded_f=function(pFileName, pData){
        console.log('file ' + pFileName + ' readed');
        /*********************************/
        /* сжимаем код через clean-css */
        var clean_css=function(pData){
            /* Сохраняем весь стиль в одну переменную*/
            return cleanCSS.process(pData);
        };
        /*********************************/
        var final_code=clean_css(pData);

        lAllStyle+=final_code;

        var minFileName=pFileName.replace('.css','.min.css');

        if(pFileName===STYLE_CSS)lStyleCssDone=true;
        if(pFileName===RESET_CSS)lResetCssDone=true;
        /* if all files writed we
         * save all minimized css
         * to one file all.min.css
         */
        if(lStyleCssDone && lResetCssDone){
            /* если включена конвертация картинок в base64
             * вызываем её
             */
            if(pImgConvertToBase64_b)
                base64_images(lAllStyle);
            else
                fs.writeFile(CSSDIR+'all.min.css', lAllStyle, fileWrited('all.min.css'));
        }
         /* в другом случае - записываем сжатый css файл*/
        else fs.writeFile(minFileName, final_code, fileWrited(minFileName));
    };

    console.log('reading file ' + STYLE_CSS+'...');
    fs.readFile(STYLE_CSS,fileReaded(STYLE_CSS,dataReaded_f));

    console.log('reading file ' + RESET_CSS+'...');
    fs.readFile(RESET_CSS,fileReaded(RESET_CSS,dataReaded_f));

    return true;
};

/* функция сжимает css-стили
 * и сохраняет их с именем .min.css
 */
exports.html=function(){
    'use strict';

     /* connecting cleanCSS,
      * if we can't find it -
      * return false
      */
     var htmlMinifier;
     try{
        htmlMinifier = require('html-minifier');
    }catch(error){
        console.log('can\'n load html-minifier \n'                 +
            'to use html-minification you need to install html-minifier\n'  +
                'npm install html-minifier\n'                               +
                'https://github.com/kangax/html-minifier');
        return false;
    }

    /* Константы */
    var INDEX_HTML='index.html';

    var dataReaded_f=function(pFileName, pData){
        console.log('file ' + pFileName + ' readed');
        /*********************************/
        /* сжимаем код через clean-css */
        var html_minify=function(pData){
            /* Сохраняем весь стиль в одну переменную*/

            var lOptions={
                removeComments:                 true,
                removeCommentsFromCDATA:        true,
                removeCDATASectionsFromCDATA:   true,
                collapseWhitespace:             true,
                collapseBooleanAttributes:      true,
                removeAttributeQuotes:          true,
                removeRedundantAttributes:      true,
                useShortDoctype:                true,
                removeEmptyAttributes:          true,
                /* оставляем, поскольку у нас
                 * в элемент fm генерируеться
                 * таблица файлов
                 */
                removeEmptyElements:            false,
                removeOptionalTags:             true,
                removeScriptTypeAttributes:     true,
                removeStyleLinkTypeAttributes:  true
            };

            return htmlMinifier.minify(pData,lOptions);
        };
        /*********************************/
        var final_code=html_minify(pData);

        var minFileName=pFileName.replace('.html','.min.html');

         /* записываем сжатый html файл*/
        fs.writeFile(minFileName, final_code, fileWrited(minFileName));
    };

    console.log('reading file ' + INDEX_HTML+'...');
    fs.readFile(INDEX_HTML,fileReaded(INDEX_HTML,dataReaded_f));

    return true;
};

/* функция переводит картинки в base64 и записывает в css-файл*/
function base64_images(pFileContent_s){
    'use strict';
     var b64img;
     try{
        b64img = require('css-b64-images');
    }catch(error){
        console.log('can\'n load clean-css \n'                 +
            'to use images to base64 convertation you need to install css-base64-images \n'  +
                'npm install -g css-b64-images\n'                               +
                'https://github.com/Filirom1/css-base64-images');
        return false;
    }
    b64img.fromString(pFileContent_s, '.','', function(err, css){
        console.log('images converted to base64 and saved in css file');
        fs.writeFile(CSSDIR+'all.min.css', css, fileWrited('all.min.css'));
    });
}

/* Функция создаёт асинхроную версию
 * для чтения файла
 * @pFileName - имя считываемого файла
 */
function fileReaded(pFileName,pCompressFunc){
    "use strict";
    return function(pError,pData){
        /* функция в которую мы попадаем,
         * если данные считались
         *
         * если ошибка - показываем её
         * иначе если переданная функция -
         * функция запускаем её
         */
        if(!pError)
            if (pCompressFunc && typeof pCompressFunc==="function")
                    pCompressFunc(pFileName,pData.toString());
        else console.log(pError);
    };
}

/*
 * Функция вызываеться после записи файла
 * и выводит ошибку или сообщает,
 * что файл успешно записан
 */
function fileWrited(pFileName){
    "use strict";
    return function(error){
        console.log(error?error:('file '+pFileName+' writed...'));
    };
}<commit_msg>nodester seeting up<commit_after>/* Модуль сжатия js-скриптов и css*/

/* функция сжимает js-скрипты
 * и сохраняет их с именем .min.js
 */

var fs = require('fs');

/* CONSTANTS */
/* dir contains css-files */
var CSSDIR      = 'css/';

/* ---------------------------------- */
console.log('minify.js loaded...');
console.log('current dir: ' + process.cwd());
/* ---------------------------------- */

exports.jsScripts=function jsScripts(){
    'use strict';

    /* подключаем модуль uglify-js
     * если его нет - дальнейшая
     * работа функции не имеет смысла
     */
    try{
        var jsp = require("uglify-js").parser;
        var pro = require("uglify-js").uglify;
    }catch(error){
        console.log('can\'n load uglify-js\n'                  +
            'to use js-minification you need to install uglify-js\n'    +
                'npm install uglify-js\n'                               +
                'https://github.com/mishoo/UglifyJS');
        return false;
    }
    /* Константы */
    var CLIENT_JS='client.js';
    var CLOUDFUNC_JS='/lib/cloudfunc.js';
    var CLIENT_KEYBINDING_JS='lib/client/keyBinding.js';

    var dataReaded_f=function(pFileName, pData){
            console.log('file ' + pFileName + ' readed');

            /*********************************/
            /* сжимаем код через uglify-js */
            var uglify_js=function(pDdata){
                var orig_code = pDdata.toString();
                var ast = jsp.parse(orig_code); // parse code and get the initial AST
                ast = pro.ast_mangle(ast); // get a new AST with mangled names
                ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
                var result_code = pro.gen_code(ast); // compressed code here
                return result_code;
            };
            /*********************************/
            var final_code=uglify_js(pData);

            var minFileName=pFileName.replace('.js','.min.js');
            /* если мы сжимаем client.js -
             * меняем строку cloudfunc.js на
             * cloudfunc.min.js и выводим сообщение
             *
             * меняем строку keyBinding.js на
             * keyBinding.min.js
             * если другой файл - ничего не деалем
             */
            if(pFileName===CLIENT_JS)
                console.log('file name of ' +
                    CLOUDFUNC_JS            +
                    ' in '                  +
                    CLIENT_JS               +
                    ' changed. size:',
                    (final_code=final_code
                        .replace('cloudfunc.js','cloudfunc.min.js')
                            .replace('keyBinding.js','keyBinding.min.js')).length);

            /* записываем сжатый js-скрипт*/
            fs.writeFile(minFileName, final_code, fileWrited(minFileName));
        };
     console.log('reading file ' + CLIENT_JS+'...');
    fs.readFile(CLIENT_JS,fileReaded(CLIENT_JS,dataReaded_f));

    console.log('reading file ' + CLOUDFUNC_JS+'...');
    fs.readFile(CLOUDFUNC_JS,fileReaded(CLOUDFUNC_JS,dataReaded_f));

    console.log('reading file ' + CLIENT_KEYBINDING_JS+'...');
    fs.readFile(CLIENT_KEYBINDING_JS, fileReaded(CLIENT_KEYBINDING_JS,dataReaded_f));

    return true;
};

/* функция сжимает css-стили
 * и сохраняет их с именем .min.css
 * @pImgConvertToBase64_b - булевый признак,
 * который отвечает за то, что быконвертировать
 * картинки в base64 и поместить в выходной css файл
 */
exports.cssStyles=function cssStyles(pImgConvertToBase64_b){
    'use strict';

     /* connecting cleanCSS,
      * if we can't find it -
      * return false
      */
     var cleanCSS;
     try{
        cleanCSS = require('clean-css');
    }catch(error){
        console.log('can\'n load clean-css \n'                          +
            'to use css-minification you need to install clean-css \n'  +
                'npm install clean-css\n'                               +
                'https://github.com/GoalSmashers/clean-css');
        return false;
    }

    /* Константы */
    var STYLE_CSS   = CSSDIR+'style.css';
    var RESET_CSS   = CSSDIR+'reset.css';

    var lAllStyle='';
    var lResetCssDone=false;
    var lStyleCssDone=false;
    var dataReaded_f=function(pFileName, pData){
        console.log('file ' + pFileName + ' readed');
        /*********************************/
        /* сжимаем код через clean-css */
        var clean_css=function(pData){
            /* Сохраняем весь стиль в одну переменную*/
            return cleanCSS.process(pData);
        };
        /*********************************/
        var final_code=clean_css(pData);

        lAllStyle+=final_code;

        var minFileName=pFileName.replace('.css','.min.css');

        if(pFileName===STYLE_CSS)lStyleCssDone=true;
        if(pFileName===RESET_CSS)lResetCssDone=true;
        /* if all files writed we
         * save all minimized css
         * to one file all.min.css
         */
        if(lStyleCssDone && lResetCssDone){
            /* если включена конвертация картинок в base64
             * вызываем её
             */
            if(pImgConvertToBase64_b)
                base64_images(lAllStyle);
            else
                fs.writeFile(CSSDIR+'all.min.css', lAllStyle, fileWrited('all.min.css'));
        }
         /* в другом случае - записываем сжатый css файл*/
        else fs.writeFile(minFileName, final_code, fileWrited(minFileName));
    };

    console.log('reading file ' + STYLE_CSS+'...');
    fs.readFile(STYLE_CSS,fileReaded(STYLE_CSS,dataReaded_f));

    console.log('reading file ' + RESET_CSS+'...');
    fs.readFile(RESET_CSS,fileReaded(RESET_CSS,dataReaded_f));

    return true;
};

/* функция сжимает css-стили
 * и сохраняет их с именем .min.css
 */
exports.html=function(){
    'use strict';

     /* connecting cleanCSS,
      * if we can't find it -
      * return false
      */
     var htmlMinifier;
     try{
        htmlMinifier = require('html-minifier');
    }catch(error){
        console.log('can\'n load html-minifier \n'                 +
            'to use html-minification you need to install html-minifier\n'  +
                'npm install html-minifier\n'                               +
                'https://github.com/kangax/html-minifier');
        return false;
    }

    /* Константы */
    var INDEX_HTML='index.html';

    var dataReaded_f=function(pFileName, pData){
        console.log('file ' + pFileName + ' readed');
        /*********************************/
        /* сжимаем код через clean-css */
        var html_minify=function(pData){
            /* Сохраняем весь стиль в одну переменную*/

            var lOptions={
                removeComments:                 true,
                removeCommentsFromCDATA:        true,
                removeCDATASectionsFromCDATA:   true,
                collapseWhitespace:             true,
                collapseBooleanAttributes:      true,
                removeAttributeQuotes:          true,
                removeRedundantAttributes:      true,
                useShortDoctype:                true,
                removeEmptyAttributes:          true,
                /* оставляем, поскольку у нас
                 * в элемент fm генерируеться
                 * таблица файлов
                 */
                removeEmptyElements:            false,
                removeOptionalTags:             true,
                removeScriptTypeAttributes:     true,
                removeStyleLinkTypeAttributes:  true
            };

            return htmlMinifier.minify(pData,lOptions);
        };
        /*********************************/
        var final_code=html_minify(pData);

        var minFileName=pFileName.replace('.html','.min.html');

         /* записываем сжатый html файл*/
        fs.writeFile(minFileName, final_code, fileWrited(minFileName));
    };

    console.log('reading file ' + INDEX_HTML+'...');
    fs.readFile(INDEX_HTML,fileReaded(INDEX_HTML,dataReaded_f));

    return true;
};

/* функция переводит картинки в base64 и записывает в css-файл*/
function base64_images(pFileContent_s){
    'use strict';
     var b64img;
     try{
        b64img = require('css-b64-images');
    }catch(error){
        console.log('can\'n load clean-css \n'                 +
            'to use images to base64 convertation you need to install css-base64-images \n'  +
                'npm install -g css-b64-images\n'                               +
                'https://github.com/Filirom1/css-base64-images');
        return false;
    }
    b64img.fromString(pFileContent_s, '.','', function(err, css){
        console.log('images converted to base64 and saved in css file');
        fs.writeFile(CSSDIR+'all.min.css', css, fileWrited('all.min.css'));
    });
}

/* Функция создаёт асинхроную версию
 * для чтения файла
 * @pFileName - имя считываемого файла
 */
function fileReaded(pFileName,pCompressFunc){
    "use strict";
    return function(pError,pData){
        /* функция в которую мы попадаем,
         * если данные считались
         *
         * если ошибка - показываем её
         * иначе если переданная функция -
         * функция запускаем её
         */
        if(!pError)
            if (pCompressFunc && typeof pCompressFunc==="function")
                    pCompressFunc(pFileName,pData.toString());
        else console.log(pError);
    };
}

/*
 * Функция вызываеться после записи файла
 * и выводит ошибку или сообщает,
 * что файл успешно записан
 */
function fileWrited(pFileName){
    "use strict";
    return function(error){
        console.log(error?error:('file '+pFileName+' writed...'));
    };
}<|endoftext|>


<commit_before>/* module make possible connectoin thru socket.io on a server */

(function() {
    'use strict';

    var main            = global.cloudcmd.main,
        SRVDIR          = main.SRVDIR,

        io              = main.require('socket.io'),
        update          = main.srvrequire('update'),
        exec            = main.child_process.exec,
        Util            = main.util,
        mainpackage     = main.mainpackage,
        CLOUDCMD        = mainpackage.name,

        ClientFuncs     = [],
        OnMessageFuncs  = [],
        INFO_LOG_LEVEL  = 2,
        WIN32           = main.WIN32,

        /* windows commands thet require
         * unicode charset on locales
         * different then English
         */
        Win32Commands   = ['ASSOC', 'AT', 'ATTRIB', 'BREAK', 'CACLS', 'CALL',
                            'CD', 'CHCP', 'CHDIR', 'CHKDSK', 'CHKNTFS', 'CLS',
                            'CMD', 'COLOR', 'COMP', 'COMPACT', 'CONVERT', 'COPY',
                            'DATE', 'DEL', 'DIR', 'DISKCOMP', 'DISKCOPY', 'DOSKEY',
                            'ECHO', 'ENDLOCAL', 'ERASE', 'EXIT', 'FC', 'FIND',
                            'FINDSTR', 'FOR', 'FORMAT', 'FTYPE', 'GOTO', 'GRAFTABL',
                            'HELP', 'IF', 'LABEL', 'MD', 'MKDIR', 'MODE', 'MORE',
                            'MOVE', 'PATH', 'PAUSE', 'POPD', 'PRINT', 'PROMPT',
                            'PUSHD', 'RD', 'RECOVER', 'REM', 'REN', 'RENAME',
                            'REPLACE', 'RMDIR', 'SET', 'SETLOCAL', 'SHIFT', 'SORT',
                            'START', 'SUBST', 'TIME', 'TITLE', 'TREE', 'TYPE',
                            'VER', 'VERIFY', 'VOL', 'XCOPY'];

    /**
     * function listen on servers port
     * @pServer {Object} started server object
     */
    exports.listen = function(pServer) {
        var lRet, lListen, lConnNum, lMsg, lConn_func;

        if (io) {
            lListen     = io.listen(pServer),
            lConnNum    = 0;

            lListen.set('log level', INFO_LOG_LEVEL);

            /*
             * on Win7 application is crashing,
             * when options below is used.
             *
             * https://github.com/LearnBoost/socket.io/issues/1314
             *
             */
            if (!WIN32) {
                lListen.enable('browser client minification');
                lListen.enable('browser client gzip');
                lListen.enable('browser client etag');
            }

            lListen.set('transports', [
              'websocket',
              'htmlfile',
              'xhr-polling',
              'jsonp-polling'
            ]);

            lRet = lListen.sockets.on('connection', function (socket) {
                var lJSON;
                ++lConnNum;

                if(!OnMessageFuncs[lConnNum]) {
                    lMsg    = log(lConnNum, 'connected\n');
                    lJSON   = {
                        stdout : lMsg
                    };
                    lMsg    = Util.stringifyJSON(lJSON);

                    socket.send(lMsg);

                    OnMessageFuncs[lConnNum]    = onMessage(lConnNum, socket);
                    lConn_func                  = OnMessageFuncs[lConnNum];

                    socket.on('message', lConn_func);
                    socket.on('disconnect', Util.call(disconnect, lConnNum));
                } else {
                    lMsg = log(lConnNum, ' in use. Reconnecting...');
                    socket.send('{"stdout":"' + lMsg + '"}');
                    socket.disconnect();
                }

            });
        }

        return lRet;
    };

    function disconnect(pParams) {
        var lConnNum, lRet = Util.checkObj(pParams, ['params']);

        if(lRet) {
            lConnNum = pParams.params;
            OnMessageFuncs  [lConnNum]  =
            ClientFuncs     [lConnNum]  = null;

            log(lConnNum, 'disconnected');
        }

    }

    /**
     * function gets onMessage function
     * that execute needed command
     *
     * @param pConnNum, pSocket
     */
    function onMessage(pConnNum, pSocket) {
        return function(pCommand) {
            var lMsg, lJSON, lWinCommand, lExec_func, lDir,
                lHome, lError, lRet;

            Util.log('#' + pConnNum + ': ' + pCommand);

            if (Util.isContainStrAtBegin(pCommand, CLOUDCMD)) {
                pCommand = Util.removeStr(pCommand, CLOUDCMD);

                if( Util.isContainStrAtBegin(pCommand, ' ') ) {
                    pCommand = Util.removeStr(pCommand, ' ');

                    if( Util.isContainStrAtBegin(pCommand, 'update') && update )
                        update.get();

                    if( Util.strCmp(pCommand, 'exit') )
                        if(WIN32)
                            pCommand = 'taskkill -f /PID ' + process.pid;
                        else
                            pCommand = 'kill -9 ' + process.pid;
                }
                else {
                    lJSON = {
                        stdout  : CLOUDCMD + ' exit     \n' +
                                  CLOUDCMD + ' update   \n',
                        stderr  : null
                    };

                    lMsg = Util.stringifyJSON( lJSON );
                    pSocket.send(lMsg);

                    Util.log('received from client: ' + pCommand);
                    Util.log('sended to client: ' + lMsg);
                }
            } else if( Util.isContainStrAtBegin(pCommand, 'cd ') ) {
                lDir    = Util.removeStr(pCommand, 'cd ');
                lHome   = process.env.HOME;

                if ( Util.isContainStr(lDir, '~') )
                    lDir = Util.replaceStr(lDir, '~', lHome);

                lError = Util.tryCatchLog(function() {
                    process.chdir(lDir);
                });

                if (!lError)
                    lRet = true;
                else {
                    lJSON = {
                        stderr: Util.stringifyJSON( lError )
                    };

                    lMsg = Util.stringifyJSON( lJSON );

                    pSocket.send(lMsg);
                }
            }

            if (!lRet) {
                /* if we on windows and command is build in
                 * change code page to unicode becouse
                 * windows use unicode on non English versions
                 */
                if(WIN32) {
                    lWinCommand = pCommand.toUpperCase();

                    if( Win32Commands.indexOf(lWinCommand) >= 0 )
                        pCommand = 'chcp 65001 |' + pCommand;
                }

                if(!ClientFuncs[pConnNum])
                    ClientFuncs[pConnNum] = getExec(pSocket, pConnNum);

                lExec_func = ClientFuncs[pConnNum];

                exec(pCommand, lExec_func);
            }
        };
    }

    /**
     * function send result of command to client
     * @param pSocket
     */
    function getExec(pSocket, pConnNum) {
        return function(pError, pStdout, pStderr) {
            var lErrorStr, lExecStr, lExec,
                lError          = pStderr || pError;

            if (lError)
                if ( Util.isString(lError) )
                    lErrorStr   = lError;
                else
                    lErrorStr   = Util.stringifyJSON( lError );

            lExec               = {
                stdout : pStdout,
                stderr : lError
            };

                lExecStr       = JSON.stringify(lExec);

            log(pConnNum, pError, 'error');
            log(pConnNum, pStderr, 'stderror');

            pSocket.send(lExecStr);
        };
    }

    function log(pConnNum, pStr, pType) {
        var lRet, lType = ' ';

        if (pStr) {

            if (pType)
                lType += pType + ':';

            lRet = 'client #' + pConnNum + lType + pStr;

            Util.log(lRet);
        }

        return lRet;
    }
})();
<commit_msg>feature(socket) add spawn<commit_after>/* module make possible connectoin thru socket.io on a server */

(function() {
    'use strict';

    var main            = global.cloudcmd.main,
        SRVDIR          = main.SRVDIR,

        io              = main.require('socket.io'),
        update          = main.srvrequire('update'),
        exec            = main.child_process.exec,
        Util            = main.util,
        mainpackage     = main.mainpackage,
        CLOUDCMD        = mainpackage.name,

        ClientFuncs     = [],
        OnMessageFuncs  = [],
        INFO_LOG_LEVEL  = 2,
        WIN32           = main.WIN32,

        /* windows commands thet require
         * unicode charset on locales
         * different then English
         */
        Win32Commands   = ['ASSOC', 'AT', 'ATTRIB', 'BREAK', 'CACLS', 'CALL',
                            'CD', 'CHCP', 'CHDIR', 'CHKDSK', 'CHKNTFS', 'CLS',
                            'CMD', 'COLOR', 'COMP', 'COMPACT', 'CONVERT', 'COPY',
                            'DATE', 'DEL', 'DIR', 'DISKCOMP', 'DISKCOPY', 'DOSKEY',
                            'ECHO', 'ENDLOCAL', 'ERASE', 'EXIT', 'FC', 'FIND',
                            'FINDSTR', 'FOR', 'FORMAT', 'FTYPE', 'GOTO', 'GRAFTABL',
                            'HELP', 'IF', 'LABEL', 'MD', 'MKDIR', 'MODE', 'MORE',
                            'MOVE', 'PATH', 'PAUSE', 'POPD', 'PRINT', 'PROMPT',
                            'PUSHD', 'RD', 'RECOVER', 'REM', 'REN', 'RENAME',
                            'REPLACE', 'RMDIR', 'SET', 'SETLOCAL', 'SHIFT', 'SORT',
                            'START', 'SUBST', 'TIME', 'TITLE', 'TREE', 'TYPE',
                            'VER', 'VERIFY', 'VOL', 'XCOPY'];

    /**
     * function listen on servers port
     * @pServer {Object} started server object
     */
    exports.listen = function(pServer) {
        var lRet, lListen, lConnNum, lMsg, lConn_func;

        if (io) {
            lListen     = io.listen(pServer),
            lConnNum    = 0;

            lListen.set('log level', INFO_LOG_LEVEL);

            /*
             * on Win7 application is crashing,
             * when options below is used.
             *
             * https://github.com/LearnBoost/socket.io/issues/1314
             *
             */
            if (!WIN32) {
                lListen.enable('browser client minification');
                lListen.enable('browser client gzip');
                lListen.enable('browser client etag');
            }

            lListen.set('transports', [
              'websocket',
              'htmlfile',
              'xhr-polling',
              'jsonp-polling'
            ]);

            lRet = lListen.sockets.on('connection', function (socket) {
                var lJSON;
                ++lConnNum;

                if(!OnMessageFuncs[lConnNum]) {
                    lMsg    = log(lConnNum, 'connected\n');
                    lJSON   = {
                        stdout : lMsg
                    };
                    lMsg    = Util.stringifyJSON(lJSON);

                    socket.send(lMsg);

                    OnMessageFuncs[lConnNum]    = onMessage(lConnNum, socket);
                    lConn_func                  = OnMessageFuncs[lConnNum];

                    socket.on('message', lConn_func);
                    socket.on('disconnect', Util.call(disconnect, lConnNum));
                } else {
                    lMsg = log(lConnNum, ' in use. Reconnecting...');
                    socket.send('{"stdout":"' + lMsg + '"}');
                    socket.disconnect();
                }

            });
        }

        return lRet;
    };

    function disconnect(pParams) {
        var lConnNum, lRet = Util.checkObj(pParams, ['params']);

        if(lRet) {
            lConnNum = pParams.params;
            OnMessageFuncs  [lConnNum]  =
            ClientFuncs     [lConnNum]  = null;

            log(lConnNum, 'disconnected');
        }

    }

    /**
     * function gets onMessage function
     * that execute needed command
     *
     * @param pConnNum, pSocket
     */
    function onMessage(pConnNum, pSocket) {
        return function(pCommand) {
            var lMsg, lJSON, lWinCommand, lExec_func, lDir,
                lHome, lError, lRet, lExecSymbols;

            Util.log('#' + pConnNum + ': ' + pCommand);

            if (Util.isContainStrAtBegin(pCommand, CLOUDCMD)) {
                pCommand = Util.removeStr(pCommand, CLOUDCMD);

                if( Util.isContainStrAtBegin(pCommand, ' ') ) {
                    pCommand = Util.removeStr(pCommand, ' ');

                    if( Util.isContainStrAtBegin(pCommand, 'update') && update )
                        update.get();

                    if( Util.strCmp(pCommand, 'exit') )
                        if(WIN32)
                            pCommand = 'taskkill -f /PID ' + process.pid;
                        else
                            pCommand = 'kill -9 ' + process.pid;
                }
                else {
                    lJSON = {
                        stdout  : CLOUDCMD + ' exit     \n' +
                                  CLOUDCMD + ' update   \n',
                        stderr  : null
                    };

                    lMsg = Util.stringifyJSON( lJSON );
                    pSocket.send(lMsg);

                    Util.log('received from client: ' + pCommand);
                    Util.log('sended to client: ' + lMsg);
                }
            } else if( Util.isContainStrAtBegin(pCommand, 'cd ') ) {
                lDir    = Util.removeStr(pCommand, 'cd ');
                lHome   = process.env.HOME;

                if ( Util.isContainStr(lDir, '~') )
                    lDir = Util.replaceStr(lDir, '~', lHome);

                lError = Util.tryCatchLog(function() {
                    process.chdir(lDir);
                });

                if (!lError)
                    lRet = true;
                else {
                    lJSON = {
                        stderr: Util.stringifyJSON( lError )
                    };

                    lMsg = Util.stringifyJSON( lJSON );

                    pSocket.send(lMsg);
                }
            }

            if (!lRet) {
                /* if we on windows and command is build in
                 * change code page to unicode becouse
                 * windows use unicode on non English versions
                 */
                if(WIN32) {
                    lWinCommand = pCommand.toUpperCase();

                    if( Win32Commands.indexOf(lWinCommand) >= 0 )
                        pCommand = 'chcp 65001 |' + pCommand;
                }

                if(!ClientFuncs[pConnNum])
                    ClientFuncs[pConnNum] = getExec(pSocket, pConnNum);

                lExec_func = ClientFuncs[pConnNum];

                lExecSymbols = ['{', '}', '|', '\'', '"'];

                if (Util.isContainStr(pCommand, lExecSymbols))
                    exec(pCommand, lExec_func);
                else
                    getSpawn(pSocket, pConnNum, pCommand);
            }
        };
    }

    /**
     * function send result of command to client
     * @param pSocket
     */
    function getExec(pSocket, pConnNum) {
        return function(pError, pStdout, pStderr) {
            var lErrorStr, lExecStr, lExec,
                lError          = pStderr || pError;

            if (lError)
                if ( Util.isString(lError) )
                    lErrorStr   = lError;
                else
                    lErrorStr   = Util.stringifyJSON( lError );

            lExec               = {
                stdout : pStdout,
                stderr : lError
            };

            lExecStr       = JSON.stringify(lExec);

            log(pConnNum, pError, 'error');
            log(pConnNum, pStderr, 'stderror');

            pSocket.send(lExecStr);
        };
    }

    function getSpawn(pSocket, pConnNum, pCommand) {
        var send, cmd, spawn,
            args    = pCommand.split(' ');

        pCommand    = args.shift();

        spawn       = main.child_process.spawn;
        cmd         = spawn(pCommand, args);
        send        = function(data, isError) {
            var lExecStr,
                lExec               = {},
                msg                 = data.toString();

            if (isError)
                lExec.stderr    = msg;
            else
                lExec.stdout    = msg;

            lExecStr            = JSON.stringify(lExec);
            pSocket.send(lExecStr);
            Util.log(msg);
        };

        cmd.stdout.on('data', send);

        cmd.stderr.on('data', function(data) {
            send(data, true);
        });

        cmd.on('error', function(data) {
            send(data, true);
        });
    }

    function log(pConnNum, pStr, pType) {
        var lRet, lType = ' ';

        if (pStr) {

            if (pType)
                lType += pType + ':';

            lRet = 'client #' + pConnNum + lType + pStr;

            Util.log(lRet);
        }

        return lRet;
    }
})();
<|endoftext|>


<commit_before>module.exports.get = function(url) {
    var options = arguments.length === 2 ? {} : arguments[1];
    var callback = arguments.length === 2 ? arguments[1] : arguments[2];
    get(url, parseOptions(options), callback);
}

var http = require("http"),
    urlparse = require("url").parse,
    defaultify = require("defaultify"),
    parsers = require("./parsers");

function get(url, options, callback) {
    var urlinfo = urlparse(url);
    var requestOptions = {
        hostname: urlinfo.hostname,
        path: urlinfo.path,
        method: "GET",
        port: urlinfo.port ? urlinfo.port : 80,
        headers: {
            accept: options.accept
        }
    };

    var buffer;
    var received = 0;
    var length;
    var parsed;

    function start() {
        var request = http.request(requestOptions, onResponse);
        request.on("error", function(err) { onError("request", err) });
        request.end();
    }

    function onResponse(response) {
        if (Math.floor(response.statusCode / 100) != 2) {
            onError("response", new Error("non 2xx status code: " + response.statusCode));
        } else {
            createBuffer(response.headers["content-length"]);
            response.on("data", onData);
            response.on("end", onEnd);
        }
    }

    function onData(chunk) {
        if (length == -1)
            resizeBuffer(received + chunk.length);
        chunk.copy(buffer, received);
        received += chunk.length;
    }

    function onEnd() {
        if (length == -1) {
            length = received;
            buffer = buffer.slice(0, length);
        }
        process.nextTick(parse);
    }

    function parse() {
        try {
            options.parse(buffer, function(err, data) {
                if (err) {
                    onError("parse", err);
                } else {
                    parsed = data;
                    process.nextTick(transform);
                }
            });
        } catch (e) {
            onError("parse", e);
        }
    }

    function transform() {
        try {
            options.transform(parsed, function (err, transformed) {
                if (err) {
                    onError("transform", err);
                } else {
                    doCallback(null, transformed);
                }
            });
        } catch (e) {
            onError("transform", e);
        }
    }

    function onError(action, err) {
        doCallback({
            error: err,
            action: action,
            length: length,
            received: received,
            buffer: buffer,
            parsed: parsed
        });
    }

    function doCallback(err, data) {
        process.nextTick(function() {
            if (err) {
                callback(err);
            } else {
                callback(null, data);
            }
        });
    }

    function createBuffer(contentLength) {
        length = parseInt(contentLength === undefined ? -1 : contentLength);
        buffer = new Buffer(length > 0 ? length : 65536);
    }

    function resizeBuffer(mustBe) {
        if (buffer.length < mustBe) {
            var newLen = buffer.length * 2;
            while (newLen < mustBe) {
                newLen *= 2;
            }
            var newBuf = new Buffer(newLen);
            buffer.copy(newBuf, received);
            buffer = newBuf;
        }
    }

    process.nextTick(start);
}

function parseOptions(options) {
    var def = {
        accept: "text/plain",
        parse: parsers.plain,
        transform: parsers.plain
    };
    var transform = {
        accept: function(val) {
            if (val === "plain" || val === "text") return "text/plain";
            if (val === "json") return "application/json";
            return val;
        },
        parse: function(val) {
            if (typeof(val) === "function") return val;
            if (val === "json") return parsers.json;
            if (val === "raw") return parsers.plain;
            throw new Error("unknown parse value " + val);
        }
    };

    return defaultify(options, def, transform, true).value;
}
<commit_msg>xml resolves to application/xml<commit_after>module.exports.get = function(url) {
    var options = arguments.length === 2 ? {} : arguments[1];
    var callback = arguments.length === 2 ? arguments[1] : arguments[2];
    get(url, parseOptions(options), callback);
}

var http = require("http"),
    urlparse = require("url").parse,
    defaultify = require("defaultify"),
    parsers = require("./parsers");

function get(url, options, callback) {
    var urlinfo = urlparse(url);
    var requestOptions = {
        hostname: urlinfo.hostname,
        path: urlinfo.path,
        method: "GET",
        port: urlinfo.port ? urlinfo.port : 80,
        headers: {
            accept: options.accept
        }
    };

    var buffer;
    var received = 0;
    var length;
    var parsed;

    function start() {
        var request = http.request(requestOptions, onResponse);
        request.on("error", function(err) { onError("request", err) });
        request.end();
    }

    function onResponse(response) {
        if (Math.floor(response.statusCode / 100) != 2) {
            onError("response", new Error("non 2xx status code: " + response.statusCode));
        } else {
            createBuffer(response.headers["content-length"]);
            response.on("data", onData);
            response.on("end", onEnd);
        }
    }

    function onData(chunk) {
        if (length == -1)
            resizeBuffer(received + chunk.length);
        chunk.copy(buffer, received);
        received += chunk.length;
    }

    function onEnd() {
        if (length == -1) {
            length = received;
            buffer = buffer.slice(0, length);
        }
        process.nextTick(parse);
    }

    function parse() {
        try {
            options.parse(buffer, function(err, data) {
                if (err) {
                    onError("parse", err);
                } else {
                    parsed = data;
                    process.nextTick(transform);
                }
            });
        } catch (e) {
            onError("parse", e);
        }
    }

    function transform() {
        try {
            options.transform(parsed, function (err, transformed) {
                if (err) {
                    onError("transform", err);
                } else {
                    doCallback(null, transformed);
                }
            });
        } catch (e) {
            onError("transform", e);
        }
    }

    function onError(action, err) {
        doCallback({
            error: err,
            action: action,
            length: length,
            received: received,
            buffer: buffer,
            parsed: parsed
        });
    }

    function doCallback(err, data) {
        process.nextTick(function() {
            if (err) {
                callback(err);
            } else {
                callback(null, data);
            }
        });
    }

    function createBuffer(contentLength) {
        length = parseInt(contentLength === undefined ? -1 : contentLength);
        buffer = new Buffer(length > 0 ? length : 65536);
    }

    function resizeBuffer(mustBe) {
        if (buffer.length < mustBe) {
            var newLen = buffer.length * 2;
            while (newLen < mustBe) {
                newLen *= 2;
            }
            var newBuf = new Buffer(newLen);
            buffer.copy(newBuf, received);
            buffer = newBuf;
        }
    }

    process.nextTick(start);
}

function parseOptions(options) {
    var def = {
        accept: "text/plain",
        parse: parsers.plain,
        transform: parsers.plain
    };
    var transform = {
        accept: function(val) {
            if (val === "plain" || val === "text") return "text/plain";
            if (val === "json") return "application/json";
            if (val === "xml") return "application/xml";
            return val;
        },
        parse: function(val) {
            if (typeof(val) === "function") return val;
            if (val === "json") return parsers.json;
            if (val === "raw") return parsers.plain;
            throw new Error("unknown parse value " + val);
        }
    };

    return defaultify(options, def, transform, true).value;
}
<|endoftext|>


<commit_before>/*!
 * qwebs-mongo
 * Copyright(c) 2017 Benoît Claveau <benoit.claveau@gmail.com> / CABASI
 * MIT Licensed
 */
"use strict";

const DataError = require("qwebs").DataError;
const ObjectID = require('mongodb').ObjectID;
const ToArray = require("qwebs").ToArray;
const MongoService = require("../qwebs-mongo");
const pluralize = require('pluralize');

class CrudService {
    constructor(collectionName, $mongo) {
        if (!collectionName) throw new DataError({ message: "collectionName isn't defined." });
        if (!$mongo) throw new DataError({ message: "$mongo isn't defined." });
        if ($mongo instanceof MongoService) throw new DataError({ message: "$mongo isn't a MongoService." });

        this.$mongo = $mongo;
        this.collectionName = collectionName;
        this.objectName = pluralize.singular(collectionName);
    };

    /* rest ------------------------------------------------*/

    getById(request, response) {
        let id = request.params ? request.params.id : request.query ? request.query.id : null;
        throw new DataError({ message: "Id is not defined." });
        return this.mongoGetById(id).then(content => {
            return response.send({ request: request, content: content });
        });
    };

    save(request, response) {
        if (!request.body) throw new DataError({ message: "Request body is not defined." });
        return this.mongoSave(request.body).then(content => {
            return response.send({ request: request, content: content });
        });
    };

    saveList(request, response) {
        if (!request.body) throw new DataError({ message: "Request body is not defined." });
        return this.mongoSaveList(request.body).then(content => {
            return response.send({ request: request, content: content });
        });
    };

    deleteById(request, response) {
        let id = request.params ? request.params.id : request.query ? request.query.id : null;
        throw new DataError({ message: "Id is not defined." });
        return this.mongoDeleteById(id).then(content => {
            return response.send({ request: request, content: content });
        });
    };

    delete(request, response) {
        if (!request.body) throw new DataError({ message: "Request body is not defined." });
        return this.mongoDelete(request.body).then(content => {
            return response.send({ request: request, content: content });
        });
    };

    deleteList(request, response) {
        if (!request.body) throw new DataError({ message: "Request body is not defined." });
        return this.mongoDeleteList(request.body).then(content => {
            return response.send({ request: request, content: content });
        });
    };

    /* primitives ------------------------------------------*/

    get collection() {
        return this.$mongo.db.then(db => {
            return db.collection(this.collectionName);
        });
    };

    mongoGetById(id) {
        return this.collection.then(collection => {
            if (!id) throw new DataError({ message: "Id isn't defined." });
            if (id instanceof ObjectID == false) id = new ObjectID(id);
            return collection.findOne({ _id: id }).then(object => {
                if (!object) throw new DataError({ message: `${this.objectName} isn't defined.` });
                return object;
            });
        });
    };

    mongoArray(options) {
        let options = options || options;
        options.query = options.query || {};

        return this.collection.then(collection => {
            let q = this.find(options.query);
            if (options.limit) q = q.limit(options.limit);
            if (options.skip) q = q.skip(options.skip);
            if (options.sort) q = q.sort(options.sort);

            return q.ToArray();
        });
    };

    mongoStream(options) {
        let options = options || options;
        options.query = options.query || {};

        return this.collection.then(collection => {
            let q = this.find(options.query);
            if (options.limit) q = q.limit(options.limit);
            if (options.skip) q = q.skip(options.skip);
            if (options.sort) q = q.sort(options.sort);

            return q.stream();
        });
    };

    mongoSave(object) {
        return this.mongoGetById(object._id).then(previous => {
            return this.mongoUpdate(object);
        }).catch(error => {
            if (error.message != `${this.objectName} isn't defined.`) throw error;
            return this.mongoInsert(object);
        });
    };

    mongoSavetList(objects) {
        return Promise.all(objects.map(object => {
            return this.mongoSave(object);
        }));
    };

    mongoInsert(object) {
        return this.collection.then(collection => {
            delete object._id;
            return collection.insertOne(object).then(res => {
                return res.ops[0];
            });
        });
    };

    mongoInsertList(objects) {
        return Promise.all(objects.map(object => {
            return this.mongoInsert(object);
        }));
    };

    mongoUpdate(object) {
        return this.collection.then(collection => {
            if (object._id instanceof ObjectID == false) object._id = new ObjectID(object._id);
            let copy = Object.assign({}, object);
            delete copy._id;
            return collection.updateOne({ _id: object._id }, object).then(res => {
                return this.mongoGetById(object._id);
            });
        });
    };

    mongoUpdateList(objects) {
        return Promise.all(objects.map(object => {
            return this.mongoUpdate(object);
        }));
    };

    mongoDeleteById(id) {
        return this.collection.then(collection => {
            if (!id) throw new DataError({ message: "Id isn't defined." });
            if (id instanceof ObjectID == false) id = new ObjectID(id);
            return collection.deleteOne({ _id: id });
        });
    };

    mongoDelete(object) {
        return this.mongoDeleteById(object._id);
    };

    mongoDeleteList(objects) {
        return Promise.all(objects.map(object => {
            return this.mongoDelete(object);
        }));
    };
};

exports = module.exports = CrudService;

<commit_msg>fic default options<commit_after>/*!
 * qwebs-mongo
 * Copyright(c) 2017 Benoît Claveau <benoit.claveau@gmail.com> / CABASI
 * MIT Licensed
 */
"use strict";

const DataError = require("qwebs").DataError;
const ObjectID = require('mongodb').ObjectID;
const ToArray = require("qwebs").ToArray;
const MongoService = require("../qwebs-mongo");
const pluralize = require('pluralize');

class CrudService {
    constructor(collectionName, $mongo) {
        if (!collectionName) throw new DataError({ message: "collectionName isn't defined." });
        if (!$mongo) throw new DataError({ message: "$mongo isn't defined." });
        if ($mongo instanceof MongoService) throw new DataError({ message: "$mongo isn't a MongoService." });

        this.$mongo = $mongo;
        this.collectionName = collectionName;
        this.objectName = pluralize.singular(collectionName);
    };

    /* rest ------------------------------------------------*/

    getById(request, response) {
        let id = request.params ? request.params.id : request.query ? request.query.id : null;
        throw new DataError({ message: "Id is not defined." });
        return this.mongoGetById(id).then(content => {
            return response.send({ request: request, content: content });
        });
    };

    save(request, response) {
        if (!request.body) throw new DataError({ message: "Request body is not defined." });
        return this.mongoSave(request.body).then(content => {
            return response.send({ request: request, content: content });
        });
    };

    saveList(request, response) {
        if (!request.body) throw new DataError({ message: "Request body is not defined." });
        return this.mongoSaveList(request.body).then(content => {
            return response.send({ request: request, content: content });
        });
    };

    deleteById(request, response) {
        let id = request.params ? request.params.id : request.query ? request.query.id : null;
        throw new DataError({ message: "Id is not defined." });
        return this.mongoDeleteById(id).then(content => {
            return response.send({ request: request, content: content });
        });
    };

    delete(request, response) {
        if (!request.body) throw new DataError({ message: "Request body is not defined." });
        return this.mongoDelete(request.body).then(content => {
            return response.send({ request: request, content: content });
        });
    };

    deleteList(request, response) {
        if (!request.body) throw new DataError({ message: "Request body is not defined." });
        return this.mongoDeleteList(request.body).then(content => {
            return response.send({ request: request, content: content });
        });
    };

    /* primitives ------------------------------------------*/

    get collection() {
        return this.$mongo.db.then(db => {
            return db.collection(this.collectionName);
        });
    };

    mongoGetById(id) {
        return this.collection.then(collection => {
            if (!id) throw new DataError({ message: "Id isn't defined." });
            if (id instanceof ObjectID == false) id = new ObjectID(id);
            return collection.findOne({ _id: id }).then(object => {
                if (!object) throw new DataError({ message: `${this.objectName} isn't defined.` });
                return object;
            });
        });
    };

    mongoArray(options) {
        let options = options || {};
        options.query = options.query || {};

        return this.collection.then(collection => {
            let q = this.find(options.query);
            if (options.limit) q = q.limit(options.limit);
            if (options.skip) q = q.skip(options.skip);
            if (options.sort) q = q.sort(options.sort);

            return q.ToArray();
        });
    };

    mongoStream(options) {
        let options = options || {};
        options.query = options.query || {};

        return this.collection.then(collection => {
            let q = this.find(options.query);
            if (options.limit) q = q.limit(options.limit);
            if (options.skip) q = q.skip(options.skip);
            if (options.sort) q = q.sort(options.sort);

            return q.stream();
        });
    };

    mongoSave(object) {
        return this.mongoGetById(object._id).then(previous => {
            return this.mongoUpdate(object);
        }).catch(error => {
            if (error.message != `${this.objectName} isn't defined.`) throw error;
            return this.mongoInsert(object);
        });
    };

    mongoSavetList(objects) {
        return Promise.all(objects.map(object => {
            return this.mongoSave(object);
        }));
    };

    mongoInsert(object) {
        return this.collection.then(collection => {
            delete object._id;
            return collection.insertOne(object).then(res => {
                return res.ops[0];
            });
        });
    };

    mongoInsertList(objects) {
        return Promise.all(objects.map(object => {
            return this.mongoInsert(object);
        }));
    };

    mongoUpdate(object) {
        return this.collection.then(collection => {
            if (object._id instanceof ObjectID == false) object._id = new ObjectID(object._id);
            let copy = Object.assign({}, object);
            delete copy._id;
            return collection.updateOne({ _id: object._id }, object).then(res => {
                return this.mongoGetById(object._id);
            });
        });
    };

    mongoUpdateList(objects) {
        return Promise.all(objects.map(object => {
            return this.mongoUpdate(object);
        }));
    };

    mongoDeleteById(id) {
        return this.collection.then(collection => {
            if (!id) throw new DataError({ message: "Id isn't defined." });
            if (id instanceof ObjectID == false) id = new ObjectID(id);
            return collection.deleteOne({ _id: id });
        });
    };

    mongoDelete(object) {
        return this.mongoDeleteById(object._id);
    };

    mongoDeleteList(objects) {
        return Promise.all(objects.map(object => {
            return this.mongoDelete(object);
        }));
    };
};

exports = module.exports = CrudService;

<|endoftext|>


<commit_before>/**
 * @fileOverview
 */
modules.define('shower', [
    'event.Emitter',
    'shower.Container',
    'shower.Parser',
    'shower.Player',
    'util.extend'
], function (provide, EventEmitter, Container, Parser, Player, extend) {

    /**
     * @name Shower
     * @constructor
     */
    function Shower () {
        this.events = new EventEmitter();

        this.options = null;
        this.container = null;

        this.player = null;

        this._slideParser = null;
        this._slides = [];
    }

    extend(Shower.prototype, /** @lends Shower.prototype */{
        /**
         * Init shower.
         * @param {HTMLElement} containerElement
         * @param {Object} options
         */
        init: function (containerElement, options) {
            this.options = extend({
                //default options
                parser: Parser
            }, options);

            this.container = new Container(containerElement);
            this.player = new Player(this);

            this._slideParser = new this.options.parser(containerElement);

            this._parseSlides();
            this.events.emmit('ready');
        },

        destroy: function () {
            this.container.destroy();
            this.player.destroy();

            this._slides.length = 0;
        },

        /**
         * @param {Slide | Slide[]} slide
         * @returns {Shower}
         */
        add: function (slide) {
            if (Array.isArray(slide)) {
                for (var i = 0, k = slide.length; i < k; i++) {
                    this._slides.push(slide[i]);
                }
            } else {
                this._slides.push(slide);
            }

            // TODO: ?
            // slide.setParent(this);

            this.events.emmit('slideadd');
            return this;
        },

        /**
         * @param {Slide | Number} slide
         * @returns {Shower}
         */
        remove: function (slide) {
            var slidePosition;

            if (typeof slide == 'number') {
                slidePosition = slide;
            } else if (this._slides.indexOf(slide) != -1) {
                slidePosition = this._slides.indexOf(slide);
            } else {
                throw new Error('Slide not found');
            }

            slide = this._slides.slice(slidePosition, 1);
            slide.destroy();

            this.events.emmit('slideremove');

            return this;
        },

        /**
         * @param {Number} index Slide index.
         * @returns {Slide} Slide by index.
         */
        get: function (index) {
            return this._slides[index];
        },

        /**
         * @returns {Slide[]}
         */
        getSlidesArray: function () {
            return this._slides.slice();
        },

        /**
         * @returns {Number} Slides count.
         */
        getSlidesCount: function () {
            return this._slides.length;
        },

        /**
         * @borrows shower.Player.next
         */
        next: function () {
            this.player.next();
        },

        /**
         * @borrows shower.Player.prev
         */
        prev: function () {
            this.player.prev();
        },

        _parseSlides: function () {
            this.add(this._slideParser.parse());
        }
    });

    provide(new Shower());
});
<commit_msg>[Shower] ready state<commit_after>/**
 * @fileOverview
 */
modules.define('shower', [
    'event.Emitter',
    'shower.Container',
    'shower.Parser',
    'shower.Player',
    'util.extend'
], function (provide, EventEmitter, Container, Parser, Player, extend) {

    /**
     * @name Shower
     * @constructor
     */
    function Shower () {
        this.events = new EventEmitter();

        this.options = null;
        this.container = null;

        this.player = null;

        this._slideParser = null;
        this._slides = [];

        this._isReady = false;
    }

    extend(Shower.prototype, /** @lends Shower.prototype */{
        /**
         * Init shower.
         * @param {HTMLElement} containerElement
         * @param {Object} options
         */
        init: function (containerElement, options) {
            this.options = extend({
                //default options
                parser: Parser
            }, options);

            this.container = new Container(containerElement);
            this.player = new Player(this);

            this._slideParser = new this.options.parser(containerElement);

            this._parseSlides();

            this._isReady = true;
            this.events.emmit('ready');
        },

        destroy: function () {
            this.container.destroy();
            this.player.destroy();

            this._slides.length = 0;
        },

        /**
         * @returns {Boolean}
         */
        isReady: function () {
            return this._isReady;
        },

        /**
         * @param {Slide | Slide[]} slide
         * @returns {Shower}
         */
        add: function (slide) {
            if (Array.isArray(slide)) {
                for (var i = 0, k = slide.length; i < k; i++) {
                    this._slides.push(slide[i]);
                }
            } else {
                this._slides.push(slide);
            }

            // TODO: ?
            // slide.setParent(this);

            this.events.emmit('slideadd');
            return this;
        },

        /**
         * @param {Slide | Number} slide
         * @returns {Shower}
         */
        remove: function (slide) {
            var slidePosition;

            if (typeof slide == 'number') {
                slidePosition = slide;
            } else if (this._slides.indexOf(slide) != -1) {
                slidePosition = this._slides.indexOf(slide);
            } else {
                throw new Error('Slide not found');
            }

            slide = this._slides.splice(slidePosition, 1);
            slide.destroy();

            this.events.emmit('slideremove');

            return this;
        },

        /**
         * @param {Number} index Slide index.
         * @returns {Slide} Slide by index.
         */
        get: function (index) {
            return this._slides[index];
        },

        /**
         * @returns {Slide[]}
         */
        getSlidesArray: function () {
            return this._slides.slice();
        },

        /**
         * @returns {Number} Slides count.
         */
        getSlidesCount: function () {
            return this._slides.length;
        },

        /**
         * @borrows shower.Player.next
         */
        next: function () {
            this.player.next();
        },

        /**
         * @borrows shower.Player.prev
         */
        prev: function () {
            this.player.prev();
        },

        _parseSlides: function () {
            this.add(this._slideParser.parse());
        }
    });

    provide(new Shower());
});
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var page = require('page');
var SignupForm = require('./signup-form-view');
var EmailValidationForm = require('./email-validation-form-view');
var ResendValidationEmailForm = require('./resend-validation-email-form-view');
var empty = require('empty');
var request = require('request');
var domify = require('domify');
var classes = require('classes');
var citizen = require('citizen');
var title = require('title');
var t = require('t');
var o = require('query');

page('/signup', function(ctx, next) {
  // Build form view with options
  var form = SignupForm({});

  // Display content section
  classes(document.body).add("signup-page");

  // Update page's title
  title(t('Signup'));

  // Empty container and render form
  form.replace('#content');

  // form.on('submit', function(data) {
  //   request
  //   .post('/signup')
  //   .send(data)
  //   .end(function(err, res) {
  //     if (!res.ok) {
  //       return form.errors([JSON.parse(res.text).error]);
  //     };
  //     if (err || (res.body && res.body.error)) {
  //       return form.errors([err || res.body.error]);
  //     };
  //     title(t('Signup complete'));
  //     form.showSuccess();
  //   });
  // });
});

page('/signup/validate/:token', function(ctx, next) {
  // Build form view with options
  var form = EmailValidationForm({});
  var token = ctx.params.token;
  var data = {token: token};
  request
  .post('/signup/validate')
  .send(data)
  .end(function(err, res) {
    if (!res.ok) {
       return form.errors([res.error]);
    };
    if (err || (res.body && res.body.error)) {
      return form.errors([err || res.body.error]);
    };
    window.location.replace('/signup/validated');
  });
});

page('/signup/validated', citizen.optional, function(ctx, next) {
  // Build form view with options
  var form = EmailValidationForm({});
  empty(o('#content')).appendChild(form.render());

});

page('/signup/resend-validation-email', function(ctx, next) {
  // Build form view with options
  var form = ResendValidationEmailForm({});

  // Display content section
  classes(document.body).add("signup-page");

  // Update page's title
  title(t('Resend validation email'));

  // Empty container and render form
  empty(o('#content')).appendChild(form.render());

  form.on('submit', function(data) {
    request
    .post('/signup/resend-validation-email')
    .send(data)
    .end(function(err, res) {
      if (!res.ok) {
        return form.errors([JSON.parse(res.text).error]);
      };
      if (err || (res.body && res.body.error)) {
        return form.errors([err || res.body.error]);
      };
      title(t('Resend validation email complete'));
      form.showSuccess();
    });
  });
});
<commit_msg>[signup] - Remove form logic on middleware<commit_after>/**
 * Module dependencies.
 */

var page = require('page');
var SignupForm = require('./signup-form-view');
var EmailValidationForm = require('./email-validation-form-view');
var ResendValidationEmailForm = require('./resend-validation-email-form-view');
var empty = require('empty');
var request = require('request');
var domify = require('domify');
var classes = require('classes');
var citizen = require('citizen');
var title = require('title');
var t = require('t');
var o = require('query');

page('/signup', function(ctx, next) {
  // Build form view with options
  var form = SignupForm({});

  // Display content section
  classes(document.body).add("signup-page");

  // Update page's title
  title(t('Signup'));

  // Empty container and render form
  form.replace('#content');
});

page('/signup/validate/:token', function(ctx, next) {
  // Build form view with options
  var form = EmailValidationForm({});
  var token = ctx.params.token;
  var data = {token: token};
  request
  .post('/signup/validate')
  .send(data)
  .end(function(err, res) {
    if (!res.ok) {
       return form.errors([res.error]);
    };
    if (err || (res.body && res.body.error)) {
      return form.errors([err || res.body.error]);
    };
    window.location.replace('/signup/validated');
  });
});

page('/signup/validated', citizen.optional, function(ctx, next) {
  // Build form view with options
  var form = EmailValidationForm({});
  empty(o('#content')).appendChild(form.render());

});

page('/signup/resend-validation-email', function(ctx, next) {
  // Build form view with options
  var form = ResendValidationEmailForm({});

  // Display content section
  classes(document.body).add("signup-page");

  // Update page's title
  title(t('Resend validation email'));

  // Empty container and render form
  empty(o('#content')).appendChild(form.render());

  form.on('submit', function(data) {
    request
    .post('/signup/resend-validation-email')
    .send(data)
    .end(function(err, res) {
      if (!res.ok) {
        return form.errors([JSON.parse(res.text).error]);
      };
      if (err || (res.body && res.body.error)) {
        return form.errors([err || res.body.error]);
      };
      title(t('Resend validation email complete'));
      form.showSuccess();
    });
  });
});
<|endoftext|>


<commit_before>
var main = null;

exports.init = function(mainApp) {
  main = mainApp;

  main.addEndpoint("/api/champion/:championId", getChampionStats);
}

function getChampionStats(req, res, next) {
  var champion_id = req.params.championId;
  var promises = [];
  promises.push(getChampionData(champion_id));
  promises.push(getCountableStats(champion_id));
  promises.push(getMasteryDistribution(champion_id));
  promises.push(getMaxGradeDistribution(champion_id));
  promises.push(getPercentSumsChestGranted(champion_id));
  promises.push(getTop10PlayersPerChamp(champion_id));
  promises.push(getChampionRank(champion_id));
  promises.push(getTotalPointsDistribution(champion_id));
  promises.push(getTop10HighestMastery(champion_id));
  var resultObj = {};
  Promise.all(promises).then((result) => {
    for (var i = 0; i < result.length; i++) {
      resultObj[result[i].name] = result[i].data;
    }
    res.status(200).send(resultObj);
  }).catch((err) => {
    main.logger.warn(err);
    res.status(500).send("Internal Server Error");
  });
}

function getTotalPointsDistribution(champion_id) {
    return main.database.query("select max(pts_total) as max_pts, min(pts_total) as min_pts, STDDEV(pts_total) as standard_deviation,  sum(pts_total) / count(pts_total) as avg_pts from current_mastery where champion_id = ?", [champion_id]).then((result) => {
      return {name: "totalptsstats", data: result[0]};
    });
}

function getChampionData(champion_id) {
  return main.database.query("SELECT id, name, full, sprite from champions where id = ?", [champion_id]).then((result) => {
    return {name: "data", data: result[0]};
  })
}
// avg_gains, games_played, avg_games_summoner, number_of_summoners_played last week
function getCountableStats(champion_id) {
  return main.database.query("select sum(pts_gained) / count(pts_gained) as avg_gains, count(*) as games_played, count(*)  / count(distinct summoner_id) as avg_games_summoner, count(distinct summoner_id) as summoners_played FROM gains g where champion_id = ? and game_timestamp > now() - Interval 3 day group by champion_id;", [champion_id]).then((result) => {
    return {name: "stats", data: result[0]};
  });
}

function getMasteryDistribution(champion_id) {
  var masteryDistribution = [0,0,0,0,0,0];
  return main.database.query(" select mastery_level, count(*) as cnt from current_mastery where champion_id = ? group by mastery_level;", [champion_id]).then((result) => {
    result.forEach(r => masteryDistribution[r.mastery_level] = r.cnt);
    return main.database.query("select count(*) as cnt from summoners;");
  }).then((totalSummonersResult) => {
    var elemSum = masteryDistribution.reduce((previousValue, currentValue) => previousValue + currentValue, 0);
    masteryDistribution[0] = totalSummonersResult[0].cnt - elemSum;
    var avg = masteryDistribution.reduce((previous, current, index) => {
      return previous += current * index;
    },0) / elemSum;
    return {name: "masterydistribution", data: {avg: avg, distribution: masteryDistribution} };
  });
}

function getMaxGradeDistribution(champion_id) {
  return main.database.query("select highest_grade, count(*) as cnt from current_mastery where champion_id = ? group by highest_grade" , [champion_id]).then((result) => {
    return {name: "gradedistribution", data: result};
  })
}

// percent of sums who played the champ
function getPercentSumsChestGranted(champion_id) {
  var res;
  return main.database.query("select sum(chest_granted = 1) as yes from current_mastery where champion_id = ?;", [champion_id]).then((result) => {
    res = result[0];
    return main.database.query("select count(*) as cnt from summoners;");
  }).then((sums) => {
    res.no = sums[0].cnt - res.yes;
    return {name: "percent_chest_granted", data: res};
  })
}

function getTop10HighestMastery(champion_id) {
    return main.database.query("SELECT pts_total, mastery_level, pts_next, pts_since FROM current_mastery WHERE champion_id = ? group by summoner_id ORDER BY pts_total DESC LIMIT 10", [champion_id]).then((result) => {
      return {name: "top10HighestMastery", data: result};
    })
}

function getTop10PlayersPerChamp(champion_id) {
  return main.database.query("SELECT s.summoner_name as name, s.summoner_id as id, MAX(pts_total) as total, MAX(pts_gained) as max, MIN(pts_gained) as min, SUM(pts_gained) / COUNT(pts_gained) as avg FROM gains g, summoners s where g.pts_gained is not null and s.summoner_id = g.summoner_id and g.game_timestamp > now() - interval 3 day and g.champion_id = ? group by g.summoner_id order by avg desc LIMIT 10", [champion_id]).then((result) => {
    var outputVal = [];
    for (var i = 0; i < result.length; i++) {
      var current = result[i];
      outputVal.push({rank: i+1, id: current.id, name: current.name, change: current.avg, total: current.total, max: current.max, min: current.min})
    }
    return {name: "top10Players", data: outputVal};
  })
}

function getChampionRank(champion_id) {
  return main.database.query("select rank, avg_gain, games from (select @rn:=@rn+1 as rank, champion_id, avg_gain, games FROM (select @rank:=@rank+1 as rank, champion_id, sum(pts_gained)/count(pts_gained) as avg_gain, count(pts_gained) as games from gains where game_timestamp > now() - interval 3 day group by champion_id having avg_gain is not null order by avg_gain desc) t1, (select @rn:=0) t2) t3 where t3.champion_id = ?", [champion_id]).then((result) => {
    return {name: "rank", data: result[0]};
  })
}
<commit_msg>Added games played to top10players per champ endpoint<commit_after>
var main = null;

exports.init = function(mainApp) {
  main = mainApp;

  main.addEndpoint("/api/champion/:championId", getChampionStats);
}

function getChampionStats(req, res, next) {
  var champion_id = req.params.championId;
  var promises = [];
  promises.push(getChampionData(champion_id));
  promises.push(getCountableStats(champion_id));
  promises.push(getMasteryDistribution(champion_id));
  promises.push(getMaxGradeDistribution(champion_id));
  promises.push(getPercentSumsChestGranted(champion_id));
  promises.push(getTop10PlayersPerChamp(champion_id));
  promises.push(getChampionRank(champion_id));
  promises.push(getTotalPointsDistribution(champion_id));
  promises.push(getTop10HighestMastery(champion_id));
  var resultObj = {};
  Promise.all(promises).then((result) => {
    for (var i = 0; i < result.length; i++) {
      resultObj[result[i].name] = result[i].data;
    }
    res.status(200).send(resultObj);
  }).catch((err) => {
    main.logger.warn(err);
    res.status(500).send("Internal Server Error");
  });
}

function getTotalPointsDistribution(champion_id) {
    return main.database.query("select max(pts_total) as max_pts, min(pts_total) as min_pts, STDDEV(pts_total) as standard_deviation,  sum(pts_total) / count(pts_total) as avg_pts from current_mastery where champion_id = ?", [champion_id]).then((result) => {
      return {name: "totalptsstats", data: result[0]};
    });
}

function getChampionData(champion_id) {
  return main.database.query("SELECT id, name, full, sprite from champions where id = ?", [champion_id]).then((result) => {
    return {name: "data", data: result[0]};
  })
}
// avg_gains, games_played, avg_games_summoner, number_of_summoners_played last week
function getCountableStats(champion_id) {
  return main.database.query("select sum(pts_gained) / count(pts_gained) as avg_gains, count(*) as games_played, count(*)  / count(distinct summoner_id) as avg_games_summoner, count(distinct summoner_id) as summoners_played FROM gains g where champion_id = ? and game_timestamp > now() - Interval 3 day group by champion_id;", [champion_id]).then((result) => {
    return {name: "stats", data: result[0]};
  });
}

function getMasteryDistribution(champion_id) {
  var masteryDistribution = [0,0,0,0,0,0];
  return main.database.query(" select mastery_level, count(*) as cnt from current_mastery where champion_id = ? group by mastery_level;", [champion_id]).then((result) => {
    result.forEach(r => masteryDistribution[r.mastery_level] = r.cnt);
    return main.database.query("select count(*) as cnt from summoners;");
  }).then((totalSummonersResult) => {
    var elemSum = masteryDistribution.reduce((previousValue, currentValue) => previousValue + currentValue, 0);
    masteryDistribution[0] = totalSummonersResult[0].cnt - elemSum;
    var avg = masteryDistribution.reduce((previous, current, index) => {
      return previous += current * index;
    },0) / elemSum;
    return {name: "masterydistribution", data: {avg: avg, distribution: masteryDistribution} };
  });
}

function getMaxGradeDistribution(champion_id) {
  return main.database.query("select highest_grade, count(*) as cnt from current_mastery where champion_id = ? group by highest_grade" , [champion_id]).then((result) => {
    return {name: "gradedistribution", data: result};
  })
}

// percent of sums who played the champ
function getPercentSumsChestGranted(champion_id) {
  var res;
  return main.database.query("select sum(chest_granted = 1) as yes from current_mastery where champion_id = ?;", [champion_id]).then((result) => {
    res = result[0];
    return main.database.query("select count(*) as cnt from summoners;");
  }).then((sums) => {
    res.no = sums[0].cnt - res.yes;
    return {name: "percent_chest_granted", data: res};
  })
}

function getTop10HighestMastery(champion_id) {
    return main.database.query("SELECT pts_total, mastery_level, pts_next, pts_since FROM current_mastery WHERE champion_id = ? group by summoner_id ORDER BY pts_total DESC LIMIT 10", [champion_id]).then((result) => {
      return {name: "top10HighestMastery", data: result};
    })
}

function getTop10PlayersPerChamp(champion_id) {
  return main.database.query("SELECT s.summoner_name as name, s.summoner_id as id, count(pts_gained) as games,  MAX(pts_total) as total, MAX(pts_gained) as max, MIN(pts_gained) as min, SUM(pts_gained) / COUNT(pts_gained) as avg FROM gains g, summoners s where g.pts_gained is not null and s.summoner_id = g.summoner_id and g.game_timestamp > now() - interval 3 day and g.champion_id = ? group by g.summoner_id order by avg desc LIMIT 10", [champion_id]).then((result) => {
    var outputVal = [];
    for (var i = 0; i < result.length; i++) {
      var current = result[i];
      outputVal.push({rank: i+1, id: current.id, name: current.name, change: current.avg, total: current.total, games: current.games, max: current.max, min: current.min})
    }
    return {name: "top10Players", data: outputVal};
  })
}

function getChampionRank(champion_id) {
  return main.database.query("select rank, avg_gain, games from (select @rn:=@rn+1 as rank, champion_id, avg_gain, games FROM (select @rank:=@rank+1 as rank, champion_id, sum(pts_gained)/count(pts_gained) as avg_gain, count(pts_gained) as games from gains where game_timestamp > now() - interval 3 day group by champion_id having avg_gain is not null order by avg_gain desc) t1, (select @rn:=0) t2) t3 where t3.champion_id = ?", [champion_id]).then((result) => {
    return {name: "rank", data: result[0]};
  })
}
<|endoftext|>