<commit_before>const NumberGenerator = require('./numbergenerator.js');
const ConstantValue = require('./constant.config.js');

const numberGeneratorObj = new NumberGenerator();

class DataGenerator extends ConstantValue {
    constructor(str) {
        super();
        this.inputAr = [];
        this.inputDataSetAr = [];
        this.inputDataScatter = [];
        this.inputStringAr = [];
        this.finalJSON = {};
        this.finalJSONAr = [];
        this.finalJSONCategory = [];
        this.propertiesToBeAssigned = [];
        this.commandStack = [];
        // 0 - Data, 1 - DataSet, 2 - Scatter, 3 - Bubble
        this.chartType = -1;
        this.setChartType(str);
    }

    initialize() {
        this.inputAr = [];
        this.inputDataSetAr = []
        this.inputDataScatter = [];
        this.inputStringAr = [];
        this.finalJSON = {};
        this.finalJSONAr = [];
        this.finalJSONCategory = [];
        this.propertiesToBeAssigned = [];
    }

    presentIn(arr, target) {
        let i;
        for (i = 0; i < arr.length; i++) {
            if (arr[i] === target) {
                return true;
            }
        }
        return false;
    }

    setChartType(str) {
        if (str === undefined) {
            return false;
        }

        if (this.presentIn(this.chartTypeZero, str)) {
            this.chartType = 0;
        } else if (this.presentIn(this.chartTypeOne, str)) {
            this.chartType = 1;
        } else if (this.presentIn(this.chartTypeTwo, str)) {
            this.chartType = 2;
        } else if (this.presentIn(this.chartTypeThree, str)) {
            this.chartType = 3;
        } else {
            console.log('Chart type not supported.');
            return false;
        }
        numberGeneratorObj.chartType = this.chartType;
        return this.chartType;
    }

    assignProperty(property, value, location) {
        this.commandStack.push('assignProperty("'+property+'", "'+value+'", "'+location+'")');
        let ar = [];
        ar.push(property);
        ar.push(value);
        ar.push(location);

        this.propertiesToBeAssigned.push(ar);
    }

    applyProperties() {
        let i, j, k;

        for (i = 0; i < this.propertiesToBeAssigned.length; i++) {
            if (this.propertiesToBeAssigned[i][2] === 'data') {
                // console.log('data');
                if (this.finalJSON.dataset !== undefined) {
                    for (j = 0; j < this.finalJSON.dataset.length; j++) {
                        for (k = 0; k < this.finalJSON.dataset[j].data.length; k++) {
                            this.finalJSON.dataset[j].data[k][this.propertiesToBeAssigned[i][0]] = this.propertiesToBeAssigned[i][1];
                        }
                    }
                } else if (this.finalJSON.data !== undefined) {
                    for (j = 0; j < this.finalJSON.data.length; j++) {
                        this.finalJSON.data[j][this.propertiesToBeAssigned[i][0]] = this.propertiesToBeAssigned[i][1];
                    }
                }
            } else if (this.propertiesToBeAssigned[i][2] === 'dataset') {
                // console.log('dataset');
                if (this.finalJSON.dataset !== undefined) {
                    for (j = 0; j < this.finalJSON.dataset.length; j++) {
                        this.finalJSON.dataset[j][this.propertiesToBeAssigned[i][0]] = this.propertiesToBeAssigned[i][1];
                    }
                }
            } else if (this.propertiesToBeAssigned[i][2] === 'categories') {
                // console.log('categories');
                if (this.finalJSON.categories !== undefined) {
                    for (j = 0; j < this.finalJSON.categories.length; j++) {
                        this.finalJSON.categories[j][this.propertiesToBeAssigned[i][0]] = this.propertiesToBeAssigned[i][1];
                    }
                }
            } else if (this.propertiesToBeAssigned[i][2] === 'category') {
                // console.log('category')
                if (this.finalJSON.categories !== undefined) {
                    for (j = 0; j < this.finalJSON.categories.length; j++) {
                        for (k = 0; k < this.finalJSON.categories[j].category.length; k++) {
                            this.finalJSON.categories[j].category[k][this.propertiesToBeAssigned[i][0]] = this.propertiesToBeAssigned[i][1];
                        }
                    }
                }
            } else if (this.propertiesToBeAssigned[i][2] === 'chart') {
                // console.log('chart');
                this.finalJSON.chart[this.propertiesToBeAssigned[i][0]] = this.propertiesToBeAssigned[i][1];
            } else if (this.propertiesToBeAssigned[i][2] === 'json') {
                this.finalJSON[this.propertiesToBeAssigned[i][0]] = this.propertiesToBeAssigned[i][1];
            }
        }
    }

    parseData(arr) {
        let i, tempJSONdata = {};

        for (i = 0; i < arr[0].length; i++) {
            tempJSONdata = {};
            tempJSONdata['label'] = arr[1][i];
            tempJSONdata['value'] = arr[0][i] + '';
            this.finalJSONAr.push(tempJSONdata);
        }

        return this.finalJSONAr.length;
    }

    parseDataset(arr, append) {
        let i, tempAr = [],
            tempObj = {},
            tempCategory = [];

        if (arr[1].length !== 0) {
            if (this.finalJSONCategory.length > 0) {
                tempCategory = this.finalJSONCategory.pop()['category'];
            }
            // console.log(tempCategory);
            for (i = 0; i < arr[1].length; i++) {
                tempObj = {};
                tempObj['label'] = arr[1][i];
                tempCategory.push(tempObj);
            }

            tempObj = {};
            tempObj['category'] = tempCategory;
            this.finalJSONCategory.push(tempObj);
        }

        if (append === true) {
            if (this.finalJSONAr.length > 0) {
                tempAr = this.finalJSONAr.pop().data;
            }
        }

        // console.log(tempAr);
        for (i = 0; i < arr[0].length; i++) {
            tempObj = {};
            tempObj['value'] = arr[0][i] + '';
            tempAr.push(tempObj);
        }

        tempObj = {};
        tempObj['seriesname'] = 'series';
        tempObj['data'] = tempAr;

        this.finalJSONAr.push(tempObj);
    }

    parseDatasetBubble(arr, append) {
        let i, tempAr = [],
            tempObj = {};

        if (append === true) {
            if (this.finalJSONAr.length > 0) {
                tempAr = this.finalJSONAr.pop().data;
            }
        }

        for (i = 0; i < arr.length; i++) {
            tempObj = {};
            tempObj['x'] = arr[i][0] + '';
            tempObj['y'] = arr[i][1] + '';
            tempObj['z'] = arr[i][2] + '';
            tempObj['name'] = 'randomName';
            tempAr.push(tempObj);
        }

        tempObj = {};
        tempObj['seriesname'] = 'Bubbles';
        tempObj['data'] = tempAr;

        this.finalJSONAr.push(tempObj);
    }

    parseDatasetScatter(arr, append) {
        let i, tempAr = [],
            tempObj = {};

        if (append === true) {
            if (this.finalJSONAr.length > 0) {
                tempAr = this.finalJSONAr.pop().data;
            }
        }

        for (i = 0; i < arr.length; i++) {
            tempObj = {};
            tempObj['y'] = arr[i][0] + '';
            tempObj['x'] = arr[i][1] + '';
            tempAr.push(tempObj);
        }

        tempObj = {};
        tempObj['seriesname'] = 'scatter';
        tempObj['data'] = tempAr;

        this.finalJSONAr.push(tempObj);
    }

    addArray(arr, append) {
        // console.log(arr);
        if (arr === undefined || arr.length === 0) {
            return 'Array cannot be undefined or empty';
        }
        switch (this.chartType) {
            case 0:
                this.parseData(arr);
                break;
            case 1:
                this.parseDataset(arr, append);
                break;
            case 2:
                this.parseDatasetScatter(arr, append);
                break;
            case 3:
                this.parseDatasetBubble(arr, append);
                break;
            default: // do nothing.
        }
    }

    createNewPropertyOfNumber(property, _value) {
        Object.defineProperty(NumberGenerator.prototype, property, {
            value: _value
        });
    }

    modifyNumber(property, value) {
        this.commandStack.push('modifyNumber("'+property+'", "'+value+'")');
        numberGeneratorObj.modifier(property, value);
    }
    generateNumber(numberType, total, append, label) {
        this.commandStack.push('generateNumber("'+numberType+'", '+total+', '+append+ (label===undefined?')':', "'+label+'")'));
        this.addArray(numberGeneratorObj.generate(numberType, total, label), append);
    }

    getCommandStack(){
        let i;
        console.log(this.commandStack.length);
        for(i=0;i<this.commandStack.length;i++){
            console.log(this.commandStack[i]);
        }
    }
    clearCommandStack(){
        this.commandStack=[];
        return this.commandStack.length;
    }

    getJSON() {
        this.finalJSON['chart'] = {};
        if (this.chartType === 0) {
            this.finalJSON['data'] = this.finalJSONAr;
        } else if (this.chartType === 1) {
            this.finalJSON['categories'] = this.finalJSONCategory;
            this.finalJSON['dataset'] = this.finalJSONAr;
        } else if (this.chartType === 2) {
            this.finalJSON['dataset'] = this.finalJSONAr;
        } else if (this.chartType === 3) {
            this.finalJSON['dataset'] = this.finalJSONAr;
        }
        this.applyProperties();

        console.log(JSON.stringify(this.finalJSON, null, 2));
        this.initialize();
        return JSON.stringify(this.finalJSON, null, 2);
    }
}

const datageneratorObj = new DataGenerator('column2d');

// Write your code here

datageneratorObj.modifyNumber('range', '30, 200');
datageneratorObj.modifyNumber('trend', 'linear');
datageneratorObj.generateNumber('integer', 5, false, 'month_short');

// datageneratorObj.getJSON();

datageneratorObj.modifyNumber('range', '300, 500');
datageneratorObj.modifyNumber('trend', 'random');
datageneratorObj.assignProperty('abc', 'series', 'chart');

datageneratorObj.generateNumber('integer', 5, false);

datageneratorObj.getJSON();
// datageneratorObj.getCommandStack();<commit_msg>Fixed few bugs<commit_after>

const NumberGenerator = require('./numbergenerator.js');
const ConstantValue = require('./constant.config.js');

const numberGeneratorObj = new NumberGenerator();

/**
 * Class that creates a json for fusioncharts testing
 * @class DataGenerator
 * @extends {ConstantValue}
 */
class DataGenerator extends ConstantValue {

