<commit_before>// server.js

// 必要なパッケージの読み込み
var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var fs         = require('fs');

// DBへの接続
var mongoose   = require('mongoose');
mongoose.connect('mongodb://localhost/repair');

// モデルの宣言
var User              = require('./app/models/user');
var EditProgram       = require('./app/models/edit_program');
var Support           = require('./app/models/support');
var Edit              = require('./app/models/edit');
var Exec              = require('./app/models/exec');

// POSTでdataを受け取るための記述
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// 3000番を指定
var port = process.env.PORT || 3000;

// expressでAPIサーバを使うための準備
var router = express.Router();

router.use(function(req, res, next) {
    console.log('Something is happening.');
    next();
});

// 正しく実行出来るか左記にアクセスしてテストする (GET http://localhost:3000/api)
router.get('/', function(req, res) {
    res.json({ message: 'Successfully Posted a test message.' });
});

// /users というルートを作成する．
// ----------------------------------------------------
router.route('/users')

// ユーザの作成 (POST http://localhost:3000/api/users)
    .post(function(req, res) {

        // 新しいユーザのモデルを作成する．
        var user = new User();

        // ユーザの各カラムの情報を取得する．
        user.name = req.body.name;
        user.is_login = req.body.is_login;

        // ユーザ情報をセーブする．
        user.save(function(err) {
            if (err)
                res.send(err);
            res.json({ message: 'User created!' });
        });
    })

// 全てのユーザ一覧を取得 (GET http://localhost:8080/api/users)
    .get(function(req, res) {

        //あるプログラムの作成者を表示する．
        if(req.query.programName != null){
            EditProgram.find({"name" : req.query.programName}, function(err,edit_program){
                if(err)
                    res.send(err);
                else{
                    edit_program.forEach(function(edit_program){
                        Edit.find({"e_id": edit_program._id},function(err,edit){
                            if(err)
                                res.send(err);
                            edit.forEach(function(edit){
                                User.findById(edit.u_id,function(err,user){
                                    if(err)
                                        res.send(err);
                                    res.json(user);
                                });
                            });
                        });
                    });
                }
            });
        }
        else{
            User.find(function(err, users) {
                if (err)
                    res.send(err);
                res.json(users);
            });
        }
    });

// /users/:user_id というルートを作成する．
// ----------------------------------------------------
router.route('/users/:user_id')

// 1人のユーザの情報を取得 (GET http://localhost:3000/api/users/:user_id)
    .get(function(req, res) {
        //user_idが一致するデータを探す．
        User.findById(req.params.user_id, function(err, user) {
            if (err)
                res.send(err);
            res.json(user);
        });
    })
// 1人のユーザの情報を更新 (PUT http://localhost:3000/api/users/:user_id)
    .put(function(req, res) {
        User.findById(req.params.user_id, function(err, user) {
            if (err)
                res.send(err);
            // ユーザの各カラムの情報を更新する．
            user.name = req.body.name;
            user.is_login = req.body.is_login;

            user.save(function(err) {
                if (err)
                    res.send(err);
                res.json({ message: 'User updated!' });
            });
        });
    })

// 1人のユーザの情報を削除 (DELETE http://localhost:3000/api/users/:user_id)
    .delete(function(req, res) {
        User.remove({
            _id: req.params.user_id
        }, function(err, user) {
            if (err)
                res.send(err);
            res.json({ message: 'Successfully deleted' });
        });
    });

// /edit_program というルートを作成する．
// ----------------------------------------------------
router.route('/edit_programs')

// プログラムの作成 (POST http://localhost:3000/api/edit_programs)
    .post(function(req, res) {

        if(req.query.userID != null){

            // 新しいプログラムのモデルを作成する．
            var edit_program = new EditProgram();

            // プログラムの各カラムの情報を取得する．
            edit_program.name = req.body.name;
            edit_program.type = req.body.type;
            edit_program.source = req.body.source;

            // プログラム情報をセーブする．
            edit_program.save(function(err) {
                if (err)
                    res.send(err);
            });

            // Editモデルの情報を作成，セーブする．

            var edit = new Edit();
            edit.e_id = edit_program._id;
            edit.u_id = req.query.userID;

            edit.save(function(err) {
                if (err)
                    res.send(err);
                res.json({ message: 'Edit created!' });
            });

        }})
// 全てのプログラム一覧を取得 (GET http://localhost:8080/api/edit_programs)
    .get(function(req, res) {

        EditProgram.find(function(err, edit_programs) {
            if (err)
                res.send(err);
            res.json(edit_programs);
        });
    });

// /edit_programs/:edit_program_id というルートを作成する．
// ----------------------------------------------------
router.route('/edit_programs/:edit_program_id')

// 1つのプログラムの情報を取得 (GET http://localhost:3000/api/edit_programs/:edit_program_id)
    .get(function(req, res) {
        //edit_program_idが一致するデータを探す．
        EditProgram.findById(req.params.edit_program_id, function(err, edit_program) {
            if (err)
                res.send(err);
            res.json(edit_program);
        });
    })
// 1つのプログラムの情報を更新 (PUT http://localhost:3000/api/edit_programs/:edit_program_id)
    .put(function(req, res) {
        User.findById(req.params.edit_program_id, function(err, edit_program) {
            if (err)
                res.send(err);
            // プログラムの各カラムの情報を更新する．
            edit_program.name = req.body.name;
            edit_program.type = req.body.type;
            edit_program.source = req.body.source;

            edit_program.save(function(err) {
                if (err)
                    res.send(err);
                res.json({ message: 'edit_program updated!' });
            });
        });
    })

// 1つのプログラムの情報を削除 (DELETE http://localhost:3000/api/edit_programs/:edit_program_id)
    .delete(function(req, res) {
        EditProgram.remove({
            _id: req.params.edit_program_id
        }, function(err, edit_program) {
            if (err)
                res.send(err);
            res.json({ message: 'Successfully deleted' });
        });
    });

// /supports というルートを作成する．
// ----------------------------------------------------
router.route('/supports')

// 推奨環境設定の作成 (POST http://localhost:3000/api/supports)
    .post(function(req, res) {
        if(req.query.editProgramID != null){
            // 推奨環境設定のモデルを作成する．
            var support = new Support();

            // 推奨環境設定の情報を取得する．
            support.os = req.body.os;
            support.browser = req.body.browser;

            // 設定をセーブする．
            support.save(function(err) {
                if (err)
                    res.send(err);
            });

            // Execモデルの情報を作成，セーブする．
            var exec = new Exec();
            exec.s_id = support._id;
            exec.e_id = req.query.editProgramID;

            exec.save(function(err) {
                if (err)
                    res.send(err);
                res.json({ message: 'Exec created!' });
            });
        }})

// 全ての環境設定一覧を取得 (GET http://localhost:8080/api/supports)
    .get(function(req, res) {
        Support.find(function(err, supports) {
            if (err)
                res.send(err);
            res.json(supports);
        });
    });

// /supports/:support_id というルートを作成する．
// ----------------------------------------------------
router.route('/supports/:support_id')

// 1つの環境情報を取得 (GET http://localhost:3000/api/supports/:support_id)
    .get(function(req, res) {
        //support_idが一致するデータを探す．
        Support.findById(req.params.support_id, function(err, support) {
            if (err)
                res.send(err);
            res.json(support);
        });
    })
// 1つの環境情報を更新 (PUT http://localhost:3000/api/supports/:support_id)
    .put(function(req, res) {
        User.findById(req.params.support_id, function(err, support) {
            if (err)
                res.send(err);
            // ユーザの各カラムの情報を更新する．
            support.os = req.body.os;
            support.browser = req.body.browser;

            support.save(function(err) {
                if (err)
                    res.send(err);
                res.json({ message: 'support updated!' });
            });
        });
    })

// 1つの環境情報を削除 (DELETE http://localhost:3000/api/supports/:support_id)
    .delete(function(req, res) {
        Support.remove({
            _id: req.params.support_id
        }, function(err, support) {
            if (err)
                res.send(err);
            res.json({ message: 'Successfuly deleted' });
        });
    });

// ルーティング登録
app.use('/api', router);

//サーバ起動
app.listen(port);
console.log('listen on port ' + port);

// USE Socket.io and static page

var http = require('http');
var viewDir = "./app/view"
var connect = require('connect');
var serveStatic = require('serve-static');
var view = connect();
view.use(serveStatic(viewDir));
var viewServer = http.createServer(view);
viewServer.listen(8080);

// add start
var socketIO = require('socket.io');
var io = socketIO.listen(viewServer);
console.log("listen on port 8080");

io.sockets.on('connection', function(socket) {
    console.log("connection");
    socket.on('message', function(data) {
        console.log("message");
        io.sockets.emit('message', { value: data.value });
    });

    socket.on('disconnect', function(){
        console.log("disconnect");
    });
});
<commit_msg>[WIP]ADD: プログラムの動作環境を表示する．<commit_after>// server.js

// 必要なパッケージの読み込み
var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var fs         = require('fs');

// DBへの接続
var mongoose   = require('mongoose');
mongoose.connect('mongodb://localhost/repair');

// モデルの宣言
var User              = require('./app/models/user');
var EditProgram       = require('./app/models/edit_program');
var Support           = require('./app/models/support');
var Edit              = require('./app/models/edit');
var Exec              = require('./app/models/exec');

// POSTでdataを受け取るための記述
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// 3000番を指定
var port = process.env.PORT || 3000;

// expressでAPIサーバを使うための準備
var router = express.Router();

router.use(function(req, res, next) {
    console.log('Something is happening.');
    next();
});

// 正しく実行出来るか左記にアクセスしてテストする (GET http://localhost:3000/api)
router.get('/', function(req, res) {
    res.json({ message: 'Successfully Posted a test message.' });
});

// /users というルートを作成する．
// ----------------------------------------------------
router.route('/users')

// ユーザの作成 (POST http://localhost:3000/api/users)
    .post(function(req, res) {

        // 新しいユーザのモデルを作成する．
        var user = new User();

        // ユーザの各カラムの情報を取得する．
        user.name = req.body.name;
        user.is_login = req.body.is_login;

        // ユーザ情報をセーブする．
        user.save(function(err) {
            if (err)
                res.send(err);
            res.json({ message: 'User created!' });
        });
    })

// 全てのユーザ一覧を取得 (GET http://localhost:8080/api/users)
    .get(function(req, res) {

        //あるプログラムの作成者を表示する．
        if(req.query.programName != null  && req.query.searchUser == "ture"){
            EditProgram.find({"name" : req.query.programName}, function(err,edit_program){
                if(err)
                    res.send(err);
                else{
                    edit_program.forEach(function(edit_program){
                        Edit.find({"e_id": edit_program._id},function(err,edit){
                            if(err)
                                res.send(err);
                            edit.forEach(function(edit){
                                User.findById(edit.u_id,function(err,user){
                                    if(err)
                                        res.send(err);
                                    res.json(user);
                                });
                            });
                        });
                    });
                }
            });
        }
        else if(req.query.programName != null && req.query.searchUser == "false"){
            EditProgram.find({"name" : req.query.programName}, function(err,edit_program){
                if(err)
                    res.send(err);
                else{
                    edit_program.forEach(function(edit_program){
                        Exec.find({"e_id": edit_program._id},function(err,exec){
                            if(err)
                                res.send(err);
                            exec.forEach(function(exec){
                                Support.findById(exec.s_id,function(err,support){
                                    if(err)
                                        res.send(err);
                                    console.log(support);
                                    res.json({status: support});
                                });
                            });
                        });
                    });
                }
            });
        }
        else{
            User.find(function(err, users) {
                if (err)
                    res.send(err);
                res.json(users);
            });
        }
    });

