<commit_before>'use strict';

console.log(''); // new line
var vm = require('vm');
var fs = require('fs');
var zlib = require('zlib');
var http = require('http');
var WebSocketServer = require("ws").Server

/**
 * The main namespace. All classes should be prefixed with it.
 * @namespace
 */
var murmures = {
    /**
     * Startup time.
     * @private
     */
    startTime: process.hrtime(),

    /**
     * Writes timestamped log to the console.
     * @public
     */
    serverLog: function (txt) {
        let diff = process.hrtime(this.startTime);
        let fdiff = diff[0] + diff[1] / 1e9;
        if (typeof txt !== 'undefined') {
            console.log(fdiff.toFixed(6) + ' - ' + txt);
        }
        return fdiff;
    },

    restartGame: function (targetLevel) {
        gameEngine.levels = [];
        gameEngine.activeLevel = 0;
        gameEngine.levelIds = fs.readdirSync('./data/staticlevels/', 'utf8');
        let loopCounter = 0;
        gameEngine.levelIds.forEach(function (levelName) {
            let level1Txt = fs.readFileSync('./data/staticlevels/' + levelName, 'utf8').toString().replace(/^\uFEFF/, '');
            let level1 = new murmures.Level();
            level1.build(JSON.parse(level1Txt));
            level1.id = levelName.replace('.json', '');
            gameEngine.levels.push(level1);
            if (typeof targetLevel !== 'undefined' && targetLevel && targetLevel === levelName) {
                gameEngine.activeLevel = loopCounter;
            }
            loopCounter++;
        }, this);
        gameEngine.level = gameEngine.levels[gameEngine.activeLevel];

        let hero1Txt = fs.readFileSync('./data/hero1.json', 'utf8').toString().replace(/^\uFEFF/, '');
        gameEngine.heros = [];
        let hero = new murmures.Character();
        hero.build(gameEngine.level.getStartingPoint(), JSON.parse(hero1Txt).mobTemplate);
        hero.setVision();
        hero.stateOrder = murmures.C.STATE_HERO_ORDER_INPROGRESS;
        gameEngine.heros.push(hero);

        let hero2Txt = fs.readFileSync('./data/hero2.json', 'utf8').toString().replace(/^\uFEFF/, '');
        let hero2 = new murmures.Character();
        hero2.build(gameEngine.level.getStartingPoint(), JSON.parse(hero2Txt).mobTemplate);
        gameEngine.heros.push(hero2);

        let hero3Txt = fs.readFileSync('./data/hero3.json', 'utf8').toString().replace(/^\uFEFF/, '');
        let hero3 = new murmures.Character();
        hero3.build(gameEngine.level.getStartingPoint(), JSON.parse(hero3Txt).mobTemplate);
        gameEngine.heros.push(hero3);

        gameEngine.state = murmures.C.STATE_ENGINE_INIT;
    }
};

/**
 * Declares the gameEngine variable for a later use.
 * This variable will be set to an instance of murmures.GameEngine after all classes are loaded.
 * @instance
 * @type {murmures.GameEngine}
 */
var gameEngine = {};

murmures.serverLog('Loading classes');

/**
 * Loads classes into the murmures namespace
 */