    /**
     * Creates an instance of DataGenerator.
     * @param {string} str
     * @memberof DataGenerator
     */
    constructor(str) {
        super();
        this.inputAr = [];
        this.inputDataSetAr = [];
        this.inputDataScatter = [];
        this.inputStringAr = [];
        this.finalJSON = {};
        this.finalJSONAr = [];
        this.finalJSONCategory = [];
        this.propertiesToBeAssigned = [];
        this.commandStack = [];
        // 0 - Data, 1 - DataSet, 2 - Scatter, 3 - Bubble
        this.chartType = -1;
        this.setChartType(str);
    }

    /**
     * Reset all the class members.
     * @memberof DataGenerator
     */
    initialize() {
        this.inputAr = [];
        this.inputDataSetAr = []
        this.inputDataScatter = [];
        this.inputStringAr = [];
        this.finalJSON = {};
        this.finalJSONAr = [];
        this.finalJSONCategory = [];
        this.propertiesToBeAssigned = [];
    }

    /**
     * Checks if an element is present in array
     * @param {array} arr
     * @param {string} target
     * @returns boolean
     * @memberof DataGenerator
     */
    presentIn(arr, target) {
        let i;
        for (i = 0; i < arr.length; i++) {
            if (arr[i] === target) {
                return true;
            }
        }
        return false;
    }

    /**
     * Sets chart type
     * @param {string} str
     * @returns boolean | chartType
     * @memberof DataGenerator
     */
    setChartType(str) {
        if (str === undefined) {
            return false;
        }

        if (this.presentIn(this.chartTypeZero, str)) {
            this.chartType = 0;
        } else if (this.presentIn(this.chartTypeOne, str)) {
            this.chartType = 1;
        } else if (this.presentIn(this.chartTypeTwo, str)) {
            this.chartType = 2;
        } else if (this.presentIn(this.chartTypeThree, str)) {
            this.chartType = 3;
        } else {
            console.log('Chart type not supported.');
            return false;
        }
        numberGeneratorObj.chartType = this.chartType;
        return this.chartType;
    }

    /**
     * Stores a property given by user as input.
     * @param {string} property
     * @param {string} value
     * @param {string} location
     * @memberof DataGenerator
     */
    assignProperty(property, value, location) {
        this.commandStack.push('assignProperty("'+property+'", "'+value+'", "'+location+'")');
        let ar = [];
        ar.push(property);
        ar.push(value);
        ar.push(location);

        this.propertiesToBeAssigned.push(ar);
        return ar;
    }

    /**
     * Applies/adds all properties given as input by the user.
     * @memberof DataGenerator
     */
    applyProperties() {
        let i, j, k;

        for (i = 0; i < this.propertiesToBeAssigned.length; i++) {
            if (this.propertiesToBeAssigned[i][2] === 'data') {
                // console.log('data');
                if (this.finalJSON.dataset !== undefined) {
                    for (j = 0; j < this.finalJSON.dataset.length; j++) {
                        for (k = 0; k < this.finalJSON.dataset[j].data.length; k++) {
                            this.finalJSON.dataset[j].data[k][this.propertiesToBeAssigned[i][0]] = this.propertiesToBeAssigned[i][1];
                        }
                    }
                } else if (this.finalJSON.data !== undefined) {
                    for (j = 0; j < this.finalJSON.data.length; j++) {
                        this.finalJSON.data[j][this.propertiesToBeAssigned[i][0]] = this.propertiesToBeAssigned[i][1];
                    }
                }
            } else if (this.propertiesToBeAssigned[i][2] === 'dataset') {
                // console.log('dataset');
                if (this.finalJSON.dataset !== undefined) {
                    for (j = 0; j < this.finalJSON.dataset.length; j++) {
                        this.finalJSON.dataset[j][this.propertiesToBeAssigned[i][0]] = this.propertiesToBeAssigned[i][1];
                    }
                }
            } else if (this.propertiesToBeAssigned[i][2] === 'categories') {
                // console.log('categories');
                if (this.finalJSON.categories !== undefined) {
                    for (j = 0; j < this.finalJSON.categories.length; j++) {
                        this.finalJSON.categories[j][this.propertiesToBeAssigned[i][0]] = this.propertiesToBeAssigned[i][1];
                    }
                }
            } else if (this.propertiesToBeAssigned[i][2] === 'category') {
                // console.log('category')
                if (this.finalJSON.categories !== undefined) {
                    for (j = 0; j < this.finalJSON.categories.length; j++) {
                        for (k = 0; k < this.finalJSON.categories[j].category.length; k++) {
                            this.finalJSON.categories[j].category[k][this.propertiesToBeAssigned[i][0]] = this.propertiesToBeAssigned[i][1];
                        }
                    }
                }
            } else if (this.propertiesToBeAssigned[i][2] === 'chart') {
                // console.log('chart');
                this.finalJSON.chart[this.propertiesToBeAssigned[i][0]] = this.propertiesToBeAssigned[i][1];
            } else if (this.propertiesToBeAssigned[i][2] === 'json') {
                this.finalJSON[this.propertiesToBeAssigned[i][0]] = this.propertiesToBeAssigned[i][1];
            }
        }
    }

    /**
     * Create data array
     * @param {string} arr
     * @returns length of data array
     * @memberof DataGenerator
     */
    parseData(arr) {
        let i, tempJSONdata = {};

        for (i = 0; i < arr[0].length; i++) {
            tempJSONdata = {};
            tempJSONdata['label'] = arr[1][i];
            tempJSONdata['value'] = arr[0][i] + '';
            this.finalJSONAr.push(tempJSONdata);
        }

        return this.finalJSONAr.length;
    }

    /**
     * Create a dataset array
     * @param {array} arr - Data to be processed
     * @param {boolean} append - whether the current input should be appended to the previous input
     * @memberof DataGenerator
     */
    parseDataset(arr, append) {
        let i, tempAr = [],
            tempObj = {},
            tempCategory = [];

        if (arr[1].length !== 0) {
            if (this.finalJSONCategory.length > 0) {
                tempCategory = this.finalJSONCategory.pop()['category'];
            }
            // console.log(tempCategory);
            for (i = 0; i < arr[1].length; i++) {
                tempObj = {};
                tempObj['label'] = arr[1][i];
                tempCategory.push(tempObj);
            }

            tempObj = {};
            tempObj['category'] = tempCategory;
            this.finalJSONCategory.push(tempObj);
        }

        if (append === true) {
            if (this.finalJSONAr.length > 0) {
                tempAr = this.finalJSONAr.pop().data;
            }
        }

        // console.log(tempAr);
        for (i = 0; i < arr[0].length; i++) {
            tempObj = {};
            tempObj['value'] = arr[0][i] + '';
            tempAr.push(tempObj);
        }

        tempObj = {};
        tempObj['seriesname'] = 'series';
        tempObj['data'] = tempAr;

        this.finalJSONAr.push(tempObj);
    }

    /**
     * Create dataset for bubble chart
     * @param {array} arr - Data to be processed.
     * @param {boolean} append - Whether to append the current data to the last data.
     * @memberof DataGenerator
     */
    parseDatasetBubble(arr, append) {
        let i, tempAr = [],
            tempObj = {};

        if (append === true) {
            if (this.finalJSONAr.length > 0) {
                tempAr = this.finalJSONAr.pop().data;
            }
        }

        for (i = 0; i < arr.length; i++) {
            tempObj = {};
            tempObj['x'] = arr[i][0] + '';
            tempObj['y'] = arr[i][1] + '';
            tempObj['z'] = arr[i][2] + '';
            tempObj['name'] = 'randomName';
            tempAr.push(tempObj);
        }

        tempObj = {};
        tempObj['seriesname'] = 'Bubbles';
        tempObj['data'] = tempAr;

        this.finalJSONAr.push(tempObj);
    }

    parseDatasetScatter(arr, append) {
        let i, tempAr = [],
            tempObj = {};

        if (append === true) {
            if (this.finalJSONAr.length > 0) {
                tempAr = this.finalJSONAr.pop().data;
            }
        }

        for (i = 0; i < arr.length; i++) {
            tempObj = {};
            tempObj['y'] = arr[i][0] + '';
            tempObj['x'] = arr[i][1] + '';
            tempAr.push(tempObj);
        }

        tempObj = {};
        tempObj['seriesname'] = 'scatter';
        tempObj['data'] = tempAr;

        this.finalJSONAr.push(tempObj);
    }

    addArray(arr, append) {
        // console.log(arr);
        if (arr === undefined || arr.length === 0) {
            return 'Array cannot be undefined or empty';
        }
        switch (this.chartType) {
            case 0:
                this.parseData(arr);
                break;
            case 1:
                this.parseDataset(arr, append);
                break;
            case 2:
                this.parseDatasetScatter(arr, append);
                break;
            case 3:
                this.parseDatasetBubble(arr, append);
                break;
            default: // do nothing.
        }
    }

    createNewPropertyOfNumber(property, _value) {
        Object.defineProperty(NumberGenerator.prototype, property, {
            value: _value
        });
    }

    modifyNumber(property, value) {
        this.commandStack.push('modifyNumber("'+property+'", "'+value+'")');
        numberGeneratorObj.modifier(property, value);
    }
    generateNumber(numberType, total, append, label) {
        this.commandStack.push('generateNumber("'+numberType+'", '+total+', '+append+ (label===undefined?')':', "'+label+'")'));
        this.addArray(numberGeneratorObj.generate(numberType, total, label), append);
    }

    getCommandStack(){
        let i;
        console.log(this.commandStack.length);
        for(i=0;i<this.commandStack.length;i++){
            console.log(this.commandStack[i]);
        }
    }
    clearCommandStack(){
        this.commandStack=[];
        return this.commandStack.length;
    }

    getJSON() {
        this.finalJSON['chart'] = {};
        if (this.chartType === 0) {
            this.finalJSON['data'] = this.finalJSONAr;
        } else if (this.chartType === 1) {
            this.finalJSON['categories'] = this.finalJSONCategory;
            this.finalJSON['dataset'] = this.finalJSONAr;
        } else if (this.chartType === 2) {
            this.finalJSON['dataset'] = this.finalJSONAr;
        } else if (this.chartType === 3) {
            this.finalJSON['dataset'] = this.finalJSONAr;
        }
        this.applyProperties();

        console.log(JSON.stringify(this.finalJSON, null, 2));
        this.initialize();
        return JSON.stringify(this.finalJSON, null, 2);
    }
}

const datageneratorObj = new DataGenerator('column2d');

// Write your code here

datageneratorObj.modifyNumber('range', '30, 200');
datageneratorObj.modifyNumber('trend', 'linear');
datageneratorObj.generateNumber('integer', 5, false,'generic1');

// datageneratorObj.modifyNumber('range', '30, 200');
datageneratorObj.modifyNumber('trend', 'exp');
datageneratorObj.generateNumber('integer', 5, false,'generic1');

// datageneratorObj.getJSON();