// /users/:user_id というルートを作成する．
// ----------------------------------------------------
router.route('/users/:user_id')

// 1人のユーザの情報を取得 (GET http://localhost:3000/api/users/:user_id)
    .get(function(req, res) {
        //user_idが一致するデータを探す．
        User.findById(req.params.user_id, function(err, user) {
            if (err)
                res.send(err);
            res.json(user);
        });
    })
// 1人のユーザの情報を更新 (PUT http://localhost:3000/api/users/:user_id)
    .put(function(req, res) {
        User.findById(req.params.user_id, function(err, user) {
            if (err)
                res.send(err);
            // ユーザの各カラムの情報を更新する．
            user.name = req.body.name;
            user.is_login = req.body.is_login;

            user.save(function(err) {
                if (err)
                    res.send(err);
                res.json({ message: 'User updated!' });
            });
        });
    })

// 1人のユーザの情報を削除 (DELETE http://localhost:3000/api/users/:user_id)
    .delete(function(req, res) {
        User.remove({
            _id: req.params.user_id
        }, function(err, user) {
            if (err)
                res.send(err);
            res.json({ message: 'Successfully deleted' });
        });
    });

// /edit_program というルートを作成する．
// ----------------------------------------------------
router.route('/edit_programs')

// プログラムの作成 (POST http://localhost:3000/api/edit_programs)
    .post(function(req, res) {

        if(req.query.userID != null){

            // 新しいプログラムのモデルを作成する．
            var edit_program = new EditProgram();

            // プログラムの各カラムの情報を取得する．
            edit_program.name = req.body.name;
            edit_program.type = req.body.type;
            edit_program.source = req.body.source;

            // プログラム情報をセーブする．
            edit_program.save(function(err) {
                if (err)
                    res.send(err);
            });

            // Editモデルの情報を作成，セーブする．

            var edit = new Edit();
            edit.e_id = edit_program._id;
            edit.u_id = req.query.userID;

            edit.save(function(err) {
                if (err)
                    res.send(err);
                res.json({ message: 'Edit created!' });
            });

        }})
// 全てのプログラム一覧を取得 (GET http://localhost:8080/api/edit_programs)
    .get(function(req, res) {

        EditProgram.find(function(err, edit_programs) {
            if (err)
                res.send(err);
            res.json(edit_programs);
        });
    });

// /edit_programs/:edit_program_id というルートを作成する．
// ----------------------------------------------------
router.route('/edit_programs/:edit_program_id')

// 1つのプログラムの情報を取得 (GET http://localhost:3000/api/edit_programs/:edit_program_id)
    .get(function(req, res) {
        //edit_program_idが一致するデータを探す．
        EditProgram.findById(req.params.edit_program_id, function(err, edit_program) {
            if (err)
                res.send(err);
            res.json(edit_program);
        });
    })
// 1つのプログラムの情報を更新 (PUT http://localhost:3000/api/edit_programs/:edit_program_id)
    .put(function(req, res) {
        User.findById(req.params.edit_program_id, function(err, edit_program) {
            if (err)
                res.send(err);
            // プログラムの各カラムの情報を更新する．
            edit_program.name = req.body.name;
            edit_program.type = req.body.type;
            edit_program.source = req.body.source;

            edit_program.save(function(err) {
                if (err)
                    res.send(err);
                res.json({ message: 'edit_program updated!' });
            });
        });
    })

// 1つのプログラムの情報を削除 (DELETE http://localhost:3000/api/edit_programs/:edit_program_id)
    .delete(function(req, res) {
        EditProgram.remove({
            _id: req.params.edit_program_id
        }, function(err, edit_program) {
            if (err)
                res.send(err);
            res.json({ message: 'Successfully deleted' });
        });
    });

// /supports というルートを作成する．
// ----------------------------------------------------
router.route('/supports')

// 推奨環境設定の作成 (POST http://localhost:3000/api/supports)
    .post(function(req, res) {
        if(req.query.editProgramID != null){
            // 推奨環境設定のモデルを作成する．
            var support = new Support();

            // 推奨環境設定の情報を取得する．
            support.os = req.body.os;
            support.browser = req.body.browser;

            // 設定をセーブする．
            support.save(function(err) {
                if (err)
                    res.send(err);
            });

            // Execモデルの情報を作成，セーブする．
            var exec = new Exec();
            exec.s_id = support._id;
            exec.e_id = req.query.editProgramID;

            exec.save(function(err) {
                if (err)
                    res.send(err);
                res.json({ message: 'Exec created!' });
            });
        }})

// 全ての環境設定一覧を取得 (GET http://localhost:8080/api/supports)
    .get(function(req, res) {
        Support.find(function(err, supports) {
            if (err)
                res.send(err);
            res.json(supports);
        });
    });

// /supports/:support_id というルートを作成する．
// ----------------------------------------------------
router.route('/supports/:support_id')

// 1つの環境情報を取得 (GET http://localhost:3000/api/supports/:support_id)
    .get(function(req, res) {
        //support_idが一致するデータを探す．
        Support.findById(req.params.support_id, function(err, support) {
            if (err)
                res.send(err);
            res.json(support);
        });
    })
// 1つの環境情報を更新 (PUT http://localhost:3000/api/supports/:support_id)
    .put(function(req, res) {
        User.findById(req.params.support_id, function(err, support) {
            if (err)
                res.send(err);
            // ユーザの各カラムの情報を更新する．
            support.os = req.body.os;
            support.browser = req.body.browser;

            support.save(function(err) {
                if (err)
                    res.send(err);
                res.json({ message: 'support updated!' });
            });
        });
    })

// 1つの環境情報を削除 (DELETE http://localhost:3000/api/supports/:support_id)
    .delete(function(req, res) {
        Support.remove({
            _id: req.params.support_id
        }, function(err, support) {
            if (err)
                res.send(err);
            res.json({ message: 'Successfuly deleted' });
        });
    });

// ルーティング登録
app.use('/api', router);

//サーバ起動
app.listen(port);
console.log('listen on port ' + port);

// USE Socket.io and static page

var http = require('http');
var viewDir = "./app/view"
var connect = require('connect');
var serveStatic = require('serve-static');
var view = connect();
view.use(serveStatic(viewDir));
var viewServer = http.createServer(view);
viewServer.listen(8080);

// add start
var socketIO = require('socket.io');
var io = socketIO.listen(viewServer);
console.log("listen on port 8080");

io.sockets.on('connection', function(socket) {
    console.log("connection");
    socket.on('message', function(data) {
        console.log("message");
        io.sockets.emit('message', { value: data.value });
    });

    socket.on('disconnect', function(){
        console.log("disconnect");
    });
});
<|endoftext|>


<commit_before>'use strict';
 var mongoAddr = '"' + process.env.MONGO_PORT_27017_TCP_ADDR + '"';
 var mongoPort = process.env.MONGO_PORT_27017_TCP_PORT;
 var fs = require('fs');

 var fileContents = fs.readFileSync(__dirname + '/datasources_template.json', 'utf8');
 fileContents = fileContents.replace(/MONGO_HOST_ADDR/g, mongoAddr);
 fileContents = fileContents.replace(/MONGO_HOST_PORT/g, mongoPort);
 fs.writeFileSync(__dirname + '/datasources.json', fileContents);

var loopback = require('loopback');
var boot = require('loopback-boot');
var path = require('path');
var app = module.exports = loopback();
var env = require('get-env')({
  test: 'test'
});

// Set up the /favicon.ico
app.use(loopback.favicon(path.join(__dirname, 'waveicon16.png')));

// request pre-processing middleware
app.use(loopback.compress());

// -- Add your pre-processing middleware here --

// boot scripts mount components like REST API
boot(app, __dirname);

// -- Mount static files here--
// All static middleware should be registered at the end, as all requests
// passing the static middleware are hitting the file system
// Example:

var staticPath = null;

if (env !== 'prod') {
  staticPath = path.resolve(__dirname, '../client/app/');
  console.log("Running app in development mode");
} else {
  staticPath = path.resolve(__dirname, '../dist/');
  console.log("Running app in production mode");
}

app.use(loopback.static(staticPath));

// Requests that get this far won't be handled
// by any middleware. Convert them into a 404 error
// that will be handled later down the chain.
app.use(loopback.urlNotFound());

// The ultimate error handler.
app.use(loopback.errorHandler());

/*var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '1mb'}));
app.use(bodyParser.urlencoded({limit: '1mb', extended: true}));*/

app.start = function() {
  // start the web server
  return app.listen(function() {
    app.emit('started');
    console.log('Web server listening at: %s', app.get('url'));
  });
};

// start the server if `$ node server.js`
if (require.main === module) {
  app.start();
}
<commit_msg>Revert "Removed comments so app will use docker ENV variables for connection to MongoDB" due to side-effects<commit_after>'use strict';
/*
 var mongoAddr = '"' + process.env.MONGO_PORT_27017_TCP_ADDR + '"';
 var mongoPort = process.env.MONGO_PORT_27017_TCP_PORT;
 var fs = require('fs');

 var fileContents = fs.readFileSync(__dirname + '/datasources_template.json', 'utf8');
 fileContents = fileContents.replace(/MONGO_HOST_ADDR/g, mongoAddr);
 fileContents = fileContents.replace(/MONGO_HOST_PORT/g, mongoPort);
 fs.writeFileSync(__dirname + '/datasources.json', fileContents);
 */
var loopback = require('loopback');
var boot = require('loopback-boot');
var path = require('path');
var app = module.exports = loopback();
var env = require('get-env')({
  test: 'test'
});

// Set up the /favicon.ico
app.use(loopback.favicon(path.join(__dirname, 'waveicon16.png')));

// request pre-processing middleware
app.use(loopback.compress());

// -- Add your pre-processing middleware here --

// boot scripts mount components like REST API
boot(app, __dirname);

// -- Mount static files here--
// All static middleware should be registered at the end, as all requests
// passing the static middleware are hitting the file system
// Example:

var staticPath = null;

if (env !== 'prod') {
  staticPath = path.resolve(__dirname, '../client/app/');
  console.log("Running app in development mode");
} else {
  staticPath = path.resolve(__dirname, '../dist/');
  console.log("Running app in production mode");
}

app.use(loopback.static(staticPath));

// Requests that get this far won't be handled
// by any middleware. Convert them into a 404 error
// that will be handled later down the chain.
app.use(loopback.urlNotFound());