(function () {
    const ctx = {
        murmures: murmures,
        gameEngine: {}
    };
    vm.createContext(ctx);

    let constantsjs = fs.readFileSync('./src/js/core/constants.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(constantsjs, ctx, { filename: 'constants.js' });
    let gameEnginejs = fs.readFileSync('./src/js/core/gameengine.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(gameEnginejs, ctx, { filename: 'gameengine.js' });

    ctx.gameEngine = new murmures.GameEngine();

    let playerjs = fs.readFileSync('./src/js/core/player.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(playerjs, ctx, { filename: 'player.js' });
    let tilejs = fs.readFileSync('./src/js/core/tile.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(tilejs, ctx, { filename: 'tile.js' });
    let leveljs = fs.readFileSync('./src/js/core/level.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(leveljs, ctx, { filename: 'level.js' });
    let characterjs = fs.readFileSync('./src/js/core/character.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(characterjs, ctx, { filename: 'character.js' });
    let orderjs = fs.readFileSync('./src/js/core/order.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(orderjs, ctx, { filename: 'order.js' });
    let physicalBodyjs = fs.readFileSync('./src/js/core/physicalbody.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(physicalBodyjs, ctx, { filename: 'physicalbody.js' });
    let behaviorjs = fs.readFileSync('./src/js/core/behavior.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(behaviorjs, ctx, { filename: 'behavior.js' });

    let vmperfjs = fs.readFileSync('./src/js/test/vmperf.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(vmperfjs, ctx, { filename: 'vmperf.js' });
    let servertestjs = fs.readFileSync('./src/js/test/servertest.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(servertestjs, ctx, { filename: 'servertest.js' });

    gameEngine = ctx.gameEngine;
})();

murmures.serverLog('Initializing game');

/**
 * Initializes game
 */
(function () {
    let assetsJson = fs.readFileSync('./data/reference/assets.json', 'utf8').toString().replace(/^\uFEFF/, '');
    gameEngine.bodies = JSON.parse(assetsJson);

    let localefrJson = fs.readFileSync('./data/locale/fr.json', 'utf8').toString().replace(/^\uFEFF/, '');
    let localeenJson = fs.readFileSync('./data/locale/en.json', 'utf8').toString().replace(/^\uFEFF/, '');
    gameEngine.locale = {};
    gameEngine.locale.fr = JSON.parse(localefrJson);
    gameEngine.locale.en = JSON.parse(localeenJson);

    murmures.restartGame();
})();

murmures.serverLog('Starting HTTP server');

// Tries to compress (gzip) the response, if the client browser allows it
function compressAndSend(request, response, contType, txt, callback) {
    let acceptEncoding = request.headers['accept-encoding'];
    if (!acceptEncoding) {
        acceptEncoding = '';
    }
    if (acceptEncoding.match(/\bgzip\b/) && contType !== 'image/png') {
        zlib.gzip(txt, function (err, zipped) {
            if (err) throw err;
            murmures.serverLog('Response compressed');
            response.writeHead(200, { 'Content-Type': contType, 'Content-Encoding': 'gzip' });
            response.end(zipped, 'utf8', callback);
        });
    } else if (contType === 'image/png') {
        let stats = fs.statSync('./src/img/murmures.png');
        response.writeHead(200, { 'Content-Type': contType, 'Content-Length': stats.size });
        response.end(txt);
    } else {
        response.writeHead(200, { 'Content-Type': contType });
        response.end(txt);
    }
}

var server = http.createServer(function (request, response) {
    if (request.url === '/favicon.ico') {
        response.writeHead(204); // No content
        response.end();
    }
    else if (request.url === '/') {
        response.writeHead(301, { 'Location': '/src/pages/client.html' });
        response.end();
    }
    else if (request.url.startsWith('/src/')) {
        // #region Static Pages
        try {
            let fileName = request.url;
            fs.readFile('.' + fileName, function (err, fileContent) {
                if (err) throw err;
                if (fileName.endsWith('.js')) {
                    compressAndSend(request, response, 'application/javascript', fileContent.toString());
                }
                else if (fileName.endsWith('.css')) {
                    compressAndSend(request, response, 'text/css', fileContent.toString());
                }
                else if (fileName.endsWith('.png')) {
                    compressAndSend(request, response, 'image/png', fileContent);
                }
                else if (fileName.endsWith('.html')) {
                    compressAndSend(request, response, 'text/html', fileContent.toString());
                }
                else {
                    response.writeHead(400); // Bad Request
                    response.end();
                }
            });
        } catch (e) {
            response.writeHead(404);
            response.end();
        }
        // #endregion
    }
    else {
        response.writeHead(404);
        response.end();
    }
}).listen(process.env.PORT || 15881);

var wss = new WebSocketServer({ server: server })
wss.on('connection', function (ws) {
    ws.on('message', function (messageTxt) {
        let message = JSON.parse(messageTxt);
        if (message.service === 'getLevel') {
            ws.send(JSON.stringify({ fn: 'init', payload: gameEngine }));
        }
        else if (message.service === 'order') {
            murmures.serverLog('Request received');
            let clientOrder = new murmures.Order();
            let parsing = clientOrder.build(message.payload);
            if (parsing.valid) {
                let check = gameEngine.checkOrder(clientOrder);
                if (check.valid) {
                    //gameEngine.gameTurn++;
                    murmures.serverLog('Order checked');
                    let beforeState = gameEngine.clone(); // TODO : clone AFTER the turn.
                    murmures.serverLog('State saved');
                    gameEngine.saveOrder(clientOrder);

                    murmures.serverLog('Order applied');
                    let ge = gameEngine.compare(beforeState);
                    let res = JSON.stringify({ fn: 'o', payload: ge });
                    murmures.serverLog('Response stringified');
                    // broadcast to all clients
                    wss.clients.forEach(function each(client) {
                        client.send(res);
                    });
                }
                else {
                    ws.send(JSON.stringify({ fn: 'o', payload: { error: check.reason } }));
                }
            }
            else {
                ws.send(JSON.stringify({ fn: 'o', payload: { error: parsing.reason } }));
            }
            murmures.serverLog('Response sent');
        }
        else if (message.service === 'restart') {
            murmures.restartGame(message.payload);
            wss.clients.forEach(function each(client) {
                client.send(JSON.stringify({ fn: 'init', payload: gameEngine }));
            });
        }
        else if (message.service === 'test') {
            let test = new murmures.ServerTest();
            test.run(require);
        }
        else {
            murmures.serverLog('Received an incorrect request:' + messageTxt.toString());
        }
    });
});

murmures.serverLog('Listening on http://127.0.0.1:' + (process.env.PORT || 15881).toString() + '/');
<commit_msg>random heroes<commit_after>'use strict';

console.log(''); // new line
var vm = require('vm');
var fs = require('fs');
var zlib = require('zlib');
var http = require('http');
var WebSocketServer = require("ws").Server

/**
 * The main namespace. All classes should be prefixed with it.
 * @namespace
 */
var murmures = {
    /**
     * Startup time.
     * @private
     */
    startTime: process.hrtime(),

    /**
     * Writes timestamped log to the console.
     * @public
     */
    serverLog: function (txt) {
        let diff = process.hrtime(this.startTime);
        let fdiff = diff[0] + diff[1] / 1e9;
        if (typeof txt !== 'undefined') {
            console.log(fdiff.toFixed(6) + ' - ' + txt);
        }
        return fdiff;
    },

    restartGame: function (targetLevel) {
        gameEngine.levels = [];
        gameEngine.activeLevel = 0;
        gameEngine.levelIds = fs.readdirSync('./data/staticlevels/', 'utf8');
        let loopCounter = 0;
        gameEngine.levelIds.forEach(function (levelName) {
            let level1Txt = fs.readFileSync('./data/staticlevels/' + levelName, 'utf8').toString().replace(/^\uFEFF/, '');
            let level1 = new murmures.Level();
            level1.build(JSON.parse(level1Txt));
            level1.id = levelName.replace('.json', '');
            gameEngine.levels.push(level1);
            if (typeof targetLevel !== 'undefined' && targetLevel && targetLevel === levelName) {
                gameEngine.activeLevel = loopCounter;
            }
            loopCounter++;
        }, this);
        gameEngine.level = gameEngine.levels[gameEngine.activeLevel];

        gameEngine.heros = [];
        let allHeroesKeys = [];
        for (let assetId in gameEngine.bodies) {
            let ref = gameEngine.bodies[assetId];
            if (murmures.C.LAYERS[ref.layerId][0] === 'Hero') allHeroesKeys.push(assetId);
        }

        let chosenHeroesKeys = [];
        let chosenHero;
        for (loopCounter = 0; loopCounter < 3; loopCounter++) {
            do {
                let rand = Math.floor(Math.random() * allHeroesKeys.length);
                chosenHero = allHeroesKeys[rand];
            } while (chosenHeroesKeys.indexOf(chosenHero) >= 0); // This loop prevents duplicate heroes

            let hero1 = new murmures.Character();
            hero1.build(gameEngine.level.getStartingPoint(), chosenHero);
            if (loopCounter === 0) {
                hero1.setVision();
                hero1.stateOrder = murmures.C.STATE_HERO_ORDER_INPROGRESS;
            }
            gameEngine.heros.push(hero1);
        }

        gameEngine.state = murmures.C.STATE_ENGINE_INIT;
    }
};

/**
 * Declares the gameEngine variable for a later use.
 * This variable will be set to an instance of murmures.GameEngine after all classes are loaded.
 * @instance
 * @type {murmures.GameEngine}
 */
var gameEngine = {};

murmures.serverLog('Loading classes');

/**
 * Loads classes into the murmures namespace
 */
(function () {
    const ctx = {
        murmures: murmures,
        gameEngine: {}
    };
    vm.createContext(ctx);

    let constantsjs = fs.readFileSync('./src/js/core/constants.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(constantsjs, ctx, { filename: 'constants.js' });
    let gameEnginejs = fs.readFileSync('./src/js/core/gameengine.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(gameEnginejs, ctx, { filename: 'gameengine.js' });

    ctx.gameEngine = new murmures.GameEngine();

    let playerjs = fs.readFileSync('./src/js/core/player.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(playerjs, ctx, { filename: 'player.js' });
    let tilejs = fs.readFileSync('./src/js/core/tile.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(tilejs, ctx, { filename: 'tile.js' });
    let leveljs = fs.readFileSync('./src/js/core/level.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(leveljs, ctx, { filename: 'level.js' });
    let characterjs = fs.readFileSync('./src/js/core/character.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(characterjs, ctx, { filename: 'character.js' });
    let orderjs = fs.readFileSync('./src/js/core/order.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(orderjs, ctx, { filename: 'order.js' });
    let physicalBodyjs = fs.readFileSync('./src/js/core/physicalbody.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(physicalBodyjs, ctx, { filename: 'physicalbody.js' });
    let behaviorjs = fs.readFileSync('./src/js/core/behavior.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(behaviorjs, ctx, { filename: 'behavior.js' });

    let vmperfjs = fs.readFileSync('./src/js/test/vmperf.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(vmperfjs, ctx, { filename: 'vmperf.js' });
    let servertestjs = fs.readFileSync('./src/js/test/servertest.js', 'utf8').toString().replace(/^\uFEFF/, '');
    vm.runInContext(servertestjs, ctx, { filename: 'servertest.js' });

    gameEngine = ctx.gameEngine;
})();

murmures.serverLog('Initializing game');

/**
 * Initializes game
 */
(function () {
    let assetsJson = fs.readFileSync('./data/reference/assets.json', 'utf8').toString().replace(/^\uFEFF/, '');
    gameEngine.bodies = JSON.parse(assetsJson);

    let localefrJson = fs.readFileSync('./data/locale/fr.json', 'utf8').toString().replace(/^\uFEFF/, '');
    let localeenJson = fs.readFileSync('./data/locale/en.json', 'utf8').toString().replace(/^\uFEFF/, '');
    gameEngine.locale = {};
    gameEngine.locale.fr = JSON.parse(localefrJson);
    gameEngine.locale.en = JSON.parse(localeenJson);

    murmures.restartGame();
})();

murmures.serverLog('Starting HTTP server');

// Tries to compress (gzip) the response, if the client browser allows it
function compressAndSend(request, response, contType, txt, callback) {
    let acceptEncoding = request.headers['accept-encoding'];
    if (!acceptEncoding) {
        acceptEncoding = '';
    }
    if (acceptEncoding.match(/\bgzip\b/) && contType !== 'image/png') {
        zlib.gzip(txt, function (err, zipped) {
            if (err) throw err;
            murmures.serverLog('Response compressed');
            response.writeHead(200, { 'Content-Type': contType, 'Content-Encoding': 'gzip' });
            response.end(zipped, 'utf8', callback);
        });
    } else if (contType === 'image/png') {
        let stats = fs.statSync('./src/img/murmures.png');
        response.writeHead(200, { 'Content-Type': contType, 'Content-Length': stats.size });
        response.end(txt);
    } else {
        response.writeHead(200, { 'Content-Type': contType });
        response.end(txt);
    }
}

var server = http.createServer(function (request, response) {
    if (request.url === '/favicon.ico') {
        response.writeHead(204); // No content
        response.end();
    }
    else if (request.url === '/') {
        response.writeHead(301, { 'Location': '/src/pages/client.html' });
        response.end();
    }
    else if (request.url.startsWith('/src/')) {
        // #region Static Pages
        try {
            let fileName = request.url;
            fs.readFile('.' + fileName, function (err, fileContent) {
                if (err) throw err;
                if (fileName.endsWith('.js')) {
                    compressAndSend(request, response, 'application/javascript', fileContent.toString());
                }
                else if (fileName.endsWith('.css')) {
                    compressAndSend(request, response, 'text/css', fileContent.toString());
                }
                else if (fileName.endsWith('.png')) {
                    compressAndSend(request, response, 'image/png', fileContent);
                }
                else if (fileName.endsWith('.html')) {
                    compressAndSend(request, response, 'text/html', fileContent.toString());
                }
                else {
                    response.writeHead(400); // Bad Request
                    response.end();
                }
            });
        } catch (e) {
            response.writeHead(404);
            response.end();
        }
        // #endregion
    }
    else {
        response.writeHead(404);
        response.end();
    }
}).listen(process.env.PORT || 15881);

var wss = new WebSocketServer({ server: server })
wss.on('connection', function (ws) {
    ws.on('message', function (messageTxt) {
        let message = JSON.parse(messageTxt);
        if (message.service === 'getLevel') {
            ws.send(JSON.stringify({ fn: 'init', payload: gameEngine }));
        }
        else if (message.service === 'order') {
            murmures.serverLog('Request received');
            let clientOrder = new murmures.Order();
            let parsing = clientOrder.build(message.payload);
            if (parsing.valid) {
                let check = gameEngine.checkOrder(clientOrder);
                if (check.valid) {
                    //gameEngine.gameTurn++;
                    murmures.serverLog('Order checked');
                    let beforeState = gameEngine.clone(); // TODO : clone AFTER the turn.
                    murmures.serverLog('State saved');
                    gameEngine.saveOrder(clientOrder);

                    murmures.serverLog('Order applied');
                    let ge = gameEngine.compare(beforeState);
                    let res = JSON.stringify({ fn: 'o', payload: ge });
                    murmures.serverLog('Response stringified');
                    // broadcast to all clients
                    wss.clients.forEach(function each(client) {
                        client.send(res);
                    });
                }
                else {
                    ws.send(JSON.stringify({ fn: 'o', payload: { error: check.reason } }));
                }
            }
            else {
                ws.send(JSON.stringify({ fn: 'o', payload: { error: parsing.reason } }));
            }
            murmures.serverLog('Response sent');
        }
        else if (message.service === 'restart') {
            murmures.restartGame(message.payload);
            wss.clients.forEach(function each(client) {
                client.send(JSON.stringify({ fn: 'init', payload: gameEngine }));
            });
        }
        else if (message.service === 'test') {
            let test = new murmures.ServerTest();
            test.run(require);
        }
        else {
            murmures.serverLog('Received an incorrect request:' + messageTxt.toString());
        }
    });
});

murmures.serverLog('Listening on http://127.0.0.1:' + (process.env.PORT || 15881).toString() + '/');
<|endoftext|>


<commit_before>// @flow
/**
 * Part of GDL gdl-frontend.
 * Copyright (C) 2017 @PROJECT@
 *
 * See LICENSE
 */

const express = require('express');
const next = require('next');
const requestLanguage = require('express-request-language');
const cookieParser = require('cookie-parser');
const glob = require('glob');
const compression = require('compression');
const routes = require('./routes');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = routes.getRequestHandler(app);

const languages = glob.sync('locale/*/messages.js').map(f => f.split('/')[1]);
console.log('Found translations for the following languages: ', languages);

app
  .prepare()
  .then(() => {
    const server = express();

    // Gzip responses
    server.use(compression());

    // Health check for AWS
    server.get('/health', (req, res) => {
      res.status(200).json({ status: 200, text: 'Health check ok' });
    });

    // Setup the cookie parsing for express
    server.use(cookieParser());
    // Determine language based on query parameter, cookie, or http accept header
    // This middleware injects a language property on the request object.
    server.use(
      requestLanguage({
        languages,
        queryName: 'hl',
        cookie: {
          name: 'language',
        },
      }),
    );

    server.get('*', (req, res) => {
      handle(req, res);
    });

    server.listen(3000, err => {
      if (err) throw err;
      console.log('> Ready on http://localhost:3000');
    });
  })
  .catch(ex => {
    console.error(ex.stack);
    process.exit(1);
  });
<commit_msg>404 the favicon request<commit_after>// @flow
/**
 * Part of GDL gdl-frontend.
 * Copyright (C) 2017 @PROJECT@
 *
 * See LICENSE
 */

const express = require('express');
const next = require('next');
const requestLanguage = require('express-request-language');
const cookieParser = require('cookie-parser');
const glob = require('glob');
const compression = require('compression');
const routes = require('./routes');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = routes.getRequestHandler(app);

const languages = glob.sync('locale/*/messages.js').map(f => f.split('/')[1]);
console.log('Found translations for the following languages: ', languages);

app
  .prepare()
  .then(() => {
    const server = express();

    // Gzip responses
    server.use(compression());

    // 404 all requests for favicons since we don't have one, and it attempts to match with our next routes
    server.get('/favicon.ico', (req, res) => res.sendStatus(404));

    // Health check for AWS
    server.get('/health', (req, res) => {
      res.status(200).json({ status: 200, text: 'Health check ok' });
    });

    // Setup the cookie parsing for express
    server.use(cookieParser());
    // Determine language based on query parameter, cookie, or http accept header
    // This middleware injects a language property on the request object.
    server.use(
      requestLanguage({
        languages,
        queryName: 'hl',
        cookie: {
          name: 'language',
        },
      }),
    );

    server.get('*', (req, res) => {
      handle(req, res);
    });

    server.listen(3000, err => {
      if (err) throw err;
      console.log('> Ready on http://localhost:3000');
    });
  })
  .catch(ex => {
    console.error(ex.stack);
    process.exit(1);
  });
<|endoftext|>


<commit_before>var http = require ('http');              // For serving a basic web page.
var mongoose = require ("mongoose");      // The reason for this demo.
var querystring = require('querystring');

// The http server will listen to an appropriate port, or default to
// port 5000.
var port = process.env.PORT || 5000;

var slack_token = process.env.SLACK_TOKEN;

/***************** DATABASE CONNEXION AND INITIALIZATION ****************/

// Here we find an appropriate database to connect to, defaulting to
// localhost if we don't find one.
var MongoURI =
process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/HelloMongoose';

// Makes connection asynchronously.  Mongoose will queue up database
// operations and release them when the connection is complete.
mongoose.connect(MongoURI, function (err, res) {
  if (err) {
  console.log ('ERROR connecting to: ' + MongoURI + '. ' + err);
  } else {
    console.log ('Succeeded connected to: ' + MongoURI);
  }
});

var UserSchema = new mongoose.Schema({
  slack_id: { type: String },
  name: { type: String }
});

var User = mongoose.model('User', UserSchema);

var OperationSchema = new mongoose.Schema({
  slack_id_sender: { type: String },
  slack_id_receiver: { type: String },
  amount: { type: Number }
});

var Operation = mongoose.model('Operation', OperationSchema);

/***************** APPLICATION'S LOGIC ****************/

http.createServer(function (req, res) {
    var fullBody = '';

    req.on('data', function(chunk) {
      // append the current chunk of data to the fullBody variable
      fullBody += chunk.toString();
    });

    req.on('end', function() {

      // request ended -> do something with the data
      res.writeHead(200, "OK", {'Content-Type': 'text/html'});

      // parse the received body data
      var decodedBody = querystring.parse(fullBody);
        console.log(decodedBody);

      var responseBody;
      if(decodedBody.token != slack_token)
      {
          responseBody = { text : ' Authentication error : wrong token ' };
          res.writeHead(200, {'Content-Type': 'application/json'});
          res.end( JSON.stringify(responseBody) );
          return;
      }

      // Create the user if does not exists, or find him in DB
      var user = getOrCreateUser(decodedBody.user_id, decodedBody.user_name, function(user){

        console.log(user);
        if(user.justCreated)
        {

        //TODO : prevent an exchange to be catched here if the message contains hi
          if ( decodedBody.text.indexOf("hi") > -1)
          {
            responseBody = { text : 'Bienvenue ' + user.name + ' !' };
          }
          else
          {
            responseBody = { text : 'Vous devez commencer par " bangs: hi " ' };
          }

          console.log('early return');

          res.writeHead(200, {'Content-Type': 'application/json'});
          res.end( JSON.stringify(responseBody) );

        }else{

          // First find for who is the money
          findTarget(decodedBody.text, function(target){

            console.log(target);

            if(target == null)
            {

              console.log('target null');

              responseBody = { text : 'Le destinataire n\'existe pas ou n\'a pas dit "bangs: hi" ' };
              res.writeHead(200, {'Content-Type': 'application/json'});
              res.end( JSON.stringify(responseBody) );
              return;
            }

            // Second find how many
            var amount = findAmount(decodedBody.text);
            amount = parseInt(amount);

            console.log(target);

            if(amount == null)
            {

              console.log('amount null');

              responseBody = { text : 'Vous devez préciser la somme dans votre message !' };
              res.writeHead(200, {'Content-Type': 'application/json'});
              res.end( JSON.stringify(responseBody) );
              return;
            }

            // Finally save the bank operation in DB and display updated funds.
            var op = new Operation({ slack_id_sender: user.slack_id, slack_id_receiver: target.slack_id, amount: amount  });
            op.save();

              processBank(user, function(user_bank){
                processBank(target, function(target_bank){

              console.log(user_bank);
              console.log(target_bank);

                  responseBody = { text : 'Bangs envoyés ! ' + amount + ' à ' +target.name + '\n'+ user.name +':' + user_bank+ ' bangs\n'+ target.name+':' + target_bank + ' bangs' };

                  res.writeHead(200, {'Content-Type': 'application/json'});
                  res.end( JSON.stringify(responseBody) );

              });

            });

          });
        }

      });

    });

}).listen(port);

console.log('Server running at http://127.0.0.1:'+port);

/********************** HELPERS *********************/

// Find mentionned user to receive funds
var findTarget = function(text, callback){
  var target_ids = text.match(/\<@(.*)\>/);

  var target_id;
  if(target_ids != null && target_ids.length > 0)
  {

    target_id = target_ids.pop();

    User.find({ slack_id: target_id}, function(err, users){
      callback(users[0]);
    });
  }
  else
  {
    callback(null);
  }
}

// Find amount to send
var findAmount = function(text){
  var numbers = text.match(/\d+/);
  return numbers[0];
}

// Current bank of a user
var processBank = function(user, callback){
  Operation.aggregate({ $group: { _id:{ slack_id_sender: user.slack_id } , total: {$sum: "$amount"} } }
   , function(err, senders){
        console.log(senders);
    Operation.aggregate({ $group: { _id:{ slack_id_receiver: user.slack_id } , total: {$sum: "$amount"} } }
       , function(err, receivers){
        console.log(receivers);
        var received = 0;
        if(receivers.length > 0)
        {
            received = receivers[0].total;
        }

        var sent = 0;
        if(senders.length > 0)
        {
            sent = senders[0].total;
        }
        callback( received - sent );
    });
  });

}

// Find a user givenn it's slack_id
var getOrCreateUser = function(slack_id, name, callback){

  User.find({ slack_id: slack_id}, function(err, users){

    if (err) return console.error(err);

    var user;
    if (users.length == 0)
    {
      user = new User({ slack_id: slack_id, name: name });
      user.save();
      user.justCreated = true;
    }

    else
    {
      user = users[0];
      user.justCreated = false;
    }

    callback(user);

  });

}<commit_msg>dont recognize bot<commit_after>var http = require ('http');              // For serving a basic web page.
var mongoose = require ("mongoose");      // The reason for this demo.
var querystring = require('querystring');

// The http server will listen to an appropriate port, or default to
// port 5000.
var port = process.env.PORT || 5000;

var slack_token = process.env.SLACK_TOKEN;

/***************** DATABASE CONNEXION AND INITIALIZATION ****************/

// Here we find an appropriate database to connect to, defaulting to
// localhost if we don't find one.
var MongoURI =
process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/HelloMongoose';

// Makes connection asynchronously.  Mongoose will queue up database
// operations and release them when the connection is complete.
mongoose.connect(MongoURI, function (err, res) {
  if (err) {
  console.log ('ERROR connecting to: ' + MongoURI + '. ' + err);
  } else {
    console.log ('Succeeded connected to: ' + MongoURI);
  }
});

var UserSchema = new mongoose.Schema({
  slack_id: { type: String },
  name: { type: String }
});

var User = mongoose.model('User', UserSchema);

var OperationSchema = new mongoose.Schema({
  slack_id_sender: { type: String },
  slack_id_receiver: { type: String },
  amount: { type: Number }
});

var Operation = mongoose.model('Operation', OperationSchema);

/***************** APPLICATION'S LOGIC ****************/

http.createServer(function (req, res) {
    var fullBody = '';

    req.on('data', function(chunk) {
      // append the current chunk of data to the fullBody variable
      fullBody += chunk.toString();
    });

    req.on('end', function() {

      // request ended -> do something with the data
      res.writeHead(200, "OK", {'Content-Type': 'text/html'});

      // parse the received body data
      var decodedBody = querystring.parse(fullBody);
        console.log(decodedBody);

      var responseBody;
      if(decodedBody.token != slack_token)
      {
          responseBody = { text : ' Authentication error : wrong token ' };
          res.writeHead(200, {'Content-Type': 'application/json'});
          res.end( JSON.stringify(responseBody) );
          return;
      }

      // Create the user if does not exists, or find him in DB
      var user = getOrCreateUser(decodedBody.user_id, decodedBody.user_name, function(user){

        console.log(user);
        if(user.justCreated)
        {

        //TODO : prevent an exchange to be catched here if the message contains hi
          if ( decodedBody.text.indexOf("hi") > -1)
          {
            responseBody = { text : 'Bienvenue ' + user.name + ' !' };
          }
          else
          {
            responseBody = { text : 'Vous devez commencer par " bangs: hi " ' };
          }

          console.log('early return');

          res.writeHead(200, {'Content-Type': 'application/json'});
          res.end( JSON.stringify(responseBody) );

        }else{

          if(decodedBody.slack_id == 'USLACKBOT')
          {
            return;
          }

          // First find for who is the money
          findTarget(decodedBody.text, function(target){

            console.log(target);

            if(target == null)
            {

              console.log('target null');

              responseBody = { text : 'Le destinataire n\'existe pas ou n\'a pas dit "bangs: hi" ' };
              res.writeHead(200, {'Content-Type': 'application/json'});
              res.end( JSON.stringify(responseBody) );
              return;
            }

            // Second find how many
            var amount = findAmount(decodedBody.text);
            amount = parseInt(amount);

            console.log(target);

            if(amount == null)
            {

              console.log('amount null');

              responseBody = { text : 'Vous devez préciser la somme dans votre message !' };
              res.writeHead(200, {'Content-Type': 'application/json'});
              res.end( JSON.stringify(responseBody) );
              return;
            }

            // Finally save the bank operation in DB and display updated funds.
            var op = new Operation({ slack_id_sender: user.slack_id, slack_id_receiver: target.slack_id, amount: amount  });
            op.save();

              processBank(user, function(user_bank){
                processBank(target, function(target_bank){

              console.log(user_bank);
              console.log(target_bank);

                  responseBody = { text : 'Bangs envoyés ! ' + amount + ' à ' +target.name + '\n'+ user.name +':' + user_bank+ ' bangs\n'+ target.name+':' + target_bank + ' bangs' };

                  res.writeHead(200, {'Content-Type': 'application/json'});
                  res.end( JSON.stringify(responseBody) );

              });

            });

          });
        }

      });

    });

}).listen(port);

console.log('Server running at http://127.0.0.1:'+port);

/********************** HELPERS *********************/

// Find mentionned user to receive funds
var findTarget = function(text, callback){
  var target_ids = text.match(/\<@(.*)\>/);

  var target_id;
  if(target_ids != null && target_ids.length > 0)
  {

    target_id = target_ids.pop();

    User.find({ slack_id: target_id}, function(err, users){
      callback(users[0]);
    });
  }
  else
  {
    callback(null);
  }
}

// Find amount to send
var findAmount = function(text){
  var numbers = text.match(/\d+/);
  return numbers[0];
}

// Current bank of a user
var processBank = function(user, callback){

  Operation.aggregate({ $group: { _id:{ slack_id_sender: user.slack_id } , total: {$sum: "$amount"} } }
   , function(err, senders){

        console.log(senders);

    Operation.aggregate({ $group: { _id:{ slack_id_receiver: user.slack_id } , total: {$sum: "$amount"} } }
       , function(err, receivers){

        console.log(receivers);

        var received = 0;
        if(receivers.length > 0)
        {
            received = receivers[0].total;
        }

        var sent = 0;
        if(senders.length > 0)
        {
            sent = senders[0].total;
        }
        callback( received - sent );
    });
  });

}

// Find a user givenn it's slack_id
var getOrCreateUser = function(slack_id, name, callback){

  User.find({ slack_id: slack_id}, function(err, users){

    if (err) return console.error(err);

    var user;
    if (users.length == 0)
    {
      user = new User({ slack_id: slack_id, name: name });
      user.save();
      user.justCreated = true;
    }

    else
    {
      user = users[0];
      user.justCreated = false;
    }

    callback(user);

  });

}<|endoftext|>


<commit_before>var static = require('node-static');

//
// Create a node-static server instance to serve the './public' folder
//
var file = new static.Server('.', { cache: 60 });
var port = Number(process.env.PORT || 5000);

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        //
        // Serve files!
        //
        file.serve(request, response);
    }).resume();
}).listen(port);
<commit_msg>Code style<commit_after>'use strict';

var nodeStatic = require('node-static');

//
// Create a node-static server instance to serve the './public' folder
//
var file = new nodeStatic.Server('.', { cache: 60 });
var port = Number(process.env.PORT || 5000);

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        //
        // Serve files!
        //
        file.serve(request, response);
    }).resume();
}).listen(port);
<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser')
var app     = express();
var path    = require('path');
var giphy = require('giphy-api')(process.env.GIPHY_API_KEY);

app.use(express.static('public'));

app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.html'));
  //__dirname : It will resolve to your project folder.
});
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.post('/make-gr8', urlencodedParser, function(req, res) {
  giphy.random({
    rating: 'pg-13',
    tag: req.body.searchTerm || ''
  }, function(err, output) {
    res.send(output.data);
  });
});

app.listen(80);

console.log("http://mygif2u.herokuapp.com");
<commit_msg>heroku port<commit_after>var express = require('express');
var bodyParser = require('body-parser')
var app     = express();
var path    = require('path');
var giphy = require('giphy-api')(process.env.GIPHY_API_KEY);

app.use(express.static('public'));

app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.html'));
  //__dirname : It will resolve to your project folder.
});
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.post('/make-gr8', urlencodedParser, function(req, res) {
  giphy.random({
    rating: 'pg-13',
    tag: req.body.searchTerm || ''
  }, function(err, output) {
    res.send(output.data);
  });
});

app.listen(process.env.PORT);

console.log("http://mygif2u.herokuapp.com @ ", process.env.PORT);
<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// LAN message
slapp.message('/\slan\s/ig', 'ambient', (msg) => {
  msg.say('LAN is coming soon.')
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<commit_msg>altered regex<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// LAN message
slapp.message('\slan\s', 'ambient', (msg) => {
  msg.say('LAN is coming soon.')
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<|endoftext|>


<commit_before>'use strict';
<commit_msg>further basic set up stuff<commit_after>'use strict';

const EXPRESS = require('express');
const bodyParser = require('body-parser');
const PG = require('pg');
const PORT = process.env.PORT || 3000;
const app = EXPRESS();
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('playerList', ['playerList']);
var bodyParser = require('body-parser');
var http = require('http');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());

app.get('/playerList', function (req, res) {
  console.log('I received a GET request');

  db.playerList.find(function (err, docs) {

    res.json(docs);
  });
});

app.post('/playerList', function (req, res) {

  db.playerList.insert(req.body, function(err, doc) {
    res.json(doc);
  });
});

app.get('/playerList/:id', function (req, res) {
  var id = req.params.id;

  db.playerList.findOne({_id: mongojs.ObjectId(id)}, function (err, doc) {
    res.json(doc);
  });
});

app.put('/playerList/:id', function (req, res) {
  var id = req.params.id;
  db.playerList.findAndModify({
    query: {_id: mongojs.ObjectId(id)},
    update: {$set: {onTeam: req.body.onTeam}},
    new: true}, function (err, doc) {
      res.json(doc);
    }
  );
});
app.set('port', process.env.PORT || 3000);

http.createServer(app).listen(app.get('port'),
	function(){
		console.log("Express server listening on port " + app.get('port'));
});

//app.listen(3000);
//console.log("Server running on port 3000");

<commit_msg>formatting changes<commit_after>var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('playerList', ['playerList']);
var bodyParser = require('body-parser');
var http = require('http');

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());

app.get('/playerList', function (req, res) {
  console.log('I received a GET request');

  db.playerList.find(function (err, docs) {

    res.json(docs);
  });
});

app.get('/playerList/:id', function (req, res) {
  var id = req.params.id;

  db.playerList.findOne({_id: mongojs.ObjectId(id)}, function (err, doc) {
    res.json(doc);
  });
});

app.post('/playerList', function (req, res) {

  db.playerList.insert(req.body, function(err, doc) {
    res.json(doc);
  });
});

app.put('/playerList/:id', function (req, res) {
  var id = req.params.id;
  db.playerList.findAndModify({
    query: {_id: mongojs.ObjectId(id)},
    update: {$set: {onTeam: req.body.onTeam}},
    new: true}, function (err, doc) {
      res.json(doc);
    }
  );
});

app.set('port', process.env.PORT || 3000);

http.createServer(app).listen(app.get('port'), function(){
		console.log("server listening on port " + app.get('port'));
});

<|endoftext|>


<commit_before><commit_msg>added v1 api for tessel routing<commit_after>'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var tesselV1 = require('./controllers/v1/tessel');
var app = express();

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// port of the api server
var port = process.env.PORT || 3000;

// REGISTER OUR ROUTES
// =============================================================================
app.use('/v1/tessel', tesselV1);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
<|endoftext|>


<commit_before>var connect = require('connect');
var http    = require('http');

var server  = connect()
.use(connect.static(__dirname + '/public'));

http.createServer(server).listen(3000);<commit_msg>Updated port location for heroku<commit_after>var connect = require('connect');
var http    = require('http');

var server  = connect()
.use(connect.static(__dirname + '/public'));

http.createServer(server).listen(process.env.PORT || 3000);<|endoftext|>


<commit_before>(function () {
  'use strict';

  // loading dependencies
  var Plugin = require('plugin');
  var Db = require('db');
  var Timer = require('timer');

  var Constants = require('Constants')();
  var GameTime = require('GameTime');

  // variables

  // the current GameTime (is updated on restart)
  var gameTime = GameTime.startingOn(Db.shared.get('time', 'start'));

  /**
   * + Jonas Raoni Soares Silva
   * @ http://jsfromhell.com/array/shuffle [v1.0]
   */
  function shuffle(o){ //v1.0
      for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
      return o;
  }

  /**
   * Clears the dabatase by setting all values to 0
   */
  function dbClear() {
    // reset the shared values
    Db.shared.set(null);
    // reset the personal values (for all the current users)
    Plugin.userIds().forEach(function (user) {
      Db.personal(user).set(null);
    });
  }

  /**
   * Creates a mapping of the userids to a role.
   * @param roles an object containing what roles should be added.
   *            each key should represent a role and the value how many of those
   *            roles. (if not enough roles, than we add normal citizens).
   * @param users the id of the users to assign roles to.
   */
  function generateRoles(roles, users) {

    // an array containing all the roles we want to add
    var roleArray = [];
    // index used for looping
    var i;

    // adding all the roles
    for (var role in roles) {
      if (roles.hasOwnProperty(role)) {
        // add the role
        for (i = 0; i < roles[role]; i++) {
          roleArray.push(role);
        }
      }
    }

    // add the missing roles
    for (i = roleArray.length; i < users.length; i++) {
      // add a citizen
      roleArray.push(Constants.roles.CITIZEN);
    }

    // shuffle the array
    shuffle(roleArray);

    // the result object (mapping from user -> role)
    var result = {};
    for (i = 0; i < users.length; i++) {
      result[users[i]] = roleArray[i];
    }

    return result;
  }

  /**
   * Determines whether the given user is alive.
   * This is used in filters to find the correct users
   */
  function isAlive(user) {
    return Db.shared.get('users', user, 'isAlive');
  }

  /**
   * Gets all the users with the given role.
   */
  function usersWithRole(role) {
    var users = Plugin.userIds();
    return users.filter(function (user) {
      return Db.personal(user).get('role') === role;
    });
  }

  /**
   * Kills the given user.
   * The user is no longer alive and his role will be exposed.
   */
  function kill(user) {
    Db.shared.set('users', user, {
      isAlive: false,
      role: Db.personal(user).get('role')
    });
  }

  /**
   * Gets the player who has the most votes in the voting with the given id.
   * If multiple players have the same number of votes, then one will be picked
   * randomly.
   * Returns null when no one has voted.
   */
  function mostVotes(votingId) {
    var voting = Db.shared.get('votings', votingId);

    // count the votes for each player
    var votes = {};

    // counting the votes
    for (var user in voting) {
      if (voting.hasOwnProperty(user)) {
        var voteFor = voting[user];

        if (voteFor) { // user has voted for someone
          if (votes[voteFor]) { // votes[voteFor] is defined (and atleast 1)
            votes['' + voteFor]++;
          } else { // not yet defined
            votes['' + voteFor] = 1;
          }
        }
      }
    }

    // get the max number of votes
    var values = Object.keys(votes).map(function (user) {
      return votes[user];
    });
    var max = Math.max.apply(null, values);

    if (max) { // there has been voted
      // get the users that have the max number of votes
      var maxUsers = Object.keys(voting).filter(function (user) {
        return votes[user] === max;
      });

      // take on randomly from the maxUsers
      var r = Math.floor(Math.random() * maxUsers.length);
      return maxUsers[r];
    } else { // no one has voted
      return null;
    }
  }

  /**
   * Creates a new voting with the given votingId.
   * For this voting there is an entry prepared for users
   */
  function createVoting(votingId, users) {
    users.forEach(function (user) {
      Db.shared.set('votings', votingId, user, 0);
    });
  }

  /**
   * Closes the previous night and starts the new day.
   * @param number the current number of the day that just started
   */
  function startDay(number) {
    // message about the start of the day
    log('Starting day ', number);

    if (number === 0) { // no voting on day 0
      // TODO: send some message about first day and welcome and stuff
    } else {
      // kill the player voted for by the werewolves
      var target = mostVotes('night' + (number - 1));
      if (target) {
        kill(target);
      }

      // start a new vote
      var votingId = 'day' + number;
      var users = Plugin.userIds().filter(isAlive);
      createVoting(votingId, users);
    }

  }

  /**
   * Closes the day and starts the night.
   * @param number the current number of the day
   */
  function startNight(number) {
    // message about start of the night
    log('Starting night ', number);

    if (number > 0) { // if there was a day before, then finish the lynching
      // kill the player voted for (if there has been voted)
      var target = mostVotes('day' + number);
      if (target) {
        kill(target);
      }
    }

    // start a new vote
    var votingId = 'night' + number;
    var werewolves = usersWithRole(Constants.roles.WEREWOLF);
    createVoting(votingId, werewolves.filter(isAlive));
  }

  /**
   * Will be called when the day changes from night to day.
   * (or when a new game has been started)
   * @param the game time it was the last time this function was called
   */
  function onTimeChanged(lastTime) {
    // getting the time
    var now = new Date();
    var currentTime = time.getTime(now);

    // starting new timer
    var nextChange = time.nextChange;
    var delay = nextChange.getTime() - now.getTime();

    Timer.set(delay, 'onTimeChanged', currentTime);

    // calling startDay/startNight (only when the time is different)
    if (lastTime.timeId !== currentTime.timeId) {
      // the time is different
      // anounce the start of the day/night
      if (currentTime.isDay) {
        startDay(currentTime.number);
      } else {
        startNight(currentTime.number);
      }
    }
  }

  /**
   * Starts a new game with the given configuration.
   * THis will destroy the current game (if there is any).
   */
  function restart(config) {
    // destroy old game
    Timer.cancel('onTimeChanged');
    dbClear();

    // start new game
    var users = Plugin.userIds();

    // saving each player in the players list
    users.forEach(function (user) {
      Db.shared.set('users', '' + user, {
        isAlive: true
      });
    });

    // the roles to select
    var selectRoles = {};
    selectRoles[Constants.roles.WEREWOLF] = config.nWerewolf;

    // the roles for the users
    var userRoles = generateRoles(selectRoles, users);

    // save the roles
    users.forEach(function (user) {
      var role = userRoles['' + user];
      Db.personal(user).set('role', role);
    });

    // setting up the time
    var now = Date.now();
    Db.shared.set('time', {
      start: now
    });

    // starting the timer and init the game time
    gameTime = GameTime.startingOn(now);

    var date = new Date();
    onTimeChanged(gameTime.getTime(now));

    log('The game has been restarted');
  }

  /**
   * Handles the installation of the application in a Happening group.
   */
  exports.onInstall = function (config) {
    restart(config);
  };

  /**
   * Updates the settings for this game
   */
  exports.onConfig = function (config) {
    if (config.restart) { // restart the game
      restart(config);
    }
  };

  exports.onTimeChanged = onTimeChanged;

  /* The rpc calls */

  /**
   * Votes at the voting for the given user.
   * @param votingId the id of the voting you want to vote on
   * @param vote the user to vote for
   */
  exports.client_vote = function (votingId, vote) {
    // the user that is trying to vote
    var currentUser = Plugin.userId();

    // verify whether the user is allowed to vote for this
    var voting = Db.shared.get('votings', votingId);
    if (voting.hasOwnProperty(currentUser)) {
      // the current user is allowed to vote

      // and voting!
      Db.shared.set('votings', votingId, currentUser, vote);
    }
  };

}());
<commit_msg>Add rpc call for getTime<commit_after>(function () {
  'use strict';

  // loading dependencies
  var Plugin = require('plugin');
  var Db = require('db');
  var Timer = require('timer');

  var Constants = require('Constants')();
  var GameTime = require('GameTime');

  // variables

  // the current GameTime (is updated on restart)
  var gameTime = GameTime.startingOn(Db.shared.get('time', 'start'));

  /**
   * + Jonas Raoni Soares Silva
   * @ http://jsfromhell.com/array/shuffle [v1.0]
   */
  function shuffle(o){ //v1.0
      for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
      return o;
  }

  /**
   * Clears the dabatase by setting all values to 0
   */
  function dbClear() {
    // reset the shared values
    Db.shared.set(null);
    // reset the personal values (for all the current users)
    Plugin.userIds().forEach(function (user) {
      Db.personal(user).set(null);
    });
  }

  /**
   * Creates a mapping of the userids to a role.
   * @param roles an object containing what roles should be added.
   *            each key should represent a role and the value how many of those
   *            roles. (if not enough roles, than we add normal citizens).
   * @param users the id of the users to assign roles to.
   */
  function generateRoles(roles, users) {

    // an array containing all the roles we want to add
    var roleArray = [];
    // index used for looping
    var i;

    // adding all the roles
    for (var role in roles) {
      if (roles.hasOwnProperty(role)) {
        // add the role
        for (i = 0; i < roles[role]; i++) {
          roleArray.push(role);
        }
      }
    }

    // add the missing roles
    for (i = roleArray.length; i < users.length; i++) {
      // add a citizen
      roleArray.push(Constants.roles.CITIZEN);
    }

    // shuffle the array
    shuffle(roleArray);

    // the result object (mapping from user -> role)
    var result = {};
    for (i = 0; i < users.length; i++) {
      result[users[i]] = roleArray[i];
    }

    return result;
  }

  /**
   * Determines whether the given user is alive.
   * This is used in filters to find the correct users
   */
  function isAlive(user) {
    return Db.shared.get('users', user, 'isAlive');
  }

  /**
   * Gets all the users with the given role.
   */
  function usersWithRole(role) {
    var users = Plugin.userIds();
    return users.filter(function (user) {
      return Db.personal(user).get('role') === role;
    });
  }

  /**
   * Kills the given user.
   * The user is no longer alive and his role will be exposed.
   */
  function kill(user) {
    Db.shared.set('users', user, {
      isAlive: false,
      role: Db.personal(user).get('role')
    });
  }

  /**
   * Gets the player who has the most votes in the voting with the given id.
   * If multiple players have the same number of votes, then one will be picked
   * randomly.
   * Returns null when no one has voted.
   */
  function mostVotes(votingId) {
    var voting = Db.shared.get('votings', votingId);

    // count the votes for each player
    var votes = {};

    // counting the votes
    for (var user in voting) {
      if (voting.hasOwnProperty(user)) {
        var voteFor = voting[user];

        if (voteFor) { // user has voted for someone
          if (votes[voteFor]) { // votes[voteFor] is defined (and atleast 1)
            votes['' + voteFor]++;
          } else { // not yet defined
            votes['' + voteFor] = 1;
          }
        }
      }
    }

    // get the max number of votes
    var values = Object.keys(votes).map(function (user) {
      return votes[user];
    });
    var max = Math.max.apply(null, values);

    if (max) { // there has been voted
      // get the users that have the max number of votes
      var maxUsers = Object.keys(voting).filter(function (user) {
        return votes[user] === max;
      });

      // take on randomly from the maxUsers
      var r = Math.floor(Math.random() * maxUsers.length);
      return maxUsers[r];
    } else { // no one has voted
      return null;
    }
  }

  /**
   * Creates a new voting with the given votingId.
   * For this voting there is an entry prepared for users
   */
  function createVoting(votingId, users) {
    users.forEach(function (user) {
      Db.shared.set('votings', votingId, user, 0);
    });
  }

  /**
   * Closes the previous night and starts the new day.
   * @param number the current number of the day that just started
   */
  function startDay(number) {
    // message about the start of the day
    log('Starting day ', number);

    if (number === 0) { // no voting on day 0
      // TODO: send some message about first day and welcome and stuff
    } else {
      // kill the player voted for by the werewolves
      var target = mostVotes('night' + (number - 1));
      if (target) {
        kill(target);
      }

      // start a new vote
      var votingId = 'day' + number;
      var users = Plugin.userIds().filter(isAlive);
      createVoting(votingId, users);
    }

  }

  /**
   * Closes the day and starts the night.
   * @param number the current number of the day
   */
  function startNight(number) {
    // message about start of the night
    log('Starting night ', number);

    if (number > 0) { // if there was a day before, then finish the lynching
      // kill the player voted for (if there has been voted)
      var target = mostVotes('day' + number);
      if (target) {
        kill(target);
      }
    }

    // start a new vote
    var votingId = 'night' + number;
    var werewolves = usersWithRole(Constants.roles.WEREWOLF);
    createVoting(votingId, werewolves.filter(isAlive));
  }

  /**
   * Will be called when the day changes from night to day.
   * (or when a new game has been started)
   * @param the game time it was the last time this function was called
   */
  function onTimeChanged(lastTime) {
    // getting the time
    var now = new Date();
    var currentTime = time.getTime(now);

    // starting new timer
    var nextChange = time.nextChange;
    var delay = nextChange.getTime() - now.getTime();

    Timer.set(delay, 'onTimeChanged', currentTime);

    // calling startDay/startNight (only when the time is different)
    if (lastTime.timeId !== currentTime.timeId) {
      // the time is different
      // anounce the start of the day/night
      if (currentTime.isDay) {
        startDay(currentTime.number);
      } else {
        startNight(currentTime.number);
      }
    }
  }

  /**
   * Starts a new game with the given configuration.
   * THis will destroy the current game (if there is any).
   */
  function restart(config) {
    // destroy old game
    Timer.cancel('onTimeChanged');
    dbClear();

    // start new game
    var users = Plugin.userIds();

    // saving each player in the players list
    users.forEach(function (user) {
      Db.shared.set('users', '' + user, {
        isAlive: true
      });
    });

    // the roles to select
    var selectRoles = {};
    selectRoles[Constants.roles.WEREWOLF] = config.nWerewolf;

    // the roles for the users
    var userRoles = generateRoles(selectRoles, users);

    // save the roles
    users.forEach(function (user) {
      var role = userRoles['' + user];
      Db.personal(user).set('role', role);
    });

    // setting up the time
    var now = Date.now();
    Db.shared.set('time', {
      start: now
    });

    // starting the timer and init the game time
    gameTime = GameTime.startingOn(now);

    var date = new Date();
    onTimeChanged(gameTime.getTime(now));

    log('The game has been restarted');
  }

  /**
   * Handles the installation of the application in a Happening group.
   */
  exports.onInstall = function (config) {
    restart(config);
  };

  /**
   * Updates the settings for this game
   */
  exports.onConfig = function (config) {
    if (config.restart) { // restart the game
      restart(config);
    }
  };

  exports.onTimeChanged = onTimeChanged;

  /* The rpc calls */

  /**
   * Votes at the voting for the given user.
   * @param votingId the id of the voting you want to vote on
   * @param vote the user to vote for
   */
  exports.client_vote = function (votingId, vote) {
    // the user that is trying to vote
    var currentUser = Plugin.userId();

    // verify whether the user is allowed to vote for this
    var voting = Db.shared.get('votings', votingId);
    if (voting.hasOwnProperty(currentUser)) {
      // the current user is allowed to vote

      // and voting!
      Db.shared.set('votings', votingId, currentUser, vote);
    }
  };

  /**
   * Returns the current GameTime as a GameTime object.
   * See the GameTime module at the returned value for information about this object.
   * The gameTime is returned through the callback function as the only argument
   */
  exports.client_getTime = function (callback) {
    var now = new Date();
    var time = gameTime.getTime(now);
    callback(time);
  };

}());
<|endoftext|>


<commit_before><commit_msg>Added server.js stubble<commit_after>// Initializing Server
var express = require('express');
var app = express();
var path = require('path'); // Using path module to easily serve static files and favicon

// Setting up Templating Engine
var engines = require('consolidate');
app.engine('html', engines.hogan); // Tell Express to run .html files through Hogan
app.set('views', __dirname + '/views'); // Tell Express where to find templates

// Setting up static files and favicon
app.use(express.static(path.join(__dirname, 'public'))); // Tell Express where to find static JS and CSS files
app.use(express.favicon(path.join(__dirname, 'public/images/favicon.ico'))); // Tell Express where to find favicon<|endoftext|>


<commit_before>var http = require('http');
var url = require('url');
var Busboy = require('busboy');
var router = require('./router');
var port = 3000;

var multipart = function(req, done) {
  var busboy = new Busboy({ headers: req.headers });
  var buffers = [];

  if (!req.body) {
    req.body = {};
  }

  busboy.on('file', function(field, file) {
    file.on('data', function(data) {
      buffers.push(data);
    });
    file.on('end', function() {
      req.body[field] = Buffer.concat(buffers);
    });
  });

  busboy.on('field', function(field, val) {
    req.body[field] = val;
  });

  busboy.on('finish', done);

  req.pipe(busboy);
};

var requestHandler = function(req, res) {
  var path = url.parse(req.url).pathname;

  if (req.method === 'POST' && req.headers['content-type']) {
    multipart(req, function() {
      router(req.method.toUpperCase(), path, req, res);
    });
  } else {
    router(req.method.toUpperCase(), path, req, res);
  }
};

http.createServer(requestHandler).listen(port);
<commit_msg>allow to send port by env<commit_after>var http = require('http');
var url = require('url');
var Busboy = require('busboy');
var router = require('./router');
var port = process.env.PORT || 3000;

var multipart = function(req, done) {
  var busboy = new Busboy({ headers: req.headers });
  var buffers = [];

  if (!req.body) {
    req.body = {};
  }

  busboy.on('file', function(field, file) {
    file.on('data', function(data) {
      buffers.push(data);
    });
    file.on('end', function() {
      req.body[field] = Buffer.concat(buffers);
    });
  });

  busboy.on('field', function(field, val) {
    req.body[field] = val;
  });

  busboy.on('finish', done);

  req.pipe(busboy);
};

var requestHandler = function(req, res) {
  var path = url.parse(req.url).pathname;

  if (req.method === 'POST' && req.headers['content-type']) {
    multipart(req, function() {
      router(req.method.toUpperCase(), path, req, res);
    });
  } else {
    router(req.method.toUpperCase(), path, req, res);
  }
};

http.createServer(requestHandler).listen(port);
<|endoftext|>


<commit_before>var fs = require('fs')
, path = require('path')
, express = require('express')
, bodyParser = require('body-parser')
, app = express();

app.set('port', process.env.PORT || 3000);

app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.get('/venezuela.json', function(req, res) {
  fs.readFile('venezuela.json', function(err, data) {
    res.setHeader('Content-Type', 'application/json');
    res.send(data);
  });
});

app.listen(app.set('port'), function() {
	console.log("Server running on http://localhost:" + app.set('port') );
});<commit_msg>El servidor de archivos estáticos ya es necesario<commit_after><|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const Koa = require('koa');
const app = new Koa();
const bodyParser = require('koa-bodyparser');

// x-response-time

app.use(async function (ctx, next) {
    const start = new Date();
    await next();
    const ms = new Date() - start;
    ctx.set('X-Response-Time', `${ms}ms`);
});

// logger

app.use(async function (ctx, next) {
    const start = new Date();
    await next();
    const ms = new Date() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

// response

app.use(bodyParser());

app.use(ctx => {
    const inputCommand = _.get(ctx, 'request.body.text', '');
    const bitbucketRegex = /^https:\/\/bitbucket.org\/([a-z0-9\-_]+)\/([a-z0-9\-_]+)\/pull-requests\/([0-9]+)/gi
    const bitbucketMatch = inputCommand.match(bitbucketRegex);

    const user = _.get(ctx, 'request.body.username');

    if (bitbucketMatch) {
        const responseObj = {
            "text": `${user} needs someone to look at a pull request.`,
            "attachments": [
                {
                    "text": `${inputCommand}`
                }
            ]
        };
        ctx.body = JSON.stringify(responseObj);
    } else {
        ctx.body = 'Sorry, but this wasn\'t recognised.  Either it\'s not a Bitbucket pull request, or @owen sucks at regex';
    }
});

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

app.listen(port);<commit_msg>Fix for bad slack docs<commit_after>'use strict';

const _ = require('lodash');
const Koa = require('koa');
const app = new Koa();
const bodyParser = require('koa-bodyparser');

// x-response-time

app.use(async function (ctx, next) {
    const start = new Date();
    await next();
    const ms = new Date() - start;
    ctx.set('X-Response-Time', `${ms}ms`);
});

// logger

app.use(async function (ctx, next) {
    const start = new Date();
    await next();
    const ms = new Date() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

// response

app.use(bodyParser());

app.use(ctx => {
    const inputCommand = _.get(ctx, 'request.body.text', '');
    const bitbucketRegex = /^https:\/\/bitbucket.org\/([a-z0-9\-_]+)\/([a-z0-9\-_]+)\/pull-requests\/([0-9]+)/gi
    const bitbucketMatch = inputCommand.match(bitbucketRegex);

    const user = _.get(ctx, 'request.body.username');

    if (bitbucketMatch) {
        const responseObj = {
            "text": `${user} needs someone to look at a pull request.`,
            "attachments": [
                {
                    "text": `${inputCommand}`
                }
            ]
        };
        ctx.body = responseObj;
    } else {
        ctx.body = 'Sorry, but this wasn\'t recognised.  Either it\'s not a Bitbucket pull request, or @owen sucks at regex';
    }
});

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

app.listen(port);<|endoftext|>


<commit_before>// Modules
var http=require('http'),
	fs=require('fs'),
	url = require('url'),
	crypto = require('crypto'),
	zlib = require('zlib');

// Constants
const MIME_TYPES={
	'html':'text/html',
	'js':'text/javascript',
	'manifest':'text/cache-manifest',
	'css': 'text/css',
	'png': 'image/png',
	'jpg': 'image/jpeg',
	'ico': 'image/ico',
	'mp3': 'audio/mp3',
	'ogg': 'audio/ogg',
	'mid': 'audio/x-midi',
	'json': 'application/json',
	'csv': 'text/csv',
	'webapp':'application/x-web-app-manifest+json'
	};

// Global vars
var rootDirectory=__dirname+'/www', // default directory
	domain='hexa.insertafter.com',
	port=8127;

// HTTP Server

// looking for the RootDirectory on CLI args
if(process.argv[2])
	rootDirectory=process.argv[2];
if(!fs.statSync(rootDirectory).isDirectory())
	throw Error('Cannot stat the given rootDirectory ('+rootDirectory+').');

var httpServer=http.createServer(function (request, response) {
	// Parsing URI
	var parsedUrl=url.parse(request.url);
	// Dynamic contents
	// generating the manifest
	if(parsedUrl.pathname==='/application.manifest'&&
		(request.method=='HEAD'||request.method=='GET')) {
		// parralelizing folder stat
		var folders=['images','css'];
		var listings=[];
		var foldersLeft=folders.length;
		folders.forEach(function(name) {
			fs.readdir(rootDirectory+'/'+name,function(error,file) {
				if(error) {
					response.writeHead(500);
					response.end();
					throw Error('Unable to read the folder "'+name+'".');
				}
				listings[name]=file;
				// when all folders are stated
				if(0==--foldersLeft) {
					response.writeHead(200,{'Content-Type':MIME_TYPES['manifest']});
					// generating the manifest
					response.write('CACHE MANIFEST\n# v 1.1\n\nCACHE:\n/index.html\n');
					folders.forEach(function(name) {
						for(var i=listings[name].length-1; i>=0; i--) {
							if(-1!==listings[name][i].indexOf('.')&&'list.json'!==listings[name][i])
								response.write('/'+name+'/'+listings[name][i]+'\n');
							}
						});
					// ending the manifest
					response.end('javascript/production.js\n\nFALLBACK:\n\n\nNETWORK:\n*\n');
					}
				});
			});
		return;
		}

	// Static contents : read-only access
	if('HEAD'!==request.method&&'GET'!==request.method) {
		response.writeHead(401);
		response.end();
		return;
	}
	// No query params
	if('search' in parsedUrl) {
		response.writeHead(401);
		response.end();
	}
	// redirecting the rootDirectory to index.html
	if('/'===parsedUrl.pathname||!parsedUrl.pathname) {
		response.writeHead(301,{'Location':'/index.html'});
		response.end();
		return;
	}
	// Checking the file corresponding to the path
	fs.stat(rootDirectory+parsedUrl.pathname,
		function(error,result) {
			var headers={}, code=0, start=0, end;
			// Sending 404 errors
			if(error||!result.isFile()) {
				response.writeHead(404);
				response.end();
				return;
			}
			// Reading file ext
			var ext=parsedUrl.pathname
				.replace(/^(?:.*)\.([a-z0-9]+)$/,'$1');
			if(!MIME_TYPES[ext]) {
				response.writeHead(500);
				response.end();
				throw Error('Unsupported MIME type ('+ext+')');
			}
			headers['Content-Type']=MIME_TYPES[ext];
			headers['Content-Length']=result.size;
			// Looking for ranged requests
			if(request.headers.range) {
				var chunks = request.headers.range.replace(/bytes=/, "").split("-");
				start = parseInt(chunks[0],10);
				end =  chunks[1] ? parseInt(chunks[1], 10) :
					headers['Content-Length']-1;
				headers['Content-Range'] = 'bytes ' + start + '-' + end + '/'
					+ (headers['Content-Length']);
				headers['Accept-Ranges'] = 'bytes';
				headers['Content-Length']= (end-start)+1;
				headers['Transfer-Encoding'] = 'chunked';
				headers['Connection'] = 'close';
				code=206;
			} else {
				code=200;
			}
			if('GET'===request.method) {
				if(0===MIME_TYPES[ext].indexOf('text/')) {
					// setting content encoding
					if(request.headers['accept-encoding'].match(/\bdeflate\b/)) {
						headers['Content-Encoding'] = 'deflate';
						delete headers['Content-Length'];
					} else if (request.headers['accept-encoding'].match(/\bgzip\b/)) {
						headers['Content-Encoding'] = 'gzip';
						delete headers['Content-Length'];
					}
				}
				// sending code and headers
				response.writeHead(code, headers);
				// getting ofstream
				var ofstream=fs.createReadStream(rootDirectory
					+parsedUrl.pathname,{start: start, end: end});
				if(headers['Content-Encoding']) {
					ofstream.pipe('gzip'===headers['Content-Encoding']?
							zlib.createGzip():zlib.createDeflate())
						.pipe(response);
				}
				else {
					ofstream.pipe(response);
				}
			} else {
				// sending code and headers
				response.writeHead(code, headers);
				response.end();
			}
		}
	);
}).listen(port);

console.log('Server started on http://'+domain+':'+port+'/, '
	+'serving directory :'+rootDirectory);

<commit_msg>Fixed dev server bug<commit_after>// Modules
var http=require('http'),
	fs=require('fs'),
	url = require('url'),
	crypto = require('crypto'),
	zlib = require('zlib');

// Constants
const MIME_TYPES={
	'html':'text/html',
	'js':'text/javascript',
	'manifest':'text/cache-manifest',
	'css': 'text/css',
	'png': 'image/png',
	'jpg': 'image/jpeg',
	'ico': 'image/ico',
	'mp3': 'audio/mp3',
	'ogg': 'audio/ogg',
	'mid': 'audio/x-midi',
	'json': 'application/json',
	'csv': 'text/csv',
	'webapp':'application/x-web-app-manifest+json'
	};

// Global vars
var rootDirectory=__dirname+'/www', // default directory
	domain='hexa.insertafter.com',
	port=8127;

// HTTP Server

// looking for the RootDirectory on CLI args
if(process.argv[2])
	rootDirectory=process.argv[2];
if(!fs.statSync(rootDirectory).isDirectory())
	throw Error('Cannot stat the given rootDirectory ('+rootDirectory+').');

var httpServer=http.createServer(function (request, response) {
	// Parsing URI
	var parsedUrl=url.parse(request.url);
	// Dynamic contents
	// generating the manifest
	if(parsedUrl.pathname==='/application.manifest'&&
		(request.method=='HEAD'||request.method=='GET')) {
		// parralelizing folder stat
		var folders=['images','css'];
		var listings=[];
		var foldersLeft=folders.length;
		folders.forEach(function(name) {
			fs.readdir(rootDirectory+'/'+name,function(error,file) {
				if(error) {
					response.writeHead(500);
					response.end();
					throw Error('Unable to read the folder "'+name+'".');
				}
				listings[name]=file;
				// when all folders are stated
				if(0==--foldersLeft) {
					response.writeHead(200,{'Content-Type':MIME_TYPES['manifest']});
					// generating the manifest
					response.write('CACHE MANIFEST\n# v 1.1\n\nCACHE:\n/index.html\n');
					folders.forEach(function(name) {
						for(var i=listings[name].length-1; i>=0; i--) {
							if(-1!==listings[name][i].indexOf('.')&&'list.json'!==listings[name][i])
								response.write('/'+name+'/'+listings[name][i]+'\n');
							}
						});
					// ending the manifest
					response.end('javascript/production.js\n\nFALLBACK:\n\n\nNETWORK:\n*\n');
					}
				});
			});
		return;
		}

	// Static contents : read-only access
	if('HEAD'!==request.method&&'GET'!==request.method) {
		response.writeHead(401);
		response.end();
		return;
	}
	// No query params
	if('search' in parsedUrl) {
		response.writeHead(401);
		response.end();
	}
	// redirecting the rootDirectory to index.html
	if('/'===parsedUrl.pathname||!parsedUrl.pathname) {
		response.writeHead(301,{'Location':'/index.html'});
		response.end();
		return;
	}
	// Checking the file corresponding to the path
	fs.stat(rootDirectory+parsedUrl.pathname,
		function(error,result) {
			var headers={}, code=0, start=0, end;
			// Sending 404 errors
			if(error||!result.isFile()) {
				response.writeHead(404);
				response.end();
				return;
			}
			// Reading file ext
			var ext=parsedUrl.pathname
				.replace(/^(?:.*)\.([a-z0-9]+)$/,'$1');
			if(!MIME_TYPES[ext]) {
				response.writeHead(500);
				response.end();
				throw Error('Unsupported MIME type ('+ext+')');
			}
			headers['Content-Type']=MIME_TYPES[ext];
			headers['Content-Length']=result.size;
			// Looking for ranged requests
			if(request.headers.range) {
				var chunks = request.headers.range.replace(/bytes=/, "").split("-");
				start = parseInt(chunks[0],10);
				end =  chunks[1] ? parseInt(chunks[1], 10) :
					headers['Content-Length']-1;
				headers['Content-Range'] = 'bytes ' + start + '-' + end + '/'
					+ (headers['Content-Length']);
				headers['Accept-Ranges'] = 'bytes';
				headers['Content-Length']= (end-start)+1;
				headers['Transfer-Encoding'] = 'chunked';
				headers['Connection'] = 'close';
				code=206;
			} else {
				code=200;
			}
			if('GET'===request.method) {
				if(0===MIME_TYPES[ext].indexOf('text/')
					&&request.headers['accept-encoding']) {
					// setting content encoding
					if(request.headers['accept-encoding'].match(/\bdeflate\b/)) {
						headers['Content-Encoding'] = 'deflate';
						delete headers['Content-Length'];
					} else if (request.headers['accept-encoding'].match(/\bgzip\b/)) {
						headers['Content-Encoding'] = 'gzip';
						delete headers['Content-Length'];
					}
				}
				// sending code and headers
				response.writeHead(code, headers);
				// getting ofstream
				var ofstream=fs.createReadStream(rootDirectory
					+parsedUrl.pathname,{start: start, end: end});
				if(headers['Content-Encoding']) {
					ofstream.pipe('gzip'===headers['Content-Encoding']?
							zlib.createGzip():zlib.createDeflate())
						.pipe(response);
				}
				else {
					ofstream.pipe(response);
				}
			} else {
				// sending code and headers
				response.writeHead(code, headers);
				response.end();
			}
		}
	);
}).listen(port);

console.log('Server started on http://'+domain+':'+port+'/, '
	+'serving directory :'+rootDirectory);

<|endoftext|>


<commit_before>/* eslint no-console: off */
const path = require("path");
const express = require("express");
const expressStaticGzip = require("express-static-gzip");
const charon = require("./src/server/charon");
const globals = require("./src/server/globals");

/* documentation in the static site! */

const devServer = process.argv.indexOf("dev") !== -1;
globals.setGlobals({
  localData: process.argv.indexOf("localData") !== -1
});

/* if we are in dev-mode, we need to import specific libraries & set flags */
let webpack, config, webpackDevMiddleware, webpackHotMiddleware;
if (devServer) {
  webpack = require("webpack"); // eslint-disable-line
  config = require("./webpack.config.dev"); // eslint-disable-line
  webpackDevMiddleware = require("webpack-dev-middleware"); // eslint-disable-line
  webpackHotMiddleware = require("webpack-hot-middleware"); // eslint-disable-line
}

const app = express();
app.set('port', process.env.PORT || 4000);

if (devServer) {
  const compiler = webpack(config);
  app.use(webpackDevMiddleware(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath
  }));
  app.use(webpackHotMiddleware(compiler));
} else {
  app.use("/dist", expressStaticGzip("dist"));
  app.use(express.static(path.join(__dirname, "dist")));
}

/* redirect www.nextstrain.org to nextstrain.org */
app.use(require('express-naked-redirect')({reverse: true}));

app.get("/favicon.png", (req, res) => {
  res.sendFile(path.join(__dirname, "favicon.png"));
});

charon.applyCharonToApp(app);

app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname, "index.html"));
});

const server = app.listen(app.get('port'), () => {
  console.log("-----------------------------------");
  console.log("Auspice server started on port " + server.address().port);
  console.log(devServer ? "Serving dev bundle with hot-reloading enabled" : "Serving compiled bundle from /dist");
  console.log(global.LOCAL_DATA ? "Data is being sourced from /data" : "Dataset JSONs are being sourced from S3, narratives via the static github repo");
  console.log("-----------------------------------\n\n");
});
<commit_msg>Log the actual local data path in use in the server<commit_after>/* eslint no-console: off */
const path = require("path");
const express = require("express");
const expressStaticGzip = require("express-static-gzip");
const charon = require("./src/server/charon");
const globals = require("./src/server/globals");

/* documentation in the static site! */

const devServer = process.argv.indexOf("dev") !== -1;
globals.setGlobals({
  localData: process.argv.indexOf("localData") !== -1
});

/* if we are in dev-mode, we need to import specific libraries & set flags */
let webpack, config, webpackDevMiddleware, webpackHotMiddleware;
if (devServer) {
  webpack = require("webpack"); // eslint-disable-line
  config = require("./webpack.config.dev"); // eslint-disable-line
  webpackDevMiddleware = require("webpack-dev-middleware"); // eslint-disable-line
  webpackHotMiddleware = require("webpack-hot-middleware"); // eslint-disable-line
}

const app = express();
app.set('port', process.env.PORT || 4000);

if (devServer) {
  const compiler = webpack(config);
  app.use(webpackDevMiddleware(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath
  }));
  app.use(webpackHotMiddleware(compiler));
} else {
  app.use("/dist", expressStaticGzip("dist"));
  app.use(express.static(path.join(__dirname, "dist")));
}

/* redirect www.nextstrain.org to nextstrain.org */
app.use(require('express-naked-redirect')({reverse: true}));

app.get("/favicon.png", (req, res) => {
  res.sendFile(path.join(__dirname, "favicon.png"));
});

charon.applyCharonToApp(app);

app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname, "index.html"));
});

const server = app.listen(app.get('port'), () => {
  console.log("-----------------------------------");
  console.log("Auspice server started on port " + server.address().port);
  console.log(devServer ? "Serving dev bundle with hot-reloading enabled" : "Serving compiled bundle from /dist");
  console.log(global.LOCAL_DATA ? `Data is being sourced from ${global.LOCAL_DATA_PATH}` : "Dataset JSONs are being sourced from S3, narratives via the static github repo");
  console.log("-----------------------------------\n\n");
});
<|endoftext|>