datageneratorObj.modifyNumber('range', '300, 500');
datageneratorObj.modifyNumber('trend', 'random');
// datageneratorObj.assignProperty('abc', 'series', 'chart');

datageneratorObj.generateNumber('integer', 10, false,'generic2');

datageneratorObj.getJSON();
datageneratorObj.getCommandStack();<|endoftext|>


<commit_before>var extend = require('util')._extend;
var config = require('./config.js');
var express = require('express');
var mysql = require('mysql');
var minimist = require('minimist');
var bodyParser = require('body-parser');

var options = minimist(process.argv.slice(2), {
  boolean: 'live',
  default: { live: false }
});

const PORT = 3000;

var db = mysql.createConnection( extend( config.database.test, {} ) );

db.connect(function(err){
	if(!err) {
		console.log("Database is connected ... \n\n");
	} else {
		console.error("Error connecting database ... \n\n");
	}
});

var app = express();

if(options.live)
{
	app.use(require('connect-livereload')({
		port: 35729
	}));
}

app.use(express.static('build'));
app.use(bodyParser.json());       // to support JSON-encoded bodies
//app.use(bodyParser.urlencoded({ extended: true }));	// to support URL-encoded bodies

var getList = function(task) {
	return new Promise(function(resolve, reject){
		db.query(
	    	'SELECT users.displayname AS name, turns.inserted AS date, users.id ' +
	    	'FROM tasks INNER JOIN turns on turns.task_id = tasks.id INNER JOIN USERS ON turns.user_id = users.id ' +
			'WHERE tasks.id = ? ORDER BY turns.inserted DESC',
			task, function(err, rows, fields){
				if(err) {
					reject(err);
				} else {
					resolve(rows);
				}
			});
	});
}

var getStatus = function(id, callback) {
	return new Promise(function(resolve, reject){
		db.query(
	    	'SELECT users.id AS id, users.displayname AS name, COUNT(turns.user_id) AS turns ' +
			'FROM turns ' +
			'RIGHT JOIN participants ON participants.task_id = turns.task_id and participants.user_id = turns.user_id ' +
			'INNER JOIN users ON participants.user_id = users.id ' +
			'WHERE participants.task_id = ? GROUP BY turns.user_id',
			id, function(err, rows, fields){
				if(err) {
					reject(err);
				} else {
					resolve(rows);
				}
			});
	});
};

var saveAddress = function(user, ip, callback) {
	return new Promise(function(resolve, reject){
	    db.query( 'INSERT INTO addresses SET ? ON DUPLICATE KEY UPDATE user_id = ?',
	    	[{user_id: user, ip: ip}, user], function(err, rows, fields) {
			if (err) {
				if(err.code === 'ER_DUP_ENTRY') {
					console.log('Already saved user %d address %s', user, ip);
					resolve(user);
				} else {
					console.error('Error while performing addresses query', err);
					reject(err);
				}
			} else {
				console.log('Saved user %d address %s', user, ip);
				resolve(user);
			}
		})
	});
};

var getUserId = function(ip, callback) {
	return new Promise(function(resolve, reject){
		db.query('SELECT user_id FROM addresses WHERE ip = ?', ip, function(err, rows, fields) {
			if(err) {
				console.error('Error while getting address', err);
				reject(err);
			} else {
				if(rows[0]) {
					console.log('Got user %d from address %s', rows[0].user_id, ip);
					resolve(rows[0].user_id);
				} else {
					console.warn("Didn't find user for address %s", ip);
					reject();
				}
			}
		});
	});
};

var takeTurn = function(task, user, res) {
	return new Promise(function(resolve, reject){
	    db.query( 'INSERT INTO turns SET ?', {user_id: user, task_id: task}, function(err, rows, fields) {
			if (err) {
				console.error('Error while performing turn query', err);
				reject(err);
			} else {
				resolve();
			}
	    });
	});
};

app.get('/api/list', function(req,res) {
	var userPromise = getUserId(req.ip);
	var listPromise = userPromise.then(function(){
		return getList(req.query.id);
	});

	Promise.all([userPromise, listPromise]).then(function(results){
		res.json({user: results[0], list: results[1]});
	}).catch(function(err) {
		console.error('list error', err);
		res.json({user: null, error: 'query error'});
	});
});

app.get('/api/status', function(req,res) {
	getStatus(req.query.id).then(function(rows){
		res.json({users: rows});
	}).catch(function(err){
		console.error('Error while performing status query', err);
		res.json({error: 'Query Error'});
	});
});

app.get('/api/list-status', function(req,res) {
	var userPromise = getUserId(req.ip);
	var listPromise = userPromise.then(function(){
		return getList(req.query.id);
	});
	Promise.all([userPromise, listPromise, getStatus(req.query.id)]).then(function(results){
		res.json({user: results[0], list: results[1], users: results[2]});
	}).catch(function(err){
		console.error('list-status error', err);
		res.json({error: 'query error'});
	});
});

app.post('/api/turn', function(req,res) {
	(req.body.user_id ? saveAddress(req.body.user_id, req.ip) : getUserId(req.ip)).then(function(user){
		return takeTurn(req.body.task_id, user);
	}).then(function(){
		return Promise.all([getList(req.body.task_id), getStatus(req.body.task_id)]);
	}, function(){
		console.error('failed to take turn', err);
		return Promise.all([getList(req.body.task_id), getStatus(req.body.task_id)]);
	}).then(function(results){
		console.log(results);
		res.json({list: results[0], users: results[1]});
	}).catch(function(err){
		console.error('turn error', err);
		res.json({error: 'query error'});
	});
});

var server = app.listen(PORT, function() {
	var host = server.address().address;
	var port = server.address().port;
	console.log('TurnTracker listening at http://%s:%s', host, port);
});<commit_msg>removed unnecessary log<commit_after>var extend = require('util')._extend;
var config = require('./config.js');
var express = require('express');
var mysql = require('mysql');
var minimist = require('minimist');
var bodyParser = require('body-parser');

var options = minimist(process.argv.slice(2), {
  boolean: 'live',
  default: { live: false }
});

const PORT = 3000;

var db = mysql.createConnection( extend( config.database.test, {} ) );

db.connect(function(err){
	if(!err) {
		console.log("Database is connected ... \n\n");
	} else {
		console.error("Error connecting database ... \n\n");
	}
});

var app = express();

if(options.live)
{
	app.use(require('connect-livereload')({
		port: 35729
	}));
}

app.use(express.static('build'));
app.use(bodyParser.json());       // to support JSON-encoded bodies
//app.use(bodyParser.urlencoded({ extended: true }));	// to support URL-encoded bodies

var getList = function(task) {
	return new Promise(function(resolve, reject){
		db.query(
	    	'SELECT users.displayname AS name, turns.inserted AS date, users.id ' +
	    	'FROM tasks INNER JOIN turns on turns.task_id = tasks.id INNER JOIN USERS ON turns.user_id = users.id ' +
			'WHERE tasks.id = ? ORDER BY turns.inserted DESC',
			task, function(err, rows, fields){
				if(err) {
					reject(err);
				} else {
					resolve(rows);
				}
			});
	});
}

var getStatus = function(id, callback) {
	return new Promise(function(resolve, reject){
		db.query(
	    	'SELECT users.id AS id, users.displayname AS name, COUNT(turns.user_id) AS turns ' +
			'FROM turns ' +
			'RIGHT JOIN participants ON participants.task_id = turns.task_id and participants.user_id = turns.user_id ' +
			'INNER JOIN users ON participants.user_id = users.id ' +
			'WHERE participants.task_id = ? GROUP BY turns.user_id',
			id, function(err, rows, fields){
				if(err) {
					reject(err);
				} else {
					resolve(rows);
				}
			});
	});
};

var saveAddress = function(user, ip, callback) {
	return new Promise(function(resolve, reject){
	    db.query( 'INSERT INTO addresses SET ? ON DUPLICATE KEY UPDATE user_id = ?',
	    	[{user_id: user, ip: ip}, user], function(err, rows, fields) {
			if (err) {
				if(err.code === 'ER_DUP_ENTRY') {
					console.log('Already saved user %d address %s', user, ip);
					resolve(user);
				} else {
					console.error('Error while performing addresses query', err);
					reject(err);
				}
			} else {
				console.log('Saved user %d address %s', user, ip);
				resolve(user);
			}
		})
	});
};

var getUserId = function(ip, callback) {
	return new Promise(function(resolve, reject){
		db.query('SELECT user_id FROM addresses WHERE ip = ?', ip, function(err, rows, fields) {
			if(err) {
				console.error('Error while getting address', err);
				reject(err);
			} else {
				if(rows[0]) {
					console.log('Got user %d from address %s', rows[0].user_id, ip);
					resolve(rows[0].user_id);
				} else {
					console.warn("Didn't find user for address %s", ip);
					reject();
				}
			}
		});
	});
};

var takeTurn = function(task, user, res) {
	return new Promise(function(resolve, reject){
	    db.query( 'INSERT INTO turns SET ?', {user_id: user, task_id: task}, function(err, rows, fields) {
			if (err) {
				console.error('Error while performing turn query', err);
				reject(err);
			} else {
				resolve();
			}
	    });
	});
};

app.get('/api/list', function(req,res) {
	var userPromise = getUserId(req.ip);
	var listPromise = userPromise.then(function(){
		return getList(req.query.id);
	});

	Promise.all([userPromise, listPromise]).then(function(results){
		res.json({user: results[0], list: results[1]});
	}).catch(function(err) {
		console.error('list error', err);
		res.json({user: null, error: 'query error'});
	});
});

app.get('/api/status', function(req,res) {
	getStatus(req.query.id).then(function(rows){
		res.json({users: rows});
	}).catch(function(err){
		console.error('Error while performing status query', err);
		res.json({error: 'Query Error'});
	});
});

app.get('/api/list-status', function(req,res) {
	var userPromise = getUserId(req.ip);
	var listPromise = userPromise.then(function(){
		return getList(req.query.id);
	});
	Promise.all([userPromise, listPromise, getStatus(req.query.id)]).then(function(results){
		res.json({user: results[0], list: results[1], users: results[2]});
	}).catch(function(err){
		console.error('list-status error', err);
		res.json({error: 'query error'});
	});
});

app.post('/api/turn', function(req,res) {
	(req.body.user_id ? saveAddress(req.body.user_id, req.ip) : getUserId(req.ip)).then(function(user){
		return takeTurn(req.body.task_id, user);
	}).then(function(){
		return Promise.all([getList(req.body.task_id), getStatus(req.body.task_id)]);
	}, function(){
		console.error('failed to take turn', err);
		return Promise.all([getList(req.body.task_id), getStatus(req.body.task_id)]);
	}).then(function(results){
		res.json({list: results[0], users: results[1]});
	}).catch(function(err){
		console.error('turn error', err);
		res.json({error: 'query error'});
	});
});