// The ultimate error handler.
app.use(loopback.errorHandler());

/*var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '1mb'}));
app.use(bodyParser.urlencoded({limit: '1mb', extended: true}));*/

app.start = function() {
  // start the web server
  return app.listen(function() {
    app.emit('started');
    console.log('Web server listening at: %s', app.get('url'));
  });
};

// start the server if `$ node server.js`
if (require.main === module) {
  app.start();
}
<|endoftext|>


<commit_before>var allowedStatus = ['online', 'away', 'busy', 'offline'];

var logEnable = false;

var log = function(msg, color) {
	if (logEnable) {
		if (color) {
			console.log(msg[color]);
		} else {
			console.log(msg);
		}
	}
};

var logRed    = function() {log(Array.prototype.slice.call(arguments).join(' '), 'red');};
var logGrey   = function() {log(Array.prototype.slice.call(arguments).join(' '), 'grey');};
var logGreen  = function() {log(Array.prototype.slice.call(arguments).join(' '), 'green');};
var logYellow = function() {log(Array.prototype.slice.call(arguments).join(' '), 'yellow');};

UserPresence = {
	activeLogs: function() {
		logEnable = true;
	},

	removeLostConnections: function() {
		if (Package['konecty:multiple-instances-status']) {
			var ids = InstanceStatus.getCollection().find({}, {fields: {_id: 1}}).fetch();

			ids = ids.map(function(id) {
				return id._id;
			});

			var update = {
				$pull: {
					connections: {
						instanceId: {
							$nin: ids
						}
					}
				}
			};

			UsersSessions.update({}, update, {multi: true});
		} else {
			UsersSessions.remove({});
		}
	},

	removeConnectionsByInstanceId: function(instanceId) {
		logRed('[user-presence] removeConnectionsByInstanceId', instanceId);
		var update = {
			$pull: {
				connections: {
					instanceId: instanceId
				}
			}
		};

		UsersSessions.update({}, update, {multi: true});
	},

	removeAllConnections: function() {
		logRed('[user-presence] removeAllConnections');
		UsersSessions.remove({});
	},

	startObserveForDeletedServers: function() {
		InstanceStatus.getCollection().find({}, {fields: {_id: 1}}).observeChanges({
			removed: function(id) {
				UserPresence.removeConnectionsByInstanceId(id);
			}
		});
	},

	createConnection: function(userId, connection) {
		if (!userId) {
			return;
		};

		logGreen('[user-presence] createConnection', userId, connection.id);

		var query = {
			_id: userId
		};

		var now = new Date();

		var instanceId = undefined;
		if (Package['konecty:multiple-instances-status']) {
			instanceId = InstanceStatus.id();
		};

		var update = {
			$push: {
				connections: {
					id: connection.id,
					instanceId: instanceId,
					status: 'online',
					_createdAt: now,
					_updatedAt: now
				}
			}
		};

		UsersSessions.upsert(query, update);
	},

	setConnection: function(userId, connection, status) {
		if (!userId) {
			return;
		};

		logGrey('[user-presence] setConnection', userId, connection.id, status);

		var query = {
			_id: userId,
			'connections.id': connection.id
		};

		var now = new Date();

		var update = {
			$set: {
				'connections.$.status': status
			}
		};

		UsersSessions.upsert(query, update);
	},

	setDefaultStatus: function(userId, status) {
		if (!userId) {
			return;
		};

		if (allowedStatus.indexOf(status) === -1) {
			return;
		};

		logYellow('[user-presence] setDefaultStatus', userId, status);

		Meteor.users.update({_id: userId, statusDefault: {$ne: status}}, {$set: {statusDefault: status}});
	},

	removeConnection: function(connectionId) {
		logRed('[user-presence] removeConnection', connectionId);

		var query = {
			'connections.id': connectionId
		};

		var update = {
			$pull: {
				connections: {
					id: connectionId
				}
			}
		};

		UsersSessions.update(query, update);
	},

	start: function() {
		Meteor.onConnection(function(connection) {
			connection.onClose(function() {
				UserPresence.removeConnection(connection.id);
			});
		});

		process.on('exit', function() {
			if (Package['konecty:multiple-instances-status']) {
				UserPresence.removeConnectionsByInstanceId(InstanceStatus.id());
			} else {
				UserPresence.removeAllConnections();
			}
		});

		Accounts.onLogin(function(login) {
			UserPresence.createConnection(login.user._id, login.connection);
		});

		Meteor.publish(null, function() {
			if (this.userId == null) {
				UserPresence.removeConnection(this.connection.id);
			}
		});

		if (Package['konecty:multiple-instances-status']) {
			UserPresence.startObserveForDeletedServers();
		}

		UserPresence.removeLostConnections();

		Meteor.methods({
			'UserPresence:connect': function() {
				UserPresence.createConnection(this.userId, this.connection);
			},

			'UserPresence:away': function() {
				UserPresence.setConnection(this.userId, this.connection, 'away');
			},

			'UserPresence:online': function() {
				UserPresence.setConnection(this.userId, this.connection, 'online');
			},

			'UserPresence:setDefaultStatus': function(status) {
				UserPresence.setDefaultStatus(this.userId, status);
			}
		});
	}
}
<commit_msg>Add this.unblock() to all methods<commit_after>var allowedStatus = ['online', 'away', 'busy', 'offline'];

var logEnable = false;

var log = function(msg, color) {
	if (logEnable) {
		if (color) {
			console.log(msg[color]);
		} else {
			console.log(msg);
		}
	}
};

var logRed    = function() {log(Array.prototype.slice.call(arguments).join(' '), 'red');};
var logGrey   = function() {log(Array.prototype.slice.call(arguments).join(' '), 'grey');};
var logGreen  = function() {log(Array.prototype.slice.call(arguments).join(' '), 'green');};
var logYellow = function() {log(Array.prototype.slice.call(arguments).join(' '), 'yellow');};

UserPresence = {
	activeLogs: function() {
		logEnable = true;
	},

	removeLostConnections: function() {
		if (Package['konecty:multiple-instances-status']) {
			var ids = InstanceStatus.getCollection().find({}, {fields: {_id: 1}}).fetch();

			ids = ids.map(function(id) {
				return id._id;
			});

			var update = {
				$pull: {
					connections: {
						instanceId: {
							$nin: ids
						}
					}
				}
			};

			UsersSessions.update({}, update, {multi: true});
		} else {
			UsersSessions.remove({});
		}
	},

	removeConnectionsByInstanceId: function(instanceId) {
		logRed('[user-presence] removeConnectionsByInstanceId', instanceId);
		var update = {
			$pull: {
				connections: {
					instanceId: instanceId
				}
			}
		};

		UsersSessions.update({}, update, {multi: true});
	},

	removeAllConnections: function() {
		logRed('[user-presence] removeAllConnections');
		UsersSessions.remove({});
	},

	startObserveForDeletedServers: function() {
		InstanceStatus.getCollection().find({}, {fields: {_id: 1}}).observeChanges({
			removed: function(id) {
				UserPresence.removeConnectionsByInstanceId(id);
			}
		});
	},

	createConnection: function(userId, connection) {
		if (!userId) {
			return;
		};

		logGreen('[user-presence] createConnection', userId, connection.id);

		var query = {
			_id: userId
		};

		var now = new Date();

		var instanceId = undefined;
		if (Package['konecty:multiple-instances-status']) {
			instanceId = InstanceStatus.id();
		};

		var update = {
			$push: {
				connections: {
					id: connection.id,
					instanceId: instanceId,
					status: 'online',
					_createdAt: now,
					_updatedAt: now
				}
			}
		};

		UsersSessions.upsert(query, update);
	},

	setConnection: function(userId, connection, status) {
		if (!userId) {
			return;
		};

		logGrey('[user-presence] setConnection', userId, connection.id, status);

		var query = {
			_id: userId,
			'connections.id': connection.id
		};

		var now = new Date();

		var update = {
			$set: {
				'connections.$.status': status
			}
		};

		UsersSessions.upsert(query, update);
	},

	setDefaultStatus: function(userId, status) {
		if (!userId) {
			return;
		};

		if (allowedStatus.indexOf(status) === -1) {
			return;
		};

		logYellow('[user-presence] setDefaultStatus', userId, status);

		Meteor.users.update({_id: userId, statusDefault: {$ne: status}}, {$set: {statusDefault: status}});
	},

	removeConnection: function(connectionId) {
		logRed('[user-presence] removeConnection', connectionId);

		var query = {
			'connections.id': connectionId
		};

		var update = {
			$pull: {
				connections: {
					id: connectionId
				}
			}
		};

		UsersSessions.update(query, update);
	},

	start: function() {
		Meteor.onConnection(function(connection) {
			connection.onClose(function() {
				UserPresence.removeConnection(connection.id);
			});
		});

		process.on('exit', function() {
			if (Package['konecty:multiple-instances-status']) {
				UserPresence.removeConnectionsByInstanceId(InstanceStatus.id());
			} else {
				UserPresence.removeAllConnections();
			}
		});

		Accounts.onLogin(function(login) {
			UserPresence.createConnection(login.user._id, login.connection);
		});

		Meteor.publish(null, function() {
			if (this.userId == null) {
				UserPresence.removeConnection(this.connection.id);
			}
		});

		if (Package['konecty:multiple-instances-status']) {
			UserPresence.startObserveForDeletedServers();
		}

		UserPresence.removeLostConnections();

		Meteor.methods({
			'UserPresence:connect': function() {
				this.unblock();
				UserPresence.createConnection(this.userId, this.connection);
			},

			'UserPresence:away': function() {
				this.unblock();
				UserPresence.setConnection(this.userId, this.connection, 'away');
			},

			'UserPresence:online': function() {
				this.unblock();
				UserPresence.setConnection(this.userId, this.connection, 'online');
			},

			'UserPresence:setDefaultStatus': function(status) {
				this.unblock();
				UserPresence.setDefaultStatus(this.userId, status);
			}
		});
	}
}
<|endoftext|>


<commit_before>var path = require('path');
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var yaml = require('js-yaml');

var configFilePath = 'server/config.yml';

if (!fs.existsSync(configFilePath)) {
    console.log("Config file not found!");
    return;
}

var config = yaml.safeLoad(fs.readFileSync(configFilePath));

var users = [];
var foods = [];
var sockets = [];
var updatereq = true;

var maxSizeMass = config.maxSizeMass;
var maxMoveSpeed = config.maxMoveSpeed;

var massDecreaseRatio = config.massDecreaseRatio;

var foodMass = config.foodMass;

var newFoodPerPlayer = config.newFoodPerPlayer;
var respawnFoodPerPlayer = config.respawnFoodPerPlayer;

var foodRandomWidth = config.foodRandomWidth;
var foodRandomHeight = config.foodRandomHeight;
var maxFoodCount = config.maxFoodCount;

var noPlayer = config.noPlayer;

var defaultPlayerSize = config.defaultPlayerSize;

var eatableMassDistance = config.eatableMassDistance;

app.use(express.static(__dirname + '/../client'));

function genPos(from, to) {
    return Math.floor(Math.random() * (to - from)) + from;
}