var server = app.listen(PORT, function() {
	var host = server.address().address;
	var port = server.address().port;
	console.log('TurnTracker listening at http://%s:%s', host, port);
});<|endoftext|>


<commit_before>var express      = require('express'),
    app          = express(),
    http         = require('http'),
    path         = require('path'),
    body         = require('body-parser'),
    cfenv        = require('cfenv'),
    ibmbluemix   = require('ibmbluemix'),
    IBMData      = require('ibmdata'),
    IBMPush      = require('ibmpush'),
    ibmcloudcode = require('ibmcloudcode'),
    Client       = require('ibmiotf'),
    namespace    = require('express-namespace');

// IBM Bluemix app id config
var config = {
    // change to real application route assigned for your application
    applicationRoute : "cierra.mybluemix.net",
    // change to real application ID generated by Bluemix for your application
    applicationId : "295033ac-e5ad-4769-bc20-9fc1711b813f"
};

// IBM Watson IoT appclient config
var appClientConfig = {
    "org": "1555wo",
    "id": "homePi",
    "domain": "internetofthings.ibmcloud.com",
    "type": "pi_cierra",
    "auth-key": "token",
    "auth-token": "2kGUBlhBx_g8Z6R-_@"
};

// init core sdk
ibmbluemix.initialize(config);
var logger = ibmbluemix.getLogger();

// initialize Watson iot connector
var appClient = new Client.IotfApplication(appClientConfig);

// all environments
app.set('host', process.env.VCAP_APP_HOST || 'localhost');
app.set('port', process.env.VCAP_APP_PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));

// init service sdks
app.use(function(req, res, next) {
    req.data = IBMData.initializeService(req);
    req.push = IBMPush.initializeService(req);
    next();
});

// connect to the IBM Watson IoT platform
appClient.connect();
console.log('IOTF is set!');

appClient.log.setLevel = 'info';

// device connect event
appClient.on('connect', function(){
    console.log('Device connected!');
});

appClient.on('error', function(){
    console.log('Error occurred');
});

// init basics for an express app
app.use(require('./lib/setup'));

var ibmconfig = ibmbluemix.getConfig();
// "Require" modules and files containing endpoints and apply the routes to our application
app.use(ibmconfig.getContextRoot(), require('./lib/staticfile'));

logger.info('mbaas context root: '+ibmconfig.getContextRoot());

app.listen(ibmconfig.getPort());
logger.info('Server started at port: '+ibmconfig.getPort());
<commit_msg>iotf settings modified<commit_after>var express      = require('express'),
    app          = express(),
    http         = require('http'),
    path         = require('path'),
    body         = require('body-parser'),
    cfenv        = require('cfenv'),
    ibmbluemix   = require('ibmbluemix'),
    IBMData      = require('ibmdata'),
    IBMPush      = require('ibmpush'),
    ibmcloudcode = require('ibmcloudcode'),
    Client       = require('ibmiotf'),
    namespace    = require('express-namespace');

// IBM Bluemix app id config
var config = {
    // change to real application route assigned for your application
    applicationRoute : "cierra.mybluemix.net",
    // change to real application ID generated by Bluemix for your application
    applicationId : "295033ac-e5ad-4769-bc20-9fc1711b813f"
};

// IBM Watson IoT appclient config
var appClientConfig = {
    "org": "1555wo",
    "id": "homePi",
    "domain": "internetofthings.ibmcloud.com",
    "type": "pi_cierra",
    "auth-key": "token",
    "auth-token": "2kGUBlhBx_g8Z6R-_@"
};

// init core sdk
ibmbluemix.initialize(config);
var logger = ibmbluemix.getLogger();

// initialize Watson iot connector
var appClient = new Client.IotfApplication(appClientConfig);

// all environments
app.set('host', process.env.VCAP_APP_HOST || 'localhost');
app.set('port', process.env.VCAP_APP_PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));

// init service sdks
app.use(function(req, res, next) {
    req.data = IBMData.initializeService(req);
    req.push = IBMPush.initializeService(req);
    next();
});

// connect to the IBM Watson IoT platform
appClient.connect();
console.log('IOTF is set!');

appClient.log.setLevel = 'info';

// // device connect event
// appClient.on('connect', function(){
//     console.log('Device connected!');
// });

// appClient.on('error', function(){
//     console.log('Error occurred');
// });

// init basics for an express app
app.use(require('./lib/setup'));

var ibmconfig = ibmbluemix.getConfig();
// "Require" modules and files containing endpoints and apply the routes to our application
app.use(ibmconfig.getContextRoot(), require('./lib/staticfile'));

logger.info('mbaas context root: '+ibmconfig.getContextRoot());

app.listen(ibmconfig.getPort());
logger.info('Server started at port: '+ibmconfig.getPort());
<|endoftext|>


<commit_before>const express = require('express');
const app = express();
const proxy = require('http-proxy-middleware');
const nano = require('nano')('http://couchdb:5984'),
    simpleshelfDB = nano.use('simpleshelf-dev-personal');

const port = process.env.PORT || 8080;

app.use('/', express.static('output-public'));
app.get('/simpleshelf', (req, res) => {
    nano.db.list(function(err, body) {
        if (err) {
            console.warn(err);
            res.send('Error when retrieving current databases.');
        } else {
            // body is an array
            body.forEach(function(db) {
                console.log(db);
            });
            res.send('Listed current databases to console.');
        }
    });
});

/*app.all('*', (req, res) => {
    // res.send(`Hello world, from ${req.path} route`);
    console.info(`Rec'd ${req.method} method from ${req.path} path`);
    res.send('!!');
});*/

app.use('/api', proxy({
    target: 'http://couchdb:5984',
    changeOrigin: true,
    pathRewrite: {
        '^/api' : ''           // remove base path
    },
    logLevel: 'debug'
}));

app.listen(8080, () => console.log(`Example app listening on port ${port}!!!`));
<commit_msg>Use config for server, update /api, /auth proxies<commit_after>const config = require('config');
const express = require('express');
const app = express();
const proxy = require('http-proxy-middleware');
console.info('NODE_ENV: ' + config.util.getEnv('NODE_ENV'));
console.info('[couchdbServer]', config.get('couchdbServer'), '[databaseName]', config.get('databaseName'));
const nano = require('nano')(config.get('couchdbServer')),
    simpleshelfDB = nano.use(config.get('databaseName'));

const port = process.env.PORT || 8080;
const baseProxy = {
    target: config.get('couchdbServer'),
    changeOrigin: true,
    logLevel: 'debug'
};

app.use('/', express.static('output-public'));
app.get('/simpleshelf', (req, res) => {
    nano.db.list(function(err, body) {
        if (err) {
            console.warn(err);
            res.send('Error when retrieving current databases.');
        } else {
            // body is an array
            body.forEach(function(db) {
                console.log(db);
            });
            res.send('Listed current databases to console.');
        }
    });
});

/*app.all('*', (req, res) => {
    // res.send(`Hello world, from ${req.path} route`);
    console.info(`Rec'd ${req.method} method from ${req.path} path`);
    res.send('!!');
});*/

app.use('/auth', proxy(Object.assign({}, baseProxy, {
    pathRewrite: {
        '^/auth' : ''           // remove base path
    }
})));

app.use('/api', proxy(Object.assign({}, baseProxy, {
    target: config.get('couchdbServer') + '/' + config.get('databaseName'),
    pathRewrite: {
        '^/api' : ''           // remove base path
    }
})));

app.listen(8080, () => console.log(`Example app listening on port ${port}!!!`));
<|endoftext|>


<commit_before>var net = require("net");
var express = require("express");
var bodyParser = require("body-parser");
var config = require('./config');

var app;

// Create a simple server
var server = net.createServer(function (conn) {

    app = express();

    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());

    conn.on("error", function(err) {
      console.log("Connection Closed: " + err.stack);
      exp_server.close();
    });

    conn.on('end', function() {
      console.log("Connection Closed Properly");
      exp_server.close();
    });

    // Handle data from client
    conn.on("data", function(data) {
        data = JSON.parse(data);
        conn.write(JSON.stringify({response: "Received Message: " + data.response}))
    });

    // Let's response with a hello message
    conn.write(
        JSON.stringify(
            { response: "Hey there client!" }
        )
    );

    app.post('/command', function(req, res) {
      conn.write(JSON.stringify({response: req.body.command}));
	  console.log(req.body.command);
      res.end("yes");
    });

    var exp_server = app.listen(config.PORT_APP, function() {
      console.log("Express started");
    });
});

// Listen for connections
server.listen(config.PORT_NET,
  config.ALLOWED_IPS,
  config.HOST,
  function () {
    console.log("Server: Listening");
});
<commit_msg>Fix multiple connection issues<commit_after>var net = require("net");
var express = require("express");
var bodyParser = require("body-parser");
var config = require('./config');

var app;

// Create a simple server
var server = net.createServer(function (conn) {

    conn.on("error", function(err) {
      console.log("Connection Closed: " + err.stack);
      exp_server.close();
	  server.close();
	  server.listen(config.PORT_NET,
		  config.ALLOWED_IPS,
		  config.HOST,
		  function () {
			console.log("Server: Listening");
		});
		app = express();
		conn.destroy();
    });

    conn.on('end', function() {
      console.log("Connection Closed Properly");
	  conn.destroy();
      exp_server.close();
    });

    // Handle data from client
    conn.on("data", function(data) {
        data = JSON.parse(data);
        conn.write(JSON.stringify({response: "Received Message: " + data.response}))
    });

    // Let's response with a hello message
    conn.write(
        JSON.stringify(
            { response: "Hey there client!" }
        )
    );

	conn.pipe(conn);

	app = express();

    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());

	var exp_server = app.listen(config.PORT_APP, function() {
      console.log("Express started");
    });

    app.post('/command', function(req, res) {
      conn.write(JSON.stringify({response: req.body.command}));
	  console.log(req.body.command);
      res.end("yes");
    });

});

// Listen for connections
server.listen(config.PORT_NET,
  config.ALLOWED_IPS,
  config.HOST,
  function () {
    console.log("Server: Listening");
});
<|endoftext|>


<commit_before>
// internal libs
import Eventhandler from '../libs/eventhandler';

/**
 * on (EventHandler)
 * @param  {Any} ...args
 * @return {Function}
 */
export default function on(eventDomain) {

	if(!eventDomain){
		throw new Error('Please pass an event type e.g "click"');
	}

	return (target, method, descriptor) => {

		// register events
		on.helper.registerEvent(target, eventDomain, method, descriptor.value);

		// define $onCreated callbacks
		if(!target.$onCreated) {
			target.$onCreated = [];
		}

		// ensure "registerOnCreatedCallback" called once
		if(target.$onCreated.length > 0){
			return;
		}

		on.helper.registerOnCreatedCallback(target, ( domNode ) => {

			let eventHandler = Eventhandler.create({
				events: domNode.$appDecorators.on.events,
				element: domNode,
			});

			// define namespace for eventhandler
			domNode.$ ? null : domNode.$ = {};
			domNode.$.eventHandler = eventHandler;

		});

		on.helper.registerOnDetachedCallback(target, (domNode) => {

			// cleanup: remove all eventhandler
			domNode.$.eventHandler.reset();
			domNode.$.eventHandler = null;

		});

	}
}

/*****************************************
 * ########## Decorator Helper ###########
 *****************************************/

// define namespace
on.helper = {};

/**
 * Helper for registering events
 * @param  {String} event
 * @param  {Function} callback
 * @return {Function} target
 */
on.helper.registerEvent = (target, eventDomain, method, callback = function(){}) => {

	// define namespaces
	on.helper.registerNamespaces(target);

	if(target.$appDecorators.on.events[eventDomain]) {
		throw new Error(`The method: "${method}" already exists!`);
	}

	// define events
	target.$appDecorators.on.events[eventDomain] = callback;

	return target;

};

/**
 * Register on created callback
 * @param  {Object} target
 * @param  {Function} callback
 * @return {Function} target
 */
on.helper.registerOnCreatedCallback = (target, callback) => {

	// init render engine
	target.$onCreated.push(callback);

	return target;

};

/**
 * Register on Detached callback
 * @param  {Object} target
 * @param  {Function} callback
 * @return {Function} target
 */
on.helper.registerOnDetachedCallback = (target, callback) => {

	// define $onCreated callbacks
	if(!target.$onDetached) {
		target.$onDetached = [];
	}

	// init render engine
	target.$onDetached.push(callback);

	return target;

};

/**
 * Register namespace of on decorator
 * @param  {Function|Objet} target
 * @return {Function} target
 */
on.helper.registerNamespaces = (target) => {

	// if namespace already exists do nothing
	if(target.$appDecorators && target.$appDecorators.on){
		return target;
	}

	// define namespace
	if(!target.$appDecorators){
		target.$appDecorators = {};
	}
	if(!target.$appDecorators.on){
		target.$appDecorators.on = {
			events : {},
		};
	}

	return target;
};
<commit_msg>decorators/on.js: improved documentation for critical place<commit_after>
// internal libs
import Eventhandler from '../libs/eventhandler';

/**
 * on (EventHandler)
 * @param  {Any} ...args
 * @return {Function}
 */
export default function on(eventDomain) {

	if(!eventDomain){
		throw new Error('Please pass an event type e.g "click"');
	}

	return (target, method, descriptor) => {

		// register events
		on.helper.registerEvent(target, eventDomain, method, descriptor.value);

		// define $onCreated callbacks
		if(!target.$onCreated) {
			target.$onCreated = [];
		}

		/**
		 * ### Ensure "registerOnCreatedCallback" (see below) registered only once ###
		 * This function will called every time if an event registered e.g. @on('click .foo')
		 * but registerOnCreatedCallback can only call once because we want only Create
		 * one eventhandler
		 */
		if(target.$onCreated.length > 0){
			return;
		}

		on.helper.registerOnCreatedCallback(target, ( domNode ) => {

			let eventHandler = Eventhandler.create({
				events: domNode.$appDecorators.on.events,
				element: domNode,
			});

			// define namespace for eventhandler
			domNode.$ ? null : domNode.$ = {};
			domNode.$.eventHandler = eventHandler;

		});

		on.helper.registerOnDetachedCallback(target, (domNode) => {

			// cleanup: remove all eventhandler
			domNode.$.eventHandler.reset();
			domNode.$.eventHandler = null;

		});

	}
}

/*****************************************
 * ########## Decorator Helper ###########
 *****************************************/

// define namespace
on.helper = {};

/**
 * Helper for registering events
 * @param  {String} event
 * @param  {Function} callback
 * @return {Function} target
 */
on.helper.registerEvent = (target, eventDomain, method, callback = function(){}) => {

	// define namespaces
	on.helper.registerNamespaces(target);

	if(target.$appDecorators.on.events[eventDomain]) {
		throw new Error(`The method: "${method}" already exists!`);
	}

	// define events
	target.$appDecorators.on.events[eventDomain] = callback;

	return target;

};

/**
 * Register on created callback
 * @param  {Object} target
 * @param  {Function} callback
 * @return {Function} target
 */
on.helper.registerOnCreatedCallback = (target, callback) => {

	// init render engine
	target.$onCreated.push(callback);

	return target;

};

/**
 * Register on Detached callback
 * @param  {Object} target
 * @param  {Function} callback
 * @return {Function} target
 */
on.helper.registerOnDetachedCallback = (target, callback) => {

	// define $onCreated callbacks
	if(!target.$onDetached) {
		target.$onDetached = [];
	}

	// init render engine
	target.$onDetached.push(callback);

	return target;

};

/**
 * Register namespace of on decorator
 * @param  {Function|Objet} target
 * @return {Function} target
 */
on.helper.registerNamespaces = (target) => {

	// if namespace already exists do nothing
	if(target.$appDecorators && target.$appDecorators.on){
		return target;
	}

	// define namespace
	if(!target.$appDecorators){
		target.$appDecorators = {};
	}
	if(!target.$appDecorators.on){
		target.$appDecorators.on = {
			events : {},
		};
	}

	return target;
};
<|endoftext|>


<commit_before>var url = require("url");
var express = require("express");
var bodyParser = require("body-parser");
var path = require('path');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);

var roomStates = {};
var port = process.env.PORT || 3000;
var USERNAMES = ["( ͡° ͜ʖ ͡°)", "ಠ_ಠ", "Harambe", "Hugh Mungus", "Tuck Frump", "Kappa", "Pat", "Terry", "Frankie", "Tyler", "Dakota", "Sam", "Peyton", "Logan", "Jordan", "Hayden", "Stevie", "Jesse", "Devon", "Jamie", "Jaden"]

server.listen(port, function () {
    console.log('Server listening at port %d', port);
});

app.use(bodyParser.json());
app.use(express.static(path.resolve("app")));

app.get("/", function (req,res){
    res.sendFile("index.html",{ root: __dirname + "/../app" });
});

app.get("/[a-z]{4}/", function(req,res,next){
    var room = get_url(req.url);
    res.sendFile("index.html",{ root: __dirname + "/../app" });
});

io.on('connection', function (socket) {

    var id;
    var username;
    var addedUser = false;
    var room;

    // when the client emits 'new message', this listens and executes
    socket.on('new message', function (data) {
        // we tell the client to execute 'new message'
        socket.to(room).broadcast.emit('new message', {
            username: username,
            message: data
        });
    });

    // when the client emits 'add user', this listens and executes
    socket.on('add user', function (path) {
        room = path;
        if(roomStates[room] == null) {
            roomStates[room] = {'numUsers':0, 'currentIds':{}};
        }
        socket.join(room);
        if(roomStates[room].numUsers >= USERNAMES.length) {
            socket.emit('denied', 'Room is full.');
            return;
        }

        id = nextId(room);
        roomStates[room].currentIds[id] = socket.id;
        username = USERNAMES[id];
        if (addedUser) return;

        roomStates[room].numUsers++;
        addedUser = true;
        socket.emit('login', {
            username: username,
            numUsers: roomStates[room].numUsers
        });
        // echo globally (all clients) that a person has connected
        socket.to(room).broadcast.emit('user joined', {
            username: username,
            numUsers: roomStates[room].numUsers
        });
    });

    // when the client emits 'typing', we broadcast it to others
    socket.on('typing', function () {
        socket.to(room).broadcast.emit('typing', {
            username: username
        });
    });

    // when the client emits 'stop typing', we broadcast it to others
    socket.on('stop typing', function () {
        socket.to(room).broadcast.emit('stop typing', {
            username: username
        });
    });

    // when the user disconnects.. perform this
    socket.on('disconnect', function () {
        if (addedUser) {
            roomStates[room].numUsers--;
            //remove id from room state

            //roomStates[room].currentIds.splice(roomStates[room].currentIds.indexOf(id), 1);
            delete roomStates[room].currentIds.id;
            // echo globally that this client has left
            socket.to(room).broadcast.emit('user left', {
                username: username,
                numUsers: roomStates[room].numUsers
            });
            if(roomStates[room].numUsers <= 0) {
                delete roomStates[room];
            }
        }
    });

    // a user starts a game and transitions into game mode
    socket.on('requestGameVote', function(){

        io.to(room).emit('transitionToGame');

        myRoom = roomStates[room];

        users = [];

        for(var ids in myRoom.currentIds){
            users.push(ids);
        }

        var hostId = users[Math.floor(Math.random() * users.length)];

        io.sockets.connected[myRoom.currentIds[hostId]].emit('pickTopic');
    });

    socket.on('topicPicked', function(topic){

        myRoom = roomStates[room];

        users = [];

        for(var ids in myRoom.currentIds){
            if(ids != id)
                users.push(ids);
        };

        var teamNum = 1;

        var teamMap = {};

        var room1 = room + ":1";
        var room2 = room + ":2";

        while(users.length > 0){

            i = Math.floor(Math.random() * users.length);
            var memberId = users[i];
            users.splice(i, 1);
            teamMap[memberId] = teamNum;

            if(teamNum == 1){
                io.sockets.connected[myRoom.currentIds[memberId]].join(room1);
                teamNum = 2;
            }
            else{
                io.sockets.connected[myRoom.currentIds[memberId]].join(room2);
                teamNum = 1;
            }
        }

        socket.broadcast.to(room1).emit('beginDrawing', {'topic' :topic, 'team' : '1'});
        socket.broadcast.to(room2).emit('beginDrawing', {'topic' :topic, 'team' : '2'});

        socket.join(room1);
        socket.join(room2);
    });
});

var nextId = function(room) {
    var r;
    while (true) {
        r = Math.trunc(Math.random() * USERNAMES.length);
        if(roomStates[room].currentIds.r == null) {
            return r;
        }
    }
}

var get_url = function(x) {
    var path = url.parse(x).pathname;
    return path.split("/")[1];
};
<commit_msg>Bug fix<commit_after>var url = require("url");
var express = require("express");
var bodyParser = require("body-parser");
var path = require('path');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);

var roomStates = {};
var port = process.env.PORT || 3000;
var USERNAMES = ["( ͡° ͜ʖ ͡°)", "ಠ_ಠ", "Harambe", "Hugh Mungus", "Tuck Frump", "Kappa", "Pat", "Terry", "Frankie", "Tyler", "Dakota", "Sam", "Peyton", "Logan", "Jordan", "Hayden", "Stevie", "Jesse", "Devon", "Jamie", "Jaden"]