function addFoods(target) {
    foods.push({
        id: (new Date()).getTime(),
        x: genPos(0, target.gameWidth),
        y: genPos(0, target.gameHeight),
        color: randomColor(),
        rotation: Math.random() * (Math.PI * 2)
    });
}

function generateFood(target) {
    if (foods.length < maxFoodCount) {
        addFoods(target);
    }
}

// arr is for example users or foods
function findIndex(arr, id) {
    var len = arr.length;

    while (len--) {
        if (arr[len].id === id) {
            return len;
        }
    }

    return -1;

}

function randomColor() {
    var color = '#' + ('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6),
        difference = 32,
        c = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(color),
        r = parseInt(c[1], 16) - difference,
        g = parseInt(c[2], 16) - difference,
        b = parseInt(c[3], 16) - difference;

    if (r < 0) {
        r = 0;
    }
    if (g < 0) {
        g = 0;
    }
    if (b < 0) {
        b = 0;
    }

    return {
        fill: color,
        border: '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
    };
}

function findPlayer(id) {
    var index = findIndex(users, id);

    return index !== -1 ? users[index] : null;
}

function removePlayer(id) {
    users.splice(findIndex(users, id), 1);
}

function hitTest(start, end, min) {
    var distance = Math.sqrt((start.x - end.x) * (start.x - end.x) + (start.y - end.y) * (start.y - end.y));
    return (distance <= min);
}

function movePlayer(player, target) {
    var dist = Math.sqrt(Math.pow(target.y - player.screenHeight / 2, 2) + Math.pow(target.x - player.screenWidth / 2, 2)),
       deg = Math.atan2(target.y - player.screenHeight / 2, target.x - player.screenWidth / 2);

    var deltaY = player.speed * Math.sin(deg);
    var deltaX = player.speed * Math.cos(deg);

    if (dist < (100 + defaultPlayerSize + player.mass)) {
        deltaY *= dist / (100 + defaultPlayerSize + player.mass);
        deltaX *= dist / (100 + defaultPlayerSize + player.mass);
    }

    player.y += (player.y + deltaY >= 0 && player.y + deltaY <= player.gameHeight) ? deltaY : 0;
    player.x += (player.x + deltaX >= 0 && player.x + deltaX <= player.gameWidth) ? deltaX : 0;
}

io.on('connection', function (socket) {
    console.log('A user connected. Assigning UserID...');

    var userID = socket.id;
    var playerSettings = {
      id: userID,
      hue: Math.round(Math.random() * 360)
    };
    var currentPlayer = {};

    socket.emit('welcome', playerSettings);

    socket.on('gotit', function (player) {
        player.id = userID;
        sockets[player.id] = socket;

        if (findPlayer(player.id) === null) {
            console.log('Player ' + player.id + ' connected!');
            users.push(player);
            currentPlayer = player;
        }

        io.emit('playerJoin', {playersList: users, connectedName: player.name});
        console.log('Total player: ' + users.length);

        // Add new food when player connected
        for (var i = 0; i < newFoodPerPlayer; i++) {
            generateFood(player);
        }
updatereq = true;
    });

    socket.on('ping', function () {
        socket.emit('pong');
    });

    socket.on('disconnect', function () {
        var playerName = findPlayer(userID).name;

        removePlayer(userID);

        console.log('User #' + userID + ' disconnected');

        socket.broadcast.emit(
            'playerDisconnect',
            {
                playersList: users,
                disconnectName: playerName
            }
        );
    });

    socket.on('playerChat', function (data) {
        var _sender = data.sender.replace(/(<([^>]+)>)/ig, '');
        var _message = data.message.replace(/(<([^>]+)>)/ig, '');
        socket.broadcast.emit('serverSendPlayerChat', {sender: _sender, message: _message});
    });

    // Heartbeat function, update everytime
    socket.on('0', function (target) {
     // if you want to use uncomment the line below
    //    console.log(currentPlayer.x + " " + currentPlayer.y);
        if (target.x !== currentPlayer.x || target.y !== currentPlayer.y) {
            movePlayer(currentPlayer, target);

            for (var f = 0; f < foods.length; f++) {
                if (hitTest(
                        {x: foods[f].x, y: foods[f].y},
                        {x: currentPlayer.x, y: currentPlayer.y},
                        currentPlayer.mass + defaultPlayerSize
                    )) {
                    foods[f] = {};
                    foods.splice(f, 1);

                    if (currentPlayer.mass < maxSizeMass) {
                        currentPlayer.mass += foodMass;
                    }

                    if (currentPlayer.speed < maxMoveSpeed) {
                        currentPlayer.speed += currentPlayer.mass / massDecreaseRatio;
                    }

                    console.log('Food eaten');

                    // Respawn food
                    for (var r = 0; r < respawnFoodPerPlayer; r++) {
                        generateFood(currentPlayer);
                    }
                    updatereq = true;
                    break;
                }
            }

            for (var e = 0; e < users.length; e++) {
                if (hitTest(
                        {x: users[e].x, y: users[e].y},
                        {x: currentPlayer.x, y: currentPlayer.y},
                        currentPlayer.mass + defaultPlayerSize
                    ) || hitTest(
                        {x: currentPlayer.x, y: currentPlayer.y},
                        {x: users[e].x, y: users[e].y},
                        users[e].mass + defaultPlayerSize
                    )) {
                    if (users[e].mass !== 0 && users[e].mass < currentPlayer.mass - eatableMassDistance) {
                        if (currentPlayer.mass < maxSizeMass) {
                            currentPlayer.mass += users[e].mass;
                        }

                        if (currentPlayer.speed < maxMoveSpeed) {
                            currentPlayer.speed += currentPlayer.mass / massDecreaseRatio;
                        }

                        sockets[users[e].id].emit('RIP');
                        sockets[users[e].id].disconnect();
                        users.splice(e, 1);
                        break;
                    }
                    if (currentPlayer.mass !== 0 && currentPlayer.mass < users[e].mass - eatableMassDistance) {
                        if (users[e].mass < maxSizeMass) {
                            users[e].mass += currentPlayer.mass;
                        }

                        if (users[e].speed < maxMoveSpeed) {
                            users[e].speed += users[e].mass / massDecreaseRatio;
                        }

                        sockets[currentPlayer.id].emit('RIP');
                        sockets[currentPlayer.id].disconnect();
                        users.splice(currentPlayer, 1);
                        break;
                    }
                }
            }

            // Do some continuous emit
               if(updatereq){
                              socket.emit('serverTellPlayerMove', currentPlayer, foods);
                              socket.broadcast.emit('serverUpdateAll', users, foods);
                              updatereq = false;
               }
               else{
                              socket.emit('serverTellPlayerMove', currentPlayer, 0);
                              socket.broadcast.emit('serverUpdateAll', users, 0);
               }

        }
    });
});

// Don't touch on ip
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || process.env.IP || '127.0.0.1';
var serverport = process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || config.port;
if (process.env.OPENSHIFT_NODEJS_IP !== undefined) {
    http.listen( serverport, ipaddress, function() {
        console.log('listening on *:' + serverport);
    });
} else {
    http.listen( serverport, function() {
        console.log('listening on *:' + config.port);
    });
}
<commit_msg>Slow player as mass increases<commit_after>var path = require('path');
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var yaml = require('js-yaml');

var configFilePath = 'server/config.yml';

if (!fs.existsSync(configFilePath)) {
    console.log("Config file not found!");
    return;
}

var config = yaml.safeLoad(fs.readFileSync(configFilePath));

var users = [];
var foods = [];
var sockets = [];
var updatereq = true;

var maxSizeMass = config.maxSizeMass;
var maxMoveSpeed = config.maxMoveSpeed;

var massDecreaseRatio = config.massDecreaseRatio;

var foodMass = config.foodMass;

var newFoodPerPlayer = config.newFoodPerPlayer;
var respawnFoodPerPlayer = config.respawnFoodPerPlayer;

var foodRandomWidth = config.foodRandomWidth;
var foodRandomHeight = config.foodRandomHeight;
var maxFoodCount = config.maxFoodCount;

var noPlayer = config.noPlayer;

var defaultPlayerSize = config.defaultPlayerSize;

var eatableMassDistance = config.eatableMassDistance;

app.use(express.static(__dirname + '/../client'));

function genPos(from, to) {
    return Math.floor(Math.random() * (to - from)) + from;
}

function addFoods(target) {
    foods.push({
        id: (new Date()).getTime(),
        x: genPos(0, target.gameWidth),
        y: genPos(0, target.gameHeight),
        color: randomColor(),
        rotation: Math.random() * (Math.PI * 2)
    });
}

function generateFood(target) {
    if (foods.length < maxFoodCount) {
        addFoods(target);
    }
}

// arr is for example users or foods
function findIndex(arr, id) {
    var len = arr.length;

    while (len--) {
        if (arr[len].id === id) {
            return len;
        }
    }

    return -1;

}

function randomColor() {
    var color = '#' + ('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6),
        difference = 32,
        c = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(color),
        r = parseInt(c[1], 16) - difference,
        g = parseInt(c[2], 16) - difference,
        b = parseInt(c[3], 16) - difference;

    if (r < 0) {
        r = 0;
    }
    if (g < 0) {
        g = 0;
    }
    if (b < 0) {
        b = 0;
    }

    return {
        fill: color,
        border: '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
    };
}

function findPlayer(id) {
    var index = findIndex(users, id);

    return index !== -1 ? users[index] : null;
}

function removePlayer(id) {
    users.splice(findIndex(users, id), 1);
}

function hitTest(start, end, min) {
    var distance = Math.sqrt((start.x - end.x) * (start.x - end.x) + (start.y - end.y) * (start.y - end.y));
    return (distance <= min);
}

function movePlayer(player, target) {
    var dist = Math.sqrt(Math.pow(target.y - player.screenHeight / 2, 2) + Math.pow(target.x - player.screenWidth / 2, 2)),
       deg = Math.atan2(target.y - player.screenHeight / 2, target.x - player.screenWidth / 2);

    //Slows player as mass increases.
    var slowDown = ((player.mass + 1)/17) + 1;

	var deltaY = player.speed * Math.sin(deg)/ slowDown;
	var deltaX = player.speed * Math.cos(deg)/ slowDown;

    if (dist < (100 + defaultPlayerSize + player.mass)) {
        deltaY *= dist / (100 + defaultPlayerSize + player.mass);
        deltaX *= dist / (100 + defaultPlayerSize + player.mass);
    }

    player.y += (player.y + deltaY >= 0 && player.y + deltaY <= player.gameHeight) ? deltaY : 0;
    player.x += (player.x + deltaX >= 0 && player.x + deltaX <= player.gameWidth) ? deltaX : 0;
}

io.on('connection', function (socket) {
    console.log('A user connected. Assigning UserID...');

    var userID = socket.id;
    var playerSettings = {
      id: userID,
      hue: Math.round(Math.random() * 360)
    };
    var currentPlayer = {};

    socket.emit('welcome', playerSettings);

    socket.on('gotit', function (player) {
        player.id = userID;
        sockets[player.id] = socket;

        if (findPlayer(player.id) === null) {
            console.log('Player ' + player.id + ' connected!');
            users.push(player);
            currentPlayer = player;
        }

        io.emit('playerJoin', {playersList: users, connectedName: player.name});
        console.log('Total player: ' + users.length);

        // Add new food when player connected
        for (var i = 0; i < newFoodPerPlayer; i++) {
            generateFood(player);
        }
updatereq = true;
    });

    socket.on('ping', function () {
        socket.emit('pong');
    });

    socket.on('disconnect', function () {
        var playerName = findPlayer(userID).name;

        removePlayer(userID);

        console.log('User #' + userID + ' disconnected');

        socket.broadcast.emit(
            'playerDisconnect',
            {
                playersList: users,
                disconnectName: playerName
            }
        );
    });

    socket.on('playerChat', function (data) {
        var _sender = data.sender.replace(/(<([^>]+)>)/ig, '');
        var _message = data.message.replace(/(<([^>]+)>)/ig, '');
        socket.broadcast.emit('serverSendPlayerChat', {sender: _sender, message: _message});
    });

    // Heartbeat function, update everytime
    socket.on('0', function (target) {
     // if you want to use uncomment the line below
    //    console.log(currentPlayer.x + " " + currentPlayer.y);
        if (target.x !== currentPlayer.x || target.y !== currentPlayer.y) {
            movePlayer(currentPlayer, target);

            for (var f = 0; f < foods.length; f++) {
                if (hitTest(
                        {x: foods[f].x, y: foods[f].y},
                        {x: currentPlayer.x, y: currentPlayer.y},
                        currentPlayer.mass + defaultPlayerSize
                    )) {
                    foods[f] = {};
                    foods.splice(f, 1);

                    if (currentPlayer.mass < maxSizeMass) {
                        currentPlayer.mass += foodMass;
                    }

                    if (currentPlayer.speed < maxMoveSpeed) {
                        currentPlayer.speed += currentPlayer.mass / massDecreaseRatio;
                    }

                    console.log('Food eaten');

                    // Respawn food
                    for (var r = 0; r < respawnFoodPerPlayer; r++) {
                        generateFood(currentPlayer);
                    }
                    updatereq = true;
                    break;
                }
            }

            for (var e = 0; e < users.length; e++) {
                if (hitTest(
                        {x: users[e].x, y: users[e].y},
                        {x: currentPlayer.x, y: currentPlayer.y},
                        currentPlayer.mass + defaultPlayerSize
                    ) || hitTest(
                        {x: currentPlayer.x, y: currentPlayer.y},
                        {x: users[e].x, y: users[e].y},
                        users[e].mass + defaultPlayerSize
                    )) {
                    if (users[e].mass !== 0 && users[e].mass < currentPlayer.mass - eatableMassDistance) {
                        if (currentPlayer.mass < maxSizeMass) {
                            currentPlayer.mass += users[e].mass;
                        }

                        if (currentPlayer.speed < maxMoveSpeed) {
                            currentPlayer.speed += currentPlayer.mass / massDecreaseRatio;
                        }

                        sockets[users[e].id].emit('RIP');
                        sockets[users[e].id].disconnect();
                        users.splice(e, 1);
                        break;
                    }
                    if (currentPlayer.mass !== 0 && currentPlayer.mass < users[e].mass - eatableMassDistance) {
                        if (users[e].mass < maxSizeMass) {
                            users[e].mass += currentPlayer.mass;
                        }

                        if (users[e].speed < maxMoveSpeed) {
                            users[e].speed += users[e].mass / massDecreaseRatio;
                        }

                        sockets[currentPlayer.id].emit('RIP');
                        sockets[currentPlayer.id].disconnect();
                        users.splice(currentPlayer, 1);
                        break;
                    }
                }
            }

            // Do some continuous emit
               if(updatereq){
                              socket.emit('serverTellPlayerMove', currentPlayer, foods);
                              socket.broadcast.emit('serverUpdateAll', users, foods);
                              updatereq = false;
               }
               else{
                              socket.emit('serverTellPlayerMove', currentPlayer, 0);
                              socket.broadcast.emit('serverUpdateAll', users, 0);
               }

        }
    });
});

// Don't touch on ip
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || process.env.IP || '127.0.0.1';
var serverport = process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || config.port;
if (process.env.OPENSHIFT_NODEJS_IP !== undefined) {
    http.listen( serverport, ipaddress, function() {
        console.log('listening on *:' + serverport);
    });
} else {
    http.listen( serverport, function() {
        console.log('listening on *:' + config.port);
    });
}
<|endoftext|>


<commit_before>/*
@author: yichao, naomileow, jishnumohan, jellyjellyrobot
*/

/*
Init Scripts
*/

var mongoose = require('mongoose');
var express = require('express');
var nodemailer = require('nodemailer');
var geolib = require('geolib');

console.log("Script Initialized")

var mongoUri = 'mongodb://getaway.jellykaya.com/test'

/*
Schema Init for Database Objects
*/

/*
Google Geocoding API
https://developers.google.com/maps/documentation/geocoding/#JSON
*/

var activitySchema = mongoose.Schema({
  activityId: String,
  startTime: Date,
  loc: {
    longitude: Number,
    latitude: Number,
    formattedAdd: String
  },
  categories: [String],
  picUrl: String
});

var Activity = mongoose.model('Activity', activitySchema);

var userSchema = mongoose.Schema({
  oauthId: Number,
  email: { type: String, unique: true },
  lastKnownLoc: {
    longitude: Number,
    latitude: Number
  },
  picture: String,
  categories: [String],
  phoneNumber: String
})

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

var activityGroupSchema = mongoose.Schema({
  groupName: String,
  activityId: String,
  groupOwnerId: Number,
  groupMemberId: [Number],
  meetingLoc: {
    longitude: Number,
    latitude: Number,
    formattedAdd: String
  },
  meetingTime: Date,
  transport: String
})

var ActivityGroup = mongoose.model('ActivityGroup', activityGroupSchema);

console.log("Schemas Initialized");

mongoose.connect(mongoUri, function(err){
  if (err) {
    console.log("Cannot connect to getaway.jellykaya.com!")
    console.log(err);
  }else{
    console.log("Connected to getaway.jellykaya.com")
  }
});

/*
Init Socket.io
*/

var app = express();
var ioServer = require('http').Server(app)
var io = require('socket.io')(ioServer);

ioServer.listen(3001, function(){
  console.log("ioServer running at port 3001!")
});

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

  console.log("Socket intialized");

  /*
  Sanitizer Required because Socket.io sucks
  */

  var sanitizeInput = function(oldObject){
    var newObject = {}
    for(var key in oldObject) {
      if (key != '__v' && key != '$resolved' && key != '$promise'){
        newObject[key] = oldObject[key];
      }
    }
    return newObject;
  }

  socket.emit('connected', {});

  /*
  User related listeners
  */

  socket.on('addUser', function (newUser){
    newUser = sanitizeInput(newUser);
    new User({
      oauthId: newUser.oauthId,
      email: newUser.email,
      lastKnownLoc: {
        longitude: newUser.lastKnownLoc.longitude,
        latitude: newUser.lastKnownLoc.latitude
      },
      picture: newUser.picture,
      categories: newUser.categories,
      phoneNumber: newUser.phoneNumber
    }).save(function(err){
      if (err) {
        console.log("Error in saving user");
        console.log(err);
      };
    });
  });
  socket.on('updateUser', function (newUser){
    newUser = sanitizeInput(newUser);
    User.update({ email: newUser.email }, newUser,
      function(err, elementsChanged, rawMongoOutput){
        if (err) {
          console.log("Error in saving user");
          console.log(err);
        };
    });
  });

  /*
  Activity related Listeners
  */

  socket.on('addActivity', function(newActivity){
    newActivity = sanitiseInput(newActivity);
    new Activity({
      activityId: newActivity.activityId,
      startTime: newActivity.startTime,
      loc: {
        longitude: newActivity.loc.longitude,
        latitude: newActivity.loc.latitude,
        formattedAdd: newActivity.loc.latitude
      },
      categories: newActivity.categories,
      picUrl: newActivity.picUrl
    }).save(function(err){
      if (err) {
        console.log("Error in saving activity");
        console.log(err);
      };
    });
    socket.broadcast.emit('addActivity', newActivity);
  });
  socket.on('updateActivity', function(newActivity){
    newActivity = sanitiseInput(newActivity);
    Activity.update({ activityId: newActivity.activityId }, newActivity,
      function(err, elementsChanged, rawMongoOutput){
        if (err) {
          console.log("Error in saving activity");
          console.log(err);
        }
    });
    socket.broadcast.emit('updateActivity', newActivity);
  });
  socket.on('getActivities', function(){
    var activities = [];
    Activity.find({}).exec(function(err, activity){
      activities.push(activity);
    });
    socket.emit('receiveActivities', activities);
  });

  /*
  ActivityGroup related Listeners
  */

  socket.on('addActivityGroup', function(newActivityGroup){
    newActivityGroup = sanitiseInput(newActivityGroup);
    new ActivityGroup({
      groupName: newActivityGroup.groupName,
      activityId: newActivityGroup.activityId,
      groupOwnerId: newActivityGroup.groupOwnerId,
      groupMemberId: newActivityGroup.groupMemberId,
      meetingLoc: {
        longitude: newActivityGroup.meetingLoc.longitude,
        latitude: newActivityGroup.meetingLoc.latitude,
        formattedAdd: newActivityGroup.meetingLoc.formattedAdd
      },
      meetingTime: newActivityGroup.meetingTime,
      transport: newActivityGroup.transport
    }).save(function(err){
      if (err) {
        console.log("Error in saving activity group");
        console.log(err);
      };
    });
    socket.broadcast.emit('addActivityGroup', newActivity);
  });
  socket.on('updateActivityGroup', function(newActivityGroup){
    newActivityGroup = sanitiseInput(newActivityGroup);
    ActivityGroup.update({ groupName: newActivityGroup.groupName },
      newActivityGroup, function(err, elementsChanged, rawMongoOutput){
        if (err) {
          console.log("Error in saving activity group");
          console.log(err);
        }
      });
    socket.broadcast.emit('updateActivityGroup', newActivity);
  });
  socket.on('getActivityGroup', function(query){
    var activityGroups = [];
    ActivityGroup.find({
      activityId: query.activityId,
      transport: query.transport
    }).exec(function(err, activityGroup){
      activityGroups.push(activityGroup);
    });
    socket.emit('receiveActivityGroups', activityGroups);
  });

  //Signal closure of socket
  socket.on('disconnect', function(){
    console.log("Socket closed");
  });
});
<commit_msg>allow CORS<commit_after>/*
@author: yichao, naomileow, jishnumohan, jellyjellyrobot
*/

/*
Init Scripts
*/

var mongoose = require('mongoose');
var express = require('express');
var nodemailer = require('nodemailer');
var geolib = require('geolib');

console.log("Script Initialized")

var mongoUri = 'mongodb://getaway.jellykaya.com/test'

/*
Schema Init for Database Objects
*/

/*
Google Geocoding API
https://developers.google.com/maps/documentation/geocoding/#JSON
*/

var activitySchema = mongoose.Schema({
  activityId: String,
  startTime: Date,
  loc: {
    longitude: Number,
    latitude: Number,
    formattedAdd: String
  },
  categories: [String],
  picUrl: String
});

var Activity = mongoose.model('Activity', activitySchema);

var userSchema = mongoose.Schema({
  oauthId: Number,
  email: { type: String, unique: true },
  lastKnownLoc: {
    longitude: Number,
    latitude: Number
  },
  picture: String,
  categories: [String],
  phoneNumber: String
})

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

var activityGroupSchema = mongoose.Schema({
  groupName: String,
  activityId: String,
  groupOwnerId: Number,
  groupMemberId: [Number],
  meetingLoc: {
    longitude: Number,
    latitude: Number,
    formattedAdd: String
  },
  meetingTime: Date,
  transport: String
})

var ActivityGroup = mongoose.model('ActivityGroup', activityGroupSchema);