server.listen(port, function () {
    console.log('Server listening at port %d', port);
});

app.use(bodyParser.json());
app.use(express.static(path.resolve("app")));

app.get("/", function (req,res){
    res.sendFile("index.html",{ root: __dirname + "/../app" });
});

app.get("/[a-z]{4}/", function(req,res,next){
    var room = get_url(req.url);
    res.sendFile("index.html",{ root: __dirname + "/../app" });
});

io.on('connection', function (socket) {

    var id;
    var username;
    var addedUser = false;
    var room;

    // when the client emits 'new message', this listens and executes
    socket.on('new message', function (data) {
        // we tell the client to execute 'new message'
        socket.to(room).broadcast.emit('new message', {
            username: username,
            message: data
        });
    });

    // when the client emits 'add user', this listens and executes
    socket.on('add user', function (path) {
        room = path;
        if(roomStates[room] == null) {
            roomStates[room] = {'numUsers':0, 'currentIds':{}};
        }
        socket.join(room);
        if(roomStates[room].numUsers >= USERNAMES.length) {
            socket.emit('denied', 'Room is full.');
            return;
        }

        id = nextId(room);
        roomStates[room].currentIds[id] = socket.id;
        username = USERNAMES[id];
        if (addedUser) return;

        roomStates[room].numUsers++;
        addedUser = true;
        socket.emit('login', {
            username: username,
            numUsers: roomStates[room].numUsers
        });
        // echo globally (all clients) that a person has connected
        socket.to(room).broadcast.emit('user joined', {
            username: username,
            numUsers: roomStates[room].numUsers
        });
    });

    // when the client emits 'typing', we broadcast it to others
    socket.on('typing', function () {
        socket.to(room).broadcast.emit('typing', {
            username: username
        });
    });

    // when the client emits 'stop typing', we broadcast it to others
    socket.on('stop typing', function () {
        socket.to(room).broadcast.emit('stop typing', {
            username: username
        });
    });

    // when the user disconnects.. perform this
    socket.on('disconnect', function () {
        if (addedUser) {
            roomStates[room].numUsers--;
            //remove id from room state

            //roomStates[room].currentIds.splice(roomStates[room].currentIds.indexOf(id), 1);
            delete roomStates[room].currentIds.id;
            // echo globally that this client has left
            socket.to(room).broadcast.emit('user left', {
                username: username,
                numUsers: roomStates[room].numUsers
            });
            if(roomStates[room].numUsers <= 0) {
                delete roomStates[room];
            }
        }
    });

    // a user starts a game and transitions into game mode
    socket.on('requestGameVote', function(){

        io.to(room).emit('transitionToGame');

        myRoom = roomStates[room];

        users = [];

        for(var ids in myRoom.currentIds){
            users.push(ids);
        }

        var hostId = users[Math.floor(Math.random() * users.length)];

        io.sockets.connected[myRoom.currentIds[hostId]].emit('pickTopic');
    });

    socket.on('topicPicked', function(topic){

        myRoom = roomStates[room];

        users = [];

        for(var ids in myRoom.currentIds){
            if(ids != id)
                users.push(ids);
        };

        var teamNum = 1;

        var teamMap = {};

        var room1 = room + ":1";
        var room2 = room + ":2";

        while(users.length > 0){

            i = Math.floor(Math.random() * users.length);
            var memberId = users[i];
            users.splice(i, 1);
            teamMap[memberId] = teamNum;

            if(teamNum == 1){
                io.sockets.connected[myRoom.currentIds[memberId]].join(room1);
                teamNum = 2;
            }
            else{
                io.sockets.connected[myRoom.currentIds[memberId]].join(room2);
                teamNum = 1;
            }
        }

        socket.broadcast.to(room1).emit('beginDrawing', {'topic' :topic, 'team' : '1'});
        socket.broadcast.to(room2).emit('beginDrawing', {'topic' :topic, 'team' : '2'});

        socket.join(room1);
        socket.join(room2);
    });
});

var nextId = function(room) {
    var r;
    while (true) {
        r = Math.trunc(Math.random() * USERNAMES.length);
        if(roomStates[room].currentIds[r] == null) {
            return r;
        }
    }
}

var get_url = function(x) {
    var path = url.parse(x).pathname;
    return path.split("/")[1];
};
<|endoftext|>


<commit_before>var ConnectionEndpoint = require( './message/connection-endpoint' ),
	MessageProcessor = require( './message/message-processor' ),
	MessageDistributor = require( './message/message-distributor' ),
	DataTransforms = require( './message/data-transforms' ),
	EventHandler = require( './event/event-handler' ),
	EventEmitter = require( 'events' ).EventEmitter,
	messageParser = require( './message/message-parser' ),
	readMessage = require( './utils/read-message' ),
	util = require( 'util' ),
	utils = require( './utils/utils' ),
	defaultOptions = require( './default-options' ),
	RpcHandler = require( './rpc/rpc-handler' ),
	RecordHandler = require( './record/record-handler' ),
	WebRtcHandler = require( './webrtc/webrtc-handler' ),
	DependencyInitialiser = require( './utils/dependency-initialiser' ),
	C = require( './constants/constants' );

require( 'colors' );

/**
 * Deepstream is a realtime data server that scales horizontally
 * by running in clusters of interacting nodes
 *
 * @copyright 2015 Hoxton-One Ltd.
 * @author Wolfram Hempel
 * @version <version>
 *
 * @constructor
 */
var Deepstream = function() {
	this.isRunning = false;
	this.constants = C;
	this._options = defaultOptions.get();
	this._connectionEndpoint = null;
	this._engineIo = null;
	this._messageProcessor = null;
	this._messageDistributor = null;
	this._eventHandler = null;
	this._rpcHandler = null;
	this._recordHandler = null;
	this._webRtcHandler = null;
	this._initialised = false;
	this._plugins = [
		'messageConnector',
		'storage',
		'cache',
		'logger',
		'permissionHandler' //TODO: This now requires the permissionHandler to have a ready flag / emit events
	];
};

util.inherits( Deepstream, EventEmitter );

/**
 * Sets the name of the process
 *
 * @type {String}
 */
process.title = 'deepstream server';

/**
 * Expose constants to allow consumers to access them without
 * requiring a reference to a deepstream instance.
 *
 *
*/
Deepstream.constants = C;

/**
 * Utility method to return a helper object to simplify permissions assertions
 *
 * @param  {object} message description
 * @return {object}         description
 */
Deepstream.readMessage = readMessage;

/**
 * Set a deepstream option. For a list of all available options
 * please see default-options.
 *
 * @param {String} key   the name of the option
 * @param {Mixed} value  the value, e.g. a portnumber for ports or an instance of a logger class
 *
 * @public
 * @returns {void}
 */
Deepstream.prototype.set = function( key, value ) {
	if( this._options[ key ] === undefined ) {
		throw new Error( 'Unknown option "' + key + '"' );
	}

	this._options[ key ] = value;
};

/**
 * Starts up deepstream. The startup process has three steps:
 *
 * - Initialise all dependencies (cache connector, message connector, storage connector and logger)
 * - Instantiate the messaging pipeline and record-, rpc- and event-handler
 * - Start TCP and HTTP server
 *
 * @public
 * @returns {void}
 */
Deepstream.prototype.start = function() {
	this._showStartLogo();

	if( this._options.logger.isReady ) {
		this._options.logger.setLogLevel( this._options.logLevel );
		this._options.logger._$useColors = this._options.colors;
	}

	if( this._options.dataTransforms ) {
		this._options.dataTransforms = new DataTransforms( this._options.dataTransforms );
	}

	var i,
		initialiser;

	for( i = 0; i < this._plugins.length; i++ ) {
		initialiser = new DependencyInitialiser( this._options, this._plugins[ i ] );
		initialiser.once( 'ready', this._checkReady.bind( this, this._plugins[ i ], initialiser.getDependency() ));
	}
};

/**
 * Stops the server and closes all connections. The server can be started again,
 * but all clients have to reconnect. Will emit a 'stopped' event once done
 *
 * @public
 * @returns {void}
 */
Deepstream.prototype.stop = function() {
	var i,
		plugin,
		closables = [ this._connectionEndpoint ];

	for( i = 0; i < this._plugins.length; i++ ) {
		plugin = this._options[ this._plugins[ i ] ];
		if( typeof plugin.close === 'function' ) {
			closables.push( plugin );
			setTimeout( plugin.close.bind( plugin ) );
		}
	}

	this._initialised = false;
	utils.combineEvents( closables, 'close', this._onStopped.bind( this ) );
	this._connectionEndpoint.close();
};

/**
 * Expose the message-parser's convertTyped method
 * so that it can be used within permissionHandlers
 *
 * @param   {String} value A String starting with a type identifier (see C.TYPES)
 *
 * @public
 * @returns {mixed} the converted value
 */
Deepstream.prototype.convertTyped = function( value ) {
	return messageParser.convertTyped( value );
};

/**
 * Callback for the final stop event
 *
 * @private
 * @returns {void}
 */
Deepstream.prototype._onStopped = function() {
	this.isRunning = false;
	this.emit( 'stopped' );
};

/**
 * Shows a giant ASCII art logo which is absolutely crucial
 * for the proper functioning of the server
 *
 * @private
 * @returns {void}
 */
Deepstream.prototype._showStartLogo = function() {
	if( this._options.showLogo !== true ) {
		return;
	}

	var logo =
	' _____________________________________________________________________________\n'+
	'                                                                              \n'+
	'         /                                                             ,      \n'+
	' ----__-/----__----__------__---__--_/_---)__----__----__---_--_-----------__-\n'+
	'   /   /   /___) /___)   /   ) (_ ` /    /   ) /___) /   ) / /  )    /   /   )\n'+
	' _(___/___(___ _(___ ___/___/_(__)_(_ __/_____(___ _(___(_/_/__/__o_/___(___/_\n'+
	'                       /                                                      \n'+
	'                      /                                                       \n'+
	'=============================== STARTING... ==================================\n';

	process.stdout.write( this._options.colors ? logo.yellow : logo );
};

/**
 * Invoked once all dependencies are initialised. Instantiates the messaging pipeline and the various handlers.
 * The startup sequence will be complete once the connection endpoint is started and listening
 *
 * @private
 * @returns {void}
 */