console.log("Schemas Initialized");

mongoose.connect(mongoUri, function(err){
  if (err) {
    console.log("Cannot connect to getaway.jellykaya.com!")
    console.log(err);
  }else{
    console.log("Connected to getaway.jellykaya.com")
  }
});

/*
Init Socket.io
*/

var app = express();

//CORS middleware
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'example.com');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
}

//...
app.configure(function() {;
    app.use(allowCrossDomain);
});

var ioServer = require('http').Server(app)
var io = require('socket.io')(ioServer);

ioServer.listen(3001, function(){
  console.log("ioServer running at port 3001!")
});

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

  console.log("Socket intialized");

  /*
  Sanitizer Required because Socket.io sucks
  */

  var sanitizeInput = function(oldObject){
    var newObject = {}
    for(var key in oldObject) {
      if (key != '__v' && key != '$resolved' && key != '$promise'){
        newObject[key] = oldObject[key];
      }
    }
    return newObject;
  }

  socket.emit('connected', {});

  /*
  User related listeners
  */

  socket.on('addUser', function (newUser){
    newUser = sanitizeInput(newUser);
    new User({
      oauthId: newUser.oauthId,
      email: newUser.email,
      lastKnownLoc: {
        longitude: newUser.lastKnownLoc.longitude,
        latitude: newUser.lastKnownLoc.latitude
      },
      picture: newUser.picture,
      categories: newUser.categories,
      phoneNumber: newUser.phoneNumber
    }).save(function(err){
      if (err) {
        console.log("Error in saving user");
        console.log(err);
      };
    });
  });
  socket.on('updateUser', function (newUser){
    newUser = sanitizeInput(newUser);
    User.update({ email: newUser.email }, newUser,
      function(err, elementsChanged, rawMongoOutput){
        if (err) {
          console.log("Error in saving user");
          console.log(err);
        };
    });
  });

  /*
  Activity related Listeners
  */

  socket.on('addActivity', function(newActivity){
    newActivity = sanitiseInput(newActivity);
    new Activity({
      activityId: newActivity.activityId,
      startTime: newActivity.startTime,
      loc: {
        longitude: newActivity.loc.longitude,
        latitude: newActivity.loc.latitude,
        formattedAdd: newActivity.loc.latitude
      },
      categories: newActivity.categories,
      picUrl: newActivity.picUrl
    }).save(function(err){
      if (err) {
        console.log("Error in saving activity");
        console.log(err);
      };
    });
    socket.broadcast.emit('addActivity', newActivity);
  });
  socket.on('updateActivity', function(newActivity){
    newActivity = sanitiseInput(newActivity);
    Activity.update({ activityId: newActivity.activityId }, newActivity,
      function(err, elementsChanged, rawMongoOutput){
        if (err) {
          console.log("Error in saving activity");
          console.log(err);
        }
    });
    socket.broadcast.emit('updateActivity', newActivity);
  });
  socket.on('getActivities', function(){
    var activities = [];
    Activity.find({}).exec(function(err, activity){
      activities.push(activity);
    });
    socket.emit('receiveActivities', activities);
  });

  /*
  ActivityGroup related Listeners
  */

  socket.on('addActivityGroup', function(newActivityGroup){
    newActivityGroup = sanitiseInput(newActivityGroup);
    new ActivityGroup({
      groupName: newActivityGroup.groupName,
      activityId: newActivityGroup.activityId,
      groupOwnerId: newActivityGroup.groupOwnerId,
      groupMemberId: newActivityGroup.groupMemberId,
      meetingLoc: {
        longitude: newActivityGroup.meetingLoc.longitude,
        latitude: newActivityGroup.meetingLoc.latitude,
        formattedAdd: newActivityGroup.meetingLoc.formattedAdd
      },
      meetingTime: newActivityGroup.meetingTime,
      transport: newActivityGroup.transport
    }).save(function(err){
      if (err) {
        console.log("Error in saving activity group");
        console.log(err);
      };
    });
    socket.broadcast.emit('addActivityGroup', newActivity);
  });
  socket.on('updateActivityGroup', function(newActivityGroup){
    newActivityGroup = sanitiseInput(newActivityGroup);
    ActivityGroup.update({ groupName: newActivityGroup.groupName },
      newActivityGroup, function(err, elementsChanged, rawMongoOutput){
        if (err) {
          console.log("Error in saving activity group");
          console.log(err);
        }
      });
    socket.broadcast.emit('updateActivityGroup', newActivity);
  });
  socket.on('getActivityGroup', function(query){
    var activityGroups = [];
    ActivityGroup.find({
      activityId: query.activityId,
      transport: query.transport
    }).exec(function(err, activityGroup){
      activityGroups.push(activityGroup);
    });
    socket.emit('receiveActivityGroups', activityGroups);
  });

  //Signal closure of socket
  socket.on('disconnect', function(){
    console.log("Socket closed");
  });
});
<|endoftext|>


<commit_before>// (C) Copyright 2014-2015 Hewlett-Packard Development Company, L.P.

var compression = require('compression');
var express = require('express');
var http = require("http");
var router = express.Router();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var path = require('path');
var httpProxy = require('http-proxy');

var proxy = httpProxy.createProxyServer({
  target: 'ws://localhost:8010',
  ws: true
});

var request = require('request');

var docs = require('./docs');
var ctoAppTuner = require('./cto-app-tuner');
var todoAppModular = require('./todo-app-modular');
var cabler = require('./cabler');

var PORT = 8000;

var app = express();

app.use(compression());

app.use(cookieParser());

if (!process.env.SILENT_MODE) {
  app.use(morgan('tiny'));
}

router.get('/', function (req, res) {
  res.redirect('/docs');
});

app.use('/', function(req, res, next) {
  var acceptLanguageHeader = req.headers['accept-language'];

  if (acceptLanguageHeader) {
    var acceptedLanguages = acceptLanguageHeader.match(/[a-zA-z\-]{2,10}/g);
    if (acceptedLanguages) {
      res.cookie('languages', JSON.stringify(acceptedLanguages));
    }
  }

  next();
});

app.use('/tour/', function (req, res) {
  res.redirect('/medium-app');
});

app.use('/medium-app', function(req, res) {
  proxy.web(req, res, { target: 'http://localhost:8010/medium-app' });
});

app.use('/people-finder', function(req, res) {
  proxy.web(req, res, { target: 'http://localhost:8020/' });
});

app.use('/ldap', function(req, res) {
  proxy.web(req, res, { target: 'http://localhost:8020/ldap' });
});

app.use('/rest', function(req, res) {
  proxy.web(req, res, { target: 'http://localhost:8010/rest' });
});

app.use('/slackin', function(req, res) {
  proxy.web(req, res, { target: 'http://localhost:3000/' });
});

app.use('/socket.io', function(req, res) {
  proxy.web(req, res, { target: 'http://localhost:3000/socket.io' });
});

app.use('/invite', bodyParser.json(), function(req, res) {
  var data = req.body;
  if (!data.channels) {
    data.channels = ['general'];
  }
  request.post({uri: 'http://localhost:3000/invite', json: data}).pipe(res);
});

app.get('/assets/design/:name', function(req, res) {
  var options = {
    root: path.join(__dirname, '/../docs/dist/assets/design'),
    dotfiles: 'deny',
    headers: {
        'x-timestamp': Date.now(),
        'x-sent': true
    }
  };

  // Express uses the mime.lookup() method in the node-mime
  // https://github.com/broofa/node-mime project to determine
  // a file's mime type.  This method returns the mime type
  // of 'application/postscript' for Adobe Illustrator files
  // and this results in Safari attempting to show a preview of
  // the file in the browser.  So we'll check for Illustrator
  // files and handle them as a special case for now.
  if (/\.ai$/.test(req.params.name) ) {
    res.type('application/illustrator');
  } else {
    res.type(req.params.name);
  }

  res.sendFile(req.params.name, options);
});

app.
  use('/docs', docs).
  use('/cto-app-tuner', ctoAppTuner).
  use('/todo-app-modular', todoAppModular).
  use('/cabler', cabler).
  use('/hello-world', express.static(path.join(__dirname, '/../examples/hello-world'))).
  use('/assets', express.static(path.join(__dirname, '/../docs/dist/assets'))).
  use('/assets', express.static('/usr/local/lib/node_modules/slackin/lib/assets')).
  use('', router);

var server = http.createServer(app);

server.on('upgrade', function (req, socket, head) {
  proxy.ws(req, socket, head);
});

server.listen(PORT);

console.log('Server started, listening at: http://localhost:' + PORT + '...');
<commit_msg>Add proxy redirect for missing forward slash.<commit_after>// (C) Copyright 2014-2015 Hewlett-Packard Development Company, L.P.

var compression = require('compression');
var express = require('express');
var http = require("http");
var router = express.Router();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var path = require('path');
var httpProxy = require('http-proxy');

var proxy = httpProxy.createProxyServer({
  target: 'ws://localhost:8010',
  ws: true
});

var request = require('request');

var docs = require('./docs');
var ctoAppTuner = require('./cto-app-tuner');
var todoAppModular = require('./todo-app-modular');
var cabler = require('./cabler');

var PORT = 8000;

var app = express();

app.use(compression());

app.use(cookieParser());

if (!process.env.SILENT_MODE) {
  app.use(morgan('tiny'));
}

router.get('/', function (req, res) {
  res.redirect('/docs');
});

app.use('/', function(req, res, next) {
  var acceptLanguageHeader = req.headers['accept-language'];

  if (acceptLanguageHeader) {
    var acceptedLanguages = acceptLanguageHeader.match(/[a-zA-z\-]{2,10}/g);
    if (acceptedLanguages) {
      res.cookie('languages', JSON.stringify(acceptedLanguages));
    }
  }

  next();
});

app.use('/tour/', function (req, res) {
  res.redirect('/medium-app');
});

var mediumAppPath = '/medium-app';