Deepstream.prototype._init = function() {
	this._connectionEndpoint = new ConnectionEndpoint( this._options, this._onStarted.bind( this ) );
	this._messageProcessor = new MessageProcessor( this._options );
	this._messageDistributor = new MessageDistributor( this._options );
	this._connectionEndpoint.onMessage = this._messageProcessor.process.bind( this._messageProcessor );

	this._eventHandler = new EventHandler( this._options );
	this._messageDistributor.registerForTopic( C.TOPIC.EVENT, this._eventHandler.handle.bind( this._eventHandler ) );

	this._rpcHandler = new RpcHandler( this._options );
	this._messageDistributor.registerForTopic( C.TOPIC.RPC, this._rpcHandler.handle.bind( this._rpcHandler ) );

	this._webRtcHandler = new WebRtcHandler( this._options );
	this._messageDistributor.registerForTopic( C.TOPIC.WEBRTC, this._webRtcHandler.handle.bind( this._webRtcHandler ) );

	this._recordHandler = new RecordHandler( this._options );
	this._messageDistributor.registerForTopic( C.TOPIC.RECORD, this._recordHandler.handle.bind( this._recordHandler ) );

	this._messageProcessor.onAuthenticatedMessage = this._messageDistributor.distribute.bind( this._messageDistributor );

	this._initialised = true;
};

/**
 * Called whenever a dependency emits a ready event. Once all dependencies are ready
 * deepstream moves to the init step.
 *
 * @private
 * @returns {void}
 */
Deepstream.prototype._checkReady = function( pluginName, plugin ) {
	if( plugin instanceof EventEmitter ) {
		plugin.on( 'error', this._onPluginError.bind( this, pluginName ) );
	}

	for( var i = 0; i < this._plugins.length; i++ ) {
		if( this._options[ this._plugins[ i ] ].isReady !== true ) {
			return;
		}
	}

	if( this._initialised === false ) {
		this._init();
	}
};

/**
 * Final callback - Deepstream is up and running now
 *
 * @private
 * @returns {void}
 */
Deepstream.prototype._onStarted = function() {
	this._options.logger.log( C.LOG_LEVEL.INFO, C.EVENT.INFO, 'Deepstream started' );
	this.isRunning = true;
	this.emit( 'started' );
};

/**
 * Callback for plugin errors that occur at runtime. Errors during initialisation
 * are handled by the DependencyInitialiser
 *
 * @param   {String} pluginName
 * @param   {Error} error
 *
 * @private
 * @returns {void}
 */
Deepstream.prototype._onPluginError = function( pluginName, error  ) {
	var msg = 'Error from ' + pluginName + ' plugin: ' + error.toString();
	this._options.logger.log( C.LOG_LEVEL.ERROR, C.EVENT.PLUGIN_ERROR, msg );
};

module.exports = Deepstream;
<commit_msg>Made server.set() return itself<commit_after>var ConnectionEndpoint = require( './message/connection-endpoint' ),
	MessageProcessor = require( './message/message-processor' ),
	MessageDistributor = require( './message/message-distributor' ),
	DataTransforms = require( './message/data-transforms' ),
	EventHandler = require( './event/event-handler' ),
	EventEmitter = require( 'events' ).EventEmitter,
	messageParser = require( './message/message-parser' ),
	readMessage = require( './utils/read-message' ),
	util = require( 'util' ),
	utils = require( './utils/utils' ),
	defaultOptions = require( './default-options' ),
	RpcHandler = require( './rpc/rpc-handler' ),
	RecordHandler = require( './record/record-handler' ),
	WebRtcHandler = require( './webrtc/webrtc-handler' ),
	DependencyInitialiser = require( './utils/dependency-initialiser' ),
	C = require( './constants/constants' );

require( 'colors' );

/**
 * Deepstream is a realtime data server that scales horizontally
 * by running in clusters of interacting nodes
 *
 * @copyright 2015 Hoxton-One Ltd.
 * @author Wolfram Hempel
 * @version <version>
 *
 * @constructor
 */
var Deepstream = function() {
	this.isRunning = false;
	this.constants = C;
	this._options = defaultOptions.get();
	this._connectionEndpoint = null;
	this._engineIo = null;
	this._messageProcessor = null;
	this._messageDistributor = null;
	this._eventHandler = null;
	this._rpcHandler = null;
	this._recordHandler = null;
	this._webRtcHandler = null;
	this._initialised = false;
	this._plugins = [
		'messageConnector',
		'storage',
		'cache',
		'logger',
		'permissionHandler' //TODO: This now requires the permissionHandler to have a ready flag / emit events
	];
};

util.inherits( Deepstream, EventEmitter );

/**
 * Sets the name of the process
 *
 * @type {String}
 */
process.title = 'deepstream server';

/**
 * Expose constants to allow consumers to access them without
 * requiring a reference to a deepstream instance.
 *
 *
*/
Deepstream.constants = C;

/**
 * Utility method to return a helper object to simplify permissions assertions
 *
 * @param  {object} message description
 * @return {object}         description
 */
Deepstream.readMessage = readMessage;

/**
 * Set a deepstream option. For a list of all available options
 * please see default-options.
 *
 * @param {String} key   the name of the option
 * @param {Mixed} value  the value, e.g. a portnumber for ports or an instance of a logger class
 *
 * @public
 * @returns {void}
 */
Deepstream.prototype.set = function( key, value ) {
	if( this._options[ key ] === undefined ) {
		throw new Error( 'Unknown option "' + key + '"' );
	}

	this._options[ key ] = value;
	return this;
};

/**
 * Starts up deepstream. The startup process has three steps:
 *
 * - Initialise all dependencies (cache connector, message connector, storage connector and logger)
 * - Instantiate the messaging pipeline and record-, rpc- and event-handler
 * - Start TCP and HTTP server
 *
 * @public
 * @returns {void}
 */
Deepstream.prototype.start = function() {
	this._showStartLogo();

	if( this._options.logger.isReady ) {
		this._options.logger.setLogLevel( this._options.logLevel );
		this._options.logger._$useColors = this._options.colors;
	}

	if( this._options.dataTransforms ) {
		this._options.dataTransforms = new DataTransforms( this._options.dataTransforms );
	}

	var i,
		initialiser;

	for( i = 0; i < this._plugins.length; i++ ) {
		initialiser = new DependencyInitialiser( this._options, this._plugins[ i ] );
		initialiser.once( 'ready', this._checkReady.bind( this, this._plugins[ i ], initialiser.getDependency() ));
	}
};

/**
 * Stops the server and closes all connections. The server can be started again,
 * but all clients have to reconnect. Will emit a 'stopped' event once done
 *
 * @public
 * @returns {void}
 */
Deepstream.prototype.stop = function() {
	var i,
		plugin,
		closables = [ this._connectionEndpoint ];

	for( i = 0; i < this._plugins.length; i++ ) {
		plugin = this._options[ this._plugins[ i ] ];
		if( typeof plugin.close === 'function' ) {
			closables.push( plugin );
			setTimeout( plugin.close.bind( plugin ) );
		}
	}

	this._initialised = false;
	utils.combineEvents( closables, 'close', this._onStopped.bind( this ) );
	this._connectionEndpoint.close();
};

/**
 * Expose the message-parser's convertTyped method
 * so that it can be used within permissionHandlers
 *
 * @param   {String} value A String starting with a type identifier (see C.TYPES)
 *
 * @public
 * @returns {mixed} the converted value
 */
Deepstream.prototype.convertTyped = function( value ) {
	return messageParser.convertTyped( value );
};

/**
 * Callback for the final stop event
 *
 * @private
 * @returns {void}
 */
Deepstream.prototype._onStopped = function() {
	this.isRunning = false;
	this.emit( 'stopped' );
};

/**
 * Shows a giant ASCII art logo which is absolutely crucial
 * for the proper functioning of the server
 *
 * @private
 * @returns {void}
 */
Deepstream.prototype._showStartLogo = function() {
	if( this._options.showLogo !== true ) {
		return;
	}

	var logo =
	' _____________________________________________________________________________\n'+
	'                                                                              \n'+
	'         /                                                             ,      \n'+
	' ----__-/----__----__------__---__--_/_---)__----__----__---_--_-----------__-\n'+
	'   /   /   /___) /___)   /   ) (_ ` /    /   ) /___) /   ) / /  )    /   /   )\n'+
	' _(___/___(___ _(___ ___/___/_(__)_(_ __/_____(___ _(___(_/_/__/__o_/___(___/_\n'+
	'                       /                                                      \n'+
	'                      /                                                       \n'+
	'=============================== STARTING... ==================================\n';

	process.stdout.write( this._options.colors ? logo.yellow : logo );
};

/**
 * Invoked once all dependencies are initialised. Instantiates the messaging pipeline and the various handlers.
 * The startup sequence will be complete once the connection endpoint is started and listening
 *
 * @private
 * @returns {void}
 */
Deepstream.prototype._init = function() {
	this._connectionEndpoint = new ConnectionEndpoint( this._options, this._onStarted.bind( this ) );
	this._messageProcessor = new MessageProcessor( this._options );
	this._messageDistributor = new MessageDistributor( this._options );
	this._connectionEndpoint.onMessage = this._messageProcessor.process.bind( this._messageProcessor );

	this._eventHandler = new EventHandler( this._options );
	this._messageDistributor.registerForTopic( C.TOPIC.EVENT, this._eventHandler.handle.bind( this._eventHandler ) );

	this._rpcHandler = new RpcHandler( this._options );
	this._messageDistributor.registerForTopic( C.TOPIC.RPC, this._rpcHandler.handle.bind( this._rpcHandler ) );

	this._webRtcHandler = new WebRtcHandler( this._options );
	this._messageDistributor.registerForTopic( C.TOPIC.WEBRTC, this._webRtcHandler.handle.bind( this._webRtcHandler ) );

	this._recordHandler = new RecordHandler( this._options );
	this._messageDistributor.registerForTopic( C.TOPIC.RECORD, this._recordHandler.handle.bind( this._recordHandler ) );

	this._messageProcessor.onAuthenticatedMessage = this._messageDistributor.distribute.bind( this._messageDistributor );

	this._initialised = true;
};

/**
 * Called whenever a dependency emits a ready event. Once all dependencies are ready
 * deepstream moves to the init step.
 *
 * @private
 * @returns {void}
 */
Deepstream.prototype._checkReady = function( pluginName, plugin ) {
	if( plugin instanceof EventEmitter ) {
		plugin.on( 'error', this._onPluginError.bind( this, pluginName ) );
	}

	for( var i = 0; i < this._plugins.length; i++ ) {
		if( this._options[ this._plugins[ i ] ].isReady !== true ) {
			return;
		}
	}

	if( this._initialised === false ) {
		this._init();
	}
};

/**
 * Final callback - Deepstream is up and running now
 *
 * @private
 * @returns {void}
 */
Deepstream.prototype._onStarted = function() {
	this._options.logger.log( C.LOG_LEVEL.INFO, C.EVENT.INFO, 'Deepstream started' );
	this.isRunning = true;
	this.emit( 'started' );
};