app.use(mediumAppPath, function(req, res) {
  if (req.originalUrl === mediumAppPath) {
    res.redirect(301, req.originalUrl + '/');
  } else {
    proxy.web(req, res, { target: 'http://localhost:8010/medium-app' });
  }
});

app.use('/people-finder', function(req, res) {
  proxy.web(req, res, { target: 'http://localhost:8020/' });
});

app.use('/ldap', function(req, res) {
  proxy.web(req, res, { target: 'http://localhost:8020/ldap' });
});

app.use('/rest', function(req, res) {
  proxy.web(req, res, { target: 'http://localhost:8010/rest' });
});

app.use('/slackin', function(req, res) {
  proxy.web(req, res, { target: 'http://localhost:3000/' });
});

app.use('/socket.io', function(req, res) {
  proxy.web(req, res, { target: 'http://localhost:3000/socket.io' });
});

app.use('/invite', bodyParser.json(), function(req, res) {
  var data = req.body;
  if (!data.channels) {
    data.channels = ['general'];
  }
  request.post({uri: 'http://localhost:3000/invite', json: data}).pipe(res);
});

app.get('/assets/design/:name', function(req, res) {
  var options = {
    root: path.join(__dirname, '/../docs/dist/assets/design'),
    dotfiles: 'deny',
    headers: {
        'x-timestamp': Date.now(),
        'x-sent': true
    }
  };

  // Express uses the mime.lookup() method in the node-mime
  // https://github.com/broofa/node-mime project to determine
  // a file's mime type.  This method returns the mime type
  // of 'application/postscript' for Adobe Illustrator files
  // and this results in Safari attempting to show a preview of
  // the file in the browser.  So we'll check for Illustrator
  // files and handle them as a special case for now.
  if (/\.ai$/.test(req.params.name) ) {
    res.type('application/illustrator');
  } else {
    res.type(req.params.name);
  }

  res.sendFile(req.params.name, options);
});

app.
  use('/docs', docs).
  use('/cto-app-tuner', ctoAppTuner).
  use('/todo-app-modular', todoAppModular).
  use('/cabler', cabler).
  use('/hello-world', express.static(path.join(__dirname, '/../examples/hello-world'))).
  use('/assets', express.static(path.join(__dirname, '/../docs/dist/assets'))).
  use('/assets', express.static('/usr/local/lib/node_modules/slackin/lib/assets')).
  use('', router);

var server = http.createServer(app);

server.on('upgrade', function (req, socket, head) {
  proxy.ws(req, socket, head);
});

server.listen(PORT);

console.log('Server started, listening at: http://localhost:' + PORT + '...');
<|endoftext|>


<commit_before>const http = require('http');
const path = require('path');
const express = require('express');
const WebSocket = require('ws');

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

const players = {};

// Colors are in g, r, b
const colors = [
  [75, 0, 50], // Blue
  [25, 150, 0], // Red
  [100, 200, 0], // Orange
  [150, 125, 0], // Yellow
  [0, 150, 175], // Purple
  [175, 0, 25] // Green
];

const app = express()
  .use(express.static(path.join(__dirname, 'public')))
  .set('view engine', 'ejs')
  .set('views', path.join(__dirname))
  .get('/', getApp);

const server = http.createServer(app);
const wss = new WebSocket.Server({server});

wss.broadcast = broadcast;

wss.on('connection', onSocketConnection);

server.listen(port, onListen);

function getApp(req, res) {
  res.render('index');
}

function onListen() {
  console.log('Server started at port ' + port);
}

function broadcast(data) {
  wss.clients.forEach(sendData);

  function sendData(client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(data);
    }
  }
}

function onSocketConnection(socket) {
  socket.on('message', onSocketMessage);

  function onSocketMessage(message) {
    try {
      message = JSON.parse(message);

      switch (message.device) {
        case 'nodemcu': return nodemcuMessage(socket, message);
        case 'scoreboard': return scoreboardMessage(message);
        default:
          console.log('Device not recognized: ', message.device);
      }
    } catch (err) {
      console.log('Message not in JSON:', message);
    }
  }
}

function nodemcuMessage(socket, message) {
  console.log(message);
  switch (message.action) {
    case 'JOIN_GAME':
      const color = colors[Object.keys(players).length % colors.length];
      players[message.id] = {
        color, score: 0
      };

      return socket.send(JSON.stringify({
        action: 'CHANGE_COLOR',
        color
      }));
    default: return false;
  }
}

function scoreboardMessage(message) {
  console.log(message);
}
<commit_msg>Don't reset color on reconnect<commit_after>const http = require('http');
const path = require('path');
const express = require('express');
const WebSocket = require('ws');

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

const players = {};

// Colors are in g, r, b
const colors = [
  [75, 0, 50], // Blue
  [25, 150, 0], // Red
  [100, 200, 0], // Orange
  [150, 125, 0], // Yellow
  [0, 150, 175], // Purple
  [175, 0, 25] // Green
];

const app = express()
  .use(express.static(path.join(__dirname, 'public')))
  .set('view engine', 'ejs')
  .set('views', path.join(__dirname))
  .get('/', getApp);

const server = http.createServer(app);
const wss = new WebSocket.Server({server});

wss.broadcast = broadcast;

wss.on('connection', onSocketConnection);

server.listen(port, onListen);

function getApp(req, res) {
  res.render('index');
}

function onListen() {
  console.log('Server started at port ' + port);
}

function broadcast(data) {
  wss.clients.forEach(sendData);

  function sendData(client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(data);
    }
  }
}

function onSocketConnection(socket) {
  socket.on('message', onSocketMessage);

  function onSocketMessage(message) {
    try {
      message = JSON.parse(message);

      switch (message.device) {
        case 'nodemcu': return nodemcuMessage(socket, message);
        case 'scoreboard': return scoreboardMessage(message);
        default:
          console.log('Device not recognized: ', message.device);
      }
    } catch (err) {
      console.log('Message not in JSON:', message);
    }
  }
}

function nodemcuMessage(socket, message) {
  console.log(message);
  switch (message.action) {
    case 'JOIN_GAME':
      let color;

      if (players[message.id]) {
        color = players[message.id].color;
      } else {
        color = colors[Object.keys(players).length % colors.length];
        players[message.id] = {
          color, score: 0
        };
      }

      return socket.send(JSON.stringify({
        action: 'CHANGE_COLOR',
        color
      }));
    default: return false;
  }
}

function scoreboardMessage(message) {
  console.log(message);
}
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
//var reqLogger= require('morgan');
var log4js = require('log4js');
/*
log4js.configure({
  appenders: [
    {type: 'console'},
    {type: 'file', filename: 'logs/app.log', category: 'app'}
  ]
});
*/

var bodyParser = require('body-parser');

var app = express();
var log = log4js.getLogger('app');
var environment = process.argv[2] || app.get('env') || 'development';
var serverConfig = require('./env.json')[ environment ];

// view engine setup
/*
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'jade');
*/
//app.use(reqLogger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', express.static('./client/'));
app.use('/', express.static('./'));

var request = require('request');

var gpio = undefined;
if (serverConfig.isRaspi) {
  log.info('Server configured as a raspberry pi. Loading gpio modules');
  gpio = require('pi-gpio');
}

var raspi = require('./action/raspi.js');
raspi = raspi(log4js, gpio, serverConfig.isRaspi);

var model = require('./model/model.js');
model = model(log4js, serverConfig.dbFile); //configure action
model.connect();

var notify = require('./notify/notify.js');
notify = notify(log4js, model);

var os = require('os');
var hostname = os.hostname();

var action = require('./action/action.js');
action = action(log4js, request, hostname, notify, raspi, model);

//Configure additional dependencies
model.setAction(action);
raspi.setStates(model.status);

raspi.openPins();

/**
 * set api routes up
 */
var api = require('./api/api.js');
api = api(log4js, express, model, notify);
app.use(api);

/**
 *
 * Status Codes
 *
 */

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

/**
 *
 * Error Handlers
 *
 */

if (environment === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    err.message = err.message || 'Internal Server Error';
    log.error(err.status + ' - ' + err.message + ': Error in request of ' + req.originalUrl + ' from ' + req.ip);
    log.error(err.message);
    log.error(err.stack);
    res.send(err.status + ': ' + err.message);
  });
}

app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  err.message = err.message || 'Internal Server Error';
  log.error(err.status + ' - ' + err.message + ': Error in request of ' + req.originalUrl + ' from ' + req.ip);
  //log.error(err.stack);
  res.send(err.status + ': ' + err.message);
});

process.on('SIGINT', function() {
  log.info('CTRL C detected, exiting gracefully');
  raspi.closePins(function () {
    log.info('pins should be closed... exiting');
    process.exit();
  });
});

var server = app.listen(serverConfig.port, function () {
  log.info('lwefd listening on port '+ serverConfig.port)
});

module.exports = app;
<commit_msg>improved structure for raspberry pi modules<commit_after>var express = require('express');
var path = require('path');
//var reqLogger= require('morgan');
var log4js = require('log4js');

log4js.configure({
  appenders: [
    {type: 'console'},
    {type: 'file', filename: 'logs/app.log', category: 'app'}
  ]
});

var bodyParser = require('body-parser');

var app = express();
var log = log4js.getLogger('app');
var environment = process.argv[2] || app.get('env') || 'development';
var serverConfig = require('./env.json')[ environment ];

// view engine setup
/*
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'jade');
*/
//app.use(reqLogger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', express.static('./client/'));
app.use('/', express.static('./'));

var request = require('request');

/*
  Setup raspberry pi modules if this is one.
 */
var gpio = undefined;
var raspi = undefined;
if (serverConfig.isRaspi) {
  log.info('Server configured as a raspberry pi. Loading gpio modules');
  gpio = require('pi-gpio');
  raspi = require('./action/raspi.js');
  raspi = raspi(log4js, gpio, serverConfig.isRaspi);
}

var model = require('./model/model.js');
model = model(log4js, serverConfig.dbFile); //configure action
model.connect();

var notify = require('./notify/notify.js');
notify = notify(log4js, model);

var os = require('os');
var hostname = os.hostname();

var action = require('./action/action.js');
action = action(log4js, request, hostname, notify, raspi, model);

//Configure additional dependencies
model.setAction(action);

if (serverConfig.isRaspi) {
  raspi.setStates(model.status);
  raspi.openPins();
}

/**
 * set api routes up
 */
var api = require('./api/api.js');
api = api(log4js, express, model, notify);
app.use(api);

/**
 *
 * Status Codes
 *
 */

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

/**
 *
 * Error Handlers
 *
 */

if (environment === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    err.message = err.message || 'Internal Server Error';
    log.error(err.status + ' - ' + err.message + ': Error in request of ' + req.originalUrl + ' from ' + req.ip);
    log.error(err.message);
    log.error(err.stack);
    res.send(err.status + ': ' + err.message);
  });
}

app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  err.message = err.message || 'Internal Server Error';
  log.error(err.status + ' - ' + err.message + ': Error in request of ' + req.originalUrl + ' from ' + req.ip);
  //log.error(err.stack);
  res.send(err.status + ': ' + err.message);
});