/**
 * Callback for plugin errors that occur at runtime. Errors during initialisation
 * are handled by the DependencyInitialiser
 *
 * @param   {String} pluginName
 * @param   {Error} error
 *
 * @private
 * @returns {void}
 */
Deepstream.prototype._onPluginError = function( pluginName, error  ) {
	var msg = 'Error from ' + pluginName + ' plugin: ' + error.toString();
	this._options.logger.log( C.LOG_LEVEL.ERROR, C.EVENT.PLUGIN_ERROR, msg );
};

module.exports = Deepstream;
<|endoftext|>


<commit_before>var express = require('express'); // Routing framework. http://expressjs.com/
var http = require('http'); // HTTP support. http://nodejs.org/api/http.html
var fs = require('node-fs'); // Recursive directory creation. https://github.com/bpedro/node-fs
var osc = require('node-osc'); // OSC server. https://github.com/TheAlphaNerd/node-osc
var _ = require('underscore'); // Utilities. http://underscorejs.org/
var Backbone = require('backbone'); // Data model utilities. http://backbonejs.org/

// Load config file.
try {
    global.config = JSON.parse(fs.readFileSync('./config.json'));
} catch (error) {
    console.log("Couldn't load config file.");
    console.log(error);
}

// Set up server.
var app = express();
var server = http.createServer(app);
global.io = require('socket.io').listen(server);
io.set('log level', 2);
server.listen(3000);

// Set up OSC server to receive messages from app.
global.oscServer = new osc.Server(3001);
global.oscClient = new osc.Client('127.0.0.1', 3002);
oscServer.on('message', function(msg, rinfo) {
    // Convert OSC messages to objects and emit them similar to sockets.
    var parts = msg[0].substr(1).split('/');
    var action = parts.shift();

    var message = {};
    while (parts.length) {
        var key = parts.shift();
        var val = parts.shift();
        var f = parseFloat(val);
        message[key] = isNaN(f) ? val : f;
    }

    oscServer.emit(action, message);
});

// Set up view routing.
app.use('/static', express.static(__dirname + '/view'));
app.get('/', function(req, res) {
    res.sendfile(__dirname + '/view/index.html');
});

// Set up models.
var ServerState = require('./model/serverState.js').ServerState;
var serverState = new ServerState();

var AppState = require('./model/appState.js').AppState;
var appState = new AppState();

// Update clients with server state when they ask for it, throttled to 60 FPS.
var throttle = 1000 / 60;
io.sockets.on('connection', function(socket) {
    socket.on('getServerState', function(message) {
        clearInterval(socket.serverInterval);
        socket.serverInterval = setInterval(function() {
            socket.emit('serverState', serverState.xport());
        }, throttle);
    });

    socket.on('getAppState', function(message) {
        clearInterval(socket.appInterval);
        socket.appInterval = setInterval(function() {
            socket.emit('appState', appState.xport());
        }, throttle);
    });
});

oscServer.on('getAppState', function(message) {
    clearInterval(oscClient.appInterval);
    oscClient.appInterval = setInterval(function() {
        oscClient.send('/appState/' + JSON.stringify(appState.xport()));
    }, throttle);
});

oscServer.on('getServerState', function(message) {
    clearInterval(oscClient.serverInterval);
    oscClient.serverInterval = setInterval(function() {
        oscClient.send('/serverState/' + JSON.stringify(serverState.xport()));
    }, throttle);
});

///// Support multiple clients
// Each client connects with a config, including its network path for updating content

///// Updater
// Kill/start button
// Update button: kill process, update content, update client, restart client
// Update server
// Support to update from non-web location

///// App controller
// Monitor process
// Restart on hang
// Give up restart after n times

///// Server
// Schedule content update (shut down before, restart after)
// Schedule shutdown/restart
// Run as service? https://npmjs.org/package/node-windows

///// Logger
// Server listens to events from updater/controller and sends those to logger
// Logger listens on a port for log messages

///// Monitor
// Monitor listens on a port for monitor messages
// Revisit ICE for patterns

///// UI
// shut down / start (toggle)
// update (show progress)
// Display monitor status
// Display recent logs
// Memory/CPU usage https://github.com/markitondemand/node-perfmon

///// Central UI
// Forward all messages to another instance of server?
// UI displays all inputs at once?
// Send commands (shutdown etc) back to clients?

///// Plugin for custom app logic
// Short term -- extend serverState class
// Long term -- define a set of properties/types/intervals to keep in sync across clients.

///// Analytics
// Hook into analytics service? Or log analysis tool?

///// V.next
// Try to reduce export payload
<commit_msg>timeouts, not intervals<commit_after>var express = require('express'); // Routing framework. http://expressjs.com/
var http = require('http'); // HTTP support. http://nodejs.org/api/http.html
var fs = require('node-fs'); // Recursive directory creation. https://github.com/bpedro/node-fs
var osc = require('node-osc'); // OSC server. https://github.com/TheAlphaNerd/node-osc
var _ = require('underscore'); // Utilities. http://underscorejs.org/
var Backbone = require('backbone'); // Data model utilities. http://backbonejs.org/

// Load config file.
try {
    global.config = JSON.parse(fs.readFileSync('./config.json'));
} catch (error) {
    console.log("Couldn't load config file.");
    console.log(error);
    process.exit(1);
}

// Set up server.
var app = express();
var server = http.createServer(app);
global.io = require('socket.io').listen(server);
io.set('log level', 2);
server.listen(3000);

// Set up OSC server to receive messages from app.
global.oscClient = new osc.Client('127.0.0.1', 3002);
global.oscServer = new osc.Server(3001);
oscServer.on('message', function(msg, rinfo) {
    console.log(msg);
    // Convert OSC messages to objects and emit them similar to sockets.
    var parts = msg[0].substr(1).split('/');
    var action = parts.shift();

    var message = {};
    while (parts.length) {
        var key = parts.shift();
        var val = parts.shift();
        var f = parseFloat(val);
        message[key] = isNaN(f) ? val : f;
    }

    oscServer.emit(action, message);
});

// Set up view routing.
app.use('/static', express.static(__dirname + '/view'));
app.get('/', function(req, res) {
    res.sendfile(__dirname + '/view/index.html');
});

// Set up models.
var ServerState = require('./model/serverState.js').ServerState;
var serverState = new ServerState();

var AppState = require('./model/appState.js').AppState;
var appState = new AppState();

// Update clients with server state when they ask for it, throttled to 60 FPS.
var throttle = 1000 / 60;
io.sockets.on('connection', function(socket) {
    socket.on('getServerState', function(message) {
        clearInterval(socket.serverTimeout);
        socket.serverTimeout = setTimeout(function() {
            socket.emit('serverState', serverState.xport());
        }, throttle);
    });

    socket.on('getAppState', function(message) {
        clearInterval(socket.appTimeout);
        socket.appTimeout = setTimeout(function() {
            socket.emit('appState', appState.xport());
        }, throttle);
    });
});

oscServer.on('getAppState', function(message) {
    clearInterval(oscClient.appTimeout);
    oscClient.appTimeout = setTimeout(function() {
        oscClient.send('/appState/' + JSON.stringify(appState.xport()));
    }, throttle);
});

oscServer.on('getServerState', function(message) {
    clearInterval(oscClient.serverTimeout);
    oscClient.serverTimeout = setTimeout(function() {
        oscClient.send('/serverState/' + JSON.stringify(serverState.xport()));
    }, throttle);
});

///// Client
// Send to local and remote
// Only listen to remote
// Handle connection failures (looping scheme might prevent...)

///// Support multiple clients
// Each client connects with a config, including its network path for updating content

///// Updater
// Kill/start button
// Update button: kill process, update content, update client, restart client
// Update server
// Support to update from non-web location

///// App controller
// Monitor process
// Restart on hang
// Give up restart after n times

///// Server
// Schedule content update (shut down before, restart after)
// Schedule shutdown/restart
// Run as service? https://npmjs.org/package/node-windows

///// Logger
// Server listens to events from updater/controller and sends those to logger
// Logger listens on a port for log messages

///// Monitor
// Monitor listens on a port for monitor messages
// Revisit ICE for patterns

///// UI
// shut down / start (toggle)
// update (show progress)
// Display monitor status
// Display recent logs
// Memory/CPU usage https://github.com/markitondemand/node-perfmon

///// Central UI
// Forward all messages to another instance of server?
// UI displays all inputs at once?
// Send commands (shutdown etc) back to clients?

///// Plugin for custom app logic
// Short term -- extend serverState class
// Long term -- define a set of properties/types/intervals to keep in sync across clients.

///// Analytics
// Hook into analytics service? Or log analysis tool?

///// V.next
// Try to reduce export payload
<|endoftext|>


<commit_before>Meteor.startup(function () {
  // Reset Database only in environment dev
  if (process.env.NODE_ENV === 'development') {
    KSessions.remove({});
    Books.remove({});

    // Specific insert for Books
    Fixtures.books.forEach(function(rec) {
      if (Books.findOne(rec._id)) {
        Books.update(rec._id, rec);
      }
      else {
        Books.insert(rec);
      }
    });

    Meteor.publish("all_books", function() {
      return Books.find();
    });

    // Specific insert for KSessions
    Fixtures.ksessions.forEach(function(rec) {
      if (KSessions.findOne(rec._id)) {
        KSessions.update(rec._id, rec);
      }
      else {
        KSessions.insert(rec);
      }
    });

    Meteor.publish("all_ksessions", function() {
      return KSessions.find();
    });

    // Specific insert for users
    Fixtures.users.forEach(function(user) {
      if (! Meteor.users.findOne({username: user.username})) {
        Accounts.createUser(user);
      }

    });
  }
});<commit_msg>Fix publish/subscribe<commit_after>Meteor.startup(function () {
  // Reset Database only in environment dev
  if (process.env.NODE_ENV === 'development') {
    KSessions.remove({});
    Books.remove({});

    // Specific insert for Books
    Fixtures.books.forEach(function(rec) {
      if (Books.findOne(rec._id)) {
        Books.update(rec._id, rec);
      }
      else {
        Books.insert(rec);
      }
    });

    // Specific insert for KSessions
    Fixtures.ksessions.forEach(function(rec) {
      if (KSessions.findOne(rec._id)) {
        KSessions.update(rec._id, rec);
      }
      else {
        KSessions.insert(rec);
      }
    });

    // Specific insert for users
    Fixtures.users.forEach(function(user) {
      if (! Meteor.users.findOne({username: user.username})) {
        Accounts.createUser(user);
      }

    });
  }

  Meteor.publish("all_books", function() {
    return Books.find();
  });

  Meteor.publish("all_ksessions", function() {
    return KSessions.find();
  });
});<|endoftext|>