process.on('SIGINT', function() {
  log.info('CTRL C detected, exiting gracefully');

  if (serverConfig.isRaspi) {
    raspi.closePins(function () {
      log.info('pins should be closed... exiting');
      process.exit();
    });
  } else {
    process.exit();
  }
});

var server = app.listen(serverConfig.port, function () {
  log.info('lwefd listening on port '+ serverConfig.port)
});

module.exports = app;
<|endoftext|>


<commit_before>var http = require('http'),
		url = require('url'),
		fs = require('fs'),
		io = require('socket.io'),
		sys = require('sys'),
    sm = require('./socketmanager');

send404 = function(res){
	res.writeHead(404);
	res.write('404');
	res.end();
},

server = http.createServer(function(req, res){
	var path = url.parse(req.url).pathname;
	switch (path){
		case '/':
			res.writeHead(200, {'Content-Type': 'text/html'});
			res.write('
Welcome to Chat Everywhare.

Install the client chat (Chrome Only).
');
			res.end();
			break;

		default:
// 			if (/\.(js|html|swf)$/.test(path)){
// 				try {
// 					var swf = path.substr(-4) === '.swf';
// 					res.writeHead(200, {'Content-Type': swf ? 'application/x-shockwave-flash' : ('text/' + (path.substr(-3) === '.js' ? 'javascript' : 'html'))});
// 					fs.readFile(__dirname + path, swf ? 'binary' : 'utf8', function(err, data){
// 						if (!err) res.write(data, swf ? 'binary' : 'utf8');
// 						res.end();
// 					});
// 				} catch(e){
// 					send404(res);
// 				}
// 				break;
// 			}

			send404(res);
			break;
	}
});

server.listen(8080);

var io = io.listen(server),
		channels = {},
		users = {};

sm = new sm.SocketManager();
sm.register(io);

sm.on('join', function(client, message){
  //client.username = message.username;
  //sys.debug('sessionId: ' + client.sessionId);
  //sys.debug('msgType: ' + message.msgType);
  sm.connectToChannel(client, message.url);
  sm.broadcastToChannel(client, message.url, message.msgType, {message: message});
  users[client.sessionId] = {username: message.username, image_url: message.image_url};
  var _users = [];
  if ((sm.channels[message.url]) && (sm.channels[message.url].length >= 1)) {
    //sys.debug(sm.channels[message.url]);
    var len = sm.channels[message.url].length;
    for (var i = 0; i < len; i++) {
      var sessionId = sm.channels[message.url][i];
      //sys.debug(sessionId + ", " + users[sessionId]);
      if (sessionId) {
        var user = users[sessionId];
        if (user) {
          _users.push({username: user.username, image_url: user.image_url, message: ""});
        }
      }
    }
    sm.send('buffer', client.sessionId, {message: _users});
  }
});

sm.on('rejoin', function(client, message){
  var _users = [];
  if ((sm.channels[message.url]) && (sm.channels[message.url].length >= 1)) {
    //sys.debug(sm.channels[message.url]);
    var len = sm.channels[message.url].length;
    for (var i = 0; i < len; i++) {
      var sessionId = sm.channels[message.url][i];
      //sys.debug(sessionId + ", " + users[sessionId]);
      if (sessionId) {
        var user = users[sessionId];
        if (user) {
          _users.push({username: user.username, image_url: user.image_url, message: ""});
        }
      }
    }
    sm.send('buffer', client.sessionId, {message: _users});
  }
});

sm.on('update', function(client, message){
  //client.username = message.username;
  sm.broadcastToChannel(client, message.url, message.msgType, {message: message});
});

sm.on('exit', function(client, message){
  sm.broadcastToChannel(client, message.url, message.msgType, {message: message});
  sm.exitFromChannel(client, message.url);
});

<commit_msg>Divide into 2 servers. One for websites and another for websockets.<commit_after>var http = require('http'),
		url = require('url'),
		fs = require('fs'),
		io = require('socket.io'),
		sys = require('sys'),
    sm = require('./socketmanager'),
    servers = [];

var send404 = function(res){
	res.writeHead(404);
	res.write('404');
	res.end();
};

servers[0] = http.createServer(function(req, res){
	var path = url.parse(req.url).pathname;
	switch (path){
		case '/':
			res.writeHead(200, {'Content-Type': 'text/html'});
			res.write('
Welcome to Chat Everywhare.

Install the client chat (Chrome Only).
');
			res.end();
			break;
		default:
			send404(res);
			break;
	}
}).listen(80);

servers[1] = http.createServer(function(req, res){
	res.writeHead(200, {'Content-Type': 'text/plain'});
	res.end('');
});
servers[1].listen(8080);

var io = io.listen(servers[1]),
		channels = {},
		users = {};

sm = new sm.SocketManager();
sm.register(io);

sm.on('join', function(client, message){
  //client.username = message.username;
  //sys.debug('sessionId: ' + client.sessionId);
  //sys.debug('msgType: ' + message.msgType);
  sm.connectToChannel(client, message.url);
  sm.broadcastToChannel(client, message.url, message.msgType, {message: message});
  users[client.sessionId] = {username: message.username, image_url: message.image_url};
  var _users = [];
  if ((sm.channels[message.url]) && (sm.channels[message.url].length >= 1)) {
    //sys.debug(sm.channels[message.url]);
    var len = sm.channels[message.url].length;
    for (var i = 0; i < len; i++) {
      var sessionId = sm.channels[message.url][i];
      //sys.debug(sessionId + ", " + users[sessionId]);
      if (sessionId) {
        var user = users[sessionId];
        if (user) {
          _users.push({username: user.username, image_url: user.image_url, message: ""});
        }
      }
    }
    sm.send('buffer', client.sessionId, {message: _users});
  }
});

sm.on('rejoin', function(client, message){
  var _users = [];
  if ((sm.channels[message.url]) && (sm.channels[message.url].length >= 1)) {
    //sys.debug(sm.channels[message.url]);
    var len = sm.channels[message.url].length;
    for (var i = 0; i < len; i++) {
      var sessionId = sm.channels[message.url][i];
      //sys.debug(sessionId + ", " + users[sessionId]);
      if (sessionId) {
        var user = users[sessionId];
        if (user) {
          _users.push({username: user.username, image_url: user.image_url, message: ""});
        }
      }
    }
    sm.send('buffer', client.sessionId, {message: _users});
  }
});

sm.on('update', function(client, message){
  //client.username = message.username;
  sm.broadcastToChannel(client, message.url, message.msgType, {message: message});
});

sm.on('exit', function(client, message){
  sm.broadcastToChannel(client, message.url, message.msgType, {message: message});
  sm.exitFromChannel(client, message.url);
});

<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var should = require('should');
//middleware that automatically logs responses, requests, and associated data
var logger = require('morgan');
var routes = require('./routes');
var fs = require('fs');
var parser = require('body-parser');
var routeHandlers = require('./routeHandlers');
var session = require('express-session');
var cors = require('cors');
var deleteHandlers = require('./deleteHandler');

// authentication and encryption middleware//
var passport =  require('passport');

//what does flag do?
//setup log file
var expressLogFile = fs.createWriteStream('./logs/express.log', {flags: 'a'});

//configuration
//log requests/responses to file
app.use(logger('combined', {stream: expressLogFile}));

/*allows the server to automatically process urlencoded stuff into a javscript object
if we decided to pass JSON to the server instead we'll need to change this to parser.JSON()*/
app.use(parser.json());
app.use(parser.urlencoded({extended: true}));

//set up sessions
app.use(session({
	secret: 'chillestWhales',
	resave: false,
	saveUninitialized: false
}));

//serves the client
app.use(express.static(__dirname + '/../client/'));
// Initialize passport and passport session
// passport session invocation must be after the express sessions declaration as it is going to piggyback on that
// app.use(passport.initialize());
// app.use(passport.session());

//allows cors
app.use(cors());

//start server functions and export
var start = function() {
	//attachs all the routes to the server
	routes.setup(app, routeHandlers, deleteHandlers);
	//if deployed to heroku will use heroku port, otherwise on local machine will use port 3000
	var port = process.env.port || 3000;
	app.listen(port);
	console.log("Express server listening on %d in %s mode", port, app.settings.env)
}

exports.start = start;
exports.app = app;<commit_msg>[Refactor] wrong name for deleteHandler<commit_after>var express = require('express');
var app = express();
var should = require('should');
//middleware that automatically logs responses, requests, and associated data
var logger = require('morgan');
var routes = require('./routes');
var fs = require('fs');
var parser = require('body-parser');
var routeHandlers = require('./routeHandlers');
var session = require('express-session');
var cors = require('cors');
var deleteHandlers = require('./deleteHandlers');

// authentication and encryption middleware//
var passport =  require('passport');

//what does flag do?
//setup log file
var expressLogFile = fs.createWriteStream('./logs/express.log', {flags: 'a'});

//configuration
//log requests/responses to file
app.use(logger('combined', {stream: expressLogFile}));

/*allows the server to automatically process urlencoded stuff into a javscript object
if we decided to pass JSON to the server instead we'll need to change this to parser.JSON()*/
app.use(parser.json());
app.use(parser.urlencoded({extended: true}));

//set up sessions
app.use(session({
	secret: 'chillestWhales',
	resave: false,
	saveUninitialized: false
}));

//serves the client
app.use(express.static(__dirname + '/../client/'));
// Initialize passport and passport session
// passport session invocation must be after the express sessions declaration as it is going to piggyback on that
// app.use(passport.initialize());
// app.use(passport.session());

//allows cors
app.use(cors());

//start server functions and export
var start = function() {
	//attachs all the routes to the server
	routes.setup(app, routeHandlers, deleteHandlers);
	//if deployed to heroku will use heroku port, otherwise on local machine will use port 3000
	var port = process.env.port || 3000;
	app.listen(port);
	console.log("Express server listening on %d in %s mode", port, app.settings.env)
}

exports.start = start;
exports.app = app;<|endoftext|>


<commit_before>const express = require('express');
const path = require('path');
const app = express();

app.get('/', (req, res) => {
    res.send(__dirname)
})
app.get('/login', function(request, response) {
    response.send('login page');
    // response.sendFile(path.join(__dirname + '/../www/html/login.html')); // uncoment when branches are merged
});

app.get('/rooms', function(request, response) {
    response.send('create or join a room page');
});

app.get('/room/:roomCode', function(request, response) {
    respone.send('a room page')
})

app.listen(3000, function() {
    console.log('Moose started on port 3000. Go to localhost:3000');
});<commit_msg>for #5 remove unnecessary route<commit_after>const express = require('express');
const path = require('path');
const app = express();

app.get('/login', function(request, response) {
    response.send('login page');
    // response.sendFile(path.join(__dirname + '/../www/html/login.html')); // uncoment when branches are merged
});

app.get('/rooms', function(request, response) {
    response.send('create or join a room page');
});

app.get('/room/:roomCode', function(request, response) {
    respone.send('a room page')
})

app.listen(3000, function() {
    console.log('Moose started on port 3000. Go to localhost:3000');
});<|endoftext|>